diff --git a/.gitignore b/.gitignore index 5f6dcc89a..dc5a7b4b3 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/apps/vault/Cargo.toml b/apps/vault/Cargo.toml index 5a30e4300..66f4521e6 100644 --- a/apps/vault/Cargo.toml +++ b/apps/vault/Cargo.toml @@ -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"] diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index d88e37d53..ae9952958 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -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承認するには任意のキーを押してください", diff --git a/apps/vault/src/ctap/mod.rs b/apps/vault/src/ctap/mod.rs index 0f268dbde..34928c1c9 100644 --- a/apps/vault/src/ctap/mod.rs +++ b/apps/vault/src/ctap/mod.rs @@ -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 { //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) } diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 29cfb2328..a7fc4cd79 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -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); + } + } } } } diff --git a/apps/vault/src/ux.rs b/apps/vault/src/ux.rs index 0b64c87ed..344ad3d23 100644 --- a/apps/vault/src/ux.rs +++ b/apps/vault/src/ux.rs @@ -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) diff --git a/buildpush.ps1 b/buildpush.ps1 index 4dd03e317..cb542d67a 100644 --- a/buildpush.ps1 +++ b/buildpush.ps1 @@ -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 diff --git a/services/engine-sha512/src/sha256/soft.rs b/services/engine-sha512/src/sha256/soft.rs index 34826a7e8..0ab1f2b17 100644 --- a/services/engine-sha512/src/sha256/soft.rs +++ b/services/engine-sha512/src/sha256/soft.rs @@ -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]]; diff --git a/services/engine-sha512/src/sha512/soft.rs b/services/engine-sha512/src/sha512/soft.rs index 86105e7e8..7cead514f 100644 --- a/services/engine-sha512/src/sha512/soft.rs +++ b/services/engine-sha512/src/sha512/soft.rs @@ -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; diff --git a/services/ffi-test/src/bindings.rs b/services/ffi-test/src/bindings.rs index 7bfb0183a..689f69277 100644 --- a/services/ffi-test/src/bindings.rs +++ b/services/ffi-test/src/bindings.rs @@ -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 = 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); diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index 3896a96e0..e132188ae 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -54,5 +54,6 @@ pub enum U2fCode { TxAck, RxWait, RxAck, + Hangup, Denied, } \ No newline at end of file diff --git a/services/usb-device-xous/src/lib.rs b/services/usb-device-xous/src/lib.rs index 495c82f59..60dbe9de3 100644 --- a/services/usb-device-xous/src/lib.rs +++ b/services/usb-device-xous/src/lib.rs @@ -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::().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 { diff --git a/services/usb-device-xous/src/main.rs b/services/usb-device-xous/src/main.rs index f8678312b..429d525ff 100644 --- a/services/usb-device-xous/src/main.rs +++ b/services/usb-device-xous/src/main.rs @@ -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::().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 { diff --git a/tools/src/elf.rs b/tools/src/elf.rs index d14a4d36f..0deb13178 100644 --- a/tools/src/elf.rs +++ b/tools/src/elf.rs @@ -315,11 +315,13 @@ pub fn read_minielf>(filename: P) -> Result>(filename: P) -> Result { + 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), + } } } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2028887ad..ded24294f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -63,7 +63,7 @@ fn main() -> Result<(), Box> { "llio", "susres", "codec", - "sha2:0.9.8", + "sha2", "engine-25519", "spinor", "root-keys",