Merge remote-tracking branch 'upstream/main' into gsora/backlight-on-keypress

This commit is contained in:
Gianguido Sorà 2022-06-10 12:37:11 +02:00
commit 2fee46753e
16 changed files with 128 additions and 45 deletions

4
.gitignore vendored
View file

@ -18,11 +18,15 @@ apps/vault/tools/crypto_data
# local utility shellscripts
update-precursors.sh
buildpush.ps1
# pddb debug files
tools/pddb-images/
tools/__pycache__
# renode will tickle this every time you run it, but you shouldn't commit that back to the tree
emulation/linux-server-rootfs.jffs2
# don't record weirdnesses dealing with vscode
.vscode/settings-hw.json
.vscode/settings-xous.json

View file

@ -45,4 +45,4 @@ with_ctap1 = ["ctap-crypto/with_ctap1"]
with_ctap2_1 = []
autotest = []
multireset = [] # allows credential reset more than once per boot
default = ["with_ctap1", "with_ctap2_1", "autotest"]
default = ["with_ctap1", "with_ctap2_1"]

View file

@ -5,6 +5,18 @@
"zh": "秒 直到中止",
"en-tts": "s until abort"
},
"vault.fido.pin_uv_auth": {
"en": "FIDO host is creating a PIN.\nPress any key to accept.",
"ja": "FIDOホストがPINを作成しています。\n任意のキーを押して受け入れます。",
"zh": "FIDO 主机正在创建 PIN。\n按任意键接受。",
"en-tts": "FIDO host is creating a PIN.\nPress any key to accept."
},
"vault.fido.next_assertion": {
"en": "This site is requires multiple credentials.\nPress any key to allow the next credential.",
"ja": "このサイトには複数のクレデンシャルが必要です。\n次のクレデンシャルを許可するには、任意のキーを押してください。",
"zh": "此站点需要多个凭据。\n按任意键以允许下一个凭据。",
"en-tts": "This site is requires multiple credentials.\nPress any key to allow the next credential."
},
"vault.fido.make_credential": {
"en": "FIDO Make Credential Request.\nPress any key to approve.",
"ja": "FIDOは資格情報を要求します\n承認するには任意のキーを押してください",

View file

@ -397,7 +397,9 @@ where
// This case was added in FIDO 2.1.
if auth_param.is_empty() {
//(self.check_user_presence)(cid)?;
if crate::ux::request_permission_blocking("pin_uv_auth_precheck".to_string(), cid).is_none() {
if crate::ux::request_permission_blocking(
t!("vault.fido.pin_uv_auth", xous::LANG).to_string(),
cid).is_none() {
return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED)
}
if self.persistent_store.pin_hash()?.is_none() {
@ -859,7 +861,10 @@ where
_now: ClockValue,
) -> Result<ResponseData, Ctap2StatusCode> {
//self.check_command_permission(now)?;
if crate::ux::request_permission_blocking("GetAssertion".to_string(), [0xff, 0xff, 0xff, 0xff]).is_none() {
if crate::ux::request_permission_blocking(
t!("vault.fido.next_assertion", xous::LANG).to_string(),
[0xff, 0xff, 0xff, 0xff]
).is_none() {
return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED);
}
let (assertion_input, credential) =
@ -931,6 +936,9 @@ where
)
}
pub fn unplug_reset(&mut self) {
self.pin_protocol_v1.reset(self.rng);
}
fn process_reset(
&mut self,
cid: ChannelID,
@ -939,7 +947,7 @@ where
// Resets are only possible in the first 10 seconds after booting.
// TODO(kaczmarczyck) 2.1 allows Reset after Reset and 15 seconds?
// self.check_command_permission(now)?;
if let Some(c) = crate::ux::request_permission_blocking(locales::t!("vault.u2f.factoryreset", xous::LANG).to_string(), cid) {
if let Some(c) = crate::ux::request_permission_blocking(t!("vault.u2f.factoryreset", xous::LANG).to_string(), cid) {
if c != 'y' {
return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED)
}
@ -952,6 +960,8 @@ where
_ => return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED),
}
//(self.check_user_presence)(cid)?;
// we skip the double-confirmation during autotesting, but leave it here for production
#[cfg(not(feature="autotest"))]
if crate::ux::request_permission_blocking(t!("vault.u2f.reset_check", xous::LANG).to_string(), cid).is_none() {
return Err(Ctap2StatusCode::CTAP2_ERR_NOT_ALLOWED)
}

View file

@ -16,6 +16,16 @@ use ctap::CtapState;
mod shims;
use shims::*;
// CTAP2 testing notes:
// run our branch and use this to forward the prompts on to the device:
// netcat -k -u -l 6502 > /dev/ttyS0
// use the "autotest" feature to remove some excess prompts that interfere with the test
// the OpenSK code is based off of commit f2496a8e6d71a4e838884996a1c9b62121f87df2 from the
// Google OpenSK repository. The last push was Nov 19 2021, and the initial merge into Xous
// was finished on June 9 2022. Any patches to this code base will have to be manually
// applied. Please update the information here to reflect the latest patch status.
/*
UI concept:
@ -110,7 +120,15 @@ fn main() -> ! {
}
}
Err(e) => {
log::warn!("FIDO listener got an error: {:?}", e);
match e {
xous::Error::ProcessTerminated => { // unplug happened, reset the authenticator
log::info!("CTAP unplug_reset");
ctap_state.unplug_reset();
},
_ => {
log::warn!("FIDO listener got an error: {:?}", e);
}
}
}
}
}

View file

@ -10,6 +10,16 @@ use std::io::{Write, Read};
use chrono::{Utc, DateTime, NaiveDateTime};
use std::time::{SystemTime, UNIX_EPOCH};
// conceptual note: this UX conflates both the U2F and the FIDO2 paths.
// - U2F is a polled implementation, where the state goes from Idle->Prompt->Present
// and then immediately back to Idle. It is non-blocking and always returns a value.
// - FIDO is a deferred responder, meaning it is blocking the caller. It goes from
// Idle->Prompt->Idle again. The caller is blocked until the Prompt is answered.
// You *can* take the state machine to Present after Prompt, in which case, it will
// "remember" that a user was present for another 30 seconds. This is not actually
// the mandated behavior, it was only implemented because I got confused on part
// of the spec, but the code stubs are still around.
pub(crate) const U2F_APP_DICT: &'static str = "fido.u2fapps";
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
@ -403,15 +413,7 @@ pub(crate) fn start_ux_thread() {
last_timer = new_timer;
}
}
// check if we got a hit
#[cfg(not(feature="autotest"))]
let key_hit = kbhit.load(Ordering::SeqCst);
#[cfg(feature="autotest")]
let key_hit = if num_fido_auths != 82 { // 82 is the test number of "don't touch it"
'y' as u32
} else {
0
};
if key_hit != 0 {
num_fido_auths += 1;
log::info!("got user presence! count: {}", num_fido_auths);
@ -421,13 +423,12 @@ pub(crate) fn start_ux_thread() {
fido_request.granted = char::from_u32(key_hit);
log::info!("returning {:?}", fido_request.granted);
buffer.replace(fido_request).unwrap();
ux_state = UxState::Idle; // comment out this line if you want presence to persist after touch for FIDO2
} else {
// this is the U2F flow
ux_state = UxState::Present(tt.elapsed_ms() as i64 + timeouts.presence_timeout_ms);
}
// this is used only if we want presence to persist after the touch
//ux_state = UxState::Present(tt.elapsed_ms() as i64 + timeouts.presence_timeout_ms);
// this will take us straight back to Idle after a touch
ux_state = UxState::Idle;
modals.dynamic_notification_close().unwrap();
send_message(self_cid,
Message::new_scalar(UxOp::Pump.to_usize().unwrap(), KEEPALIVE_MS, 0, 0, 0)

View file

@ -3,7 +3,7 @@
# set RUSTFLAGS=--remap-path-prefix=F:\largework\rust-win\code\xous-core\=build
# $env:RUSTFLAGS="--remap-path-prefix=$(Get-Location)=build"
cargo xtask app-image ball repl # vault
cargo xtask app-image vault ball
# cargo xtask ffi-test
# cargo xtask minimal precursors/soc.svd

View file

@ -39,7 +39,7 @@ fn sha256load(v2: [u32; 4], v3: [u32; 4]) -> [u32; 4] {
fn sha256swap(v0: [u32; 4]) -> [u32; 4] {
[v0[2], v0[3], v0[0], v0[1]]
}
#[inline(never)] // bunnie: reduce binary size
fn sha256msg1(v0: [u32; 4], v1: [u32; 4]) -> [u32; 4] {
// sigma 0 on vectors
#[inline]
@ -52,7 +52,7 @@ fn sha256msg1(v0: [u32; 4], v1: [u32; 4]) -> [u32; 4] {
add(v0, sigma0x4(sha256load(v0, v1)))
}
#[inline(never)] // bunnie: reduce binary size
fn sha256msg2(v4: [u32; 4], v3: [u32; 4]) -> [u32; 4] {
macro_rules! sigma1 {
($a:expr) => {
@ -70,7 +70,7 @@ fn sha256msg2(v4: [u32; 4], v3: [u32; 4]) -> [u32; 4] {
[w19, w18, w17, w16]
}
#[inline(never)] // bunnie: reduce binary size
fn sha256_digest_round_x2(cdgh: [u32; 4], abef: [u32; 4], wk: [u32; 4]) -> [u32; 4] {
macro_rules! big_sigma0 {
($a:expr) => {
@ -162,6 +162,7 @@ macro_rules! schedule_rounds4 {
}
/// Process a block with the SHA-256 algorithm.
#[inline(never)] // bunnie: reduce binary size
fn sha256_digest_block_u32(state: &mut [u32; 8], block: &[u32; 16]) {
let mut abef = [state[0], state[1], state[4], state[5]];
let mut cdgh = [state[2], state[3], state[6], state[7]];

View file

@ -17,6 +17,7 @@ fn sha512load(v0: [u64; 2], v1: [u64; 2]) -> [u64; 2] {
}
/// Performs 2 rounds of the SHA-512 message schedule update.
#[inline(never)] // bunnie: reduce binary size
pub fn sha512_schedule_x2(v0: [u64; 2], v1: [u64; 2], v4to5: [u64; 2], v7: [u64; 2]) -> [u64; 2] {
// sigma 0
fn sigma0(x: u64) -> u64 {
@ -46,6 +47,7 @@ pub fn sha512_schedule_x2(v0: [u64; 2], v1: [u64; 2], v4to5: [u64; 2], v7: [u64;
}
/// Performs one round of the SHA-512 message block digest.
#[inline(never)] // bunnie: reduce binary size
pub fn sha512_digest_round(
ae: [u64; 2],
bf: [u64; 2],
@ -100,6 +102,7 @@ pub fn sha512_digest_round(
}
/// Process a block with the SHA-512 algorithm.
#[inline(never)] // bunnie: reduce binary size
pub fn sha512_digest_block_u64(state: &mut [u64; 8], block: &[u64; 16]) {
let k = &K64X2;

View file

@ -148,6 +148,10 @@ pub unsafe extern "C" fn realloc(
ptr: *mut c_void,
size: c_uint
) -> *mut c_void {
if ptr.is_null() {
// if ptr is null, realloc() is identical to malloc()
return malloc(size);
}
let mut region_index: Option<usize> = None;
for (index, region) in C_HEAP.iter().enumerate() {
if region.as_ptr() as usize == ptr as usize {
@ -158,7 +162,7 @@ pub unsafe extern "C" fn realloc(
match region_index {
Some(index) => {
log::info!("realloc/free success: {:x}", ptr as usize);
let mut old = C_HEAP.remove(index);
let mut old = C_HEAP.swap_remove(index);
let checked_size = if size == 0 {
1 // at least 1 element so we have a pointer we can pass back
} else {
@ -170,6 +174,7 @@ pub unsafe extern "C" fn realloc(
alloc.push(src);
}
old.clear();
alloc.set_len(checked_size as usize);
C_HEAP.push(alloc);
log::info!("realloc/allocated: {:x}", ret_ptr as usize);

View file

@ -54,5 +54,6 @@ pub enum U2fCode {
TxAck,
RxWait,
RxAck,
Hangup,
Denied,
}

View file

@ -209,10 +209,17 @@ impl UsbHid {
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let ack = buf.to_original::<U2fMsgIpc, _>().unwrap();
assert_eq!(ack.code, U2fCode::RxAck, "Expected U2fCode::RxAck");
let mut u2fmsg = FidoMsg::default();
u2fmsg.packet.copy_from_slice(&ack.data);
Ok(u2fmsg)
match ack.code {
U2fCode::RxAck => {
let mut u2fmsg = FidoMsg::default();
u2fmsg.packet.copy_from_slice(&ack.data);
Ok(u2fmsg)
},
U2fCode::Hangup => {
Err(xous::Error::ProcessTerminated)
},
_ => Err(xous::Error::InternalError)
}
}
pub fn u2f_send(&self, msg: FidoMsg) -> Result<(), xous::Error> {
let mut req = U2fMsgIpc {

View file

@ -189,6 +189,8 @@ fn main() -> ! {
let mut fido_rx_queue = VecDeque::<[u8; 64]>::new();
let mut lockstatus_force_update = true; // some state to track if we've been through a susupend/resume, to help out the status thread with its UX update after a restart-from-cold
#[cfg(any(target_os = "none", target_os = "xous"))]
let mut was_suspend = true;
loop {
let mut msg = xous::receive_message(usbdev_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
@ -286,6 +288,25 @@ fn main() -> ! {
Err(e) => log::trace!("U2F ERR: {:?}", e),
}
}
#[cfg(any(target_os = "none", target_os = "xous"))]
if usb_dev.state() == UsbDeviceState::Suspend {
log::info!("suspend detected");
if was_suspend == false {
// FIDO listener needs to know when USB was unplugged, so that it can reset state per FIDO2 spec
if let Some(mut listener) = fido_listener.take() {
let mut response = unsafe {
Buffer::from_memory_message_mut(listener.body.memory_message_mut().unwrap())
};
let mut buf = response.to_original::<U2fMsgIpc, _>().unwrap();
assert_eq!(buf.code, U2fCode::RxWait, "Expected U2fcode::RxWait in wrapper");
buf.code = U2fCode::Hangup;
response.replace(buf).unwrap();
}
}
was_suspend = true;
} else {
was_suspend = false;
}
},
Some(Opcode::SwitchCores) => msg_blocking_scalar_unpack!(msg, core, _, _, _, {
if core == 1 {

View file

@ -315,11 +315,13 @@ pub fn read_minielf<P: AsRef<Path>>(filename: P) -> Result<MiniElf, ElfReadError
debug!(" link: {:?}", s.link());
let size = s.size();
let no_copy = s.get_type() == Ok(ShType::NoBits);
if s.flags() & SHF_ALLOC == 0 {
debug!("section has no allocations -- skipping");
continue;
}
if s.get_type() == Ok(ShType::NoBits) {
if no_copy {
flags |= MiniElfFlags::NOCOPY;
}
if s.flags() & SHF_EXECINSTR != 0 {
@ -335,17 +337,17 @@ pub fn read_minielf<P: AsRef<Path>>(filename: P) -> Result<MiniElf, ElfReadError
name,
s.offset(),
program_offset,
s.raw_data(&elf).len(),
if no_copy { 0 } else { s.raw_data(&elf).len() },
program_offset
);
let section_data = s.raw_data(&elf);
debug!(
"Section start: {:02x} {:02x} {:02x} {:02x} going into offset 0x{:08x}",
section_data[0], section_data[1], section_data[2], section_data[3], program_offset
);
// If this section gets copied, add it to the program stream.
if s.get_type() != Ok(ShType::NoBits) {
let section_data = s.raw_data(&elf);
debug!(
"Section start: {:02x} {:02x} {:02x} {:02x} going into offset 0x{:08x}",
section_data[0], section_data[1], section_data[2], section_data[3], program_offset
);
program_data
.seek(SeekFrom::Start(program_offset))
.map_err(ElfReadError::FileSeekError)?;

View file

@ -124,21 +124,19 @@ impl Envelope {
));
}
_ => {
Message::Borrow(_) | Message::MutableBorrow(_) | Message::Scalar(_) => {
let result = crate::send_message(connection, body);
let new_self = ManuallyDrop::into_inner(manual_self);
if let Ok(crate::Result::Ok) = result {
match result {
// `new_self` will have its Drop() called
return Ok(());
}
Ok(crate::Result::Ok) | Ok(crate::Result::MemoryReturned(_, _)) => Ok(()),
// If there's an error, reconstitute ourselves and return.
if let Err(e) = result {
return Err((new_self, e));
}
// If there's an error, reconstitute ourselves and return.
Err(e) => Err((new_self, e)),
return Err((new_self, crate::Error::MemoryInUse));
// Any other value is a bug in the kernel
o => panic!("unrecognized return from send_message: {:?}", o),
}
}
}
}

View file

@ -63,7 +63,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"llio",
"susres",
"codec",
"sha2:0.9.8",
"sha2",
"engine-25519",
"spinor",
"root-keys",