initial integration of fido2.1 now passing some basic tests

This commit is contained in:
bunnie 2023-01-25 00:55:12 +08:00 committed by Sean Cross
parent a00691dab7
commit 15962925e7
9 changed files with 543 additions and 256 deletions

View file

@ -461,6 +461,13 @@
"ja": "アプリ名:",
"zh": "应用名称:"
},
"vault.u2f.appinfo.newapp": {
"en": "New app: ",
"en-tts": "New app: ",
"fr": "Nouvelle application: ",
"ja": "新しいアプリ: ",
"zh": "新应用: "
},
"vault.u2f.appinfo.never": {
"en": "never",
"en-tts": "never",

View file

@ -58,10 +58,11 @@ pub(crate) fn start_actions_thread(
sid: SID, mode: Arc::<Mutex::<VaultMode>>,
item_lists: Arc::<Mutex::<ItemLists>>,
action_active: Arc::<AtomicBool>,
opensk_mutex: Arc::<Mutex::<i32>>,
) {
let _ = thread::spawn({
move || {
let mut manager = ActionManager::new(main_conn, mode, item_lists, action_active);
let mut manager = ActionManager::new(main_conn, mode, item_lists, action_active, opensk_mutex);
loop {
let msg = xous::receive_message(sid).unwrap();
let opcode: Option<ActionOp> = FromPrimitive::from_usize(msg.body.id());
@ -152,6 +153,7 @@ struct ActionManager<'a> {
pddb: RefCell::<pddb::Pddb>,
tt: ticktimer_server::Ticktimer,
action_active: Arc::<AtomicBool>,
opensk_mutex: Arc::<Mutex::<i32>>,
mode_cache: VaultMode,
main_conn: xous::CID,
#[cfg(feature="vaultperf")]
@ -168,7 +170,8 @@ impl<'a> ActionManager<'a> {
main_conn: xous::CID,
mode: Arc::<Mutex::<VaultMode>>,
item_lists: Arc::<Mutex::<ItemLists>>,
action_active: Arc::<AtomicBool>
action_active: Arc::<AtomicBool>,
opensk_mutex: Arc::<Mutex::<i32>>,
) -> ActionManager<'a> {
let xns = xous_names::XousNames::new().unwrap();
let storage_manager = storage::Manager::new(&xns);
@ -199,6 +202,7 @@ impl<'a> ActionManager<'a> {
pddb: RefCell::new(pddb::Pddb::new()),
tt: ticktimer_server::Ticktimer::new().unwrap(),
action_active,
opensk_mutex,
main_conn,
#[cfg(feature="vaultperf")]
perfbuf,
@ -957,7 +961,7 @@ impl<'a> ActionManager<'a> {
t!("vault.u2f.appinfo.authcount", xous::LANG),
ai.count,
);
let desc = format!("{}", ai.name);
let desc = format!("{} (U2F)", ai.name);
let li = ListItem {
name: desc,
extra,
@ -995,61 +999,67 @@ impl<'a> ActionManager<'a> {
},
}
log::debug!("listing in {}", OPENSK2_DICT);
match self.pddb.borrow().read_dict(OPENSK2_DICT, None, Some(256 * 1024)) {
Ok(keys) => {
let mut oom_keys = 0;
for key in keys {
if let Some(data) = key.data {
match vault::ctap::storage::deserialize_credential(&data) {
Some(result) => {
let name = if let Some(display_name) = result.user_display_name {
display_name
} else {
String::from_utf8(result.user_handle).unwrap_or("".to_string())
};
let desc = format!("{} / {}", result.rp_id, String::from_utf8(result.credential_id).unwrap_or("---".to_string()));
let extra = format!("FIDO2 {}", name);
let li = ListItem {
name: desc,
extra,
dirty: true,
guid: key.name,
count: 0,
atime: 0,
};
il.insert(li.key(), li);
{ // this brace creates a block that defines the lifetime of `mutex`; it is released on drop as it goes out of scope
// access to OPENSK2_DICT has to be mutex-guarded, otherwise we get errors as the
// OpenSK thread mutates the dictionary while we query it
let mutex = self.opensk_mutex.lock().unwrap();
log::debug!("listing in {}", OPENSK2_DICT);
match self.pddb.borrow().read_dict(OPENSK2_DICT, None, Some(256 * 1024)) {
Ok(keys) => {
let mut oom_keys = 0;
for key in keys {
let key_number = key.name.parse::<usize>().unwrap_or(0);
if vault::ctap::storage::key::CREDENTIALS.contains(&key_number) {
if let Some(data) = key.data {
match vault::ctap::storage::deserialize_credential(&data) {
Some(result) => {
let name = if let Some(display_name) = result.user_display_name {
display_name
} else {
String::from_utf8(result.user_handle).unwrap_or("".to_string())
};
let desc = format!("{} / {} (FIDO2)", result.rp_id, String::from_utf8(result.credential_id).unwrap_or("---".to_string()));
let extra = format!("{}", name);
let li = ListItem {
name: desc,
extra,
dirty: true,
guid: key.name,
count: 0,
atime: 0,
};
il.insert(li.key(), li);
}
None => {
// Probably more indicative of a mismatch in OpenSK key range mapping, rather than a hard error.
let err = format!("{}:{}:{}: ({}){:x?}...",
key.basis, OPENSK2_DICT, key.name, key.len, &data[..16]
);
log::info!("Couldn't deserialize FIDO2 key {}", err);
},
}
} else {
oom_keys += 1;
}
None => {
// this is "harmless" because we're now returning, like, everything
// print to info! for now, so we can be more selective down the road about
// deserializations and maybe save some time
let err = format!("{}:{}:{}: ({}){:x?}...",
key.basis, OPENSK2_DICT, key.name, key.len, &data[..16]
);
log::info!("Couldn't deserialize FIDO2 key {}", err);
},
}
} else {
oom_keys += 1;
}
if oom_keys != 0 {
log::warn!("Ran out of cache space handling FIDO2 tokens. {} tokens are not loaded.", oom_keys);
self.report_err(&format!("Ran out of cache space handling FIDO2 entries. {} tokens not loaded", oom_keys), None::<crate::storage::Error>);
}
}
if oom_keys != 0 {
log::warn!("Ran out of cache space handling FIDO2 tokens. {} tokens are not loaded.", oom_keys);
self.report_err(&format!("Ran out of cache space handling FIDO2 entries. {} tokens not loaded", oom_keys), None::<crate::storage::Error>);
}
Err(e) => {
match e.kind() {
ErrorKind::NotFound => {
// this is fine, it just means no entries have been entered yet
},
_ => {
log::error!("Error opening FIDO2 dictionary");
self.report_err("Error opening FIDO2 dictionary", Some(e))
}
}
},
}
Err(e) => {
match e.kind() {
ErrorKind::NotFound => {
// this is fine, it just means no entries have been entered yet
},
_ => {
log::error!("Error opening FIDO2 dictionary");
self.report_err("Error opening FIDO2 dictionary", Some(e))
}
}
},
}
}
VaultMode::Totp => {

View file

@ -37,13 +37,16 @@ pub trait UserPresence {
/// Must be called between calls to [`Self::check_init`] and [`Self::check_complete`].
#[cfg(feature="xous")]
fn wait_with_timeout(&mut self, timeout: Duration, reason: Option<String>, cid: [u8; 4]) -> UserPresenceResult;
#[cfg(feature="xous")]
fn recently_requested(&mut self) -> bool;
#[cfg(not(feature="xous"))]
fn wait_with_timeout(&mut self, timeout: Duration) -> UserPresenceResult;
/// CTAP1 waits don't require keepalive packets. They just block. However, they also have
/// an `app_id` which we have to lookup to turn into a human-readable identifier.
/// On the first call, pops up a request box for user presence approval
/// Subsequent calls simply return true/false if the user has finally approved.
/// The request box eventually times out on its own.
#[cfg(feature="xous")]
fn wait_ctap1(&mut self, reason: String, app_id: [u8; 32]) -> bool;
fn poll_approval_ctap1(&mut self, reason: String, app_id: [u8; 32]) -> bool;
/// Finalizes a user presence check.
///

View file

@ -201,6 +201,7 @@ impl Ctap1Command {
}
#[cfg(feature="xous")]
let regstr = String::from(t!("vault.u2f.register", xous::LANG));
#[cfg(feature="xous")]
if !ctap_state.u2f_up_state.consume_up(env, regstr, application) {
log::debug!("still waiting...");
return Err(Ctap1StatusCode::SW_COND_USE_NOT_SATISFIED);
@ -224,6 +225,7 @@ impl Ctap1Command {
#[cfg(feature="xous")]
let authstr = String::from(t!("vault.u2f.authenticate", xous::LANG));
// The order is important due to side effects of checking user presence.
#[cfg(feature="xous")]
if flags == Ctap1Flags::EnforceUpAndSign
&& !ctap_state.u2f_up_state.consume_up(env, authstr, application)
{

View file

@ -113,7 +113,7 @@ pub const TOUCH_TIMEOUT_MS: u64 = 30000;
#[cfg(feature = "with_ctap1")]
pub const TOUCH_TIMEOUT: Duration = Duration::from_millis(TOUCH_TIMEOUT_MS);
#[cfg(feature = "with_ctap1")]
const U2F_UP_PROMPT_TIMEOUT: Duration = Duration::from_millis(10000);
pub const U2F_UP_PROMPT_TIMEOUT: Duration = Duration::from_millis(10000);
// TODO(kaczmarczyck) 2.1 allows Reset after Reset and 15 seconds?
const RESET_TIMEOUT_DURATION: Duration = Duration::from_millis(10000);
const STATEFUL_COMMAND_TIMEOUT_DURATION: Duration = Duration::from_millis(30000);
@ -569,10 +569,10 @@ impl CtapState {
now: Instant,
) -> Vec<u8> {
let cmd = Command::deserialize(command_cbor);
log::debug!("Received command: {:#?}", cmd);
log::debug!("Received command: {:?}", cmd);
let response =
cmd.and_then(|command| self.process_parsed_command(env, command, channel, now));
log::debug!("Sending response: {:#?}", response);
log::debug!("Sending response: {:?}", response);
match response {
Ok(response_data) => {
let mut response_vec = vec![Ctap2StatusCode::CTAP2_OK as u8];
@ -1552,8 +1552,8 @@ impl CtapState {
}
#[cfg(feature = "with_ctap1")]
pub fn u2f_needs_user_presence(&mut self, now: Instant) -> bool {
self.u2f_up_state.is_up_needed(now)
pub fn u2f_needs_user_presence(&mut self, env: &mut impl Env, now: Instant) -> bool {
self.u2f_up_state.is_up_needed(env, now)
}
}

View file

@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature="xous")]
pub mod key; // allows us to access the table of key names so we can inspect the contents of OpenSK's database
#[cfg(not(feature="xous"))]
mod key;
use crate::api::attestation_store::{self, AttestationStore};

View file

@ -96,7 +96,7 @@ impl U2fUserPresenceState {
// This marks user presence as needed or uses it up if already granted. Also cleans up.
#[cfg(feature="xous")]
pub fn consume_up(&mut self, env: &mut impl Env, reason: String, app_id: [u8; 32]) -> bool {
env.user_presence().wait_ctap1(String::from(reason), app_id)
env.user_presence().poll_approval_ctap1(String::from(reason), app_id)
}
#[cfg(not(feature="xous"))]
pub fn consume_up(&mut self, now: Instant) -> bool {
@ -117,8 +117,8 @@ impl U2fUserPresenceState {
self.needs_up.is_granted(now)
}
#[cfg(feature="xous")]
pub fn is_up_needed(&mut self, _now: Instant) -> bool {
false
pub fn is_up_needed(&mut self, env: &mut impl Env, _now: Instant) -> bool {
env.user_presence().recently_requested()
}
// If you don't regularly call any other function, not cleaning up leads to overflow problems.

View file

@ -19,6 +19,7 @@ use pddb::Pddb;
use modals::Modals;
use locales::t;
use std::io::{Read, Write};
use std::num::ParseIntError;
use num_traits::*;
use crate::ctap::hid::{CtapHid, KeepaliveStatus, ProcessedPacket, CtapHidCommand};
@ -28,6 +29,13 @@ pub const U2F_APP_DICT: &'static str = "fido.u2fapps";
const KEEPALIVE_DELAY: Duration = Duration::from_millis(KEEPALIVE_DELAY_MS);
mod storage;
fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16))
.collect()
}
pub struct XousHidConnection {
pub endpoint: usb_device_xous::UsbHid,
}
@ -47,6 +55,12 @@ impl XousHidConnection {
}
}
}
pub fn u2f_wait_incoming(&self) -> Result<RawFidoMsg, xous::Error> {
self.endpoint.u2f_wait_incoming()
}
pub fn u2f_send(&self, msg: RawFidoMsg) -> Result<(), xous::Error> {
self.endpoint.u2f_send(msg)
}
}
impl HidConnection for XousHidConnection {
@ -67,6 +81,18 @@ impl HidConnection for XousHidConnection {
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
struct Ctap1Request {
reason: xous_ipc::String::<1024>,
app_id: [u8; 32],
approved: bool,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
enum Ctap1Op {
PollPermission,
UpdateAppInfo,
Invalid,
}
pub struct XousEnv {
rng: XousRng256,
store: Store<XousStorage>,
@ -76,6 +102,8 @@ pub struct XousEnv {
modals: Modals,
pddb: Pddb,
main_cid: xous::CID,
last_user_presence_request: Option::<Instant>,
ctap1_cid: xous::CID,
}
impl XousEnv {
@ -86,6 +114,302 @@ impl XousEnv {
let storage = XousStorage {};
let store = Store::new(storage).ok().unwrap();
let xns = XousNames::new().unwrap();
let ctap1_sid = xous::create_server().unwrap();
let ctap1_cid = xous::connect(ctap1_sid).unwrap();
std::thread::spawn({
let main_cid = conn.clone();
move || {
let xns = xous_names::XousNames::new().unwrap();
let pddb = pddb::Pddb::new();
let modals = modals::Modals::new(&xns).unwrap();
let tt = ticktimer_server::Ticktimer::new().unwrap();
let mut msg_opt = None;
let mut _return_type = 0;
let mut current_id: Option<[u8; 32]> = None;
let mut denied_id: Option<[u8; 32]> = None;
let mut request_str = String::new();
let mut request_start = 0u64;
let mut last_remaining = 0u64;
let kbhit = Arc::new(AtomicU32::new(0));
loop {
xous::reply_and_receive_next_legacy(ctap1_sid, &mut msg_opt, &mut _return_type)
.unwrap();
let msg = msg_opt.as_mut().unwrap();
log::trace!("msg: {:x?}", msg);
match num_traits::FromPrimitive::from_usize(msg.body.id())
.unwrap_or(Ctap1Op::Invalid)
{
Ctap1Op::PollPermission => {
let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut(
msg.body.memory_message_mut().unwrap(),
)
};
let mut request = buf.to_original::<Ctap1Request, _>().unwrap();
request.approved = false;
if let Some(id) = &current_id {
log::trace!("poll of existing ID");
if *id != request.app_id {
log::error!("Request ID changed while request is in progress. Ignoring request");
buf.replace(request).ok();
modals.dynamic_notification_close().ok();
current_id = None;
continue;
} else {
let key = kbhit.load(Ordering::SeqCst);
if key != 0 && key != 0x11 { // approved
log::trace!("approved");
request.approved = true;
current_id = None;
modals.dynamic_notification_close().ok();
} else if key == 0x11 { // denied
log::trace!("denied");
request.approved = false;
denied_id = current_id.take();
modals.dynamic_notification_close().ok();
} else {
log::trace!("waiting");
// keep waiting for an interaction, with a timeout
let now = tt.elapsed_ms();
if (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) > (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 {
log::trace!("update timer");
last_remaining = new_remaining;
let mut to_request_str = request_str.to_string();
to_request_str.push_str(
&format!("\n\n⚠ {}{} ⚠\n",
last_remaining,
t!("vault.fido.countdown", xous::LANG)
));
modals.dynamic_notification_update(
Some(t!("vault.u2freq", xous::LANG)),
Some(&to_request_str),
).unwrap();
}
} else {
log::trace!("timed out");
// timed out
current_id = None;
denied_id = None;
request.approved = false;
modals.dynamic_notification_close().ok();
}
}
buf.replace(request).ok();
continue;
}
} else {
log::debug!("setup new ID query: {:?}", request.app_id);
if let Some(denied) = denied_id.take() {
if tt.elapsed_ms() - request_start < (crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64) {
if denied == request.app_id {
// this is a repeat request for a denied ID
request.approved = false;
buf.replace(request).ok();
denied_id = Some(denied);
continue;
} else {
// it's a different request, carry on; the denied_id will be reset as we handle this new request
}
} else {
// denial should automatically reset due to .take()
}
}
// determine the application info string
let app_id_str = hex::encode(request.app_id);
if let Some(mut info) = {
// fetch the application info, if it exists
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
match pddb.get(
U2F_APP_DICT,
&app_id_str,
None, true, false,
Some(256), Some(basis_change)
) {
Ok(mut app_data) => {
let app_attr = app_data.attributes().unwrap();
if app_attr.len != 0 {
let mut descriptor = Vec::<u8>::new();
match app_data.read_to_end(&mut descriptor) {
Ok(_) => {
deserialize_app_info(descriptor)
}
Err(e) => {log::error!("Couldn't read app info: {:?}", e); None}
}
} else {
None
}
}
_ => {
log::info!("couldn't find key {}", app_id_str);
None
}
}
} {
request_str.clear();
// we have some prior record of the app, human-format it
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.name", xous::LANG), info.name
));
request_str.push_str(&format!("\n{}",
crate::atime_to_str(info.atime)
));
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.authcount", xous::LANG),
info.count,
));
} else {
request_str.clear();
// request approval of the new app ID
request_str.push_str(&format!("\n{}\nApp ID: {:x?}",
t!("vault.u2f.appinfo.newapp", xous::LANG), request.app_id
));
}
let mut to_request_str = request_str.to_string();
request_start = tt.elapsed_ms();
last_remaining = ((crate::ctap::U2F_UP_PROMPT_TIMEOUT.as_millis() as u64)
- (tt.elapsed_ms() - request_start)) / 1000;
to_request_str.push_str(
&format!("\n\n⚠ {}{} ⚠\n",
last_remaining,
t!("vault.fido.countdown", xous::LANG)
));
modals.dynamic_notification(
Some(t!("vault.u2freq", xous::LANG)),
Some(&to_request_str),
).unwrap();
// start a keyboard listener
kbhit.store(0, Ordering::SeqCst);
let _ = std::thread::spawn({
let token = modals.token().clone();
let conn = modals.conn().clone();
let kbhit = kbhit.clone();
move || {
// note that if no key is hit, we get None back on dialog box close automatically
match modals::dynamic_notification_blocking_listener(token, conn) {
Ok(Some(c)) => {
log::trace!("kbhit got {}", c);
kbhit.store(c as u32, Ordering::SeqCst)
},
Ok(None) => {
log::trace!("kbhit exited or had no characters");
kbhit.store(0, Ordering::SeqCst)
},
Err(e) => log::error!("error waiting for keyboard hit from blocking listener: {:?}", e),
}
}
});
current_id = Some(request.app_id);
denied_id = None; // reset the denial timers, too
request.approved = false;
buf.replace(request).ok();
}
}
Ctap1Op::UpdateAppInfo => {
let buf = unsafe {
xous_ipc::Buffer::from_memory_message(
msg.body.memory_message().unwrap(),
)
};
let update = buf.to_original::<Ctap1Request, _>().unwrap();
let app_id_str = hex::encode(update.app_id);
// note the access
let mut info = {
// fetch the application info, if it exists
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
match pddb.get(
U2F_APP_DICT,
&app_id_str,
None, true, false,
Some(256), Some(basis_change)
) {
Ok(mut app_data) => {
let app_attr = app_data.attributes().unwrap();
if app_attr.len != 0 {
let mut descriptor = Vec::<u8>::new();
match app_data.read_to_end(&mut descriptor) {
Ok(_) => {
deserialize_app_info(descriptor)
}
Err(e) => {log::error!("Couldn't read app info: {:?}", e); None}
}
} else {
None
}
}
_ => {
log::info!("couldn't find key {}", app_id_str);
None
}
}
}.unwrap_or_else(
|| {
// otherwise, create it
match modals
.alert_builder(t!("vault.u2f.give_app_name", xous::LANG))
.field(None, None)
.build()
{
Ok(name) => {
let info = AppInfo {
name: name.content()[0].content.to_string(),
notes: t!("vault.notes", xous::LANG).to_string(),
id: update.app_id,
ctime: crate::utc_now().timestamp() as u64,
atime: 0,
count: 0,
};
info
}
_ => {
log::error!("couldn't get name for app");
panic!("couldn't get name for app");
}
}
}
);
info.atime = crate::utc_now().timestamp() as u64;
info.count = info.count.saturating_add(1);
let ser = serialize_app_info(&info);
// 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();
match pddb.get(
U2F_APP_DICT,
&app_id_str,
None, true, true,
Some(256), Some(basis_change)
) {
Ok(mut app_data) => {
app_data.write(&ser).expect("couldn't update atime");
}
_ => log::error!("Error updating app atime"),
}
pddb.sync().ok();
log::debug!("sycing UI state...");
xous::send_message(
main_cid,
xous::Message::new_scalar(
crate::VaultOp::ReloadDbAndFullRedraw.to_usize().unwrap(),
0, 0, 0, 0)
).unwrap();
}
Ctap1Op::Invalid => {
log::error!("got invalid opcode: {}, ignoring", msg.body.id());
}
}
}
}
});
XousEnv {
rng: XousRng256::new(&xns),
store,
@ -99,6 +423,8 @@ impl XousEnv {
modals: modals::Modals::new(&xns).unwrap(),
pddb: pddb::Pddb::new(),
main_cid: conn,
last_user_presence_request: None,
ctap1_cid,
}
}
/// Checks if the SoC is compatible with USB drivers (older versions of Precursor's FPGA don't have the USB device core)
@ -156,6 +482,68 @@ impl XousEnv {
}
Ok(())
}
/// The point of the attestation key is to delegate the question of the authenticity of your U2F
/// key effectively to a transaction that happens between the factory and the server. If the
/// attestation private key is an impenetrable secret and you can trust the factory, then the
/// attestation key effectively proves the U2F token was made by the factory to its specifications.
///
/// In the case of Precursor's threat model, you don't trust the factory, and you assume there is
/// basically no such thing as an impenetrable secret. So an attestation key is equivalent to any
/// private key created entirely within your own device; its use proves that you're you, or at
/// least, someone has possession of your device and your unlock password.
///
/// Thus, for Precursor, there is no delegation of the question of authenticity -- you
/// choose to verify the device to the level you're satisfied with. If you're happy to
/// just take it out of the box and use it without checking anything, that's your choice,
/// but you can also check everything as much as you like.
///
/// As a result, the "attestation key" serves no role for Precursor users, other than to
/// identify them as Precursor users. A unique per-device key would furthermore allow
/// a server to uniquely identify each Precursor user. Therefore, we commit the private key
/// into this public repository so any and all Precursor users may share it. The more
/// widely it is used, the harder it becomes to de-anonymize a Precursor users.
///
/// This key was generated using the script in `tools/gen_key_materials.sh`, and then printed
/// out by calling
/// `./configure.py --private-key=crypto_data/opensk.key --certificate=crypto_data/opensk_cert.pem`
pub fn attestation_check_init(&mut self) {
// check if the certs exist; if they don't, populate them.
// STORAGE_KEYS[0] is the private key; [1] is the public key
match self.store().find(crate::api::attestation_store::STORAGE_KEYS[0]) {
Ok(Some(_)) => {},
Ok(None) |
Err(_) => {
let pk = decode_hex("b8c3abd05cbe17b2faf87659c6f73e8467832112a0e609807cb68996c9a0c6a8").unwrap();
self.store().insert(
crate::api::attestation_store::STORAGE_KEYS[0],
&pk
).expect("pddb error initializing OpenSK");
}
}
match self.store().find(crate::api::attestation_store::STORAGE_KEYS[1]) {
Ok(Some(_)) => {}
Ok(None) |
Err(_) => {
let der = decode_hex(
"308201423081e9021449a3e2a4e1078eae2f1a18567f0a734b09db2478300a06\
082a8648ce3d040302301f311d301b06035504030c14507265637572736f7220\
55324620444959204341301e170d3232303630353138313233395a170d333230\
3630343138313233395a30293127302506035504030c1e507265637572736f72\
2053656c662d5665726966696564204465766963653059301306072a8648ce3d\
020106082a8648ce3d030107034200042d8fad76c25851ee70ae651ab2361bee\
1b5d93769aff99d95ad112871060f2f342fb79566fee9e1bade250a29cd65012\
55e731531755284bfcbe85ada1f39f44300a06082a8648ce3d04030203480030\
45022100d27e39187da5efaa376254329499bb705f7188dd8c78e0725c7ed28d\
e5d218e1022070853e1a43707298e07ebe9b9eb7cd5839b794db4c3d22209554\
1f0bdf82d1f4").unwrap();
self.store().insert(
crate::api::attestation_store::STORAGE_KEYS[1],
&der
).expect("pddb error initializing OpenSK");
}
}
}
}
impl UserPresence for XousEnv {
@ -231,152 +619,42 @@ impl UserPresence for XousEnv {
}
}
/// A ctap1-specific call to see if a request was recently made
fn recently_requested(&mut self) -> bool {
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() {
true
} else {
false
}
} else {
false
}
}
/// 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
/// We also give users the option to abort out of approving.
fn wait_ctap1(&mut self, reason: String, app_id: [u8; 32]) -> bool {
let app_id_str = hex::encode(app_id);
let mut first_time = false;
let mut info = {
// fetch the application info, if it exists
let app_id_str = hex::encode(app_id);
log::info!("querying U2F record {}", app_id_str);
// add code to query the PDDB here to look for the k/v mapping of this app ID
match self.pddb.get(
U2F_APP_DICT,
&app_id_str,
None, true, false,
Some(256), Some(basis_change)
) {
Ok(mut app_data) => {
let app_attr = app_data.attributes().unwrap();
if app_attr.len != 0 {
let mut descriptor = Vec::<u8>::new();
match app_data.read_to_end(&mut descriptor) {
Ok(_) => {
deserialize_app_info(descriptor)
}
Err(e) => {log::error!("Couldn't read app info: {:?}", e); None}
}
} else {
None
}
}
_ => {
log::info!("couldn't find key {}", app_id_str);
None
}
}
}.unwrap_or_else(
|| {
// otherwise, create it
match self.modals
.alert_builder(t!("vault.u2f.give_app_name", xous::LANG))
.field(None, None)
.build()
{
Ok(name) => {
first_time = true;
let info = AppInfo {
name: name.content()[0].content.to_string(),
notes: t!("vault.notes", xous::LANG).to_string(),
id: app_id,
ctime: crate::utc_now().timestamp() as u64,
atime: 0,
count: 0,
};
info
}
_ => {
log::error!("couldn't get name for app");
panic!("couldn't get name for app");
}
}
}
);
// request approval, if we didn't just create the record
if !first_time {
let mut request_str = String::from(&reason);
// we have some prior record of the app, human-format it
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.name", xous::LANG), info.name
));
request_str.push_str(&format!("\n{}",
crate::atime_to_str(info.atime)
));
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.authcount", xous::LANG),
info.count,
));
fn poll_approval_ctap1(&mut self, reason: String, app_id: [u8; 32]) -> bool {
// update the user presence request parameter
self.last_user_presence_request = Some(Instant::now());
self.modals.dynamic_notification(
Some(t!("vault.u2freq", xous::LANG)),
Some(&request_str),
).unwrap();
// block until the user hits a key
match modals::dynamic_notification_blocking_listener(self.modals.token(), self.modals.conn()) {
Ok(Some(c)) => {
if c as u32 == 0x11 { // this is the F1 key
return false;
} else {
// any other key shall accept
}
},
Ok(None) => {
log::trace!("kbhit exited or had no characters");
return false;
},
Err(e) => {
log::error!("error waiting for keyboard hit from blocking listener: {:?}", e);
return false;
},
}
}
// note the access
info.atime = crate::utc_now().timestamp() as u64;
info.count = info.count.saturating_add(1);
let ser = serialize_app_info(&info);
// update the access time, by deleting the key and writing it back into the PDDB
let basis = match self.pddb.get(
U2F_APP_DICT,
&app_id_str,
None, true, true,
Some(256), Some(basis_change)
) {
Ok(app_data) => {
let attr = app_data.attributes().expect("couldn't get attributes");
attr.basis
}
Err(e) => {
log::error!("error updating app atime: {:?}", e);
return false;
}
let request = Ctap1Request {
reason: xous_ipc::String::from_str(&reason),
app_id,
approved: false
};
self.pddb.delete_key(U2F_APP_DICT, &app_id_str, Some(&basis)).ok();
match self.pddb.get(
U2F_APP_DICT,
&app_id_str,
Some(&basis), true, true,
Some(256), Some(basis_change)
) {
Ok(mut app_data) => {
app_data.write(&ser).expect("couldn't update atime");
}
_ => log::error!("Error updating app atime"),
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");
let response = buf.to_original::<Ctap1Request, _>().expect("couldn't convert IPC structure");
if response.approved {
// 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
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");
true
} else {
false
}
self.pddb.sync().ok();
log::info!("sycing UI state...");
xous::send_message(
self.main_cid,
xous::Message::new_scalar(
crate::VaultOp::ReloadDbAndFullRedraw.to_usize().unwrap(),
0, 0, 0, 0)
).unwrap();
true
}
fn check_complete(&mut self) {

View file

@ -69,7 +69,7 @@ UI concept:
|-----------------|
F1-F4: switch between functions using F-keys. Functions are:
- FIDO2 (U2F authenicators)
- FIDO2 (U2F authenticators)
- TOTP (time based authenticators)
- Vault (passwords)
- Prefs (preferences)
@ -193,7 +193,7 @@ impl EndpointReplies {
fn main() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Debug);
log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
@ -207,6 +207,8 @@ fn main() -> ! {
let item_lists = Arc::new(Mutex::new(ItemLists::new()));
let action_active = Arc::new(AtomicBool::new(false));
let allow_host = Arc::new(AtomicBool::new(false));
// Protects access to the openSK PDDB entries from simultaneous readout on the UX while OpenSK is updating it
let opensk_mutex = Arc::new(Mutex::new(0));
// spawn the actions server. This is responsible for grooming the UX elements. It
// has to be in its own thread because it uses blocking modal calls that would cause
@ -218,7 +220,8 @@ fn main() -> ! {
actions_sid,
mode.clone(),
item_lists.clone(),
action_active.clone()
action_active.clone(),
opensk_mutex.clone(),
);
let actions_conn = xous::connect(actions_sid).unwrap();
@ -226,6 +229,7 @@ fn main() -> ! {
// spawn the FIDO2 USB handler
let _ = thread::spawn({
let allow_host = allow_host.clone();
let opensk_mutex = opensk_mutex.clone();
let conn = conn.clone();
move || {
let xns = xous_names::XousNames::new().unwrap();
@ -236,7 +240,11 @@ fn main() -> ! {
let pddb = pddb::Pddb::new();
pddb.is_mounted_blocking();
let env = XousEnv::new(conn);
let mut env = XousEnv::new(conn);
{
let mutex = opensk_mutex.lock().unwrap();
env.attestation_check_init(); // ensures that our attestation keys have been created
}
let mut replies = EndpointReplies::new();
// only run the main loop if the SoC is compatible
if env.is_soc_compatible() {
@ -246,55 +254,31 @@ fn main() -> ! {
///////////
// TODO: vendor command for gsora backup protocol has disappeared.
///////////
if let Some(mut packet) = replies.next_packet() {
// send and receive.
match ctap.env().main_hid_connection().send_and_maybe_recv(&mut packet.packet, SEND_TIMEOUT) {
Ok(SendOrRecvStatus::Timeout) => {
log::debug!("Sending packet timed out");
// TODO: reset the ctap_hid state.
// Since sending the packet timed out, we cancel this reply.
break;
}
Ok(SendOrRecvStatus::Sent) => {
log::debug!("Sent packet");
}
Ok(SendOrRecvStatus::Received) => {
log::debug!("Received another packet");
// Copy to incoming packet to local buffer to be consistent
// with the receive flow.
pkt_request = Some(packet.packet);
}
Err(_) => panic!("Error sending packet"),
}
} else {
// receive
let mut rx_buf = [0u8; 64];
pkt_request = match ctap.env().main_hid_connection().recv_with_timeout(&mut rx_buf, KEEPALIVE_DELAY)
{
SendOrRecvStatus::Received => {
log::debug!("Received packet");
Some(rx_buf)
}
SendOrRecvStatus::Sent => {
panic!("Returned transmit status on receive");
}
SendOrRecvStatus::Timeout => {
None
},
};
}
if let Some(pkt_request) = pkt_request.take() {
let reply = ctap.process_hid_packet(&pkt_request, Transport::MainHid, Instant::now());
if reply.has_data() {
// Update endpoint with the reply.
for ep in replies.replies.iter_mut() {
if ep.reply.has_data() {
log::warn!("Warning overwriting existing reply");
match ctap.env().main_hid_connection().u2f_wait_incoming() {
Ok(msg) => {
let mutex = opensk_mutex.lock().unwrap();
log::debug!("Received U2F packet");
let reply = ctap.process_hid_packet(&msg.packet, Transport::MainHid, Instant::now());
for pkt_reply in reply {
let mut reply = RawFidoMsg::default();
reply.packet.copy_from_slice(&pkt_reply);
let status = ctap.env().main_hid_connection().u2f_send(reply);
match status {
Ok(()) => {
log::debug!("Sent U2F packet");
}
Err(e) => {
log::error!("Error sending U2F packet: {:?}", e);
}
}
}
// mutex goes out of scope here, and is released
}
Err(e) => {
match e {
_ => {
log::warn!("FIDO listener got an error: {:?}", e);
}
ep.reply = reply;
break;
}
}
}