From b9c6ce42edcca96ee30b0255cc163e313a65700e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 24 Oct 2022 16:03:19 +0200 Subject: [PATCH 01/59] Run cargo fmt --- src/commands.rs | 82 ++++++++----- src/constants.rs | 20 ++-- src/container.rs | 102 ++++++++-------- src/dispatch.rs | 17 ++- src/lib.rs | 286 ++++++++++++++++++++++++++------------------- src/piv_types.rs | 77 +++++++----- src/state.rs | 85 +++++++------- tests/get_data.rs | 2 +- tests/setup/mod.rs | 53 ++++++--- 9 files changed, 432 insertions(+), 292 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 09965d4..109d9a3 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -66,7 +66,6 @@ impl<'l> TryFrom<&'l [u8]> for Select<'l> { } } - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct GetData(containers::Container); @@ -74,7 +73,9 @@ impl TryFrom<&[u8]> for GetData { type Error = Status; fn try_from(data: &[u8]) -> Result { let mut decoder = flexiber::Decoder::new(data); - let tagged_slice: flexiber::TaggedSlice = decoder.decode().map_err(|_| Status::IncorrectDataParameter)?; + let tagged_slice: flexiber::TaggedSlice = decoder + .decode() + .map_err(|_| Status::IncorrectDataParameter)?; if tagged_slice.tag() != flexiber::Tag::application(0x1C) { return Err(Status::IncorrectDataParameter); } @@ -155,13 +156,20 @@ pub enum Verify { impl TryFrom> for Verify { type Error = Status; fn try_from(arguments: VerifyArguments<'_>) -> Result { - let VerifyArguments { key_reference, logout, data } = arguments; + let VerifyArguments { + key_reference, + logout, + data, + } = arguments; if key_reference != VerifyKeyReference::PivPin { return Err(Status::FunctionNotSupported); } Ok(match (logout.0, data.len()) { (false, 0) => Verify::Status(key_reference), - (false, 8) => Verify::Login(VerifyLogin::PivPin(data.try_into().map_err(|_| Status::IncorrectDataParameter)?)), + (false, 8) => Verify::Login(VerifyLogin::PivPin( + data.try_into() + .map_err(|_| Status::IncorrectDataParameter)?, + )), (false, _) => return Err(Status::IncorrectDataParameter), (true, 0) => Verify::Logout(key_reference), (true, _) => return Err(Status::IncorrectDataParameter), @@ -204,22 +212,27 @@ pub enum ChangeReference { impl TryFrom> for ChangeReference { type Error = Status; fn try_from(arguments: ChangeReferenceArguments<'_>) -> Result { - let ChangeReferenceArguments { key_reference, data } = arguments; + let ChangeReferenceArguments { + key_reference, + data, + } = arguments; use ChangeReferenceKeyReference::*; Ok(match (key_reference, data) { (GlobalPin, _) => return Err(Status::FunctionNotSupported), - (PivPin, data) => { - ChangeReference::ChangePin { - old_pin: Pin::try_from(&data[..8]).map_err(|_| Status::IncorrectDataParameter)?, - new_pin: Pin::try_from(&data[8..]).map_err(|_| Status::IncorrectDataParameter)?, - } - } + (PivPin, data) => ChangeReference::ChangePin { + old_pin: Pin::try_from(&data[..8]).map_err(|_| Status::IncorrectDataParameter)?, + new_pin: Pin::try_from(&data[8..]).map_err(|_| Status::IncorrectDataParameter)?, + }, (Puk, data) => { use crate::commands::Puk; ChangeReference::ChangePuk { - old_puk: Puk(data[..8].try_into().map_err(|_| Status::IncorrectDataParameter)?), - new_puk: Puk(data[8..].try_into().map_err(|_| Status::IncorrectDataParameter)?), + old_puk: Puk(data[..8] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), + new_puk: Puk(data[8..] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), } } }) @@ -229,7 +242,7 @@ impl TryFrom> for ChangeReference { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ResetPinRetries { pub padded_pin: [u8; 8], - pub puk: [u8; 8], + pub puk: [u8; 8], } impl TryFrom<&[u8]> for ResetPinRetries { @@ -321,8 +334,7 @@ pub struct AuthenticateArguments<'l> { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Authenticate { -} +pub enum Authenticate {} impl TryFrom> for Authenticate { type Error = Status; @@ -332,8 +344,7 @@ impl TryFrom> for Authenticate { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct PutData { -} +pub struct PutData {} impl TryFrom<&[u8]> for PutData { type Error = Status; @@ -373,8 +384,7 @@ pub struct GenerateAsymmetricArguments<'l> { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GenerateAsymmetric { -} +pub enum GenerateAsymmetric {} impl TryFrom> for GenerateAsymmetric { type Error = Status; @@ -392,7 +402,12 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { /// /// The individual piv::Command TryFroms then further interpret these validated parameters. fn try_from(command: &'l iso7816::Command) -> Result { - let (class, instruction, p1, p2) = (command.class(), command.instruction(), command.p1, command.p2); + let (class, instruction, p1, p2) = ( + command.class(), + command.instruction(), + command.p1, + command.p2, + ); let data = command.data(); if !class.secure_messaging().none() { @@ -406,7 +421,6 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { // TODO: should we check `command.expected() == 0`, where specified? Ok(match (class.into_inner(), instruction, p1, p2) { - (0x00, Instruction::Select, 0x04, 0x00) => { Self::Select(Select::try_from(data.as_slice())?) } @@ -418,12 +432,19 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { (0x00, Instruction::Verify, p1, p2) => { let logout = VerifyLogout::try_from(p1)?; let key_reference = VerifyKeyReference::try_from(p2)?; - Self::Verify(Verify::try_from(VerifyArguments { key_reference, logout, data })?) + Self::Verify(Verify::try_from(VerifyArguments { + key_reference, + logout, + data, + })?) } (0x00, Instruction::ChangeReferenceData, 0x00, p2) => { let key_reference = ChangeReferenceKeyReference::try_from(p2)?; - Self::ChangeReference(ChangeReference::try_from(ChangeReferenceArguments { key_reference, data })?) + Self::ChangeReference(ChangeReference::try_from(ChangeReferenceArguments { + key_reference, + data, + })?) } (0x00, Instruction::ResetRetryCounter, 0x00, 0x80) => { @@ -433,7 +454,11 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { (0x00, Instruction::GeneralAuthenticate, p1, p2) => { let unparsed_algorithm = p1; let key_reference = AuthenticateKeyReference::try_from(p2)?; - Self::Authenticate(Authenticate::try_from(AuthenticateArguments { unparsed_algorithm, key_reference, data })?) + Self::Authenticate(Authenticate::try_from(AuthenticateArguments { + unparsed_algorithm, + key_reference, + data, + })?) } (0x00, Instruction::PutData, 0x3F, 0xFF) => { @@ -442,7 +467,12 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { (0x00, Instruction::GenerateAsymmetricKeyPair, 0x00, p2) => { let key_reference = GenerateAsymmetricKeyReference::try_from(p2)?; - Self::GenerateAsymmetric(GenerateAsymmetric::try_from(GenerateAsymmetricArguments { key_reference, data })?) + Self::GenerateAsymmetric(GenerateAsymmetric::try_from( + GenerateAsymmetricArguments { + key_reference, + data, + }, + )?) } _ => return Err(Status::FunctionNotSupported), diff --git a/src/constants.rs b/src/constants.rs index 0a14aba..2452d6d 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -19,7 +19,8 @@ pub const DERIVED_PIV_PIX: [u8; 6] = hex!("0000 2000 0100"); pub const PIV_TRUNCATED_AID: [u8; 9] = hex!("A000000308 00001000"); // pub const PIV_AID: &[u8] = &hex!("A000000308 00001000 0100"); -pub const PIV_AID: iso7816::Aid = iso7816::Aid::new_truncatable(&hex!("A000000308 00001000 0100"), 9); +pub const PIV_AID: iso7816::Aid = + iso7816::Aid::new_truncatable(&hex!("A000000308 00001000 0100"), 9); pub const DERIVED_PIV_AID: [u8; 11] = hex!("A000000308 00002000 0100"); @@ -27,7 +28,6 @@ pub const APPLICATION_LABEL: &[u8] = b"SoloKeys PIV"; pub const APPLICATION_URL: &[u8] = b"https://github.com/solokeys/piv-authenticator"; // pub const APPLICATION_URL: &[u8] = b"https://piv.is/SoloKeys/PIV/1.0.0-alpha1"; - // https://git.io/JfWuD pub const YUBICO_OTP_PIX: [u8; 3] = hex!("200101"); pub const YUBICO_OTP_AID: iso7816::Aid = iso7816::Aid::new(&hex!("A000000527 200101")); @@ -84,7 +84,7 @@ pub const SELECT: (u8, u8, u8, u8) = ( // p2: i think this is dummy here 0x00, // b2, b1 zero means "file occurence": first/only occurence, // b4, b3 zero means "file control information": return FCI template - // 256, + // 256, ); // @@ -101,12 +101,11 @@ pub const SELECT: (u8, u8, u8, u8) = ( pub const GET_DATA: (u8, u8, u8, u8) = ( 0x00, // as before, would be 0x0C for secure messaging 0xCB, // GET DATA. There's also `CA`, setting bit 1 here - // means (7816-4, sec. 5.1.2): use BER-TLV, as opposed - // to "no indication provided". + // means (7816-4, sec. 5.1.2): use BER-TLV, as opposed + // to "no indication provided". // P1, P2: 7816-4, sec. 7.4.1: bit 1 of INS set => P1,P2 identifies // a file. And 0x3FFF identifies current DF - 0x3F, - 0xFF, + 0x3F, 0xFF, // 256, ); @@ -233,7 +232,6 @@ pub const GET_DATA: (u8, u8, u8, u8) = ( // } //} - // 6A, 80 incorrect parameter in command data field // 6A, 81 function not supported // 6A, 82 data object not found ( = NOT FOUND for files, e.g. certificate, e.g. after GET-DATA) @@ -420,13 +418,13 @@ pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &'static [u8; 584] = &[ ]; // pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = b"123456781234567812345678"; pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = &[ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, ]; // stolen from le yubico -pub const DISCOVERY_OBJECT: &'static [u8; 20] = b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; +pub const DISCOVERY_OBJECT: &'static [u8; 20] = + b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; // import secrets; secrets.token_bytes(16) pub const GUID: &'static [u8; 16] = b"\x0c\x92\xc9\x04\xd0\xdeL\xd9\xf6\xd1\xa2\x9fE3\xca\xeb"; diff --git a/src/container.rs b/src/container.rs index 5870edb..dfc3a0d 100644 --- a/src/container.rs +++ b/src/container.rs @@ -29,7 +29,6 @@ pub enum KeyReference { // 20x RetiredKeyManagement(RetiredIndex), - } impl From for u8 { @@ -85,7 +84,7 @@ impl From for ContainerId { use Container::*; Self(match container { CardCapabilityContainer => 0xDB00, - CardHolderUniqueIdentifier =>0x3000, + CardHolderUniqueIdentifier => 0x3000, X509CertificateFor9A => 0x0101, CardholderFingerprints => 0x6010, SecurityObject => 0x9000, @@ -194,64 +193,63 @@ impl TryFrom> for Container { } } +// #[derive(Clone, Copy, PartialEq)] +// pub struct CertInfo { +// compressed: bool, +// } - // #[derive(Clone, Copy, PartialEq)] - // pub struct CertInfo { - // compressed: bool, - // } - - // impl From for u8 { - // fn from(cert_info: CertInfo) -> Self { - // cert_info.compressed as u8 - // } - // } +// impl From for u8 { +// fn from(cert_info: CertInfo) -> Self { +// cert_info.compressed as u8 +// } +// } - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } +// impl Encodable for CertInfo { +// fn encoded_len(&self) -> der::Result { +// Length::from(1) +// } - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } +// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { +// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) +// } +// } - // pub struct Certificate<'a> { - // // max bytes: 1856 - // certificate: &'a [u8], // tag: 0x70 - // // 1B - // cert_info: CertInfo, // tag: 0x71 - // // 38 - // // mscuid: ?, // tag: 0x72 - // error_detection_code: [u8; 0], // tag: 0xFE - // } +// pub struct Certificate<'a> { +// // max bytes: 1856 +// certificate: &'a [u8], // tag: 0x70 +// // 1B +// cert_info: CertInfo, // tag: 0x71 +// // 38 +// // mscuid: ?, // tag: 0x72 +// error_detection_code: [u8; 0], // tag: 0xFE +// } - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } +// impl Encodable for CertInfo { +// fn encoded_len(&self) -> der::Result { +// Length::from(1) +// } - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } +// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { +// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) +// } +// } - // #[derive(Encodable)] - // pub struct DiscoveryObject<'a> { - // #[tlv(tag = "0x4F")] - // piv_card_application_aid: &'a [u8; 11], // tag: 0x4F, max bytes = 12, - // #[tlv(tag = 0x5F2f)] - // pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, - // } +// #[derive(Encodable)] +// pub struct DiscoveryObject<'a> { +// #[tlv(tag = "0x4F")] +// piv_card_application_aid: &'a [u8; 11], // tag: 0x4F, max bytes = 12, +// #[tlv(tag = 0x5F2f)] +// pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, +// } - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } +// impl Encodable for CertInfo { +// fn encoded_len(&self) -> der::Result { +// Length::from(1) +// } - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } +// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { +// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) +// } +// } // } diff --git a/src/dispatch.rs b/src/dispatch.rs index 77c6d13..a2a09ed 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -1,20 +1,27 @@ use crate::{Authenticator, /*constants::PIV_AID,*/ Result}; -use apdu_dispatch::{app::App, command, Command, response}; +use apdu_dispatch::{app::App, command, response, Command}; use trussed::client; #[cfg(feature = "apdu-dispatch")] -impl App<{command::SIZE}, {response::SIZE}> for Authenticator +impl App<{ command::SIZE }, { response::SIZE }> for Authenticator where - T: client::Client + client::Ed255 + client::Tdes + T: client::Client + client::Ed255 + client::Tdes, { fn select(&mut self, apdu: &Command, reply: &mut response::Data) -> Result { self.select(apdu, reply) } - fn deselect(&mut self) { self.deselect() } + fn deselect(&mut self) { + self.deselect() + } - fn call(&mut self, _: iso7816::Interface, apdu: &Command, reply: &mut response::Data) -> Result { + fn call( + &mut self, + _: iso7816::Interface, + apdu: &Command, + reply: &mut response::Data, + ) -> Result { self.respond(apdu, reply) } } diff --git a/src/lib.rs b/src/lib.rs index 373faf7..b2ded31 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,14 +11,13 @@ pub mod commands; pub use commands::Command; pub mod constants; pub mod container; +pub mod derp; #[cfg(feature = "apdu-dispatch")] mod dispatch; -pub mod state; -pub mod derp; pub mod piv_types; +pub mod state; pub use piv_types::{Pin, Puk}; - use core::convert::TryInto; use flexiber::EncodableHeapless; @@ -35,14 +34,12 @@ pub type Result = iso7816::Result<()>; /// The `C` parameter is necessary, as PIV includes command sequences, /// where we need to store the previous command, so we need to know how /// much space to allocate. -pub struct Authenticator -{ +pub struct Authenticator { state: state::State, trussed: T, } -impl iso7816::App for Authenticator -{ +impl iso7816::App for Authenticator { fn aid(&self) -> iso7816::Aid { crate::constants::PIV_AID } @@ -52,11 +49,7 @@ impl Authenticator where T: client::Client + client::Ed255 + client::Tdes, { - pub fn new( - trussed: T, - ) - -> Self - { + pub fn new(trussed: T) -> Self { // seems like RefCell is not the right thing, we want something like `Rc` instead, // which can be cloned and injected into other parts of the App that use Trussed. // let trussed = RefCell::new(trussed); @@ -69,24 +62,20 @@ where // TODO: we'd like to listen on multiple AIDs. // The way apdu-dispatch currently works, this would deselect, resetting security indicators. - pub fn deselect(&mut self) { - } + pub fn deselect(&mut self) {} - pub fn select(&mut self, _apdu: &iso7816::Command, reply: &mut Data) -> Result - { + pub fn select( + &mut self, + _apdu: &iso7816::Command, + reply: &mut Data, + ) -> Result { use piv_types::Algorithms::*; info_now!("selecting PIV maybe"); let application_property_template = piv_types::ApplicationPropertyTemplate::default() .with_application_label(APPLICATION_LABEL) .with_application_url(APPLICATION_URL) - .with_supported_cryptographic_algorithms(&[ - Tdes, - Aes256, - P256, - Ed255, - X255, - ]); + .with_supported_cryptographic_algorithms(&[Tdes, Aes256, P256, Ed255, X255]); application_property_template .encode_to_heapless_vec(reply) @@ -95,8 +84,11 @@ where Ok(()) } - pub fn respond(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { + pub fn respond( + &mut self, + command: &iso7816::Command, + reply: &mut Data, + ) -> Result { // need to implement Debug on iso7816::Command // info_now!("PIV responding to {:?}", command); let last_or_only = command.class().chain().last_or_only(); @@ -105,7 +97,10 @@ where let entire_command = match self.state.runtime.chained_command.as_mut() { Some(command_so_far) => { // TODO: make sure the header matches, e.g. '00 DB 3F FF' - command_so_far.data_mut().extend_from_slice(command.data()).unwrap(); + command_so_far + .data_mut() + .extend_from_slice(command.data()) + .unwrap(); if last_or_only { let entire_command = command_so_far.clone(); @@ -142,7 +137,6 @@ where // maybe reserve this for the case VerifyLogin::PivPin? pub fn login(&mut self, login: commands::VerifyLogin) -> Result { if let commands::VerifyLogin::PivPin(pin) = login { - // the actual PIN verification let mut persistent_state = self.state.persistent(&mut self.trussed); @@ -154,7 +148,6 @@ where persistent_state.reset_consecutive_pin_mismatches(); self.state.runtime.app_security_status.pin_verified = true; Ok(()) - } else { let remaining = persistent_state.increment_consecutive_pin_mismatches(); // should we logout here? @@ -181,9 +174,12 @@ where return Err(Status::FunctionNotSupported); } if self.state.runtime.app_security_status.pin_verified { - return Ok(()) + return Ok(()); } else { - let retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); + let retries = self + .state + .persistent(&mut self.trussed) + .remaining_pin_retries(); return Err(Status::RemainingRetries(retries)); } } @@ -343,9 +339,11 @@ where // - 9000, 61XX for success // - 6982 security status // - 6A80, 6A86 for data, P1/P2 issue - pub fn general_authenticate(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { - + pub fn general_authenticate( + &mut self, + command: &iso7816::Command, + reply: &mut Data, + ) -> Result { // For "SSH", we need implement A.4.2 in SP-800-73-4 Part 2, ECDSA signatures // // ins = 87 = general authenticate @@ -432,7 +430,13 @@ where } info_now!("looking for keyreference"); - let key_handle = match self.state.persistent(&mut self.trussed).state.keys.authentication_key { + let key_handle = match self + .state + .persistent(&mut self.trussed) + .state + .keys + .authentication_key + { Some(key) => key, None => return Err(Status::KeyReferenceNotFound), }; @@ -442,8 +446,8 @@ where .map_err(|_error| { // NoSuchKey debug_now!("{:?}", &_error); - Status::UnspecifiedNonpersistentExecutionError } - )? + Status::UnspecifiedNonpersistentExecutionError + })? .signature; piv_types::DynamicAuthenticationTemplate::with_response(&signature) @@ -454,8 +458,12 @@ where Ok(()) } - pub fn request_for_challenge(&mut self, command: &iso7816::Command, remaining_data: &[u8], reply: &mut Data) -> Result - { + pub fn request_for_challenge( + &mut self, + command: &iso7816::Command, + remaining_data: &[u8], + reply: &mut Data, + ) -> Result { // - data is of the form // 00 87 03 9B 16 7C 14 80 08 99 6D 71 40 E7 05 DF 7F 81 08 6E EF 9C 02 00 69 73 E8 // - remaining data contains 81 08 @@ -474,9 +482,12 @@ where use state::{AuthenticateManagement, CommandCache}; let our_challenge = match self.state.runtime.command_cache { - Some(CommandCache::AuthenticateManagement(AuthenticateManagement { challenge } )) - => challenge, - _ => { return Err(Status::InstructionNotSupportedOrInvalid); } + Some(CommandCache::AuthenticateManagement(AuthenticateManagement { challenge })) => { + challenge + } + _ => { + return Err(Status::InstructionNotSupportedOrInvalid); + } }; // no retries ;) self.state.runtime.command_cache = None; @@ -495,7 +506,12 @@ where return Err(Status::IncorrectDataParameter); } - let key = self.state.persistent(&mut self.trussed).state.keys.management_key; + let key = self + .state + .persistent(&mut self.trussed) + .state + .keys + .management_key; let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, challenge)).ciphertext; @@ -506,8 +522,12 @@ where Ok(()) } - pub fn request_for_witness(&mut self, command: &iso7816::Command, remaining_data: &[u8], reply: &mut Data) -> Result - { + pub fn request_for_witness( + &mut self, + command: &iso7816::Command, + remaining_data: &[u8], + reply: &mut Data, + ) -> Result { // invariants: parsed data was '7C L1 80 00' + remaining_data if command.p1 != 0x03 || command.p2 != 0x9b { @@ -518,11 +538,19 @@ where return Err(Status::IncorrectDataParameter); } - let key = self.state.persistent(&mut self.trussed).state.keys.management_key; + let key = self + .state + .persistent(&mut self.trussed) + .state + .keys + .management_key; let challenge = syscall!(self.trussed.random_bytes(8)).bytes; - let command_cache = state::AuthenticateManagement { challenge: challenge[..].try_into().unwrap() }; - self.state.runtime.command_cache = Some(state::CommandCache::AuthenticateManagement(command_cache)); + let command_cache = state::AuthenticateManagement { + challenge: challenge[..].try_into().unwrap(), + }; + self.state.runtime.command_cache = + Some(state::CommandCache::AuthenticateManagement(command_cache)); let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, &challenge)).ciphertext; @@ -531,7 +559,6 @@ where .unwrap(); Ok(()) - } //fn change_reference_data(&mut self, command: &Command) -> Result { @@ -617,7 +644,6 @@ where // return Ok(()); // } - // Err(Status::KeyReferenceNotFound) //} @@ -682,8 +708,11 @@ where // } //} - pub fn generate_asymmetric_keypair(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { + pub fn generate_asymmetric_keypair( + &mut self, + command: &iso7816::Command, + reply: &mut Data, + ) -> Result { if !self.state.runtime.app_security_status.management_verified { return Err(Status::SecurityStatusNotSatisfied); } @@ -721,23 +750,25 @@ where // TODO: iterate on this, don't expect tags.. let input = derp::Input::from(&command.data()); // let (mechanism, parameter) = input.read_all(derp::Error::Read, |input| { - let (mechanism, _pin_policy, _touch_policy) = input.read_all(derp::Error::Read, |input| { - derp::nested(input, 0xac, |input| { - let mechanism = derp::expect_tag_and_get_value(input, 0x80)?; - // let parameter = derp::expect_tag_and_get_value(input, 0x81)?; - let pin_policy = derp::expect_tag_and_get_value(input, 0xaa)?; - let touch_policy = derp::expect_tag_and_get_value(input, 0xab)?; - // Ok((mechanism.as_slice_less_safe(), parameter.as_slice_less_safe())) - Ok(( - mechanism.as_slice_less_safe(), - pin_policy.as_slice_less_safe(), - touch_policy.as_slice_less_safe(), - )) + let (mechanism, _pin_policy, _touch_policy) = input + .read_all(derp::Error::Read, |input| { + derp::nested(input, 0xac, |input| { + let mechanism = derp::expect_tag_and_get_value(input, 0x80)?; + // let parameter = derp::expect_tag_and_get_value(input, 0x81)?; + let pin_policy = derp::expect_tag_and_get_value(input, 0xaa)?; + let touch_policy = derp::expect_tag_and_get_value(input, 0xab)?; + // Ok((mechanism.as_slice_less_safe(), parameter.as_slice_less_safe())) + Ok(( + mechanism.as_slice_less_safe(), + pin_policy.as_slice_less_safe(), + touch_policy.as_slice_less_safe(), + )) + }) }) - }).map_err(|_e| { + .map_err(|_e| { info_now!("error parsing GenerateAsymmetricKeypair: {:?}", &_e); Status::IncorrectDataParameter - })?; + })?; // if mechanism != &[0x11] { // HA! patch in Ed255 @@ -747,16 +778,22 @@ where // ble policy - if let Some(key) = self.state.persistent(&mut self.trussed).state.keys.authentication_key { + if let Some(key) = self + .state + .persistent(&mut self.trussed) + .state + .keys + .authentication_key + { syscall!(self.trussed.delete(key)); } // let key = syscall!(self.trussed.generate_p256_private_key( // let key = syscall!(self.trussed.generate_p256_private_key( - let key = syscall!(self.trussed.generate_ed255_private_key( - trussed::types::Location::Internal, - )).key; - + let key = syscall!(self + .trussed + .generate_ed255_private_key(trussed::types::Location::Internal,)) + .key; // // TEMP // let mechanism = trussed::types::Mechanism::P256Prehashed; @@ -777,21 +814,26 @@ where // .signature; // blocking::dbg!(&signature); - self.state.persistent(&mut self.trussed).state.keys.authentication_key = Some(key); + self.state + .persistent(&mut self.trussed) + .state + .keys + .authentication_key = Some(key); self.state.persistent(&mut self.trussed).save(); // let public_key = syscall!(self.trussed.derive_p256_public_key( - let public_key = syscall!(self.trussed.derive_ed255_public_key( - key, - trussed::types::Location::Volatile, - )).key; + let public_key = syscall!(self + .trussed + .derive_ed255_public_key(key, trussed::types::Location::Volatile,)) + .key; let serialized_public_key = syscall!(self.trussed.serialize_key( // trussed::types::Mechanism::P256, trussed::types::Mechanism::Ed255, public_key.clone(), trussed::types::KeySerialization::Raw, - )).serialized_key; + )) + .serialized_key; // info_now!("supposed SEC1 pubkey, len {}: {:X?}", serialized_public_key.len(), &serialized_public_key); @@ -800,7 +842,9 @@ where let l2 = 32; let l1 = l2 + 2; - reply.extend_from_slice(&[0x7f, 0x49, l1, 0x86, l2]).unwrap(); + reply + .extend_from_slice(&[0x7f, 0x49, l1, 0x86, l2]) + .unwrap(); reply.extend_from_slice(&serialized_public_key).unwrap(); Ok(()) @@ -827,15 +871,17 @@ where // let input = derp::Input::from(&command.data()); - let (data_object, data) = input.read_all(derp::Error::Read, |input| { - let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; - let data = derp::expect_tag_and_get_value(input, 0x53)?; - Ok((data_object.as_slice_less_safe(), data.as_slice_less_safe())) - // }).unwrap(); - }).map_err(|_e| { + let (data_object, data) = input + .read_all(derp::Error::Read, |input| { + let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; + let data = derp::expect_tag_and_get_value(input, 0x53)?; + Ok((data_object.as_slice_less_safe(), data.as_slice_less_safe())) + // }).unwrap(); + }) + .map_err(|_e| { info_now!("error parsing PutData: {:?}", &_e); Status::IncorrectDataParameter - })?; + })?; // info_now!("PutData in {:?}: {:?}", data_object, data); @@ -858,7 +904,8 @@ where trussed::types::PathBuf::from(b"printed-information"), trussed::types::Message::from_slice(data).unwrap(), None, - )).map_err(|_| Status::NotEnoughMemory)?; + )) + .map_err(|_| Status::NotEnoughMemory)?; return Ok(()); } @@ -883,7 +930,8 @@ where trussed::types::PathBuf::from(b"authentication-key.x5c"), trussed::types::Message::from_slice(data).unwrap(), None, - )).map_err(|_| Status::NotEnoughMemory)?; + )) + .map_err(|_| Status::NotEnoughMemory)?; return Ok(Default::default()); } @@ -891,18 +939,19 @@ where Err(Status::IncorrectDataParameter) } + // match container { + // containers::Container::CardHolderUniqueIdentifier => + // piv_types::CardHolderUniqueIdentifier::default() + // .encode + // _ => todo!(), + // } + // todo!(); - // match container { - // containers::Container::CardHolderUniqueIdentifier => - // piv_types::CardHolderUniqueIdentifier::default() - // .encode - // _ => todo!(), - // } - // todo!(); - - fn get_data(&mut self, container: container::Container, reply: &mut Data) -> Result - { - + fn get_data( + &mut self, + container: container::Container, + reply: &mut Data, + ) -> Result { // TODO: check security status, else return Status::SecurityStatusNotSatisfied // Table 3, Part 1, SP 800-73-4 @@ -916,7 +965,7 @@ where } Container::BiometricInformationTemplatesGroupTemplate => { - return Err(Status::InstructionNotSupportedOrInvalid) + return Err(Status::InstructionNotSupportedOrInvalid); // todo!("biometric information template"), } @@ -967,26 +1016,27 @@ where // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); // reply.extend_from_slice(&data).ok(); // } - _ => return Err(Status::NotFound), } Ok(()) } - pub fn yubico_piv_extension(&mut self, command: &iso7816::Command, instruction: YubicoPivExtension, reply: &mut Data) -> Result - { + pub fn yubico_piv_extension( + &mut self, + command: &iso7816::Command, + instruction: YubicoPivExtension, + reply: &mut Data, + ) -> Result { info_now!("yubico extension: {:?}", &instruction); match instruction { YubicoPivExtension::GetSerial => { // make up a 4-byte serial - reply.extend_from_slice( - &[0x00, 0x52, 0xf7, 0x43]).ok(); + reply.extend_from_slice(&[0x00, 0x52, 0xf7, 0x43]).ok(); } YubicoPivExtension::GetVersion => { // make up a version, be >= 5.0.0 - reply.extend_from_slice( - &[0x06, 0x06, 0x06]).ok(); + reply.extend_from_slice(&[0x06, 0x06, 0x06]).ok(); } YubicoPivExtension::Attest => { @@ -997,10 +1047,11 @@ where let slot = command.p1; if slot == 0x9a { - reply.extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A).ok(); + reply + .extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A) + .ok(); } else { - - return Err(Status::FunctionNotSupported) + return Err(Status::FunctionNotSupported); } } @@ -1012,7 +1063,9 @@ where // TODO: find out what all needs resetting :) self.state.persistent(&mut self.trussed).reset_pin(); self.state.persistent(&mut self.trussed).reset_puk(); - self.state.persistent(&mut self.trussed).reset_management_key(); + self.state + .persistent(&mut self.trussed) + .reset_management_key(); self.state.runtime.app_security_status.pin_verified = false; self.state.runtime.app_security_status.puk_verified = false; self.state.runtime.app_security_status.management_verified = false; @@ -1020,13 +1073,14 @@ where try_syscall!(self.trussed.remove_file( trussed::types::Location::Internal, trussed::types::PathBuf::from(b"printed-information"), - )).ok(); + )) + .ok(); try_syscall!(self.trussed.remove_file( trussed::types::Location::Internal, trussed::types::PathBuf::from(b"authentication-key.x5c"), - )).ok(); - + )) + .ok(); } YubicoPivExtension::SetManagementKey => { @@ -1055,15 +1109,13 @@ where return Err(Status::IncorrectDataParameter); } let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); - self.state.persistent(&mut self.trussed).set_management_key(&new_management_key); - + self.state + .persistent(&mut self.trussed) + .set_management_key(&new_management_key); } _ => return Err(Status::FunctionNotSupported), } Ok(()) } - } - - diff --git a/src/piv_types.rs b/src/piv_types.rs index 11194a9..006da27 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -34,7 +34,7 @@ impl TryFrom<&[u8]> for Pin { Err(()) } } - _ => Err(()) + _ => Err(()), } } } @@ -103,45 +103,53 @@ impl Encodable for CryptographicAlgorithmTemplate<'_> { // '80' let cryptographic_algorithm_identifier_tag = flexiber::Tag::context(0); for alg in self.algorithms.iter() { - encoder.encode(&flexiber::TaggedSlice::from(cryptographic_algorithm_identifier_tag, &[*alg as _])?)?; + encoder.encode(&flexiber::TaggedSlice::from( + cryptographic_algorithm_identifier_tag, + &[*alg as _], + )?)?; } // '06' let object_identifier_tag = flexiber::Tag::universal(6); - encoder.encode(&flexiber::TaggedSlice::from(object_identifier_tag, &[0x00])?) + encoder.encode(&flexiber::TaggedSlice::from( + object_identifier_tag, + &[0x00], + )?) } } #[derive(Clone, Copy, Encodable, Eq, PartialEq)] pub struct CoexistentTagAllocationAuthorityTemplate<'l> { - #[tlv(application, primitive, number = "0xF")] // = 0x4F + #[tlv(application, primitive, number = "0xF")] // = 0x4F pub application_identifier: &'l [u8], } impl Default for CoexistentTagAllocationAuthorityTemplate<'static> { fn default() -> Self { - Self { application_identifier: crate::constants::NIST_RID } + Self { + application_identifier: crate::constants::NIST_RID, + } } } #[derive(Clone, Copy, Encodable, Eq, PartialEq)] -#[tlv(application, constructed, number = "0x1")] // = 0x61 +#[tlv(application, constructed, number = "0x1")] // = 0x61 pub struct ApplicationPropertyTemplate<'l> { /// Application identifier of application: PIX (without RID, with version) - #[tlv(application, primitive, number = "0xF")] // = 0x4F - aid: &'l[u8], + #[tlv(application, primitive, number = "0xF")] // = 0x4F + aid: &'l [u8], /// Text describing the application; e.g., for use on a man-machine interface. - #[tlv(application, primitive, number = "0x10")] // = 0x50 + #[tlv(application, primitive, number = "0x10")] // = 0x50 application_label: &'l [u8], /// Reference to the specification describing the application. - #[tlv(application, primitive, number = "0x50")] // = 0x5F50 + #[tlv(application, primitive, number = "0x50")] // = 0x5F50 application_url: &'l [u8], - #[tlv(context, constructed, number = "0xC")] // = 0xAC + #[tlv(context, constructed, number = "0xC")] // = 0xAC supported_cryptographic_algorithms: CryptographicAlgorithmTemplate<'l>, - #[tlv(application, constructed, number = "0x19")] // = 0x79 + #[tlv(application, constructed, number = "0x19")] // = 0x79 coexistent_tag_allocation_authority: CoexistentTagAllocationAuthorityTemplate<'l>, } @@ -158,7 +166,6 @@ impl Default for ApplicationPropertyTemplate<'static> { } impl<'a> ApplicationPropertyTemplate<'a> { - pub const fn with_application_label(self, application_label: &'a [u8]) -> Self { Self { aid: self.aid, @@ -179,18 +186,22 @@ impl<'a> ApplicationPropertyTemplate<'a> { } } - pub const fn with_supported_cryptographic_algorithms(self, supported_cryptographic_algorithms: &'a [Algorithms]) -> Self { + pub const fn with_supported_cryptographic_algorithms( + self, + supported_cryptographic_algorithms: &'a [Algorithms], + ) -> Self { Self { aid: self.aid, application_label: self.application_label, application_url: self.application_url, - supported_cryptographic_algorithms: CryptographicAlgorithmTemplate { algorithms: supported_cryptographic_algorithms}, + supported_cryptographic_algorithms: CryptographicAlgorithmTemplate { + algorithms: supported_cryptographic_algorithms, + }, coexistent_tag_allocation_authority: self.coexistent_tag_allocation_authority, } } } - /// TODO: This should be an enum of sorts, maybe. /// /// The data objects that appear in the dynamic authentication template (tag '7C') in the data field @@ -201,40 +212,52 @@ impl<'a> ApplicationPropertyTemplate<'a> { /// - '80 00' Returns '80 TL ' (as per definition) /// - '81 00' Returns '81 TL ' (as per external authenticate example) #[derive(Clone, Copy, Default, Encodable, Eq, PartialEq)] -#[tlv(application, constructed, number = "0x1C")] // = 0x7C +#[tlv(application, constructed, number = "0x1C")] // = 0x7C pub struct DynamicAuthenticationTemplate<'l> { /// The Witness (tag '80') contains encrypted data (unrevealed fact). /// This data is decrypted by the card. #[tlv(simple = "0x80")] - witness: Option<&'l[u8]>, + witness: Option<&'l [u8]>, /// The Challenge (tag '81') contains clear data (byte sequence), /// which is encrypted by the card. #[tlv(simple = "0x81")] - challenge: Option<&'l[u8]>, + challenge: Option<&'l [u8]>, /// The Response (tag '82') contains either the decrypted data from tag '80' /// or the encrypted data from tag '81'. #[tlv(simple = "0x82")] - response: Option<&'l[u8]>, + response: Option<&'l [u8]>, /// Not documented in SP-800-73-4 #[tlv(simple = "0x85")] - exponentiation: Option<&'l[u8]>, + exponentiation: Option<&'l [u8]>, } impl<'a> DynamicAuthenticationTemplate<'a> { pub fn with_challenge(challenge: &'a [u8]) -> Self { - Self { challenge: Some(challenge), ..Default::default() } + Self { + challenge: Some(challenge), + ..Default::default() + } } pub fn with_exponentiation(exponentiation: &'a [u8]) -> Self { - Self { exponentiation: Some(exponentiation), ..Default::default() } + Self { + exponentiation: Some(exponentiation), + ..Default::default() + } } pub fn with_response(response: &'a [u8]) -> Self { - Self { response: Some(response), ..Default::default() } + Self { + response: Some(response), + ..Default::default() + } } pub fn with_witness(witness: &'a [u8]) -> Self { - Self { witness: Some(witness), ..Default::default() } + Self { + witness: Some(witness), + ..Default::default() + } } } @@ -246,7 +269,7 @@ impl<'a> DynamicAuthenticationTemplate<'a> { // pivy: https://git.io/JfzBo // https://www.idmanagement.gov/wp-content/uploads/sites/1171/uploads/TIG_SCEPACS_v2.3.pdf #[derive(Clone, Copy, Encodable, Eq, PartialEq)] -#[tlv(application, primitive, number = "0x13")] // = 0x53 +#[tlv(application, primitive, number = "0x13")] // = 0x53 pub struct CardHolderUniqueIdentifier<'l> { #[tlv(simple = "0x30")] // pivy: 26B, TIG: 25B @@ -269,7 +292,6 @@ pub struct CardHolderUniqueIdentifier<'l> { // #[tlv(simple = "0x36")] // // 16B, like guid // cardholder_uuid: Option<&'l [u8]>, - #[tlv(simple = "0x3E")] issuer_asymmetric_signature: &'l [u8], @@ -384,4 +406,3 @@ pub struct DiscoveryObject { #[tlv(slice, application, number = "0x2f")] pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, } - diff --git a/src/state.rs b/src/state.rs index 4ca3974..198e268 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,10 +1,9 @@ use core::convert::{TryFrom, TryInto}; use trussed::{ - block, + block, syscall, try_syscall, + types::{KeyId, Location, PathBuf}, Client as TrussedClient, - syscall, try_syscall, - types::{KeyId, PathBuf, Location}, }; use crate::constants::*; @@ -37,7 +36,10 @@ pub struct Slot { impl Default for Slot { fn default() -> Self { - Self { key: None, pin_policy: PinPolicy::Once, /*touch_policy: TouchPolicy::Never*/ } + Self { + key: None, + pin_policy: PinPolicy::Once, /*touch_policy: TouchPolicy::Never*/ + } } } @@ -46,10 +48,15 @@ impl Slot { use SlotName::*; match name { // Management => Slot { pin_policy: PinPolicy::Never, ..Default::default() }, - Signature => Slot { pin_policy: PinPolicy::Always, ..Default::default() }, - Pinless => Slot { pin_policy: PinPolicy::Never, ..Default::default() }, + Signature => Slot { + pin_policy: PinPolicy::Always, + ..Default::default() + }, + Pinless => Slot { + pin_policy: PinPolicy::Never, + ..Default::default() + }, _ => Default::default(), - } } } @@ -68,9 +75,9 @@ impl core::convert::TryFrom for RetiredSlotIndex { } pub enum SlotName { Identity, - Management, // Personalization? Administration? + Management, // Personalization? Administration? Signature, - Decryption, // Management after all? + Decryption, // Management after all? Pinless, Retired(RetiredSlotIndex), Attestation, @@ -78,8 +85,8 @@ pub enum SlotName { impl SlotName { pub fn default_pin_policy(&self) -> PinPolicy { - use SlotName::*; use PinPolicy::*; + use SlotName::*; match *self { Signature => Always, Pinless | Management | Attestation => Never, @@ -88,7 +95,10 @@ impl SlotName { } pub fn default_slot(&self) -> Slot { - Slot { key: None, pin_policy: self.default_pin_policy() } + Slot { + key: None, + pin_policy: self.default_pin_policy(), + } } pub fn reference(&self) -> u8 { @@ -137,7 +147,6 @@ pub struct Keys { pub retired_keys: [Option; 20], } - #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct State { pub runtime: Runtime, @@ -156,8 +165,8 @@ impl State { // TODO: it is really not good to overwrite user data on failure to decode old state. // To fix this, need a flag to detect if we're "fresh", and/or initialize state in factory. pub fn persistent<'t, T>(&mut self, trussed: &'t mut T) -> Persistent<'t, T> - where T: TrussedClient - + trussed::client::Tdes + where + T: TrussedClient + trussed::client::Tdes, { Persistent::load_or_initialize(trussed) } @@ -237,7 +246,6 @@ impl AsRef for Persistent<'_, T> { pub struct Runtime { // aid: Option< // consecutive_pin_mismatches: u8, - pub global_security_status: GlobalSecurityStatus, // pub currently_selected_application: SelectableAid, pub app_security_status: AppSecurityStatus, @@ -299,8 +307,7 @@ pub struct Runtime { // } #[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct GlobalSecurityStatus { -} +pub struct GlobalSecurityStatus {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum SecurityStatus { @@ -328,10 +335,8 @@ pub enum CommandCache { AuthenticateManagement(AuthenticateManagement), } - #[derive(Clone, Debug, Eq, PartialEq)] -pub struct GetData { -} +pub struct GetData {} #[derive(Clone, Debug, Eq, PartialEq)] pub struct AuthenticateManagement { @@ -342,7 +347,6 @@ impl<'t, T> Persistent<'t, T> where T: TrussedClient + trussed::client::Tdes, { - pub const PIN_RETRIES_DEFAULT: u8 = 3; // hmm...! pub const PUK_RETRIES_DEFAULT: u8 = 5; @@ -444,10 +448,10 @@ where pub fn set_management_key(&mut self, management_key: &[u8; 24]) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( - let new_management_key = syscall!(self.trussed.unsafe_inject_shared_key( - management_key, - trussed::types::Location::Internal, - )).key; + let new_management_key = syscall!(self + .trussed + .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) + .key; let old_management_key = self.state.keys.management_key; self.state.keys.management_key = new_management_key; self.save(); @@ -459,7 +463,8 @@ where let management_key = syscall!(trussed.unsafe_inject_shared_key( YUBICO_DEFAULT_MANAGEMENT_KEY, trussed::types::Location::Internal, - )).key; + )) + .key; let mut guid: [u8; 16] = syscall!(trussed.random_bytes(16)) .bytes @@ -489,21 +494,21 @@ where puk: Puk::try_from(Self::DEFAULT_PUK).unwrap(), timestamp: 0, guid, - } + }, }; state.save(); state } pub fn load(trussed: &'t mut T) -> Result { - let data = block!(trussed.read_file( - Location::Internal, - PathBuf::from(Self::FILENAME), - ).unwrap() - ).map_err(|e| { + let data = block!(trussed + .read_file(Location::Internal, PathBuf::from(Self::FILENAME),) + .unwrap()) + .map_err(|e| { info!("loading error: {:?}", &e); drop(e) - })?.data; + })? + .data; let previous_state: PersistentState = trussed::cbor_deserialize(&data).map_err(|e| { info!("cbor deser error: {:?}", e); @@ -511,12 +516,16 @@ where drop(e) })?; // horrible deser bug to forget Ok here :) - Ok(Self { trussed, state: previous_state }) + Ok(Self { + trussed, + state: previous_state, + }) } pub fn load_or_initialize(trussed: &'t mut T) -> Self { // todo: can't seem to combine load + initialize without code repetition - let data = try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); + let data = + try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); if let Ok(data) = data { let previous_state = trussed::cbor_deserialize(&data.data).map_err(|e| { info!("cbor deser error: {:?}", e); @@ -524,8 +533,8 @@ where drop(e) }); if let Ok(state) = previous_state { - // horrible deser bug to forget Ok here :) - return Self { trussed, state } + // horrible deser bug to forget Ok here :) + return Self { trussed, state }; } } @@ -548,6 +557,4 @@ where self.save(); self.state.timestamp } - } - diff --git a/tests/get_data.rs b/tests/get_data.rs index cbdd046..8e669a3 100644 --- a/tests/get_data.rs +++ b/tests/get_data.rs @@ -9,7 +9,7 @@ fn get_data() { // let cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); // let cmd = cmd!("00 f8 00 00"); -// // without PIN, no key generation + // // without PIN, no key generation setup::piv(|piv| { // ykGetSerial diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 293c9cf..c53b0dd 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,5 +1,6 @@ -trussed::platform!(Platform, - R: rand_core::OsRng,//chacha20::ChaCha8Rng, +trussed::platform!( + Platform, + R: rand_core::OsRng, //chacha20::ChaCha8Rng, S: store::Store, UI: ui::UserInterface, ); @@ -8,15 +9,21 @@ const COMMAND_SIZE: usize = 3072; #[macro_export] macro_rules! cmd { - ($tt:tt) => { iso7816::Command::<3072>::try_from(&hex_literal::hex!($tt)).unwrap() } + ($tt:tt) => { + iso7816::Command::<3072>::try_from(&hex_literal::hex!($tt)).unwrap() + }; } pub type Piv<'service> = piv_authenticator::Authenticator< - trussed::ClientImplementation<&'service mut trussed::service::Service>, COMMAND_SIZE>; + trussed::ClientImplementation<&'service mut trussed::service::Service>, + COMMAND_SIZE, +>; pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { use trussed::Interchange as _; - unsafe { trussed::pipe::TrussedInterchange::reset_claims(); } + unsafe { + trussed::pipe::TrussedInterchange::reset_claims(); + } let trussed_platform = init_platform(); let mut trussed_service = trussed::service::Service::new(trussed_platform); let client_id = "test"; @@ -31,7 +38,7 @@ pub fn init_platform() -> Platform { store::InternalStorage::new(), store::ExternalStorage::new(), store::VolatileStorage::new(), - ); + ); let ui = ui::UserInterface::new(); let platform = Platform::new(rng, store, ui); @@ -41,28 +48,48 @@ pub fn init_platform() -> Platform { pub mod ui { use trussed::platform::{consent, reboot, ui}; - pub struct UserInterface { start_time: std::time::Instant } + pub struct UserInterface { + start_time: std::time::Instant, + } - impl UserInterface { pub fn new() -> Self { Self { start_time: std::time::Instant::now() } } } + impl UserInterface { + pub fn new() -> Self { + Self { + start_time: std::time::Instant::now(), + } + } + } impl trussed::platform::UserInterface for UserInterface { - fn check_user_presence(&mut self) -> consent::Level { consent::Level::Normal } + fn check_user_presence(&mut self) -> consent::Level { + consent::Level::Normal + } fn set_status(&mut self, _status: ui::Status) {} fn refresh(&mut self) {} - fn uptime(&mut self) -> core::time::Duration { self.start_time.elapsed() } - fn reboot(&mut self, _to: reboot::To) -> ! { loop { continue; } } + fn uptime(&mut self) -> core::time::Duration { + self.start_time.elapsed() + } + fn reboot(&mut self, _to: reboot::To) -> ! { + loop { + continue; + } + } } } pub mod store { - use littlefs2::{const_ram_storage, consts, fs::{Allocation, Filesystem}}; + use littlefs2::{ + const_ram_storage, consts, + fs::{Allocation, Filesystem}, + }; use trussed::types::{LfsResult, LfsStorage}; const_ram_storage!(InternalStorage, 8192); const_ram_storage!(ExternalStorage, 8192); const_ram_storage!(VolatileStorage, 8192); - trussed::store!(Store, + trussed::store!( + Store, Internal: InternalStorage, External: ExternalStorage, Volatile: VolatileStorage From 53076d70d735da7d046b5494962ca20671ee64f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 24 Oct 2022 16:10:13 +0200 Subject: [PATCH 02/59] Update dependencies --- Cargo.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fd7d994..4c9e965 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,19 +11,19 @@ documentation = "https://docs.rs/piv-authenticator" [dependencies] apdu-dispatch = { version = "0.1", optional = true } -delog = "0.1.0" +delog = "0.1.6" flexiber = { version = "0.1", features = ["derive", "heapless"] } heapless = "0.7" hex-literal = "0.3" -interchange = "0.2.0" +interchange = "0.2.2" iso7816 = "0.1" serde = { version = "1", default-features = false } trussed = { git = "https://github.com/trussed-dev/trussed" } # trussed = { path = "../../../trussed" } -untrusted = "0.7" +untrusted = "0.9" [dev-dependencies] -littlefs2 = "0.3.1" +littlefs2 = "0.3.2" rand_core = { version = "0.6", features = ["getrandom"] } [features] From ce939ee714d4ea1caf68170b4a4a6e93155b3d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 24 Oct 2022 16:32:08 +0200 Subject: [PATCH 03/59] Fix clippy warnings --- src/constants.rs | 14 +++++----- src/lib.rs | 38 +++++++++++++++------------- src/piv_types.rs | 4 +-- src/state.rs | 20 +++++++-------- tests/generate_asymmetric_keypair.rs | 6 ++--- tests/get_data.rs | 2 +- tests/put_data.rs | 2 +- tests/setup/mod.rs | 7 +++-- 8 files changed, 46 insertions(+), 47 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 2452d6d..84ceb4b 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -301,7 +301,7 @@ impl core::convert::TryFrom for YubicoPivExtension { } } -pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &'static [u8; 351] = &[ +pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &[u8; 351] = &[ 0x53, 0x82, 0x01, 0x5b, 0x70, 0x82, 0x01, 0x52, 0x30, 0x82, 0x01, 0x4e, 0x30, 0x81, 0xf5, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0x8e, 0x46, 0x32, 0xd8, 0xf0, 0xc1, 0xf7, 0xc1, 0x4d, 0x67, 0xd1, 0x4b, 0xfd, 0xe3, 0x64, 0x8e, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, @@ -326,7 +326,7 @@ pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &'static [u8; 351] = &[ 0x93, 0x33, 0xb8, 0x47, 0xa9, 0x73, 0xc2, 0x82, 0x92, 0x3e, 0x71, 0x01, 0x00, 0xfe, 0x00, ]; -pub const YUBICO_ATTESTATION_CERTIFICATE: &'static [u8; 754] = &[ +pub const YUBICO_ATTESTATION_CERTIFICATE: &[u8; 754] = &[ 0x53, 0x82, 0x02, 0xee, 0x70, 0x82, 0x02, 0xea, 0x30, 0x82, 0x02, 0xe6, 0x30, 0x82, 0x01, 0xce, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0xa4, 0x85, 0x22, 0xaa, 0x34, 0xaf, 0xae, 0x4f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, @@ -377,7 +377,7 @@ pub const YUBICO_ATTESTATION_CERTIFICATE: &'static [u8; 754] = &[ 0xa0, 0x85, ]; -pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &'static [u8; 584] = &[ +pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &[u8; 584] = &[ 0x30, 0x82, 0x02, 0x44, 0x30, 0x82, 0x01, 0x2c, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0xc6, 0x36, 0xe7, 0xb3, 0xa5, 0xa5, 0xa4, 0x98, 0x5d, 0x13, 0x6e, 0x43, 0x36, 0x2d, 0x13, 0xf7, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, @@ -416,15 +416,15 @@ pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &'static [u8; 584] = &[ 0x76, 0xa7, 0x05, 0xe1, 0x4c, 0x45, 0x55, 0x14, 0xff, 0x10, 0x10, 0x89, 0x69, 0x6a, 0x13, 0x3d, 0x89, 0xf2, 0xca, 0xfd, 0x14, 0x9a, 0xc4, 0xd0, ]; -// pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = b"123456781234567812345678"; -pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = &[ +// pub const YUBICO_DEFAULT_MANAGEMENT_KEY: & [u8; 24] = b"123456781234567812345678"; +pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &[u8; 24] = &[ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, ]; // stolen from le yubico -pub const DISCOVERY_OBJECT: &'static [u8; 20] = +pub const DISCOVERY_OBJECT: &[u8; 20] = b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; // import secrets; secrets.token_bytes(16) -pub const GUID: &'static [u8; 16] = b"\x0c\x92\xc9\x04\xd0\xdeL\xd9\xf6\xd1\xa2\x9fE3\xca\xeb"; +pub const GUID: &[u8; 16] = b"\x0c\x92\xc9\x04\xd0\xdeL\xd9\xf6\xd1\xa2\x9fE3\xca\xeb"; diff --git a/src/lib.rs b/src/lib.rs index b2ded31..00d2f75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,7 +107,7 @@ where self.state.runtime.chained_command = None; entire_command } else { - return Ok(Default::default()); + return Ok(()); } } @@ -117,7 +117,7 @@ where command.clone() } else { self.state.runtime.chained_command = Some(command.clone()); - return Ok(Default::default()); + return Ok(()); } } }; @@ -174,13 +174,13 @@ where return Err(Status::FunctionNotSupported); } if self.state.runtime.app_security_status.pin_verified { - return Ok(()); + Ok(()) } else { let retries = self .state .persistent(&mut self.trussed) .remaining_pin_retries(); - return Err(Status::RemainingRetries(retries)); + Err(Status::RemainingRetries(retries)) } } } @@ -209,7 +209,7 @@ where persistent_state.reset_consecutive_pin_mismatches(); persistent_state.set_pin(new_pin); self.state.runtime.app_security_status.pin_verified = true; - return Ok(Default::default()); + Ok(()) } pub fn change_puk(&mut self, old_puk: commands::Puk, new_puk: commands::Puk) -> Result { @@ -227,7 +227,7 @@ where persistent_state.reset_consecutive_puk_mismatches(); persistent_state.set_puk(new_puk); self.state.runtime.app_security_status.puk_verified = true; - return Ok(Default::default()); + Ok(()) } // pub fn old_respond(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result { @@ -379,10 +379,12 @@ where panic!("unhandled >1B lengths"); } if data[1] == 0x81 { - data[2] as usize; + // FIXME: Proper length parsing and avoid panics + // data[2] as usize; data = &data[3..]; } else { - data[1] as usize; // ~158 for ssh ed25519 signatures (which have a ~150B commitment) + // FIXME: Proper length parsing and avoid panics + // data[1] as usize; // ~158 for ssh ed25519 signatures (which have a ~150B commitment) data = &data[2..]; }; @@ -492,7 +494,7 @@ where // no retries ;) self.state.runtime.command_cache = None; - if &our_challenge != response { + if our_challenge != response { debug_now!("{:?}", &our_challenge); debug_now!("{:?}", &response); return Err(Status::IncorrectDataParameter); @@ -502,7 +504,7 @@ where // B) encrypt their challenge let (header, challenge) = data.split_at(2); - if header != &[0x81, 0x08] { + if header != [0x81, 0x08] { return Err(Status::IncorrectDataParameter); } @@ -748,7 +750,7 @@ where // } // TODO: iterate on this, don't expect tags.. - let input = derp::Input::from(&command.data()); + let input = derp::Input::from(command.data()); // let (mechanism, parameter) = input.read_all(derp::Error::Read, |input| { let (mechanism, _pin_policy, _touch_policy) = input .read_all(derp::Error::Read, |input| { @@ -772,7 +774,7 @@ where // if mechanism != &[0x11] { // HA! patch in Ed255 - if mechanism != &[0x22] { + if mechanism != [0x22] { return Err(Status::InstructionNotSupportedOrInvalid); } @@ -830,7 +832,7 @@ where let serialized_public_key = syscall!(self.trussed.serialize_key( // trussed::types::Mechanism::P256, trussed::types::Mechanism::Ed255, - public_key.clone(), + public_key, trussed::types::KeySerialization::Raw, )) .serialized_key; @@ -870,7 +872,7 @@ where // 88 1A 89 18 AA 81 D5 48 A5 EC 26 01 60 BA 06 F6 EC 3B B6 05 00 2E B6 3D 4B 28 7F 86 // - let input = derp::Input::from(&command.data()); + let input = derp::Input::from(command.data()); let (data_object, data) = input .read_all(derp::Error::Read, |input| { let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; @@ -885,7 +887,7 @@ where // info_now!("PutData in {:?}: {:?}", data_object, data); - if data_object == &[0x5f, 0xc1, 0x09] { + if data_object == [0x5f, 0xc1, 0x09] { // "Printed Information", supposedly // Yubico uses this to store its "Metadata" // @@ -910,7 +912,7 @@ where return Ok(()); } - if data_object == &[0x5f, 0xc1, 0x05] { + if data_object == [0x5f, 0xc1, 0x05] { // "X.509 Certificate for PIV Authentication", supposedly // IOW, the cert for "authentication key" // Yubico uses this to store its "Metadata" @@ -933,7 +935,7 @@ where )) .map_err(|_| Status::NotEnoughMemory)?; - return Ok(Default::default()); + return Ok(()); } Err(Status::IncorrectDataParameter) @@ -1105,7 +1107,7 @@ where return Err(Status::IncorrectDataParameter); } let (prefix, new_management_key) = data.split_at(3); - if prefix != &[0x03, 0x9b, 0x18] { + if prefix != [0x03, 0x9b, 0x18] { return Err(Status::IncorrectDataParameter); } let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); diff --git a/src/piv_types.rs b/src/piv_types.rs index 006da27..65d72fd 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -24,9 +24,9 @@ impl TryFrom<&[u8]> for Pin { match unpadded_pin.len() { len @ 6..=8 => { let verifier = if cfg!(feature = "strict-pin") { - |&byte| byte >= b'0' && byte <= b'9' + |&byte| (b'0'..=b'9').contains(&byte) } else { - |&byte| byte >= 32 && byte <= 127 + |&byte| (32..=127).contains(&byte) }; if unpadded_pin.iter().all(verifier) { Ok(Pin { padded_pin, len }) diff --git a/src/state.rs b/src/state.rs index 198e268..cdcd5d6 100644 --- a/src/state.rs +++ b/src/state.rs @@ -66,7 +66,7 @@ pub struct RetiredSlotIndex(u8); impl core::convert::TryFrom for RetiredSlotIndex { type Error = u8; fn try_from(i: u8) -> core::result::Result { - if 1 <= i && i <= 20 { + if (1..=20).contains(&i) { Ok(Self(i)) } else { Err(i) @@ -477,7 +477,7 @@ where let keys = Keys { authentication_key: None, - management_key: management_key, + management_key, signature_key: None, encryption_key: None, pinless_authentication_key: None, @@ -500,20 +500,19 @@ where state } + #[allow(clippy::result_unit_err)] pub fn load(trussed: &'t mut T) -> Result { let data = block!(trussed .read_file(Location::Internal, PathBuf::from(Self::FILENAME),) .unwrap()) - .map_err(|e| { - info!("loading error: {:?}", &e); - drop(e) + .map_err(|_err| { + info!("loading error: {_err:?}"); })? .data; - let previous_state: PersistentState = trussed::cbor_deserialize(&data).map_err(|e| { - info!("cbor deser error: {:?}", e); + let previous_state: PersistentState = trussed::cbor_deserialize(&data).map_err(|_err| { + info!("cbor deser error: {_err:?}"); info!("data: {:X?}", &data); - drop(e) })?; // horrible deser bug to forget Ok here :) Ok(Self { @@ -527,10 +526,9 @@ where let data = try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); if let Ok(data) = data { - let previous_state = trussed::cbor_deserialize(&data.data).map_err(|e| { - info!("cbor deser error: {:?}", e); + let previous_state = trussed::cbor_deserialize(&data.data).map_err(|_err| { + info!("cbor deser error: {_err:?}", e); info!("data: {:X?}", &data); - drop(e) }); if let Ok(state) = previous_state { // horrible deser bug to forget Ok here :) diff --git a/tests/generate_asymmetric_keypair.rs b/tests/generate_asymmetric_keypair.rs index bfd8817..877ceea 100644 --- a/tests/generate_asymmetric_keypair.rs +++ b/tests/generate_asymmetric_keypair.rs @@ -1,6 +1,6 @@ mod setup; -use iso7816::Status::*; + // example: 00 47 00 9A 0B // AC 09 @@ -13,10 +13,10 @@ use iso7816::Status::*; #[test] fn gen_keypair() { - let cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); + let _cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); // without PIN, no key generation - setup::piv(|piv| { + setup::piv(|_piv| { // not currently implemented // // let mut response = iso7816::Data::<16>::default(); diff --git a/tests/get_data.rs b/tests/get_data.rs index 8e669a3..7164901 100644 --- a/tests/get_data.rs +++ b/tests/get_data.rs @@ -10,7 +10,7 @@ fn get_data() { // let cmd = cmd!("00 f8 00 00"); // // without PIN, no key generation - setup::piv(|piv| { + setup::piv(|_piv| { // ykGetSerial // println!("{}", hex_str!(&piv.respond(&cmd!("00 f8 00 00")).unwrap())); diff --git a/tests/put_data.rs b/tests/put_data.rs index ee6e034..dcfbaa5 100644 --- a/tests/put_data.rs +++ b/tests/put_data.rs @@ -16,7 +16,7 @@ mod setup; #[test] fn put_data() { - setup::piv(|piv| { + setup::piv(|_piv| { // let mut response = iso7816::Data::<16>::default(); // piv.respond(&cmd!( diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index c53b0dd..edea91c 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -41,9 +41,9 @@ pub fn init_platform() -> Platform { ); let ui = ui::UserInterface::new(); - let platform = Platform::new(rng, store, ui); + - platform + Platform::new(rng, store, ui) } pub mod ui { @@ -79,8 +79,7 @@ pub mod ui { pub mod store { use littlefs2::{ - const_ram_storage, consts, - fs::{Allocation, Filesystem}, + const_ram_storage, }; use trussed::types::{LfsResult, LfsStorage}; From 1a65eb8e11288e2b26ef41560ff6f3f975ee2981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 24 Oct 2022 16:44:46 +0200 Subject: [PATCH 04/59] Use latest trussed commit --- Cargo.toml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4c9e965..14dd9ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,8 +18,7 @@ hex-literal = "0.3" interchange = "0.2.2" iso7816 = "0.1" serde = { version = "1", default-features = false } -trussed = { git = "https://github.com/trussed-dev/trussed" } -# trussed = { path = "../../../trussed" } +trussed = "0.1" untrusted = "0.9" [dev-dependencies] @@ -36,3 +35,6 @@ log-info = [] log-debug = [] log-warn = [] log-error = [] + +[patch.crates-io] +trussed = { git = "https://github.com/trussed-dev/trussed", rev = "28478f8abed11d78c51e6a6a32326821ed61957a"} From 65fd2b42c85a614e35e0451c65ee05e9471a224a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 24 Oct 2022 17:03:21 +0200 Subject: [PATCH 05/59] Use trussed's virt module --- Cargo.toml | 1 + tests/setup/mod.rs | 91 ++++------------------------------------------ 2 files changed, 8 insertions(+), 84 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 14dd9ce..c04584f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ untrusted = "0.9" [dev-dependencies] littlefs2 = "0.3.2" rand_core = { version = "0.6", features = ["getrandom"] } +trussed = { version = "0.1.0", features = ["virt"] } [features] default = [] diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index edea91c..2f081af 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,10 +1,3 @@ -trussed::platform!( - Platform, - R: rand_core::OsRng, //chacha20::ChaCha8Rng, - S: store::Store, - UI: ui::UserInterface, -); - const COMMAND_SIZE: usize = 3072; #[macro_export] @@ -14,83 +7,13 @@ macro_rules! cmd { }; } -pub type Piv<'service> = piv_authenticator::Authenticator< - trussed::ClientImplementation<&'service mut trussed::service::Service>, - COMMAND_SIZE, ->; - -pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { - use trussed::Interchange as _; - unsafe { - trussed::pipe::TrussedInterchange::reset_claims(); - } - let trussed_platform = init_platform(); - let mut trussed_service = trussed::service::Service::new(trussed_platform); - let client_id = "test"; - let trussed_client = trussed_service.try_as_new_client(client_id).unwrap(); - let mut piv_app = piv_authenticator::Authenticator::new(trussed_client); - test(&mut piv_app) -} - -pub fn init_platform() -> Platform { - let rng = rand_core::OsRng; - let store = store::Store::format( - store::InternalStorage::new(), - store::ExternalStorage::new(), - store::VolatileStorage::new(), - ); - let ui = ui::UserInterface::new(); - - - - Platform::new(rng, store, ui) -} +use trussed::virt::{Client, Ram}; -pub mod ui { - use trussed::platform::{consent, reboot, ui}; - pub struct UserInterface { - start_time: std::time::Instant, - } +pub type Piv<'service> = piv_authenticator::Authenticator, COMMAND_SIZE>; - impl UserInterface { - pub fn new() -> Self { - Self { - start_time: std::time::Instant::now(), - } - } - } - - impl trussed::platform::UserInterface for UserInterface { - fn check_user_presence(&mut self) -> consent::Level { - consent::Level::Normal - } - fn set_status(&mut self, _status: ui::Status) {} - fn refresh(&mut self) {} - fn uptime(&mut self) -> core::time::Duration { - self.start_time.elapsed() - } - fn reboot(&mut self, _to: reboot::To) -> ! { - loop { - continue; - } - } - } -} - -pub mod store { - use littlefs2::{ - const_ram_storage, - }; - use trussed::types::{LfsResult, LfsStorage}; - - const_ram_storage!(InternalStorage, 8192); - const_ram_storage!(ExternalStorage, 8192); - const_ram_storage!(VolatileStorage, 8192); - - trussed::store!( - Store, - Internal: InternalStorage, - External: ExternalStorage, - Volatile: VolatileStorage - ); +pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { + trussed::virt::with_ram_client("test", |client| { + let mut piv_app = piv_authenticator::Authenticator::new(client); + test(&mut piv_app) + }) } From 89d8410324fe17f0a5b9e6d5e4f6ad87ba0a5fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 25 Oct 2022 09:49:12 +0200 Subject: [PATCH 06/59] Add vsmartcard example --- Cargo.toml | 13 +++- examples/virtual.rs | 25 +++++++ src/commands.rs | 2 +- src/lib.rs | 56 +++++++++------- src/state.rs | 4 +- src/vpicc.rs | 155 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 224 insertions(+), 31 deletions(-) create mode 100644 examples/virtual.rs create mode 100644 src/vpicc.rs diff --git a/Cargo.toml b/Cargo.toml index c04584f..faa1507 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,16 +2,18 @@ name = "piv-authenticator" version = "0.0.0-unreleased" authors = ["Nicolas Stalder "] -edition = "2018" +edition = "2021" license = "Apache-2.0 OR MIT" repository = "https://github.com/solokeys/piv-authenticator" documentation = "https://docs.rs/piv-authenticator" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[[example]] +name = "virtual" +required-features = ["virtual"] [dependencies] apdu-dispatch = { version = "0.1", optional = true } -delog = "0.1.6" +delog = { version = "0.1.5", optional = true } flexiber = { version = "0.1", features = ["derive", "heapless"] } heapless = "0.7" hex-literal = "0.3" @@ -20,15 +22,20 @@ iso7816 = "0.1" serde = { version = "1", default-features = false } trussed = "0.1" untrusted = "0.9" +vpicc = { version = "0.1.0", optional = true } +log = "0.4" [dev-dependencies] littlefs2 = "0.3.2" rand_core = { version = "0.6", features = ["getrandom"] } trussed = { version = "0.1.0", features = ["virt"] } +env_logger = "0.9" [features] default = [] strict-pin = [] +std = [] +virtual = ["std", "vpicc","trussed/virt"] log-all = [] log-none = [] diff --git a/examples/virtual.rs b/examples/virtual.rs new file mode 100644 index 0000000..b454c4f --- /dev/null +++ b/examples/virtual.rs @@ -0,0 +1,25 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: CC0-1.0 + +// To use this, make sure that you have vpcd from vsmartcard installed and configured (e. g. +// install vsmartcard-vpcd on Debian). You might have to restart your pcscd, e. g. +// `systemctl restart pcscd pcscd.socket`. +// +// Now you should be able to see the card in `pcsc_scan` and talk to it with `piv-tool`r +// +// Set `RUST_LOG=piv_authenticator::card=info` to see the executed commands. + +// TODO: add CLI + +fn main() { + env_logger::init(); + + trussed::virt::with_ram_client("opcard", |client| { + let card = piv_authenticator::Authenticator::new(client); + let mut virtual_card = piv_authenticator::vpicc::VirtualCard::new(card); + let vpicc = vpicc::connect().expect("failed to connect to vpicc"); + vpicc + .run(&mut virtual_card) + .expect("failed to run virtual smartcard"); + }); +} diff --git a/src/commands.rs b/src/commands.rs index 109d9a3..b380583 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -83,7 +83,7 @@ impl TryFrom<&[u8]> for GetData { .try_into() .map_err(|_| Status::IncorrectDataParameter)?; - info_now!("request to GetData for container {:?}", container); + info!("request to GetData for container {:?}", container); Ok(Self(container)) } } diff --git a/src/lib.rs b/src/lib.rs index 00d2f75..e4af02e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,11 @@ -#![cfg_attr(not(test), no_std)] +#![cfg_attr(not(any(test, feature = "std")), no_std)] +#[cfg(not(feature = "delog"))] #[macro_use] -extern crate delog; -generate_macros!(); +extern crate log; + +#[cfg(feature = "delog")] +delog::generate_macros!(); #[macro_use(hex)] extern crate hex_literal; @@ -18,6 +21,9 @@ pub mod piv_types; pub mod state; pub use piv_types::{Pin, Puk}; +#[cfg(feature = "virtual")] +pub mod vpicc; + use core::convert::TryInto; use flexiber::EncodableHeapless; @@ -70,7 +76,7 @@ where reply: &mut Data, ) -> Result { use piv_types::Algorithms::*; - info_now!("selecting PIV maybe"); + info!("selecting PIV maybe"); let application_property_template = piv_types::ApplicationPropertyTemplate::default() .with_application_label(APPLICATION_LABEL) @@ -80,7 +86,7 @@ where application_property_template .encode_to_heapless_vec(reply) .unwrap(); - info_now!("returning: {}", hex_str!(reply)); + info!("returning: {:02X?}", reply); Ok(()) } @@ -90,7 +96,7 @@ where reply: &mut Data, ) -> Result { // need to implement Debug on iso7816::Command - // info_now!("PIV responding to {:?}", command); + // info!("PIV responding to {:?}", command); let last_or_only = command.class().chain().last_or_only(); // TODO: avoid owned copy? @@ -124,7 +130,7 @@ where // parse Iso7816Command as PivCommand let command: Command = (&entire_command).try_into()?; - info_now!("parsed: {:?}", &command); + info!("parsed: {:?}", &command); match command { Command::Verify(verify) => self.verify(verify), @@ -281,14 +287,14 @@ where // return Err(Status::LogicalChannelNotSupported); // } - // // info_now!("CLA = {:?}", &command.class()); - // info_now!("INS = {:?}, P1 = {:X}, P2 = {:X}", + // // info!("CLA = {:?}", &command.class()); + // info!("INS = {:?}, P1 = {:X}, P2 = {:X}", // &command.instruction(), // command.p1, command.p2, // ); - // // info_now!("extended = {:?}", command.extended); + // // info!("extended = {:?}", command.extended); - // // info_now!("INS = {:?}" &command.instruction()); + // // info!("INS = {:?}" &command.instruction()); // match command.instruction() { // Instruction::GetData => self.get_data(command, reply), // Instruction::PutData => self.put_data(command), @@ -431,7 +437,7 @@ where return Err(Status::IncorrectDataParameter); } - info_now!("looking for keyreference"); + info!("looking for keyreference"); let key_handle = match self .state .persistent(&mut self.trussed) @@ -447,7 +453,7 @@ where let signature = try_syscall!(self.trussed.sign_ed255(key_handle, commitment)) .map_err(|_error| { // NoSuchKey - debug_now!("{:?}", &_error); + debug!("{:?}", &_error); Status::UnspecifiedNonpersistentExecutionError })? .signature; @@ -495,8 +501,8 @@ where self.state.runtime.command_cache = None; if our_challenge != response { - debug_now!("{:?}", &our_challenge); - debug_now!("{:?}", &response); + debug!("{:?}", &our_challenge); + debug!("{:?}", &response); return Err(Status::IncorrectDataParameter); } @@ -768,7 +774,7 @@ where }) }) .map_err(|_e| { - info_now!("error parsing GenerateAsymmetricKeypair: {:?}", &_e); + info!("error parsing GenerateAsymmetricKeypair: {:?}", &_e); Status::IncorrectDataParameter })?; @@ -837,7 +843,7 @@ where )) .serialized_key; - // info_now!("supposed SEC1 pubkey, len {}: {:X?}", serialized_public_key.len(), &serialized_public_key); + // info!("supposed SEC1 pubkey, len {}: {:X?}", serialized_public_key.len(), &serialized_public_key); // P256 SEC1 has 65 bytes, Ed255 pubkeys have 32 // let l2 = 65; @@ -853,7 +859,7 @@ where } pub fn put_data(&mut self, command: &iso7816::Command) -> Result { - info_now!("PutData"); + info!("PutData"); if command.p1 != 0x3f || command.p2 != 0xff { return Err(Status::IncorrectP1OrP2Parameter); } @@ -881,11 +887,11 @@ where // }).unwrap(); }) .map_err(|_e| { - info_now!("error parsing PutData: {:?}", &_e); + info!("error parsing PutData: {:?}", &_e); Status::IncorrectDataParameter })?; - // info_now!("PutData in {:?}: {:?}", data_object, data); + // info!("PutData in {:?}: {:?}", data_object, data); if data_object == [0x5f, 0xc1, 0x09] { // "Printed Information", supposedly @@ -976,7 +982,7 @@ where piv_types::CardCapabilityContainer::default() .encode_to_heapless_vec(reply) .unwrap(); - info_now!("returning CCC {}", hex_str!(reply)); + info!("returning CCC {:02X?}", reply); } // '5FC1 02' (351B) @@ -986,14 +992,14 @@ where .with_guid(guid) .encode_to_heapless_vec(reply) .unwrap(); - info_now!("returning CHUID {}", hex_str!(reply)); + info!("returning CHUID {:02X?}", reply); } // // '5FC1 05' (351B) // Container::X509CertificateForPivAuthentication => { // // return Err(Status::NotFound); - // // info_now!("loading 9a cert"); + // // info!("loading 9a cert"); // // it seems like fetching this certificate is the way Filo's agent decides // // whether the key is "already setup": // // https://github.com/FiloSottile/yubikey-agent/blob/8781bc0082db5d35712a2244e3ab3086f415dd59/setup.go#L69-L70 @@ -1001,7 +1007,7 @@ where // trussed::types::Location::Internal, // trussed::types::PathBuf::from(b"authentication-key.x5c"), // )).map_err(|_| { - // // info_now!("error loading: {:?}", &e); + // // info!("error loading: {:?}", &e); // Status::NotFound // } )?.data; @@ -1029,7 +1035,7 @@ where instruction: YubicoPivExtension, reply: &mut Data, ) -> Result { - info_now!("yubico extension: {:?}", &instruction); + info!("yubico extension: {:?}", &instruction); match instruction { YubicoPivExtension::GetSerial => { // make up a 4-byte serial diff --git a/src/state.rs b/src/state.rs index cdcd5d6..e456a25 100644 --- a/src/state.rs +++ b/src/state.rs @@ -459,7 +459,7 @@ where } pub fn initialize(trussed: &'t mut T) -> Self { - info_now!("initializing PIV state"); + info!("initializing PIV state"); let management_key = syscall!(trussed.unsafe_inject_shared_key( YUBICO_DEFAULT_MANAGEMENT_KEY, trussed::types::Location::Internal, @@ -527,7 +527,7 @@ where try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); if let Ok(data) = data { let previous_state = trussed::cbor_deserialize(&data.data).map_err(|_err| { - info!("cbor deser error: {_err:?}", e); + info!("cbor deser error: {_err:?}"); info!("data: {:X?}", &data); }); if let Ok(state) = previous_state { diff --git a/src/vpicc.rs b/src/vpicc.rs new file mode 100644 index 0000000..9464e48 --- /dev/null +++ b/src/vpicc.rs @@ -0,0 +1,155 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +use iso7816::{command::FromSliceError, Command, Status}; +use trussed::virt::{Client, Ram}; + +use std::convert::{TryFrom, TryInto}; + +use crate::Authenticator; + +const REQUEST_LEN: usize = 7609; +const RESPONSE_LEN: usize = 7609; +const BUFFER_LEN: usize = 7609; + +/// Virtual PIV smartcard implementation. +/// +/// This struct provides a virtual PIV smart card implementation that can be used with +/// `vpicc-rs` and [`vsmartcard`](https://frankmorgner.github.io/vsmartcard/) to emulate the card. +pub struct VirtualCard { + request_buffer: RequestBuffer, + response_buffer: ResponseBuffer, + card: Authenticator, BUFFER_LEN>, +} + +impl VirtualCard { + /// Creates a new virtual smart card from the given card. + pub fn new(card: Authenticator, BUFFER_LEN>) -> Self { + Self { + request_buffer: Default::default(), + response_buffer: Default::default(), + card, + } + } + + fn handle(&mut self, request: &[u8]) -> (&[u8], Status) { + parse_command(request) + .and_then(|command| self.request_buffer.handle(command)) + .map(|command| { + command + .map(|command| { + self.response_buffer + .handle(&command, |c, b| self.card.respond(c, b)) + }) + .unwrap_or_default() + }) + .unwrap_or_else(|status| (&[], status)) + } +} + +impl vpicc::VSmartCard for VirtualCard { + fn power_on(&mut self) {} + + fn power_off(&mut self) { + self.card.deselect(); + } + + fn reset(&mut self) { + self.card.deselect(); + } + + fn execute(&mut self, request: &[u8]) -> Vec { + trace!("Received request {:x?}", request); + let (data, status) = self.handle(request); + let response = make_response(data, status); + trace!("Sending response {:x?}", response); + response + } +} + +fn parse_command(data: &[u8]) -> Result, Status> { + data.try_into().map_err(|err| { + warn!("Failed to parse command: {err:?}"); + match err { + FromSliceError::InvalidSliceLength + | FromSliceError::TooShort + | FromSliceError::TooLong => Status::WrongLength, + FromSliceError::InvalidClass => Status::ClassNotSupported, + FromSliceError::InvalidFirstBodyByteForExtended => Status::UnspecifiedCheckingError, + } + }) +} + +fn make_response(data: &[u8], status: Status) -> Vec { + let status: [u8; 2] = status.into(); + let mut response = Vec::with_capacity(data.len() + 2); + response.extend_from_slice(data); + response.extend_from_slice(&status); + response +} + +#[derive(Clone, Debug, Default)] +struct RequestBuffer { + command: Option>, +} + +impl RequestBuffer { + pub fn handle(&mut self, command: Command) -> Result>, Status> { + if let Some(buffer) = &mut self.command { + buffer + .extend_from_command(&command) + .map_err(|_| Status::WrongLength)?; + } + if command.class().chain().last_or_only() { + if let Some(buffer) = self.command.take() { + Ok(Some(buffer)) + } else { + Ok(Some(command)) + } + } else { + if self.command.is_none() { + self.command = Some(command); + } + Ok(None) + } + } +} + +#[derive(Clone, Debug, Default)] +struct ResponseBuffer { + buffer: heapless::Vec, + offset: usize, +} + +impl ResponseBuffer { + pub fn handle< + const C: usize, + F: FnOnce(&Command, &mut heapless::Vec) -> Result<(), Status>, + >( + &mut self, + command: &Command, + exec: F, + ) -> (&[u8], Status) { + if command.instruction() != iso7816::Instruction::GetResponse { + self.buffer.clear(); + self.offset = 0; + if let Err(status) = exec(command, &mut self.buffer) { + return (&[], status); + } + } + self.response(command.expected()) + } + + fn response(&mut self, n: usize) -> (&[u8], Status) { + let n = n.min(self.buffer.len() - self.offset); + let data = &self.buffer[self.offset..][..n]; + self.offset += n; + let status = if self.offset >= self.buffer.len() { + Status::Success + } else { + let rest = self.buffer.len() - self.offset; + Status::MoreAvailable(u8::try_from(rest).unwrap_or(u8::MAX)) + }; + (data, status) + } +} From 3b42f0b32e06a1dbb7f844d0a0ea6e1f3922c3cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 25 Oct 2022 10:22:23 +0200 Subject: [PATCH 07/59] Use recent method for macro import --- src/constants.rs | 2 ++ src/container.rs | 2 ++ src/lib.rs | 3 --- src/piv_types.rs | 1 + 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 84ceb4b..8426c9a 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,5 +1,7 @@ // https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html +use hex_literal::hex; + pub const RID_LENGTH: usize = 5; // top nibble of first byte is "category", here "A" = International diff --git a/src/container.rs b/src/container.rs index dfc3a0d..f211a78 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,4 +1,6 @@ use core::convert::TryFrom; + +use hex_literal::hex; // use flexiber::{Decodable, Encodable}; pub struct Tag<'a>(&'a [u8]); diff --git a/src/lib.rs b/src/lib.rs index e4af02e..304e82c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,9 +7,6 @@ extern crate log; #[cfg(feature = "delog")] delog::generate_macros!(); -#[macro_use(hex)] -extern crate hex_literal; - pub mod commands; pub use commands::Command; pub mod constants; diff --git a/src/piv_types.rs b/src/piv_types.rs index 65d72fd..8b4eaf8 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -1,6 +1,7 @@ use core::convert::{TryFrom, TryInto}; use flexiber::Encodable; +use hex_literal::hex; use serde::{Deserialize, Serialize}; /// According to spec, a PIN must be 6-8 digits, padded to 8 bytes with 0xFF. From c9a6249d7856922e2fc9f2923129ee16a0e35b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 25 Oct 2022 10:53:30 +0200 Subject: [PATCH 08/59] Add infrastructure for command-response tests (taken from opcard-rs) --- Cargo.toml | 8 +- tests/command_response.ron | 4 + tests/command_response.rs | 266 +++++++++++++++++++++++++++ tests/generate_asymmetric_keypair.rs | 2 - tests/setup/mod.rs | 4 +- 5 files changed, 279 insertions(+), 5 deletions(-) create mode 100644 tests/command_response.ron create mode 100644 tests/command_response.rs diff --git a/Cargo.toml b/Cargo.toml index faa1507..39885b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ heapless = "0.7" hex-literal = "0.3" interchange = "0.2.2" iso7816 = "0.1" -serde = { version = "1", default-features = false } +serde = { version = "1", default-features = false, features = ["derive"] } trussed = "0.1" untrusted = "0.9" vpicc = { version = "0.1.0", optional = true } @@ -30,6 +30,12 @@ littlefs2 = "0.3.2" rand_core = { version = "0.6", features = ["getrandom"] } trussed = { version = "0.1.0", features = ["virt"] } env_logger = "0.9" +serde = { version = "1", features = ["derive"] } +serde_cbor = { version = "0.11", features = ["std"] } +hex = "0.4" +test-log = "0.2" +ron = "0.8" + [features] default = [] diff --git a/tests/command_response.ron b/tests/command_response.ron new file mode 100644 index 0000000..112c59b --- /dev/null +++ b/tests/command_response.ron @@ -0,0 +1,4 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +[] diff --git a/tests/command_response.rs b/tests/command_response.rs new file mode 100644 index 0000000..563f372 --- /dev/null +++ b/tests/command_response.rs @@ -0,0 +1,266 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only +#![cfg(feature = "virtual")] + +mod setup; + +use std::borrow::Cow; + +use serde::Deserialize; + +// iso7816::Status doesn't support serde +#[derive(Deserialize, Debug, PartialEq, Clone, Copy)] +enum Status { + Success, + MoreAvailable(u8), + VerificationFailed, + RemainingRetries(u8), + UnspecifiedNonpersistentExecutionError, + UnspecifiedPersistentExecutionError, + WrongLength, + LogicalChannelNotSupported, + SecureMessagingNotSupported, + CommandChainingNotSupported, + SecurityStatusNotSatisfied, + ConditionsOfUseNotSatisfied, + OperationBlocked, + IncorrectDataParameter, + FunctionNotSupported, + NotFound, + NotEnoughMemory, + IncorrectP1OrP2Parameter, + KeyReferenceNotFound, + InstructionNotSupportedOrInvalid, + ClassNotSupported, + UnspecifiedCheckingError, +} + +fn serialize_len(len: usize) -> heapless::Vec { + let mut buf = heapless::Vec::new(); + if let Ok(len) = u8::try_from(len) { + if len <= 0x7f { + buf.extend_from_slice(&[len]).ok(); + } else { + buf.extend_from_slice(&[0x81, len]).ok(); + } + } else if let Ok(len) = u16::try_from(len) { + let arr = len.to_be_bytes(); + buf.extend_from_slice(&[0x82, arr[0], arr[1]]).ok(); + } else { + } + buf +} + +fn tlv(tag: &[u8], data: &[u8]) -> Vec { + let mut buf = Vec::from(tag); + buf.extend_from_slice(&serialize_len(data.len())); + buf.extend_from_slice(data); + buf +} + +fn build_command(cla: u8, ins: u8, p1: u8, p2: u8, data: &[u8], le: u16) -> Vec { + let mut res = vec![cla, ins, p1, p2]; + let lc = data.len(); + let extended = if lc == 0 { + false + } else if let Ok(len) = lc.try_into() { + res.push(len); + false + } else { + let len: u16 = lc.try_into().unwrap(); + res.push(0); + res.extend_from_slice(&len.to_be_bytes()); + true + }; + + res.extend_from_slice(data); + + if le == 0 { + return res; + } + + if let Ok(len) = (le - 1).try_into() { + let _: u8 = len; + res.push(len.wrapping_add(1)); + } else if extended { + res.extend_from_slice(&le.to_be_bytes()); + } else { + res.push(0); + res.extend_from_slice(&le.to_be_bytes()); + } + + res +} + +impl TryFrom for Status { + type Error = u16; + fn try_from(sw: u16) -> Result { + Ok(match sw { + 0x6300 => Self::VerificationFailed, + sw @ 0x63c0..=0x63cf => Self::RemainingRetries((sw as u8) & 0xf), + + 0x6400 => Self::UnspecifiedNonpersistentExecutionError, + 0x6500 => Self::UnspecifiedPersistentExecutionError, + + 0x6700 => Self::WrongLength, + + 0x6881 => Self::LogicalChannelNotSupported, + 0x6882 => Self::SecureMessagingNotSupported, + 0x6884 => Self::CommandChainingNotSupported, + + 0x6982 => Self::SecurityStatusNotSatisfied, + 0x6985 => Self::ConditionsOfUseNotSatisfied, + 0x6983 => Self::OperationBlocked, + + 0x6a80 => Self::IncorrectDataParameter, + 0x6a81 => Self::FunctionNotSupported, + 0x6a82 => Self::NotFound, + 0x6a84 => Self::NotEnoughMemory, + 0x6a86 => Self::IncorrectP1OrP2Parameter, + 0x6a88 => Self::KeyReferenceNotFound, + + 0x6d00 => Self::InstructionNotSupportedOrInvalid, + 0x6e00 => Self::ClassNotSupported, + 0x6f00 => Self::UnspecifiedCheckingError, + + 0x9000 => Self::Success, + sw @ 0x6100..=0x61FF => Self::MoreAvailable(sw as u8), + other => return Err(other), + }) + } +} + +impl Default for Status { + fn default() -> Status { + Status::Success + } +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct IoTest { + name: String, + cmd_resp: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +enum OutputMatcher { + Len(usize), + // The () at the end are here to workaround a compiler bug. See: + // https://github.com/rust-lang/rust/issues/89940#issuecomment-1282321806 + And(Cow<'static, [OutputMatcher]>, #[serde(default)] ()), + Or(Cow<'static, [OutputMatcher]>, #[serde(default)] ()), + /// HEX data + Data(Cow<'static, str>), + Bytes(Cow<'static, [u8]>), + NonZero, +} + +impl Default for OutputMatcher { + fn default() -> Self { + MATCH_EMPTY + } +} + +fn parse_hex(data: &str) -> Vec { + let tmp: String = data.split_whitespace().collect(); + hex::decode(&tmp).unwrap() +} + +impl OutputMatcher { + fn validate(&self, data: &[u8]) -> bool { + match self { + Self::NonZero => data.iter().max() != Some(&0), + Self::Data(expected) => { + println!("Validating output with {expected}"); + data == parse_hex(expected) + } + Self::Bytes(expected) => { + println!("Validating output with {expected:x?}"); + data == &**expected + } + Self::Len(len) => data.len() == *len, + Self::And(matchers, _) => matchers.iter().filter(|m| !m.validate(data)).count() == 0, + Self::Or(matchers, _) => matchers.iter().filter(|m| m.validate(data)).count() != 0, + } + } +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +enum IoCmd { + IoData { + input: String, + #[serde(default)] + output: OutputMatcher, + #[serde(default)] + expected_status: Status, + }, +} + +const MATCH_EMPTY: OutputMatcher = OutputMatcher::Len(0); + +impl IoCmd { + fn run(&self, card: &mut setup::Piv) { + match self { + Self::IoData { + input, + output, + expected_status, + } => Self::run_iodata(input, output, *expected_status, card), + } + } + + fn run_bytes( + input: &[u8], + output: &OutputMatcher, + expected_status: Status, + card: &mut setup::Piv, + ) { + println!("Command: {:x?}", input); + let mut rep: heapless::Vec = heapless::Vec::new(); + let cmd: iso7816::Command<{ setup::COMMAND_SIZE }> = iso7816::Command::try_from(input) + .unwrap_or_else(|err| { + panic!("Bad command: {err:?}, for command: {}", hex::encode(&input)) + }); + let status: Status = card + .respond(&cmd, &mut rep) + .err() + .map(|s| TryFrom::::try_from(s.into()).unwrap()) + .unwrap_or_default(); + + println!("Output: {:?}\nStatus: {status:?}", hex::encode(&rep)); + + if !output.validate(&rep) { + panic!("Bad output. Expected {:?}", output); + } + if status != expected_status { + panic!("Bad status. Expected {:?}", expected_status); + } + } + + fn run_iodata( + input: &str, + output: &OutputMatcher, + expected_status: Status, + card: &mut setup::Piv, + ) { + Self::run_bytes(&parse_hex(input), output, expected_status, card) + } +} + +#[test_log::test] +fn command_response() { + let data = std::fs::read_to_string("tests/command_response.ron").unwrap(); + let tests: Vec = ron::from_str(&data).unwrap(); + for t in tests { + println!("\n\n===========================================================",); + println!("Running {}", t.name); + setup::piv(|mut card| { + for io in t.cmd_resp { + io.run(&mut card); + } + }); + } +} diff --git a/tests/generate_asymmetric_keypair.rs b/tests/generate_asymmetric_keypair.rs index 877ceea..f72f50f 100644 --- a/tests/generate_asymmetric_keypair.rs +++ b/tests/generate_asymmetric_keypair.rs @@ -1,7 +1,5 @@ mod setup; - - // example: 00 47 00 9A 0B // AC 09 // # P256 diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 2f081af..45f8149 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,4 +1,4 @@ -const COMMAND_SIZE: usize = 3072; +pub const COMMAND_SIZE: usize = 3072; #[macro_export] macro_rules! cmd { @@ -9,7 +9,7 @@ macro_rules! cmd { use trussed::virt::{Client, Ram}; -pub type Piv<'service> = piv_authenticator::Authenticator, COMMAND_SIZE>; +pub type Piv = piv_authenticator::Authenticator, COMMAND_SIZE>; pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { trussed::virt::with_ram_client("test", |client| { From 4bb20fe0df0c284de31ea587d9dc5ea50e4d855f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 25 Oct 2022 11:41:35 +0200 Subject: [PATCH 09/59] Log commands --- src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 304e82c..2c0c6af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,8 +92,7 @@ where command: &iso7816::Command, reply: &mut Data, ) -> Result { - // need to implement Debug on iso7816::Command - // info!("PIV responding to {:?}", command); + info!("PIV responding to {:?}", command); let last_or_only = command.class().chain().last_or_only(); // TODO: avoid owned copy? From 98fa36fe82b42710e2d87d681151fb1b6738944a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 25 Oct 2022 16:41:47 +0200 Subject: [PATCH 10/59] Add test with default PIN --- tests/command_response.ron | 10 +++++++++- tests/command_response.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/tests/command_response.ron b/tests/command_response.ron index 112c59b..5bf2d6d 100644 --- a/tests/command_response.ron +++ b/tests/command_response.ron @@ -1,4 +1,12 @@ // Copyright (C) 2022 Nitrokey GmbH // SPDX-License-Identifier: LGPL-3.0-only -[] +[ + IoTest( + name: "Verify", + cmd_resp: [ + VerifyDefaultApplicationPin(), + VerifyDefaultGlobalPin(expected_status: FunctionNotSupported) + ] + ) +] diff --git a/tests/command_response.rs b/tests/command_response.rs index 563f372..bc1f7b7 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -6,6 +6,7 @@ mod setup; use std::borrow::Cow; +use hex_literal::hex; use serde::Deserialize; // iso7816::Status doesn't support serde @@ -197,6 +198,14 @@ enum IoCmd { #[serde(default)] expected_status: Status, }, + VerifyDefaultApplicationPin { + #[serde(default)] + expected_status: Status, + }, + VerifyDefaultGlobalPin { + #[serde(default)] + expected_status: Status, + }, } const MATCH_EMPTY: OutputMatcher = OutputMatcher::Len(0); @@ -209,6 +218,12 @@ impl IoCmd { output, expected_status, } => Self::run_iodata(input, output, *expected_status, card), + Self::VerifyDefaultApplicationPin { expected_status } => { + Self::run_verify_default_application_pin(*expected_status, card) + } + Self::VerifyDefaultGlobalPin { expected_status } => { + Self::run_verify_default_global_pin(*expected_status, card) + } } } @@ -248,6 +263,23 @@ impl IoCmd { ) { Self::run_bytes(&parse_hex(input), output, expected_status, card) } + + fn run_verify_default_global_pin(expected_status: Status, card: &mut setup::Piv) { + Self::run_bytes( + &hex!("00 20 00 00 08 313233343536FFFF"), + &MATCH_EMPTY, + expected_status, + card, + ) + } + fn run_verify_default_application_pin(expected_status: Status, card: &mut setup::Piv) { + Self::run_bytes( + &hex!("00 20 00 80 08 313233343536FFFF"), + &MATCH_EMPTY, + expected_status, + card, + ) + } } #[test_log::test] From cc989dc656443c27d7444ccaf9bc4dbba21067a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Wed, 26 Oct 2022 11:28:59 +0200 Subject: [PATCH 11/59] Add select command support and test --- src/lib.rs | 3 ++- tests/command_response.ron | 8 +++++++- tests/command_response.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2c0c6af..26d9824 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,7 +69,7 @@ where pub fn select( &mut self, - _apdu: &iso7816::Command, + _aid: commands::Select<'_>, reply: &mut Data, ) -> Result { use piv_types::Algorithms::*; @@ -132,6 +132,7 @@ where Command::Verify(verify) => self.verify(verify), Command::ChangeReference(change_reference) => self.change_reference(change_reference), Command::GetData(container) => self.get_data(container, reply), + Command::Select(aid) => self.select(aid, reply), _ => todo!(), } } diff --git a/tests/command_response.ron b/tests/command_response.ron index 5bf2d6d..bcee492 100644 --- a/tests/command_response.ron +++ b/tests/command_response.ron @@ -8,5 +8,11 @@ VerifyDefaultApplicationPin(), VerifyDefaultGlobalPin(expected_status: FunctionNotSupported) ] - ) + ), + IoTest( + name: "Select", + cmd_resp: [ + Select + ] + ), ] diff --git a/tests/command_response.rs b/tests/command_response.rs index bc1f7b7..15d49f9 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -206,6 +206,7 @@ enum IoCmd { #[serde(default)] expected_status: Status, }, + Select, } const MATCH_EMPTY: OutputMatcher = OutputMatcher::Len(0); @@ -224,6 +225,7 @@ impl IoCmd { Self::VerifyDefaultGlobalPin { expected_status } => { Self::run_verify_default_global_pin(*expected_status, card) } + Self::Select => Self::run_select(card), } } @@ -280,6 +282,37 @@ impl IoCmd { card, ) } + + fn run_select(card: &mut setup::Piv) { + let matcher = OutputMatcher::Bytes(Cow::Borrowed(&hex!( + " + 61 63 // Card application property template + 4f 06 000010000100 // Application identifier + 50 0c 536f6c6f4b65797320504956 // Application label = b\"Solokeys PIV\" + + // URL = b\"https://github.com/solokeys/piv-authenticator\" + 5f50 2d 68747470733a2f2f6769746875622e636f6d2f736f6c6f6b6579732f7069762d61757468656e74696361746f72 + + // Cryptographic Algorithm Identifier Template + ac 12 + 80 01 03 // TDES - ECB + 80 01 0c // AES256 - ECB + 80 01 11 // P-256 + 80 01 e2 // Ed25519 + 80 01 e3 // X25519 + 06 01 00 + // Coexistent Tag Allocation Authority Template + 79 07 + 4f 05 a000000308 + " + ))); + Self::run_bytes( + &hex!("00 A4 04 00 0C A000000308000010000100 00"), + &matcher, + Status::Success, + card, + ) + } } #[test_log::test] From 3e8fc3e653462bedef1f3ec14999ca8774d10fe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Wed, 26 Oct 2022 17:35:48 +0200 Subject: [PATCH 12/59] Fix fasc-n encoding --- src/piv_types.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/piv_types.rs b/src/piv_types.rs index 8b4eaf8..40dc7ab 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -268,12 +268,13 @@ impl<'a> DynamicAuthenticationTemplate<'a> { /// /// We remove the deprecated data elements. // pivy: https://git.io/JfzBo -// https://www.idmanagement.gov/wp-content/uploads/sites/1171/uploads/TIG_SCEPACS_v2.3.pdf +// https://www.idmanagement.gov/wp-content/uploads/sites/1171/uploads/TIG_SCEPACS_v2.3.pdf FIXME: dead link #[derive(Clone, Copy, Encodable, Eq, PartialEq)] #[tlv(application, primitive, number = "0x13")] // = 0x53 pub struct CardHolderUniqueIdentifier<'l> { #[tlv(simple = "0x30")] // pivy: 26B, TIG: 25B + // https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf fasc_n: &'l [u8], #[tlv(simple = "0x34")] @@ -324,8 +325,21 @@ pub struct CardHolderUniqueIdentifier<'l> { impl Default for CardHolderUniqueIdentifier<'static> { fn default() -> Self { Self { - // 9999 = non-federal - fasc_n: &[0x99, 0x99], + // Corresponds to bit string in CBD (see https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf) + // 11010_10011_10011_10011_10011_10110_00001_00001_00001_00001 + // 10110_00001_00001_00001_00001_00001_00001_10110_00001_10110 + // 00001_10110_00001_00001_00001_00001_00001_00001_00001_00001 + // 00001_00001_10000_00001_00001_00001_00001_10000_11111_10011 + // AGENCY CODE = 9999 (non federal) + // SYSTEM CODE = 0000 + // CREDENTIAL# = 000000 + // CS = 0 + // ICI = 0 + // PI = 0000000000 + // OC= 1 + // OI=0000 + // POA=1 + fasc_n: &hex!("D4E739D821086C1084210D8360D8210842108421804210C3F3"), guid: hex!("00000000000040008000000000000000"), expiration_date: *b"99991231", // cardholder_uuid: None, From e076633cc7337a3994fbaa89ff416e9481dfe01a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 09:48:44 +0100 Subject: [PATCH 13/59] Add convinience make targets --- Makefile | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Makefile b/Makefile index 031929b..4c4b036 100644 --- a/Makefile +++ b/Makefile @@ -1,2 +1,27 @@ +.NOTPARALLEL: + +export RUST_LOG ?= info,cargo_tarpaulin=off + +.PHONY: build-cortex-m4 build-cortex-m4: cargo build --target thumbv7em-none-eabi + +.PHONY: test +test: + cargo test --features virtual + +.PHONY: check +check: + cargo fmt --check + cargo check --all-targets --all-features + cargo check --target thumbv7em-none-eabi + cargo clippy -- -Dwarnings + RUSTDOCFLAGS='-Dwarnings' cargo doc --all-features + +.PHONY: tarpaulin +tarpaulin: + cargo tarpaulin --features virtual -o Html -o Xml + +.PHONY: example +example: + cargo run --example virtual --features virtual From fd23a9fd4227ff942f91831a0bbdce2195f336e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 09:56:14 +0100 Subject: [PATCH 14/59] Remove the unused apdu from the select command --- src/dispatch.rs | 2 +- src/lib.rs | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/dispatch.rs b/src/dispatch.rs index a2a09ed..b9b2536 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -9,7 +9,7 @@ where T: client::Client + client::Ed255 + client::Tdes, { fn select(&mut self, apdu: &Command, reply: &mut response::Data) -> Result { - self.select(apdu, reply) + self.select(reply) } fn deselect(&mut self) { diff --git a/src/lib.rs b/src/lib.rs index 26d9824..163cfe4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,11 +67,7 @@ where // The way apdu-dispatch currently works, this would deselect, resetting security indicators. pub fn deselect(&mut self) {} - pub fn select( - &mut self, - _aid: commands::Select<'_>, - reply: &mut Data, - ) -> Result { + pub fn select(&mut self, reply: &mut Data) -> Result { use piv_types::Algorithms::*; info!("selecting PIV maybe"); @@ -132,7 +128,7 @@ where Command::Verify(verify) => self.verify(verify), Command::ChangeReference(change_reference) => self.change_reference(change_reference), Command::GetData(container) => self.get_data(container, reply), - Command::Select(aid) => self.select(aid, reply), + Command::Select(_aid) => self.select(reply), _ => todo!(), } } From 0ac5cc5a424e3e1facaaaa37dca5e6ab18aea8fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 10:49:18 +0100 Subject: [PATCH 15/59] Improve documentation of default FASC_N --- src/piv_types.rs | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/piv_types.rs b/src/piv_types.rs index 40dc7ab..b4e7765 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -322,24 +322,26 @@ pub struct CardHolderUniqueIdentifier<'l> { // error_detection_code: [u8; 0], // } +/// Corresponds to bit string in CBD (see https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf) +/// 11010_10011_10011_10011_10011_10110_00001_00001_00001_00001 +/// 10110_00001_00001_00001_00001_00001_00001_10110_00001_10110 +/// 00001_10110_00001_00001_00001_00001_00001_00001_00001_00001 +/// 00001_00001_10000_00001_00001_00001_00001_10000_11111_10011 +/// AGENCY CODE = 9999 (non federal) +/// SYSTEM CODE = 0000 +/// CREDENTIAL# = 000000 +/// CS = 0 +/// ICI = 0 +/// PI = 0000000000 +/// OC= 1 +/// OI=0000 +/// POA=1 +const DEFAULT_FASC_N: &[u8] = &hex!("D4E739D821086C1084210D8360D8210842108421804210C3F3"); + impl Default for CardHolderUniqueIdentifier<'static> { fn default() -> Self { Self { - // Corresponds to bit string in CBD (see https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf) - // 11010_10011_10011_10011_10011_10110_00001_00001_00001_00001 - // 10110_00001_00001_00001_00001_00001_00001_10110_00001_10110 - // 00001_10110_00001_00001_00001_00001_00001_00001_00001_00001 - // 00001_00001_10000_00001_00001_00001_00001_10000_11111_10011 - // AGENCY CODE = 9999 (non federal) - // SYSTEM CODE = 0000 - // CREDENTIAL# = 000000 - // CS = 0 - // ICI = 0 - // PI = 0000000000 - // OC= 1 - // OI=0000 - // POA=1 - fasc_n: &hex!("D4E739D821086C1084210D8360D8210842108421804210C3F3"), + fasc_n: DEFAULT_FASC_N, guid: hex!("00000000000040008000000000000000"), expiration_date: *b"99991231", // cardholder_uuid: None, From 34a9629a260c995df6ad5ca0e52299ddff69a290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 10:59:58 +0100 Subject: [PATCH 16/59] Fix pivy-tool list --- src/piv_types.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/piv_types.rs b/src/piv_types.rs index b4e7765..04e9de5 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -344,9 +344,7 @@ impl Default for CardHolderUniqueIdentifier<'static> { fasc_n: DEFAULT_FASC_N, guid: hex!("00000000000040008000000000000000"), expiration_date: *b"99991231", - // cardholder_uuid: None, - // at least pivy only checks for non-empty entry - issuer_asymmetric_signature: b" ", + issuer_asymmetric_signature: b"", error_detection_code: [0u8; 0], } } From aab53029e0047f01ea7a77ae4367137c743f1498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 11:16:10 +0100 Subject: [PATCH 17/59] Fix remaining warnings --- Makefile | 2 +- src/dispatch.rs | 2 +- tests/command_response.rs | 6 ++++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 4c4b036..a81e9fe 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ check: cargo fmt --check cargo check --all-targets --all-features cargo check --target thumbv7em-none-eabi - cargo clippy -- -Dwarnings + cargo clippy --all-targets --all-features -- -Dwarnings RUSTDOCFLAGS='-Dwarnings' cargo doc --all-features .PHONY: tarpaulin diff --git a/src/dispatch.rs b/src/dispatch.rs index b9b2536..a6f9cd7 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -8,7 +8,7 @@ impl App<{ command::SIZE }, { response::SIZE }> for Authenticator Result { + fn select(&mut self, _apdu: &Command, reply: &mut response::Data) -> Result { self.select(reply) } diff --git a/tests/command_response.rs b/tests/command_response.rs index 15d49f9..b5fafd8 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -52,6 +52,7 @@ fn serialize_len(len: usize) -> heapless::Vec { buf } +#[allow(unused)] fn tlv(tag: &[u8], data: &[u8]) -> Vec { let mut buf = Vec::from(tag); buf.extend_from_slice(&serialize_len(data.len())); @@ -59,6 +60,7 @@ fn tlv(tag: &[u8], data: &[u8]) -> Vec { buf } +#[allow(unused)] fn build_command(cla: u8, ins: u8, p1: u8, p2: u8, data: &[u8], le: u16) -> Vec { let mut res = vec![cla, ins, p1, p2]; let lc = data.len(); @@ -322,9 +324,9 @@ fn command_response() { for t in tests { println!("\n\n===========================================================",); println!("Running {}", t.name); - setup::piv(|mut card| { + setup::piv(|card| { for io in t.cmd_resp { - io.run(&mut card); + io.run(card); } }); } From 0dc602cd8197d41c1586d0c728cd9611393d5400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 11:24:18 +0100 Subject: [PATCH 18/59] Remove command chaining This is handled by [apdu_dispatch](https://github.com/solokeys/apdu-dispatch/blob/main/src/dispatch.rs#L155) --- src/lib.rs | 34 +--------------------------------- src/state.rs | 1 - 2 files changed, 1 insertion(+), 34 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 163cfe4..7896207 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -89,39 +89,7 @@ where reply: &mut Data, ) -> Result { info!("PIV responding to {:?}", command); - let last_or_only = command.class().chain().last_or_only(); - - // TODO: avoid owned copy? - let entire_command = match self.state.runtime.chained_command.as_mut() { - Some(command_so_far) => { - // TODO: make sure the header matches, e.g. '00 DB 3F FF' - command_so_far - .data_mut() - .extend_from_slice(command.data()) - .unwrap(); - - if last_or_only { - let entire_command = command_so_far.clone(); - self.state.runtime.chained_command = None; - entire_command - } else { - return Ok(()); - } - } - - None => { - if last_or_only { - // iso7816::Command - command.clone() - } else { - self.state.runtime.chained_command = Some(command.clone()); - return Ok(()); - } - } - }; - - // parse Iso7816Command as PivCommand - let command: Command = (&entire_command).try_into()?; + let command: Command = command.try_into()?; info!("parsed: {:?}", &command); match command { diff --git a/src/state.rs b/src/state.rs index e456a25..9c16c63 100644 --- a/src/state.rs +++ b/src/state.rs @@ -250,7 +250,6 @@ pub struct Runtime { // pub currently_selected_application: SelectableAid, pub app_security_status: AppSecurityStatus, pub command_cache: Option, - pub chained_command: Option>, } // pub trait Aid { From d1fac724ea73da52c8824942b857d74760372025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 11:27:07 +0100 Subject: [PATCH 19/59] Use full names for cryptosystems --- src/lib.rs | 2 +- src/piv_types.rs | 12 ++++++------ src/state.rs | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7896207..5cc5dd4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -74,7 +74,7 @@ where let application_property_template = piv_types::ApplicationPropertyTemplate::default() .with_application_label(APPLICATION_LABEL) .with_application_url(APPLICATION_URL) - .with_supported_cryptographic_algorithms(&[Tdes, Aes256, P256, Ed255, X255]); + .with_supported_cryptographic_algorithms(&[Tdes, Aes256, P256, Ed25519, X25519]); application_property_template .encode_to_heapless_vec(reply) diff --git a/src/piv_types.rs b/src/piv_types.rs index 04e9de5..9ef4506 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -60,8 +60,8 @@ impl TryFrom<&[u8]> for Puk { // references Opacity ZKM. pub enum Algorithms { Tdes = 0x3, - Rsa1k = 0x6, - Rsa2k = 0x7, + Rsa1024 = 0x6, + Rsa2048 = 0x7, Aes128 = 0x8, Aes192 = 0xA, Aes256 = 0xC, @@ -74,10 +74,10 @@ pub enum Algorithms { // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 P521 = 0x15, // non-standard! - Rsa3k = 0xE0, - Rsa4k = 0xE1, - Ed255 = 0xE2, - X255 = 0xE3, + Rsa3072 = 0xE0, + Rsa4096 = 0xE1, + Ed25519 = 0xE2, + X25519 = 0xE3, Ed448 = 0xE4, X448 = 0xE5, diff --git a/src/state.rs b/src/state.rs index 9c16c63..bba3932 100644 --- a/src/state.rs +++ b/src/state.rs @@ -13,9 +13,9 @@ use crate::{Pin, Puk}; pub type Result = core::result::Result; pub enum Key { - Ed255(KeyId), + Ed25519(KeyId), P256(KeyId), - X255(KeyId), + X25519(KeyId), } pub enum PinPolicy { Never, From 04d8ea1e8951145485f68d1c86e1cf5f44a49816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 11:39:02 +0100 Subject: [PATCH 20/59] Return FunctionNotSupported rather than NotFound for unimplemeted GetData objects --- src/lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 5cc5dd4..29d1897 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -985,7 +985,10 @@ where // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); // reply.extend_from_slice(&data).ok(); // } - _ => return Err(Status::NotFound), + _ => { + warn!("Unimplemented GET DATA object: {container:?}"); + return Err(Status::FunctionNotSupported); + } } Ok(()) } From d4c68e77c8326ec8a44f621d32ef09a9938d6a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 31 Oct 2022 17:30:13 +0100 Subject: [PATCH 21/59] Remove outdated comments --- src/commands.rs | 4 - src/constants.rs | 133 --------------------------- src/container.rs | 62 ------------- src/error.rs | 110 ----------------------- src/lib.rs | 228 ----------------------------------------------- src/piv_types.rs | 17 ---- src/state.rs | 40 --------- 7 files changed, 594 deletions(-) delete mode 100644 src/error.rs diff --git a/src/commands.rs b/src/commands.rs index b380583..4c96e08 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -105,14 +105,10 @@ impl TryFrom for VerifyKeyReference { // then no other key reference shall be able to be verified by the PIV Card Application VERIFY command. match p2 { 0x00 => Ok(Self::GlobalPin), - // 0x00 => Err(Status::FunctionNotSupported), 0x80 => Ok(Self::PivPin), 0x96 => Ok(Self::PrimaryFingerOcc), 0x97 => Ok(Self::SecondaryFingerOcc), 0x98 => Ok(Self::PairingCode), - // 0x96 => Err(Status::FunctionNotSupported), - // 0x97 => Err(Status::FunctionNotSupported), - // 0x98 => Err(Status::FunctionNotSupported), _ => Err(Status::KeyReferenceNotFound), } } diff --git a/src/constants.rs b/src/constants.rs index 8426c9a..dc60c56 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -111,139 +111,6 @@ pub const GET_DATA: (u8, u8, u8, u8) = ( // 256, ); -// SW (SP 800-73 Part 1, Table 6) -// == == == == == == == == == == == -// 61, xx success, more response data bytes -// -// 63, 00 verification failed -// 63, Cx verification failed, x furtehr retries or resets -// -// 68, 82 secure messaging not supported -// -// 69, 82 security status not satisfied -// 69, 83 authn method blocked -// : (more secure messaging stuff) -// - -//// ISO/IEC 7816-4, 5.1.3 "Status bytes" -//#[derive(Copy, Clone, Debug, Eq, PartialEq)] -//pub enum StatusWord { - -//////////////////////////////// -//// Normal processing (90, 61) -//////////////////////////////// - -// // 9000 -// Success, - -// // 61XX -// MoreAvailable(u8), - -///////////////////////////////// -//// Warning processing (62, 63) -///////////////////////////////// - -// // 62XX: state of non-volatile memory unchanged (cf. SW2) - -// // 63XX: state of non-volatile memory changed (cf. SW2) -// VerificationFailed, -// FailedRetries(u8), - -////////////////////////////////// -//// Execution error (64, 65, 66) -////////////////////////////////// - -// // 64XX: persistent memory unchanged (cf. SW2) -// // 65XX: persistent memory changed (cf. SW2) -// // 66XX: security related issues - -///////////////////////////////// -//// Checking error (67 - 6F) -///////////////////////////////// - -// // 6700: wrong length, no further indication - -// // 68XX: functions in CLA not supported (cf. SW2) -// SecureMessagingNotSupported, -// CommandChainingNotSupported, - -// // 69xx: command not allowed (cf. SW2) -// SecurityStatusNotSatisfied, -// OperationBlocked, - -// // 6Axx: wrong parameters P1-P2 (cf. SW2) -// IncorrectDataParameter, -// FunctionNotSupported, -// NotFound, -// NotEnoughMemory, -// IncorrectP1OrP2Parameter, -// KeyReferenceNotFound, - -// // 6BXX: wrong parameters P1-P2 - -// // 6CXX: wrong Le field, SW2 encodes available bytes - -// // 6D00: instruction code not supported or invalid -// InstructionNotSupportedOrInvalid, - -// // 6E00: class not supported -// ClassNotSupported, - -// // 6F00: no precise diagnosis -// UnspecifiedCheckingError, -//} - -//impl Into for StatusWord { -// #[inline] -// fn into(self) -> u16 { -// match self { -// Self::VerificationFailed => 0x6300, -// Self::FailedRetries(x) => { -// assert!(x < 16); -// u16::from_be_bytes([0x63, 0xc0 + x]) -// } - -// Self::SecureMessagingNotSupported => 0x6882, -// Self::CommandChainingNotSupported => 0x6884, - -// Self::SecurityStatusNotSatisfied => 0x6982, -// Self::OperationBlocked => 0x6983, - -// Self::IncorrectDataParameter => 0x6a80, -// Self::FunctionNotSupported => 0x6a81, -// Self::NotFound => 0x6a82, -// Self::NotEnoughMemory => 0x6a84, -// Self::IncorrectP1OrP2Parameter => 0x6a86, -// Self::KeyReferenceNotFound => 0x6a88, - -// Self::InstructionNotSupportedOrInvalid => 0x6d00, -// Self::ClassNotSupported => 0x6e00, -// Self::UnspecifiedCheckingError => 0x6f00, - -// Self::Success => 0x9000, -// Self::MoreAvailable(x) => u16::from_be_bytes([0x61, x]), -// } -// } -//} - -//impl Into<[u8; 2]> for StatusWord { -// #[inline] -// fn into(self) -> [u8; 2] { -// let sw: u16 = self.into(); -// sw.to_be_bytes() -// } -//} - -// 6A, 80 incorrect parameter in command data field -// 6A, 81 function not supported -// 6A, 82 data object not found ( = NOT FOUND for files, e.g. certificate, e.g. after GET-DATA) -// 6A, 84 not enough memory -// 6A, 86 incorrect parameter in P1/P2 -// 6A, 88 reference(d) data not found ( = NOT FOUND for keys, e.g. global PIN, e.g. after VERIFY) -// -// 90, 00 SUCCESS! -// == == == == == == == == == == == - // #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct DataObjects {} #[allow(non_upper_case_globals)] diff --git a/src/container.rs b/src/container.rs index f211a78..62359aa 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,7 +1,6 @@ use core::convert::TryFrom; use hex_literal::hex; -// use flexiber::{Decodable, Encodable}; pub struct Tag<'a>(&'a [u8]); impl<'a> Tag<'a> { @@ -194,64 +193,3 @@ impl TryFrom> for Container { }) } } - -// #[derive(Clone, Copy, PartialEq)] -// pub struct CertInfo { -// compressed: bool, -// } - -// impl From for u8 { -// fn from(cert_info: CertInfo) -> Self { -// cert_info.compressed as u8 -// } -// } - -// impl Encodable for CertInfo { -// fn encoded_len(&self) -> der::Result { -// Length::from(1) -// } - -// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { -// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) -// } -// } - -// pub struct Certificate<'a> { -// // max bytes: 1856 -// certificate: &'a [u8], // tag: 0x70 -// // 1B -// cert_info: CertInfo, // tag: 0x71 -// // 38 -// // mscuid: ?, // tag: 0x72 -// error_detection_code: [u8; 0], // tag: 0xFE -// } - -// impl Encodable for CertInfo { -// fn encoded_len(&self) -> der::Result { -// Length::from(1) -// } - -// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { -// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) -// } -// } - -// #[derive(Encodable)] -// pub struct DiscoveryObject<'a> { -// #[tlv(tag = "0x4F")] -// piv_card_application_aid: &'a [u8; 11], // tag: 0x4F, max bytes = 12, -// #[tlv(tag = 0x5F2f)] -// pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, -// } - -// impl Encodable for CertInfo { -// fn encoded_len(&self) -> der::Result { -// Length::from(1) -// } - -// fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { -// encoder.encode(der::Any::new(0x71, &[u8::from(self)])) -// } -// } - -// } diff --git a/src/error.rs b/src/error.rs deleted file mode 100644 index 4131ea0..0000000 --- a/src/error.rs +++ /dev/null @@ -1,110 +0,0 @@ -pub enum Error { - VerificationFailed { remaining: u8 }, // 63 00 or 63 CX - SecureMessagingNotSupported, // 68 82 - SecurityStatusNotSatisfied, // 69 82 - AuthenticationMethodBlocked, // 69 83 - // ExpectedSecureMessagingDataObjectsMissing, // 69 87 - // SecureMessagingDataObjectsIncorrect, // 69 88 - IncorrectParameterInCommandDataField, // 6A 80 - FunctionNotSupported, // 6A 81 - DataObjectOrApplicationNotFound, // 6A 82 - NotEnoughMemory, // 6A 84 - IncorrecParameterInP1OrP2, // 6A 86 - ReferencedDataOrReferenceDataNotFound, // 6A 88 -} - -pub enum Success { - Success, // 61 xx - SuccessResponseDataStillAvailable(u8), // 90 00 -} - -pub type Result = core::result::Result; - -// macro_rules! status_word { -// ($($Name:ident: [$sw1:expr, $sw2:tt],)*) => { -// $( -// // pub struct $Name {} - -// status_word! ($Name, $sw1, $sw2); -// )* - -// pub enum StatusWord { -// $($Name($Name),)* -// } -// }; - -// ($Name:ident, $sw1:expr, XX) => { -// pub struct $Name { -// sw2: u8, -// } - -// impl $Name { -// const SW1: u8 = $sw1; - -// pub fn new(sw2: u8) -> Self { -// Self { sw2 } -// } - -// pub fn as_bytes(&self) -> [u8; 2] { -// [Self::SW1, self.sw2] -// } - -// } - -// // impl core::ops::Deref for $Name { -// // type Target = [u8; 2]; -// // fn deref(&self) -> &Self::Target { -// // &[Self::SW1, self.sw2] -// // } -// // } - -// }; - -// ($Name:ident, $sw1:expr, $sw2:expr) => { -// #[derive(Default)] -// pub struct $Name {} - -// impl $Name { -// const SW1: u8 = $sw1; -// const SW2: u8 = $sw2; - -// pub fn new() -> Self { -// Default::default() -// } - -// pub fn as_bytes(&self) -> [u8; 2] { -// [Self::SW1, Self::SW2] -// } -// } -// }; -// } - -// status_word! { -// SecurityStatusNotSatisfied: [0x69, 0x82], -// NotFound: [0x6a, 0x82], -// Success: [0x90, 0x00], - -// SuccessBytesRemaining: [0x61, XX ], -// } - -// pub trait StatusWordTrait { -// fn sw1(&self) -> u8; -// fn sw2(&self) -> u8; -// -// fn sw(&self) -> [u8; 2] { -// [self.sw1(), self.sw2()] -// } -// } - -// #[cfg(test)] -// mod tests { -// use super::*; - -// #[test] -// fn deref() { -// let sw = SuccessBytesRemaining::new(42); -// println!("SW: {:?}", &sw.as_bytes()); -// } - -// } - diff --git a/src/lib.rs b/src/lib.rs index 29d1897..8d3df91 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -197,87 +197,6 @@ where Ok(()) } - // pub fn old_respond(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result { - - // // TEMP - // // blocking::dbg!(self.state.persistent(&mut self.trussed).timestamp(&mut self.trussed)); - - // // handle CLA - // // - command chaining not supported - // // - secure messaging not supported - // // - only channel zero supported - // // - ensure INS known to us - - // let last_or_only = command.class().chain().last_or_only(); - - // // TODO: avoid owned copy? - // let owned_command = match self.state.runtime.chained_command.as_mut() { - // Some(command_so_far) => { - // // TODO: make sure the prefix matches, e.g. '00 DB 3F FF' - // command_so_far.data_mut().extend_from_slice(command.data()).unwrap(); - - // if last_or_only { - // let total_command = command_so_far.clone(); - // self.state.runtime.chained_command = None; - // total_command - // } else { - // return Ok(Default::default()); - // } - // } - - // None => { - // if last_or_only { - // // iso7816::Command - // command.clone() - // } else { - // self.state.runtime.chained_command = Some(command.clone()); - // return Ok(Default::default()); - // } - // } - // }; - - // let command = &owned_command; - - // let class = command.class(); - - // if !class.secure_messaging().none() { - // return Err(Status::SecureMessagingNotSupported); - // } - - // if class.channel() != Some(0) { - // return Err(Status::LogicalChannelNotSupported); - // } - - // // info!("CLA = {:?}", &command.class()); - // info!("INS = {:?}, P1 = {:X}, P2 = {:X}", - // &command.instruction(), - // command.p1, command.p2, - // ); - // // info!("extended = {:?}", command.extended); - - // // info!("INS = {:?}" &command.instruction()); - // match command.instruction() { - // Instruction::GetData => self.get_data(command, reply), - // Instruction::PutData => self.put_data(command), - // Instruction::Verify => panic!(),//self.old_verify(command), - // Instruction::ChangeReferenceData => panic!(),//self.change_reference_data(command), - // Instruction::GeneralAuthenticate => self.general_authenticate(command, reply), - // Instruction::GenerateAsymmetricKeyPair => self.generate_asymmetric_keypair(command, reply), - - // Instruction::Unknown(ins) => { - - // // see if it's a Yubico thing - // if let Ok(instruction) = YubicoPivExtension::try_from(ins) { - // self.yubico_piv_extension(command, instruction, reply) - // } else { - // Err(Status::FunctionNotSupported) - // } - // } - - // _ => Err(Status::FunctionNotSupported), - // } - // } - // SP 800-73-4, Part 2, Section 3.2.4 // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=92 // @@ -530,153 +449,6 @@ where Ok(()) } - //fn change_reference_data(&mut self, command: &Command) -> Result { - // // The way `piv-go` blocks PUK (which it needs to do because Yubikeys only - // // allow their Reset if PIN+PUK are blocked) is that it sends "change PUK" - // // with random (i.e. incorrect) PUK listed as both old and new PUK. - // // - // // 00 24 00 81 10 - // // 32 38 36 34 31 39 30 36 32 38 36 34 31 39 30 36 - // // - // // For now, we don't support PUK, so we can just return "Blocked" directly - // // if the key reference in P2 is '81' = PUK - - // // application PIN - // if command.p2 == 0x80 { - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if command.data().len() != 16 { - // return Err(Status::IncorrectDataParameter); - // } - - // let (old_pin, new_pin) = command.data().split_at(8); - - // let old_pin = match state::Pin::try_new(old_pin) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // let new_pin = match state::Pin::try_new(new_pin) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // if !self.state.persistent(&mut self.trussed).verify_pin(&old_pin) { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = false; - // return Err(Status::RemainingRetries(remaining)); - // } - - // self.state.persistent(&mut self.trussed).reset_consecutive_pin_mismatches(&mut self.trussed); - // self.state.persistent(&mut self.trussed).set_pin(&mut self.trussed, new_pin); - // self.state.runtime.app_security_status.pin_verified = true; - // return Ok(()); - // } - - // // PUK - // if command.p2 == 0x81 { - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_puk_retries(); - - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if command.data().len() != 16 { - // return Err(Status::IncorrectDataParameter); - // } - - // let (old_puk, new_puk) = command.data().split_at(8); - - // let old_puk = match state::Pin::try_new(old_puk) { - // Ok(puk) => puk, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // let new_puk = match state::Pin::try_new(new_puk) { - // Ok(puk) => puk, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // if !self.state.persistent(&mut self.trussed).verify_puk(&old_puk) { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_puk_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.puk_verified = false; - // return Err(Status::RemainingRetries(remaining)); - // } - - // self.state.persistent(&mut self.trussed).reset_consecutive_puk_mismatches(&mut self.trussed); - // self.state.persistent(&mut self.trussed).set_puk(&mut self.trussed, new_puk); - // self.state.runtime.app_security_status.puk_verified = true; - // return Ok(()); - // } - - // Err(Status::KeyReferenceNotFound) - //} - - //fn old_verify(&mut self, command: &Command) -> Result { - // // we only implement our own PIN, not global Pin, not OCC data, not pairing code - // if command.p2 != 0x80 { - // return Err(Status::KeyReferenceNotFound); - // } - - // let p1 = command.p1; - // if p1 != 0x00 && p1 != 0xFF { - // return Err(Status::IncorrectP1OrP2Parameter); - // } - - // // all above failures shall not change security status or retry counter - - // // 1) If p1 is FF, "log out" of PIN - // if p1 == 0xFF { - // if command.data().len() != 0 { - // return Err(Status::IncorrectDataParameter); - // } else { - // self.state.runtime.app_security_status.pin_verified = false; - // return Ok(()); - // } - // } - - // // 2) Get retries (or whether verification is even needed) by passing no data - // if p1 == 0x00 && command.data().len() == 0 { - // if self.state.runtime.app_security_status.pin_verified { - // return Ok(()); - // } else { - // let retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - // return Err(Status::RemainingRetries(retries)); - // } - // } - - // // if malformed PIN is sent, no security implication - // if command.data().len() != 8 { - // return Err(Status::IncorrectDataParameter); - // } - - // let sent_pin = match state::Pin::try_new(&command.data()) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // // 3) Verify le PIN! - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if self.state.persistent(&mut self.trussed).verify_pin(&sent_pin) { - // self.state.persistent(&mut self.trussed).reset_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = true; - // Ok(()) - - // } else { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = false; - // Err(Status::RemainingRetries(remaining)) - // } - //} - pub fn generate_asymmetric_keypair( &mut self, command: &iso7816::Command, diff --git a/src/piv_types.rs b/src/piv_types.rs index 9ef4506..47d39e9 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -305,23 +305,6 @@ pub struct CardHolderUniqueIdentifier<'l> { error_detection_code: [u8; 0], } -// #[derive(Decodable, Encodable)] -// #[tlv(application, number = "0x13")] -// pub struct CardHolderUniqueIdentifier { -// #[tlv(slice, simple = "0x30")] -// fasc_n: [u8; 25], -// // #[tlv(slice, simple = "0x33")] -// // duns: [u8; 9], -// #[tlv(slice, simple = "0x34")] -// guid: [u8; 16], -// #[tlv(slice, simple = "0x35")] -// expiration_date: [u8; 8], // YYYYMMDD -// #[tlv(slice, simple = "0x3E")] -// issuer_asymmetric_signature: [u8; 1], -// #[tlv(slice, simple = "0xFE")] -// error_detection_code: [u8; 0], -// } - /// Corresponds to bit string in CBD (see https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf) /// 11010_10011_10011_10011_10011_10110_00001_00001_00001_00001 /// 10110_00001_00001_00001_00001_00001_00001_10110_00001_10110 diff --git a/src/state.rs b/src/state.rs index bba3932..cfc78c4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -172,46 +172,6 @@ impl State { } } -// #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -// pub struct Pin { -// // padded_pin: [u8; 8] -// pin: heapless_bytes::Bytes, -// } - -// impl Default for Pin { -// /// Default is "202020" -// /// But right now we have to use "123456" cause.. Filo -// fn default() -> Self { -// // Self::try_new(b"202020\xff\xff").unwrap() -// Self::try_new(b"123456\xff\xff").unwrap() -// } -// } - -// impl Pin { -// pub fn try_new(padded_pin: &[u8]) -> Result { -// if padded_pin.len() != 8 { -// return Err(()); -// } -// let first_pad_byte = padded_pin.iter().position(|&b| b == 0xff); -// let unpadded_pin = match first_pad_byte { -// Some(l) => &padded_pin[..l], -// None => padded_pin, -// }; -// if unpadded_pin.len() < 6 { -// return Err(()); -// } -// let valid_bytes = unpadded_pin.iter().all(|&b| b >= b'0' && b <= b'9'); -// if valid_bytes { -// Ok(Self { -// // padded_pin: padded_pin.try_into().unwrap(), -// pin: Bytes::from_slice(padded_pin).unwrap(),//padded_pin.try_into().unwrap(), -// }) -// } else { -// Err(()) -// } -// } -// } - #[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct PersistentState { pub keys: Keys, From 8477aa13338e7f247825c61053086d9b2664a15b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 1 Nov 2022 11:52:20 +0100 Subject: [PATCH 22/59] Add yubico commands --- src/commands.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++- src/constants.rs | 35 --------------------------------- src/lib.rs | 13 +++++++----- src/piv_types.rs | 2 +- src/state.rs | 2 ++ 5 files changed, 61 insertions(+), 42 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 4c96e08..b8f81c0 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -8,8 +8,22 @@ use core::convert::{TryFrom, TryInto}; // use flexiber::Decodable; use iso7816::{Instruction, Status}; +use crate::state::TouchPolicy; pub use crate::{container as containers, piv_types, Pin, Puk}; +// https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum YubicoPivExtension { + SetManagementKey(TouchPolicy), + ImportAsymmetricKey, + GetVersion, + Reset, + SetPinRetries, + Attest, + GetSerial, // also used via 0x01 + GetMetadata, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Command<'l> { /// Select the application @@ -36,6 +50,9 @@ pub enum Command<'l> { /// Store a data object / container. PutData(PutData), GenerateAsymmetric(GenerateAsymmetric), + + /* Yubico commands */ + YkExtension(YubicoPivExtension), } impl<'l> Command<'l> { @@ -127,7 +144,6 @@ impl TryFrom for VerifyLogout { } } } - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct VerifyArguments<'l> { pub key_reference: VerifyKeyReference, @@ -470,6 +486,39 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { }, )?) } + // (0x00, 0x01, 0x10, 0x00) + (0x00, Instruction::Unknown(0x01), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::GetSerial) + } + (0x00, Instruction::Unknown(0xff), 0xFF, 0xFE) => { + Self::YkExtension(YubicoPivExtension::SetManagementKey(TouchPolicy::Never)) + } + (0x00, Instruction::Unknown(0xff), 0xFF, 0xFF) => { + Self::YkExtension(YubicoPivExtension::SetManagementKey(TouchPolicy::Always)) + } + (0x00, Instruction::Unknown(0xfe), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::ImportAsymmetricKey) + } + (0x00, Instruction::Unknown(0xfd), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::GetVersion) + } + (0x00, Instruction::Unknown(0xfb), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::Reset) + } + (0x00, Instruction::Unknown(0xfa), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::SetPinRetries) + } + // (0x00, 0xf9, 0x9a, 0x00) + (0x00, Instruction::Unknown(0xf9), _, _) => { + Self::YkExtension(YubicoPivExtension::Attest) + } + // (0x00, 0xf8, 0x00, 0x00) + (0x00, Instruction::Unknown(0xf8), _, _) => { + Self::YkExtension(YubicoPivExtension::GetSerial) + } + (0x00, Instruction::Unknown(0xf7), _, _) => { + Self::YkExtension(YubicoPivExtension::GetMetadata) + } _ => return Err(Status::FunctionNotSupported), }) diff --git a/src/constants.rs b/src/constants.rs index dc60c56..3268639 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -135,41 +135,6 @@ impl YubicoObjects { pub const AttestationCertificate: &'static [u8] = b"\x5f\xff\x01"; } -// https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html -#[repr(u8)] -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum YubicoPivExtension { - SetManagementKey = 0xff, - ImportAsymmetricKey = 0xfe, - GetVersion = 0xfd, - Reset = 0xfb, - SetPinRetries = 0xfa, - Attest = 0xf9, - GetSerial = 0xf8, // also used via 0x01 - GetMetadata = 0xf7, -} - -impl core::convert::TryFrom for YubicoPivExtension { - type Error = (); - fn try_from(ins: u8) -> core::result::Result { - Ok(match ins { - // (0x00, 0x01, 0x10, 0x00) - 0x01 => YubicoPivExtension::GetSerial, - 0xff => YubicoPivExtension::SetManagementKey, - 0xfe => YubicoPivExtension::ImportAsymmetricKey, - 0xfd => YubicoPivExtension::GetVersion, - 0xfb => YubicoPivExtension::Reset, - 0xfa => YubicoPivExtension::SetPinRetries, - // (0x00, 0xf9, 0x9a, 0x00) - 0xf9 => YubicoPivExtension::Attest, - // (0x00, 0xf8, 0x00, 0x00) - 0xf8 => YubicoPivExtension::GetSerial, - 0xf7 => YubicoPivExtension::GetMetadata, - _ => return Err(()), - }) - } -} - pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &[u8; 351] = &[ 0x53, 0x82, 0x01, 0x5b, 0x70, 0x82, 0x01, 0x52, 0x30, 0x82, 0x01, 0x4e, 0x30, 0x81, 0xf5, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0x8e, 0x46, 0x32, 0xd8, 0xf0, 0xc1, 0xf7, 0xc1, 0x4d, diff --git a/src/lib.rs b/src/lib.rs index 8d3df91..7d7b1ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,7 +8,7 @@ extern crate log; delog::generate_macros!(); pub mod commands; -pub use commands::Command; +pub use commands::{Command, YubicoPivExtension}; pub mod constants; pub mod container; pub mod derp; @@ -89,14 +89,17 @@ where reply: &mut Data, ) -> Result { info!("PIV responding to {:?}", command); - let command: Command = command.try_into()?; - info!("parsed: {:?}", &command); + let parsed_command: Command = command.try_into()?; + info!("parsed: {:?}", &parsed_command); - match command { + match parsed_command { Command::Verify(verify) => self.verify(verify), Command::ChangeReference(change_reference) => self.change_reference(change_reference), Command::GetData(container) => self.get_data(container, reply), Command::Select(_aid) => self.select(reply), + Command::YkExtension(yk_command) => { + self.yubico_piv_extension(command, yk_command, reply) + } _ => todo!(), } } @@ -827,7 +830,7 @@ where .ok(); } - YubicoPivExtension::SetManagementKey => { + YubicoPivExtension::SetManagementKey(_touch_policy) => { // cmd := apdu{ // instruction: insSetMGMKey, // param1: 0xff, diff --git a/src/piv_types.rs b/src/piv_types.rs index 47d39e9..0cb7610 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -52,7 +52,7 @@ impl TryFrom<&[u8]> for Puk { } #[repr(u8)] -#[derive(Clone, Copy, Eq, PartialEq)] +#[derive(Clone, Copy, Eq, PartialEq, Debug)] // As additional reference, see: // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 // diff --git a/src/state.rs b/src/state.rs index cfc78c4..c3f49ef 100644 --- a/src/state.rs +++ b/src/state.rs @@ -22,6 +22,8 @@ pub enum PinPolicy { Once, Always, } + +#[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum TouchPolicy { Never, Always, From b9164b5f0dd7f8712fd06e346f0c24b117cbec94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 3 Nov 2022 10:05:36 +0100 Subject: [PATCH 23/59] Add gitlab ci --- .gitignore | 2 ++ .gitlab-ci.yml | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ Makefile | 5 ++++- ci/Dockerfile | 18 +++++++++++++++++ ci/Makefile | 29 ++++++++++++++++++++++++++++ ci/entrypoint.sh | 12 ++++++++++++ 6 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 .gitlab-ci.yml create mode 100644 ci/Dockerfile create mode 100644 ci/Makefile create mode 100644 ci/entrypoint.sh diff --git a/.gitignore b/.gitignore index 96ef6c0..71af5be 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /target Cargo.lock +tarpaulin-report.html +cobertura.xml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..34915ac --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,50 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +include: 'https://raw.githubusercontent.com/Nitrokey/common-ci-jobs/master/common_jobs.yml' + +stages: + - pull-github + - build + - deploy + +variables: + GIT_STRATEGY: clone + GIT_DEPTH: 0 + GIT_SUBMODULE_STRATEGY: recursive + REPO_NAME: piv-authenticator + MAIN_BRANCH: main + COMMON_PULL: "true" + COMMON_UPLOAD_NIGHTLY: "false" + COMMON_GITHUB_RELEASE: "false" + COMMON_UPLOAD_FILES: "false" + +build: + image: registry.git.nitrokey.com/nitrokey/piv-authenticator/piv-authenticator-build:latest + rules: + - if: '$CI_PIPELINE_SHOULD_NOT_BUILD == "true"' + when: never + - if: '$CI_PIPELINE_SOURCE == "push"' + - if: '$CI_PIPELINE_SOURCE == "web"' + - if: '$CI_PIPELINE_SOURCE == "schedule"' + tags: + - docker + stage: build + before_script: + - cargo --version + script: + - make ci + after_script: + - cp /app/.cache/scdaemon.log scdaemon.log + - wget $icon_server/checkmark/$CI_COMMIT_REF_NAME/$CI_COMMIT_SHA/$CI_JOB_NAME/$CI_JOB_STATUS/${CI_JOB_URL#*/*/*/} + coverage: '/^\d+.\d+% coverage/' + artifacts: + when: always + paths: + - "scdaemon.log" + - "cobertura.xml" + - "tarpaulin-report.html" + reports: + coverage_report: + coverage_format: cobertura + path: cobertura.xml diff --git a/Makefile b/Makefile index a81e9fe..9b86f58 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,6 @@ test: check: cargo fmt --check cargo check --all-targets --all-features - cargo check --target thumbv7em-none-eabi cargo clippy --all-targets --all-features -- -Dwarnings RUSTDOCFLAGS='-Dwarnings' cargo doc --all-features @@ -25,3 +24,7 @@ tarpaulin: .PHONY: example example: cargo run --example virtual --features virtual + +.PHONY: ci +ci: check tarpaulin + diff --git a/ci/Dockerfile b/ci/Dockerfile new file mode 100644 index 0000000..036b5b6 --- /dev/null +++ b/ci/Dockerfile @@ -0,0 +1,18 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +FROM docker.io/rust:latest + +RUN apt update && apt install --yes scdaemon libclang-dev llvm python3-pip vsmartcard-vpcd pkg-config nettle-dev libpcsclite-dev + +RUN rustup component add clippy rustfmt && rustup target add thumbv7em-none-eabi +RUN cargo install cargo-tarpaulin --profile release && rm -rf "$CARGO_HOME"/registry +# initialize cargo cache +RUN cargo search + +ENV CARGO_HOME=/app/.cache/cargo + +WORKDIR /app + +COPY entrypoint.sh /entrypoint.sh +ENTRYPOINT ["/bin/bash", "/entrypoint.sh"] diff --git a/ci/Makefile b/ci/Makefile new file mode 100644 index 0000000..28ae5e9 --- /dev/null +++ b/ci/Makefile @@ -0,0 +1,29 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +-include config.mk + +TAG := registry.git.nitrokey.com/nitrokey/piv-authenticator/piv-authenticator-build +DOCKER ?= docker +FUZZ_JOBS?=$(shell nproc) +FUZZ_DURATION?="0" + +.PHONY: build +build: + $(DOCKER) build . --tag $(TAG) + +.PHONY: push +push: + $(DOCKER) push $(TAG) + +.PHONY: run +run: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make ci + +.PHONY: test +test: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make test + +.PHONY: fuzz +fuzz: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make fuzz FUZZ_JOBS=${FUZZ_JOBS} FUZZ_DURATION=${FUZZ_DURATION} diff --git a/ci/entrypoint.sh b/ci/entrypoint.sh new file mode 100644 index 0000000..4c27a27 --- /dev/null +++ b/ci/entrypoint.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +set -e +mkdir -p /app/.cache +if [ ! -e "$CARGO_HOME" ] +then + cp -r /usr/local/cargo $CARGO_HOME +fi +pcscd +exec "$@" From 253b0e4463f12ee685d06cf5ce1c349eb2255bc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 3 Nov 2022 11:11:37 +0100 Subject: [PATCH 24/59] Use hex! for constants --- src/constants.rs | 249 ++++++++++++++++++++++++----------------------- 1 file changed, 128 insertions(+), 121 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 3268639..29604a2 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -132,133 +132,140 @@ impl DataObjects { pub struct YubicoObjects {} #[allow(non_upper_case_globals)] impl YubicoObjects { - pub const AttestationCertificate: &'static [u8] = b"\x5f\xff\x01"; + pub const AttestationCertificate: &'static [u8] = &hex!("5fff01"); } -pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &[u8; 351] = &[ - 0x53, 0x82, 0x01, 0x5b, 0x70, 0x82, 0x01, 0x52, 0x30, 0x82, 0x01, 0x4e, 0x30, 0x81, 0xf5, 0xa0, - 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0x8e, 0x46, 0x32, 0xd8, 0xf0, 0xc1, 0xf7, 0xc1, 0x4d, - 0x67, 0xd1, 0x4b, 0xfd, 0xe3, 0x64, 0x8e, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, - 0x04, 0x03, 0x02, 0x30, 0x2a, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0d, - 0x79, 0x75, 0x62, 0x69, 0x6b, 0x65, 0x79, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x31, 0x10, 0x30, - 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x07, 0x28, 0x64, 0x65, 0x76, 0x65, 0x6c, 0x29, 0x30, - 0x20, 0x17, 0x0d, 0x32, 0x30, 0x30, 0x35, 0x30, 0x39, 0x31, 0x32, 0x30, 0x30, 0x34, 0x39, 0x5a, - 0x18, 0x0f, 0x32, 0x30, 0x36, 0x32, 0x30, 0x35, 0x30, 0x39, 0x31, 0x33, 0x30, 0x30, 0x34, 0x39, - 0x5a, 0x30, 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x07, 0x53, 0x53, - 0x48, 0x20, 0x6b, 0x65, 0x79, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, - 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, - 0x83, 0x2a, 0x92, 0x47, 0x8b, 0x4e, 0xb5, 0x7a, 0x46, 0x1b, 0x2a, 0x5e, 0x0e, 0x44, 0x25, 0x03, - 0x9b, 0xfb, 0x27, 0x94, 0x56, 0x78, 0xed, 0x48, 0x2b, 0x1c, 0xf2, 0x21, 0x61, 0x6d, 0xda, 0xbd, - 0x3d, 0x8f, 0xb6, 0x2b, 0x75, 0xc6, 0xac, 0x3f, 0x83, 0x4a, 0x59, 0x4e, 0x5a, 0xdf, 0xed, 0xe7, - 0x3a, 0xe4, 0x99, 0x1a, 0xe7, 0x33, 0x2f, 0x61, 0x2b, 0xcf, 0x6c, 0x0e, 0xd6, 0x78, 0x72, 0xeb, - 0xa3, 0x12, 0x30, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, - 0x03, 0x02, 0x03, 0x88, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, - 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x03, 0x09, 0xe2, 0x84, 0x47, 0xdc, 0xb7, 0xc5, 0x32, - 0xee, 0x97, 0x5b, 0x9e, 0x44, 0xfa, 0x42, 0x06, 0xf2, 0x26, 0x67, 0xc1, 0xa6, 0xc6, 0x4a, 0xdc, - 0x6a, 0x0b, 0x5d, 0xa9, 0x87, 0x63, 0x8b, 0x02, 0x21, 0x00, 0xbb, 0x4e, 0xcb, 0x18, 0x72, 0xcc, - 0x12, 0x39, 0xd3, 0xd4, 0x18, 0x36, 0x14, 0x18, 0xe4, 0xa9, 0xf3, 0x83, 0x81, 0x4b, 0x74, 0x0f, - 0x93, 0x33, 0xb8, 0x47, 0xa9, 0x73, 0xc2, 0x82, 0x92, 0x3e, 0x71, 0x01, 0x00, 0xfe, 0x00, -]; +pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &[u8; 351] = &hex!( + " + 5382 015b 7082 0152 3082 014e 3081 f5a0 + 0302 0102 0211 008e 4632 d8f0 c1f7 c14d + 67d1 4bfd e364 8e30 0a06 082a 8648 ce3d + 0403 0230 2a31 1630 1406 0355 040a 130d + 7975 6269 6b65 792d 6167 656e 7431 1030 + 0e06 0355 040b 1307 2864 6576 656c 2930 + 2017 0d32 3030 3530 3931 3230 3034 395a + 180f 3230 3632 3035 3039 3133 3030 3439 + 5a30 1231 1030 0e06 0355 0403 1307 5353 + 4820 6b65 7930 5930 1306 072a 8648 ce3d + 0201 0608 2a86 48ce 3d03 0107 0342 0004 + 832a 9247 8b4e b57a 461b 2a5e 0e44 2503 + 9bfb 2794 5678 ed48 2b1c f221 616d dabd + 3d8f b62b 75c6 ac3f 834a 594e 5adf ede7 + 3ae4 991a e733 2f61 2bcf 6c0e d678 72eb + a312 3010 300e 0603 551d 0f01 01ff 0404 + 0302 0388 300a 0608 2a86 48ce 3d04 0302 + 0348 0030 4502 2003 09e2 8447 dcb7 c532 + ee97 5b9e 44fa 4206 f226 67c1 a6c6 4adc + 6a0b 5da9 8763 8b02 2100 bb4e cb18 72cc + 1239 d3d4 1836 1418 e4a9 f383 814b 740f + 9333 b847 a973 c282 923e 7101 00fe 00 +" +); + +pub const YUBICO_ATTESTATION_CERTIFICATE: &[u8; 754] = &hex!( + " + 5382 02ee 7082 02ea 3082 02e6 3082 01ce + a003 0201 0202 0900 a485 22aa 34af ae4f + 300d 0609 2a86 4886 f70d 0101 0b05 0030 + 2b31 2930 2706 0355 0403 0c20 5975 6269 + 636f 2050 4956 2052 6f6f 7420 4341 2053 + 6572 6961 6c20 3236 3337 3531 3020 170d + 3136 3033 3134 3030 3030 3030 5a18 0f32 + 3035 3230 3431 3730 3030 3030 305a 3021 + 311f 301d 0603 5504 030c 1659 7562 6963 + 6f20 5049 5620 4174 7465 7374 6174 696f + 6e30 8201 2230 0d06 092a 8648 86f7 0d01 + 0101 0500 0382 010f 0030 8201 0a02 8201 + 0100 aba9 0b16 9bef 31cc 3eac 185a 2d45 + 8075 70c7 58b0 6c3f 1b59 0d49 b989 e86f + cebb 276f d83c 603a 8500 ef5c bc40 993d + 41ee eac0 817f 7648 e4a9 4cbc d56b e11f + 0a60 93c6 feaa d28d 8ee2 b7cd 8b2b f79b + dd5a ab2f cfb9 0e54 ceec 8df5 5ed7 7b91 + c3a7 569c dcc1 0686 7636 4453 fb08 25d8 + 06b9 068c 81fd 6367 ca3c a8b8 ea1c a6ca + db44 7b12 cab2 3401 7e73 e436 83df ebf9 + 2300 0701 6a07 198a 6456 9d10 8ac5 7302 + 3d18 6eaf 3fc3 02a7 c0f7 a2fd 6d5a 4276 + 4ed6 c01e d6c0 c6aa 5da7 1a9f 10db 3057 + 185c b5b5 fd0c be49 2422 af1e 564a 3444 + d4aa d4e1 ae95 4c75 c088 61f4 8c7e 54f3 + 13eb 0fe5 2b52 605a 6eba d7e5 8c63 da51 + 1abb 225c 372b d7d1 7057 4c2e dc35 3c22 + 989b 0203 0100 01a3 1530 1330 1106 0a2b + 0601 0401 82c4 0a03 0304 0304 0303 300d + 0609 2a86 4886 f70d 0101 0b05 0003 8201 + 0100 5280 5a6d c39e df47 a8f1 b2a5 9ca3 + 8081 3b1d 6aeb 6a12 624b 11fd 8d30 f17b + fc71 10c9 b208 fcd1 4e35 7f45 f210 a252 + b9d4 b302 1a01 5607 6bfa 64a7 08f0 03fb + 27a9 608d 0dd3 ac5a 10cf 2096 4e82 bc9d + e337 dac1 4c50 e13d 16b4 caf4 1bff 0864 + c974 4f2a 3a43 e0de 4279 f213 ae77 a1e2 + ae6b df72 a5b6 ced7 4c90 13df dedb f28b + 3445 8b30 dc51 aba9 34f8 a9e5 0c47 29aa + 2f42 54f2 f819 5ab4 89fe 1b9f 197a 16c8 + c8ba 8f18 177a 07a9 97a1 56b9 525d a121 + c081 672d e80e a651 b908 b09d d360 1c70 + a30f fad8 62d8 792b 0ae6 42fc f82d f5e4 + cdfb 1596 23ff b6c0 a7a7 e285 83f9 70c8 + 196b f3c1 3f37 4465 27fb 6788 c883 b72f + 851f 8044 bb72 ce06 8259 2d83 00e1 948d + a085 +" +); -pub const YUBICO_ATTESTATION_CERTIFICATE: &[u8; 754] = &[ - 0x53, 0x82, 0x02, 0xee, 0x70, 0x82, 0x02, 0xea, 0x30, 0x82, 0x02, 0xe6, 0x30, 0x82, 0x01, 0xce, - 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0xa4, 0x85, 0x22, 0xaa, 0x34, 0xaf, 0xae, 0x4f, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, - 0x2b, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x59, 0x75, 0x62, 0x69, - 0x63, 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41, 0x20, 0x53, - 0x65, 0x72, 0x69, 0x61, 0x6c, 0x20, 0x32, 0x36, 0x33, 0x37, 0x35, 0x31, 0x30, 0x20, 0x17, 0x0d, - 0x31, 0x36, 0x30, 0x33, 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x32, - 0x30, 0x35, 0x32, 0x30, 0x34, 0x31, 0x37, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x30, 0x21, - 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x59, 0x75, 0x62, 0x69, 0x63, - 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, - 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, - 0x01, 0x00, 0xab, 0xa9, 0x0b, 0x16, 0x9b, 0xef, 0x31, 0xcc, 0x3e, 0xac, 0x18, 0x5a, 0x2d, 0x45, - 0x80, 0x75, 0x70, 0xc7, 0x58, 0xb0, 0x6c, 0x3f, 0x1b, 0x59, 0x0d, 0x49, 0xb9, 0x89, 0xe8, 0x6f, - 0xce, 0xbb, 0x27, 0x6f, 0xd8, 0x3c, 0x60, 0x3a, 0x85, 0x00, 0xef, 0x5c, 0xbc, 0x40, 0x99, 0x3d, - 0x41, 0xee, 0xea, 0xc0, 0x81, 0x7f, 0x76, 0x48, 0xe4, 0xa9, 0x4c, 0xbc, 0xd5, 0x6b, 0xe1, 0x1f, - 0x0a, 0x60, 0x93, 0xc6, 0xfe, 0xaa, 0xd2, 0x8d, 0x8e, 0xe2, 0xb7, 0xcd, 0x8b, 0x2b, 0xf7, 0x9b, - 0xdd, 0x5a, 0xab, 0x2f, 0xcf, 0xb9, 0x0e, 0x54, 0xce, 0xec, 0x8d, 0xf5, 0x5e, 0xd7, 0x7b, 0x91, - 0xc3, 0xa7, 0x56, 0x9c, 0xdc, 0xc1, 0x06, 0x86, 0x76, 0x36, 0x44, 0x53, 0xfb, 0x08, 0x25, 0xd8, - 0x06, 0xb9, 0x06, 0x8c, 0x81, 0xfd, 0x63, 0x67, 0xca, 0x3c, 0xa8, 0xb8, 0xea, 0x1c, 0xa6, 0xca, - 0xdb, 0x44, 0x7b, 0x12, 0xca, 0xb2, 0x34, 0x01, 0x7e, 0x73, 0xe4, 0x36, 0x83, 0xdf, 0xeb, 0xf9, - 0x23, 0x00, 0x07, 0x01, 0x6a, 0x07, 0x19, 0x8a, 0x64, 0x56, 0x9d, 0x10, 0x8a, 0xc5, 0x73, 0x02, - 0x3d, 0x18, 0x6e, 0xaf, 0x3f, 0xc3, 0x02, 0xa7, 0xc0, 0xf7, 0xa2, 0xfd, 0x6d, 0x5a, 0x42, 0x76, - 0x4e, 0xd6, 0xc0, 0x1e, 0xd6, 0xc0, 0xc6, 0xaa, 0x5d, 0xa7, 0x1a, 0x9f, 0x10, 0xdb, 0x30, 0x57, - 0x18, 0x5c, 0xb5, 0xb5, 0xfd, 0x0c, 0xbe, 0x49, 0x24, 0x22, 0xaf, 0x1e, 0x56, 0x4a, 0x34, 0x44, - 0xd4, 0xaa, 0xd4, 0xe1, 0xae, 0x95, 0x4c, 0x75, 0xc0, 0x88, 0x61, 0xf4, 0x8c, 0x7e, 0x54, 0xf3, - 0x13, 0xeb, 0x0f, 0xe5, 0x2b, 0x52, 0x60, 0x5a, 0x6e, 0xba, 0xd7, 0xe5, 0x8c, 0x63, 0xda, 0x51, - 0x1a, 0xbb, 0x22, 0x5c, 0x37, 0x2b, 0xd7, 0xd1, 0x70, 0x57, 0x4c, 0x2e, 0xdc, 0x35, 0x3c, 0x22, - 0x98, 0x9b, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x15, 0x30, 0x13, 0x30, 0x11, 0x06, 0x0a, 0x2b, - 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x03, 0x04, 0x03, 0x04, 0x03, 0x03, 0x30, 0x0d, - 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, - 0x01, 0x00, 0x52, 0x80, 0x5a, 0x6d, 0xc3, 0x9e, 0xdf, 0x47, 0xa8, 0xf1, 0xb2, 0xa5, 0x9c, 0xa3, - 0x80, 0x81, 0x3b, 0x1d, 0x6a, 0xeb, 0x6a, 0x12, 0x62, 0x4b, 0x11, 0xfd, 0x8d, 0x30, 0xf1, 0x7b, - 0xfc, 0x71, 0x10, 0xc9, 0xb2, 0x08, 0xfc, 0xd1, 0x4e, 0x35, 0x7f, 0x45, 0xf2, 0x10, 0xa2, 0x52, - 0xb9, 0xd4, 0xb3, 0x02, 0x1a, 0x01, 0x56, 0x07, 0x6b, 0xfa, 0x64, 0xa7, 0x08, 0xf0, 0x03, 0xfb, - 0x27, 0xa9, 0x60, 0x8d, 0x0d, 0xd3, 0xac, 0x5a, 0x10, 0xcf, 0x20, 0x96, 0x4e, 0x82, 0xbc, 0x9d, - 0xe3, 0x37, 0xda, 0xc1, 0x4c, 0x50, 0xe1, 0x3d, 0x16, 0xb4, 0xca, 0xf4, 0x1b, 0xff, 0x08, 0x64, - 0xc9, 0x74, 0x4f, 0x2a, 0x3a, 0x43, 0xe0, 0xde, 0x42, 0x79, 0xf2, 0x13, 0xae, 0x77, 0xa1, 0xe2, - 0xae, 0x6b, 0xdf, 0x72, 0xa5, 0xb6, 0xce, 0xd7, 0x4c, 0x90, 0x13, 0xdf, 0xde, 0xdb, 0xf2, 0x8b, - 0x34, 0x45, 0x8b, 0x30, 0xdc, 0x51, 0xab, 0xa9, 0x34, 0xf8, 0xa9, 0xe5, 0x0c, 0x47, 0x29, 0xaa, - 0x2f, 0x42, 0x54, 0xf2, 0xf8, 0x19, 0x5a, 0xb4, 0x89, 0xfe, 0x1b, 0x9f, 0x19, 0x7a, 0x16, 0xc8, - 0xc8, 0xba, 0x8f, 0x18, 0x17, 0x7a, 0x07, 0xa9, 0x97, 0xa1, 0x56, 0xb9, 0x52, 0x5d, 0xa1, 0x21, - 0xc0, 0x81, 0x67, 0x2d, 0xe8, 0x0e, 0xa6, 0x51, 0xb9, 0x08, 0xb0, 0x9d, 0xd3, 0x60, 0x1c, 0x70, - 0xa3, 0x0f, 0xfa, 0xd8, 0x62, 0xd8, 0x79, 0x2b, 0x0a, 0xe6, 0x42, 0xfc, 0xf8, 0x2d, 0xf5, 0xe4, - 0xcd, 0xfb, 0x15, 0x96, 0x23, 0xff, 0xb6, 0xc0, 0xa7, 0xa7, 0xe2, 0x85, 0x83, 0xf9, 0x70, 0xc8, - 0x19, 0x6b, 0xf3, 0xc1, 0x3f, 0x37, 0x44, 0x65, 0x27, 0xfb, 0x67, 0x88, 0xc8, 0x83, 0xb7, 0x2f, - 0x85, 0x1f, 0x80, 0x44, 0xbb, 0x72, 0xce, 0x06, 0x82, 0x59, 0x2d, 0x83, 0x00, 0xe1, 0x94, 0x8d, - 0xa0, 0x85, -]; +pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &[u8; 584] = &hex!( + " + 3082 0244 3082 012c a003 0201 0202 1100 + c636 e7b3 a5a5 a498 5d13 6e43 362d 13f7 + 300d 0609 2a86 4886 f70d 0101 0b05 0030 + 2131 1f30 1d06 0355 0403 0c16 5975 6269 + 636f 2050 4956 2041 7474 6573 7461 7469 + 6f6e 3020 170d 3136 3033 3134 3030 3030 + 3030 5a18 0f32 3035 3230 3431 3730 3030 + 3030 305a 3025 3123 3021 0603 5504 030c + 1a59 7562 694b 6579 2050 4956 2041 7474 + 6573 7461 7469 6f6e 2039 6130 5930 1306 + 072a 8648 ce3d 0201 0608 2a86 48ce 3d03 + 0107 0342 0004 832a 9247 8b4e b57a 461b + 2a5e 0e44 2503 9bfb 2794 5678 ed48 2b1c + f221 616d dabd 3d8f b62b 75c6 ac3f 834a + 594e 5adf ede7 3ae4 991a e733 2f61 2bcf + 6c0e d678 72eb a33c 303a 3011 060a 2b06 + 0104 0182 c40a 0303 0403 0403 0430 1306 + 0a2b 0601 0401 82c4 0a03 0704 0502 0352 + f743 3010 060a 2b06 0104 0182 c40a 0308 + 0402 0202 300d 0609 2a86 4886 f70d 0101 + 0b05 0003 8201 0100 0217 38a8 f61d 1735 + e130 9dd2 d5c4 d4d0 0de1 9f37 9abe cf63 + 6a0e 2bd0 d7a4 045c 407d f743 9be4 ee7d + 9655 d291 dc32 8254 fe2d 9f19 2354 bbdd + 7d6b e961 2a1d c813 65e2 049f a287 de61 + 92d5 de46 d4a4 c2a6 b480 5d4a a4d1 1ba7 + 34f2 977b 7a5a ad9a a85d 2ad4 7fb1 57bf + 261d 3da6 b3ea 3d3d f794 cd16 3640 24cd + 7c8e 7adb 2df9 22da 26b3 c1c8 00a3 4797 + 5210 1273 4baf 12fe b70d 9e91 30a7 52cf + 12d8 2bdf 126a b62f 3924 c604 a26f ed70 + b5f2 0d2a 73e3 38a9 9cfe 353e dc17 4055 + d595 7f05 8e24 c2b3 b105 2d69 0ccf 5bf7 + 0640 1736 0ac3 a5db 3cda 62f8 532d f13f + 0455 700c 437b 1fa3 63b1 a05e 8928 5b4f + 76a7 05e1 4c45 5514 ff10 1089 696a 133d + 89f2 cafd 149a c4d0 +" +); -pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &[u8; 584] = &[ - 0x30, 0x82, 0x02, 0x44, 0x30, 0x82, 0x01, 0x2c, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, - 0xc6, 0x36, 0xe7, 0xb3, 0xa5, 0xa5, 0xa4, 0x98, 0x5d, 0x13, 0x6e, 0x43, 0x36, 0x2d, 0x13, 0xf7, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, - 0x21, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x59, 0x75, 0x62, 0x69, - 0x63, 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x30, 0x20, 0x17, 0x0d, 0x31, 0x36, 0x30, 0x33, 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, - 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x32, 0x30, 0x35, 0x32, 0x30, 0x34, 0x31, 0x37, 0x30, 0x30, 0x30, - 0x30, 0x30, 0x30, 0x5a, 0x30, 0x25, 0x31, 0x23, 0x30, 0x21, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, - 0x1a, 0x59, 0x75, 0x62, 0x69, 0x4b, 0x65, 0x79, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, - 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x39, 0x61, 0x30, 0x59, 0x30, 0x13, 0x06, - 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, - 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x83, 0x2a, 0x92, 0x47, 0x8b, 0x4e, 0xb5, 0x7a, 0x46, 0x1b, - 0x2a, 0x5e, 0x0e, 0x44, 0x25, 0x03, 0x9b, 0xfb, 0x27, 0x94, 0x56, 0x78, 0xed, 0x48, 0x2b, 0x1c, - 0xf2, 0x21, 0x61, 0x6d, 0xda, 0xbd, 0x3d, 0x8f, 0xb6, 0x2b, 0x75, 0xc6, 0xac, 0x3f, 0x83, 0x4a, - 0x59, 0x4e, 0x5a, 0xdf, 0xed, 0xe7, 0x3a, 0xe4, 0x99, 0x1a, 0xe7, 0x33, 0x2f, 0x61, 0x2b, 0xcf, - 0x6c, 0x0e, 0xd6, 0x78, 0x72, 0xeb, 0xa3, 0x3c, 0x30, 0x3a, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, - 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x30, 0x13, 0x06, - 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x07, 0x04, 0x05, 0x02, 0x03, 0x52, - 0xf7, 0x43, 0x30, 0x10, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x08, - 0x04, 0x02, 0x02, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, - 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x02, 0x17, 0x38, 0xa8, 0xf6, 0x1d, 0x17, 0x35, - 0xe1, 0x30, 0x9d, 0xd2, 0xd5, 0xc4, 0xd4, 0xd0, 0x0d, 0xe1, 0x9f, 0x37, 0x9a, 0xbe, 0xcf, 0x63, - 0x6a, 0x0e, 0x2b, 0xd0, 0xd7, 0xa4, 0x04, 0x5c, 0x40, 0x7d, 0xf7, 0x43, 0x9b, 0xe4, 0xee, 0x7d, - 0x96, 0x55, 0xd2, 0x91, 0xdc, 0x32, 0x82, 0x54, 0xfe, 0x2d, 0x9f, 0x19, 0x23, 0x54, 0xbb, 0xdd, - 0x7d, 0x6b, 0xe9, 0x61, 0x2a, 0x1d, 0xc8, 0x13, 0x65, 0xe2, 0x04, 0x9f, 0xa2, 0x87, 0xde, 0x61, - 0x92, 0xd5, 0xde, 0x46, 0xd4, 0xa4, 0xc2, 0xa6, 0xb4, 0x80, 0x5d, 0x4a, 0xa4, 0xd1, 0x1b, 0xa7, - 0x34, 0xf2, 0x97, 0x7b, 0x7a, 0x5a, 0xad, 0x9a, 0xa8, 0x5d, 0x2a, 0xd4, 0x7f, 0xb1, 0x57, 0xbf, - 0x26, 0x1d, 0x3d, 0xa6, 0xb3, 0xea, 0x3d, 0x3d, 0xf7, 0x94, 0xcd, 0x16, 0x36, 0x40, 0x24, 0xcd, - 0x7c, 0x8e, 0x7a, 0xdb, 0x2d, 0xf9, 0x22, 0xda, 0x26, 0xb3, 0xc1, 0xc8, 0x00, 0xa3, 0x47, 0x97, - 0x52, 0x10, 0x12, 0x73, 0x4b, 0xaf, 0x12, 0xfe, 0xb7, 0x0d, 0x9e, 0x91, 0x30, 0xa7, 0x52, 0xcf, - 0x12, 0xd8, 0x2b, 0xdf, 0x12, 0x6a, 0xb6, 0x2f, 0x39, 0x24, 0xc6, 0x04, 0xa2, 0x6f, 0xed, 0x70, - 0xb5, 0xf2, 0x0d, 0x2a, 0x73, 0xe3, 0x38, 0xa9, 0x9c, 0xfe, 0x35, 0x3e, 0xdc, 0x17, 0x40, 0x55, - 0xd5, 0x95, 0x7f, 0x05, 0x8e, 0x24, 0xc2, 0xb3, 0xb1, 0x05, 0x2d, 0x69, 0x0c, 0xcf, 0x5b, 0xf7, - 0x06, 0x40, 0x17, 0x36, 0x0a, 0xc3, 0xa5, 0xdb, 0x3c, 0xda, 0x62, 0xf8, 0x53, 0x2d, 0xf1, 0x3f, - 0x04, 0x55, 0x70, 0x0c, 0x43, 0x7b, 0x1f, 0xa3, 0x63, 0xb1, 0xa0, 0x5e, 0x89, 0x28, 0x5b, 0x4f, - 0x76, 0xa7, 0x05, 0xe1, 0x4c, 0x45, 0x55, 0x14, 0xff, 0x10, 0x10, 0x89, 0x69, 0x6a, 0x13, 0x3d, - 0x89, 0xf2, 0xca, 0xfd, 0x14, 0x9a, 0xc4, 0xd0, -]; // pub const YUBICO_DEFAULT_MANAGEMENT_KEY: & [u8; 24] = b"123456781234567812345678"; -pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &[u8; 24] = &[ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, -]; +pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &[u8; 24] = &hex!( + " + 0102030405060708 + 0102030405060708 + 0102030405060708 +" +); // stolen from le yubico pub const DISCOVERY_OBJECT: &[u8; 20] = b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; - -// import secrets; secrets.token_bytes(16) -pub const GUID: &[u8; 16] = b"\x0c\x92\xc9\x04\xd0\xdeL\xd9\xf6\xd1\xa2\x9fE3\xca\xeb"; From ce76bcc198f25e68f6609dc78ba8c1d4019bd425 Mon Sep 17 00:00:00 2001 From: "lennard.boediger" Date: Fri, 4 Nov 2022 08:50:12 +0100 Subject: [PATCH 25/59] test ci From 53b0e71e61fa8afd0a3cb33e1bb18927d6f6a77e Mon Sep 17 00:00:00 2001 From: "lennard.boediger" Date: Fri, 4 Nov 2022 08:52:42 +0100 Subject: [PATCH 26/59] test ci From 46267de9388c77bd0a794ce5ec04d4d03ebf1a9b Mon Sep 17 00:00:00 2001 From: "lennard.boediger" Date: Fri, 4 Nov 2022 08:53:28 +0100 Subject: [PATCH 27/59] test webhook From 0f1aa824a89bf4e894945020aec57beb85d6c2f4 Mon Sep 17 00:00:00 2001 From: "lennard.boediger" Date: Fri, 4 Nov 2022 08:58:51 +0100 Subject: [PATCH 28/59] set initial-refacto as main branch for the ci --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 34915ac..30a01f8 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -13,7 +13,7 @@ variables: GIT_DEPTH: 0 GIT_SUBMODULE_STRATEGY: recursive REPO_NAME: piv-authenticator - MAIN_BRANCH: main + MAIN_BRANCH: initial-refacto COMMON_PULL: "true" COMMON_UPLOAD_NIGHTLY: "false" COMMON_GITHUB_RELEASE: "false" From f325e148aa672200eda2dd34bece6b0f1aea3aac Mon Sep 17 00:00:00 2001 From: "lennard.boediger" Date: Fri, 4 Nov 2022 10:46:16 +0100 Subject: [PATCH 29/59] move the checkmark call to the top of the after_script section --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 30a01f8..2d18f2f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -35,8 +35,8 @@ build: script: - make ci after_script: - - cp /app/.cache/scdaemon.log scdaemon.log - wget $icon_server/checkmark/$CI_COMMIT_REF_NAME/$CI_COMMIT_SHA/$CI_JOB_NAME/$CI_JOB_STATUS/${CI_JOB_URL#*/*/*/} + - cp /app/.cache/scdaemon.log scdaemon.log coverage: '/^\d+.\d+% coverage/' artifacts: when: always From 9ffff5c4086e4090a70207e8d534b57e3c9ffbac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 3 Nov 2022 16:36:21 +0100 Subject: [PATCH 30/59] Fix boilerplate for GENERAL AUTHENTICATE --- src/commands.rs | 27 +++--- src/lib.rs | 221 +++++++++-------------------------------------- src/piv_types.rs | 103 ++++++++++++++-------- src/tlv.rs | 96 ++++++++++++++++++++ 4 files changed, 215 insertions(+), 232 deletions(-) create mode 100644 src/tlv.rs diff --git a/src/commands.rs b/src/commands.rs index b8f81c0..2910ec4 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -46,7 +46,7 @@ pub enum Command<'l> { /// The most general purpose method, performing actual cryptographic operations /// /// In particular, this can also decrypt or similar. - Authenticate(Authenticate), + GeneralAuthenticate(GeneralAuthenticate), /// Store a data object / container. PutData(PutData), GenerateAsymmetric(GenerateAsymmetric), @@ -55,6 +55,12 @@ pub enum Command<'l> { YkExtension(YubicoPivExtension), } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct GeneralAuthenticate { + algorithm: piv_types::Algorithms, + key_reference: AuthenticateKeyReference, +} + impl<'l> Command<'l> { /// Core method, constructs a PIV command, if the iso7816::Command is valid. /// @@ -345,16 +351,6 @@ pub struct AuthenticateArguments<'l> { pub data: &'l [u8], } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Authenticate {} - -impl TryFrom> for Authenticate { - type Error = Status; - fn try_from(_arguments: AuthenticateArguments<'_>) -> Result { - todo!(); - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct PutData {} @@ -464,13 +460,12 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { } (0x00, Instruction::GeneralAuthenticate, p1, p2) => { - let unparsed_algorithm = p1; + let algorithm = p1.try_into()?; let key_reference = AuthenticateKeyReference::try_from(p2)?; - Self::Authenticate(Authenticate::try_from(AuthenticateArguments { - unparsed_algorithm, + Self::GeneralAuthenticate(GeneralAuthenticate { + algorithm, key_reference, - data, - })?) + }) } (0x00, Instruction::PutData, 0x3F, 0xFF) => { diff --git a/src/lib.rs b/src/lib.rs index 7d7b1ab..05ce02b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ extern crate log; delog::generate_macros!(); pub mod commands; +use commands::GeneralAuthenticate; pub use commands::{Command, YubicoPivExtension}; pub mod constants; pub mod container; @@ -16,6 +17,9 @@ pub mod derp; mod dispatch; pub mod piv_types; pub mod state; +mod tlv; +use tlv::take_do; + pub use piv_types::{Pin, Puk}; #[cfg(feature = "virtual")] @@ -97,6 +101,9 @@ where Command::ChangeReference(change_reference) => self.change_reference(change_reference), Command::GetData(container) => self.get_data(container, reply), Command::Select(_aid) => self.select(reply), + Command::GeneralAuthenticate(authenticate) => { + self.general_authenticate(authenticate, command.data(), reply) + } Command::YkExtension(yk_command) => { self.yubico_piv_extension(command, yk_command, reply) } @@ -230,7 +237,8 @@ where // - 6A80, 6A86 for data, P1/P2 issue pub fn general_authenticate( &mut self, - command: &iso7816::Command, + auth: GeneralAuthenticate, + data: &[u8], reply: &mut Data, ) -> Result { // For "SSH", we need implement A.4.2 in SP-800-73-4 Part 2, ECDSA signatures @@ -250,206 +258,59 @@ where // // expected response: "7C L1 82 L2 SEQ(INT r, INT s)" - let _alg = command.p1; - let _slot = command.p2; - let mut data = command.data().as_slice(); - // refine as we gain more capability if data.len() < 2 { return Err(Status::IncorrectDataParameter); } - let tag = data[0]; - if tag != 0x7c { + let Some((tag,data, [])) = take_do(data) else { return Err(Status::IncorrectDataParameter); - } - - if data[1] > 0x81 { - panic!("unhandled >1B lengths"); - } - if data[1] == 0x81 { - // FIXME: Proper length parsing and avoid panics - // data[2] as usize; - data = &data[3..]; - } else { - // FIXME: Proper length parsing and avoid panics - // data[1] as usize; // ~158 for ssh ed25519 signatures (which have a ~150B commitment) - data = &data[2..]; }; - // step 1 of piv-go/ykAuthenticate - // https://github.com/go-piv/piv-go/blob/d5ec95eb3bec9c20d60611fb77b7caeed7d886b6/piv/piv.go#L359-L384 - if data.starts_with(&[0x80, 0x00]) { - // "request for witness" - // hint that this is an attempt to SetManagementKey - data = &data[2..]; - return self.request_for_witness(command, data, reply); - } - - // step 2 of piv-go/ykAuthenticate - // https://github.com/go-piv/piv-go/blob/d5ec95eb3bec9c20d60611fb77b7caeed7d886b6/piv/piv.go#L415-L420 - if data.starts_with(&[0x80, 0x08]) { - data = &data[2..]; - return self.request_for_challenge(command, data, reply); - } - - // expect '82 00' - if !data.starts_with(&[0x82, 0x00]) { - return Err(Status::IncorrectDataParameter); - } - data = &data[2..]; - - // // expect '81 20' - // if !data.starts_with(&[0x81, 0x20]) { - // return Err(Status::IncorrectDataParameter); - // } - // data = &data[2..]; - - // expect '81 81 96' - // if !data.starts_with(&[0x81, 0x81, 0x96]) { - if !data.starts_with(&[0x81, 0x81]) { - return Err(Status::IncorrectDataParameter); + // part 2 table 7 + match tag { + 0x80 => self.request_for_witness(auth, data, reply), + 0x81 => self.request_for_challenge(auth, data, reply), + 0x82 => self.request_for_response(auth, data, reply), + 0x85 => self.request_for_exponentiation(auth, data, reply), + _ => Err(Status::IncorrectDataParameter), } - let len = data[2] as usize; - data = &data[3..]; - - // if data.len() != 32 { - // return Err(Status::IncorrectDataParameter); - // } - if data.len() != len { - return Err(Status::IncorrectDataParameter); - } - - info!("looking for keyreference"); - let key_handle = match self - .state - .persistent(&mut self.trussed) - .state - .keys - .authentication_key - { - Some(key) => key, - None => return Err(Status::KeyReferenceNotFound), - }; - - let commitment = data; // 32B of data // 150B for ed25519 - let signature = try_syscall!(self.trussed.sign_ed255(key_handle, commitment)) - .map_err(|_error| { - // NoSuchKey - debug!("{:?}", &_error); - Status::UnspecifiedNonpersistentExecutionError - })? - .signature; + } - piv_types::DynamicAuthenticationTemplate::with_response(&signature) - .encode_to_heapless_vec(reply) - // todo: come up with error handling (in this case, shouldn't fail) - .unwrap(); + pub fn request_for_response( + &mut self, + _auth: GeneralAuthenticate, + _data: &[u8], + _reply: &mut Data, + ) -> Result { + todo!() + } - Ok(()) + pub fn request_for_exponentiation( + &mut self, + _auth: GeneralAuthenticate, + _data: &[u8], + _reply: &mut Data, + ) -> Result { + todo!() } pub fn request_for_challenge( &mut self, - command: &iso7816::Command, - remaining_data: &[u8], - reply: &mut Data, + _auth: GeneralAuthenticate, + _data: &[u8], + _reply: &mut Data, ) -> Result { - // - data is of the form - // 00 87 03 9B 16 7C 14 80 08 99 6D 71 40 E7 05 DF 7F 81 08 6E EF 9C 02 00 69 73 E8 - // - remaining data contains 81 08 - // - we must a) verify the decrypted challenge, b) decrypt the counter challenge - - if command.p1 != 0x03 || command.p2 != 0x9b { - return Err(Status::IncorrectP1OrP2Parameter); - } - - if remaining_data.len() != 8 + 2 + 8 { - return Err(Status::IncorrectDataParameter); - } - - // A) verify decrypted challenge - let (response, data) = remaining_data.split_at(8); - - use state::{AuthenticateManagement, CommandCache}; - let our_challenge = match self.state.runtime.command_cache { - Some(CommandCache::AuthenticateManagement(AuthenticateManagement { challenge })) => { - challenge - } - _ => { - return Err(Status::InstructionNotSupportedOrInvalid); - } - }; - // no retries ;) - self.state.runtime.command_cache = None; - - if our_challenge != response { - debug!("{:?}", &our_challenge); - debug!("{:?}", &response); - return Err(Status::IncorrectDataParameter); - } - - self.state.runtime.app_security_status.management_verified = true; - - // B) encrypt their challenge - let (header, challenge) = data.split_at(2); - if header != [0x81, 0x08] { - return Err(Status::IncorrectDataParameter); - } - - let key = self - .state - .persistent(&mut self.trussed) - .state - .keys - .management_key; - - let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, challenge)).ciphertext; - - piv_types::DynamicAuthenticationTemplate::with_response(&encrypted_challenge) - .encode_to_heapless_vec(reply) - .unwrap(); - - Ok(()) + todo!() } pub fn request_for_witness( &mut self, - command: &iso7816::Command, - remaining_data: &[u8], - reply: &mut Data, + _auth: GeneralAuthenticate, + _data: &[u8], + _reply: &mut Data, ) -> Result { - // invariants: parsed data was '7C L1 80 00' + remaining_data - - if command.p1 != 0x03 || command.p2 != 0x9b { - return Err(Status::IncorrectP1OrP2Parameter); - } - - if !remaining_data.is_empty() { - return Err(Status::IncorrectDataParameter); - } - - let key = self - .state - .persistent(&mut self.trussed) - .state - .keys - .management_key; - - let challenge = syscall!(self.trussed.random_bytes(8)).bytes; - let command_cache = state::AuthenticateManagement { - challenge: challenge[..].try_into().unwrap(), - }; - self.state.runtime.command_cache = - Some(state::CommandCache::AuthenticateManagement(command_cache)); - - let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, &challenge)).ciphertext; - - piv_types::DynamicAuthenticationTemplate::with_witness(&encrypted_challenge) - .encode_to_heapless_vec(reply) - .unwrap(); - - Ok(()) + todo!() } pub fn generate_asymmetric_keypair( diff --git a/src/piv_types.rs b/src/piv_types.rs index 0cb7610..f57b90b 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -2,8 +2,39 @@ use core::convert::{TryFrom, TryInto}; use flexiber::Encodable; use hex_literal::hex; +use iso7816::Status; use serde::{Deserialize, Serialize}; +macro_rules! enum_u8 { + ( + $(#[$outer:meta])* + $vis:vis enum $name:ident { + $($var:ident = $num:expr),+ + $(,)* + } + ) => { + $(#[$outer])* + #[repr(u8)] + $vis enum $name { + $( + $var = $num, + )* + } + + impl TryFrom for $name { + type Error = Status; + fn try_from(val: u8) -> Result { + match val { + $( + $num => Ok($name::$var), + )* + _ => Err(Status::KeyReferenceNotFound) + } + } + } + } +} + /// According to spec, a PIN must be 6-8 digits, padded to 8 bytes with 0xFF. /// /// We are more lenient, and allow ASCII 0x20..=0x7E. @@ -51,44 +82,44 @@ impl TryFrom<&[u8]> for Puk { } } -#[repr(u8)] -#[derive(Clone, Copy, Eq, PartialEq, Debug)] -// As additional reference, see: -// https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 -// -// This GP ISO standard contains PIV types as subset (although SM is not quite clear), -// references Opacity ZKM. -pub enum Algorithms { - Tdes = 0x3, - Rsa1024 = 0x6, - Rsa2048 = 0x7, - Aes128 = 0x8, - Aes192 = 0xA, - Aes256 = 0xC, - P256 = 0x11, - P384 = 0x14, - - // // non-standard! in piv-go though! - // Ed255_prev = 0x22, - +enum_u8! { + #[derive(Clone, Copy, Eq, PartialEq, Debug)] + // As additional reference, see: // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 - P521 = 0x15, - // non-standard! - Rsa3072 = 0xE0, - Rsa4096 = 0xE1, - Ed25519 = 0xE2, - X25519 = 0xE3, - Ed448 = 0xE4, - X448 = 0xE5, - - // non-standard! picked by Alex, but maybe due for removal - P256Sha1 = 0xF0, - P256Sha256 = 0xF1, - P384Sha1 = 0xF2, - P384Sha256 = 0xF3, - P384Sha384 = 0xF4, + // + // This GP ISO standard contains PIV types as subset (although SM is not quite clear), + // references Opacity ZKM. + pub enum Algorithms { + Tdes = 0x3, + Rsa1024 = 0x6, + Rsa2048 = 0x7, + Aes128 = 0x8, + Aes192 = 0xA, + Aes256 = 0xC, + P256 = 0x11, + P384 = 0x14, + + // // non-standard! in piv-go though! + // Ed255_prev = 0x22, + + // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 + P521 = 0x15, + // non-standard! + Rsa3072 = 0xE0, + Rsa4096 = 0xE1, + Ed25519 = 0xE2, + X25519 = 0xE3, + Ed448 = 0xE4, + X448 = 0xE5, + + // non-standard! picked by Alex, but maybe due for removal + P256Sha1 = 0xF0, + P256Sha256 = 0xF1, + P384Sha1 = 0xF2, + P384Sha256 = 0xF3, + P384Sha384 = 0xF4, + } } - /// TODO: #[derive(Clone, Copy, Default, Eq, PartialEq)] pub struct CryptographicAlgorithmTemplate<'a> { diff --git a/src/tlv.rs b/src/tlv.rs new file mode 100644 index 0000000..5d3ee33 --- /dev/null +++ b/src/tlv.rs @@ -0,0 +1,96 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +//! Utilities for dealing with TLV (Tag-Length-Value) encoded data + +pub fn get_do<'input>(tag_path: &[u16], data: &'input [u8]) -> Option<&'input [u8]> { + let mut to_ret = data; + let mut remainder = data; + for tag in tag_path { + loop { + let (cur_tag, cur_value, cur_remainder) = take_do(remainder)?; + remainder = cur_remainder; + if *tag == cur_tag { + to_ret = cur_value; + remainder = cur_value; + break; + } + } + } + Some(to_ret) +} + +/// Returns (tag, data, remainder) +pub fn take_do(data: &[u8]) -> Option<(u16, &[u8], &[u8])> { + let (tag, remainder) = take_tag(data)?; + let (len, remainder) = take_len(remainder)?; + if remainder.len() < len { + warn!("Tried to parse TLV with data length shorter that the length data"); + None + } else { + let (value, remainder) = remainder.split_at(len); + Some((tag, value, remainder)) + } +} + +// See +// https://www.emvco.com/wp-content/uploads/2017/05/EMV_v4.3_Book_3_Application_Specification_20120607062110791.pdf +// Annex B1 +fn take_tag(data: &[u8]) -> Option<(u16, &[u8])> { + let b1 = *data.first()?; + if (b1 & 0x1f) == 0x1f { + let b2 = *data.get(1)?; + + if (b2 & 0b10000000) != 0 { + // OpenPGP doesn't have any DO with a tag longer than 2 bytes + warn!("Got a tag larger than 2 bytes: {data:x?}"); + return None; + } + Some((u16::from_be_bytes([b1, b2]), &data[2..])) + } else { + Some((u16::from_be_bytes([0, b1]), &data[1..])) + } +} + +fn take_len(data: &[u8]) -> Option<(usize, &[u8])> { + let l1 = *data.first()?; + if l1 <= 0x7F { + Some((l1 as usize, &data[1..])) + } else if l1 == 0x81 { + Some((*data.get(1)? as usize, &data[2..])) + } else { + if l1 != 0x82 { + warn!("Got an unexpected length tag: {l1:x}"); + return None; + } + let l2 = *data.get(1)?; + let l3 = *data.get(2)?; + let len = u16::from_be_bytes([l2, l3]) as usize; + Some((len as usize, &data[3..])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use hex_literal::hex; + use test_log::test; + + #[test] + fn dos() { + assert_eq!( + get_do(&[0x02], &hex!("02 02 1DB9 02 02 1DB9")), + Some(hex!("1DB9").as_slice()) + ); + assert_eq!( + get_do(&[0xA6, 0x7F49, 0x86], &hex!("A6 26 7F49 23 86 21 04 2525252525252525252525252525252525252525252525252525252525252525")), + Some(hex!("04 2525252525252525252525252525252525252525252525252525252525252525").as_slice()) + ); + + // Multiple nested + assert_eq!( + get_do(&[0xA6, 0x7F49, 0x86], &hex!("A6 2A 02 02 DEAD 7F49 23 86 21 04 2525252525252525252525252525252525252525252525252525252525252525")), + Some(hex!("04 2525252525252525252525252525252525252525252525252525252525252525").as_slice()) + ); + } +} From 3f93ae13ab328dfd962fc2590ebdbec44c36db1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 10:34:48 +0100 Subject: [PATCH 31/59] Remove trussed from the persistent state --- src/lib.rs | 56 ++++++------ src/state.rs | 235 ++++++++++++++++++++++++++------------------------- 2 files changed, 146 insertions(+), 145 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 05ce02b..3985bb6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,18 +115,19 @@ where pub fn login(&mut self, login: commands::VerifyLogin) -> Result { if let commands::VerifyLogin::PivPin(pin) = login { // the actual PIN verification - let mut persistent_state = self.state.persistent(&mut self.trussed); + let persistent_state = self.state.persistent(&mut self.trussed)?; if persistent_state.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } if persistent_state.verify_pin(&pin) { - persistent_state.reset_consecutive_pin_mismatches(); + persistent_state.reset_consecutive_pin_mismatches(&mut self.trussed); self.state.runtime.app_security_status.pin_verified = true; Ok(()) } else { - let remaining = persistent_state.increment_consecutive_pin_mismatches(); + let remaining = + persistent_state.increment_consecutive_pin_mismatches(&mut self.trussed); // should we logout here? self.state.runtime.app_security_status.pin_verified = false; Err(Status::RemainingRetries(remaining)) @@ -155,7 +156,7 @@ where } else { let retries = self .state - .persistent(&mut self.trussed) + .persistent(&mut self.trussed)? .remaining_pin_retries(); Err(Status::RemainingRetries(retries)) } @@ -172,37 +173,39 @@ where } pub fn change_pin(&mut self, old_pin: commands::Pin, new_pin: commands::Pin) -> Result { - let mut persistent_state = self.state.persistent(&mut self.trussed); + let persistent_state = self.state.persistent(&mut self.trussed)?; if persistent_state.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } if !persistent_state.verify_pin(&old_pin) { - let remaining = persistent_state.increment_consecutive_pin_mismatches(); + let remaining = + persistent_state.increment_consecutive_pin_mismatches(&mut self.trussed); self.state.runtime.app_security_status.pin_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_pin_mismatches(); - persistent_state.set_pin(new_pin); + persistent_state.reset_consecutive_pin_mismatches(&mut self.trussed); + persistent_state.set_pin(new_pin, &mut self.trussed); self.state.runtime.app_security_status.pin_verified = true; Ok(()) } pub fn change_puk(&mut self, old_puk: commands::Puk, new_puk: commands::Puk) -> Result { - let mut persistent_state = self.state.persistent(&mut self.trussed); + let persistent_state = self.state.persistent(&mut self.trussed)?; if persistent_state.remaining_puk_retries() == 0 { return Err(Status::OperationBlocked); } if !persistent_state.verify_puk(&old_puk) { - let remaining = persistent_state.increment_consecutive_puk_mismatches(); + let remaining = + persistent_state.increment_consecutive_puk_mismatches(&mut self.trussed); self.state.runtime.app_security_status.puk_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_puk_mismatches(); - persistent_state.set_puk(new_puk); + persistent_state.reset_consecutive_puk_mismatches(&mut self.trussed); + persistent_state.set_puk(new_puk, &mut self.trussed); self.state.runtime.app_security_status.puk_verified = true; Ok(()) } @@ -385,8 +388,7 @@ where if let Some(key) = self .state - .persistent(&mut self.trussed) - .state + .persistent(&mut self.trussed)? .keys .authentication_key { @@ -418,13 +420,9 @@ where // )? // .signature; // blocking::dbg!(&signature); - - self.state - .persistent(&mut self.trussed) - .state - .keys - .authentication_key = Some(key); - self.state.persistent(&mut self.trussed).save(); + let persistent_state = self.state.persistent(&mut self.trussed)?; + persistent_state.keys.authentication_key = Some(key); + persistent_state.save(&mut self.trussed); // let public_key = syscall!(self.trussed.derive_p256_public_key( let public_key = syscall!(self @@ -584,7 +582,7 @@ where // '5FC1 02' (351B) Container::CardHolderUniqueIdentifier => { - let guid = self.state.persistent(&mut self.trussed).guid(); + let guid = self.state.persistent(&mut self.trussed)?.guid(); piv_types::CardHolderUniqueIdentifier::default() .with_guid(guid) .encode_to_heapless_vec(reply) @@ -668,12 +666,12 @@ where return Err(Status::IncorrectP1OrP2Parameter); } + let persistent_state = self.state.persistent(&mut self.trussed)?; + // TODO: find out what all needs resetting :) - self.state.persistent(&mut self.trussed).reset_pin(); - self.state.persistent(&mut self.trussed).reset_puk(); - self.state - .persistent(&mut self.trussed) - .reset_management_key(); + persistent_state.reset_pin(&mut self.trussed); + persistent_state.reset_puk(&mut self.trussed); + persistent_state.reset_management_key(&mut self.trussed); self.state.runtime.app_security_status.pin_verified = false; self.state.runtime.app_security_status.puk_verified = false; self.state.runtime.app_security_status.management_verified = false; @@ -718,8 +716,8 @@ where } let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); self.state - .persistent(&mut self.trussed) - .set_management_key(&new_management_key); + .persistent(&mut self.trussed)? + .set_management_key(&new_management_key, &mut self.trussed); } _ => return Err(Status::FunctionNotSupported), diff --git a/src/state.rs b/src/state.rs index c3f49ef..c22dad7 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,17 +1,15 @@ use core::convert::{TryFrom, TryInto}; +use iso7816::Status; use trussed::{ block, syscall, try_syscall, types::{KeyId, Location, PathBuf}, - Client as TrussedClient, }; use crate::constants::*; use crate::{Pin, Puk}; -pub type Result = core::result::Result; - pub enum Key { Ed25519(KeyId), P256(KeyId), @@ -149,33 +147,48 @@ pub struct Keys { pub retired_keys: [Option; 20], } -#[derive(Clone, Debug, Default, Eq, PartialEq)] +#[derive(Debug, Default, Eq, PartialEq)] pub struct State { pub runtime: Runtime, - // temporary "state", to be removed again - // pub hack: Hack, - // trussed: RefCell>, + pub persistent: Option, } impl State { - pub fn new() -> Self { - Default::default() + pub fn load( + &mut self, + client: &mut impl trussed::Client, + ) -> Result, Status> { + if self.persistent.is_none() { + self.persistent = Some(Persistent::load_or_initialize(client)); + } + Ok(LoadedState { + runtime: &mut self.runtime, + persistent: self.persistent.as_mut().unwrap(), + }) } - // it would be nicer to do this during "board bringup", by using TrussedService as Syscall - // - // TODO: it is really not good to overwrite user data on failure to decode old state. - // To fix this, need a flag to detect if we're "fresh", and/or initialize state in factory. - pub fn persistent<'t, T>(&mut self, trussed: &'t mut T) -> Persistent<'t, T> - where - T: TrussedClient + trussed::client::Tdes, - { - Persistent::load_or_initialize(trussed) + pub fn persistent( + &mut self, + client: &mut impl trussed::Client, + ) -> Result<&mut Persistent, Status> { + Ok(self.load(client)?.persistent) + } +} + +#[derive(Debug, Eq, PartialEq)] +pub struct LoadedState<'t, const C: usize> { + pub runtime: &'t mut Runtime, + pub persistent: &'t mut Persistent, +} + +impl State { + pub fn new() -> Self { + Default::default() } } #[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -pub struct PersistentState { +pub struct Persistent { pub keys: Keys, consecutive_pin_mismatches: u8, consecutive_puk_mismatches: u8, @@ -192,18 +205,6 @@ pub struct PersistentState { guid: [u8; 16], } -#[derive(Debug, Eq, PartialEq)] -pub struct Persistent<'t, Trussed> { - trussed: &'t mut Trussed, - pub(crate) state: PersistentState, -} - -impl AsRef for Persistent<'_, T> { - fn as_ref(&self) -> &PersistentState { - &self.state - } -} - #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Runtime { // aid: Option< @@ -304,10 +305,7 @@ pub struct AuthenticateManagement { pub challenge: [u8; 8], } -impl<'t, T> Persistent<'t, T> -where - T: TrussedClient + trussed::client::Tdes, -{ +impl Persistent { pub const PIN_RETRIES_DEFAULT: u8 = 3; // hmm...! pub const PUK_RETRIES_DEFAULT: u8 = 5; @@ -316,118 +314,130 @@ where const DEFAULT_PUK: &'static [u8] = b"12345678"; pub fn guid(&self) -> [u8; 16] { - self.state.guid + self.guid } pub fn remaining_pin_retries(&self) -> u8 { - if self.state.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { + if self.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { 0 } else { - Self::PIN_RETRIES_DEFAULT - self.state.consecutive_pin_mismatches + Self::PIN_RETRIES_DEFAULT - self.consecutive_pin_mismatches } } pub fn remaining_puk_retries(&self) -> u8 { - if self.state.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { + if self.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { 0 } else { - Self::PUK_RETRIES_DEFAULT - self.state.consecutive_puk_mismatches + Self::PUK_RETRIES_DEFAULT - self.consecutive_puk_mismatches } } + // FIXME: revisit with trussed pin management pub fn verify_pin(&self, other_pin: &Pin) -> bool { // hprintln!("verifying pin {:?} against {:?}", other_pin, &self.pin).ok(); - self.state.pin == *other_pin + self.pin == *other_pin } + // FIXME: revisit with trussed pin management pub fn verify_puk(&self, other_puk: &Puk) -> bool { // hprintln!("verifying puk {:?} against {:?}", other_puk, &self.puk).ok(); - self.state.puk == *other_puk + self.puk == *other_puk } - pub fn set_pin(&mut self, new_pin: Pin) { - self.state.pin = new_pin; - self.save(); + pub fn set_pin(&mut self, new_pin: Pin, client: &mut impl trussed::Client) { + self.pin = new_pin; + self.save(client); } - pub fn set_puk(&mut self, new_puk: Puk) { - self.state.puk = new_puk; - self.save(); + pub fn set_puk(&mut self, new_puk: Puk, client: &mut impl trussed::Client) { + self.puk = new_puk; + self.save(client); } - pub fn reset_pin(&mut self) { - self.set_pin(Pin::try_from(Self::DEFAULT_PIN).unwrap()); - self.reset_consecutive_pin_mismatches(); + pub fn reset_pin(&mut self, client: &mut impl trussed::Client) { + self.set_pin(Pin::try_from(Self::DEFAULT_PIN).unwrap(), client); + self.reset_consecutive_pin_mismatches(client); } - pub fn reset_puk(&mut self) { - self.set_puk(Puk::try_from(Self::DEFAULT_PUK).unwrap()); - self.reset_consecutive_puk_mismatches(); + pub fn reset_puk(&mut self, client: &mut impl trussed::Client) { + self.set_puk(Puk::try_from(Self::DEFAULT_PUK).unwrap(), client); + self.reset_consecutive_puk_mismatches(client); } - pub fn increment_consecutive_pin_mismatches(&mut self) -> u8 { - if self.state.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { + pub fn increment_consecutive_pin_mismatches( + &mut self, + client: &mut impl trussed::Client, + ) -> u8 { + if self.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { return 0; } - self.state.consecutive_pin_mismatches += 1; - self.save(); - Self::PIN_RETRIES_DEFAULT - self.state.consecutive_pin_mismatches + self.consecutive_pin_mismatches += 1; + self.save(client); + Self::PIN_RETRIES_DEFAULT - self.consecutive_pin_mismatches } - pub fn increment_consecutive_puk_mismatches(&mut self) -> u8 { - if self.state.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { + pub fn increment_consecutive_puk_mismatches( + &mut self, + client: &mut impl trussed::Client, + ) -> u8 { + if self.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { return 0; } - self.state.consecutive_puk_mismatches += 1; - self.save(); - Self::PUK_RETRIES_DEFAULT - self.state.consecutive_puk_mismatches + self.consecutive_puk_mismatches += 1; + self.save(client); + Self::PUK_RETRIES_DEFAULT - self.consecutive_puk_mismatches } - pub fn reset_consecutive_pin_mismatches(&mut self) -> u8 { - if self.state.consecutive_pin_mismatches != 0 { - self.state.consecutive_pin_mismatches = 0; - self.save(); + pub fn reset_consecutive_pin_mismatches(&mut self, client: &mut impl trussed::Client) -> u8 { + if self.consecutive_pin_mismatches != 0 { + self.consecutive_pin_mismatches = 0; + self.save(client); } Self::PIN_RETRIES_DEFAULT } - pub fn reset_consecutive_puk_mismatches(&mut self) -> u8 { - if self.state.consecutive_puk_mismatches != 0 { - self.state.consecutive_puk_mismatches = 0; - self.save(); + pub fn reset_consecutive_puk_mismatches(&mut self, client: &mut impl trussed::Client) -> u8 { + if self.consecutive_puk_mismatches != 0 { + self.consecutive_puk_mismatches = 0; + self.save(client); } Self::PUK_RETRIES_DEFAULT } - pub fn reset_management_key(&mut self) { - self.set_management_key(YUBICO_DEFAULT_MANAGEMENT_KEY); + pub fn reset_management_key(&mut self, client: &mut impl trussed::Client) { + self.set_management_key(YUBICO_DEFAULT_MANAGEMENT_KEY, client); } - pub fn set_management_key(&mut self, management_key: &[u8; 24]) { + pub fn set_management_key( + &mut self, + management_key: &[u8; 24], + client: &mut impl trussed::Client, + ) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( - let new_management_key = syscall!(self - .trussed - .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) - .key; - let old_management_key = self.state.keys.management_key; - self.state.keys.management_key = new_management_key; - self.save(); - syscall!(self.trussed.delete(old_management_key)); + let new_management_key = + syscall!(client + .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) + .key; + let old_management_key = self.keys.management_key; + self.keys.management_key = new_management_key; + self.save(client); + syscall!(client.delete(old_management_key)); } - pub fn initialize(trussed: &'t mut T) -> Self { + pub fn initialize(client: &mut impl trussed::Client) -> Self { info!("initializing PIV state"); - let management_key = syscall!(trussed.unsafe_inject_shared_key( + let management_key = syscall!(client.unsafe_inject_shared_key( YUBICO_DEFAULT_MANAGEMENT_KEY, trussed::types::Location::Internal, )) .key; - let mut guid: [u8; 16] = syscall!(trussed.random_bytes(16)) + let mut guid: [u8; 16] = syscall!(client.random_bytes(16)) .bytes .as_ref() .try_into() @@ -446,24 +456,21 @@ where }; let mut state = Self { - trussed, - state: PersistentState { - keys, - consecutive_pin_mismatches: 0, - consecutive_puk_mismatches: 0, - pin: Pin::try_from(Self::DEFAULT_PIN).unwrap(), - puk: Puk::try_from(Self::DEFAULT_PUK).unwrap(), - timestamp: 0, - guid, - }, + keys, + consecutive_pin_mismatches: 0, + consecutive_puk_mismatches: 0, + pin: Pin::try_from(Self::DEFAULT_PIN).unwrap(), + puk: Puk::try_from(Self::DEFAULT_PUK).unwrap(), + timestamp: 0, + guid, }; - state.save(); + state.save(client); state } #[allow(clippy::result_unit_err)] - pub fn load(trussed: &'t mut T) -> Result { - let data = block!(trussed + pub fn load(client: &mut impl trussed::Client) -> Result { + let data = block!(client .read_file(Location::Internal, PathBuf::from(Self::FILENAME),) .unwrap()) .map_err(|_err| { @@ -471,21 +478,17 @@ where })? .data; - let previous_state: PersistentState = trussed::cbor_deserialize(&data).map_err(|_err| { + let previous_state: Self = trussed::cbor_deserialize(&data).map_err(|_err| { info!("cbor deser error: {_err:?}"); info!("data: {:X?}", &data); })?; - // horrible deser bug to forget Ok here :) - Ok(Self { - trussed, - state: previous_state, - }) + Ok(previous_state) } - pub fn load_or_initialize(trussed: &'t mut T) -> Self { + pub fn load_or_initialize(client: &mut impl trussed::Client) -> Self { // todo: can't seem to combine load + initialize without code repetition let data = - try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); + try_syscall!(client.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); if let Ok(data) = data { let previous_state = trussed::cbor_deserialize(&data.data).map_err(|_err| { info!("cbor deser error: {_err:?}"); @@ -493,17 +496,17 @@ where }); if let Ok(state) = previous_state { // horrible deser bug to forget Ok here :) - return Self { trussed, state }; + return state; } } - Self::initialize(trussed) + Self::initialize(client) } - pub fn save(&mut self) { - let data: trussed::types::Message = trussed::cbor_serialize_bytes(self.as_ref()).unwrap(); + pub fn save(&mut self, client: &mut impl trussed::Client) { + let data: trussed::types::Message = trussed::cbor_serialize_bytes(&self).unwrap(); - syscall!(self.trussed.write_file( + syscall!(client.write_file( Location::Internal, PathBuf::from(Self::FILENAME), data, @@ -511,9 +514,9 @@ where )); } - pub fn timestamp(&mut self) -> u32 { - self.state.timestamp += 1; - self.save(); - self.state.timestamp + pub fn timestamp(&mut self, client: &mut impl trussed::Client) -> u32 { + self.timestamp += 1; + self.save(client); + self.timestamp } } From f06a7466b632acd63cb9376484a779c78491276b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 10:39:35 +0100 Subject: [PATCH 32/59] Fix clippy warning --- tests/command_response.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/command_response.rs b/tests/command_response.rs index b5fafd8..868976e 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -241,7 +241,7 @@ impl IoCmd { let mut rep: heapless::Vec = heapless::Vec::new(); let cmd: iso7816::Command<{ setup::COMMAND_SIZE }> = iso7816::Command::try_from(input) .unwrap_or_else(|err| { - panic!("Bad command: {err:?}, for command: {}", hex::encode(&input)) + panic!("Bad command: {err:?}, for command: {}", hex::encode(input)) }); let status: Status = card .respond(&cmd, &mut rep) From 42c1e73a79c786f37734213d7134e0663842c368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 10:50:16 +0100 Subject: [PATCH 33/59] Remove const generic in state --- src/dispatch.rs | 2 +- src/lib.rs | 16 ++++++++-------- src/state.rs | 27 +++++++++++---------------- src/tlv.rs | 1 + src/vpicc.rs | 5 ++--- tests/setup/mod.rs | 3 ++- 6 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/dispatch.rs b/src/dispatch.rs index a6f9cd7..0928899 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -4,7 +4,7 @@ use apdu_dispatch::{app::App, command, response, Command}; use trussed::client; #[cfg(feature = "apdu-dispatch")] -impl App<{ command::SIZE }, { response::SIZE }> for Authenticator +impl App<{ command::SIZE }, { response::SIZE }> for Authenticator where T: client::Client + client::Ed255 + client::Tdes, { diff --git a/src/lib.rs b/src/lib.rs index 3985bb6..fcef2d1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,18 +41,18 @@ pub type Result = iso7816::Result<()>; /// The `C` parameter is necessary, as PIV includes command sequences, /// where we need to store the previous command, so we need to know how /// much space to allocate. -pub struct Authenticator { - state: state::State, +pub struct Authenticator { + state: state::State, trussed: T, } -impl iso7816::App for Authenticator { +impl iso7816::App for Authenticator { fn aid(&self) -> iso7816::Aid { crate::constants::PIV_AID } } -impl Authenticator +impl Authenticator where T: client::Client + client::Ed255 + client::Tdes, { @@ -87,7 +87,7 @@ where Ok(()) } - pub fn respond( + pub fn respond( &mut self, command: &iso7816::Command, reply: &mut Data, @@ -316,7 +316,7 @@ where todo!() } - pub fn generate_asymmetric_keypair( + pub fn generate_asymmetric_keypair( &mut self, command: &iso7816::Command, reply: &mut Data, @@ -453,7 +453,7 @@ where Ok(()) } - pub fn put_data(&mut self, command: &iso7816::Command) -> Result { + pub fn put_data(&mut self, command: &iso7816::Command) -> Result { info!("PutData"); if command.p1 != 0x3f || command.p2 != 0xff { return Err(Status::IncorrectP1OrP2Parameter); @@ -627,7 +627,7 @@ where Ok(()) } - pub fn yubico_piv_extension( + pub fn yubico_piv_extension( &mut self, command: &iso7816::Command, instruction: YubicoPivExtension, diff --git a/src/state.rs b/src/state.rs index c22dad7..0ad84ef 100644 --- a/src/state.rs +++ b/src/state.rs @@ -148,16 +148,13 @@ pub struct Keys { } #[derive(Debug, Default, Eq, PartialEq)] -pub struct State { - pub runtime: Runtime, +pub struct State { + pub runtime: Runtime, pub persistent: Option, } -impl State { - pub fn load( - &mut self, - client: &mut impl trussed::Client, - ) -> Result, Status> { +impl State { + pub fn load(&mut self, client: &mut impl trussed::Client) -> Result, Status> { if self.persistent.is_none() { self.persistent = Some(Persistent::load_or_initialize(client)); } @@ -173,20 +170,18 @@ impl State { ) -> Result<&mut Persistent, Status> { Ok(self.load(client)?.persistent) } -} -#[derive(Debug, Eq, PartialEq)] -pub struct LoadedState<'t, const C: usize> { - pub runtime: &'t mut Runtime, - pub persistent: &'t mut Persistent, -} - -impl State { pub fn new() -> Self { Default::default() } } +#[derive(Debug, Eq, PartialEq)] +pub struct LoadedState<'t> { + pub runtime: &'t mut Runtime, + pub persistent: &'t mut Persistent, +} + #[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct Persistent { pub keys: Keys, @@ -206,7 +201,7 @@ pub struct Persistent { } #[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct Runtime { +pub struct Runtime { // aid: Option< // consecutive_pin_mismatches: u8, pub global_security_status: GlobalSecurityStatus, diff --git a/src/tlv.rs b/src/tlv.rs index 5d3ee33..7996401 100644 --- a/src/tlv.rs +++ b/src/tlv.rs @@ -3,6 +3,7 @@ //! Utilities for dealing with TLV (Tag-Length-Value) encoded data +#[allow(unused)] pub fn get_do<'input>(tag_path: &[u16], data: &'input [u8]) -> Option<&'input [u8]> { let mut to_ret = data; let mut remainder = data; diff --git a/src/vpicc.rs b/src/vpicc.rs index 9464e48..989a18d 100644 --- a/src/vpicc.rs +++ b/src/vpicc.rs @@ -10,7 +10,6 @@ use crate::Authenticator; const REQUEST_LEN: usize = 7609; const RESPONSE_LEN: usize = 7609; -const BUFFER_LEN: usize = 7609; /// Virtual PIV smartcard implementation. /// @@ -19,12 +18,12 @@ const BUFFER_LEN: usize = 7609; pub struct VirtualCard { request_buffer: RequestBuffer, response_buffer: ResponseBuffer, - card: Authenticator, BUFFER_LEN>, + card: Authenticator>, } impl VirtualCard { /// Creates a new virtual smart card from the given card. - pub fn new(card: Authenticator, BUFFER_LEN>) -> Self { + pub fn new(card: Authenticator>) -> Self { Self { request_buffer: Default::default(), response_buffer: Default::default(), diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 45f8149..2a3537d 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,3 +1,4 @@ +#[allow(unused)] pub const COMMAND_SIZE: usize = 3072; #[macro_export] @@ -9,7 +10,7 @@ macro_rules! cmd { use trussed::virt::{Client, Ram}; -pub type Piv = piv_authenticator::Authenticator, COMMAND_SIZE>; +pub type Piv = piv_authenticator::Authenticator>; pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { trussed::virt::with_ram_client("test", |client| { From 0bc75eccb4ce0945b4bee65f5b9a9f216cc726ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 11:49:20 +0100 Subject: [PATCH 34/59] Use macros to have one source of KeyReferences --- src/commands.rs | 167 +++++------------------------------------ src/container.rs | 192 ++++++++++++++++++++++++++++++++++++++--------- src/lib.rs | 2 +- src/piv_types.rs | 6 +- 4 files changed, 176 insertions(+), 191 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 2910ec4..a8a7976 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -9,7 +9,13 @@ use core::convert::{TryFrom, TryInto}; use iso7816::{Instruction, Status}; use crate::state::TouchPolicy; -pub use crate::{container as containers, piv_types, Pin, Puk}; +pub use crate::{ + container::{ + self as containers, AuthenticateKeyReference, ChangeReferenceKeyReference, + GenerateAsymmetricKeyReference, VerifyKeyReference, + }, + piv_types, Pin, Puk, +}; // https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html #[derive(Copy, Clone, Debug, Eq, PartialEq)] @@ -111,32 +117,6 @@ impl TryFrom<&[u8]> for GetData { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum VerifyKeyReference { - GlobalPin = 0x00, - PivPin = 0x80, - PrimaryFingerOcc = 0x96, - SecondaryFingerOcc = 0x97, - PairingCode = 0x98, -} - -impl TryFrom for VerifyKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - // If the PIV Card Application does not contain the Discovery Object as described in Part 1, - // then no other key reference shall be able to be verified by the PIV Card Application VERIFY command. - match p2 { - 0x00 => Ok(Self::GlobalPin), - 0x80 => Ok(Self::PivPin), - 0x96 => Ok(Self::PrimaryFingerOcc), - 0x97 => Ok(Self::SecondaryFingerOcc), - 0x98 => Ok(Self::PairingCode), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct VerifyLogout(bool); @@ -179,7 +159,7 @@ impl TryFrom> for Verify { logout, data, } = arguments; - if key_reference != VerifyKeyReference::PivPin { + if key_reference != VerifyKeyReference::ApplicationPin { return Err(Status::FunctionNotSupported); } Ok(match (logout.0, data.len()) { @@ -195,26 +175,6 @@ impl TryFrom> for Verify { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum ChangeReferenceKeyReference { - GlobalPin = 0x00, - PivPin = 0x80, - Puk = 0x81, -} - -impl TryFrom for ChangeReferenceKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x00 => Ok(Self::GlobalPin), - 0x80 => Ok(Self::PivPin), - 0x81 => Ok(Self::Puk), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ChangeReferenceArguments<'l> { pub key_reference: ChangeReferenceKeyReference, @@ -238,21 +198,18 @@ impl TryFrom> for ChangeReference { use ChangeReferenceKeyReference::*; Ok(match (key_reference, data) { (GlobalPin, _) => return Err(Status::FunctionNotSupported), - (PivPin, data) => ChangeReference::ChangePin { + (ApplicationPin, data) => ChangeReference::ChangePin { old_pin: Pin::try_from(&data[..8]).map_err(|_| Status::IncorrectDataParameter)?, new_pin: Pin::try_from(&data[8..]).map_err(|_| Status::IncorrectDataParameter)?, }, - (Puk, data) => { - use crate::commands::Puk; - ChangeReference::ChangePuk { - old_puk: Puk(data[..8] - .try_into() - .map_err(|_| Status::IncorrectDataParameter)?), - new_puk: Puk(data[8..] - .try_into() - .map_err(|_| Status::IncorrectDataParameter)?), - } - } + (PinUnblockingKey, data) => ChangeReference::ChangePuk { + old_puk: Puk(data[..8] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), + new_puk: Puk(data[8..] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), + }, }) } } @@ -276,72 +233,6 @@ impl TryFrom<&[u8]> for ResetPinRetries { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum AuthenticateKeyReference { - SecureMessaging = 0x04, - Authentication = 0x9a, - Administration = 0x9b, - Signature = 0x9c, - Management = 0x9d, - CardAuthentication = 0x9e, - Retired01 = 0x82, - Retired02 = 0x83, - Retired03 = 0x84, - Retired04 = 0x85, - Retired05 = 0x86, - Retired06 = 0x87, - Retired07 = 0x88, - Retired08 = 0x89, - Retired09 = 0x8A, - Retired10 = 0x8B, - Retired11 = 0x8C, - Retired12 = 0x8D, - Retired13 = 0x8E, - Retired14 = 0x8F, - Retired15 = 0x90, - Retired16 = 0x91, - Retired17 = 0x92, - Retired18 = 0x93, - Retired19 = 0x94, - Retired20 = 0x95, -} - -impl TryFrom for AuthenticateKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x04 => Ok(Self::SecureMessaging), - 0x9a => Ok(Self::Authentication), - 0x9b => Ok(Self::Administration), - 0x9c => Ok(Self::Signature), - 0x9d => Ok(Self::Management), - 0x9e => Ok(Self::CardAuthentication), - 0x82 => Ok(Self::Retired01), - 0x83 => Ok(Self::Retired02), - 0x84 => Ok(Self::Retired03), - 0x85 => Ok(Self::Retired04), - 0x86 => Ok(Self::Retired05), - 0x87 => Ok(Self::Retired06), - 0x88 => Ok(Self::Retired07), - 0x89 => Ok(Self::Retired08), - 0x8A => Ok(Self::Retired09), - 0x8B => Ok(Self::Retired10), - 0x8C => Ok(Self::Retired11), - 0x8D => Ok(Self::Retired12), - 0x8E => Ok(Self::Retired13), - 0x8F => Ok(Self::Retired14), - 0x90 => Ok(Self::Retired15), - 0x91 => Ok(Self::Retired16), - 0x92 => Ok(Self::Retired17), - 0x93 => Ok(Self::Retired18), - 0x94 => Ok(Self::Retired19), - 0x95 => Ok(Self::Retired20), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct AuthenticateArguments<'l> { /// To allow the authenticator to have additional algorithms beyond NIST SP 800-78-4, @@ -361,30 +252,6 @@ impl TryFrom<&[u8]> for PutData { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum GenerateAsymmetricKeyReference { - SecureMessaging = 0x04, - Authentication = 0x9a, - Signature = 0x9c, - Management = 0x9d, - CardAuthentication = 0x9e, -} - -impl TryFrom for GenerateAsymmetricKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x04 => Err(Status::FunctionNotSupported), - 0x9a => Ok(Self::Authentication), - 0x9c => Ok(Self::Signature), - 0x9d => Ok(Self::Management), - 0x9e => Ok(Self::CardAuthentication), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct GenerateAsymmetricArguments<'l> { pub key_reference: GenerateAsymmetricKeyReference, diff --git a/src/container.rs b/src/container.rs index 62359aa..cf98266 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,6 +2,61 @@ use core::convert::TryFrom; use hex_literal::hex; +macro_rules! enum_subset { + ( + $(#[$outer:meta])* + $vis:vis enum $name:ident: $sup:ident { + $($var:ident),+ + $(,)* + } + ) => { + $(#[$outer])* + #[repr(u8)] + $vis enum $name { + $( + $var, + )* + } + + impl TryFrom<$sup> for $name + { + type Error = ::iso7816::Status; + fn try_from(val: $sup) -> ::core::result::Result { + match val { + $( + $sup::$var => Ok($name::$var), + )* + _ => Err(::iso7816::Status::KeyReferenceNotFound) + } + } + } + + impl From<$name> for $sup + { + fn from(v: $name) -> $sup { + match v { + $( + $name::$var => $sup::$var, + )* + } + } + } + + impl TryFrom for $name { + type Error = ::iso7816::Status; + fn try_from(tag: u8) -> ::core::result::Result { + let v: $sup = tag.try_into()?; + match v { + $( + $sup::$var => Ok($name::$var), + )* + _ => Err(::iso7816::Status::KeyReferenceNotFound) + } + } + } + } +} + pub struct Tag<'a>(&'a [u8]); impl<'a> Tag<'a> { pub fn new(slice: &'a [u8]) -> Self { @@ -12,45 +67,108 @@ impl<'a> Tag<'a> { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RetiredIndex(u8); -// #[repr(u8)] -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum KeyReference { - GlobalPin, - ApplicationPin, - PinUnblockingKey, - PrimaryFinger, - SecondaryFinger, - PairingCode, - - PivAuthentication, - PivCardApplicationAdministration, - DigitalSignature, - KeyManagement, - CardAuthentication, - - // 20x - RetiredKeyManagement(RetiredIndex), +crate::enum_u8! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum KeyReference { + GlobalPin = 0x00, + SecureMessaging = 0x04, + ApplicationPin = 0x80, + PinUnblockingKey = 0x81, + PrimaryFinger = 0x96, + SecondaryFinger = 0x97, + PairingCode = 0x98, + + PivAuthentication = 0x9A, + PivCardApplicationAdministration = 0x9B, + DigitalSignature = 0x9C, + KeyManagement = 0x9D, + CardAuthentication = 0x9E, + + Retired01 = 0x82, + Retired02 = 0x83, + Retired03 = 0x84, + Retired04 = 0x85, + Retired05 = 0x86, + Retired06 = 0x87, + Retired07 = 0x88, + Retired08 = 0x89, + Retired09 = 0x8A, + Retired10 = 0x8B, + Retired11 = 0x8C, + Retired12 = 0x8D, + Retired13 = 0x8E, + Retired14 = 0x8F, + Retired15 = 0x90, + Retired16 = 0x91, + Retired17 = 0x92, + Retired18 = 0x93, + Retired19 = 0x94, + Retired20 = 0x95, + } } -impl From for u8 { - fn from(reference: KeyReference) -> Self { - use KeyReference::*; - match reference { - GlobalPin => 0x00, - ApplicationPin => 0x80, - PinUnblockingKey => 0x81, - PrimaryFinger => 0x96, - SecondaryFinger => 0x97, - PairingCode => 0x98, - - PivAuthentication => 0x9A, - PivCardApplicationAdministration => 0x9B, - DigitalSignature => 0x9C, - KeyManagement => 0x9D, - CardAuthentication => 0x9E, - - RetiredKeyManagement(RetiredIndex(i)) => (0x82 - 1) + i, - } +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum GenerateAsymmetricKeyReference: KeyReference { + SecureMessaging, + PivAuthentication, + DigitalSignature, + KeyManagement, + CardAuthentication, + } +} + +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum ChangeReferenceKeyReference: KeyReference { + GlobalPin, + ApplicationPin, + PinUnblockingKey, + } +} + +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum VerifyKeyReference: KeyReference { + GlobalPin, + ApplicationPin, + PrimaryFinger, + SecondaryFinger, + PairingCode, + + } +} + +enum_subset! { + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum AuthenticateKeyReference: KeyReference { + SecureMessaging, + PivAuthentication, + PivCardApplicationAdministration, + DigitalSignature, + KeyManagement, + CardAuthentication, + Retired01, + Retired02, + Retired03, + Retired04, + Retired05, + Retired06, + Retired07, + Retired08, + Retired09, + Retired10, + Retired11, + Retired12, + Retired13, + Retired14, + Retired15, + Retired16, + Retired17, + Retired18, + Retired19, + Retired20, } } diff --git a/src/lib.rs b/src/lib.rs index fcef2d1..0087cb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -148,7 +148,7 @@ where } Verify::Status(key_reference) => { - if key_reference != commands::VerifyKeyReference::PivPin { + if key_reference != commands::VerifyKeyReference::ApplicationPin { return Err(Status::FunctionNotSupported); } if self.state.runtime.app_security_status.pin_verified { diff --git a/src/piv_types.rs b/src/piv_types.rs index f57b90b..47e222a 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -2,9 +2,9 @@ use core::convert::{TryFrom, TryInto}; use flexiber::Encodable; use hex_literal::hex; -use iso7816::Status; use serde::{Deserialize, Serialize}; +#[macro_export] macro_rules! enum_u8 { ( $(#[$outer:meta])* @@ -22,13 +22,13 @@ macro_rules! enum_u8 { } impl TryFrom for $name { - type Error = Status; + type Error = ::iso7816::Status; fn try_from(val: u8) -> Result { match val { $( $num => Ok($name::$var), )* - _ => Err(Status::KeyReferenceNotFound) + _ => Err(::iso7816::Status::KeyReferenceNotFound) } } } From 7818fe6cf83ac49817c19cce51a1c44174574dfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 12:23:05 +0100 Subject: [PATCH 35/59] Remove the iso command from yubico handler --- src/commands.rs | 12 ++++++------ src/container.rs | 7 +++++++ src/lib.rs | 34 +++++++++------------------------- 3 files changed, 22 insertions(+), 31 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index a8a7976..5fbbec6 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -11,8 +11,8 @@ use iso7816::{Instruction, Status}; use crate::state::TouchPolicy; pub use crate::{ container::{ - self as containers, AuthenticateKeyReference, ChangeReferenceKeyReference, - GenerateAsymmetricKeyReference, VerifyKeyReference, + self as containers, AttestKeyReference, AuthenticateKeyReference, + ChangeReferenceKeyReference, GenerateAsymmetricKeyReference, VerifyKeyReference, }, piv_types, Pin, Puk, }; @@ -25,7 +25,7 @@ pub enum YubicoPivExtension { GetVersion, Reset, SetPinRetries, - Attest, + Attest(AttestKeyReference), GetSerial, // also used via 0x01 GetMetadata, } @@ -371,9 +371,9 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { Self::YkExtension(YubicoPivExtension::SetPinRetries) } // (0x00, 0xf9, 0x9a, 0x00) - (0x00, Instruction::Unknown(0xf9), _, _) => { - Self::YkExtension(YubicoPivExtension::Attest) - } + (0x00, Instruction::Unknown(0xf9), _, 0x00) => Self::YkExtension( + YubicoPivExtension::Attest(AttestKeyReference::try_from(p1)?), + ), // (0x00, 0xf8, 0x00, 0x00) (0x00, Instruction::Unknown(0xf8), _, _) => { Self::YkExtension(YubicoPivExtension::GetSerial) diff --git a/src/container.rs b/src/container.rs index cf98266..269f5c4 100644 --- a/src/container.rs +++ b/src/container.rs @@ -107,6 +107,13 @@ crate::enum_u8! { } } +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum AttestKeyReference: KeyReference { + PivAuthentication, + } +} + enum_subset! { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum GenerateAsymmetricKeyReference: KeyReference { diff --git a/src/lib.rs b/src/lib.rs index 0087cb5..7f2ce0c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ use commands::GeneralAuthenticate; pub use commands::{Command, YubicoPivExtension}; pub mod constants; pub mod container; +use container::AttestKeyReference; pub mod derp; #[cfg(feature = "apdu-dispatch")] mod dispatch; @@ -105,7 +106,7 @@ where self.general_authenticate(authenticate, command.data(), reply) } Command::YkExtension(yk_command) => { - self.yubico_piv_extension(command, yk_command, reply) + self.yubico_piv_extension(command.data(), yk_command, reply) } _ => todo!(), } @@ -627,9 +628,9 @@ where Ok(()) } - pub fn yubico_piv_extension( + pub fn yubico_piv_extension( &mut self, - command: &iso7816::Command, + data: &[u8], instruction: YubicoPivExtension, reply: &mut Data, ) -> Result { @@ -645,27 +646,15 @@ where reply.extend_from_slice(&[0x06, 0x06, 0x06]).ok(); } - YubicoPivExtension::Attest => { - if command.p2 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - - let slot = command.p1; - - if slot == 0x9a { - reply + YubicoPivExtension::Attest(slot) => { + match slot { + AttestKeyReference::PivAuthentication => reply .extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A) - .ok(); - } else { - return Err(Status::FunctionNotSupported); - } + .ok(), + }; } YubicoPivExtension::Reset => { - if command.p1 != 0x00 || command.p2 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - let persistent_state = self.state.persistent(&mut self.trussed)?; // TODO: find out what all needs resetting :) @@ -699,11 +688,6 @@ where // }, key[:]...), // } // TODO check we are authenticated with old management key - if command.p1 != 0xff || (command.p2 != 0xff && command.p2 != 0xfe) { - return Err(Status::IncorrectP1OrP2Parameter); - } - - let data = &command.data(); // example: 03 9B 18 // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA From 573808a793446783f91de476cea82ba9343ea5fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 15:12:14 +0100 Subject: [PATCH 36/59] Remove the need for const generics in the respond implementations --- src/commands.rs | 26 ++------------------------ src/lib.rs | 20 ++++---------------- 2 files changed, 6 insertions(+), 40 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 5fbbec6..e3d71ac 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -55,7 +55,7 @@ pub enum Command<'l> { GeneralAuthenticate(GeneralAuthenticate), /// Store a data object / container. PutData(PutData), - GenerateAsymmetric(GenerateAsymmetric), + GenerateAsymmetric(GenerateAsymmetricKeyReference), /* Yubico commands */ YkExtension(YubicoPivExtension), @@ -252,22 +252,6 @@ impl TryFrom<&[u8]> for PutData { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct GenerateAsymmetricArguments<'l> { - pub key_reference: GenerateAsymmetricKeyReference, - pub data: &'l [u8], -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GenerateAsymmetric {} - -impl TryFrom> for GenerateAsymmetric { - type Error = Status; - fn try_from(_arguments: GenerateAsymmetricArguments<'_>) -> Result { - todo!(); - } -} - impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { type Error = Status; /// The first layer of unraveling the iso7816::Command onion. @@ -340,13 +324,7 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { } (0x00, Instruction::GenerateAsymmetricKeyPair, 0x00, p2) => { - let key_reference = GenerateAsymmetricKeyReference::try_from(p2)?; - Self::GenerateAsymmetric(GenerateAsymmetric::try_from( - GenerateAsymmetricArguments { - key_reference, - data, - }, - )?) + Self::GenerateAsymmetric(GenerateAsymmetricKeyReference::try_from(p2)?) } // (0x00, 0x01, 0x10, 0x00) (0x00, Instruction::Unknown(0x01), 0x00, 0x00) => { diff --git a/src/lib.rs b/src/lib.rs index 7f2ce0c..ce506df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -319,22 +319,13 @@ where pub fn generate_asymmetric_keypair( &mut self, - command: &iso7816::Command, + data: &[u8], reply: &mut Data, ) -> Result { if !self.state.runtime.app_security_status.management_verified { return Err(Status::SecurityStatusNotSatisfied); } - if command.p1 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - - if command.p2 != 0x9a { - // TODO: make more general - return Err(Status::FunctionNotSupported); - } - // example: 00 47 00 9A 0B // AC 09 // # P256 @@ -357,7 +348,7 @@ where // } // TODO: iterate on this, don't expect tags.. - let input = derp::Input::from(command.data()); + let input = derp::Input::from(data); // let (mechanism, parameter) = input.read_all(derp::Error::Read, |input| { let (mechanism, _pin_policy, _touch_policy) = input .read_all(derp::Error::Read, |input| { @@ -454,11 +445,8 @@ where Ok(()) } - pub fn put_data(&mut self, command: &iso7816::Command) -> Result { + pub fn put_data(&mut self, data: &[u8]) -> Result { info!("PutData"); - if command.p1 != 0x3f || command.p2 != 0xff { - return Err(Status::IncorrectP1OrP2Parameter); - } // if !self.state.runtime.app_security_status.management_verified { // return Err(Status::SecurityStatusNotSatisfied); @@ -474,7 +462,7 @@ where // 88 1A 89 18 AA 81 D5 48 A5 EC 26 01 60 BA 06 F6 EC 3B B6 05 00 2E B6 3D 4B 28 7F 86 // - let input = derp::Input::from(command.data()); + let input = derp::Input::from(data); let (data_object, data) = input .read_all(derp::Error::Read, |input| { let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; From 5341fc1a41e62b565aed3ec64064a557185659d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 15:24:17 +0100 Subject: [PATCH 37/59] Remove opcard's tlv impl and use the existing derp module --- src/lib.rs | 16 ++++----- src/tlv.rs | 97 ------------------------------------------------------ 2 files changed, 6 insertions(+), 107 deletions(-) delete mode 100644 src/tlv.rs diff --git a/src/lib.rs b/src/lib.rs index ce506df..aaad470 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,8 +18,6 @@ pub mod derp; mod dispatch; pub mod piv_types; pub mod state; -mod tlv; -use tlv::take_do; pub use piv_types::{Pin, Puk}; @@ -263,11 +261,9 @@ where // expected response: "7C L1 82 L2 SEQ(INT r, INT s)" // refine as we gain more capability - if data.len() < 2 { - return Err(Status::IncorrectDataParameter); - } + let mut input = derp::Reader::new(derp::Input::from(data)); - let Some((tag,data, [])) = take_do(data) else { + let Ok((tag,data)) = derp::read_tag_and_get_value(&mut input) else { return Err(Status::IncorrectDataParameter); }; @@ -284,7 +280,7 @@ where pub fn request_for_response( &mut self, _auth: GeneralAuthenticate, - _data: &[u8], + _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { todo!() @@ -293,7 +289,7 @@ where pub fn request_for_exponentiation( &mut self, _auth: GeneralAuthenticate, - _data: &[u8], + _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { todo!() @@ -302,7 +298,7 @@ where pub fn request_for_challenge( &mut self, _auth: GeneralAuthenticate, - _data: &[u8], + _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { todo!() @@ -311,7 +307,7 @@ where pub fn request_for_witness( &mut self, _auth: GeneralAuthenticate, - _data: &[u8], + _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { todo!() diff --git a/src/tlv.rs b/src/tlv.rs deleted file mode 100644 index 7996401..0000000 --- a/src/tlv.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (C) 2022 Nitrokey GmbH -// SPDX-License-Identifier: LGPL-3.0-only - -//! Utilities for dealing with TLV (Tag-Length-Value) encoded data - -#[allow(unused)] -pub fn get_do<'input>(tag_path: &[u16], data: &'input [u8]) -> Option<&'input [u8]> { - let mut to_ret = data; - let mut remainder = data; - for tag in tag_path { - loop { - let (cur_tag, cur_value, cur_remainder) = take_do(remainder)?; - remainder = cur_remainder; - if *tag == cur_tag { - to_ret = cur_value; - remainder = cur_value; - break; - } - } - } - Some(to_ret) -} - -/// Returns (tag, data, remainder) -pub fn take_do(data: &[u8]) -> Option<(u16, &[u8], &[u8])> { - let (tag, remainder) = take_tag(data)?; - let (len, remainder) = take_len(remainder)?; - if remainder.len() < len { - warn!("Tried to parse TLV with data length shorter that the length data"); - None - } else { - let (value, remainder) = remainder.split_at(len); - Some((tag, value, remainder)) - } -} - -// See -// https://www.emvco.com/wp-content/uploads/2017/05/EMV_v4.3_Book_3_Application_Specification_20120607062110791.pdf -// Annex B1 -fn take_tag(data: &[u8]) -> Option<(u16, &[u8])> { - let b1 = *data.first()?; - if (b1 & 0x1f) == 0x1f { - let b2 = *data.get(1)?; - - if (b2 & 0b10000000) != 0 { - // OpenPGP doesn't have any DO with a tag longer than 2 bytes - warn!("Got a tag larger than 2 bytes: {data:x?}"); - return None; - } - Some((u16::from_be_bytes([b1, b2]), &data[2..])) - } else { - Some((u16::from_be_bytes([0, b1]), &data[1..])) - } -} - -fn take_len(data: &[u8]) -> Option<(usize, &[u8])> { - let l1 = *data.first()?; - if l1 <= 0x7F { - Some((l1 as usize, &data[1..])) - } else if l1 == 0x81 { - Some((*data.get(1)? as usize, &data[2..])) - } else { - if l1 != 0x82 { - warn!("Got an unexpected length tag: {l1:x}"); - return None; - } - let l2 = *data.get(1)?; - let l3 = *data.get(2)?; - let len = u16::from_be_bytes([l2, l3]) as usize; - Some((len as usize, &data[3..])) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use hex_literal::hex; - use test_log::test; - - #[test] - fn dos() { - assert_eq!( - get_do(&[0x02], &hex!("02 02 1DB9 02 02 1DB9")), - Some(hex!("1DB9").as_slice()) - ); - assert_eq!( - get_do(&[0xA6, 0x7F49, 0x86], &hex!("A6 26 7F49 23 86 21 04 2525252525252525252525252525252525252525252525252525252525252525")), - Some(hex!("04 2525252525252525252525252525252525252525252525252525252525252525").as_slice()) - ); - - // Multiple nested - assert_eq!( - get_do(&[0xA6, 0x7F49, 0x86], &hex!("A6 2A 02 02 DEAD 7F49 23 86 21 04 2525252525252525252525252525252525252525252525252525252525252525")), - Some(hex!("04 2525252525252525252525252525252525252525252525252525252525252525").as_slice()) - ); - } -} From f6eeff77c9001c87880680f71f041f4ce1b36d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 15:32:21 +0100 Subject: [PATCH 38/59] Add Nitrokey to authors --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 39885b1..c4984d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "piv-authenticator" version = "0.0.0-unreleased" -authors = ["Nicolas Stalder "] +authors = ["Nicolas Stalder ", "Nitrokey GmbH"] edition = "2021" license = "Apache-2.0 OR MIT" repository = "https://github.com/solokeys/piv-authenticator" From 2d2de43bc9a8e632a76ab5f765b5825a65d8f497 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 15:33:10 +0100 Subject: [PATCH 39/59] Fix opcard -> piv-authenticator --- examples/virtual.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/virtual.rs b/examples/virtual.rs index b454c4f..b5cd4f7 100644 --- a/examples/virtual.rs +++ b/examples/virtual.rs @@ -14,7 +14,7 @@ fn main() { env_logger::init(); - trussed::virt::with_ram_client("opcard", |client| { + trussed::virt::with_ram_client("piv-authenticator", |client| { let card = piv_authenticator::Authenticator::new(client); let mut virtual_card = piv_authenticator::vpicc::VirtualCard::new(card); let vpicc = vpicc::connect().expect("failed to connect to vpicc"); From 36b09af3d144d18c79a1f14b2364bf8f5795dc2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 15:48:49 +0100 Subject: [PATCH 40/59] Differenciate loading errors from empty filesystem --- Cargo.toml | 1 + src/state.rs | 71 ++++++++++++++++++++++++++++------------------------ 2 files changed, 39 insertions(+), 33 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c4984d7..ab7a68a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ trussed = "0.1" untrusted = "0.9" vpicc = { version = "0.1.0", optional = true } log = "0.4" +heapless-bytes = "0.3.0" [dev-dependencies] littlefs2 = "0.3.2" diff --git a/src/state.rs b/src/state.rs index 0ad84ef..b755671 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,8 +1,11 @@ use core::convert::{TryFrom, TryInto}; +use heapless_bytes::Bytes; use iso7816::Status; use trussed::{ - block, syscall, try_syscall, + api::reply::Metadata, + config::MAX_MESSAGE_LENGTH, + syscall, try_syscall, types::{KeyId, Location, PathBuf}, }; @@ -156,7 +159,7 @@ pub struct State { impl State { pub fn load(&mut self, client: &mut impl trussed::Client) -> Result, Status> { if self.persistent.is_none() { - self.persistent = Some(Persistent::load_or_initialize(client)); + self.persistent = Some(Persistent::load_or_initialize(client)?); } Ok(LoadedState { runtime: &mut self.runtime, @@ -463,39 +466,18 @@ impl Persistent { state } - #[allow(clippy::result_unit_err)] - pub fn load(client: &mut impl trussed::Client) -> Result { - let data = block!(client - .read_file(Location::Internal, PathBuf::from(Self::FILENAME),) - .unwrap()) - .map_err(|_err| { - info!("loading error: {_err:?}"); - })? - .data; - - let previous_state: Self = trussed::cbor_deserialize(&data).map_err(|_err| { - info!("cbor deser error: {_err:?}"); - info!("data: {:X?}", &data); - })?; - Ok(previous_state) - } - - pub fn load_or_initialize(client: &mut impl trussed::Client) -> Self { + pub fn load_or_initialize(client: &mut impl trussed::Client) -> Result { // todo: can't seem to combine load + initialize without code repetition - let data = - try_syscall!(client.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); - if let Ok(data) = data { - let previous_state = trussed::cbor_deserialize(&data.data).map_err(|_err| { - info!("cbor deser error: {_err:?}"); - info!("data: {:X?}", &data); - }); - if let Ok(state) = previous_state { - // horrible deser bug to forget Ok here :) - return state; - } - } + let data = load_if_exists(client, Location::Internal, &PathBuf::from(Self::FILENAME))?; + let Some(bytes) = data else { + return Ok( Self::initialize(client)); + }; - Self::initialize(client) + let parsed = trussed::cbor_deserialize(&bytes).map_err(|_err| { + error!("{_err:?}"); + Status::UnspecifiedPersistentExecutionError + })?; + Ok(parsed) } pub fn save(&mut self, client: &mut impl trussed::Client) { @@ -515,3 +497,26 @@ impl Persistent { self.timestamp } } + +fn load_if_exists( + client: &mut impl trussed::Client, + location: Location, + path: &PathBuf, +) -> Result>, Status> { + match try_syscall!(client.read_file(location, path.clone())) { + Ok(r) => Ok(Some(r.data)), + Err(_) => match try_syscall!(client.entry_metadata(location, path.clone())) { + Ok(Metadata { metadata: None }) => Ok(None), + Ok(Metadata { + metadata: Some(_metadata), + }) => { + error!("File {path} exists but couldn't be read: {_metadata:?}"); + Err(Status::UnspecifiedPersistentExecutionError) + } + Err(_err) => { + error!("File {path} couldn't be read: {_err:?}"); + Err(Status::UnspecifiedPersistentExecutionError) + } + }, + } +} From 9640780b8f842f8dccf740d38cc92595884e9823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 16:29:44 +0100 Subject: [PATCH 41/59] Make the use of persistent state easier --- src/lib.rs | 409 ++++++++++++++++++++++++++++------------------------- 1 file changed, 213 insertions(+), 196 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index aaad470..bd39013 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,6 +34,7 @@ use trussed::{syscall, try_syscall}; use constants::*; pub type Result = iso7816::Result<()>; +use state::{LoadedState, State}; /// PIV authenticator Trussed app. /// @@ -41,10 +42,15 @@ pub type Result = iso7816::Result<()>; /// where we need to store the previous command, so we need to know how /// much space to allocate. pub struct Authenticator { - state: state::State, + state: State, trussed: T, } +struct LoadedAuthenticator<'a, T> { + state: LoadedState<'a>, + trussed: &'a mut T, +} + impl iso7816::App for Authenticator { fn aid(&self) -> iso7816::Aid { crate::constants::PIV_AID @@ -66,6 +72,13 @@ where } } + fn load(&mut self) -> core::result::Result, Status> { + Ok(LoadedAuthenticator { + state: self.state.load(&mut self.trussed)?, + trussed: &mut self.trussed, + }) + } + // TODO: we'd like to listen on multiple AIDs. // The way apdu-dispatch currently works, this would deselect, resetting security indicators. pub fn deselect(&mut self) {} @@ -96,12 +109,15 @@ where info!("parsed: {:?}", &parsed_command); match parsed_command { - Command::Verify(verify) => self.verify(verify), - Command::ChangeReference(change_reference) => self.change_reference(change_reference), + Command::Verify(verify) => self.load()?.verify(verify), + Command::ChangeReference(change_reference) => { + self.load()?.change_reference(change_reference) + } Command::GetData(container) => self.get_data(container, reply), Command::Select(_aid) => self.select(reply), Command::GeneralAuthenticate(authenticate) => { - self.general_authenticate(authenticate, command.data(), reply) + self.load()? + .general_authenticate(authenticate, command.data(), reply) } Command::YkExtension(yk_command) => { self.yubico_piv_extension(command.data(), yk_command, reply) @@ -110,23 +126,185 @@ where } } + fn get_data( + &mut self, + container: container::Container, + reply: &mut Data, + ) -> Result { + // TODO: check security status, else return Status::SecurityStatusNotSatisfied + + // Table 3, Part 1, SP 800-73-4 + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=30 + use crate::container::Container; + match container { + Container::DiscoveryObject => { + // Err(Status::InstructionNotSupportedOrInvalid) + reply.extend_from_slice(DISCOVERY_OBJECT).ok(); + // todo!("discovery object"), + } + + Container::BiometricInformationTemplatesGroupTemplate => { + return Err(Status::InstructionNotSupportedOrInvalid); + // todo!("biometric information template"), + } + + // '5FC1 07' (351B) + Container::CardCapabilityContainer => { + piv_types::CardCapabilityContainer::default() + .encode_to_heapless_vec(reply) + .unwrap(); + info!("returning CCC {:02X?}", reply); + } + + // '5FC1 02' (351B) + Container::CardHolderUniqueIdentifier => { + let guid = self.state.persistent(&mut self.trussed)?.guid(); + piv_types::CardHolderUniqueIdentifier::default() + .with_guid(guid) + .encode_to_heapless_vec(reply) + .unwrap(); + info!("returning CHUID {:02X?}", reply); + } + + // // '5FC1 05' (351B) + // Container::X509CertificateForPivAuthentication => { + // // return Err(Status::NotFound); + + // // info!("loading 9a cert"); + // // it seems like fetching this certificate is the way Filo's agent decides + // // whether the key is "already setup": + // // https://github.com/FiloSottile/yubikey-agent/blob/8781bc0082db5d35712a2244e3ab3086f415dd59/setup.go#L69-L70 + // let data = try_syscall!(self.trussed.read_file( + // trussed::types::Location::Internal, + // trussed::types::PathBuf::from(b"authentication-key.x5c"), + // )).map_err(|_| { + // // info!("error loading: {:?}", &e); + // Status::NotFound + // } )?.data; + + // // todo: cleanup + // let tag = flexiber::Tag::application(0x13); // 0x53 + // flexiber::TaggedSlice::from(tag, &data) + // .unwrap() + // .encode_to_heapless_vec(reply) + // .unwrap(); + // } + + // // '5F FF01' (754B) + // YubicoObjects::AttestationCertificate => { + // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); + // reply.extend_from_slice(&data).ok(); + // } + _ => { + warn!("Unimplemented GET DATA object: {container:?}"); + return Err(Status::FunctionNotSupported); + } + } + Ok(()) + } + + pub fn yubico_piv_extension( + &mut self, + data: &[u8], + instruction: YubicoPivExtension, + reply: &mut Data, + ) -> Result { + info!("yubico extension: {:?}", &instruction); + match instruction { + YubicoPivExtension::GetSerial => { + // make up a 4-byte serial + reply.extend_from_slice(&[0x00, 0x52, 0xf7, 0x43]).ok(); + } + + YubicoPivExtension::GetVersion => { + // make up a version, be >= 5.0.0 + reply.extend_from_slice(&[0x06, 0x06, 0x06]).ok(); + } + + YubicoPivExtension::Attest(slot) => { + match slot { + AttestKeyReference::PivAuthentication => reply + .extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A) + .ok(), + }; + } + + YubicoPivExtension::Reset => { + let persistent_state = self.state.persistent(&mut self.trussed)?; + + // TODO: find out what all needs resetting :) + persistent_state.reset_pin(&mut self.trussed); + persistent_state.reset_puk(&mut self.trussed); + persistent_state.reset_management_key(&mut self.trussed); + self.state.runtime.app_security_status.pin_verified = false; + self.state.runtime.app_security_status.puk_verified = false; + self.state.runtime.app_security_status.management_verified = false; + + try_syscall!(self.trussed.remove_file( + trussed::types::Location::Internal, + trussed::types::PathBuf::from(b"printed-information"), + )) + .ok(); + + try_syscall!(self.trussed.remove_file( + trussed::types::Location::Internal, + trussed::types::PathBuf::from(b"authentication-key.x5c"), + )) + .ok(); + } + + YubicoPivExtension::SetManagementKey(_touch_policy) => { + // cmd := apdu{ + // instruction: insSetMGMKey, + // param1: 0xff, + // param2: 0xff, + // data: append([]byte{ + // alg3DES, keyCardManagement, 24, + // }, key[:]...), + // } + // TODO check we are authenticated with old management key + + // example: 03 9B 18 + // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA + if data.len() != 3 + 24 { + return Err(Status::IncorrectDataParameter); + } + let (prefix, new_management_key) = data.split_at(3); + if prefix != [0x03, 0x9b, 0x18] { + return Err(Status::IncorrectDataParameter); + } + let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); + self.state + .persistent(&mut self.trussed)? + .set_management_key(&new_management_key, &mut self.trussed); + } + + _ => return Err(Status::FunctionNotSupported), + } + Ok(()) + } +} + +impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> { // maybe reserve this for the case VerifyLogin::PivPin? pub fn login(&mut self, login: commands::VerifyLogin) -> Result { if let commands::VerifyLogin::PivPin(pin) = login { // the actual PIN verification - let persistent_state = self.state.persistent(&mut self.trussed)?; - - if persistent_state.remaining_pin_retries() == 0 { + if self.state.persistent.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } - if persistent_state.verify_pin(&pin) { - persistent_state.reset_consecutive_pin_mismatches(&mut self.trussed); + if self.state.persistent.verify_pin(&pin) { + self.state + .persistent + .reset_consecutive_pin_mismatches(self.trussed); self.state.runtime.app_security_status.pin_verified = true; Ok(()) } else { - let remaining = - persistent_state.increment_consecutive_pin_mismatches(&mut self.trussed); + let remaining = self + .state + .persistent + .increment_consecutive_pin_mismatches(self.trussed); // should we logout here? self.state.runtime.app_security_status.pin_verified = false; Err(Status::RemainingRetries(remaining)) @@ -153,10 +331,7 @@ where if self.state.runtime.app_security_status.pin_verified { Ok(()) } else { - let retries = self - .state - .persistent(&mut self.trussed)? - .remaining_pin_retries(); + let retries = self.state.persistent.remaining_pin_retries(); Err(Status::RemainingRetries(retries)) } } @@ -172,39 +347,45 @@ where } pub fn change_pin(&mut self, old_pin: commands::Pin, new_pin: commands::Pin) -> Result { - let persistent_state = self.state.persistent(&mut self.trussed)?; - if persistent_state.remaining_pin_retries() == 0 { + if self.state.persistent.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } - if !persistent_state.verify_pin(&old_pin) { - let remaining = - persistent_state.increment_consecutive_pin_mismatches(&mut self.trussed); + if !self.state.persistent.verify_pin(&old_pin) { + let remaining = self + .state + .persistent + .increment_consecutive_pin_mismatches(self.trussed); self.state.runtime.app_security_status.pin_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_pin_mismatches(&mut self.trussed); - persistent_state.set_pin(new_pin, &mut self.trussed); + self.state + .persistent + .reset_consecutive_pin_mismatches(self.trussed); + self.state.persistent.set_pin(new_pin, self.trussed); self.state.runtime.app_security_status.pin_verified = true; Ok(()) } pub fn change_puk(&mut self, old_puk: commands::Puk, new_puk: commands::Puk) -> Result { - let persistent_state = self.state.persistent(&mut self.trussed)?; - if persistent_state.remaining_puk_retries() == 0 { + if self.state.persistent.remaining_puk_retries() == 0 { return Err(Status::OperationBlocked); } - if !persistent_state.verify_puk(&old_puk) { - let remaining = - persistent_state.increment_consecutive_puk_mismatches(&mut self.trussed); + if !self.state.persistent.verify_puk(&old_puk) { + let remaining = self + .state + .persistent + .increment_consecutive_puk_mismatches(self.trussed); self.state.runtime.app_security_status.puk_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_puk_mismatches(&mut self.trussed); - persistent_state.set_puk(new_puk, &mut self.trussed); + self.state + .persistent + .reset_consecutive_puk_mismatches(self.trussed); + self.state.persistent.set_puk(new_puk, self.trussed); self.state.runtime.app_security_status.puk_verified = true; Ok(()) } @@ -374,12 +555,7 @@ where // ble policy - if let Some(key) = self - .state - .persistent(&mut self.trussed)? - .keys - .authentication_key - { + if let Some(key) = self.state.persistent.keys.authentication_key { syscall!(self.trussed.delete(key)); } @@ -408,9 +584,8 @@ where // )? // .signature; // blocking::dbg!(&signature); - let persistent_state = self.state.persistent(&mut self.trussed)?; - persistent_state.keys.authentication_key = Some(key); - persistent_state.save(&mut self.trussed); + self.state.persistent.keys.authentication_key = Some(key); + self.state.persistent.save(self.trussed); // let public_key = syscall!(self.trussed.derive_p256_public_key( let public_key = syscall!(self @@ -534,162 +709,4 @@ where // _ => todo!(), // } // todo!(); - - fn get_data( - &mut self, - container: container::Container, - reply: &mut Data, - ) -> Result { - // TODO: check security status, else return Status::SecurityStatusNotSatisfied - - // Table 3, Part 1, SP 800-73-4 - // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=30 - use crate::container::Container; - match container { - Container::DiscoveryObject => { - // Err(Status::InstructionNotSupportedOrInvalid) - reply.extend_from_slice(DISCOVERY_OBJECT).ok(); - // todo!("discovery object"), - } - - Container::BiometricInformationTemplatesGroupTemplate => { - return Err(Status::InstructionNotSupportedOrInvalid); - // todo!("biometric information template"), - } - - // '5FC1 07' (351B) - Container::CardCapabilityContainer => { - piv_types::CardCapabilityContainer::default() - .encode_to_heapless_vec(reply) - .unwrap(); - info!("returning CCC {:02X?}", reply); - } - - // '5FC1 02' (351B) - Container::CardHolderUniqueIdentifier => { - let guid = self.state.persistent(&mut self.trussed)?.guid(); - piv_types::CardHolderUniqueIdentifier::default() - .with_guid(guid) - .encode_to_heapless_vec(reply) - .unwrap(); - info!("returning CHUID {:02X?}", reply); - } - - // // '5FC1 05' (351B) - // Container::X509CertificateForPivAuthentication => { - // // return Err(Status::NotFound); - - // // info!("loading 9a cert"); - // // it seems like fetching this certificate is the way Filo's agent decides - // // whether the key is "already setup": - // // https://github.com/FiloSottile/yubikey-agent/blob/8781bc0082db5d35712a2244e3ab3086f415dd59/setup.go#L69-L70 - // let data = try_syscall!(self.trussed.read_file( - // trussed::types::Location::Internal, - // trussed::types::PathBuf::from(b"authentication-key.x5c"), - // )).map_err(|_| { - // // info!("error loading: {:?}", &e); - // Status::NotFound - // } )?.data; - - // // todo: cleanup - // let tag = flexiber::Tag::application(0x13); // 0x53 - // flexiber::TaggedSlice::from(tag, &data) - // .unwrap() - // .encode_to_heapless_vec(reply) - // .unwrap(); - // } - - // // '5F FF01' (754B) - // YubicoObjects::AttestationCertificate => { - // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); - // reply.extend_from_slice(&data).ok(); - // } - _ => { - warn!("Unimplemented GET DATA object: {container:?}"); - return Err(Status::FunctionNotSupported); - } - } - Ok(()) - } - - pub fn yubico_piv_extension( - &mut self, - data: &[u8], - instruction: YubicoPivExtension, - reply: &mut Data, - ) -> Result { - info!("yubico extension: {:?}", &instruction); - match instruction { - YubicoPivExtension::GetSerial => { - // make up a 4-byte serial - reply.extend_from_slice(&[0x00, 0x52, 0xf7, 0x43]).ok(); - } - - YubicoPivExtension::GetVersion => { - // make up a version, be >= 5.0.0 - reply.extend_from_slice(&[0x06, 0x06, 0x06]).ok(); - } - - YubicoPivExtension::Attest(slot) => { - match slot { - AttestKeyReference::PivAuthentication => reply - .extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A) - .ok(), - }; - } - - YubicoPivExtension::Reset => { - let persistent_state = self.state.persistent(&mut self.trussed)?; - - // TODO: find out what all needs resetting :) - persistent_state.reset_pin(&mut self.trussed); - persistent_state.reset_puk(&mut self.trussed); - persistent_state.reset_management_key(&mut self.trussed); - self.state.runtime.app_security_status.pin_verified = false; - self.state.runtime.app_security_status.puk_verified = false; - self.state.runtime.app_security_status.management_verified = false; - - try_syscall!(self.trussed.remove_file( - trussed::types::Location::Internal, - trussed::types::PathBuf::from(b"printed-information"), - )) - .ok(); - - try_syscall!(self.trussed.remove_file( - trussed::types::Location::Internal, - trussed::types::PathBuf::from(b"authentication-key.x5c"), - )) - .ok(); - } - - YubicoPivExtension::SetManagementKey(_touch_policy) => { - // cmd := apdu{ - // instruction: insSetMGMKey, - // param1: 0xff, - // param2: 0xff, - // data: append([]byte{ - // alg3DES, keyCardManagement, 24, - // }, key[:]...), - // } - // TODO check we are authenticated with old management key - - // example: 03 9B 18 - // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA - if data.len() != 3 + 24 { - return Err(Status::IncorrectDataParameter); - } - let (prefix, new_management_key) = data.split_at(3); - if prefix != [0x03, 0x9b, 0x18] { - return Err(Status::IncorrectDataParameter); - } - let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); - self.state - .persistent(&mut self.trussed)? - .set_management_key(&new_management_key, &mut self.trussed); - } - - _ => return Err(Status::FunctionNotSupported), - } - Ok(()) - } } From c5098fdeda20bb9a481b38c0af4c24d6ee437d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 4 Nov 2022 16:43:08 +0100 Subject: [PATCH 42/59] Fix warnings --- src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index bd39013..4ef47c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -494,6 +494,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> todo!() } + #[allow(unused)] pub fn generate_asymmetric_keypair( &mut self, data: &[u8], @@ -616,6 +617,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> Ok(()) } + #[allow(unused)] pub fn put_data(&mut self, data: &[u8]) -> Result { info!("PutData"); From 622fb5a41d6c1e40c017053eed825d8ac252189a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 8 Nov 2022 10:39:39 +0100 Subject: [PATCH 43/59] Relicense to LGPL and comply with reuse --- .cargo/config | 3 + .gitignore | 3 + Cargo.toml | 5 +- LICENSE-APACHE => LICENSES/Apache-2.0.txt | 0 LICENSES/CC0-1.0.txt | 121 +++++++++ LICENSES/LGPL-3.0-only.txt | 304 ++++++++++++++++++++++ LICENSE-MIT => LICENSES/MIT.txt | 0 Makefile | 4 + bacon.toml | 2 + ci/Dockerfile | 2 + src/commands.rs | 3 + src/constants.rs | 3 + src/container.rs | 3 + src/derp.rs | 3 + src/dispatch.rs | 3 + src/lib.rs | 3 + src/piv_types.rs | 3 + src/state.rs | 3 + tests/generate_asymmetric_keypair.rs | 3 + tests/get_data.rs | 3 + tests/put_data.rs | 3 + tests/setup/mod.rs | 3 + 22 files changed, 479 insertions(+), 1 deletion(-) rename LICENSE-APACHE => LICENSES/Apache-2.0.txt (100%) create mode 100644 LICENSES/CC0-1.0.txt create mode 100644 LICENSES/LGPL-3.0-only.txt rename LICENSE-MIT => LICENSES/MIT.txt (100%) diff --git a/.cargo/config b/.cargo/config index c91c3f3..7ce14af 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,2 +1,5 @@ +# Copyright (C) 2022 Nicolas Stalder +# SPDX-License-Identifier: Apache-2.0 OR MIT + [net] git-fetch-with-cli = true diff --git a/.gitignore b/.gitignore index 71af5be..ecd7ce7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +# SPDX-License-Identifier: Apache-2.0 OR MIT + /target Cargo.lock tarpaulin-report.html diff --git a/Cargo.toml b/Cargo.toml index ab7a68a..9c5d2b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,12 @@ +# Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +# SPDX-License-Identifier: Apache-2.0 OR MIT + [package] name = "piv-authenticator" version = "0.0.0-unreleased" authors = ["Nicolas Stalder ", "Nitrokey GmbH"] edition = "2021" -license = "Apache-2.0 OR MIT" +license = "LGPL-3.0-only" repository = "https://github.com/solokeys/piv-authenticator" documentation = "https://docs.rs/piv-authenticator" diff --git a/LICENSE-APACHE b/LICENSES/Apache-2.0.txt similarity index 100% rename from LICENSE-APACHE rename to LICENSES/Apache-2.0.txt diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt new file mode 100644 index 0000000..513d1c0 --- /dev/null +++ b/LICENSES/LGPL-3.0-only.txt @@ -0,0 +1,304 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/LICENSE-MIT b/LICENSES/MIT.txt similarity index 100% rename from LICENSE-MIT rename to LICENSES/MIT.txt diff --git a/Makefile b/Makefile index 9b86f58..ac78149 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,6 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + .NOTPARALLEL: export RUST_LOG ?= info,cargo_tarpaulin=off @@ -16,6 +19,7 @@ check: cargo check --all-targets --all-features cargo clippy --all-targets --all-features -- -Dwarnings RUSTDOCFLAGS='-Dwarnings' cargo doc --all-features + reuse lint .PHONY: tarpaulin tarpaulin: diff --git a/bacon.toml b/bacon.toml index 346112d..7642144 100644 --- a/bacon.toml +++ b/bacon.toml @@ -1,3 +1,5 @@ +# Copyright (C) 2022 Nicolas Stalder +# SPDX-License-Identifier: Apache-2.0 OR MIT # This is a configuration file for the bacon tool # More info at https://github.com/Canop/bacon diff --git a/ci/Dockerfile b/ci/Dockerfile index 036b5b6..d0b6828 100644 --- a/ci/Dockerfile +++ b/ci/Dockerfile @@ -5,6 +5,8 @@ FROM docker.io/rust:latest RUN apt update && apt install --yes scdaemon libclang-dev llvm python3-pip vsmartcard-vpcd pkg-config nettle-dev libpcsclite-dev +RUN python3 -m pip install reuse + RUN rustup component add clippy rustfmt && rustup target add thumbv7em-none-eabi RUN cargo install cargo-tarpaulin --profile release && rm -rf "$CARGO_HOME"/registry # initialize cargo cache diff --git a/src/commands.rs b/src/commands.rs index e3d71ac..7aa0bdd 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + //! Parsed PIV commands. //! //! The types here should enforce all restrictions in the spec (such as padded_piv_pin.len() == 8), diff --git a/src/constants.rs b/src/constants.rs index 29604a2..5eba22d 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + // https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html use hex_literal::hex; diff --git a/src/container.rs b/src/container.rs index 269f5c4..d727d2b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::TryFrom; use hex_literal::hex; diff --git a/src/derp.rs b/src/derp.rs index 0ece355..daa4cc5 100644 --- a/src/derp.rs +++ b/src/derp.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + pub use untrusted::{Input, Reader}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] diff --git a/src/dispatch.rs b/src/dispatch.rs index 0928899..fe03113 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use crate::{Authenticator, /*constants::PIV_AID,*/ Result}; use apdu_dispatch::{app::App, command, response, Command}; diff --git a/src/lib.rs b/src/lib.rs index 4ef47c2..b4ed68c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + #![cfg_attr(not(any(test, feature = "std")), no_std)] #[cfg(not(feature = "delog"))] diff --git a/src/piv_types.rs b/src/piv_types.rs index 47e222a..be1975c 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::{TryFrom, TryInto}; use flexiber::Encodable; diff --git a/src/state.rs b/src/state.rs index b755671..62d890b 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::{TryFrom, TryInto}; use heapless_bytes::Bytes; diff --git a/tests/generate_asymmetric_keypair.rs b/tests/generate_asymmetric_keypair.rs index f72f50f..8f787f2 100644 --- a/tests/generate_asymmetric_keypair.rs +++ b/tests/generate_asymmetric_keypair.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + mod setup; // example: 00 47 00 9A 0B diff --git a/tests/get_data.rs b/tests/get_data.rs index 7164901..2b94b0a 100644 --- a/tests/get_data.rs +++ b/tests/get_data.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + mod setup; // use delog::hex_str; diff --git a/tests/put_data.rs b/tests/put_data.rs index dcfbaa5..a92e501 100644 --- a/tests/put_data.rs +++ b/tests/put_data.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + mod setup; // use apdu_dispatch::dispatch::Interface::Contact; diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 2a3537d..91b9391 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + #[allow(unused)] pub const COMMAND_SIZE: usize = 3072; From 043094f8be8b2215974acd1efc5b16ba05cfb46b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 8 Nov 2022 15:01:42 +0100 Subject: [PATCH 44/59] Add README --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..c41c050 --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ + + +PIV-Authenticator +================= + +`piv-authenticator` is a Rust implematation of the [Personnal Identity Verification](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf) smartcard. + +Supported features +------------------ + +`piv-authenticator` is still under heavy development and currently doesn't support most of PIV's features. +See the [tracking issue for command support](https://github.com/Nitrokey/piv-authenticator/issues/1) for more information. + +License +------- + +This project is licensed under the [GNU Lesser General Public License (LGPL) +version 3][LGPL-3.0]. Configuration files and examples are licensed under the +[CC0 1.0 license][CC0-1.0]. The [original work][original] by [Solokeys][solokeys] from which this repository is forked from is licensed under [Apache-2.0][Apache-2.0] OR [MIT][MIT] For more information, see the license header in +each file. You can find a copy of the license texts in the +[`LICENSES`](./LICENSES) directory. + +[LGPL-3.0]: https://opensource.org/licenses/LGPL-3.0 +[CC0-1.0]: https://creativecommons.org/publicdomain/zero/1.0/ +[Apache-2.0]: https://www.apache.org/licenses/LICENSE-2.0.html +[MIT]: https://en.wikipedia.org/wiki/MIT_License +[solokeys]: https://solokeys.com/ +[original]: https://github.com/solokeys/piv-authenticator + +This project complies with [version 3.0 of the REUSE specification][reuse]. + +[reuse]: https://reuse.software/practices/3.0/ From 5473cccd241062802e4852ec396ce6392673dc9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Wed, 9 Nov 2022 11:10:45 +0100 Subject: [PATCH 45/59] Fix initial parsing of GENERAL AUTHENTICATE --- src/lib.rs | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b4ed68c..5e6c6b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -445,18 +445,30 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> // expected response: "7C L1 82 L2 SEQ(INT r, INT s)" // refine as we gain more capability - let mut input = derp::Reader::new(derp::Input::from(data)); + let input = derp::Input::from(data); - let Ok((tag,data)) = derp::read_tag_and_get_value(&mut input) else { - return Err(Status::IncorrectDataParameter); - }; + let input = input + .read_all(derp::Error::UnexpectedEnd, |r| { + derp::expect_tag_and_get_value(r, 0x7C) + }) + .map_err(|_err| { + warn!("Bad data: {_err:?}"); + Status::IncorrectDataParameter + })?; + + let (tag, input) = input + .read_all(derp::Error::UnexpectedEnd, derp::read_tag_and_get_value) + .map_err(|_err| { + warn!("Bad data: {_err:?}"); + Status::IncorrectDataParameter + })?; // part 2 table 7 match tag { - 0x80 => self.request_for_witness(auth, data, reply), - 0x81 => self.request_for_challenge(auth, data, reply), - 0x82 => self.request_for_response(auth, data, reply), - 0x85 => self.request_for_exponentiation(auth, data, reply), + 0x80 => self.request_for_witness(auth, input, reply), + 0x81 => self.request_for_challenge(auth, input, reply), + 0x82 => self.request_for_response(auth, input, reply), + 0x85 => self.request_for_exponentiation(auth, input, reply), _ => Err(Status::IncorrectDataParameter), } } @@ -467,6 +479,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { + info!("Request for response"); todo!() } @@ -476,6 +489,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { + info!("Request for exponentiation"); todo!() } @@ -485,6 +499,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { + info!("Request for challenge"); todo!() } @@ -494,6 +509,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> _data: derp::Input<'_>, _reply: &mut Data, ) -> Result { + info!("Request for witness"); todo!() } From 3ab233b8a5cbcc82e18f543c7aeff5036ab69444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 10 Nov 2022 14:13:18 +0100 Subject: [PATCH 46/59] Implement request for challenge --- src/constants.rs | 4 ++++ src/container.rs | 2 ++ src/lib.rs | 35 ++++++++++++++++++++++++++++----- src/state.rs | 50 ++++++++++++++++++++++++++++++++++-------------- 4 files changed, 72 insertions(+), 19 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 5eba22d..264b282 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -5,6 +5,8 @@ use hex_literal::hex; +use crate::state::ManagementAlgorithm; + pub const RID_LENGTH: usize = 5; // top nibble of first byte is "category", here "A" = International @@ -269,6 +271,8 @@ pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &[u8; 24] = &hex!( " ); +pub const YUBICO_DEFAULT_MANAGEMENT_KEY_ALG: ManagementAlgorithm = ManagementAlgorithm::Tdes; + // stolen from le yubico pub const DISCOVERY_OBJECT: &[u8; 20] = b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; diff --git a/src/container.rs b/src/container.rs index d727d2b..8f43553 100644 --- a/src/container.rs +++ b/src/container.rs @@ -60,6 +60,8 @@ macro_rules! enum_subset { } } +pub(crate) use enum_subset; + pub struct Tag<'a>(&'a [u8]); impl<'a> Tag<'a> { pub fn new(slice: &'a [u8]) -> Self { diff --git a/src/lib.rs b/src/lib.rs index 5e6c6b0..9f305d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,7 @@ pub mod vpicc; use core::convert::TryInto; use flexiber::EncodableHeapless; +use heapless_bytes::Bytes; use iso7816::{Data, Status}; use trussed::client; use trussed::{syscall, try_syscall}; @@ -37,7 +38,9 @@ use trussed::{syscall, try_syscall}; use constants::*; pub type Result = iso7816::Result<()>; -use state::{LoadedState, State}; +use state::{CommandCache, LoadedState, State}; + +use crate::piv_types::DynamicAuthenticationTemplate; /// PIV authenticator Trussed app. /// @@ -496,11 +499,33 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> pub fn request_for_challenge( &mut self, _auth: GeneralAuthenticate, - _data: derp::Input<'_>, - _reply: &mut Data, + data: derp::Input<'_>, + reply: &mut Data, ) -> Result { - info!("Request for challenge"); - todo!() + if data.len() != 0 { + warn!("Request for challenge with non empty data"); + return Err(Status::IncorrectDataParameter); + } + info!("Request for challenge "); + let challenge = syscall!(self.trussed.random_bytes( + self.state + .persistent + .keys + .management_key + .alg + .challenge_length() + )) + .bytes; + self.state.runtime.command_cache = Some(CommandCache::AuthenticateChallenge( + Bytes::from_slice(&challenge).unwrap(), + )); + let resp = DynamicAuthenticationTemplate::with_challenge(&challenge); + resp.encode_to_heapless_vec(reply) + .map_err(|_err| { + error!("Failed to encode challenge: {_err:?}"); + Status::UnspecifiedNonpersistentExecutionError + }) + .map(drop) } pub fn request_for_witness( diff --git a/src/state.rs b/src/state.rs index 62d890b..f3a41f3 100644 --- a/src/state.rs +++ b/src/state.rs @@ -13,6 +13,7 @@ use trussed::{ }; use crate::constants::*; +use crate::piv_types::Algorithms; use crate::{Pin, Puk}; @@ -133,13 +134,36 @@ impl SlotName { } } +crate::container::enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] + pub enum ManagementAlgorithm: Algorithms { + Tdes, + Aes256 + } +} + +impl ManagementAlgorithm { + pub fn challenge_length(self) -> usize { + match self { + Self::Tdes => 8, + Self::Aes256 => 16, + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct ManagementKey { + pub id: KeyId, + pub alg: ManagementAlgorithm, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct Keys { // 9a "PIV Authentication Key" (YK: PIV Authentication) #[serde(skip_serializing_if = "Option::is_none")] pub authentication_key: Option, // 9b "PIV Card Application Administration Key" (YK: PIV Management) - pub management_key: KeyId, + pub management_key: ManagementKey, // 9c "Digital Signature Key" (YK: Digital Signature) #[serde(skip_serializing_if = "Option::is_none")] pub signature_key: Option, @@ -295,17 +319,12 @@ pub struct AppSecurityStatus { #[derive(Clone, Debug, Eq, PartialEq)] pub enum CommandCache { GetData(GetData), - AuthenticateManagement(AuthenticateManagement), + AuthenticateChallenge(Bytes<16>), } #[derive(Clone, Debug, Eq, PartialEq)] pub struct GetData {} -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct AuthenticateManagement { - pub challenge: [u8; 8], -} - impl Persistent { pub const PIN_RETRIES_DEFAULT: u8 = 3; // hmm...! @@ -424,19 +443,22 @@ impl Persistent { syscall!(client .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) .key; - let old_management_key = self.keys.management_key; - self.keys.management_key = new_management_key; + let old_management_key = self.keys.management_key.id; + self.keys.management_key.id = new_management_key; self.save(client); syscall!(client.delete(old_management_key)); } pub fn initialize(client: &mut impl trussed::Client) -> Self { info!("initializing PIV state"); - let management_key = syscall!(client.unsafe_inject_shared_key( - YUBICO_DEFAULT_MANAGEMENT_KEY, - trussed::types::Location::Internal, - )) - .key; + let management_key = ManagementKey { + id: syscall!(client.unsafe_inject_shared_key( + YUBICO_DEFAULT_MANAGEMENT_KEY, + trussed::types::Location::Internal, + )) + .key, + alg: YUBICO_DEFAULT_MANAGEMENT_KEY_ALG, + }; let mut guid: [u8; 16] = syscall!(client.random_bytes(16)) .bytes From 2e629827aa268a220f46be7b5c7a31817359b645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 10 Nov 2022 15:09:15 +0100 Subject: [PATCH 47/59] Implemet GENERAL AUTHENTICATE get response support --- Cargo.toml | 1 + src/lib.rs | 40 ++++++++++++++++++++++++++++++---------- src/state.rs | 9 ++++++++- 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9c5d2b8..1c1e194 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ untrusted = "0.9" vpicc = { version = "0.1.0", optional = true } log = "0.4" heapless-bytes = "0.3.0" +subtle = "2" [dev-dependencies] littlefs2 = "0.3.2" diff --git a/src/lib.rs b/src/lib.rs index 9f305d0..88f54ae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -450,17 +450,13 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> // refine as we gain more capability let input = derp::Input::from(data); - let input = input + let (tag, input) = input .read_all(derp::Error::UnexpectedEnd, |r| { derp::expect_tag_and_get_value(r, 0x7C) }) - .map_err(|_err| { - warn!("Bad data: {_err:?}"); - Status::IncorrectDataParameter - })?; - - let (tag, input) = input - .read_all(derp::Error::UnexpectedEnd, derp::read_tag_and_get_value) + .and_then(|input| { + input.read_all(derp::Error::UnexpectedEnd, derp::read_tag_and_get_value) + }) .map_err(|_err| { warn!("Bad data: {_err:?}"); Status::IncorrectDataParameter @@ -479,11 +475,35 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> pub fn request_for_response( &mut self, _auth: GeneralAuthenticate, - _data: derp::Input<'_>, + data: derp::Input<'_>, _reply: &mut Data, ) -> Result { info!("Request for response"); - todo!() + let alg = self.state.persistent.keys.management_key.alg; + if data.len() != alg.challenge_length() { + warn!("Bad response length"); + return Err(Status::IncorrectDataParameter); + } + let Some(CommandCache::AuthenticateChallenge(plaintext)) = self.state.runtime.command_cache.take() else { + warn!("Request for response without cached challenge"); + return Err(Status::ConditionsOfUseNotSatisfied); + }; + let ciphertext = syscall!(self.trussed.encrypt( + alg.mechanism(), + self.state.persistent.keys.management_key.id, + &plaintext, + &[], + None + )) + .ciphertext; + + use subtle::ConstantTimeEq; + if data.as_slice_less_safe().ct_eq(&ciphertext).into() { + self.state.runtime.app_security_status.management_verified = true; + Ok(()) + } else { + Err(Status::SecurityStatusNotSatisfied) + } } pub fn request_for_exponentiation( diff --git a/src/state.rs b/src/state.rs index f3a41f3..0573bed 100644 --- a/src/state.rs +++ b/src/state.rs @@ -9,7 +9,7 @@ use trussed::{ api::reply::Metadata, config::MAX_MESSAGE_LENGTH, syscall, try_syscall, - types::{KeyId, Location, PathBuf}, + types::{KeyId, Location, Mechanism, PathBuf}, }; use crate::constants::*; @@ -149,6 +149,13 @@ impl ManagementAlgorithm { Self::Aes256 => 16, } } + + pub fn mechanism(self) -> Mechanism { + match self { + Self::Tdes => Mechanism::Tdes, + Self::Aes256 => Mechanism::Aes256Cbc, + } + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] From 124d334166848a729229dc1f3bf96ebdcecd4cb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 10 Nov 2022 15:28:57 +0100 Subject: [PATCH 48/59] Check that command algorithm corresponds with state --- src/commands.rs | 2 +- src/container.rs | 11 +++++++++++ src/lib.rs | 26 ++++++++++++++------------ 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 7aa0bdd..0b8cdde 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -66,7 +66,7 @@ pub enum Command<'l> { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct GeneralAuthenticate { - algorithm: piv_types::Algorithms, + pub algorithm: piv_types::Algorithms, key_reference: AuthenticateKeyReference, } diff --git a/src/container.rs b/src/container.rs index 8f43553..7206a96 100644 --- a/src/container.rs +++ b/src/container.rs @@ -45,6 +45,17 @@ macro_rules! enum_subset { } } + impl PartialEq<$sup> for $name { + fn eq(&self, other: &$sup) -> bool { + match (self,other) { + $( + | ($name::$var, $sup::$var) + )* => true, + _ => false + } + } + } + impl TryFrom for $name { type Error = ::iso7816::Status; fn try_from(tag: u8) -> ::core::result::Result { diff --git a/src/lib.rs b/src/lib.rs index 88f54ae..e1a3e88 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -474,7 +474,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> pub fn request_for_response( &mut self, - _auth: GeneralAuthenticate, + auth: GeneralAuthenticate, data: derp::Input<'_>, _reply: &mut Data, ) -> Result { @@ -484,6 +484,11 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> warn!("Bad response length"); return Err(Status::IncorrectDataParameter); } + if alg != auth.algorithm { + warn!("Bad algorithm"); + return Err(Status::IncorrectP1OrP2Parameter); + } + let Some(CommandCache::AuthenticateChallenge(plaintext)) = self.state.runtime.command_cache.take() else { warn!("Request for response without cached challenge"); return Err(Status::ConditionsOfUseNotSatisfied); @@ -518,24 +523,21 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> pub fn request_for_challenge( &mut self, - _auth: GeneralAuthenticate, + auth: GeneralAuthenticate, data: derp::Input<'_>, reply: &mut Data, ) -> Result { - if data.len() != 0 { + let alg = self.state.persistent.keys.management_key.alg; + if !data.is_empty() { warn!("Request for challenge with non empty data"); return Err(Status::IncorrectDataParameter); } + if alg != auth.algorithm { + warn!("Bad algorithm"); + return Err(Status::IncorrectP1OrP2Parameter); + } info!("Request for challenge "); - let challenge = syscall!(self.trussed.random_bytes( - self.state - .persistent - .keys - .management_key - .alg - .challenge_length() - )) - .bytes; + let challenge = syscall!(self.trussed.random_bytes(alg.challenge_length())).bytes; self.state.runtime.command_cache = Some(CommandCache::AuthenticateChallenge( Bytes::from_slice(&challenge).unwrap(), )); From 050da53719228a2c72beb2358729ec1d206fcda3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Thu, 10 Nov 2022 16:47:07 +0100 Subject: [PATCH 49/59] Add test for admin auth --- Cargo.toml | 1 + tests/command_response.ron | 10 ++++ tests/command_response.rs | 105 ++++++++++++++++++++++++++++++++++--- 3 files changed, 108 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1c1e194..b939b9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ serde_cbor = { version = "0.11", features = ["std"] } hex = "0.4" test-log = "0.2" ron = "0.8" +des = "0.8" [features] diff --git a/tests/command_response.ron b/tests/command_response.ron index bcee492..8cd1856 100644 --- a/tests/command_response.ron +++ b/tests/command_response.ron @@ -15,4 +15,14 @@ Select ] ), + // TODO: test with AES + IoTest( + name: "Default management key", + cmd_resp: [ + AuthenticateManagement( + algorithm: Tdes, + key: "0102030405060708 0102030405060708 0102030405060708" + ) + ] + ), ] diff --git a/tests/command_response.rs b/tests/command_response.rs index 868976e..4a0ed79 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -1,4 +1,4 @@ -// Copyright (C) 2022 Nitrokey GmbH +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH // SPDX-License-Identifier: LGPL-3.0-only #![cfg(feature = "virtual")] @@ -8,6 +8,7 @@ use std::borrow::Cow; use hex_literal::hex; use serde::Deserialize; +use trussed::types::GenericArray; // iso7816::Status doesn't support serde #[derive(Deserialize, Debug, PartialEq, Clone, Copy)] @@ -36,6 +37,43 @@ enum Status { UnspecifiedCheckingError, } +#[derive(Clone, Copy, Eq, PartialEq, Debug, Deserialize)] +pub enum Algorithm { + Tdes = 0x3, + Rsa1024 = 0x6, + Rsa2048 = 0x7, + Aes128 = 0x8, + Aes192 = 0xA, + Aes256 = 0xC, + P256 = 0x11, + P384 = 0x14, + + P521 = 0x15, + // non-standard! + Rsa3072 = 0xE0, + Rsa4096 = 0xE1, + Ed25519 = 0xE2, + X25519 = 0xE3, + Ed448 = 0xE4, + X448 = 0xE5, + + // non-standard! picked by Alex, but maybe due for removal + P256Sha1 = 0xF0, + P256Sha256 = 0xF1, + P384Sha1 = 0xF2, + P384Sha256 = 0xF3, + P384Sha384 = 0xF4, +} +impl Algorithm { + pub fn challenge_len(self) -> usize { + match self { + Self::Tdes => 8, + Self::Aes256 => 16, + _ => panic!(), + } + } +} + fn serialize_len(len: usize) -> heapless::Vec { let mut buf = heapless::Vec::new(); if let Ok(len) = u8::try_from(len) { @@ -52,7 +90,6 @@ fn serialize_len(len: usize) -> heapless::Vec { buf } -#[allow(unused)] fn tlv(tag: &[u8], data: &[u8]) -> Vec { let mut buf = Vec::from(tag); buf.extend_from_slice(&serialize_len(data.len())); @@ -60,7 +97,6 @@ fn tlv(tag: &[u8], data: &[u8]) -> Vec { buf } -#[allow(unused)] fn build_command(cla: u8, ins: u8, p1: u8, p2: u8, data: &[u8], le: u16) -> Vec { let mut res = vec![cla, ins, p1, p2]; let lc = data.len(); @@ -208,10 +244,19 @@ enum IoCmd { #[serde(default)] expected_status: Status, }, + AuthenticateManagement { + algorithm: Algorithm, + key: String, + #[serde(default)] + expected_status_challenge: Status, + #[serde(default)] + expected_status_response: Status, + }, Select, } const MATCH_EMPTY: OutputMatcher = OutputMatcher::Len(0); +const MATCH_ANY: OutputMatcher = OutputMatcher::And(Cow::Borrowed(&[]), ()); impl IoCmd { fn run(&self, card: &mut setup::Piv) { @@ -227,6 +272,18 @@ impl IoCmd { Self::VerifyDefaultGlobalPin { expected_status } => { Self::run_verify_default_global_pin(*expected_status, card) } + Self::AuthenticateManagement { + algorithm, + key, + expected_status_challenge, + expected_status_response, + } => Self::run_authenticate_management( + algorithm, + key, + *expected_status_challenge, + *expected_status_response, + card, + ), Self::Select => Self::run_select(card), } } @@ -236,7 +293,7 @@ impl IoCmd { output: &OutputMatcher, expected_status: Status, card: &mut setup::Piv, - ) { + ) -> heapless::Vec { println!("Command: {:x?}", input); let mut rep: heapless::Vec = heapless::Vec::new(); let cmd: iso7816::Command<{ setup::COMMAND_SIZE }> = iso7816::Command::try_from(input) @@ -257,6 +314,7 @@ impl IoCmd { if status != expected_status { panic!("Bad status. Expected {:?}", expected_status); } + rep } fn run_iodata( @@ -265,7 +323,37 @@ impl IoCmd { expected_status: Status, card: &mut setup::Piv, ) { - Self::run_bytes(&parse_hex(input), output, expected_status, card) + Self::run_bytes(&parse_hex(input), output, expected_status, card); + } + + fn run_authenticate_management( + alg: &Algorithm, + key: &str, + expected_status_challenge: Status, + expected_status_response: Status, + card: &mut setup::Piv, + ) { + use des::{ + cipher::{BlockEncrypt, KeyInit}, + TdesEde3, + }; + let command = build_command(0x00, 0x87, *alg as u8, 0x9B, &hex!("7C 02 81 00"), 0); + let mut res = Self::run_bytes(&command, &MATCH_ANY, expected_status_challenge, card); + let key = parse_hex(key); + + // Remove header + let challenge = &mut res[6..][..alg.challenge_len()]; + match alg { + Algorithm::Tdes => { + let cipher = TdesEde3::new(GenericArray::from_slice(&key)); + cipher.encrypt_block(GenericArray::from_mut_slice(challenge)); + } + Algorithm::Aes256 => todo!(), + _ => panic!(), + } + let second_data = tlv(&[0x7C], &tlv(&[0x82], challenge)); + let command = build_command(0x00, 0x87, *alg as u8, 0x9B, &second_data, 0); + Self::run_bytes(&command, &MATCH_ANY, expected_status_response, card); } fn run_verify_default_global_pin(expected_status: Status, card: &mut setup::Piv) { @@ -274,15 +362,16 @@ impl IoCmd { &MATCH_EMPTY, expected_status, card, - ) + ); } + fn run_verify_default_application_pin(expected_status: Status, card: &mut setup::Piv) { Self::run_bytes( &hex!("00 20 00 80 08 313233343536FFFF"), &MATCH_EMPTY, expected_status, card, - ) + ); } fn run_select(card: &mut setup::Piv) { @@ -313,7 +402,7 @@ impl IoCmd { &matcher, Status::Success, card, - ) + ); } } From d21a04dcec85d32faa66205d1ba0b6fe6aa4e3ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 15 Nov 2022 11:05:29 +0100 Subject: [PATCH 50/59] Fix set management key to accept any length --- src/state.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/state.rs b/src/state.rs index 0573bed..c4fccb4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -440,11 +440,7 @@ impl Persistent { self.set_management_key(YUBICO_DEFAULT_MANAGEMENT_KEY, client); } - pub fn set_management_key( - &mut self, - management_key: &[u8; 24], - client: &mut impl trussed::Client, - ) { + pub fn set_management_key(&mut self, management_key: &[u8], client: &mut impl trussed::Client) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( let new_management_key = syscall!(client From 38b7a5a146bf5d1bd2b04605a9516b70c3270821 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 15 Nov 2022 11:20:37 +0100 Subject: [PATCH 51/59] Add support for Aes key management in tests --- Cargo.toml | 1 + src/state.rs | 6 ++++-- tests/command_response.rs | 6 +++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b939b9d..2711082 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ hex = "0.4" test-log = "0.2" ron = "0.8" des = "0.8" +aes = "0.8.2" [features] diff --git a/src/state.rs b/src/state.rs index c4fccb4..07ae7c4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -9,7 +9,7 @@ use trussed::{ api::reply::Metadata, config::MAX_MESSAGE_LENGTH, syscall, try_syscall, - types::{KeyId, Location, Mechanism, PathBuf}, + types::{KeyId, KeySerialization, Location, Mechanism, PathBuf}, }; use crate::constants::*; @@ -455,9 +455,11 @@ impl Persistent { pub fn initialize(client: &mut impl trussed::Client) -> Self { info!("initializing PIV state"); let management_key = ManagementKey { - id: syscall!(client.unsafe_inject_shared_key( + id: syscall!(client.unsafe_inject_key( + YUBICO_DEFAULT_MANAGEMENT_KEY_ALG.mechanism(), YUBICO_DEFAULT_MANAGEMENT_KEY, trussed::types::Location::Internal, + KeySerialization::Raw )) .key, alg: YUBICO_DEFAULT_MANAGEMENT_KEY_ALG, diff --git a/tests/command_response.rs b/tests/command_response.rs index 4a0ed79..340ae1c 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -6,6 +6,7 @@ mod setup; use std::borrow::Cow; +use aes::Aes256Enc; use hex_literal::hex; use serde::Deserialize; use trussed::types::GenericArray; @@ -348,7 +349,10 @@ impl IoCmd { let cipher = TdesEde3::new(GenericArray::from_slice(&key)); cipher.encrypt_block(GenericArray::from_mut_slice(challenge)); } - Algorithm::Aes256 => todo!(), + Algorithm::Aes256 => { + let cipher = Aes256Enc::new(GenericArray::from_slice(&key)); + cipher.encrypt_block(GenericArray::from_mut_slice(challenge)); + } _ => panic!(), } let second_data = tlv(&[0x7C], &tlv(&[0x82], challenge)); From af7340b6abc2cc4e8d051522a160cc7f18503476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Wed, 16 Nov 2022 16:19:03 +0100 Subject: [PATCH 52/59] Set the management algorithm with the key --- src/lib.rs | 66 ++++++++++++++++++++++++++++++++-------------------- src/state.rs | 17 ++++++++++---- 2 files changed, 54 insertions(+), 29 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e1a3e88..1e122ee 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ use trussed::{syscall, try_syscall}; use constants::*; pub type Result = iso7816::Result<()>; -use state::{CommandCache, LoadedState, State}; +use state::{CommandCache, LoadedState, ManagementAlgorithm, State, TouchPolicy}; use crate::piv_types::DynamicAuthenticationTemplate; @@ -259,30 +259,9 @@ where .ok(); } - YubicoPivExtension::SetManagementKey(_touch_policy) => { - // cmd := apdu{ - // instruction: insSetMGMKey, - // param1: 0xff, - // param2: 0xff, - // data: append([]byte{ - // alg3DES, keyCardManagement, 24, - // }, key[:]...), - // } - // TODO check we are authenticated with old management key - - // example: 03 9B 18 - // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA - if data.len() != 3 + 24 { - return Err(Status::IncorrectDataParameter); - } - let (prefix, new_management_key) = data.split_at(3); - if prefix != [0x03, 0x9b, 0x18] { - return Err(Status::IncorrectDataParameter); - } - let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); - self.state - .persistent(&mut self.trussed)? - .set_management_key(&new_management_key, &mut self.trussed); + YubicoPivExtension::SetManagementKey(touch_policy) => { + self.load()? + .yubico_set_management_key(data, touch_policy, reply)?; } _ => return Err(Status::FunctionNotSupported), @@ -292,6 +271,43 @@ where } impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> { + pub fn yubico_set_management_key( + &mut self, + data: &[u8], + _touch_policy: TouchPolicy, + reply: &mut Data, + ) -> Result { + // cmd := apdu{ + // instruction: insSetMGMKey, + // param1: 0xff, + // param2: 0xff, + // data: append([]byte{ + // alg3DES, keyCardManagement, 24, + // }, key[:]...), + // } + + if !self.state.runtime.app_security_status.management_verified { + return Err(Status::SecurityStatusNotSatisfied); + } + + // example: 03 9B 18 + // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA + if data.len() != 3 + 24 { + return Err(Status::IncorrectDataParameter); + } + let (prefix, new_management_key) = data.split_at(3); + if prefix != [0x03, 0x9b, 0x18] { + return Err(Status::IncorrectDataParameter); + } + let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); + self.state.persistent.set_management_key( + &new_management_key, + ManagementAlgorithm::Tdes, + self.trussed, + ); + Ok(()) + } + // maybe reserve this for the case VerifyLogin::PivPin? pub fn login(&mut self, login: commands::VerifyLogin) -> Result { if let commands::VerifyLogin::PivPin(pin) = login { diff --git a/src/state.rs b/src/state.rs index 07ae7c4..b7bfbd4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -437,17 +437,26 @@ impl Persistent { } pub fn reset_management_key(&mut self, client: &mut impl trussed::Client) { - self.set_management_key(YUBICO_DEFAULT_MANAGEMENT_KEY, client); + self.set_management_key( + YUBICO_DEFAULT_MANAGEMENT_KEY, + YUBICO_DEFAULT_MANAGEMENT_KEY_ALG, + client, + ); } - pub fn set_management_key(&mut self, management_key: &[u8], client: &mut impl trussed::Client) { + pub fn set_management_key( + &mut self, + management_key: &[u8], + alg: ManagementAlgorithm, + client: &mut impl trussed::Client, + ) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( - let new_management_key = + let id = syscall!(client .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) .key; let old_management_key = self.keys.management_key.id; - self.keys.management_key.id = new_management_key; + self.keys.management_key = ManagementKey { id, alg }; self.save(client); syscall!(client.delete(old_management_key)); } From 0e6dbe57f1c9a4e7aedcafedeb243c53526631c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 21 Nov 2022 16:02:32 +0100 Subject: [PATCH 53/59] Add support for AES keys in SET MANAGEMENT KEY and test AES keys for GENERAL AUTHENTICATE --- Cargo.toml | 2 +- src/lib.rs | 39 ++++++++++++++++++------- src/piv_types.rs | 6 ++++ src/state.rs | 18 +++++++++--- tests/command_response.ron | 50 ++++++++++++++++++++++++++++++-- tests/command_response.rs | 59 ++++++++++++++++++++++++++++++++------ 6 files changed, 148 insertions(+), 26 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2711082..9d0eab3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,4 +58,4 @@ log-warn = [] log-error = [] [patch.crates-io] -trussed = { git = "https://github.com/trussed-dev/trussed", rev = "28478f8abed11d78c51e6a6a32326821ed61957a"} +trussed = { git = "https://github.com/sosthene-nitrokey/trussed", rev = "cbf8f3cc759fa79275fe06d3ce4661d6a4f306aa"} diff --git a/src/lib.rs b/src/lib.rs index 1e122ee..be0e796 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ extern crate log; delog::generate_macros!(); pub mod commands; +use commands::containers::KeyReference; use commands::GeneralAuthenticate; pub use commands::{Command, YubicoPivExtension}; pub mod constants; @@ -275,7 +276,7 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> &mut self, data: &[u8], _touch_policy: TouchPolicy, - reply: &mut Data, + _reply: &mut Data, ) -> Result { // cmd := apdu{ // instruction: insSetMGMKey, @@ -286,25 +287,43 @@ impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> // }, key[:]...), // } + // TODO _touch_policy + if !self.state.runtime.app_security_status.management_verified { return Err(Status::SecurityStatusNotSatisfied); } // example: 03 9B 18 // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA - if data.len() != 3 + 24 { + if data.len() < 4 { + warn!("Set management key with incorrect data"); + return Err(Status::IncorrectDataParameter); + } + + let key_data = &data[3..]; + + let Ok(alg) = ManagementAlgorithm::try_from(data[0]) else { + warn!("Set management key with incorrect alg: {:x}", data[0]); + return Err(Status::IncorrectDataParameter); + }; + + if KeyReference::PivCardApplicationAdministration != data[1] { + warn!( + "Set management key with incorrect reference: {:x}, expected: {:x}", + data[1], + KeyReference::PivCardApplicationAdministration as u8 + ); return Err(Status::IncorrectDataParameter); } - let (prefix, new_management_key) = data.split_at(3); - if prefix != [0x03, 0x9b, 0x18] { + + if data[2] as usize != key_data.len() || alg.key_len() != key_data.len() { + warn!("Set management key with incorrect data length: claimed: {}, required by algorithm: {}, real: {}", data[2], alg.key_len(), key_data.len()); return Err(Status::IncorrectDataParameter); } - let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); - self.state.persistent.set_management_key( - &new_management_key, - ManagementAlgorithm::Tdes, - self.trussed, - ); + + self.state + .persistent + .set_management_key(key_data, alg, self.trussed); Ok(()) } diff --git a/src/piv_types.rs b/src/piv_types.rs index be1975c..7f27da9 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -35,6 +35,12 @@ macro_rules! enum_u8 { } } } + + impl PartialEq for $name { + fn eq(&self, other: &u8) -> bool { + *self as u8 == *other + } + } } } diff --git a/src/state.rs b/src/state.rs index b7bfbd4..e6de4d7 100644 --- a/src/state.rs +++ b/src/state.rs @@ -156,6 +156,13 @@ impl ManagementAlgorithm { Self::Aes256 => Mechanism::Aes256Cbc, } } + + pub fn key_len(self) -> usize { + match self { + Self::Tdes => 24, + Self::Aes256 => 32, + } + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -451,10 +458,13 @@ impl Persistent { client: &mut impl trussed::Client, ) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( - let id = - syscall!(client - .unsafe_inject_shared_key(management_key, trussed::types::Location::Internal,)) - .key; + let id = syscall!(client.unsafe_inject_key( + alg.mechanism(), + management_key, + trussed::types::Location::Internal, + KeySerialization::Raw + )) + .key; let old_management_key = self.keys.management_key.id; self.keys.management_key = ManagementKey { id, alg }; self.save(client); diff --git a/tests/command_response.ron b/tests/command_response.ron index 8cd1856..2b74bad 100644 --- a/tests/command_response.ron +++ b/tests/command_response.ron @@ -15,13 +15,57 @@ Select ] ), - // TODO: test with AES IoTest( name: "Default management key", cmd_resp: [ AuthenticateManagement( - algorithm: Tdes, - key: "0102030405060708 0102030405060708 0102030405060708" + key: ( + algorithm: Tdes, + key: "0102030405060708 0102030405060708 0102030405060708" + ) + ) + ] + ), + IoTest( + name: "Aes management key", + cmd_resp: [ + AuthenticateManagement( + key: ( + algorithm: Tdes, + key: "0102030405060708 0102030405060708 0102030405060708" + ) + ), + SetManagementKey( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ) + ), + AuthenticateManagement( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ) + ) + ] + ), + IoTest( + name: "unauthenticated set management key", + cmd_resp: [ + SetManagementKey( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ), + expected_status: SecurityStatusNotSatisfied, + ), + AuthenticateManagement( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ), + expected_status_challenge: IncorrectP1OrP2Parameter, + expected_status_response: IncorrectDataParameter, ) ] ), diff --git a/tests/command_response.rs b/tests/command_response.rs index 340ae1c..5cf95a8 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -73,6 +73,14 @@ impl Algorithm { _ => panic!(), } } + + pub fn key_len(self) -> usize { + match self { + Self::Tdes => 24, + Self::Aes256 => 32, + _ => panic!(), + } + } } fn serialize_len(len: usize) -> heapless::Vec { @@ -227,6 +235,13 @@ impl OutputMatcher { } } +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct ManagementKey { + algorithm: Algorithm, + key: String, +} + #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] enum IoCmd { @@ -245,9 +260,13 @@ enum IoCmd { #[serde(default)] expected_status: Status, }, + SetManagementKey { + key: ManagementKey, + #[serde(default)] + expected_status: Status, + }, AuthenticateManagement { - algorithm: Algorithm, - key: String, + key: ManagementKey, #[serde(default)] expected_status_challenge: Status, #[serde(default)] @@ -274,21 +293,42 @@ impl IoCmd { Self::run_verify_default_global_pin(*expected_status, card) } Self::AuthenticateManagement { - algorithm, key, expected_status_challenge, expected_status_response, } => Self::run_authenticate_management( - algorithm, - key, + key.algorithm, + &key.key, *expected_status_challenge, *expected_status_response, card, ), + Self::SetManagementKey { + key, + expected_status, + } => Self::run_set_management_key(key.algorithm, &key.key, *expected_status, card), Self::Select => Self::run_select(card), } } + fn run_set_management_key( + alg: Algorithm, + key: &str, + expected_status: Status, + card: &mut setup::Piv, + ) { + let mut key_data = parse_hex(key); + let mut data = vec![alg as u8, 0x9b, key_data.len() as u8]; + data.append(&mut key_data); + + Self::run_bytes( + &build_command(0x00, 0xff, 0xff, 0xff, &data, 0), + &MATCH_ANY, + expected_status, + card, + ); + } + fn run_bytes( input: &[u8], output: &OutputMatcher, @@ -328,7 +368,7 @@ impl IoCmd { } fn run_authenticate_management( - alg: &Algorithm, + alg: Algorithm, key: &str, expected_status_challenge: Status, expected_status_response: Status, @@ -338,9 +378,12 @@ impl IoCmd { cipher::{BlockEncrypt, KeyInit}, TdesEde3, }; - let command = build_command(0x00, 0x87, *alg as u8, 0x9B, &hex!("7C 02 81 00"), 0); + let command = build_command(0x00, 0x87, alg as u8, 0x9B, &hex!("7C 02 81 00"), 0); let mut res = Self::run_bytes(&command, &MATCH_ANY, expected_status_challenge, card); let key = parse_hex(key); + if expected_status_challenge != Status::Success && res.is_empty() { + res = heapless::Vec::from_slice(&vec![0; alg.challenge_len() + 6]).unwrap(); + } // Remove header let challenge = &mut res[6..][..alg.challenge_len()]; @@ -356,7 +399,7 @@ impl IoCmd { _ => panic!(), } let second_data = tlv(&[0x7C], &tlv(&[0x82], challenge)); - let command = build_command(0x00, 0x87, *alg as u8, 0x9B, &second_data, 0); + let command = build_command(0x00, 0x87, alg as u8, 0x9B, &second_data, 0); Self::run_bytes(&command, &MATCH_ANY, expected_status_response, card); } From c036f5c9c3543fec3933e19a559a960e962e56fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 21 Nov 2022 17:49:26 +0100 Subject: [PATCH 54/59] Add basic pivy test --- Cargo.toml | 2 ++ tests/card/mod.rs | 37 +++++++++++++++++++++++++++++++++++++ tests/pivy.rs | 21 +++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 tests/card/mod.rs create mode 100644 tests/pivy.rs diff --git a/Cargo.toml b/Cargo.toml index 9d0eab3..c37b5c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,8 @@ test-log = "0.2" ron = "0.8" des = "0.8" aes = "0.8.2" +stoppable_thread = "0.2.1" +expectrl = "0.6.0" [features] diff --git a/tests/card/mod.rs b/tests/card/mod.rs new file mode 100644 index 0000000..9fa42f0 --- /dev/null +++ b/tests/card/mod.rs @@ -0,0 +1,37 @@ +use piv_authenticator::{vpicc::VirtualCard, Authenticator}; + +use std::{sync::mpsc, thread::sleep, time::Duration}; +use stoppable_thread::spawn; + +pub fn with_vsc R, R>(f: F) -> R { + let mut vpicc = vpicc::connect().expect("failed to connect to vpcd"); + + let (tx, rx) = mpsc::channel(); + let handle = spawn(move |stopped| { + trussed::virt::with_ram_client("opcard", |client| { + let card = Authenticator::new(client); + let mut virtual_card = VirtualCard::new(card); + let mut result = Ok(()); + while !stopped.get() && result.is_ok() { + result = vpicc.poll(&mut virtual_card); + if result.is_ok() { + tx.send(()).expect("failed to send message"); + } + } + result + }) + }); + + rx.recv().expect("failed to read message"); + + sleep(Duration::from_millis(200)); + + let result = f(); + + handle + .stop() + .join() + .expect("failed to join vpicc thread") + .expect("failed to run virtual smartcard"); + result +} diff --git a/tests/pivy.rs b/tests/pivy.rs new file mode 100644 index 0000000..1f03aa2 --- /dev/null +++ b/tests/pivy.rs @@ -0,0 +1,21 @@ +#![cfg(feature = "virtual")] + +mod card; + +use card::with_vsc; + +use expectrl::{spawn, Eof, Regex, WaitStatus}; + +#[test] +fn list() { + with_vsc(|| { + let mut p = spawn("pivy-tool list").unwrap(); + p.check(Regex("card: [0-9A-Z]*")).unwrap(); + p.check("device: Virtual PCD 00 00").unwrap(); + p.check("chuid: ok").unwrap(); + p.check(Regex("guid: [0-9A-Z]*")).unwrap(); + p.check("algos: 3DES AES256 ECCP256 (null) (null)").unwrap(); + p.check(Eof).unwrap(); + assert_eq!(p.wait().unwrap(), WaitStatus::Exited(p.pid(), 0)); + }); +} From 1c9a505b1086546f12473d5678e9b6de1b2783bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Tue, 22 Nov 2022 10:01:12 +0100 Subject: [PATCH 55/59] Fix reuse compliance --- tests/card/mod.rs | 3 +++ tests/pivy.rs | 3 +++ 2 files changed, 6 insertions(+) diff --git a/tests/card/mod.rs b/tests/card/mod.rs index 9fa42f0..2ef9c46 100644 --- a/tests/card/mod.rs +++ b/tests/card/mod.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use piv_authenticator::{vpicc::VirtualCard, Authenticator}; use std::{sync::mpsc, thread::sleep, time::Duration}; diff --git a/tests/pivy.rs b/tests/pivy.rs index 1f03aa2..c5dc1fa 100644 --- a/tests/pivy.rs +++ b/tests/pivy.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + #![cfg(feature = "virtual")] mod card; From ec5e758a09b00d0aeec5e5db70c5bd7dd1a38e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 16 Dec 2022 11:06:16 +0100 Subject: [PATCH 56/59] Add pivy to CI docker image --- ci/Dockerfile | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/ci/Dockerfile b/ci/Dockerfile index d0b6828..7896c87 100644 --- a/ci/Dockerfile +++ b/ci/Dockerfile @@ -3,7 +3,15 @@ FROM docker.io/rust:latest -RUN apt update && apt install --yes scdaemon libclang-dev llvm python3-pip vsmartcard-vpcd pkg-config nettle-dev libpcsclite-dev +RUN apt update && apt install --yes libpcsclite-dev \ + && wget https://github.com/arekinath/pivy/releases/download/v0.10.0/pivy-0.10.0-src.tar.gz \ + && tar xvf pivy-0.10.0-src.tar.gz \ + && cd pivy-0.10.0 \ + && make pivy-tool + +FROM docker.io/rust:latest + +RUN apt update && apt install --yes scdaemon libclang-dev llvm python3-pip vsmartcard-vpcd pkg-config nettle-dev libpcsclite-dev opensc RUN python3 -m pip install reuse @@ -14,6 +22,8 @@ RUN cargo search ENV CARGO_HOME=/app/.cache/cargo +COPY --from=0 pivy-0.10.0/pivy-tool /bin/pivy-tool + WORKDIR /app COPY entrypoint.sh /entrypoint.sh From ce366b6978659e22caec70d4bc3885683fc94210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 16 Dec 2022 11:14:19 +0100 Subject: [PATCH 57/59] Use Nitrokey trussed tag --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index c37b5c1..8261708 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,4 +60,4 @@ log-warn = [] log-error = [] [patch.crates-io] -trussed = { git = "https://github.com/sosthene-nitrokey/trussed", rev = "cbf8f3cc759fa79275fe06d3ce4661d6a4f306aa"} +trussed = { git = "https://github.com/Nitrokey/trussed", tag = "v0.1.0-nitrokey-3"} From 22a601125516633273f3a55b16729d214ae0c4a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 16 Dec 2022 11:19:18 +0100 Subject: [PATCH 58/59] Fix clippy warning --- tests/command_response.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/command_response.rs b/tests/command_response.rs index 5cf95a8..ea4f0aa 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -213,7 +213,7 @@ impl Default for OutputMatcher { fn parse_hex(data: &str) -> Vec { let tmp: String = data.split_whitespace().collect(); - hex::decode(&tmp).unwrap() + hex::decode(tmp).unwrap() } impl OutputMatcher { From d7d1a177fe94f146dfe1ac2826a089ee5c9326b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Fri, 16 Dec 2022 11:21:05 +0100 Subject: [PATCH 59/59] Fix documentation compilation --- src/piv_types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/piv_types.rs b/src/piv_types.rs index 7f27da9..7b3c76d 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -250,8 +250,8 @@ impl<'a> ApplicationPropertyTemplate<'a> { /// /// Note that the empty tags (i.e., tags with no data) return the same tag with content /// (they can be seen as “requests for requests”): -/// - '80 00' Returns '80 TL ' (as per definition) -/// - '81 00' Returns '81 TL ' (as per external authenticate example) +/// - '80 00' Returns '80 TL \' (as per definition) +/// - '81 00' Returns '81 TL \' (as per external authenticate example) #[derive(Clone, Copy, Default, Encodable, Eq, PartialEq)] #[tlv(application, constructed, number = "0x1C")] // = 0x7C pub struct DynamicAuthenticationTemplate<'l> {