Debian Codegraph @

third_party/rust/authenticator/src/ctap2/commands/client_pin.rs

raw
1 #![allow(non_upper_case_globals)]
2 use super::CtapResponse;
3 // Note: Needed for PinUvAuthTokenPermission
4 // The current version of `bitflags` doesn't seem to allow
5 // to set this for an individual bitflag-struct.
6 use super::{get_info::AuthenticatorInfo, Command, CommandError, RequestCtap2, StatusCode};
7 use crate::crypto::{COSEKey, CryptoError, PinUvAuthProtocol, SharedSecret};
8 use crate::transport::errors::HIDError;
9 use crate::transport::{FidoDevice, VirtualFidoDevice};
10 use serde::{
11 de::{Error as SerdeError, IgnoredAny, MapAccess, Visitor},
12 Deserialize, Deserializer, Serialize, Serializer,
13 };
14 use serde_bytes::{ByteBuf, Bytes};
15 use serde_cbor::de::from_slice;
16 use serde_cbor::ser::to_vec;
17 use serde_cbor::Value;
18 use sha2::{Digest, Sha256};
19 use std::convert::TryFrom;
20 use std::error::Error as StdErrorT;
21 use std::fmt;
22
23 #[derive(Debug, Copy, Clone)]
24 #[repr(u8)]
25 pub enum PINSubcommand {
26 GetPinRetries = 0x01,
27 GetKeyAgreement = 0x02,
28 SetPIN = 0x03,
29 ChangePIN = 0x04,
30 GetPINToken = 0x05, // superseded by GetPinUvAuth*
31 GetPinUvAuthTokenUsingUvWithPermissions = 0x06,
32 GetUvRetries = 0x07,
33 GetPinUvAuthTokenUsingPinWithPermissions = 0x09, // Yes, 0x08 is missing
34 }
35
36 bitflags! {
37 pub struct PinUvAuthTokenPermission: u8 {
38 const MakeCredential = 0x01; // rp_id required
39 const GetAssertion = 0x02; // rp_id required
40 const CredentialManagement = 0x04; // rp_id optional
41 const BioEnrollment = 0x08; // rp_id ignored
42 const LargeBlobWrite = 0x10; // rp_id ignored
43 const AuthenticatorConfiguration = 0x20; // rp_id ignored
44 }
45 }
46
47 impl Default for PinUvAuthTokenPermission {
48 fn default() -> Self {
49 // CTAP 2.1 spec:
50 // If authenticatorClientPIN's getPinToken subcommand is invoked, default permissions
51 // of `mc` and `ga` (value 0x03) are granted for the returned pinUvAuthToken.
52 PinUvAuthTokenPermission::MakeCredential | PinUvAuthTokenPermission::GetAssertion
53 }
54 }
55
56 #[derive(Debug)]
57 pub struct ClientPIN {
58 pub pin_protocol: Option<PinUvAuthProtocol>,
59 pub subcommand: PINSubcommand,
60 pub key_agreement: Option<COSEKey>,
61 pub pin_auth: Option<Vec<u8>>,
62 pub new_pin_enc: Option<Vec<u8>>,
63 pub pin_hash_enc: Option<Vec<u8>>,
64 pub permissions: Option<u8>,
65 pub rp_id: Option<String>,
66 }
67
68 impl Default for ClientPIN {
69 fn default() -> Self {
70 ClientPIN {
71 pin_protocol: None,
72 subcommand: PINSubcommand::GetPinRetries,
73 key_agreement: None,
74 pin_auth: None,
75 new_pin_enc: None,
76 pin_hash_enc: None,
77 permissions: None,
78 rp_id: None,
79 }
80 }
81 }
82
83 impl Serialize for ClientPIN {
84 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
85 where
86 S: Serializer,
87 {
88 let command: u8 = self.subcommand as u8;
89 serialize_map_optional!(
90 serializer,
91 &1 => self.pin_protocol.as_ref().map(|p| p.id()),
92 &2 => Some(&command),
93 &3 => &self.key_agreement,
94 &4 => self.pin_auth.as_ref().map(|pin_auth| Bytes::new(pin_auth.as_ref())),
95 &5 => self.new_pin_enc.as_ref().map(|new_pin_enc| Bytes::new(new_pin_enc.as_ref())),
96 &6 => self.pin_hash_enc.as_ref().map(|pin_hash_enc| Bytes::new(pin_hash_enc.as_ref())),
97 &9 => self.permissions,
98 &0x0A => &self.rp_id,
99 )
100 }
101 }
102
103 pub trait ClientPINSubCommand {
104 type Output;
105 fn as_client_pin(&self) -> Result<ClientPIN, CommandError>;
106 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError>;
107 }
108
109 #[derive(Default, Debug, PartialEq, Eq)]
110 pub struct ClientPinResponse {
111 pub key_agreement: Option<COSEKey>,
112 pub pin_token: Option<Vec<u8>>,
113 /// Number of PIN attempts remaining before lockout.
114 pub pin_retries: Option<u8>,
115 pub power_cycle_state: Option<bool>,
116 pub uv_retries: Option<u8>,
117 }
118
119 impl CtapResponse for ClientPinResponse {}
120
121 impl<'de> Deserialize<'de> for ClientPinResponse {
122 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
123 where
124 D: Deserializer<'de>,
125 {
126 struct ClientPinResponseVisitor;
127
128 impl<'de> Visitor<'de> for ClientPinResponseVisitor {
129 type Value = ClientPinResponse;
130
131 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
132 formatter.write_str("a map")
133 }
134
135 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
136 where
137 M: MapAccess<'de>,
138 {
139 let mut key_agreement = None;
140 let mut pin_token = None;
141 let mut pin_retries = None;
142 let mut power_cycle_state = None;
143 let mut uv_retries = None;
144 while let Some(key) = map.next_key()? {
145 match key {
146 0x01 => {
147 if key_agreement.is_some() {
148 return Err(SerdeError::duplicate_field("key_agreement"));
149 }
150 key_agreement = map.next_value()?;
151 }
152 0x02 => {
153 if pin_token.is_some() {
154 return Err(SerdeError::duplicate_field("pin_token"));
155 }
156 let value: ByteBuf = map.next_value()?;
157 pin_token = Some(value.into_vec());
158 }
159 0x03 => {
160 if pin_retries.is_some() {
161 return Err(SerdeError::duplicate_field("pin_retries"));
162 }
163 pin_retries = Some(map.next_value()?);
164 }
165 0x04 => {
166 if power_cycle_state.is_some() {
167 return Err(SerdeError::duplicate_field("power_cycle_state"));
168 }
169 power_cycle_state = Some(map.next_value()?);
170 }
171 0x05 => {
172 if uv_retries.is_some() {
173 return Err(SerdeError::duplicate_field("uv_retries"));
174 }
175 uv_retries = Some(map.next_value()?);
176 }
177 k => {
178 warn!("ClientPinResponse: unexpected key: {:?}", k);
179 let _ = map.next_value::<IgnoredAny>()?;
180 continue;
181 }
182 }
183 }
184 Ok(ClientPinResponse {
185 key_agreement,
186 pin_token,
187 pin_retries,
188 power_cycle_state,
189 uv_retries,
190 })
191 }
192 }
193 deserializer.deserialize_bytes(ClientPinResponseVisitor)
194 }
195 }
196
197 #[derive(Debug)]
198 pub struct GetKeyAgreement {
199 pin_protocol: PinUvAuthProtocol,
200 }
201
202 impl GetKeyAgreement {
203 pub fn new(pin_protocol: PinUvAuthProtocol) -> Self {
204 GetKeyAgreement { pin_protocol }
205 }
206 }
207
208 impl ClientPINSubCommand for GetKeyAgreement {
209 type Output = ClientPinResponse;
210
211 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
212 Ok(ClientPIN {
213 pin_protocol: Some(self.pin_protocol.clone()),
214 subcommand: PINSubcommand::GetKeyAgreement,
215 ..ClientPIN::default()
216 })
217 }
218
219 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
220 let get_pin_response: ClientPinResponse =
221 from_slice(input).map_err(CommandError::Deserializing)?;
222 if get_pin_response.key_agreement.is_none() {
223 return Err(CommandError::MissingRequiredField("key_agreement"));
224 }
225 Ok(get_pin_response)
226 }
227 }
228
229 #[derive(Debug)]
230 /// Superseded by GetPinUvAuthTokenUsingUvWithPermissions or
231 /// GetPinUvAuthTokenUsingPinWithPermissions, thus for backwards compatibility only
232 pub struct GetPinToken<'sc, 'pin> {
233 shared_secret: &'sc SharedSecret,
234 pin: &'pin Pin,
235 }
236
237 impl<'sc, 'pin> GetPinToken<'sc, 'pin> {
238 pub fn new(shared_secret: &'sc SharedSecret, pin: &'pin Pin) -> Self {
239 GetPinToken { shared_secret, pin }
240 }
241 }
242
243 impl<'sc, 'pin> ClientPINSubCommand for GetPinToken<'sc, 'pin> {
244 type Output = ClientPinResponse;
245
246 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
247 let input = self.pin.for_pin_token();
248 trace!("pin_hash = {:#04X?}", &input);
249 let pin_hash_enc = self.shared_secret.encrypt(&input)?;
250 trace!("pin_hash_enc = {:#04X?}", &pin_hash_enc);
251
252 Ok(ClientPIN {
253 pin_protocol: Some(self.shared_secret.pin_protocol.clone()),
254 subcommand: PINSubcommand::GetPINToken,
255 key_agreement: Some(self.shared_secret.client_input().clone()),
256 pin_hash_enc: Some(pin_hash_enc),
257 ..ClientPIN::default()
258 })
259 }
260
261 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
262 let get_pin_response: ClientPinResponse =
263 from_slice(input).map_err(CommandError::Deserializing)?;
264 if get_pin_response.pin_token.is_none() {
265 return Err(CommandError::MissingRequiredField("pin_token"));
266 }
267 Ok(get_pin_response)
268 }
269 }
270
271 #[derive(Debug)]
272 pub struct GetPinUvAuthTokenUsingPinWithPermissions<'sc, 'pin> {
273 shared_secret: &'sc SharedSecret,
274 pin: &'pin Pin,
275 permissions: PinUvAuthTokenPermission,
276 rp_id: Option<String>,
277 }
278
279 impl<'sc, 'pin> GetPinUvAuthTokenUsingPinWithPermissions<'sc, 'pin> {
280 pub fn new(
281 shared_secret: &'sc SharedSecret,
282 pin: &'pin Pin,
283 permissions: PinUvAuthTokenPermission,
284 rp_id: Option<String>,
285 ) -> Self {
286 GetPinUvAuthTokenUsingPinWithPermissions {
287 shared_secret,
288 pin,
289 permissions,
290 rp_id,
291 }
292 }
293 }
294
295 impl<'sc, 'pin> ClientPINSubCommand for GetPinUvAuthTokenUsingPinWithPermissions<'sc, 'pin> {
296 type Output = ClientPinResponse;
297
298 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
299 let input = self.pin.for_pin_token();
300 let pin_hash_enc = self.shared_secret.encrypt(&input)?;
301
302 Ok(ClientPIN {
303 pin_protocol: Some(self.shared_secret.pin_protocol.clone()),
304 subcommand: PINSubcommand::GetPinUvAuthTokenUsingPinWithPermissions,
305 key_agreement: Some(self.shared_secret.client_input().clone()),
306 pin_hash_enc: Some(pin_hash_enc),
307 permissions: Some(self.permissions.bits()),
308 rp_id: self.rp_id.clone(), /* TODO: This could probably be done less wasteful with
309 * &str all the way */
310 ..ClientPIN::default()
311 })
312 }
313
314 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
315 let get_pin_response: ClientPinResponse =
316 from_slice(input).map_err(CommandError::Deserializing)?;
317 if get_pin_response.pin_token.is_none() {
318 return Err(CommandError::MissingRequiredField("pin_token"));
319 }
320 Ok(get_pin_response)
321 }
322 }
323
324 macro_rules! implementRetries {
325 ($name:ident, $getter:ident) => {
326 #[derive(Debug, Default)]
327 pub struct $name {}
328
329 impl $name {
330 pub fn new() -> Self {
331 Self {}
332 }
333 }
334
335 impl ClientPINSubCommand for $name {
336 type Output = ClientPinResponse;
337
338 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
339 Ok(ClientPIN {
340 subcommand: PINSubcommand::$name,
341 ..ClientPIN::default()
342 })
343 }
344
345 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
346 let get_pin_response: ClientPinResponse =
347 from_slice(input).map_err(CommandError::Deserializing)?;
348 if get_pin_response.$getter.is_none() {
349 return Err(CommandError::MissingRequiredField(stringify!($getter)));
350 }
351 Ok(get_pin_response)
352 }
353 }
354 };
355 }
356
357 implementRetries!(GetPinRetries, pin_retries);
358 implementRetries!(GetUvRetries, uv_retries);
359
360 #[derive(Debug)]
361 pub struct GetPinUvAuthTokenUsingUvWithPermissions<'sc> {
362 shared_secret: &'sc SharedSecret,
363 permissions: PinUvAuthTokenPermission,
364 rp_id: Option<String>,
365 }
366
367 impl<'sc> GetPinUvAuthTokenUsingUvWithPermissions<'sc> {
368 pub fn new(
369 shared_secret: &'sc SharedSecret,
370 permissions: PinUvAuthTokenPermission,
371 rp_id: Option<String>,
372 ) -> Self {
373 GetPinUvAuthTokenUsingUvWithPermissions {
374 shared_secret,
375 permissions,
376 rp_id,
377 }
378 }
379 }
380
381 impl<'sc> ClientPINSubCommand for GetPinUvAuthTokenUsingUvWithPermissions<'sc> {
382 type Output = ClientPinResponse;
383
384 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
385 Ok(ClientPIN {
386 pin_protocol: Some(self.shared_secret.pin_protocol.clone()),
387 subcommand: PINSubcommand::GetPinUvAuthTokenUsingUvWithPermissions,
388 key_agreement: Some(self.shared_secret.client_input().clone()),
389 permissions: Some(self.permissions.bits()),
390 rp_id: self.rp_id.clone(), /* TODO: This could probably be done less wasteful with
391 * &str all the way */
392 ..ClientPIN::default()
393 })
394 }
395
396 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
397 let get_pin_response: ClientPinResponse =
398 from_slice(input).map_err(CommandError::Deserializing)?;
399 if get_pin_response.pin_token.is_none() {
400 return Err(CommandError::MissingRequiredField("pin_token"));
401 }
402 Ok(get_pin_response)
403 }
404 }
405
406 #[derive(Debug)]
407 pub struct SetNewPin<'sc, 'pin> {
408 shared_secret: &'sc SharedSecret,
409 new_pin: &'pin Pin,
410 }
411
412 impl<'sc, 'pin> SetNewPin<'sc, 'pin> {
413 pub fn new(shared_secret: &'sc SharedSecret, new_pin: &'pin Pin) -> Self {
414 SetNewPin {
415 shared_secret,
416 new_pin,
417 }
418 }
419 }
420
421 impl<'sc, 'pin> ClientPINSubCommand for SetNewPin<'sc, 'pin> {
422 type Output = ClientPinResponse;
423
424 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
425 if self.new_pin.as_bytes().len() > 63 {
426 return Err(CommandError::StatusCode(
427 StatusCode::PinPolicyViolation,
428 None,
429 ));
430 }
431
432 // newPinEnc: the result of calling encrypt(shared secret, paddedPin) where paddedPin is
433 // newPin padded on the right with 0x00 bytes to make it 64 bytes long. (Since the maximum
434 // length of newPin is 63 bytes, there is always at least one byte of padding.)
435 let new_pin_padded = self.new_pin.padded();
436 let new_pin_enc = self.shared_secret.encrypt(&new_pin_padded)?;
437
438 // pinUvAuthParam: the result of calling authenticate(shared secret, newPinEnc).
439 let pin_auth = self.shared_secret.authenticate(&new_pin_enc)?;
440
441 Ok(ClientPIN {
442 pin_protocol: Some(self.shared_secret.pin_protocol.clone()),
443 subcommand: PINSubcommand::SetPIN,
444 key_agreement: Some(self.shared_secret.client_input().clone()),
445 new_pin_enc: Some(new_pin_enc),
446 pin_auth: Some(pin_auth),
447 ..ClientPIN::default()
448 })
449 }
450
451 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
452 // Should be an empty response or a valid cbor-value (which we ignore)
453 if !input.is_empty() {
454 let _: Value = from_slice(input).map_err(CommandError::Deserializing)?;
455 }
456 Ok(ClientPinResponse::default())
457 }
458 }
459
460 #[derive(Debug)]
461 pub struct ChangeExistingPin<'sc, 'pin> {
462 pin_protocol: PinUvAuthProtocol,
463 shared_secret: &'sc SharedSecret,
464 current_pin: &'pin Pin,
465 new_pin: &'pin Pin,
466 }
467
468 impl<'sc, 'pin> ChangeExistingPin<'sc, 'pin> {
469 pub fn new(
470 info: &AuthenticatorInfo,
471 shared_secret: &'sc SharedSecret,
472 current_pin: &'pin Pin,
473 new_pin: &'pin Pin,
474 ) -> Result<Self, CommandError> {
475 Ok(ChangeExistingPin {
476 pin_protocol: PinUvAuthProtocol::try_from(info)?,
477 shared_secret,
478 current_pin,
479 new_pin,
480 })
481 }
482 }
483
484 impl<'sc, 'pin> ClientPINSubCommand for ChangeExistingPin<'sc, 'pin> {
485 type Output = ClientPinResponse;
486
487 fn as_client_pin(&self) -> Result<ClientPIN, CommandError> {
488 if self.new_pin.as_bytes().len() > 63 {
489 return Err(CommandError::StatusCode(
490 StatusCode::PinPolicyViolation,
491 None,
492 ));
493 }
494
495 // newPinEnc: the result of calling encrypt(shared secret, paddedPin) where paddedPin is
496 // newPin padded on the right with 0x00 bytes to make it 64 bytes long. (Since the maximum
497 // length of newPin is 63 bytes, there is always at least one byte of padding.)
498 let new_pin_padded = self.new_pin.padded();
499 let new_pin_enc = self.shared_secret.encrypt(&new_pin_padded)?;
500
501 let current_pin_hash = self.current_pin.for_pin_token();
502 let pin_hash_enc = self.shared_secret.encrypt(current_pin_hash.as_ref())?;
503
504 let pin_auth = self
505 .shared_secret
506 .authenticate(&[new_pin_enc.as_slice(), pin_hash_enc.as_slice()].concat())?;
507
508 Ok(ClientPIN {
509 pin_protocol: Some(self.shared_secret.pin_protocol.clone()),
510 subcommand: PINSubcommand::ChangePIN,
511 key_agreement: Some(self.shared_secret.client_input().clone()),
512 new_pin_enc: Some(new_pin_enc),
513 pin_hash_enc: Some(pin_hash_enc),
514 pin_auth: Some(pin_auth),
515 permissions: None,
516 rp_id: None,
517 })
518 }
519
520 fn parse_response_payload(&self, input: &[u8]) -> Result<Self::Output, CommandError> {
521 // Should be an empty response or a valid cbor-value (which we ignore)
522 if !input.is_empty() {
523 let _: Value = from_slice(input).map_err(CommandError::Deserializing)?;
524 }
525 Ok(ClientPinResponse::default())
526 }
527 }
528
529 impl<T> RequestCtap2 for T
530 where
531 T: ClientPINSubCommand<Output = ClientPinResponse>,
532 T: fmt::Debug,
533 {
534 type Output = <T as ClientPINSubCommand>::Output;
535
536 fn command(&self) -> Command {
537 Command::ClientPin
538 }
539
540 fn wire_format(&self) -> Result<Vec<u8>, HIDError> {
541 let client_pin = self.as_client_pin()?;
542 let output = to_vec(&client_pin).map_err(CommandError::Serializing)?;
543 trace!("client subcommmand: {:04X?}", &output);
544
545 Ok(output)
546 }
547
548 fn handle_response_ctap2<Dev: FidoDevice>(
549 &self,
550 _dev: &mut Dev,
551 input: &[u8],
552 ) -> Result<Self::Output, HIDError> {
553 trace!("Client pin subcomand response:{:04X?}", &input);
554 if input.is_empty() {
555 return Err(CommandError::InputTooSmall.into());
556 }
557
558 let status: StatusCode = input[0].into();
559 debug!("response status code: {:?}", status);
560 if status.is_ok() {
561 <T as ClientPINSubCommand>::parse_response_payload(self, &input[1..])
562 .map_err(HIDError::Command)
563 } else {
564 let add_data = if input.len() > 1 {
565 let data: Value = from_slice(&input[1..]).map_err(CommandError::Deserializing)?;
566 Some(data)
567 } else {
568 None
569 };
570 Err(CommandError::StatusCode(status, add_data).into())
571 }
572 }
573
574 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
575 &self,
576 dev: &mut Dev,
577 ) -> Result<ClientPinResponse, HIDError> {
578 dev.client_pin(&self.as_client_pin()?)
579 }
580 }
581
582 #[derive(Clone, Serialize, Deserialize)]
583 pub struct Pin(String);
584
585 impl fmt::Debug for Pin {
586 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
587 write!(f, "Pin(redacted)")
588 }
589 }
590
591 impl Pin {
592 pub fn new(value: &str) -> Pin {
593 Pin(String::from(value))
594 }
595
596 pub fn for_pin_token(&self) -> Vec<u8> {
597 Sha256::digest(self.as_bytes())[..16].into()
598 }
599
600 pub fn padded(&self) -> Vec<u8> {
601 let mut out = self.0.as_bytes().to_vec();
602 out.resize(64, 0x00);
603 out
604 }
605
606 pub fn as_bytes(&self) -> &[u8] {
607 self.0.as_bytes()
608 }
609 }
610
611 #[derive(Clone, Debug, Serialize)]
612 pub enum PinError {
613 PinRequired,
614 PinIsTooShort,
615 PinIsTooLong(usize),
616 InvalidPin(Option<u8>),
617 InvalidUv(Option<u8>),
618 PinAuthBlocked,
619 PinBlocked,
620 PinNotSet,
621 UvBlocked,
622 /// Used for CTAP2.0 UV (fingerprints)
623 PinAuthInvalid,
624 Crypto(CryptoError),
625 }
626
627 impl fmt::Display for PinError {
628 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629 match *self {
630 PinError::PinRequired => write!(f, "Pin required."),
631 PinError::PinIsTooShort => write!(f, "pin is too short"),
632 PinError::PinIsTooLong(len) => write!(f, "pin is too long ({len})"),
633 PinError::InvalidPin(ref e) => {
634 let mut res = write!(f, "Invalid Pin.");
635 if let Some(pin_retries) = e {
636 res = write!(f, " Retries left: {pin_retries:?}")
637 }
638 res
639 }
640 PinError::InvalidUv(ref e) => {
641 let mut res = write!(f, "Invalid Uv.");
642 if let Some(uv_retries) = e {
643 res = write!(f, " Retries left: {uv_retries:?}")
644 }
645 res
646 }
647 PinError::PinAuthBlocked => {
648 write!(f, "Pin authentication blocked. Device needs power cycle.")
649 }
650 PinError::PinBlocked => write!(f, "No retries left. Pin blocked. Device needs reset."),
651 PinError::PinNotSet => write!(f, "Pin needed but not set on device."),
652 PinError::UvBlocked => write!(f, "No retries left. Uv blocked. Device needs reset."),
653 PinError::PinAuthInvalid => write!(f, "PinAuth invalid."),
654 PinError::Crypto(ref e) => write!(f, "Crypto backend error: {e:?}"),
655 }
656 }
657 }
658
659 impl StdErrorT for PinError {}
660
661 impl From<CryptoError> for PinError {
662 fn from(e: CryptoError) -> Self {
663 PinError::Crypto(e)
664 }
665 }
666
667 #[cfg(test)]
668 mod test {
669 use std::convert::TryFrom;
670
671 use super::ClientPinResponse;
672 use crate::{
673 crypto::{COSEAlgorithm, COSEEC2Key, COSEKey, COSEKeyType, Curve, PinUvAuthProtocol},
674 ctap2::commands::client_pin::{ClientPIN, PINSubcommand, PinUvAuthTokenPermission},
675 AuthenticatorInfo,
676 };
677 use serde_cbor::de::from_slice;
678
679 #[test]
680 fn test_get_key_agreement() {
681 let reference = [
682 161, 1, 165, 1, 2, 3, 56, 24, 32, 1, 33, 88, 32, 115, 222, 167, 5, 88, 238, 119, 202,
683 121, 23, 241, 150, 9, 48, 197, 136, 174, 0, 17, 90, 190, 83, 65, 103, 237, 97, 41, 213,
684 128, 111, 7, 106, 34, 88, 32, 248, 204, 9, 26, 82, 96, 25, 72, 5, 82, 251, 185, 22, 39,
685 246, 149, 54, 246, 255, 225, 52, 102, 67, 221, 113, 194, 236, 213, 199, 147, 180, 81,
686 ];
687 let expected = ClientPinResponse {
688 key_agreement: Some(COSEKey {
689 alg: COSEAlgorithm::ECDH_ES_HKDF256,
690 key: COSEKeyType::EC2(COSEEC2Key {
691 curve: Curve::SECP256R1,
692 x: vec![
693 115, 222, 167, 5, 88, 238, 119, 202, 121, 23, 241, 150, 9, 48, 197, 136,
694 174, 0, 17, 90, 190, 83, 65, 103, 237, 97, 41, 213, 128, 111, 7, 106,
695 ],
696 y: vec![
697 248, 204, 9, 26, 82, 96, 25, 72, 5, 82, 251, 185, 22, 39, 246, 149, 54,
698 246, 255, 225, 52, 102, 67, 221, 113, 194, 236, 213, 199, 147, 180, 81,
699 ],
700 }),
701 }),
702 pin_token: None,
703 pin_retries: None,
704 power_cycle_state: None,
705 uv_retries: None,
706 };
707 let result: ClientPinResponse =
708 from_slice(&reference).expect("could not deserialize reference");
709 assert_eq!(expected, result);
710 }
711
712 #[test]
713 fn test_get_pin_retries() {
714 let reference = [161, 3, 7];
715 let expected = ClientPinResponse {
716 key_agreement: None,
717 pin_token: None,
718 pin_retries: Some(7),
719 power_cycle_state: None,
720 uv_retries: None,
721 };
722 let result: ClientPinResponse =
723 from_slice(&reference).expect("could not deserialize reference");
724 assert_eq!(expected, result);
725 }
726
727 #[test]
728 fn test_get_uv_retries() {
729 let reference = [161, 5, 2];
730 let expected = ClientPinResponse {
731 key_agreement: None,
732 pin_token: None,
733 pin_retries: None,
734 power_cycle_state: None,
735 uv_retries: Some(2),
736 };
737 let result: ClientPinResponse =
738 from_slice(&reference).expect("could not deserialize reference");
739 assert_eq!(expected, result);
740 }
741
742 #[test]
743 fn test_get_pin_token() {
744 let reference = [
745 161, 2, 88, 48, 173, 244, 214, 87, 128, 57, 25, 99, 142, 140, 41, 25, 94, 60, 75, 163,
746 240, 187, 211, 138, 11, 208, 74, 117, 180, 181, 97, 31, 79, 252, 191, 244, 49, 13, 201,
747 217, 204, 219, 122, 3, 101, 4, 70, 26, 14, 41, 150, 148,
748 ];
749 let expected = ClientPinResponse {
750 key_agreement: None,
751 pin_token: Some(vec![
752 173, 244, 214, 87, 128, 57, 25, 99, 142, 140, 41, 25, 94, 60, 75, 163, 240, 187,
753 211, 138, 11, 208, 74, 117, 180, 181, 97, 31, 79, 252, 191, 244, 49, 13, 201, 217,
754 204, 219, 122, 3, 101, 4, 70, 26, 14, 41, 150, 148,
755 ]),
756 pin_retries: None,
757 power_cycle_state: None,
758 uv_retries: None,
759 };
760 let result: ClientPinResponse =
761 from_slice(&reference).expect("could not deserialize reference");
762 assert_eq!(expected, result);
763 }
764
765 #[test]
766 fn test_get_puat_using_uv() {
767 let reference = [
768 161, 2, 88, 48, 94, 109, 192, 236, 90, 161, 77, 153, 23, 146, 179, 189, 133, 106, 76,
769 150, 17, 238, 155, 102, 107, 201, 98, 232, 184, 33, 153, 224, 203, 87, 147, 10, 21, 20,
770 85, 184, 109, 61, 240, 58, 236, 198, 171, 48, 242, 165, 221, 214,
771 ];
772 let expected = ClientPinResponse {
773 key_agreement: None,
774 pin_token: Some(vec![
775 94, 109, 192, 236, 90, 161, 77, 153, 23, 146, 179, 189, 133, 106, 76, 150, 17, 238,
776 155, 102, 107, 201, 98, 232, 184, 33, 153, 224, 203, 87, 147, 10, 21, 20, 85, 184,
777 109, 61, 240, 58, 236, 198, 171, 48, 242, 165, 221, 214,
778 ]),
779 pin_retries: None,
780 power_cycle_state: None,
781 uv_retries: None,
782 };
783 let result: ClientPinResponse =
784 from_slice(&reference).expect("could not deserialize reference");
785 assert_eq!(expected, result);
786 }
787
788 #[test]
789 fn test_get_puat_using_pin() {
790 let reference = [
791 161, 2, 88, 48, 143, 174, 68, 241, 186, 39, 106, 238, 129, 15, 181, 102, 112, 130, 239,
792 96, 106, 235, 3, 10, 61, 173, 106, 252, 38, 236, 44, 112, 91, 34, 218, 136, 139, 118,
793 162, 178, 172, 227, 82, 103, 136, 91, 136, 178, 170, 233, 156, 62,
794 ];
795 let expected = ClientPinResponse {
796 key_agreement: None,
797 pin_token: Some(vec![
798 143, 174, 68, 241, 186, 39, 106, 238, 129, 15, 181, 102, 112, 130, 239, 96, 106,
799 235, 3, 10, 61, 173, 106, 252, 38, 236, 44, 112, 91, 34, 218, 136, 139, 118, 162,
800 178, 172, 227, 82, 103, 136, 91, 136, 178, 170, 233, 156, 62,
801 ]),
802 pin_retries: None,
803 power_cycle_state: None,
804 uv_retries: None,
805 };
806 let result: ClientPinResponse =
807 from_slice(&reference).expect("could not deserialize reference");
808 assert_eq!(expected, result);
809 }
810
811 #[test]
812 fn test_serialize_client_pin() {
813 let client_pin = ClientPIN {
814 pin_protocol: Some(
815 PinUvAuthProtocol::try_from(&AuthenticatorInfo {
816 pin_protocols: Some(vec![2]),
817 ..Default::default()
818 })
819 .expect("Failed to create PIN protocol"),
820 ),
821 subcommand: PINSubcommand::GetPinRetries,
822 key_agreement: Some(COSEKey {
823 alg: COSEAlgorithm::ECDH_ES_HKDF256,
824 key: COSEKeyType::EC2(COSEEC2Key {
825 curve: Curve::SECP256R1,
826 x: vec![],
827 y: vec![],
828 }),
829 }),
830 pin_auth: Some(vec![1, 2, 3, 4]),
831 new_pin_enc: Some(vec![5, 6, 7, 8]),
832 pin_hash_enc: Some(vec![9, 10, 11, 12]),
833 permissions: Some(PinUvAuthTokenPermission::CredentialManagement.bits()),
834 rp_id: Some("example.org".to_string()),
835 };
836 let serialized = serde_cbor::ser::to_vec(&client_pin).expect("Failed to serialize to CBOR");
837 assert_eq!(
838 serialized,
839 [
840 // Value copied from test failure output as regression test snapshot
841 168, 1, 2, 2, 1, 3, 165, 1, 2, 3, 56, 24, 32, 1, 33, 64, 34, 64, 4, 68, 1, 2, 3, 4,
842 5, 68, 5, 6, 7, 8, 6, 68, 9, 10, 11, 12, 9, 4, 10, 107, 101, 120, 97, 109, 112,
843 108, 101, 46, 111, 114, 103
844 ]
845 );
846 }
847 }