From c619287824320b3fb6b0e4cfd011c20ac0a9270f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 8 Jul 2022 15:36:25 +0200 Subject: [PATCH] first raw commit --- .vscode/settings.json | 15 +- Cargo.lock | 90 +++++- Cargo.toml | 1 + apps/vault/src/ctap/hid/mod.rs | 122 +++++--- apps/vault/src/ctap/hid/send.rs | 10 +- apps/vault/src/main.rs | 10 +- apps/vault/src/vendor_commands.rs | 179 ++++++++++++ apps/vault/tools/totpbackup-rs/Cargo.toml | 15 + .../tools/totpbackup-rs/demo_backup.json | 16 ++ apps/vault/tools/totpbackup-rs/src/main.rs | 265 ++++++++++++++++++ 10 files changed, 671 insertions(+), 52 deletions(-) create mode 100644 apps/vault/src/vendor_commands.rs create mode 100644 apps/vault/tools/totpbackup-rs/Cargo.toml create mode 100644 apps/vault/tools/totpbackup-rs/demo_backup.json create mode 100644 apps/vault/tools/totpbackup-rs/src/main.rs diff --git a/.vscode/settings.json b/.vscode/settings.json index c7a5c45d7..0fce5c922 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,18 @@ { "rust-analyzer.checkOnSave.allTargets": false, "rust-analyzer.cargo.target":"riscv32imac-unknown-xous-elf", - "rust-analyzer.checkOnSave.extraArgs": ["--target-dir", "./target/check"] + "rust-analyzer.checkOnSave.extraArgs": ["--target-dir", "./target/check"], + "rust-analyzer.server.extraEnv": { + "XOUS_SVD_FILE": "../precursors/soc.svd" + }, + "rust-analyzer.files.excludeDirs": ["./loader/**"], + "files.exclude": { + "**/.git": true, + "**/.svn": true, + "**/.hg": true, + "**/CVS": true, + "**/.DS_Store": true, + "**/Thumbs.db": true, + "**/loader/**": true, + } } diff --git a/Cargo.lock b/Cargo.lock index 9c861761e..dfad84f45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,6 +82,35 @@ version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" +[[package]] +name = "argh" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7e7e4aa7e40747e023c0761dafcb42333a9517575bbf1241747f68dd3177a62" +dependencies = [ + "argh_derive", + "argh_shared", +] + +[[package]] +name = "argh_derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f2bd7ff6ed6414f4e5521bd509bae46454bbd513801767ced3f21a751ab4bc" +dependencies = [ + "argh_shared", + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "argh_shared" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47253b98986dafc7a3e1cf3259194f1f47ac61abb57a57f46ec09e48d004ecda" + [[package]] name = "arrayref" version = "0.3.6" @@ -771,6 +800,16 @@ dependencies = [ "xous-names", ] +[[package]] +name = "ctaphid" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a59eaecb592b343e37cffd3e67c5c64c6de0452a07731c2044d164c5b986cb64" +dependencies = [ + "hidapi", + "log", +] + [[package]] name = "ctr" version = "0.9.1" @@ -1527,6 +1566,15 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "hello" version = "0.1.0" @@ -1571,6 +1619,17 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0" +[[package]] +name = "hidapi" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b1717343691998deb81766bfcd1dce6df0d5d6c37070b5a3de2bb6d39f7822" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + [[package]] name = "hkdf" version = "0.11.0" @@ -3033,9 +3092,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.137" +version = "1.0.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +checksum = "1578c6245786b9d168c5447eeacfb96856573ca56c9d68fdcf394be134882a47" dependencies = [ "serde_derive", ] @@ -3061,9 +3120,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.137" +version = "1.0.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +checksum = "023e9b1467aef8a10fb88f25611870ada9800ef7e22afce356bb0d2387b6f27c" dependencies = [ "proc-macro2", "quote", @@ -3072,9 +3131,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7" dependencies = [ "itoa 1.0.2", "ryu", @@ -3610,6 +3669,19 @@ dependencies = [ "xmas-elf", ] +[[package]] +name = "totpbackup-rs" +version = "0.1.0" +dependencies = [ + "argh", + "cbor", + "ctaphid", + "hex 0.4.3", + "hidapi", + "serde", + "serde_json", +] + [[package]] name = "tracing" version = "0.1.35" @@ -3742,6 +3814,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99" + [[package]] name = "unicode-width" version = "0.1.9" diff --git a/Cargo.toml b/Cargo.toml index 616e70544..42423d7b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,6 +73,7 @@ members = [ "apps/hello", "apps/repl", "apps/vault", + "apps/vault/tools/totpbackup-rs", "services/libstd-test", "services/ffi-test", "services/tts", diff --git a/apps/vault/src/ctap/hid/mod.rs b/apps/vault/src/ctap/hid/mod.rs index 520eac44d..f825a10d8 100644 --- a/apps/vault/src/ctap/hid/mod.rs +++ b/apps/vault/src/ctap/hid/mod.rs @@ -15,7 +15,7 @@ pub mod receive; pub mod send; -use self::receive::MessageAssembler; +use self::{receive::MessageAssembler, send::CTAPHIDResponse}; use self::send::HidPacketIterator; #[cfg(feature = "with_ctap1")] use super::ctap1; @@ -151,7 +151,7 @@ impl CtapHid { packet: &HidPacket, clock_value: ClockValue, ctap_state: &mut CtapState, - ) -> HidPacketIterator + ) -> CTAPHIDResponse where R: Rng256, CheckUserPresence: Fn(ChannelID) -> Result<(), Ctap2StatusCode>, @@ -170,7 +170,7 @@ impl CtapHid { if !self.has_valid_channel(&message) { #[cfg(feature = "debug_ctap")] writeln!(&mut Console::new(), "Invalid channel: {:02x?}", cid).unwrap(); - return CtapHid::error_message(cid, CtapHid::ERR_INVALID_CHANNEL); + return CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_CHANNEL)); } // If another command arrives, stop winking to prevent accidential button touches. self.wink_permission = TimedPermission::waiting(); @@ -191,11 +191,11 @@ impl CtapHid { ) { Ok(payload) => { log::trace!("command success: {:x?}", payload); - CtapHid::ctap1_success_message(cid, &payload) + CTAPHIDResponse::StandardCommand(CtapHid::ctap1_success_message(cid, &payload)) }, Err(ctap1_status_code) => { log::trace!("command failure: {:?}", ctap1_status_code); - CtapHid::ctap1_error_message(cid, ctap1_status_code) + CTAPHIDResponse::StandardCommand(CtapHid::ctap1_error_message(cid, ctap1_status_code)) } } } @@ -213,7 +213,7 @@ impl CtapHid { cmd: CtapHid::COMMAND_CBOR, payload: response, }) { - iterator + CTAPHIDResponse::StandardCommand(iterator) } else { // Handle the case of a payload > 7609 bytes. // Although this shouldn't happen if the FIDO2 commands are implemented @@ -222,21 +222,23 @@ impl CtapHid { // // The error payload that we send instead is 1 <= 7609 bytes, so it is // safe to unwrap() the result. - CtapHid::split_message(Message { - cid, - cmd: CtapHid::COMMAND_CBOR, - payload: vec![ - Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_TOO_LONG as u8, - ], - }) - .unwrap() + CTAPHIDResponse::StandardCommand( + CtapHid::split_message(Message { + cid, + cmd: CtapHid::COMMAND_CBOR, + payload: vec![ + Ctap2StatusCode::CTAP2_ERR_VENDOR_RESPONSE_TOO_LONG as u8, + ], + }) + .unwrap() + ) } } // CTAP specification (version 20190130) section 8.1.9.1.3 CtapHid::COMMAND_INIT => { log::debug!("COMMAND_INIT"); if message.payload.len() != 8 { - return CtapHid::error_message(cid, CtapHid::ERR_INVALID_LEN); + return CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_LEN)); } let new_cid = if cid == CtapHid::CHANNEL_BROADCAST { @@ -258,12 +260,14 @@ impl CtapHid { payload[16] = CtapHid::CAPABILITIES; // This unwrap is safe because the payload length is 17 <= 7609 bytes. - CtapHid::split_message(Message { - cid, - cmd: CtapHid::COMMAND_INIT, - payload, - }) - .unwrap() + CTAPHIDResponse::StandardCommand( + CtapHid::split_message(Message { + cid, + cmd: CtapHid::COMMAND_INIT, + payload, + }) + .unwrap() + ) } // CTAP specification (version 20190130) section 8.1.9.1.4 CtapHid::COMMAND_PING => { @@ -271,71 +275,81 @@ impl CtapHid { // Pong the same message. // This unwrap is safe because if we could parse the incoming message, it's // payload length must be <= 7609 bytes. - CtapHid::split_message(message).unwrap() + CTAPHIDResponse::StandardCommand(CtapHid::split_message(message).unwrap()) } // CTAP specification (version 20190130) section 8.1.9.1.5 CtapHid::COMMAND_CANCEL => { log::debug!("COMMAND_CANCEL"); // Authenticators MUST NOT reply to this message. // CANCEL is handled during user presence checks in main. - HidPacketIterator::none() + CTAPHIDResponse::StandardCommand(HidPacketIterator::none()) } // Optional commands // CTAP specification (version 20190130) section 8.1.9.2.1 CtapHid::COMMAND_WINK => { log::debug!("COMMAND_WINK"); if !message.payload.is_empty() { - return CtapHid::error_message(cid, CtapHid::ERR_INVALID_LEN); + return CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_LEN)); } self.wink_permission = TimedPermission::granted(clock_value, CtapHid::WINK_TIMEOUT_DURATION); - CtapHid::split_message(Message { - cid, - cmd: CtapHid::COMMAND_WINK, - payload: vec![], - }) - .unwrap() + CTAPHIDResponse::StandardCommand( + CtapHid::split_message(Message { + cid, + cmd: CtapHid::COMMAND_WINK, + payload: vec![], + }) + .unwrap() + ) + } + // If we encountered a vendor command, return VendorCommand and let upstream code + // deal with it. + CtapHid::COMMAND_VENDOR_FIRST..=CtapHid::COMMAND_VENDOR_LAST => { + CTAPHIDResponse::VendorCommand( + message.cmd, + message.cid, + message.payload, + ) } - // CTAP specification (version 20190130) section 8.1.9.2.2 // TODO: implement LOCK _ => { log::debug!("ERR_INVALID_CMD"); // Unknown or unsupported command. - CtapHid::error_message(cid, CtapHid::ERR_INVALID_CMD) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_CMD)) } } } Ok(None) => { // Waiting for more packets to assemble the message, nothing to send for now. - HidPacketIterator::none() + CTAPHIDResponse::StandardCommand(HidPacketIterator::none()) } Err((cid, error)) => { if !self.is_allocated_channel(cid) && error != receive::Error::UnexpectedContinuation { - CtapHid::error_message(cid, CtapHid::ERR_INVALID_CHANNEL) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_CHANNEL)) } else { match error { receive::Error::UnexpectedChannel => { - CtapHid::error_message(cid, CtapHid::ERR_CHANNEL_BUSY) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_CHANNEL_BUSY)) } receive::Error::UnexpectedInit => { // TODO: Should we send another error code in this case? // Technically, we were expecting a sequence number and got another // byte, although the command/seqnum bit has higher-level semantics // than sequence numbers. - CtapHid::error_message(cid, CtapHid::ERR_INVALID_SEQ) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_SEQ)) } receive::Error::UnexpectedContinuation => { // CTAP specification (version 20190130) section 8.1.5.4 // Spurious continuation packets will be ignored. - HidPacketIterator::none() + CTAPHIDResponse::StandardCommand(HidPacketIterator::none()) } receive::Error::UnexpectedSeq => { - CtapHid::error_message(cid, CtapHid::ERR_INVALID_SEQ) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_INVALID_SEQ)) } receive::Error::Timeout => { - CtapHid::error_message(cid, CtapHid::ERR_MSG_TIMEOUT) + CTAPHIDResponse::StandardCommand(CtapHid::error_message(cid, CtapHid::ERR_MSG_TIMEOUT)) } } } @@ -437,6 +451,19 @@ impl CtapHid { }) .unwrap() } + + #[cfg(feature = "with_ctap1")] + fn ctap1_generic_success_message(cid: ChannelID, cmd: u8, payload: &[u8]) -> HidPacketIterator { + let mut response = payload.to_vec(); + let code: u16 = ctap1::Ctap1StatusCode::SW_SUCCESS.into(); + response.extend_from_slice(&code.to_be_bytes()); + CtapHid::split_message(Message { + cid, + cmd: cmd, + payload: response, + }) + .unwrap() + } } #[cfg(test)] @@ -462,7 +489,10 @@ mod test { for msg_request in request { for pkt_request in HidPacketIterator::new(msg_request).unwrap() { for pkt_reply in - ctap_hid.process_hid_packet(&pkt_request, DUMMY_CLOCK_VALUE, ctap_state) + match ctap_hid.process_hid_packet(&pkt_request, DUMMY_CLOCK_VALUE, ctap_state) { + CTAPHIDResponse::StandardCommand(iter) => iter, + CTAPHIDResponse::VendorCommand(_, _, _) => panic!("expected StandardCommand, not VendorCommand") + } { match assembler_reply.parse_packet(&pkt_reply, DUMMY_TIMESTAMP) { Ok(Some(message)) => result.push(message), @@ -538,7 +568,12 @@ mod test { let mut packet = [0x00; 64]; packet[0..7].copy_from_slice(&[0xC1, 0xC1, 0xC1, 0xC1, 0x00, 0x51, 0x51]); let mut assembler_reply = MessageAssembler::new(); - for pkt_reply in ctap_hid.process_hid_packet(&packet, DUMMY_CLOCK_VALUE, &mut ctap_state) { + let reply = match ctap_hid.process_hid_packet(&packet, DUMMY_CLOCK_VALUE, &mut ctap_state) { + CTAPHIDResponse::StandardCommand(iter) => iter, + CTAPHIDResponse::VendorCommand(_, _, _) => panic!("expected StandardCommand, not VendorCommand") + }; + + for pkt_reply in reply { // Continuation packets are silently ignored. assert_eq!( assembler_reply @@ -616,7 +651,10 @@ mod test { let mut assembler_reply = MessageAssembler::new(); for pkt_request in &[packet1, packet2] { for pkt_reply in - ctap_hid.process_hid_packet(&pkt_request, DUMMY_CLOCK_VALUE, &mut ctap_state) + match ctap_hid.process_hid_packet(&pkt_request, DUMMY_CLOCK_VALUE, &mut ctap_state) { + CTAPHIDResponse::StandardCommand(iter) => iter, + CTAPHIDResponse::VendorCommand(_, _, _) => panic!("expected StandardCommand, not VendorCommand") + } { if let Some(message) = assembler_reply .parse_packet(&pkt_reply, DUMMY_TIMESTAMP) diff --git a/apps/vault/src/ctap/hid/send.rs b/apps/vault/src/ctap/hid/send.rs index 0da70f3a2..7348bc70f 100644 --- a/apps/vault/src/ctap/hid/send.rs +++ b/apps/vault/src/ctap/hid/send.rs @@ -12,7 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{CtapHid, HidPacket, Message}; +use super::{CtapHid, HidPacket, Message, ChannelID}; + +pub enum CTAPHIDResponse { + /// Standard-compliant command processing result. + StandardCommand(HidPacketIterator), + + /// Vendor-specific command processing result. + VendorCommand(u8, ChannelID, Vec), +} pub struct HidPacketIterator(Option); diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 36e4a15e7..1c954627a 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -21,6 +21,7 @@ mod submenu; mod actions; mod totp; mod prereqs; +mod vendor_commands; use locales::t; @@ -158,7 +159,7 @@ const ERR_TIMEOUT_MS: usize = 5000; fn main() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Info); + log::set_max_level(log::LevelFilter::Debug); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -201,7 +202,12 @@ fn main() -> ! { Ok(msg) => { log::trace!("FIDO listener got message: {:?}", msg); let now = ClockValue::new(tt.elapsed_ms() as i64, 1000); - let reply = ctap_hid.process_hid_packet(&msg.packet, now, &mut ctap_state); + let reply = match ctap_hid.process_hid_packet(&msg.packet, now, &mut ctap_state) { + ctap::hid::send::CTAPHIDResponse::StandardCommand(iter) => iter, + ctap::hid::send::CTAPHIDResponse::VendorCommand(cmd, cid, payload) => { + vendor_commands::handle_vendor_command(cmd, cid, payload) + } + }; // This block handles sending packets. for pkt_reply in reply { let mut reply = RawFidoMsg::default(); diff --git a/apps/vault/src/vendor_commands.rs b/apps/vault/src/vendor_commands.rs new file mode 100644 index 000000000..de8cf3edc --- /dev/null +++ b/apps/vault/src/vendor_commands.rs @@ -0,0 +1,179 @@ +use cbor::{destructure_cbor_map, reader::DecoderError}; +use chrono::{DateTime, NaiveDateTime, Utc}; +use locales::t; +use pddb::Pddb; +use std::{time::{SystemTime, UNIX_EPOCH}, io::Write}; + +const VAULT_TOTP_DICT: &'static str = "vault.totp"; +/// bytes to reserve for a key entry. Making this slightly larger saves on some churn as stuff gets updated +const VAULT_TOTP_ALLOC_HINT: usize = 256; + +use crate::{ + actions::{TotpRecord, serialize_totp}, + ctap::hid::{send::HidPacketIterator, ChannelID, CtapHid, Message}, +}; + +// Vault-specific command to upload TOTP codes +pub const COMMAND_RESTORE_TOTP_CODES: u8 = 0x41; +pub const COMMAND_BENCHMARK: u8 = 0x42; + +pub fn handle_vendor_command( + cmd: u8, + channel_id: ChannelID, + payload: Vec, +) -> HidPacketIterator { + log::debug!("got vendor command: {}, payload: {:?}", cmd, payload); + let xns = xous_names::XousNames::new().unwrap(); + let mut trng = trng::Trng::new(&xns).unwrap(); + + let payload = match cmd { + COMMAND_BENCHMARK => Message { + cid: channel_id, + cmd: cmd, + payload: handle_benchmark(), + }, + COMMAND_RESTORE_TOTP_CODES => match handle_restore(payload, &mut trng) { + Ok(payload) => Message { + cid: channel_id, + cmd: cmd, + payload: payload, + }, + Err(_) => error_message(channel_id, 45), + }, + _ => error_message(channel_id, 0x33), + }; + + HidPacketIterator::new(payload).unwrap() +} + +fn handle_benchmark() -> Vec { + vec![0xDE, 0xAD, 0xBE, 0xEF] +} + +#[derive(Debug)] +enum RestoreError { + CborError(DecoderError), + NotAnArray, + NotAMap, + PddbError(std::io::Error), +} + +impl From for RestoreError { + fn from(de: DecoderError) -> Self { + RestoreError::CborError(de) + } +} + +fn handle_restore(data: Vec, trng: &mut trng::Trng) -> Result, RestoreError> { + // Unmarshal bytes to cbor map + let c = cbor::read(&data)?; + + let array_c = match c { + cbor::Value::Array(array) => array, + _ => return Err(RestoreError::NotAnArray), + }; + + let pddb = Pddb::new(); + + for elem in array_c { + let rawmap = match elem { + cbor::Value::Map(m) => m, + _ => return Err(RestoreError::NotAMap), + }; + + destructure_cbor_map! { + let { + 1 => step_seconds, + 2 => shared_secret, + 3 => digit_count, + 4 => algorithm, + 5 => name, + } = rawmap; + } + + let totp = TotpRecord { + version: 1, + name: extract_string(name.unwrap()).unwrap(), + secret: extract_string(shared_secret.unwrap()).unwrap(), + algorithm: crate::totp::TotpAlgorithm::HmacSha1, + digits: extract_unsigned(digit_count.unwrap()).unwrap() as u32, + timestep: extract_unsigned(step_seconds.unwrap()).unwrap(), + ctime: utc_now().timestamp() as u64, + notes: t!("vault.notes", xous::LANG).to_string(), + }; + + let ser = serialize_totp(&totp); + let guid = gen_guid(trng); + log::debug!("storing into guid: {}", guid); + match pddb.get( + VAULT_TOTP_DICT, + &guid, + None, + true, + true, + Some(VAULT_TOTP_ALLOC_HINT), + Some(crate::basis_change), + ) { + Ok(mut data) => match data.write(&ser) { + Ok(len) => log::debug!("wrote {} bytes", len), + Err(e) => return Err(RestoreError::PddbError(e)) + }, + Err(e) => return Err(RestoreError::PddbError(e)), + } + log::debug!("syncing..."); + pddb.sync().ok(); + } + + Ok(vec![0xca, 0xfe, 0xba, 0xbe]) +} + +fn error_message(cid: ChannelID, error_code: u8) -> Message { + // This unwrap is safe because the payload length is 1 <= 7609 bytes. + Message { + cid, + cmd: 0x3F, // COMMAND_ERROR + payload: vec![error_code], + } +} + +#[derive(Debug)] +enum CborConversionError { + BadCbor, + UnknownAlgorithm(u64), +} + +fn extract_unsigned(cbor_value: cbor::Value) -> Result { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::Unsigned(unsigned)) => Ok(unsigned), + _ => Err(CborConversionError::BadCbor), + } +} + +fn extract_byte_string(cbor_value: cbor::Value) -> Result, CborConversionError> { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::ByteString(byte_string)) => Ok(byte_string), + _ => Err(CborConversionError::BadCbor), + } +} + +fn extract_string(cbor_value: cbor::Value) -> Result { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::TextString(string)) => Ok(string), + _ => Err(CborConversionError::BadCbor), + } +} + +/// because we don't get Utc::now, as the crate checks your architecture and xous is not recognized as a valid target +fn utc_now() -> DateTime { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system time before Unix epoch"); + let naive = NaiveDateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos() as u32); + DateTime::from_utc(naive, Utc) +} + +fn gen_guid(trng: &mut trng::Trng) -> String { + let mut guid = [0u8; 16]; + trng.fill_bytes(&mut guid); + hex::encode(guid) +} \ No newline at end of file diff --git a/apps/vault/tools/totpbackup-rs/Cargo.toml b/apps/vault/tools/totpbackup-rs/Cargo.toml new file mode 100644 index 000000000..613ea1059 --- /dev/null +++ b/apps/vault/tools/totpbackup-rs/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "totpbackup-rs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +argh = "0.1.8" +ctaphid = "0.1.1" +cbor = {path = "../../libraries/cbor"} +hidapi = "1.4.1" +serde_json = "1.0.82" +serde = {version = "1.0.138", features = ["derive"]} +hex = "0.4.3" diff --git a/apps/vault/tools/totpbackup-rs/demo_backup.json b/apps/vault/tools/totpbackup-rs/demo_backup.json new file mode 100644 index 000000000..39f4360f7 --- /dev/null +++ b/apps/vault/tools/totpbackup-rs/demo_backup.json @@ -0,0 +1,16 @@ +[ + { + "step_seconds": 30, + "shared_secret": "I65VU7K5ZQL7WB4E", + "digit_count": 6, + "algorithm": "SHA256", + "name": "demo backup!" + }, + { + "step_seconds": 30, + "shared_secret": "I65VU7K5ZQL7WB4E", + "digit_count": 6, + "algorithm": "SHA256", + "name": "demo backup 2: this time is personal" + } +] \ No newline at end of file diff --git a/apps/vault/tools/totpbackup-rs/src/main.rs b/apps/vault/tools/totpbackup-rs/src/main.rs new file mode 100644 index 000000000..b9843b730 --- /dev/null +++ b/apps/vault/tools/totpbackup-rs/src/main.rs @@ -0,0 +1,265 @@ +use argh::FromArgs; +use cbor::{ + self, cbor_array_vec, cbor_int, cbor_key_int, cbor_map, cbor_unsigned, destructure_cbor_map, +}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, error::Error}; + +#[derive(FromArgs, PartialEq, Debug)] +#[argh(description = "A tool to backup/restore TOTP settings for the vault app via USB.")] +struct WithPositional { + #[argh(option)] + #[argh(description = "backup TOTP settings from device to file")] + backup: Option, + + #[argh(option)] + #[argh(description = "restore TOTP settings from file to device")] + restore: Option, +} + +enum CLIAction { + Backup(String), + Restore(String), +} + +impl TryInto for WithPositional { + type Error = ProgramError; + + fn try_into(self) -> Result { + if self.backup.is_some() && self.restore.is_some() { + return Err(ProgramError::CantBackupAndRestoreAtTheSameTime); + } + + if self.backup.is_some() { + return Ok(CLIAction::Backup(self.backup.unwrap())); + } + + if self.restore.is_some() { + return Ok(CLIAction::Restore(self.restore.unwrap())); + } + + panic!("impossible!") + } +} + +#[derive(Debug)] +enum CborConversionError { + BadCbor, + UnknownAlgorithm(u64), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum HashAlgorithms { + SHA1, + SHA256, + SHA512, +} + +impl From for cbor::Value { + fn from(te: HashAlgorithms) -> Self { + match te { + HashAlgorithms::SHA1 => cbor_unsigned!(1), + HashAlgorithms::SHA256 => cbor_unsigned!(2), + HashAlgorithms::SHA512 => cbor_unsigned!(3), + } + } +} + +impl TryFrom for HashAlgorithms { + fn try_from(value: cbor::Value) -> Result { + match value { + cbor::Value::KeyValue(cbor::KeyType::Unsigned(unsigned)) => match unsigned { + 1 => Ok(HashAlgorithms::SHA1), + 2 => Ok(HashAlgorithms::SHA256), + 3 => Ok(HashAlgorithms::SHA512), + other => Err(CborConversionError::UnknownAlgorithm(other)), + }, + _ => Err(CborConversionError::BadCbor), + } + } + + type Error = CborConversionError; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TotpEntry { + step_seconds: u64, + shared_secret: String, + digit_count: u64, + algorithm: HashAlgorithms, + name: String, +} + +impl From for cbor::Value { + fn from(te: TotpEntry) -> Self { + cbor_map! { + cbor_key_int!(1) => te.step_seconds as i64, + cbor_key_int!(2) => te.shared_secret, + cbor_key_int!(3) => te.digit_count as i64, + cbor_key_int!(4) => te.algorithm, + cbor_key_int!(5) => te.name, + } + } +} + +impl TryFrom for TotpEntry { + fn try_from(value: cbor::Value) -> Result { + let rawmap = match value { + cbor::Value::Map(m) => m, + _ => return Err(CborConversionError::BadCbor), + }; + + destructure_cbor_map! { + let { + 1 => step_seconds, + 2 => shared_secret, + 3 => digit_count, + 4 => algorithm, + 5 => name, + } = rawmap; + } + + let step_seconds = extract_unsigned(step_seconds.unwrap())?; + let shared_secret = extract_string(shared_secret.unwrap())?; + let digit_count = extract_unsigned(digit_count.unwrap())?; + let algorithm: HashAlgorithms = algorithm.unwrap().try_into()?; + let name = extract_string(name.unwrap())?; + + Ok(TotpEntry { + step_seconds, + shared_secret, + digit_count, + algorithm, + name, + }) + } + + type Error = CborConversionError; +} + +#[derive(Serialize, Deserialize)] +struct TotpEntries(Vec); + +impl From<&TotpEntries> for cbor::Value { + fn from(te: &TotpEntries) -> Self { + cbor_array_vec!(te.0.clone()) + } +} + +impl TryFrom for TotpEntries { + fn try_from(value: cbor::Value) -> Result { + let raw = extract_array(value)?; + let mut ret = vec![]; + + for e in raw { + ret.push(e.try_into().unwrap()) + } + + Ok(Self(ret)) + } + + type Error = CborConversionError; +} + +impl TotpEntries { + fn bytes(&self) -> Vec { + let mut ret = vec![]; + cbor::write(self.into(), &mut ret); + ret + } +} + +#[derive(Debug)] +enum ProgramError { + NoDevicesFound, + CantBackupAndRestoreAtTheSameTime, + DeviceError(Vec), +} + +impl std::fmt::Display for ProgramError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProgramError::NoDevicesFound => write!(f, "no CTAP2 devices found"), + ProgramError::CantBackupAndRestoreAtTheSameTime => { + write!(f, "can't backup and restore at the same time") + } + ProgramError::DeviceError(code) => write!(f, "device returned code {:?}", code), + } + } +} + +impl std::error::Error for ProgramError {} + +const OKAY_CANARY: &[u8] = &[0xca, 0xfe, 0xba, 0xbe]; + +fn main() -> Result<(), Box> { + let wp: WithPositional = argh::from_env(); + let argument: CLIAction = wp.try_into()?; + + let ha = hidapi::HidApi::new()?; + let dl = ha.device_list(); + + let mut precursor: Option<&hidapi::DeviceInfo> = None; + for i in dl { + if i.product_string().unwrap() == "Precursor" { + precursor = Some(i); + break; + } + } + + if precursor.is_none() { + return Err(Box::new(ProgramError::NoDevicesFound)); + } + + let device = ctaphid::Device::connect(&ha, precursor.unwrap())?; + + match argument { + CLIAction::Backup(path) => todo!(), + CLIAction::Restore(path) => { + let hbf = read_human_backup_file(&path)?; + let vcres = device.vendor_command(ctaphid::command::VendorCommand::H41, &hbf)?; + + if vcres.ne(OKAY_CANARY) { + return Err(Box::new(ProgramError::DeviceError(vcres))); + } + + Ok(()) + } + } +} + +fn read_human_backup_file(path: &str) -> Result, Box> { + let f = std::fs::File::open(path)?; + + let backup_json: TotpEntries = serde_json::from_reader(f)?; + + Ok(backup_json.bytes()) +} + +fn extract_unsigned(cbor_value: cbor::Value) -> Result { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::Unsigned(unsigned)) => Ok(unsigned), + _ => Err(CborConversionError::BadCbor), + } +} + +fn extract_byte_string(cbor_value: cbor::Value) -> Result, CborConversionError> { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::ByteString(byte_string)) => Ok(byte_string), + _ => Err(CborConversionError::BadCbor), + } +} + +fn extract_array(cbor_value: cbor::Value) -> Result, CborConversionError> { + match cbor_value { + cbor::Value::Array(array) => Ok(array), + _ => Err(CborConversionError::BadCbor), + } +} + +fn extract_string(cbor_value: cbor::Value) -> Result { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::TextString(string)) => Ok(string), + _ => Err(CborConversionError::BadCbor), + } +} \ No newline at end of file