incorporate arch migrations into vault

note that this also triggered a huge format of a crate
that was marked for non-formatting to make diffs easier to
the opensk mainline

however, it is OK to format these specific submodules because they
are platform implementations that don't exist in opensk, so there
is nothing to diff against
This commit is contained in:
bunnie 2025-05-11 12:39:41 +08:00
parent ca04a3ea82
commit d0e76fe424
3 changed files with 328 additions and 257 deletions

View file

@ -34,6 +34,7 @@ rand_core = "0.6.3"
ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.63" } ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.63" }
userprefs = { path = "../../libs/userprefs" } userprefs = { path = "../../libs/userprefs" }
ux-api = { path = "../../libs/ux-api", default-features = false } ux-api = { path = "../../libs/ux-api", default-features = false }
precursor-hal = { path = "../../libs/precursor-hal" }
# opensk # opensk
ctap-crypto = { path = "libraries/crypto" } ctap-crypto = { path = "libraries/crypto" }

View file

@ -1,29 +1,31 @@
use core::sync::atomic::{AtomicU32, Ordering};
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};
use ctap_crypto::rng256::XousRng256;
use locales::t;
use modals::Modals;
use num_traits::*;
use persistent_store::Store;
use precursor_hal::board::{BOOKEND_END, BOOKEND_START};
use xous::try_send_message;
use xous_names::XousNames;
use xous_usb_hid::device::fido::*;
pub use self::storage::XousStorage; pub use self::storage::XousStorage;
use crate::KEEPALIVE_DELAY_MS;
use crate::api::attestation_store::AttestationStore; use crate::api::attestation_store::AttestationStore;
use crate::api::connection::{HidConnection, SendOrRecvError, SendOrRecvResult, SendOrRecvStatus}; use crate::api::connection::{HidConnection, SendOrRecvError, SendOrRecvResult, SendOrRecvStatus};
use crate::api::customization::{CustomizationImpl, DEFAULT_CUSTOMIZATION}; use crate::api::customization::{CustomizationImpl, DEFAULT_CUSTOMIZATION};
use crate::api::firmware_protection::FirmwareProtection; use crate::api::firmware_protection::FirmwareProtection;
use crate::api::user_presence::{UserPresence, UserPresenceError, UserPresenceResult}; use crate::api::user_presence::{UserPresence, UserPresenceError, UserPresenceResult};
use crate::api::{attestation_store, key_store}; use crate::api::{attestation_store, key_store};
use crate::KEEPALIVE_DELAY_MS; use crate::ctap::hid::{CtapHid, CtapHidCommand, KeepaliveStatus, ProcessedPacket};
use crate::env::Env; use crate::env::Env;
use core::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};
use persistent_store::Store;
use ctap_crypto::rng256::XousRng256;
use xous::try_send_message;
use xous_names::XousNames;
use crate::env::xous::storage::XousUpgradeStorage; use crate::env::xous::storage::XousUpgradeStorage;
use xous_usb_hid::device::fido::*; use crate::{AppInfo, basis_change, deserialize_app_info, serialize_app_info};
use modals::Modals;
use locales::t;
use std::io::{Read, Write};
use num_traits::*;
use crate::ctap::hid::{CtapHid, KeepaliveStatus, ProcessedPacket, CtapHidCommand};
use crate::{basis_change, deserialize_app_info, AppInfo, serialize_app_info};
pub const U2F_APP_DICT: &'static str = "fido.u2fapps"; pub const U2F_APP_DICT: &'static str = "fido.u2fapps";
const KEEPALIVE_DELAY: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS); const KEEPALIVE_DELAY: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS);
@ -33,35 +35,25 @@ pub struct XousHidConnection {
pub endpoint: usb_device_xous::UsbHid, pub endpoint: usb_device_xous::UsbHid,
} }
impl XousHidConnection { impl XousHidConnection {
pub fn recv_with_timeout( pub fn recv_with_timeout(&mut self, buf: &mut [u8; 64], timeout_delay: Duration) -> SendOrRecvStatus {
&mut self,
buf: &mut [u8; 64],
timeout_delay: Duration,
) -> SendOrRecvStatus {
match self.endpoint.u2f_wait_incoming_timeout(timeout_delay.as_millis() as u64) { match self.endpoint.u2f_wait_incoming_timeout(timeout_delay.as_millis() as u64) {
Ok(msg) => { Ok(msg) => {
buf.copy_from_slice(&msg.packet); buf.copy_from_slice(&msg.packet);
SendOrRecvStatus::Received SendOrRecvStatus::Received
} }
Err(_e) => { Err(_e) => SendOrRecvStatus::Timeout,
SendOrRecvStatus::Timeout
}
} }
} }
pub fn u2f_wait_incoming(&self) -> Result<RawFidoReport, xous::Error> { pub fn u2f_wait_incoming(&self) -> Result<RawFidoReport, xous::Error> {
self.endpoint.u2f_wait_incoming() self.endpoint.u2f_wait_incoming()
} }
pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> {
self.endpoint.u2f_send(msg) pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> { self.endpoint.u2f_send(msg) }
}
} }
impl HidConnection for XousHidConnection { impl HidConnection for XousHidConnection {
fn send_and_maybe_recv( fn send_and_maybe_recv(&mut self, buf: &mut [u8; 64], _timeout: Duration) -> SendOrRecvResult {
&mut self,
buf: &mut [u8; 64],
_timeout: Duration,
) -> SendOrRecvResult {
let mut reply = RawFidoReport::default(); let mut reply = RawFidoReport::default();
reply.packet.copy_from_slice(buf); reply.packet.copy_from_slice(buf);
match self.endpoint.u2f_send(reply) { match self.endpoint.u2f_send(reply) {
@ -101,7 +93,7 @@ pub struct XousEnv {
#[cfg(feature = "vendor_hid")] #[cfg(feature = "vendor_hid")]
vendor_connection: XousHidConnection, vendor_connection: XousHidConnection,
modals: Modals, modals: Modals,
last_user_presence_request: Option::<Instant>, last_user_presence_request: Option<Instant>,
ctap1_cid: xous::CID, ctap1_cid: xous::CID,
lefty_mode: Arc<AtomicBool>, lefty_mode: Arc<AtomicBool>,
} }
@ -132,42 +124,73 @@ impl XousEnv {
let mut run = false; let mut run = false;
loop { loop {
xous::reply_and_receive_next_legacy(ctap1_timeout_sid, &mut msg_opt, &mut _return_type) xous::reply_and_receive_next_legacy(ctap1_timeout_sid, &mut msg_opt, &mut _return_type)
.unwrap(); .unwrap();
let msg = msg_opt.as_mut().unwrap(); let msg = msg_opt.as_mut().unwrap();
log::debug!("msg: {:x?}", msg); log::debug!("msg: {:x?}", msg);
match num_traits::FromPrimitive::from_usize(msg.body.id()) match num_traits::FromPrimitive::from_usize(msg.body.id())
.unwrap_or(Ctap1TimeoutOp::Invalid) .unwrap_or(Ctap1TimeoutOp::Invalid)
{ {
Ctap1TimeoutOp::Run => { Ctap1TimeoutOp::Run => {
if !run { // only kick off the loop on the first request to run if !run {
// only kick off the loop on the first request to run
start_time = Instant::now(); start_time = Instant::now();
try_send_message(ctap1_timeout_cid, xous::Message::new_scalar( try_send_message(
Ctap1TimeoutOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Pump.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
} }
run = true; run = true;
}, }
Ctap1TimeoutOp::Pump => { Ctap1TimeoutOp::Pump => {
let elapsed = Instant::now().duration_since(start_time); let elapsed = Instant::now().duration_since(start_time);
if run { if run {
if elapsed.as_millis() > crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() + MARGIN_MS { if elapsed.as_millis()
> crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() + MARGIN_MS
{
run = false; run = false;
// timed out, force the dialog box to close // timed out, force the dialog box to close
try_send_message(ctap1_cid, xous::Message::new_scalar( try_send_message(
Ctap1Op::ForceTimeout.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_cid,
xous::Message::new_scalar(
Ctap1Op::ForceTimeout.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
// no pump message, so the thread should stop running. // no pump message, so the thread should stop running.
} else { } else {
// no timeout, keep pinging // no timeout, keep pinging
tt.sleep_ms(1000).unwrap(); tt.sleep_ms(1000).unwrap();
try_send_message(ctap1_timeout_cid, xous::Message::new_scalar( try_send_message(
Ctap1TimeoutOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Pump.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
} }
} }
}, }
Ctap1TimeoutOp::Stop => { Ctap1TimeoutOp::Stop => {
// this can come asynchronously from the ctap1 thread once the box is ack'd. // this can come asynchronously from the ctap1 thread once the box is ack'd.
run = false; run = false;
// this will stop the pump from running, and the thread will block at waiting for incoming messages // this will stop the pump from running, and the thread will block at waiting for
}, // incoming messages
}
Ctap1TimeoutOp::Invalid => { Ctap1TimeoutOp::Invalid => {
log::error!("invalid opcode received: {:?}", msg); log::error!("invalid opcode received: {:?}", msg);
} }
@ -194,13 +217,10 @@ impl XousEnv {
let mut last_remaining = 0u64; let mut last_remaining = 0u64;
let kbhit = Arc::new(AtomicU32::new(0)); let kbhit = Arc::new(AtomicU32::new(0));
loop { loop {
xous::reply_and_receive_next_legacy(ctap1_sid, &mut msg_opt, &mut _return_type) xous::reply_and_receive_next_legacy(ctap1_sid, &mut msg_opt, &mut _return_type).unwrap();
.unwrap();
let msg = msg_opt.as_mut().unwrap(); let msg = msg_opt.as_mut().unwrap();
log::trace!("msg: {:x?}", msg); log::trace!("msg: {:x?}", msg);
match num_traits::FromPrimitive::from_usize(msg.body.id()) match num_traits::FromPrimitive::from_usize(msg.body.id()).unwrap_or(Ctap1Op::Invalid) {
.unwrap_or(Ctap1Op::Invalid)
{
Ctap1Op::PollPermission => { Ctap1Op::PollPermission => {
let mut buf = unsafe { let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut( xous_ipc::Buffer::from_memory_message_mut(
@ -212,59 +232,95 @@ impl XousEnv {
if let Some(id) = &current_id { if let Some(id) = &current_id {
log::trace!("poll of existing ID"); log::trace!("poll of existing ID");
if *id != request.app_id { if *id != request.app_id {
log::error!("Request ID changed while request is in progress. Ignoring request"); log::error!(
"Request ID changed while request is in progress. Ignoring request"
);
buf.replace(request).ok(); buf.replace(request).ok();
xous::send_message(ctap1_timeout_cid, xous::Message::new_scalar( xous::send_message(
Ctap1TimeoutOp::Stop.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Stop.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
modals.dynamic_notification_close().ok(); modals.dynamic_notification_close().ok();
current_id = None; current_id = None;
continue; continue;
} else { } else {
let key = kbhit.load(Ordering::SeqCst); let key = kbhit.load(Ordering::SeqCst);
if key != 0 && if key != 0
((!lefty_mode.load(Ordering::SeqCst) && (key != 0x11)) && ((!lefty_mode.load(Ordering::SeqCst) && (key != 0x11))
|| (lefty_mode.load(Ordering::SeqCst) && (key != 0x14)) || (lefty_mode.load(Ordering::SeqCst) && (key != 0x14)))
) { // approved {
// approved
log::trace!("approved"); log::trace!("approved");
request.approved = true; request.approved = true;
current_id = None; current_id = None;
xous::send_message(ctap1_timeout_cid, xous::Message::new_scalar( xous::send_message(
Ctap1TimeoutOp::Stop.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Stop.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
modals.dynamic_notification_close().ok(); modals.dynamic_notification_close().ok();
} else if } else if (!lefty_mode.load(Ordering::SeqCst) && (key == 0x11))
(!lefty_mode.load(Ordering::SeqCst) && (key == 0x11)) || (lefty_mode.load(Ordering::SeqCst) && (key == 0x14))
|| (lefty_mode.load(Ordering::SeqCst) && (key == 0x14)) { // denied {
// denied
log::trace!("denied"); log::trace!("denied");
request.approved = false; request.approved = false;
denied_id = current_id.take(); denied_id = current_id.take();
xous::send_message(ctap1_timeout_cid, xous::Message::new_scalar( xous::send_message(
Ctap1TimeoutOp::Stop.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Stop.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
modals.dynamic_notification_close().ok(); modals.dynamic_notification_close().ok();
} else { } else {
log::trace!("waiting"); log::trace!("waiting");
// keep waiting for an interaction, with a timeout // keep waiting for an interaction, with a timeout
let now = tt.elapsed_ms(); let now = tt.elapsed_ms();
if (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) > (now - request_start) { if (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64)
let new_remaining = ((crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) - (now - request_start)) / 1000; > (now - request_start)
{
let new_remaining =
((crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64)
- (now - request_start))
/ 1000;
if new_remaining != last_remaining { if new_remaining != last_remaining {
log::info!("countdown: {}", new_remaining); log::info!("countdown: {}", new_remaining);
last_remaining = new_remaining; last_remaining = new_remaining;
let mut to_request_str = request_str.to_string(); let mut to_request_str = request_str.to_string();
to_request_str.push_str( to_request_str.push_str(&format!(
&format!("\n\n⚠ {}{} ⚠\n", "\n\n⚠ {}{} ⚠\n",
last_remaining, last_remaining,
t!("vault.fido.countdown", locales::LANG) t!("vault.fido.countdown", locales::LANG)
)); ));
modals.dynamic_notification_update( modals
Some( .dynamic_notification_update(
if lefty_mode.load(Ordering::SeqCst) { Some(if lefty_mode.load(Ordering::SeqCst) {
t!("vault.u2freq_lefty", locales::LANG) t!("vault.u2freq_lefty", locales::LANG)
} else { } else {
t!("vault.u2freq", locales::LANG) t!("vault.u2freq", locales::LANG)
} }),
), Some(&to_request_str),
Some(&to_request_str), )
).unwrap(); .unwrap();
} }
} else { } else {
log::trace!("timed out"); log::trace!("timed out");
@ -272,8 +328,17 @@ impl XousEnv {
current_id = None; current_id = None;
denied_id = None; denied_id = None;
request.approved = false; request.approved = false;
xous::send_message(ctap1_timeout_cid, xous::Message::new_scalar( xous::send_message(
Ctap1TimeoutOp::Stop.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Stop.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
modals.dynamic_notification_close().ok(); modals.dynamic_notification_close().ok();
} }
} }
@ -283,7 +348,9 @@ impl XousEnv {
} else { } else {
log::debug!("setup new ID query: {:?}", request.app_id); log::debug!("setup new ID query: {:?}", request.app_id);
if let Some(denied) = denied_id.take() { if let Some(denied) = denied_id.take() {
if tt.elapsed_ms() - request_start < (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) { if tt.elapsed_ms() - request_start
< (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64)
{
if denied == request.app_id { if denied == request.app_id {
// this is a repeat request for a denied ID // this is a repeat request for a denied ID
request.approved = false; request.approved = false;
@ -291,7 +358,8 @@ impl XousEnv {
denied_id = Some(denied); denied_id = Some(denied);
continue; continue;
} else { } else {
// it's a different request, carry on; the denied_id will be reset as we handle this new request // it's a different request, carry on; the denied_id will be reset
// as we handle this new request
} }
} else { } else {
// denial should automatically reset due to .take() // denial should automatically reset due to .take()
@ -302,22 +370,27 @@ impl XousEnv {
if let Some(info) = { if let Some(info) = {
// fetch the application info, if it exists // fetch the application info, if it exists
log::debug!("querying U2F record {}", app_id_str); log::debug!("querying U2F record {}", app_id_str);
// add code to query the PDDB here to look for the k/v mapping of this app ID // add code to query the PDDB here to look for the k/v mapping of this app
// ID
match pddb.get( match pddb.get(
U2F_APP_DICT, U2F_APP_DICT,
&app_id_str, &app_id_str,
None, true, false, None,
Some(256), Some(basis_change) true,
false,
Some(256),
Some(basis_change),
) { ) {
Ok(mut app_data) => { Ok(mut app_data) => {
let app_attr = app_data.attributes().unwrap(); let app_attr = app_data.attributes().unwrap();
if app_attr.len != 0 { if app_attr.len != 0 {
let mut descriptor = Vec::<u8>::new(); let mut descriptor = Vec::<u8>::new();
match app_data.read_to_end(&mut descriptor) { match app_data.read_to_end(&mut descriptor) {
Ok(_) => { Ok(_) => deserialize_app_info(descriptor),
deserialize_app_info(descriptor) Err(e) => {
log::error!("Couldn't read app info: {:?}", e);
None
} }
Err(e) => {log::error!("Couldn't read app info: {:?}", e); None}
} }
} else { } else {
None None
@ -331,43 +404,47 @@ impl XousEnv {
} { } {
request_str.clear(); request_str.clear();
// we have some prior record of the app, human-format it // we have some prior record of the app, human-format it
request_str.push_str(&format!("\n{}{}", request_str.push_str(&format!(
t!("vault.u2f.appinfo.name", locales::LANG), info.name "\n{}{}",
t!("vault.u2f.appinfo.name", locales::LANG),
info.name
)); ));
request_str.push_str(&format!("\n{}", request_str.push_str(&format!("\n{}", crate::atime_to_str(info.atime)));
crate::atime_to_str(info.atime) request_str.push_str(&format!(
)); "\n{}{}",
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.authcount", locales::LANG), t!("vault.u2f.appinfo.authcount", locales::LANG),
info.count, info.count,
)); ));
} else { } else {
request_str.clear(); request_str.clear();
// request approval of the new app ID // request approval of the new app ID
request_str.push_str(&format!("\n{}\nApp ID: {:x?}", request_str.push_str(&format!(
t!("vault.u2f.appinfo.newapp", locales::LANG), request.app_id "\n{}\nApp ID: {:x?}",
t!("vault.u2f.appinfo.newapp", locales::LANG),
request.app_id
)); ));
} }
let mut to_request_str = request_str.to_string(); let mut to_request_str = request_str.to_string();
request_start = tt.elapsed_ms(); request_start = tt.elapsed_ms();
last_remaining = ((crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) last_remaining = ((crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64)
- (tt.elapsed_ms() - request_start)) / 1000; - (tt.elapsed_ms() - request_start))
to_request_str.push_str( / 1000;
&format!("\n\n⚠ {}{} ⚠\n", to_request_str.push_str(&format!(
"\n\n⚠ {}{} ⚠\n",
last_remaining, last_remaining,
t!("vault.fido.countdown", locales::LANG) t!("vault.fido.countdown", locales::LANG)
)); ));
modals.dynamic_notification( modals
Some( .dynamic_notification(
if lefty_mode.load(Ordering::SeqCst) { Some(if lefty_mode.load(Ordering::SeqCst) {
t!("vault.u2freq_lefty", locales::LANG) t!("vault.u2freq_lefty", locales::LANG)
} else { } else {
t!("vault.u2freq", locales::LANG) t!("vault.u2freq", locales::LANG)
} }),
), Some(&to_request_str),
Some(&to_request_str), )
).unwrap(); .unwrap();
// start a keyboard listener // start a keyboard listener
kbhit.store(0, Ordering::SeqCst); kbhit.store(0, Ordering::SeqCst);
let _ = std::thread::spawn({ let _ = std::thread::spawn({
@ -375,25 +452,38 @@ impl XousEnv {
let conn = modals.conn().clone(); let conn = modals.conn().clone();
let kbhit = kbhit.clone(); let kbhit = kbhit.clone();
move || { move || {
// note that if no key is hit, we get None back on dialog box close automatically // note that if no key is hit, we get None back on dialog box close
// automatically
match modals::dynamic_notification_blocking_listener(token, conn) { match modals::dynamic_notification_blocking_listener(token, conn) {
Ok(Some(c)) => { Ok(Some(c)) => {
log::trace!("kbhit got {}", c); log::trace!("kbhit got {}", c);
kbhit.store(c as u32, Ordering::SeqCst) kbhit.store(c as u32, Ordering::SeqCst)
}, }
Ok(None) => { Ok(None) => {
log::trace!("kbhit exited or had no characters"); log::trace!("kbhit exited or had no characters");
kbhit.store(0, Ordering::SeqCst) kbhit.store(0, Ordering::SeqCst)
}, }
Err(e) => log::error!("error waiting for keyboard hit from blocking listener: {:?}", e), Err(e) => log::error!(
"error waiting for keyboard hit from blocking listener: {:?}",
e
),
} }
} }
}); });
current_id = Some(request.app_id); current_id = Some(request.app_id);
// start the timeout watchdog, because if another token responds to the request, // start the timeout watchdog, because if another token responds to the
// we will be left hanging. // request, we will be left hanging.
xous::try_send_message(ctap1_timeout_cid, xous::Message::new_scalar( xous::try_send_message(
Ctap1TimeoutOp::Run.to_usize().unwrap(), 0, 0, 0, 0)).ok(); ctap1_timeout_cid,
xous::Message::new_scalar(
Ctap1TimeoutOp::Run.to_usize().unwrap(),
0,
0,
0,
0,
),
)
.ok();
denied_id = None; // reset the denial timers, too denied_id = None; // reset the denial timers, too
request.approved = false; request.approved = false;
buf.replace(request).ok(); buf.replace(request).ok();
@ -401,9 +491,7 @@ impl XousEnv {
} }
Ctap1Op::UpdateAppInfo => { Ctap1Op::UpdateAppInfo => {
let buf = unsafe { let buf = unsafe {
xous_ipc::Buffer::from_memory_message( xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap())
msg.body.memory_message().unwrap(),
)
}; };
let update = buf.to_original::<Ctap1Request, _>().unwrap(); let update = buf.to_original::<Ctap1Request, _>().unwrap();
let app_id_str = hex::encode(update.app_id); let app_id_str = hex::encode(update.app_id);
@ -412,22 +500,27 @@ impl XousEnv {
let mut info = { let mut info = {
// fetch the application info, if it exists // fetch the application info, if it exists
log::info!("Updating U2F record {}", app_id_str); log::info!("Updating U2F record {}", app_id_str);
// add code to query the PDDB here to look for the k/v mapping of this app ID // add code to query the PDDB here to look for the k/v mapping of this app
// ID
match pddb.get( match pddb.get(
U2F_APP_DICT, U2F_APP_DICT,
&app_id_str, &app_id_str,
None, true, false, None,
Some(256), Some(basis_change) true,
false,
Some(256),
Some(basis_change),
) { ) {
Ok(mut app_data) => { Ok(mut app_data) => {
let app_attr = app_data.attributes().unwrap(); let app_attr = app_data.attributes().unwrap();
if app_attr.len != 0 { if app_attr.len != 0 {
let mut descriptor = Vec::<u8>::new(); let mut descriptor = Vec::<u8>::new();
match app_data.read_to_end(&mut descriptor) { match app_data.read_to_end(&mut descriptor) {
Ok(_) => { Ok(_) => deserialize_app_info(descriptor),
deserialize_app_info(descriptor) Err(e) => {
log::error!("Couldn't read app info: {:?}", e);
None
} }
Err(e) => {log::error!("Couldn't read app info: {:?}", e); None}
} }
} else { } else {
None None
@ -438,44 +531,47 @@ impl XousEnv {
None None
} }
} }
}.unwrap_or_else( }
|| { .unwrap_or_else(|| {
// otherwise, create it // otherwise, create it
match modals match modals
.alert_builder(t!("vault.u2f.give_app_name", locales::LANG)) .alert_builder(t!("vault.u2f.give_app_name", locales::LANG))
.field(None, None) .field(None, None)
.build() .build()
{ {
Ok(name) => { Ok(name) => {
let info = AppInfo { let info = AppInfo {
name: name.content()[0].content.to_string(), name: name.content()[0].content.to_string(),
notes: t!("vault.notes", locales::LANG).to_string(), notes: t!("vault.notes", locales::LANG).to_string(),
id: update.app_id, id: update.app_id,
ctime: crate::utc_now().timestamp() as u64, ctime: crate::utc_now().timestamp() as u64,
atime: 0, atime: 0,
count: 0, count: 0,
}; };
info info
} }
_ => { _ => {
log::error!("couldn't get name for app"); log::error!("couldn't get name for app");
panic!("couldn't get name for app"); panic!("couldn't get name for app");
}
} }
} }
); });
info.atime = crate::utc_now().timestamp() as u64; info.atime = crate::utc_now().timestamp() as u64;
info.count = info.count.saturating_add(1); info.count = info.count.saturating_add(1);
let ser = serialize_app_info(&info); let ser = serialize_app_info(&info);
// update the access time, by deleting the key and writing it back into the PDDB // update the access time, by deleting the key and writing it back into the
// PDDB
pddb.delete_key(U2F_APP_DICT, &app_id_str, None).ok(); pddb.delete_key(U2F_APP_DICT, &app_id_str, None).ok();
match pddb.get( match pddb.get(
U2F_APP_DICT, U2F_APP_DICT,
&app_id_str, &app_id_str,
None, true, true, None,
Some(256), Some(basis_change) true,
true,
Some(256),
Some(basis_change),
) { ) {
Ok(mut app_data) => { Ok(mut app_data) => {
app_data.write(&ser).expect("couldn't update atime"); app_data.write(&ser).expect("couldn't update atime");
@ -492,8 +588,13 @@ impl XousEnv {
main_cid, main_cid,
xous::Message::new_scalar( xous::Message::new_scalar(
crate::VaultOp::ReloadDbAndFullRedraw.to_usize().unwrap(), crate::VaultOp::ReloadDbAndFullRedraw.to_usize().unwrap(),
0, 0, 0, 0) 0,
).unwrap(); 0,
0,
0,
),
)
.unwrap();
} }
Ctap1Op::ForceTimeout => { Ctap1Op::ForceTimeout => {
log::info!("polling timed out"); log::info!("polling timed out");
@ -512,29 +613,21 @@ impl XousEnv {
XousEnv { XousEnv {
rng: XousRng256::new(&xns), rng: XousRng256::new(&xns),
store, store,
main_connection: XousHidConnection { main_connection: XousHidConnection { endpoint: usb_device_xous::UsbHid::new() },
endpoint: usb_device_xous::UsbHid::new(),
},
#[cfg(feature = "vendor_hid")] #[cfg(feature = "vendor_hid")]
vendor_connection: XousHidConnection { vendor_connection: XousHidConnection { endpoint: UsbEndpoint::VendorHid },
endpoint: UsbEndpoint::VendorHid,
},
modals: modals::Modals::new(&xns).unwrap(), modals: modals::Modals::new(&xns).unwrap(),
last_user_presence_request: None, last_user_presence_request: None,
ctap1_cid, ctap1_cid,
lefty_mode, lefty_mode,
} }
} }
/// Checks if the SoC is compatible with USB drivers (older versions of Precursor's FPGA don't have the USB device core)
pub fn is_soc_compatible(&self) -> bool {
self.main_connection.endpoint.is_soc_compatible()
}
fn send_keepalive_up_needed( /// Checks if the SoC is compatible with USB drivers (older versions of Precursor's FPGA don't have the
&mut self, /// USB device core)
timeout: Duration, pub fn is_soc_compatible(&self) -> bool { self.main_connection.endpoint.is_soc_compatible() }
cid: [u8; 4]
) -> Result<(), UserPresenceError> { fn send_keepalive_up_needed(&mut self, timeout: Duration, cid: [u8; 4]) -> Result<(), UserPresenceError> {
let keepalive_msg = CtapHid::keepalive(cid, KeepaliveStatus::UpNeeded); let keepalive_msg = CtapHid::keepalive(cid, KeepaliveStatus::UpNeeded);
for mut pkt in keepalive_msg { for mut pkt in keepalive_msg {
match self.main_connection.send_and_maybe_recv(&mut pkt, timeout) { match self.main_connection.send_and_maybe_recv(&mut pkt, timeout) {
@ -580,29 +673,32 @@ impl XousEnv {
} }
Ok(()) Ok(())
} }
} }
impl UserPresence for XousEnv { impl UserPresence for XousEnv {
fn check_init(&mut self) { fn check_init(&mut self) {}
}
/// Implements FIDO behavior (CTAP2 protocol) /// Implements FIDO behavior (CTAP2 protocol)
fn wait_with_timeout(&mut self, timeout: Duration, reason: Option::<String>, cid: [u8; 4]) -> UserPresenceResult { fn wait_with_timeout(
log::info!("{}VAULT.PERMISSION,{}", xous::BOOKEND_START, xous::BOOKEND_END); &mut self,
timeout: Duration,
reason: Option<String>,
cid: [u8; 4],
) -> UserPresenceResult {
log::info!("{}VAULT.PERMISSION,{}", BOOKEND_START, BOOKEND_END);
let reason = reason.unwrap_or(String::new()); let reason = reason.unwrap_or(String::new());
let kbhit = Arc::new(AtomicU32::new(0)); let kbhit = Arc::new(AtomicU32::new(0));
let expiration = Instant::now().checked_add(timeout).expect("duration bug"); let expiration = Instant::now().checked_add(timeout).expect("duration bug");
self.modals.dynamic_notification( self.modals
Some( .dynamic_notification(
if self.lefty_mode.load(Ordering::SeqCst) { Some(if self.lefty_mode.load(Ordering::SeqCst) {
t!("vault.u2freq_lefty", locales::LANG) t!("vault.u2freq_lefty", locales::LANG)
} else { } else {
t!("vault.u2freq", locales::LANG) t!("vault.u2freq", locales::LANG)
} }),
), None,
None, )
).unwrap(); .unwrap();
// start the keyboard hit listener thread // start the keyboard hit listener thread
let _ = std::thread::spawn({ let _ = std::thread::spawn({
let token = self.modals.token().clone(); let token = self.modals.token().clone();
@ -614,11 +710,11 @@ impl UserPresence for XousEnv {
Ok(Some(c)) => { Ok(Some(c)) => {
log::trace!("kbhit got {}", c); log::trace!("kbhit got {}", c);
kbhit.store(c as u32, Ordering::SeqCst) kbhit.store(c as u32, Ordering::SeqCst)
}, }
Ok(None) => { Ok(None) => {
log::trace!("kbhit exited or had no characters"); log::trace!("kbhit exited or had no characters");
kbhit.store(0, Ordering::SeqCst) kbhit.store(0, Ordering::SeqCst)
}, }
Err(e) => log::error!("error waiting for keyboard hit from blocking listener: {:?}", e), Err(e) => log::error!("error waiting for keyboard hit from blocking listener: {:?}", e),
} }
} }
@ -631,49 +727,51 @@ impl UserPresence for XousEnv {
if last_remaining != remaining { if last_remaining != remaining {
log::info!("countdown: {}", remaining); log::info!("countdown: {}", remaining);
// only update the UX once per second // only update the UX once per second
request_str.push_str( request_str.push_str(&format!(
&format!("\n\n⚠ {}{} ⚠\n", "\n\n⚠ {}{} ⚠\n",
remaining, remaining,
t!("vault.fido.countdown", locales::LANG) t!("vault.fido.countdown", locales::LANG)
)); ));
self.modals.dynamic_notification_update( self.modals
Some( .dynamic_notification_update(
if self.lefty_mode.load(Ordering::SeqCst) { Some(if self.lefty_mode.load(Ordering::SeqCst) {
t!("vault.u2freq_lefty", locales::LANG) t!("vault.u2freq_lefty", locales::LANG)
} else { } else {
t!("vault.u2freq", locales::LANG) t!("vault.u2freq", locales::LANG)
} }),
), Some(&request_str),
Some(&request_str), )
).unwrap(); .unwrap();
last_remaining = remaining; last_remaining = remaining;
} }
// handle exit cases // handle exit cases
if remaining == 0 { if remaining == 0 {
self.modals.dynamic_notification_close().ok(); self.modals.dynamic_notification_close().ok();
return Err(UserPresenceError::Timeout) return Err(UserPresenceError::Timeout);
} }
let key_hit = kbhit.load(Ordering::SeqCst); let key_hit = kbhit.load(Ordering::SeqCst);
if key_hit != 0 if key_hit != 0
&& ( // approve && (
(!self.lefty_mode.load(Ordering::SeqCst) && (key_hit != 0x11)) // 0x11 is the F1 key // approve
|| (self.lefty_mode.load(Ordering::SeqCst) && (key_hit != 0x14)) // 0x14 is the F4 key (!self.lefty_mode.load(Ordering::SeqCst) && (key_hit != 0x11)) // 0x11 is the F1 key
) || (self.lefty_mode.load(Ordering::SeqCst) && (key_hit != 0x14))
// 0x14 is the F4 key
)
{ {
self.modals.dynamic_notification_close().ok(); self.modals.dynamic_notification_close().ok();
return Ok(()) return Ok(());
} else if // deny } else if
(!self.lefty_mode.load(Ordering::SeqCst) && (key_hit == 0x11)) // deny
(!self.lefty_mode.load(Ordering::SeqCst) && (key_hit == 0x11))
|| (self.lefty_mode.load(Ordering::SeqCst) && (key_hit == 0x14)) || (self.lefty_mode.load(Ordering::SeqCst) && (key_hit == 0x14))
{ {
self.modals.dynamic_notification_close().ok(); self.modals.dynamic_notification_close().ok();
return Err(UserPresenceError::Declined) return Err(UserPresenceError::Declined);
} }
// delay, and keepalive // delay, and keepalive
self.send_keepalive_up_needed(KEEPALIVE_DELAY, cid) self.send_keepalive_up_needed(KEEPALIVE_DELAY, cid).map_err(|e| e.into())?;
.map_err(|e| e.into())?;
std::thread::sleep(KEEPALIVE_DELAY); std::thread::sleep(KEEPALIVE_DELAY);
} }
} }
@ -681,7 +779,9 @@ impl UserPresence for XousEnv {
/// A ctap1-specific call to see if a request was recently made /// A ctap1-specific call to see if a request was recently made
fn recently_requested(&mut self) -> bool { fn recently_requested(&mut self) -> bool {
if let Some(last_req) = self.last_user_presence_request { if let Some(last_req) = self.last_user_presence_request {
if Instant::now().duration_since(last_req).as_millis() < crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() { if Instant::now().duration_since(last_req).as_millis()
< crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis()
{
true true
} else { } else {
false false
@ -690,6 +790,7 @@ impl UserPresence for XousEnv {
false false
} }
} }
/// Wait for user approval of a CTAP1-type credential /// Wait for user approval of a CTAP1-type credential
/// In this flow, we try to map the `app_id` to a user-provided, memorable string /// In this flow, we try to map the `app_id` to a user-provided, memorable string
/// We also give users the option to abort out of approving. /// We also give users the option to abort out of approving.
@ -697,34 +798,29 @@ impl UserPresence for XousEnv {
// update the user presence request parameter // update the user presence request parameter
self.last_user_presence_request = Some(Instant::now()); self.last_user_presence_request = Some(Instant::now());
let request = Ctap1Request { let request = Ctap1Request { reason: String::from(&reason), app_id, approved: false };
reason: String::from(&reason),
app_id,
approved: false
};
let mut buf = xous_ipc::Buffer::into_buf(request).expect("couldn't convert IPC structure"); let mut buf = xous_ipc::Buffer::into_buf(request).expect("couldn't convert IPC structure");
buf.lend_mut(self.ctap1_cid, Ctap1Op::PollPermission.to_u32().unwrap()).expect("couldn't make CTAP1 poll request"); buf.lend_mut(self.ctap1_cid, Ctap1Op::PollPermission.to_u32().unwrap())
.expect("couldn't make CTAP1 poll request");
let response = buf.to_original::<Ctap1Request, _>().expect("couldn't convert IPC structure"); let response = buf.to_original::<Ctap1Request, _>().expect("couldn't convert IPC structure");
if response.approved { if response.approved {
// serialize the response straight back to the app info update path // serialize the response straight back to the app info update path
// we can't "block" this path because if we take too long to respond, the web client will assume we have failed // we can't "block" this path because if we take too long to respond, the web client will assume
// we have failed
let buf = xous_ipc::Buffer::into_buf(response).expect("couldn't convert IPC structure"); let buf = xous_ipc::Buffer::into_buf(response).expect("couldn't convert IPC structure");
buf.send(self.ctap1_cid, Ctap1Op::UpdateAppInfo.to_u32().unwrap()).expect("couldn't make CTAP1 info update"); buf.send(self.ctap1_cid, Ctap1Op::UpdateAppInfo.to_u32().unwrap())
.expect("couldn't make CTAP1 info update");
true true
} else { } else {
false false
} }
} }
fn check_complete(&mut self) { fn check_complete(&mut self) {}
}
} }
impl FirmwareProtection for XousEnv { impl FirmwareProtection for XousEnv {
fn lock(&mut self) -> bool { fn lock(&mut self) -> bool { false }
false
}
} }
impl key_store::Helper for XousEnv {} impl key_store::Helper for XousEnv {}
@ -753,12 +849,9 @@ impl AttestationStore for XousEnv {
} }
use core::fmt; use core::fmt;
pub struct Console { pub struct Console {}
}
impl Console { impl Console {
pub fn new() -> Self { pub fn new() -> Self { Console {} }
Console { }
}
} }
impl fmt::Write for Console { impl fmt::Write for Console {
fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> { fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> {
@ -768,62 +861,39 @@ impl fmt::Write for Console {
} }
impl Env for XousEnv { impl Env for XousEnv {
type Rng = XousRng256;
type UserPresence = Self;
type Storage = XousStorage;
type KeyStore = Self;
type AttestationStore = Self; type AttestationStore = Self;
type FirmwareProtection = Self;
type Write = Console;
type Customization = CustomizationImpl; type Customization = CustomizationImpl;
type FirmwareProtection = Self;
type HidConnection = XousHidConnection; type HidConnection = XousHidConnection;
type KeyStore = Self;
type Rng = XousRng256;
type Storage = XousStorage;
type UpgradeStorage = XousUpgradeStorage; type UpgradeStorage = XousUpgradeStorage;
type UserPresence = Self;
type Write = Console;
fn rng(&mut self) -> &mut Self::Rng { fn rng(&mut self) -> &mut Self::Rng { &mut self.rng }
&mut self.rng
}
fn user_presence(&mut self) -> &mut Self::UserPresence { fn user_presence(&mut self) -> &mut Self::UserPresence { self }
self
}
fn store(&mut self) -> &mut Store<Self::Storage> { fn store(&mut self) -> &mut Store<Self::Storage> { &mut self.store }
&mut self.store
}
fn key_store(&mut self) -> &mut Self { fn key_store(&mut self) -> &mut Self { self }
self
}
fn attestation_store(&mut self) -> &mut Self { fn attestation_store(&mut self) -> &mut Self { self }
self
}
fn upgrade_storage(&mut self) -> Option<&mut Self::UpgradeStorage> { fn upgrade_storage(&mut self) -> Option<&mut Self::UpgradeStorage> { None }
None
}
fn firmware_protection(&mut self) -> &mut Self::FirmwareProtection { fn firmware_protection(&mut self) -> &mut Self::FirmwareProtection { self }
self
}
fn write(&mut self) -> Self::Write { fn write(&mut self) -> Self::Write { Console::new() }
Console::new()
}
fn customization(&self) -> &Self::Customization { fn customization(&self) -> &Self::Customization { &DEFAULT_CUSTOMIZATION }
&DEFAULT_CUSTOMIZATION
}
fn main_hid_connection(&mut self) -> &mut Self::HidConnection { fn main_hid_connection(&mut self) -> &mut Self::HidConnection { &mut self.main_connection }
&mut self.main_connection
}
#[cfg(feature = "vendor_hid")] #[cfg(feature = "vendor_hid")]
fn vendor_hid_connection(&mut self) -> &mut Self::HidConnection { fn vendor_hid_connection(&mut self) -> &mut Self::HidConnection { &mut self.vendor_connection }
&mut self.vendor_connection
}
} }
pub const KEEPALIVE_DELAY_XOUS: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS); pub const KEEPALIVE_DELAY_XOUS: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS);

View file

@ -37,7 +37,7 @@ impl Storage for XousStorage {
} }
fn num_pages(&self) -> usize { fn num_pages(&self) -> usize {
xous::PDDB_LEN as usize / 4096 precursor_hal::board::PDDB_LEN as usize / 4096
} }
fn max_word_writes(&self) -> usize { fn max_word_writes(&self) -> usize {