From 1024cebe55b65cf3a91a5739728832a2a55d31a1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 5 Jun 2022 01:49:11 +0800 Subject: [PATCH] add primitive UX layer to U2F application. fix numerous bugs The OpenSK UX layer was completely gutted and re-written using Xous-native idioms. There's a bit of ambiguity on what exactly OpenSK meant to do with the one button and the LEDs, but for Xous we want to show things like what you're signing for and why. For now, we just show the app hash during registration and signing, but down the road that will need to be matched up against a plaintext description of the application upon registration, so users can have a client-side description of what they are approving. At the moment, we're stuck at provisioning the attestation certificate and key. The transaction goes through, but is rejected by the test web site right now with not too much explanation of what went wrong, but maybe the next step is to try and use the OpenSK native tools to provision a set of keys onto the device to see if that fixes it (instead of the current bodge of hard-coding some manually extracted hex values into the database). --- Cargo.lock | 2 + apps/vault/Cargo.toml | 2 + apps/vault/locales/i18n.json | 28 +- apps/vault/src/ctap/apdu.rs | 2 +- apps/vault/src/ctap/ctap1.rs | 14 +- apps/vault/src/ctap/hid/mod.rs | 7 +- apps/vault/src/ctap/hid/receive.rs | 2 +- apps/vault/src/ctap/storage.rs | 118 +++++++- apps/vault/src/ctap/timed_permission.rs | 48 +--- apps/vault/src/main.rs | 28 +- apps/vault/src/repl.rs | 1 - apps/vault/src/shims.rs | 1 + apps/vault/src/ux.rs | 353 ++++++++++++++++++++++++ apps/vault/tools/configure.py | 196 +++++++++++++ apps/vault/tools/gen_key_materials.sh | 97 +++++++ 15 files changed, 851 insertions(+), 48 deletions(-) create mode 100644 apps/vault/src/ux.rs create mode 100755 apps/vault/tools/configure.py create mode 100755 apps/vault/tools/gen_key_materials.sh diff --git a/Cargo.lock b/Cargo.lock index 4d43c65cd..34126a0e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3773,10 +3773,12 @@ dependencies = [ "locales", "log", "log-server", + "modals", "num-derive", "num-traits", "pddb", "rand_core 0.6.3", + "rkyv", "subtle", "ticktimer-server", "tts-frontend", diff --git a/apps/vault/Cargo.toml b/apps/vault/Cargo.toml index 5abde61b5..1dc33fc39 100644 --- a/apps/vault/Cargo.toml +++ b/apps/vault/Cargo.toml @@ -9,6 +9,7 @@ num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} xous = { path = "../../xous-rs" } xous-ipc = { path = "../../xous-ipc" } +rkyv = {version = "0.4.3", features = ["const_generics"], default-features = false} log-server = { path = "../../services/log-server" } xous-names = { path = "../../services/xous-names" } gam = {path = "../../services/gam" } @@ -18,6 +19,7 @@ tts-frontend = {path="../../services/tts"} usb-device-xous = {path="../../services/usb-device-xous"} usbd-human-interface-device = {git="https://github.com/betrusted-io/usbd-human-interface-device.git", branch="main"} pddb = {path = "../../services/pddb" } +modals = {path = "../../services/modals" } ime-plugin-api = {path = "../../services/ime-plugin-api"} ime-plugin-shell = {path = "../../services/ime-plugin-shell"} diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index 19f8bf49e..d198aa4ff 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -1,8 +1,26 @@ { - "helloworld.hello": { - "en": "Hello World!", - "ja": "Hello World!", - "zh": "大家好!", - "en-tts": "Hello World!" + "vault.u2f.authenticate": { + "en": "U2F Authentication Request", + "ja": "U2F 認証リクエスト", + "zh": "U2F 认证请求", + "en-tts": "U2F Authentication Request" + }, + "vault.u2f.apphash": { + "en": "Application hash: ", + "ja": "アプリハッシュ: ", + "zh": "应用哈希: ", + "en-tts": "Application hash: " + }, + "vault.u2f.register": { + "en": "U2F Registration Request", + "ja": "U2F登録リクエスト", + "zh": "U2F 注册请求", + "en-tts": "U2F Registration Request" + }, + "vault.u2freq": { + "en": "FIDO Request", + "ja": "FIDOリクエスト", + "zh": "FIDO 请求", + "en-tts": "FIDO Request" } } \ No newline at end of file diff --git a/apps/vault/src/ctap/apdu.rs b/apps/vault/src/ctap/apdu.rs index bc4889921..55cf2a858 100644 --- a/apps/vault/src/ctap/apdu.rs +++ b/apps/vault/src/ctap/apdu.rs @@ -21,7 +21,7 @@ const APDU_HEADER_LEN: usize = 4; #[cfg_attr(test, derive(Clone, Debug))] #[allow(non_camel_case_types, dead_code)] -#[derive(PartialEq)] +#[derive(PartialEq, Debug)] pub enum ApduStatusCode { SW_SUCCESS = 0x90_00, /// Command successfully executed; 'XX' bytes of data are diff --git a/apps/vault/src/ctap/ctap1.rs b/apps/vault/src/ctap/ctap1.rs index 96bf736ea..2e989ed86 100644 --- a/apps/vault/src/ctap/ctap1.rs +++ b/apps/vault/src/ctap/ctap1.rs @@ -22,6 +22,7 @@ use core::convert::Into; use core::convert::TryFrom; use ctap_crypto::rng256::Rng256; use crate::shims::ClockValue; +use locales::t; // For now, they're the same thing with apdu.rs containing the authoritative definition pub type Ctap1StatusCode = ApduStatusCode; @@ -197,10 +198,13 @@ impl Ctap1Command { application, } => { log::debug!("REGISTER"); - if !ctap_state.u2f_up_state.consume_up(clock_value) { - log::debug!("consume_up did not work"); + let mut regstr = String::from(t!("vault.u2f.register", xous::LANG)); + regstr.push_str(&format!("\n{}\n{:x?}", t!("vault.u2f.apphash", xous::LANG), application)); + if !ctap_state.u2f_up_state.consume_up(clock_value, regstr) { + log::debug!("still waiting..."); return Err(Ctap1StatusCode::SW_COND_USE_NOT_SATISFIED); } + log::debug!("GOT IT!..."); Ctap1Command::process_register(challenge, application, ctap_state) } @@ -211,9 +215,11 @@ impl Ctap1Command { flags, } => { log::debug!("AUTHENTICATE"); + let mut authstr = String::from(t!("vault.u2f.authenticate", xous::LANG)); + authstr.push_str(&format!("\n{}\n{:x?}", t!("vault.u2f.apphash", xous::LANG), application)); // The order is important due to side effects of checking user presence. if flags == Ctap1Flags::EnforceUpAndSign - && !ctap_state.u2f_up_state.consume_up(clock_value) + && !ctap_state.u2f_up_state.consume_up(clock_value, authstr) { return Err(Ctap1StatusCode::SW_COND_USE_NOT_SATISFIED); } @@ -266,6 +272,7 @@ impl Ctap1Command { .encrypt_key_handle(sk, &application) .map_err(|_| Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?; if key_handle.len() > 0xFF { + log::info!("key_handle.len() invalid"); // This is just being defensive with unreachable code. return Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION); } @@ -301,6 +308,7 @@ impl Ctap1Command { let signature = attestation_key.sign_rfc6979::(&signature_data); response.extend(signature.to_asn1_der()); + log::info!("process_register response: {:x?}", &response[..32]); Ok(response) } diff --git a/apps/vault/src/ctap/hid/mod.rs b/apps/vault/src/ctap/hid/mod.rs index 39ae4f164..8da1af4bb 100644 --- a/apps/vault/src/ctap/hid/mod.rs +++ b/apps/vault/src/ctap/hid/mod.rs @@ -157,6 +157,7 @@ impl CtapHid { CheckUserPresence: Fn(ChannelID) -> Result<(), Ctap2StatusCode>, { // TODO: Send COMMAND_KEEPALIVE every 100ms? + log::info!("now: {}", clock_value.ms()); match self .assembler .parse_packet(packet, Timestamp::::from_clock_value(clock_value)) @@ -188,8 +189,12 @@ impl CtapHid { ctap_state, clock_value, ) { - Ok(payload) => CtapHid::ctap1_success_message(cid, &payload), + Ok(payload) => { + log::info!("command success: {:x?}", payload); + CtapHid::ctap1_success_message(cid, &payload) + }, Err(ctap1_status_code) => { + log::info!("command failure: {:?}", ctap1_status_code); CtapHid::ctap1_error_message(cid, ctap1_status_code) } } diff --git a/apps/vault/src/ctap/hid/receive.rs b/apps/vault/src/ctap/hid/receive.rs index a0081b090..4bf4340e7 100644 --- a/apps/vault/src/ctap/hid/receive.rs +++ b/apps/vault/src/ctap/hid/receive.rs @@ -89,7 +89,7 @@ impl MessageAssembler { // TODO: Support non-full-speed devices (i.e. packet len != 64)? This isn't recommended by // section 8.8.1 let (cid, processed_packet) = CtapHid::process_single_packet(&packet); - log::debug!("parsed cid: {:x?}", cid); + log::trace!("parsed cid: {:x?}", cid); if !self.idle && timestamp - self.last_timestamp >= CtapHid::TIMEOUT_DURATION { log::debug!("parse timeout"); diff --git a/apps/vault/src/ctap/storage.rs b/apps/vault/src/ctap/storage.rs index 6ad57fa31..9a4b2f105 100644 --- a/apps/vault/src/ctap/storage.rs +++ b/apps/vault/src/ctap/storage.rs @@ -63,6 +63,7 @@ const CRED_INITAL_SIZE: usize = 512; // We have: I = (P * 4084 - 5107 - K * S) / 8 * C // // With P=20 and K=150, we have I=2M which is enough for 500 increments per day for 10 years. +#[allow(dead_code)] // openSK legacy const NUM_PAGES: usize = 20; #[allow(dead_code)] // OpenSK legacy const MAX_SUPPORTED_RESIDENTIAL_KEYS: usize = 150; @@ -96,6 +97,15 @@ pub struct PersistentStore { pddb: RefCell::, } +use std::num::ParseIntError; + +pub fn decode_hex(s: &str) -> Result, ParseIntError> { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16)) + .collect() +} + impl PersistentStore { /// Gives access to the persistent store. /// @@ -182,8 +192,110 @@ impl PersistentStore { } _ => return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), } +/* + match self.pddb.borrow().get( + FIDO_PERSISTENT_DICT, + key::ATTESTATION_PRIVATE_KEY, + None, true, true, + Some(32), None:: + ) { + Ok(mut aapriv) => { + let aapriv_attr = aapriv.attributes().unwrap(); + if aapriv_attr.len != 32 { + if aapriv_attr.len != 0 { + log::error!("AAPRIV has an illegal length. Suspect PDDB corruption?"); + return Err(Ctap2StatusCode::CTAP2_ERR_INVALID_CREDENTIAL); + } + let pk = decode_hex("497b200642e71e4ed929359a19aa701b42f3a304bd7e79c4a25b5af2635b2db1").unwrap(); + log::info!("writing PK of length {}", pk.len()); + log::info!("pk: {:x?}", pk); + assert!(pk.len() == 32, "PK len is wrong"); + aapriv.write(&pk) + .or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; + } + } + _ => return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), + } + + match self.pddb.borrow().get( + FIDO_PERSISTENT_DICT, + key::ATTESTATION_CERTIFICATE, + None, true, true, + Some(512), None:: + ) { + Ok(mut cert) => { + let cert_attr = cert.attributes().unwrap(); + if cert_attr.len == 0 { + let der = decode_hex("308201283081cf021427bf2c7cc29ae91ffb3d4bb99f25fcda6fb407be300a06082a8648ce3d04030230173115301306035504030c0c507265637572736f72204341301e170d3232303630343136313231335a170d3432303630343136313231335a30173115301306035504030c0c507265637572736f722043413059301306072a8648ce3d020106082a8648ce3d03010703420004a4439a22be033f90e8a160ddd5b3552635f3d951d26724a3e453c8438fb2f9cc32c78e413323c438d276a2e3b081be118f516c4e7cb64455c46b5a4bbca85d04300a06082a8648ce3d0403020348003045022008e4e46b48d462a380be08841a9d9da946aef3948e7e7bd8da51dafeea4d563f022100bd3ef23d840dc653fa821f2e0ae940b91f495b692fb7e94588e6fd3ed7d0a3ae").unwrap(); + log::info!("writing cert of length {}", der.len()); + log::info!("der: {:x?}", der); + cert.write(&der) + .or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; + } + } + _ => return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR), + } +*/ Ok(()) } + /* + openssl x509 -in cert.der -inform der -noout -text +Certificate: + Data: + Version: 1 (0x0) + Serial Number: + 27:bf:2c:7c:c2:9a:e9:1f:fb:3d:4b:b9:9f:25:fc:da:6f:b4:07:be + Signature Algorithm: ecdsa-with-SHA256 + Issuer: CN = Precursor CA + Validity + Not Before: Jun 4 16:12:13 2022 GMT + Not After : Jun 4 16:12:13 2042 GMT + Subject: CN = Precursor CA + Subject Public Key Info: + Public Key Algorithm: id-ecPublicKey + Public-Key: (256 bit) + pub: + 04:a4:43:9a:22:be:03:3f:90:e8:a1:60:dd:d5:b3: + 55:26:35:f3:d9:51:d2:67:24:a3:e4:53:c8:43:8f: + b2:f9:cc:32:c7:8e:41:33:23:c4:38:d2:76:a2:e3: + b0:81:be:11:8f:51:6c:4e:7c:b6:44:55:c4:6b:5a: + 4b:bc:a8:5d:04 + ASN1 OID: prime256v1 + NIST CURVE: P-256 + Signature Algorithm: ecdsa-with-SHA256 + 30:45:02:20:08:e4:e4:6b:48:d4:62:a3:80:be:08:84:1a:9d: + 9d:a9:46:ae:f3:94:8e:7e:7b:d8:da:51:da:fe:ea:4d:56:3f: + 02:21:00:bd:3e:f2:3d:84:0d:c6:53:fa:82:1f:2e:0a:e9:40: + b9:1f:49:5b:69:2f:b7:e9:45:88:e6:fd:3e:d7:d0:a3:ae + +openssl asn1parse -in cert.der -inform der + 0:d=0 hl=4 l= 296 cons: SEQUENCE + 4:d=1 hl=3 l= 207 cons: SEQUENCE + 7:d=2 hl=2 l= 20 prim: INTEGER :27BF2C7CC29AE91FFB3D4BB99F25FCDA6FB407BE + 29:d=2 hl=2 l= 10 cons: SEQUENCE + 31:d=3 hl=2 l= 8 prim: OBJECT :ecdsa-with-SHA256 + 41:d=2 hl=2 l= 23 cons: SEQUENCE + 43:d=3 hl=2 l= 21 cons: SET + 45:d=4 hl=2 l= 19 cons: SEQUENCE + 47:d=5 hl=2 l= 3 prim: OBJECT :commonName + 52:d=5 hl=2 l= 12 prim: UTF8STRING :Precursor CA + 66:d=2 hl=2 l= 30 cons: SEQUENCE + 68:d=3 hl=2 l= 13 prim: UTCTIME :220604161213Z + 83:d=3 hl=2 l= 13 prim: UTCTIME :420604161213Z + 98:d=2 hl=2 l= 23 cons: SEQUENCE + 100:d=3 hl=2 l= 21 cons: SET + 102:d=4 hl=2 l= 19 cons: SEQUENCE + 104:d=5 hl=2 l= 3 prim: OBJECT :commonName + 109:d=5 hl=2 l= 12 prim: UTF8STRING :Precursor CA + 123:d=2 hl=2 l= 89 cons: SEQUENCE + 125:d=3 hl=2 l= 19 cons: SEQUENCE + 127:d=4 hl=2 l= 7 prim: OBJECT :id-ecPublicKey + 136:d=4 hl=2 l= 8 prim: OBJECT :prime256v1 + 146:d=3 hl=2 l= 66 prim: BIT STRING + 214:d=1 hl=2 l= 10 cons: SEQUENCE + 216:d=2 hl=2 l= 8 prim: OBJECT :ecdsa-with-SHA256 + 226:d=1 hl=2 l= 72 prim: BIT STRING + */ /// The credential ID, as stored in OpenSK, is a 112-entry Vec that starts with /// a random 128-bit AES IV. This effectively takes the 128-bit AES IV and turns it into @@ -681,7 +793,11 @@ impl PersistentStore { None, None:: ).ok() { let mut data = Vec::::new(); - acert.read_to_end(&mut data).or(Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR))?; + match acert.read_to_end(&mut data) { + Ok(l) => log::info!("read {} bytes", l), + Err(e) => log::error!("error reading certificate: {:?}", e), + } + log::info!("read back cert: {:x?}", data); Ok(Some(data)) } else { Ok(None) diff --git a/apps/vault/src/ctap/timed_permission.rs b/apps/vault/src/ctap/timed_permission.rs index 048f7d429..ae59654db 100644 --- a/apps/vault/src/ctap/timed_permission.rs +++ b/apps/vault/src/ctap/timed_permission.rs @@ -32,6 +32,7 @@ impl TimedPermission { // Checks if the timeout is not reached, false for differing ClockValue frequencies. pub fn is_granted(&self, now: ClockValue) -> bool { if let TimedPermission::Granted(timeout) = self { + log::info!("is_granted timeout: {}, now {}", timeout.ms(), now.ms()); if let Some(remaining_duration) = timeout.wrapping_sub(now) { return remaining_duration > Duration::from_ms(0); } @@ -43,6 +44,7 @@ impl TimedPermission { // Returns a new state for differing ClockValue frequencies. pub fn check_expiration(self, now: ClockValue) -> TimedPermission { if let TimedPermission::Granted(timeout) = self { + log::info!("check_expiration timeout: {}, now {}", timeout.ms(), now.ms()); if let Some(remaining_duration) = timeout.wrapping_sub(now) { if remaining_duration > Duration::from_ms(0) { return TimedPermission::Granted(timeout); @@ -56,14 +58,6 @@ impl TimedPermission { #[cfg(feature = "with_ctap1")] #[derive(Debug)] pub struct U2fUserPresenceState { - // If user presence was recently requested, its timeout is saved here. - needs_up: TimedPermission, - // Button touch timeouts, while user presence is requested, are saved here. - has_up: TimedPermission, - // This is the timeout duration of user presence requests. - request_duration: Duration, - // This is the timeout duration of button touches. - presence_duration: Duration, } #[cfg(feature = "with_ctap1")] @@ -72,45 +66,31 @@ impl U2fUserPresenceState { request_duration: Duration, presence_duration: Duration, ) -> U2fUserPresenceState { + crate::ux::set_durations(request_duration.ms(), presence_duration.ms()); U2fUserPresenceState { - needs_up: TimedPermission::Waiting, - has_up: TimedPermission::Waiting, - request_duration, - presence_duration, } } // Granting user presence is ignored if it needs activation, but waits. Also cleans up. - pub fn grant_up(&mut self, now: ClockValue) { - self.check_expiration(now); - if self.needs_up.is_granted(now) { - self.needs_up = TimedPermission::Waiting; - self.has_up = TimedPermission::granted(now, self.presence_duration); - } + pub fn grant_up(&mut self, _now: ClockValue) { + // this is a NOP because it's handled by another thread } // This marks user presence as needed or uses it up if already granted. Also cleans up. - pub fn consume_up(&mut self, now: ClockValue) -> bool { - self.check_expiration(now); - if self.has_up.is_granted(now) { - self.has_up = TimedPermission::Waiting; - true - } else { - self.needs_up = TimedPermission::granted(now, self.request_duration); - false - } + pub fn consume_up(&mut self, _now: ClockValue, reason: String) -> bool { + crate::ux::request_permission_polling(String::from(reason)) } // Returns if user presence was requested. Also cleans up. - pub fn is_up_needed(&mut self, now: ClockValue) -> bool { - self.check_expiration(now); - self.needs_up.is_granted(now) + pub fn is_up_needed(&mut self, _now: ClockValue) -> bool { + // this is not used by Xous + false } // If you don't regularly call any other function, not cleaning up leads to overflow problems. - pub fn check_expiration(&mut self, now: ClockValue) { - self.needs_up = self.needs_up.check_expiration(now); - self.has_up = self.has_up.check_expiration(now); + #[allow(dead_code)] + pub fn check_expiration(&mut self, _now: ClockValue) { + // not needed by Xous because we use an i64 for time } } @@ -120,7 +100,7 @@ mod test { use super::*; use core::isize; - const CLOCK_FREQUENCY_HZ: usize = 32768; + const CLOCK_FREQUENCY_HZ: usize = 1000; const ZERO: ClockValue = ClockValue::new(0, CLOCK_FREQUENCY_HZ); const BIG_POSITIVE: ClockValue = ClockValue::new(isize::MAX / 1000 - 1, CLOCK_FREQUENCY_HZ); const NEGATIVE: ClockValue = ClockValue::new(-1, CLOCK_FREQUENCY_HZ); diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index a6bfd0ad0..adca815c9 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -1,6 +1,7 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] +mod ux; mod repl; use repl::*; use num_traits::*; @@ -76,6 +77,7 @@ fn main() -> ! { // let's try keeping this completely private as a server. can we do that? let sid = xous::create_server().unwrap(); + ux::start_ux_thread(); let _ = thread::spawn({ move || { @@ -89,6 +91,15 @@ fn main() -> ! { let mut ctap_state = CtapState::new(&mut rng, check_user_presence, boot_time); let mut ctap_hid = CtapHid::new(); loop { + let now = ClockValue::new(tt.elapsed_ms() as i64, 1000); + if /*button_touched.get()*/ false { + ctap_state.u2f_up_state.grant_up(now); + } + // These calls are making sure that even for long inactivity, wrapping clock values + // never randomly wink or grant user presence for U2F. + ctap_state.update_command_permission(now); + ctap_hid.wink_permission = ctap_hid.wink_permission.check_expiration(now); + match usb.u2f_wait_incoming() { Ok(msg) => { log::trace!("FIDO listener got message: {:?}", msg); @@ -113,6 +124,21 @@ fn main() -> ! { log::warn!("FIDO listener got an error: {:?}", e); } } + let now = ClockValue::new(tt.elapsed_ms() as i64, 1000); + if ctap_hid.wink_permission.is_granted(now) { + log::info!("wink"); + // wink_leds(led_counter); + } else { + if ctap_state.u2f_up_state.is_up_needed(now) { + // Flash the LEDs with an almost regular pattern. The inaccuracy comes from + // delay caused by processing and sending of packets. + log::info!("leds blink"); + //blink_leds(led_counter); + } else { + log::info!("leds off"); + //switch_off_leds(); + } + } } } }); @@ -175,7 +201,7 @@ fn main() -> ! { xous::terminate_process(0) } -fn check_user_presence(cid: ChannelID) -> Result<(), Ctap2StatusCode> { +fn check_user_presence(_cid: ChannelID) -> Result<(), Ctap2StatusCode> { log::warn!("check user presence called, but not implemented!"); Ok(()) } diff --git a/apps/vault/src/repl.rs b/apps/vault/src/repl.rs index b297656c8..3f5048548 100644 --- a/apps/vault/src/repl.rs +++ b/apps/vault/src/repl.rs @@ -4,7 +4,6 @@ use graphics_server::{Gid, Point, Rectangle, TextBounds, TextView, DrawStyle, Pi use graphics_server::api::GlyphStyle; use xous::MessageEnvelope; use core::fmt::Write; -use locales::t; #[allow(dead_code)] pub(crate) struct Repl { diff --git a/apps/vault/src/shims.rs b/apps/vault/src/shims.rs index ddb94efc0..0c6b4a87b 100644 --- a/apps/vault/src/shims.rs +++ b/apps/vault/src/shims.rs @@ -1,3 +1,4 @@ +#![allow(dead_code)] // a fair bit of dead code here because we have adapters from Tock functions we don't use // shims for Tock calls, to avoid having to recode some fairly pervasive patterns in OpenSK use std::ops::{Sub, Add, AddAssign}; diff --git a/apps/vault/src/ux.rs b/apps/vault/src/ux.rs new file mode 100644 index 000000000..ed336d07c --- /dev/null +++ b/apps/vault/src/ux.rs @@ -0,0 +1,353 @@ +use std::thread; +use std::sync::{Arc, atomic::AtomicU32, atomic::Ordering}; +use num_traits::*; +use xous::{msg_scalar_unpack, send_message, Message, msg_blocking_scalar_unpack}; +use xous_ipc::Buffer; +use locales::t; +use crate::ctap::hid::{CtapHid, KeepaliveStatus}; +use usbd_human_interface_device::device::fido::FidoMsg; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub(crate) struct FidoRequest { + pub channel_id: [u8; 4], + pub desc: xous_ipc::String::<1024>, + pub deferred: bool, + pub granted: bool, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum UxOp { + // sets the timeouts, and also resets and pending expirations or granted state + SetTimers, + RequestPermission, + Pump, + Quit +} +struct Timeouts { + /// how long after an interaction has happened that the interaction may still be deemed valid and "consumed" + pub presence_timeout_ms: i64, + /// how long the prompt should stay up before it is considered to be timed out + pub prompt_timeout_ms: i64, +} +#[derive(Eq, PartialEq, Debug)] +enum UxState { + Idle, + Prompt(i64), + Present(i64), +} + +static SELF_CID: AtomicU32 = AtomicU32::new(0); +/* +/// This must be proceeded by a call to request permission, to set up the scenario +pub(crate) fn poll_consume_permission() -> bool { + if SELF_CID.load(Ordering::SeqCstg) == 0 { + log::error!("internal error: ux thread not started"); + return false; + } + match send_message(SELF_CID.load(Ordering::SeqCst), + Message::new_blocking_scalar(UxOp::ConsumePermission.to_usize.unwrap(), 0, 0, 0, 0) + ).expect("couldn't query ux thread") { + xous::Result::Scalar1(r) => { + if r == 1 { + true + } else { + false + } + } + _ => log::error!("Internal error: wrong return type"), + } +}*/ +pub(crate) fn set_durations(prompt: i64, presence: i64) { + if SELF_CID.load(Ordering::SeqCst) == 0 { + log::error!("internal error: ux thread not started"); + return; + } + // i mean, these really should never be bigger than this but... + assert!(presence <= usize::MAX as i64); + assert!(prompt <= usize::MAX as i64); + send_message(SELF_CID.load(Ordering::SeqCst), + Message::new_scalar(UxOp::SetTimers.to_usize().unwrap(), + presence as usize, + prompt as usize, + 0, + 0, + ) + ).expect("couldn't set timers"); +} +pub(crate) fn request_permission_blocking(reason: String, channel_id: [u8; 4]) -> bool { + log::info!("requesting permission (blocking"); + request_permission_inner(reason, channel_id, true) +} +pub(crate) fn request_permission_polling(reason: String) -> bool { + log::info!("requesting permission (polling)"); + request_permission_inner(reason, [0xff, 0xff, 0xff, 0xff], false) +} +fn request_permission_inner(reason: String, channel_id: [u8; 4], blocking: bool) -> bool { + if SELF_CID.load(Ordering::SeqCst) == 0 { + log::error!("internal error: ux thread not started"); + return false; + } + let fido_req = FidoRequest { + channel_id, + desc: xous_ipc::String::from_str(&reason), + deferred: blocking, + granted: false + }; + let mut buf = Buffer::into_buf(fido_req).expect("couldn't do IPC transformation"); + buf.lend_mut( + SELF_CID.load(Ordering::SeqCst), + UxOp::RequestPermission.to_u32().unwrap() + ).expect("couldn't request permission"); + let ret = buf.to_original::().expect("couldn't do IPC transformation"); + ret.granted +} + +const DEFAULT_PRESENCE_TIMEOUT_MS: i64 = 30_000; +const DEFAULT_PROMPT_TIMEOUT_MS: i64 = 10_000; +const POLLED_PROMPT_TIMEOUT_MS: i64 = 1000; // how long the screen stays up after the host "gives up" polling +const KEEPALIVE_MS: usize = 100; +pub(crate) fn start_ux_thread() { + let sid = xous::create_server().unwrap(); + let cid = xous::connect(sid).expect("couldn't connect to UX thread server"); + SELF_CID.store(cid, Ordering::SeqCst); + log::trace!("sid: {:?}, self CID: {}/{}", sid, cid, SELF_CID.load(Ordering::SeqCst)); + let _ = thread::spawn({ + let sid = sid.clone(); + let self_cid = cid.clone(); + move || { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let mut timeouts = Timeouts { + presence_timeout_ms: DEFAULT_PRESENCE_TIMEOUT_MS, + prompt_timeout_ms: DEFAULT_PROMPT_TIMEOUT_MS, + }; + let mut ux_state = UxState::Idle; + let mut request_str_base = String::new(); + let xns = xous_names::XousNames::new().unwrap(); + let modals = modals::Modals::new(&xns).unwrap(); + let kbhit = Arc::new(AtomicU32::new(0)); + let mut channel_id: [u8; 4] = [0xff, 0xff, 0xff, 0xff]; // this is the broadcast channel + let usb = usb_device_xous::UsbHid::new(); + let mut deferred_req: Option:: = None; + let mut last_timer = 0; + loop { + let mut msg = xous::receive_message(sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(UxOp::SetTimers) => msg_scalar_unpack!(msg, presence, prompt, _, _, { + timeouts = Timeouts { + presence_timeout_ms: presence as i64, + prompt_timeout_ms: prompt as i64, + }; + ux_state = UxState::Idle; + // in case this is called while a deferred response is pending...deny the request + if let Some(mut msg) = deferred_req.take() { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = false; + buffer.replace(fido_request).unwrap(); + } + }), + /* + // this is a polled request, used by legacy u2f transactions + Some(UxOp::ConsumePermission) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + match ux_state { + UxState::Idle | UxState::Prompt(_) => { + // 0 = not present + xous::return_scalar(msg.sender, 0).unwrap(); + }, + UxState::Present(_) => { + // 1 = present + xous::return_scalar(msg.sender, 1).unwrap(); + ux_state = UxState::Idle; + // these two paths shouldn't be mixed-and-matched, but let's just enforce that. + assert!(deferred_req.is_none(), "polled request succeeded when a blocking request was also in progress"); + } + } + }), */ + // this can set up either a blocking request (deferred = true), or a polled request (deferred = false) + // u2f polls; fido2 seems to require blocking requests. This difference causes a lot of complications. + Some(UxOp::RequestPermission) => { + let deferred = { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let fido_request = buffer.to_original::().unwrap(); + channel_id = fido_request.channel_id; + request_str_base.clear(); + request_str_base.push_str(fido_request.desc.as_str().unwrap_or("UTF8 Error")); + fido_request.deferred + }; + if deferred { + match ux_state { + UxState::Idle => {}, // do the rest of the code + // I'm interpreting the OpenSK implementation to mean that once you have indicate your presence, + // you don't have to indicate it *again* for some duration interval, to avoid annoying the user. + // If it's the case that this is not true, then what should happen is when the original deferred request + // returns, the UxState immediately goes to Idle. This will trigger another pop-up the next time + // the call is made. + UxState::Present(_) => { + // short circuit all the logic, and grant the presence + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = true; + buffer.replace(fido_request).unwrap(); + continue; + } + UxState::Prompt(_) => { + panic!("Illegal state -- the caller should have blocked on the Prompt state, making it impossible to double-initiate"); + } + } + } else { + match ux_state { + UxState::Idle => log::info!("-->U2F SETUP<--"), + UxState::Present(_) => { + log::info!("-->U2F USER PRESENT<--"); + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = true; + buffer.replace(fido_request).unwrap(); + ux_state = UxState::Idle; // in the case of U2F, there is no persistence to the presence, it goes away immediately + continue; + } + UxState::Prompt(_) => { + log::info!("-->U2F WAITING<--"); + let prompt_expiration_ms = (tt.elapsed_ms() as i64) + POLLED_PROMPT_TIMEOUT_MS; + ux_state = UxState::Prompt(prompt_expiration_ms); // extend the prompt time out + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = false; + buffer.replace(fido_request).unwrap(); + // in case of U2F, just inform that no permission is granted yet and abort + continue; + } + } + } + let prompt_expiration_ms = (tt.elapsed_ms() as i64) + + if deferred { + timeouts.prompt_timeout_ms + } else { + POLLED_PROMPT_TIMEOUT_MS + }; + ux_state = UxState::Prompt(prompt_expiration_ms); + let mut request_str = String::from(&request_str_base); + if deferred { + last_timer = 1 + (prompt_expiration_ms - tt.elapsed_ms() as i64) / 1000; + request_str.push_str( + &format!("{}\n{}s remaining", + &request_str_base, + last_timer) + ); + } + modals.dynamic_notification( + Some(t!("vault.u2freq", xous::LANG)), + Some(&request_str), + ).unwrap(); + kbhit.store(0, Ordering::SeqCst); + let _ = 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::info!("kbhit got {}", c); + kbhit.store(c as u32, Ordering::SeqCst) + }, + Ok(None) => { + log::info!("kbhit exited or had no characters"); + kbhit.store(0, Ordering::SeqCst) + }, + Err(e) => log::error!("error waiting for keyboard hit from blocking listener: {:?}", e), + } + } + }); + send_message(self_cid, + Message::new_scalar(UxOp::Pump.to_usize().unwrap(), KEEPALIVE_MS, 0, 0, 0) + ).unwrap(); + if deferred { + deferred_req = Some(msg); + } else { // in the case of a polled implementation, just return false for granted and move on + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = false; + buffer.replace(fido_request).unwrap(); + } + } + Some(UxOp::Pump) => msg_scalar_unpack!(msg, interval, _, _, _, { + match ux_state { + UxState::Idle => { + // don't issue another pump message, causing the loop to end + }, + UxState::Present(present_expiration_ms) => { + if let Some(mut msg) = deferred_req.take() { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut fido_request = buffer.to_original::().unwrap(); + fido_request.granted = true; + buffer.replace(fido_request).unwrap(); + } + // check if we timed out + if tt.elapsed_ms() as i64 >= present_expiration_ms { + ux_state = UxState::Idle; + } else { // else pump the loop again + send_message(self_cid, + Message::new_scalar(UxOp::Pump.to_usize().unwrap(), KEEPALIVE_MS, 0, 0, 0) + ).unwrap(); + } + }, + UxState::Prompt(prompt_expiration_ms) => { + if deferred_req.is_some() { // keepalives are only needed for deferred requests + let keepalive_msg = CtapHid::keepalive(channel_id, KeepaliveStatus::UpNeeded); + for pkt in keepalive_msg { + let mut ka = FidoMsg::default(); + ka.packet.copy_from_slice(&pkt); + let status = usb.u2f_send(ka); + match status { + Ok(()) => (), + Err(e) => log::error!("Error sending keepalive: {:?}", e), + } + } + let new_timer = 1 + (prompt_expiration_ms - tt.elapsed_ms() as i64) / 1000; + if last_timer != new_timer { + let mut request_str = String::from(&request_str_base); + request_str.push_str( + &format!("{}\n{}s remaining", + &request_str_base, + new_timer) + ); + modals.dynamic_notification_update( + None, + Some(&request_str), + ).unwrap(); + last_timer = new_timer; + } + } + // check if we got a hit + if kbhit.load(Ordering::SeqCst) != 0 { + ux_state = UxState::Present(tt.elapsed_ms() as i64 + timeouts.presence_timeout_ms); + send_message(self_cid, + Message::new_scalar(UxOp::Pump.to_usize().unwrap(), KEEPALIVE_MS, 0, 0, 0) + ).unwrap(); + } else { + tt.sleep_ms(interval).unwrap(); + // check if we timed out + if tt.elapsed_ms() as i64 >= prompt_expiration_ms { + ux_state = UxState::Idle; + modals.dynamic_notification_close().unwrap(); + } else { // else pump the loop again + send_message(self_cid, + Message::new_scalar(UxOp::Pump.to_usize().unwrap(), KEEPALIVE_MS, 0, 0, 0) + ).unwrap(); + } + } + } + } + }), + Some(UxOp::Quit) => { + break; + } + None => { + log::error!("got unknown message: {:?}", msg); + } + } + } + } + }); +} \ No newline at end of file diff --git a/apps/vault/tools/configure.py b/apps/vault/tools/configure.py new file mode 100755 index 000000000..16485aa5b --- /dev/null +++ b/apps/vault/tools/configure.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Lint as: python3 + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import argparse +import getpass +import datetime +import sys +import uuid + +import colorama +from tqdm.auto import tqdm + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from fido2 import ctap +from fido2 import ctap2 +from fido2 import hid + +OPENSK_VID_PID = (0x1209, 0x0001) +OPENSK_VENDOR_CONFIGURE = 0x40 + + +def fatal(msg): + tqdm.write(f"{colorama.Fore.RED + colorama.Style.BRIGHT}fatal:" + f"{colorama.Style.RESET_ALL} {msg}") + sys.exit(1) + + +def error(msg): + tqdm.write(f"{colorama.Fore.RED}error:{colorama.Style.RESET_ALL} {msg}") + + +def info(msg): + tqdm.write(f"{colorama.Fore.GREEN + colorama.Style.BRIGHT}info:" + f"{colorama.Style.RESET_ALL} {msg}") + + +def get_opensk_devices(batch_mode): + devices = [] + for dev in hid.CtapHidDevice.list_devices(): + if (dev.descriptor.vid, dev.descriptor.pid) == OPENSK_VID_PID: + if dev.capabilities & hid.CAPABILITY.CBOR: + if batch_mode: + devices.append(ctap2.CTAP2(dev)) + else: + return [ctap2.CTAP2(dev)] + return devices + + +def get_private_key(data, password=None): + # First we try without password. + try: + return serialization.load_pem_private_key(data, password=None) + except TypeError: + # Maybe we need a password then. + if sys.stdin.isatty(): + password = getpass.getpass(prompt="Private key password: ") + else: + password = sys.stdin.readline().rstrip() + return get_private_key(data, password=password.encode(sys.stdin.encoding)) + + +def main(args): + colorama.init() + # We need either both the certificate and the key or none + if bool(args.priv_key) ^ bool(args.certificate): + fatal("Certificate and private key must be set together or both omitted.") + + cbor_data = {1: args.lock} + + if args.priv_key: + cbor_data[1] = args.lock + priv_key = get_private_key(args.priv_key.read()) + if not isinstance(priv_key, ec.EllipticCurvePrivateKey): + fatal("Private key must be an Elliptic Curve one.") + if not isinstance(priv_key.curve, ec.SECP256R1): + fatal("Private key must use Secp256r1 curve.") + if priv_key.key_size != 256: + fatal("Private key must be 256 bits long.") + info("Private key is valid.") + + cert = x509.load_pem_x509_certificate(args.certificate.read()) + # Some sanity/validity checks + now = datetime.datetime.utcnow() + if cert.not_valid_before > now: + fatal("Certificate validity starts in the future.") + if cert.not_valid_after <= now: + fatal("Certificate expired.") + pub_key = cert.public_key() + if not isinstance(pub_key, ec.EllipticCurvePublicKey): + fatal("Certificate public key must be an Elliptic Curve one.") + if not isinstance(pub_key.curve, ec.SECP256R1): + fatal("Certificate public key must use Secp256r1 curve.") + if pub_key.key_size != 256: + fatal("Certificate public key must be 256 bits long.") + if pub_key.public_numbers() != priv_key.public_key().public_numbers(): + fatal("Certificate public doesn't match with the private key.") + info("Certificate is valid.") + + cbor_data[2] = { + 1: + cert.public_bytes(serialization.Encoding.DER), + 2: + priv_key.private_numbers().private_value.to_bytes( + length=32, byteorder='big', signed=False) + } + + for authenticator in tqdm(get_opensk_devices(args.batch)): + # If the device supports it, wink to show which device + # we're going to program. + if authenticator.device.capabilities & hid.CAPABILITY.WINK: + authenticator.device.wink() + aaguid = uuid.UUID(bytes=authenticator.get_info().aaguid) + info(f"Programming OpenSK device AAGUID {aaguid} ({authenticator.device}).") + info("Please touch the device to confirm...") + try: + result = authenticator.send_cbor( + OPENSK_VENDOR_CONFIGURE, + data=cbor_data, + ) + info(f"Certificate: {'Present' if result[1] else 'Missing'}") + info(f"Private Key: {'Present' if result[2] else 'Missing'}") + if args.lock: + info("Device is now locked down!") + except ctap.CtapError as ex: + if ex.code.value == ctap.CtapError.ERR.INVALID_COMMAND: + error("Failed to configure OpenSK (unsupported command).") + elif ex.code.value == 0xF2: # VENDOR_INTERNAL_ERROR + error(("Failed to configure OpenSK (lockdown conditions not met " + "or hardware error).")) + elif ex.code.value == ctap.CtapError.ERR.INVALID_PARAMETER: + error( + ("Failed to configure OpenSK (device is partially programmed but " + "the given cert/key don't match the ones currently programmed).")) + else: + error(f"Failed to configure OpenSK (unknown error: {ex}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--batch", + default=False, + action="store_true", + help=( + "When batch processing is used, all plugged OpenSK devices will " + "be programmed the same way. Otherwise (default) only the first seen " + "device will be programmed."), + ) + parser.add_argument( + "--certificate", + type=argparse.FileType("rb"), + default=None, + metavar="PEM_FILE", + dest="certificate", + help=("PEM file containing the certificate to inject into " + "the OpenSK authenticator."), + ) + parser.add_argument( + "--private-key", + type=argparse.FileType("rb"), + default=None, + metavar="PEM_FILE", + dest="priv_key", + help=("PEM file containing the private key associated " + "with the certificate."), + ) + parser.add_argument( + "--lock-device", + default=False, + action="store_true", + dest="lock", + help=("Locks the device (i.e. bootloader and JTAG access). " + "This command can fail if the certificate or the private key " + "haven't been both programmed yet."), + ) + main(parser.parse_args()) diff --git a/apps/vault/tools/gen_key_materials.sh b/apps/vault/tools/gen_key_materials.sh new file mode 100755 index 000000000..d9aa4323b --- /dev/null +++ b/apps/vault/tools/gen_key_materials.sh @@ -0,0 +1,97 @@ +#!/bin/bash +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +generate_crypto_materials () { + # OpenSK AAGUID + local aaguid_file=crypto_data/aaguid.txt + + # Root CA key pair and certificate + local ca_priv_key=crypto_data/opensk_ca.key + local ca_cert_name=crypto_data/opensk_ca + + # Attestation key pair and certificate that will be embedded into the + # firmware. The certificate will be signed by the Root CA. + local opensk_key=crypto_data/opensk.key + local opensk_cert_name=crypto_data/opensk_cert + + # Allow invoker to override the command with a full path. + local openssl=${OPENSSL:-$(which openssl)} + + # We need openssl command to continue + if [ ! -x "${openssl}" ] + then + echo "Missing openssl command. Try to specify its full path using OPENSSL environment variable." + exit 1 + fi + + # Exit on first error + set -e + + force_generate="$1" + mkdir -p crypto_data + if [ ! -f "${ca_priv_key}" ] + then + "${openssl}" ecparam -genkey -name prime256v1 -out "${ca_priv_key}" + fi + + if [ ! -f "${ca_cert_name}.pem" ] + then + "${openssl}" req \ + -new \ + -key "${ca_priv_key}" \ + -out "${ca_cert_name}.csr" \ + -subj "/CN=OpenSK CA" + "${openssl}" x509 \ + -trustout \ + -req \ + -days 7305 \ + -in "${ca_cert_name}.csr" \ + -signkey "${ca_priv_key}" \ + -outform pem \ + -out "${ca_cert_name}.pem" \ + -sha256 + fi + + if [ "${force_generate}" = "Y" -o ! -f "${opensk_key}" ] + then + "${openssl}" ecparam -genkey -name prime256v1 -out "${opensk_key}" + fi + + if [ "${force_generate}" = "Y" -o ! -f "${opensk_cert_name}.pem" ] + then + "${openssl}" req \ + -new \ + -key "${opensk_key}" \ + -out "${opensk_cert_name}.csr" \ + -subj "/CN=OpenSK Hacker Edition" + "${openssl}" x509 \ + -req \ + -days 3652 \ + -in "${opensk_cert_name}.csr" \ + -CA "${ca_cert_name}.pem" \ + -CAkey "${ca_priv_key}" \ + -CAcreateserial \ + -outform pem \ + -out "${opensk_cert_name}.pem" \ + -sha256 + fi + + if [ "${force_generate}" = "Y" -o ! -f "${aaguid_file}" ] + then + uuidgen > "${aaguid_file}" + fi +} + +generate_crypto_materials "$1"