Debian Codegraph @

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

raw
1 use super::get_info::AuthenticatorInfo;
2 use super::{
3 Command, CommandError, CtapResponse, PinUvAuthCommand, PinUvAuthResult, RequestCtap1,
4 RequestCtap2, Retryable, StatusCode,
5 };
6 use crate::consts::{
7 PARAMETER_SIZE, U2F_AUTHENTICATE, U2F_DONT_ENFORCE_USER_PRESENCE_AND_SIGN,
8 U2F_REQUEST_USER_PRESENCE,
9 };
10 use crate::crypto::{COSEKey, CryptoError, PinUvAuthParam, PinUvAuthToken, SharedSecret};
11 use crate::ctap2::attestation::{AuthenticatorData, AuthenticatorDataFlags, HmacSecretResponse};
12 use crate::ctap2::client_data::ClientDataHash;
13 use crate::ctap2::commands::get_next_assertion::GetNextAssertion;
14 use crate::ctap2::commands::make_credentials::UserVerification;
15 use crate::ctap2::server::{
16 AuthenticationExtensionsClientInputs, AuthenticationExtensionsClientOutputs,
17 AuthenticationExtensionsPRFInputs, AuthenticationExtensionsPRFOutputs, AuthenticatorAttachment,
18 PublicKeyCredentialDescriptor, PublicKeyCredentialUserEntity, RelyingParty, RpIdHash,
19 UserVerificationRequirement,
20 };
21 use crate::ctap2::utils::{read_be_u32, read_byte};
22 use crate::errors::AuthenticatorError;
23 use crate::transport::errors::{ApduErrorStatus, HIDError};
24 use crate::transport::{FidoDevice, VirtualFidoDevice};
25 use crate::u2ftypes::CTAP1RequestAPDU;
26 use serde::{
27 de::{Error as DesError, MapAccess, Visitor},
28 ser::Error as SerError,
29 Deserialize, Deserializer, Serialize, Serializer,
30 };
31 use serde_bytes::ByteBuf;
32 use serde_cbor::{de::from_slice, ser, Value};
33 use std::convert::TryFrom;
34 use std::fmt;
35 use std::io::Cursor;
36
37 #[derive(Clone, Copy, Debug, Serialize)]
38 #[cfg_attr(test, derive(Deserialize))]
39 pub struct GetAssertionOptions {
40 #[serde(rename = "uv", skip_serializing_if = "Option::is_none")]
41 pub user_verification: Option<bool>,
42 #[serde(rename = "up", skip_serializing_if = "Option::is_none")]
43 pub user_presence: Option<bool>,
44 }
45
46 impl Default for GetAssertionOptions {
47 fn default() -> Self {
48 Self {
49 user_presence: Some(true),
50 user_verification: None,
51 }
52 }
53 }
54
55 impl GetAssertionOptions {
56 pub(crate) fn has_some(&self) -> bool {
57 self.user_presence.is_some() || self.user_verification.is_some()
58 }
59 }
60
61 impl UserVerification for GetAssertionOptions {
62 fn ask_user_verification(&self) -> bool {
63 if let Some(e) = self.user_verification {
64 e
65 } else {
66 false
67 }
68 }
69 }
70
71 #[derive(Debug, Clone, PartialEq)]
72 pub struct CalculatedHmacSecretExtension {
73 pub public_key: COSEKey,
74 pub salt_enc: Vec<u8>,
75 pub salt_auth: Vec<u8>,
76 }
77
78 /// Wrapper type recording whether the hmac-secret input originally came from the hmacGetSecret or the prf client extension input.
79 #[derive(Debug, Clone, PartialEq)]
80 pub enum HmacGetSecretOrPrf {
81 /// hmac-secret inputs set by the hmacGetSecret client extension input.
82 HmacGetSecret(HmacSecretExtension),
83 /// hmac-secret input is to be calculated from PRF inputs, but we haven't yet identified which eval or evalByCredential entry to use.
84 PrfUninitialized(AuthenticationExtensionsPRFInputs),
85 /// prf client input with no eval or matching evalByCredential entry.
86 PrfUnmatched,
87 /// hmac-secret inputs set by the prf client extension input.
88 Prf(HmacSecretExtension),
89 }
90
91 impl HmacGetSecretOrPrf {
92 fn skip_serializing(value: &Option<Self>) -> bool {
93 matches!(value, None | Some(Self::PrfUnmatched))
94 }
95
96 /// Calculate the appropriate hmac-secret or PRF salt inputs from the given inputs.
97 ///
98 /// - If this is a `HmacGetSecret` instance,
99 /// this returns a new `HmacGetSecret` instance with `calculated_hmac` set, paired with [None].
100 /// - If this is a `PrfUninitialized` instance,
101 /// this attempts to select a PRF input to calculate salts from.
102 /// If an input is found, this returns a `Prf` instance with `calculated_hmac` set.
103 /// If the selected input came from `eval_by_credential`,
104 /// then this is paired with a [Some] referencing the matching element of `allow_credentials`.
105 /// If the selected input was `eval`, then this is paired with [None].
106 /// If no input is found, this returns `PrfUnmatched` and [None].
107 /// - If this is a `Prf` or `PrfUnmatched` instance, this panics.
108 ///
109 /// If the [Option] return value is [Some], the caller SHOULD set `allowCredentials`
110 /// to contain only that [PublicKeyCredentialDescriptor] value.
111 ///
112 /// # Panics
113 /// If this is a `Prf` or `PrfUnmatched` instance.
114 pub fn calculate<'allow_cred>(
115 self,
116 secret: &SharedSecret,
117 allow_credentials: &'allow_cred [PublicKeyCredentialDescriptor],
118 puat: Option<&PinUvAuthToken>,
119 ) -> Result<(Self, Option<&'allow_cred PublicKeyCredentialDescriptor>), CryptoError> {
120 Ok(match self {
121 Self::HmacGetSecret(mut extension) => {
122 extension.calculate(secret, puat)?;
123 (Self::HmacGetSecret(extension), None)
124 }
125
126 Self::PrfUninitialized(prf) => match prf.calculate(secret, allow_credentials, puat)? {
127 Some((hmac_secret, selected_credential)) => {
128 (Self::Prf(hmac_secret), selected_credential)
129 }
130 None => (Self::PrfUnmatched, None),
131 },
132
133 Self::Prf(_) | Self::PrfUnmatched => {
134 unreachable!("hmac-secret inputs from PRF already initialized")
135 }
136 })
137 }
138 }
139
140 impl Serialize for HmacGetSecretOrPrf {
141 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
142 where
143 S: Serializer,
144 {
145 match self {
146 Self::HmacGetSecret(ext) => ext.serialize(s),
147 Self::PrfUninitialized(_) => Err(serde::ser::Error::custom(
148 "PrfUninitialized must be replaced with Prf or PrfUnmatched before serializing",
149 )),
150 Self::PrfUnmatched => unreachable!("PrfUnmatched serialization should be skipped"),
151 Self::Prf(ext) => ext.serialize(s),
152 }
153 }
154 }
155
156 #[derive(Debug, Clone, Default, PartialEq)]
157 pub struct HmacSecretExtension {
158 pub salt1: Vec<u8>,
159 pub salt2: Option<Vec<u8>>,
160 calculated_hmac: Option<CalculatedHmacSecretExtension>,
161 pin_protocol: Option<u64>,
162 }
163
164 impl HmacSecretExtension {
165 pub fn new(salt1: Vec<u8>, salt2: Option<Vec<u8>>) -> Self {
166 HmacSecretExtension {
167 salt1,
168 salt2,
169 calculated_hmac: None,
170 pin_protocol: None,
171 }
172 }
173
174 #[cfg(test)]
175 pub fn new_test(
176 salt1: Vec<u8>,
177 salt2: Option<Vec<u8>>,
178 calculated_hmac: CalculatedHmacSecretExtension,
179 pin_protocol: Option<u64>,
180 ) -> Self {
181 HmacSecretExtension {
182 salt1,
183 salt2,
184 calculated_hmac: Some(calculated_hmac),
185 pin_protocol,
186 }
187 }
188
189 /// Calculate inputs for the `hmac-secret` extension.
190 /// See "authenticatorGetAssertion additional behaviors"
191 /// in https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#sctn-hmac-secret-extension
192 pub fn calculate(
193 &mut self,
194 secret: &SharedSecret,
195 puat: Option<&PinUvAuthToken>,
196 ) -> Result<(), CryptoError> {
197 let salt_enc = match (
198 <[u8; 32]>::try_from(self.salt1.as_slice()),
199 self.salt2.as_deref().map(<[u8; 32]>::try_from),
200 ) {
201 (Ok(salt1), None) => secret.encrypt(&salt1),
202 (Ok(salt1), Some(Ok(salt2))) => secret.encrypt(&[salt1, salt2].concat()),
203 (Err(_), _) | (_, Some(Err(_))) => {
204 debug!("Invalid hmac-secret salt length(s): salt1: {}, salt2: {:?} (expected 32 and 32|None)",
205 self.salt1.len(), self.salt2.as_ref().map(Vec::len));
206 Err(CryptoError::WrongSaltLength)
207 }
208 }?;
209 let salt_auth = secret.authenticate(&salt_enc)?;
210 let public_key = secret.client_input().clone();
211 self.calculated_hmac = Some(CalculatedHmacSecretExtension {
212 public_key,
213 salt_enc,
214 salt_auth,
215 });
216
217 // CTAP2.1 platforms MUST include this parameter if the value of pinUvAuthProtocol is not 1.
218 self.pin_protocol = puat
219 .map(|puat| puat.pin_protocol.id())
220 .filter(|id| *id != 1);
221
222 Ok(())
223 }
224 }
225
226 impl Serialize for HmacSecretExtension {
227 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
228 where
229 S: Serializer,
230 {
231 if let Some(calc) = &self.calculated_hmac {
232 serialize_map_optional! {
233 serializer,
234 &1 => Some(&calc.public_key),
235 &2 => Some(serde_bytes::Bytes::new(&calc.salt_enc)),
236 &3 => Some(serde_bytes::Bytes::new(&calc.salt_auth)),
237 &4 => &self.pin_protocol,
238 }
239 } else {
240 Err(SerError::custom(
241 "hmac secret has not been calculated before being serialized",
242 ))
243 }
244 }
245 }
246
247 #[derive(Debug, Default, Clone, Serialize)]
248 pub struct GetAssertionExtensions {
249 #[serde(skip_serializing)]
250 pub app_id: Option<String>,
251 #[serde(
252 rename = "hmac-secret",
253 skip_serializing_if = "HmacGetSecretOrPrf::skip_serializing"
254 )]
255 pub hmac_secret: Option<HmacGetSecretOrPrf>,
256 }
257
258 impl From<AuthenticationExtensionsClientInputs> for GetAssertionExtensions {
259 fn from(input: AuthenticationExtensionsClientInputs) -> Self {
260 let prf = input.prf;
261 Self {
262 app_id: input.app_id,
263 hmac_secret: input
264 .hmac_get_secret
265 .map(|hmac_secret| {
266 HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
267 hmac_secret.salt1.into(),
268 hmac_secret.salt2.map(|salt2| salt2.into()),
269 ))
270 })
271 .or_else(
272 || prf.map(HmacGetSecretOrPrf::PrfUninitialized), // Cannot calculate hmac-secret inputs here because we don't yet know which eval or evalByCredential entry to use
273 ),
274 }
275 }
276 }
277
278 impl GetAssertionExtensions {
279 fn has_content(&self) -> bool {
280 self.hmac_secret.is_some()
281 }
282 }
283
284 #[derive(Debug, Clone)]
285 pub struct GetAssertion {
286 pub client_data_hash: ClientDataHash,
287 pub rp: RelyingParty,
288 pub allow_list: Vec<PublicKeyCredentialDescriptor>,
289
290 // https://www.w3.org/TR/webauthn/#client-extension-input
291 // The client extension input, which is a value that can be encoded in JSON,
292 // is passed from the WebAuthn Relying Party to the client in the get() or
293 // create() call, while the CBOR authenticator extension input is passed
294 // from the client to the authenticator for authenticator extensions during
295 // the processing of these calls.
296 pub extensions: GetAssertionExtensions,
297 pub options: GetAssertionOptions,
298 pub pin_uv_auth_param: Option<PinUvAuthParam>,
299 }
300
301 impl GetAssertion {
302 pub fn new(
303 client_data_hash: ClientDataHash,
304 rp: RelyingParty,
305 allow_list: Vec<PublicKeyCredentialDescriptor>,
306 options: GetAssertionOptions,
307 extensions: GetAssertionExtensions,
308 ) -> Self {
309 Self {
310 client_data_hash,
311 rp,
312 allow_list,
313 extensions,
314 options,
315 pin_uv_auth_param: None,
316 }
317 }
318
319 pub fn process_hmac_secret_and_prf_extension(
320 mut self,
321 shared_secret: Option<(&SharedSecret, &PinUvAuthResult)>,
322 ) -> Result<Self, AuthenticatorError> {
323 let (new_hmac_secret, new_allow_list) = self
324 .extensions
325 .hmac_secret
326 .take()
327 .and_then(|hmac_get_secret_or_prf| {
328 if let Some((secret, pin_uv_auth_result)) = shared_secret {
329 Some(hmac_get_secret_or_prf.calculate(
330 secret,
331 &self.allow_list,
332 pin_uv_auth_result.get_pin_uv_auth_token().as_ref(),
333 ))
334 } else {
335 debug!(
336 "Shared secret not available - will not send hmac-secret extension input: {:?}",
337 hmac_get_secret_or_prf
338 );
339 match hmac_get_secret_or_prf {
340 HmacGetSecretOrPrf::HmacGetSecret(_) => None,
341 HmacGetSecretOrPrf::PrfUninitialized(_)
342 | HmacGetSecretOrPrf::PrfUnmatched
343 | HmacGetSecretOrPrf::Prf(_) => {
344 Some(Ok((HmacGetSecretOrPrf::PrfUnmatched, None)))
345 }
346 }
347 }
348 })
349 .transpose()
350 .map_err(|err| match err {
351 CryptoError::WrongSaltLength => AuthenticatorError::InvalidRelyingPartyInput,
352 e => e.into(),
353 })?
354 .map(|(nhs, nal)| (Some(nhs), nal))
355 .unwrap_or((None, None));
356
357 (self.extensions.hmac_secret, self.allow_list) = (
358 new_hmac_secret,
359 new_allow_list
360 .map(|selected_credential| vec![selected_credential.clone()])
361 .unwrap_or(self.allow_list),
362 );
363
364 Ok(self)
365 }
366
367 pub fn finalize_result<Dev: FidoDevice>(&self, dev: &Dev, result: &mut GetAssertionResult) {
368 result.attachment = match dev.get_authenticator_info() {
369 Some(info) if info.options.platform_device => AuthenticatorAttachment::Platform,
370 Some(_) => AuthenticatorAttachment::CrossPlatform,
371 None => AuthenticatorAttachment::Unknown,
372 };
373
374 // Handle extensions whose outputs are not encoded in the authenticator data.
375 // 1. appId
376 if let Some(app_id) = &self.extensions.app_id {
377 result.extensions.app_id =
378 Some(result.assertion.auth_data.rp_id_hash == RelyingParty::from(app_id).hash());
379 }
380
381 // 2. prf
382 // If the prf extension was requested and hmac-secret returned secrets,
383 // we need to decrypt and output them as prf client outputs.
384 match self.extensions.hmac_secret {
385 Some(HmacGetSecretOrPrf::HmacGetSecret(_)) => {
386 result.extensions.hmac_get_secret =
387 if let Some(hmac_response @ HmacSecretResponse::Secret(_)) =
388 &result.assertion.auth_data.extensions.hmac_secret
389 {
390 dev.get_shared_secret()
391 .and_then(|shared_secret| hmac_response.decrypt_secrets(shared_secret))
392 .and_then(|result| match result {
393 Ok(ok) => Some(ok),
394 Err(err) => {
395 debug!("Failed to decrypt hmac-secret response: {:?}", err);
396 None
397 }
398 })
399 } else {
400 None
401 };
402 }
403 Some(HmacGetSecretOrPrf::PrfUninitialized(_)) => {
404 unreachable!("Reached GetAssertion.finalize_result without replacing PrfUninitialized instance with Prf")
405 }
406 Some(HmacGetSecretOrPrf::PrfUnmatched) => {
407 result.extensions.prf = Some(AuthenticationExtensionsPRFOutputs {
408 enabled: None,
409 results: None,
410 });
411 }
412 Some(HmacGetSecretOrPrf::Prf(_)) => {
413 result.extensions.prf = Some(AuthenticationExtensionsPRFOutputs {
414 enabled: None,
415 results: if let Some(hmac_response @ HmacSecretResponse::Secret(_)) =
416 &result.assertion.auth_data.extensions.hmac_secret
417 {
418 dev.get_shared_secret()
419 .and_then(|shared_secret| hmac_response.decrypt_secrets(shared_secret))
420 .and_then(|result| match result {
421 Ok(ok) => Some(ok),
422 Err(err) => {
423 debug!("Failed to decrypt hmac-secret response: {:?}", err);
424 None
425 }
426 })
427 .map(|outputs| outputs.into())
428 } else {
429 None
430 },
431 });
432 }
433 None => {}
434 }
435 }
436 }
437
438 impl PinUvAuthCommand for GetAssertion {
439 fn set_pin_uv_auth_param(
440 &mut self,
441 pin_uv_auth_token: Option<PinUvAuthToken>,
442 ) -> Result<(), AuthenticatorError> {
443 let mut param = None;
444 if let Some(token) = pin_uv_auth_token {
445 param = Some(
446 token
447 .derive(self.client_data_hash.as_ref())
448 .map_err(CommandError::Crypto)?,
449 );
450 }
451 self.pin_uv_auth_param = param;
452 Ok(())
453 }
454
455 fn set_uv_option(&mut self, uv: Option<bool>) {
456 self.options.user_verification = uv;
457 }
458
459 fn get_rp_id(&self) -> Option<&String> {
460 Some(&self.rp.id)
461 }
462
463 fn can_skip_user_verification(
464 &mut self,
465 info: &AuthenticatorInfo,
466 uv_req: UserVerificationRequirement,
467 ) -> bool {
468 let supports_uv = info.options.user_verification == Some(true);
469 let pin_configured = info.options.client_pin == Some(true);
470 let device_protected = supports_uv || pin_configured;
471 let uv_discouraged = uv_req == UserVerificationRequirement::Discouraged;
472 let always_uv = info.options.always_uv == Some(true);
473
474 !always_uv && (!device_protected || uv_discouraged)
475 }
476
477 fn get_pin_uv_auth_param(&self) -> Option<&PinUvAuthParam> {
478 self.pin_uv_auth_param.as_ref()
479 }
480 }
481
482 impl Serialize for GetAssertion {
483 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
484 where
485 S: Serializer,
486 {
487 serialize_map_optional! {
488 serializer,
489 &1 => Some(&self.rp.id),
490 &2 => Some(&self.client_data_hash),
491 &3 => (!&self.allow_list.is_empty()).then_some(&self.allow_list),
492 &4 => self.extensions.has_content().then_some(&self.extensions),
493 &5 => self.options.has_some().then_some(&self.options),
494 &6 => &self.pin_uv_auth_param,
495 &7 => self.pin_uv_auth_param.as_ref().map(|p| p.pin_protocol.id()),
496 }
497 }
498 }
499
500 type GetAssertionOutput = Vec<GetAssertionResult>;
501 impl CtapResponse for GetAssertionOutput {}
502
503 impl RequestCtap1 for GetAssertion {
504 type Output = Vec<GetAssertionResult>;
505 type AdditionalInfo = PublicKeyCredentialDescriptor;
506
507 fn ctap1_format(&self) -> Result<(Vec<u8>, Self::AdditionalInfo), HIDError> {
508 // Pre-flighting should reduce the list to exactly one entry
509 let key_handle = match &self.allow_list[..] {
510 [key_handle] => key_handle,
511 [] => {
512 return Err(HIDError::Command(CommandError::StatusCode(
513 StatusCode::NoCredentials,
514 None,
515 )));
516 }
517 _ => {
518 return Err(HIDError::UnsupportedCommand);
519 }
520 };
521
522 debug!("sending key_handle = {:?}", key_handle);
523
524 let flags = if self.options.user_presence.unwrap_or(true) {
525 U2F_REQUEST_USER_PRESENCE
526 } else {
527 U2F_DONT_ENFORCE_USER_PRESENCE_AND_SIGN
528 };
529 let mut auth_data =
530 Vec::with_capacity(2 * PARAMETER_SIZE + 1 /* key_handle_len */ + key_handle.id.len());
531
532 auth_data.extend_from_slice(self.client_data_hash.as_ref());
533 auth_data.extend_from_slice(self.rp.hash().as_ref());
534 auth_data.extend_from_slice(&[key_handle.id.len() as u8]);
535 auth_data.extend_from_slice(key_handle.id.as_ref());
536
537 let cmd = U2F_AUTHENTICATE;
538 let apdu = CTAP1RequestAPDU::serialize(cmd, flags, &auth_data)?;
539 Ok((apdu, key_handle.clone()))
540 }
541
542 fn handle_response_ctap1<Dev: FidoDevice>(
543 &self,
544 dev: &mut Dev,
545 status: Result<(), ApduErrorStatus>,
546 input: &[u8],
547 add_info: &PublicKeyCredentialDescriptor,
548 ) -> Result<Self::Output, Retryable<HIDError>> {
549 if Err(ApduErrorStatus::ConditionsNotSatisfied) == status {
550 return Err(Retryable::Retry);
551 }
552 if let Err(err) = status {
553 return Err(Retryable::Error(HIDError::ApduStatus(err)));
554 }
555
556 let mut result = GetAssertionResult::from_ctap1(input, &self.rp.hash(), add_info)
557 .map_err(|e| Retryable::Error(HIDError::Command(e)))?;
558 self.finalize_result(dev, &mut result);
559 // Although there's only one result, we return a vector for consistency with CTAP2.
560 Ok(vec![result])
561 }
562
563 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
564 &self,
565 dev: &mut Dev,
566 ) -> Result<Self::Output, HIDError> {
567 let mut results = dev.get_assertion(self)?;
568 for result in results.iter_mut() {
569 self.finalize_result(dev, result);
570 }
571 Ok(results)
572 }
573 }
574
575 impl RequestCtap2 for GetAssertion {
576 type Output = Vec<GetAssertionResult>;
577
578 fn command(&self) -> Command {
579 Command::GetAssertion
580 }
581
582 fn wire_format(&self) -> Result<Vec<u8>, HIDError> {
583 Ok(ser::to_vec(&self).map_err(CommandError::Serializing)?)
584 }
585
586 fn handle_response_ctap2<Dev: FidoDevice>(
587 &self,
588 dev: &mut Dev,
589 input: &[u8],
590 ) -> Result<Self::Output, HIDError> {
591 if input.is_empty() {
592 return Err(CommandError::InputTooSmall.into());
593 }
594
595 let status: StatusCode = input[0].into();
596 debug!(
597 "response status code: {:?}, rest: {:?}",
598 status,
599 &input[1..]
600 );
601 if input.len() == 1 {
602 if status.is_ok() {
603 return Err(CommandError::InputTooSmall.into());
604 }
605 return Err(CommandError::StatusCode(status, None).into());
606 }
607
608 if status.is_ok() {
609 let assertion: GetAssertionResponse =
610 from_slice(&input[1..]).map_err(CommandError::Deserializing)?;
611 let number_of_credentials = assertion.number_of_credentials.unwrap_or(1);
612
613 let mut results = Vec::with_capacity(number_of_credentials);
614 results.push(GetAssertionResult {
615 assertion: assertion.into(),
616 attachment: AuthenticatorAttachment::Unknown,
617 extensions: Default::default(),
618 });
619
620 let msg = GetNextAssertion;
621 // We already have one, so skipping 0
622 for _ in 1..number_of_credentials {
623 let assertion = dev.send_cbor(&msg)?;
624 results.push(GetAssertionResult {
625 assertion: assertion.into(),
626 attachment: AuthenticatorAttachment::Unknown,
627 extensions: Default::default(),
628 });
629 }
630
631 for result in results.iter_mut() {
632 self.finalize_result(dev, result);
633 }
634 Ok(results)
635 } else {
636 let data: Value = from_slice(&input[1..]).map_err(CommandError::Deserializing)?;
637 Err(CommandError::StatusCode(status, Some(data)).into())
638 }
639 }
640
641 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
642 &self,
643 dev: &mut Dev,
644 ) -> Result<Self::Output, HIDError> {
645 let mut results = dev.get_assertion(self)?;
646 for result in results.iter_mut() {
647 self.finalize_result(dev, result);
648 }
649 Ok(results)
650 }
651 }
652
653 #[derive(Debug, PartialEq, Eq)]
654 pub struct Assertion {
655 pub credentials: Option<PublicKeyCredentialDescriptor>, /* Was optional in CTAP2.0, is
656 * mandatory in CTAP2.1 */
657 pub auth_data: AuthenticatorData,
658 pub signature: Vec<u8>,
659 pub user: Option<PublicKeyCredentialUserEntity>,
660 }
661
662 impl From<GetAssertionResponse> for Assertion {
663 fn from(r: GetAssertionResponse) -> Self {
664 Assertion {
665 credentials: r.credentials,
666 auth_data: r.auth_data,
667 signature: r.signature,
668 user: r.user,
669 }
670 }
671 }
672
673 #[derive(Debug, PartialEq, Eq)]
674 pub struct GetAssertionResult {
675 pub assertion: Assertion,
676 pub attachment: AuthenticatorAttachment,
677 pub extensions: AuthenticationExtensionsClientOutputs,
678 }
679
680 impl GetAssertionResult {
681 pub fn from_ctap1(
682 input: &[u8],
683 rp_id_hash: &RpIdHash,
684 key_handle: &PublicKeyCredentialDescriptor,
685 ) -> Result<GetAssertionResult, CommandError> {
686 let mut data = Cursor::new(input);
687 let user_presence = read_byte(&mut data).map_err(CommandError::Deserializing)?;
688 let counter = read_be_u32(&mut data).map_err(CommandError::Deserializing)?;
689 // Remaining data is signature (Note: `data.remaining_slice()` is not yet stabilized)
690 let signature = Vec::from(&data.get_ref()[data.position() as usize..]);
691
692 // Step 5 of Section 10.3 of CTAP2.1: "Copy bits 0 (the UP bit) and bit 1 from the
693 // CTAP2/U2F response user presence byte to bits 0 and 1 of the CTAP2 flags, respectively.
694 // Set all other bits of flags to zero."
695 let flag_mask = AuthenticatorDataFlags::USER_PRESENT | AuthenticatorDataFlags::RESERVED_1;
696 let flags = flag_mask & AuthenticatorDataFlags::from_bits_truncate(user_presence);
697 let auth_data = AuthenticatorData {
698 rp_id_hash: rp_id_hash.clone(),
699 flags,
700 counter,
701 credential_data: None,
702 extensions: Default::default(),
703 };
704 let assertion = Assertion {
705 credentials: Some(key_handle.clone()),
706 signature,
707 user: None,
708 auth_data,
709 };
710
711 Ok(GetAssertionResult {
712 assertion,
713 attachment: AuthenticatorAttachment::Unknown,
714 extensions: Default::default(),
715 })
716 }
717 }
718
719 #[derive(Debug, PartialEq)]
720 pub struct GetAssertionResponse {
721 pub credentials: Option<PublicKeyCredentialDescriptor>,
722 pub auth_data: AuthenticatorData,
723 pub signature: Vec<u8>,
724 pub user: Option<PublicKeyCredentialUserEntity>,
725 pub number_of_credentials: Option<usize>,
726 }
727
728 impl CtapResponse for GetAssertionResponse {}
729
730 impl<'de> Deserialize<'de> for GetAssertionResponse {
731 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
732 where
733 D: Deserializer<'de>,
734 {
735 struct GetAssertionResponseVisitor;
736
737 impl<'de> Visitor<'de> for GetAssertionResponseVisitor {
738 type Value = GetAssertionResponse;
739
740 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
741 formatter.write_str("a byte array")
742 }
743
744 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
745 where
746 M: MapAccess<'de>,
747 {
748 let mut credentials = None;
749 let mut auth_data = None;
750 let mut signature = None;
751 let mut user = None;
752 let mut number_of_credentials = None;
753
754 while let Some(key) = map.next_key()? {
755 match key {
756 1 => {
757 if credentials.is_some() {
758 return Err(M::Error::duplicate_field("credentials"));
759 }
760 credentials = Some(map.next_value()?);
761 }
762 2 => {
763 if auth_data.is_some() {
764 return Err(M::Error::duplicate_field("auth_data"));
765 }
766 auth_data = Some(map.next_value()?);
767 }
768 3 => {
769 if signature.is_some() {
770 return Err(M::Error::duplicate_field("signature"));
771 }
772 let signature_bytes: ByteBuf = map.next_value()?;
773 let signature_bytes: Vec<u8> = signature_bytes.into_vec();
774 signature = Some(signature_bytes);
775 }
776 4 => {
777 if user.is_some() {
778 return Err(M::Error::duplicate_field("user"));
779 }
780 user = map.next_value()?;
781 }
782 5 => {
783 if number_of_credentials.is_some() {
784 return Err(M::Error::duplicate_field("number_of_credentials"));
785 }
786 number_of_credentials = Some(map.next_value()?);
787 }
788 k => return Err(M::Error::custom(format!("unexpected key: {k:?}"))),
789 }
790 }
791
792 let auth_data = auth_data.ok_or_else(|| M::Error::missing_field("auth_data"))?;
793 let signature = signature.ok_or_else(|| M::Error::missing_field("signature"))?;
794
795 Ok(GetAssertionResponse {
796 credentials,
797 auth_data,
798 signature,
799 user,
800 number_of_credentials,
801 })
802 }
803 }
804
805 deserializer.deserialize_bytes(GetAssertionResponseVisitor)
806 }
807 }
808
809 #[cfg(test)]
810 pub mod test {
811
812 use super::{
813 Assertion, CommandError, GetAssertion, GetAssertionOptions, GetAssertionResult, HIDError,
814 StatusCode,
815 };
816 use crate::consts::{
817 Capability, HIDCmd, SW_CONDITIONS_NOT_SATISFIED, SW_NO_ERROR, U2F_CHECK_IS_REGISTERED,
818 U2F_REQUEST_USER_PRESENCE,
819 };
820 use crate::crypto::{COSEAlgorithm, COSEEC2Key, COSEKey, COSEKeyType, Curve, PinUvAuthParam};
821 use crate::ctap2::attestation::{AAGuid, AuthenticatorData, AuthenticatorDataFlags};
822 use crate::ctap2::client_data::{
823 Challenge, ClientDataHash, CollectedClientData, TokenBinding, WebauthnType,
824 };
825 use crate::ctap2::commands::client_pin::PinUvAuthTokenPermission;
826 use crate::ctap2::commands::get_assertion::{
827 CalculatedHmacSecretExtension, GetAssertionExtensions, HmacGetSecretOrPrf,
828 HmacSecretExtension,
829 };
830 use crate::ctap2::commands::get_info::tests::AAGUID_RAW;
831 use crate::ctap2::commands::get_info::{
832 AuthenticatorInfo, AuthenticatorOptions, AuthenticatorVersion,
833 };
834 use crate::ctap2::commands::{RequestCtap1, RequestCtap2};
835 use crate::ctap2::preflight::{
836 do_credential_list_filtering_ctap1, do_credential_list_filtering_ctap2,
837 };
838 use crate::ctap2::server::{
839 AuthenticationExtensionsPRFInputs, AuthenticatorAttachment, PublicKeyCredentialDescriptor,
840 PublicKeyCredentialUserEntity, RelyingParty, RpIdHash, Transport,
841 };
842 use crate::transport::device_selector::Device;
843 use crate::transport::hid::HIDDevice;
844 use crate::transport::{FidoDevice, FidoDeviceIO, FidoProtocol};
845 use crate::u2ftypes::U2FDeviceInfo;
846 use rand::{thread_rng, RngCore};
847
848 #[test]
849 fn test_get_assertion_ctap2() {
850 let client_data = CollectedClientData {
851 webauthn_type: WebauthnType::Create,
852 challenge: Challenge::from(vec![0x00, 0x01, 0x02, 0x03]),
853 origin: String::from("example.com"),
854 cross_origin: false,
855 token_binding: Some(TokenBinding::Present(String::from("AAECAw"))),
856 };
857 let assertion = GetAssertion::new(
858 client_data.hash().expect("failed to serialize client data"),
859 RelyingParty::from("example.com"),
860 vec![PublicKeyCredentialDescriptor {
861 id: vec![
862 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35,
863 0xEF, 0xAA, 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D,
864 0xA4, 0x85, 0x34, 0xC8, 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5,
865 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD, 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5,
866 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08, 0xFE, 0x42, 0x00, 0x38,
867 ],
868 transports: vec![Transport::USB],
869 }],
870 GetAssertionOptions {
871 user_presence: Some(true),
872 user_verification: None,
873 },
874 Default::default(),
875 );
876 let mut device = Device::new("commands/get_assertion").unwrap();
877 assert_eq!(device.get_protocol(), FidoProtocol::CTAP2);
878 let mut cid = [0u8; 4];
879 thread_rng().fill_bytes(&mut cid);
880 device.set_cid(cid);
881
882 let mut msg = cid.to_vec();
883 msg.extend(vec![HIDCmd::Cbor.into(), 0x00, 0x90]);
884 msg.extend(vec![0x2]); // u2f command
885 msg.extend(vec![
886 0xa4, // map(4)
887 0x1, // rpid
888 0x6b, // text(11)
889 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, // example.com
890 0x2, // clientDataHash
891 0x58, 0x20, //bytes(32)
892 0x75, 0x35, 0x35, 0x7d, 0x49, 0x6e, 0x33, 0xc8, 0x18, 0x7f, 0xea, 0x8d, 0x11, 0x32,
893 0x64, 0xaa, 0xa4, 0x52, 0x3e, 0x13, 0x40, 0x14, 0x9f, 0xbe, 0x00, 0x3f, 0x10, 0x87,
894 0x54, 0xc3, 0x2d, 0x80, // hash
895 0x3, //allowList
896 0x81, // array(1)
897 0xa2, // map(2)
898 0x62, // text(2)
899 0x69, 0x64, // id
900 0x58, // bytes(
901 ]);
902 device.add_write(&msg, 0);
903
904 msg = cid.to_vec();
905 msg.extend([0x0]); //SEQ
906 msg.extend([0x40]); // 64)
907 msg.extend(&assertion.allow_list[0].id[..58]);
908 device.add_write(&msg, 0);
909
910 msg = cid.to_vec();
911 msg.extend([0x1]); //SEQ
912 msg.extend(&assertion.allow_list[0].id[58..64]);
913 msg.extend(vec![
914 0x64, // text(4),
915 0x74, 0x79, 0x70, 0x65, // type
916 0x6a, // text(10)
917 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x2D, 0x6B, 0x65, 0x79, // public-key
918 0x5, // options
919 0xa1, // map(1)
920 0x62, // text(2)
921 0x75, 0x70, // up
922 0xf5, // true
923 ]);
924 device.add_write(&msg, 0);
925
926 // fido response
927 let mut msg = cid.to_vec();
928 msg.extend([HIDCmd::Cbor.into(), 0x1, 0x2a]); // cmd + bcnt
929 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[..57]);
930 device.add_read(&msg, 0);
931
932 let mut msg = cid.to_vec();
933 msg.extend([0x0]); // SEQ
934 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[57..116]);
935 device.add_read(&msg, 0);
936
937 let mut msg = cid.to_vec();
938 msg.extend([0x1]); // SEQ
939 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[116..175]);
940 device.add_read(&msg, 0);
941
942 let mut msg = cid.to_vec();
943 msg.extend([0x2]); // SEQ
944 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[175..234]);
945 device.add_read(&msg, 0);
946
947 let mut msg = cid.to_vec();
948 msg.extend([0x3]); // SEQ
949 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[234..293]);
950 device.add_read(&msg, 0);
951 let mut msg = cid.to_vec();
952 msg.extend([0x4]); // SEQ
953 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[293..]);
954 device.add_read(&msg, 0);
955
956 // Check if response is correct
957 let expected_auth_data = AuthenticatorData {
958 rp_id_hash: RpIdHash([
959 0x62, 0x5d, 0xda, 0xdf, 0x74, 0x3f, 0x57, 0x27, 0xe6, 0x6b, 0xba, 0x8c, 0x2e, 0x38,
960 0x79, 0x22, 0xd1, 0xaf, 0x43, 0xc5, 0x03, 0xd9, 0x11, 0x4a, 0x8f, 0xba, 0x10, 0x4d,
961 0x84, 0xd0, 0x2b, 0xfa,
962 ]),
963 flags: AuthenticatorDataFlags::USER_PRESENT,
964 counter: 0x11,
965 credential_data: None,
966 extensions: Default::default(),
967 };
968
969 let expected_assertion = Assertion {
970 credentials: Some(PublicKeyCredentialDescriptor {
971 id: vec![
972 242, 32, 6, 222, 79, 144, 90, 246, 138, 67, 148, 47, 2, 79, 42, 94, 206, 96,
973 61, 156, 109, 75, 61, 248, 190, 8, 237, 1, 252, 68, 38, 70, 208, 52, 133, 138,
974 199, 91, 237, 63, 213, 128, 191, 152, 8, 217, 79, 203, 238, 130, 185, 178, 239,
975 102, 119, 175, 10, 220, 195, 88, 82, 234, 107, 158,
976 ],
977 transports: vec![],
978 }),
979 signature: vec![
980 0x30, 0x45, 0x02, 0x20, 0x4a, 0x5a, 0x9d, 0xd3, 0x92, 0x98, 0x14, 0x9d, 0x90, 0x47,
981 0x69, 0xb5, 0x1a, 0x45, 0x14, 0x33, 0x00, 0x6f, 0x18, 0x2a, 0x34, 0xfb, 0xdf, 0x66,
982 0xde, 0x5f, 0xc7, 0x17, 0xd7, 0x5f, 0xb3, 0x50, 0x02, 0x21, 0x00, 0xa4, 0x6b, 0x8e,
983 0xa3, 0xc3, 0xb9, 0x33, 0x82, 0x1c, 0x6e, 0x7f, 0x5e, 0xf9, 0xda, 0xae, 0x94, 0xab,
984 0x47, 0xf1, 0x8d, 0xb4, 0x74, 0xc7, 0x47, 0x90, 0xea, 0xab, 0xb1, 0x44, 0x11, 0xe7,
985 0xa0,
986 ],
987 user: Some(PublicKeyCredentialUserEntity {
988 id: vec![
989 0x30, 0x82, 0x01, 0x93, 0x30, 0x82, 0x01, 0x38, 0xa0, 0x03, 0x02, 0x01, 0x02,
990 0x30, 0x82, 0x01, 0x93, 0x30, 0x82, 0x01, 0x38, 0xa0, 0x03, 0x02, 0x01, 0x02,
991 0x30, 0x82, 0x01, 0x93, 0x30, 0x82,
992 ],
993 name: Some("[email protected]".to_string()),
994 display_name: Some("John P. Smith".to_string()),
995 }),
996 auth_data: expected_auth_data,
997 };
998
999 let expected = vec![GetAssertionResult {
1000 assertion: expected_assertion,
1001 attachment: AuthenticatorAttachment::Unknown,
1002 extensions: Default::default(),
1003 }];
1004 let response = device.send_cbor(&assertion).unwrap();
1005 assert_eq!(response, expected);
1006 }
1007
1008 #[test]
1009 fn test_serialize_get_assertion_ctap2() {
1010 let client_data = CollectedClientData {
1011 webauthn_type: WebauthnType::Create,
1012 challenge: Challenge::from(vec![0x00, 0x01, 0x02, 0x03]),
1013 origin: String::from("example.com"),
1014 cross_origin: false,
1015 token_binding: Some(TokenBinding::Present(String::from("AAECAw"))),
1016 };
1017 let assertion = GetAssertion {
1018 client_data_hash: client_data.hash().expect("failed to serialize client data"),
1019 rp: RelyingParty::from("example.com"),
1020 allow_list: vec![PublicKeyCredentialDescriptor {
1021 id: vec![
1022 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35,
1023 0xEF, 0xAA, 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D,
1024 0xA4, 0x85, 0x34, 0xC8, 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5,
1025 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD, 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5,
1026 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08, 0xFE, 0x42, 0x00, 0x38,
1027 ],
1028 transports: vec![Transport::USB],
1029 }],
1030 extensions: GetAssertionExtensions {
1031 app_id: Some("https://example.com".to_string()),
1032 hmac_secret: Some(HmacGetSecretOrPrf::HmacGetSecret(
1033 HmacSecretExtension::new_test(
1034 vec![32; 32],
1035 None,
1036 CalculatedHmacSecretExtension {
1037 public_key: COSEKey {
1038 alg: COSEAlgorithm::ECDH_ES_HKDF256,
1039 key: COSEKeyType::EC2(COSEEC2Key {
1040 curve: Curve::SECP256R1,
1041 x: vec![],
1042 y: vec![],
1043 }),
1044 },
1045 salt_enc: vec![7; 32],
1046 salt_auth: vec![8; 16],
1047 },
1048 None,
1049 ),
1050 )),
1051 },
1052 options: GetAssertionOptions {
1053 user_presence: Some(true),
1054 user_verification: None,
1055 },
1056 pin_uv_auth_param: Some(PinUvAuthParam::create_empty()),
1057 };
1058 let req_serialized = assertion
1059 .wire_format()
1060 .expect("Failed to serialize GetAssertion request");
1061 assert_eq!(
1062 req_serialized,
1063 [
1064 // Value copied from test failure output as regression test snapshot
1065 167, 1, 107, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 2, 88, 32, 117, 53,
1066 53, 125, 73, 110, 51, 200, 24, 127, 234, 141, 17, 50, 100, 170, 164, 82, 62, 19,
1067 64, 20, 159, 190, 0, 63, 16, 135, 84, 195, 45, 128, 3, 129, 162, 98, 105, 100, 88,
1068 64, 62, 189, 137, 191, 119, 236, 80, 151, 85, 238, 156, 38, 53, 239, 170, 172, 123,
1069 43, 156, 92, 239, 23, 54, 195, 113, 125, 164, 133, 52, 200, 198, 182, 84, 215, 255,
1070 148, 95, 80, 181, 204, 78, 120, 5, 91, 221, 57, 107, 100, 247, 141, 162, 197, 249,
1071 98, 0, 204, 212, 21, 205, 8, 254, 66, 0, 56, 100, 116, 121, 112, 101, 106, 112,
1072 117, 98, 108, 105, 99, 45, 107, 101, 121, 4, 161, 107, 104, 109, 97, 99, 45, 115,
1073 101, 99, 114, 101, 116, 163, 1, 165, 1, 2, 3, 56, 24, 32, 1, 33, 64, 34, 64, 2, 88,
1074 32, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1075 7, 7, 7, 7, 7, 7, 3, 80, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 161,
1076 98, 117, 112, 245, 6, 64, 7, 1
1077 ]
1078 );
1079 }
1080
1081 #[test]
1082 fn test_serialize_get_assertion_ctap2_pin_protocol_2() {
1083 let assertion = GetAssertion {
1084 client_data_hash: ClientDataHash([0; 32]),
1085 rp: RelyingParty::from("example.com"),
1086 allow_list: vec![],
1087 extensions: GetAssertionExtensions {
1088 app_id: None,
1089 hmac_secret: Some(HmacGetSecretOrPrf::HmacGetSecret(
1090 HmacSecretExtension::new_test(
1091 vec![32; 32],
1092 None,
1093 CalculatedHmacSecretExtension {
1094 public_key: COSEKey {
1095 alg: COSEAlgorithm::ECDH_ES_HKDF256,
1096 key: COSEKeyType::EC2(COSEEC2Key {
1097 curve: Curve::SECP256R1,
1098 x: vec![],
1099 y: vec![],
1100 }),
1101 },
1102 salt_enc: vec![7; 32],
1103 salt_auth: vec![8; 16],
1104 },
1105 Some(2),
1106 ),
1107 )),
1108 },
1109 options: GetAssertionOptions {
1110 user_presence: None,
1111 user_verification: None,
1112 },
1113 pin_uv_auth_param: Some(PinUvAuthParam::create_test(
1114 2,
1115 vec![9; 4],
1116 PinUvAuthTokenPermission::GetAssertion,
1117 )),
1118 };
1119 let req_serialized = assertion
1120 .wire_format()
1121 .expect("Failed to serialize GetAssertion request");
1122 assert_eq!(
1123 req_serialized,
1124 [
1125 // Value copied from test failure output as regression test snapshot
1126 165, 1, 107, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 2, 88, 32, 0, 0, 0,
1127 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1128 0, 4, 161, 107, 104, 109, 97, 99, 45, 115, 101, 99, 114, 101, 116, 164, 1, 165, 1,
1129 2, 3, 56, 24, 32, 1, 33, 64, 34, 64, 2, 88, 32, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1130 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 3, 80, 8, 8, 8, 8, 8,
1131 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 2, 6, 68, 9, 9, 9, 9, 7, 2
1132 ]
1133 );
1134 }
1135
1136 #[test]
1137 #[should_panic(
1138 expected = "PrfUninitialized must be replaced with Prf or PrfUnmatched before serializing"
1139 )]
1140 fn test_serialize_prf_uninitialized() {
1141 let assertion = GetAssertion {
1142 client_data_hash: ClientDataHash([0; 32]),
1143 rp: RelyingParty::from("example.com"),
1144 allow_list: vec![],
1145 extensions: GetAssertionExtensions {
1146 app_id: None,
1147 hmac_secret: Some(HmacGetSecretOrPrf::PrfUninitialized(
1148 AuthenticationExtensionsPRFInputs {
1149 eval: None,
1150 eval_by_credential: None,
1151 },
1152 )),
1153 },
1154 options: GetAssertionOptions {
1155 user_presence: None,
1156 user_verification: None,
1157 },
1158 pin_uv_auth_param: None,
1159 };
1160 assertion
1161 .wire_format()
1162 .expect("Failed to serialize GetAssertion request");
1163 }
1164
1165 #[test]
1166 fn test_serialize_prf_unmatched() {
1167 let assertion = GetAssertion {
1168 client_data_hash: ClientDataHash([0; 32]),
1169 rp: RelyingParty::from("example.com"),
1170 allow_list: vec![],
1171 extensions: GetAssertionExtensions {
1172 app_id: None,
1173 hmac_secret: Some(HmacGetSecretOrPrf::PrfUnmatched),
1174 },
1175 options: GetAssertionOptions {
1176 user_presence: None,
1177 user_verification: None,
1178 },
1179 pin_uv_auth_param: None,
1180 };
1181 let req_serialized = assertion
1182 .wire_format()
1183 .expect("Failed to serialize GetAssertion request");
1184 assert_eq!(
1185 req_serialized,
1186 [
1187 // Value copied from test failure output as regression test snapshot
1188 163, 1, 107, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 2, 88, 32, 0, 0, 0,
1189 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1190 0, 4, 160
1191 ]
1192 );
1193 }
1194
1195 fn fill_device_ctap1(device: &mut Device, cid: [u8; 4], flags: u8, answer_status: [u8; 2]) {
1196 // ctap2 request
1197 let mut msg = cid.to_vec();
1198 msg.extend([HIDCmd::Msg.into(), 0x00, 0x8A]); // cmd + bcnt
1199 msg.extend([0x00, 0x2]); // U2F_AUTHENTICATE
1200 msg.extend([flags]);
1201 msg.extend([0x00, 0x00, 0x00]);
1202 msg.extend([0x81]); // Data len - 7
1203 msg.extend(CLIENT_DATA_HASH);
1204 msg.extend(&RELYING_PARTY_HASH[..18]);
1205 device.add_write(&msg, 0);
1206
1207 // Continuation package
1208 let mut msg = cid.to_vec();
1209 msg.extend(vec![0x00]); // SEQ
1210 msg.extend(&RELYING_PARTY_HASH[18..]);
1211 msg.extend([KEY_HANDLE.len() as u8]);
1212 msg.extend(&KEY_HANDLE[..44]);
1213 device.add_write(&msg, 0);
1214
1215 let mut msg = cid.to_vec();
1216 msg.extend(vec![0x01]); // SEQ
1217 msg.extend(&KEY_HANDLE[44..]);
1218 device.add_write(&msg, 0);
1219
1220 // fido response
1221 let mut msg = cid.to_vec();
1222 msg.extend([HIDCmd::Msg.into(), 0x0, 0x4D]); // cmd + bcnt
1223 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP1[0..57]);
1224 device.add_read(&msg, 0);
1225
1226 let mut msg = cid.to_vec();
1227 msg.extend([0x0]); // SEQ
1228 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP1[57..]);
1229 msg.extend(answer_status);
1230 device.add_read(&msg, 0);
1231 }
1232
1233 #[test]
1234 fn test_get_assertion_ctap1() {
1235 let client_data = CollectedClientData {
1236 webauthn_type: WebauthnType::Create,
1237 challenge: Challenge::from(vec![0x00, 0x01, 0x02, 0x03]),
1238 origin: String::from("example.com"),
1239 cross_origin: false,
1240 token_binding: Some(TokenBinding::Present(String::from("AAECAw"))),
1241 };
1242 let allowed_key = PublicKeyCredentialDescriptor {
1243 id: vec![
1244 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35, 0xEF,
1245 0xAA, 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D, 0xA4, 0x85,
1246 0x34, 0xC8, 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78,
1247 0x05, 0x5B, 0xDD, 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC,
1248 0xD4, 0x15, 0xCD, 0x08, 0xFE, 0x42, 0x00, 0x38,
1249 ],
1250 transports: vec![Transport::USB],
1251 };
1252 let mut assertion = GetAssertion::new(
1253 client_data.hash().expect("failed to serialize client data"),
1254 RelyingParty::from("example.com"),
1255 vec![allowed_key.clone()],
1256 GetAssertionOptions {
1257 user_presence: Some(true),
1258 user_verification: None,
1259 },
1260 Default::default(),
1261 );
1262 let mut device = Device::new("commands/get_assertion").unwrap(); // not really used (all functions ignore it)
1263 // channel id
1264 device.downgrade_to_ctap1();
1265 assert_eq!(device.get_protocol(), FidoProtocol::CTAP1);
1266 let mut cid = [0u8; 4];
1267 thread_rng().fill_bytes(&mut cid);
1268
1269 device.set_cid(cid);
1270
1271 // ctap1 request
1272 fill_device_ctap1(
1273 &mut device,
1274 cid,
1275 U2F_CHECK_IS_REGISTERED,
1276 SW_CONDITIONS_NOT_SATISFIED,
1277 );
1278 let key_handle = do_credential_list_filtering_ctap1(
1279 &mut device,
1280 &assertion.allow_list,
1281 &assertion.rp,
1282 &assertion.client_data_hash,
1283 )
1284 .expect("Did not find a key_handle, even though it should have");
1285 assertion.allow_list = vec![key_handle];
1286 let (ctap1_request, key_handle) = assertion.ctap1_format().unwrap();
1287 assert_eq!(key_handle, allowed_key);
1288 // Check if the request is going to be correct
1289 assert_eq!(ctap1_request, GET_ASSERTION_SAMPLE_REQUEST_CTAP1);
1290
1291 // Now do it again, but parse the actual response
1292 // Pre-flighting is not done automatically
1293 fill_device_ctap1(&mut device, cid, U2F_REQUEST_USER_PRESENCE, SW_NO_ERROR);
1294
1295 let response = device.send_ctap1(&assertion).unwrap();
1296
1297 // Check if response is correct
1298 let expected_auth_data = AuthenticatorData {
1299 rp_id_hash: RpIdHash(RELYING_PARTY_HASH),
1300 flags: AuthenticatorDataFlags::USER_PRESENT,
1301 counter: 0x3B,
1302 credential_data: None,
1303 extensions: Default::default(),
1304 };
1305
1306 let expected_assertion = Assertion {
1307 credentials: Some(allowed_key),
1308 signature: vec![
1309 0x30, 0x44, 0x02, 0x20, 0x7B, 0xDE, 0x0A, 0x52, 0xAC, 0x1F, 0x4C, 0x8B, 0x27, 0xE0,
1310 0x03, 0xA3, 0x70, 0xCD, 0x66, 0xA4, 0xC7, 0x11, 0x8D, 0xD2, 0x2D, 0x54, 0x47, 0x83,
1311 0x5F, 0x45, 0xB9, 0x9C, 0x68, 0x42, 0x3F, 0xF7, 0x02, 0x20, 0x3C, 0x51, 0x7B, 0x47,
1312 0x87, 0x7F, 0x85, 0x78, 0x2D, 0xE1, 0x00, 0x86, 0xA7, 0x83, 0xD1, 0xE7, 0xDF, 0x4E,
1313 0x36, 0x39, 0xE7, 0x71, 0xF5, 0xF6, 0xAF, 0xA3, 0x5A, 0xAD, 0x53, 0x73, 0x85, 0x8E,
1314 ],
1315 user: None,
1316 auth_data: expected_auth_data,
1317 };
1318
1319 let expected = vec![GetAssertionResult {
1320 assertion: expected_assertion,
1321 attachment: AuthenticatorAttachment::Unknown,
1322 extensions: Default::default(),
1323 }];
1324 assert_eq!(response, expected);
1325 }
1326
1327 #[test]
1328 fn test_get_assertion_ctap1_long_keys() {
1329 let client_data = CollectedClientData {
1330 webauthn_type: WebauthnType::Create,
1331 challenge: Challenge::from(vec![0x00, 0x01, 0x02, 0x03]),
1332 origin: String::from("example.com"),
1333 cross_origin: false,
1334 token_binding: Some(TokenBinding::Present(String::from("AAECAw"))),
1335 };
1336
1337 let too_long_key_handle = PublicKeyCredentialDescriptor {
1338 id: vec![0; 1000],
1339 transports: vec![Transport::USB],
1340 };
1341 let mut assertion = GetAssertion::new(
1342 client_data.hash().expect("failed to serialize client data"),
1343 RelyingParty::from("example.com"),
1344 vec![too_long_key_handle.clone()],
1345 GetAssertionOptions {
1346 user_presence: Some(true),
1347 user_verification: None,
1348 },
1349 Default::default(),
1350 );
1351
1352 let mut device = Device::new("commands/get_assertion").unwrap(); // not really used (all functions ignore it)
1353 // channel id
1354 device.downgrade_to_ctap1();
1355 assert_eq!(device.get_protocol(), FidoProtocol::CTAP1);
1356 let mut cid = [0u8; 4];
1357 thread_rng().fill_bytes(&mut cid);
1358
1359 device.set_cid(cid);
1360
1361 assert_matches!(
1362 do_credential_list_filtering_ctap1(
1363 &mut device,
1364 &assertion.allow_list,
1365 &assertion.rp,
1366 &assertion.client_data_hash,
1367 ),
1368 None
1369 );
1370 assertion.allow_list = vec![];
1371 // It should also fail when trying to format
1372 assert_matches!(
1373 assertion.ctap1_format(),
1374 Err(HIDError::Command(CommandError::StatusCode(
1375 StatusCode::NoCredentials,
1376 ..
1377 )))
1378 );
1379
1380 // Test also multiple too long keys and an empty allow list
1381 for allow_list in [vec![], vec![too_long_key_handle.clone(); 5]] {
1382 assertion.allow_list = allow_list;
1383
1384 assert_matches!(
1385 do_credential_list_filtering_ctap1(
1386 &mut device,
1387 &assertion.allow_list,
1388 &assertion.rp,
1389 &assertion.client_data_hash,
1390 ),
1391 None
1392 );
1393 }
1394
1395 let ok_key_handle = PublicKeyCredentialDescriptor {
1396 id: vec![
1397 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35, 0xEF,
1398 0xAA, 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D, 0xA4, 0x85,
1399 0x34, 0xC8, 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78,
1400 0x05, 0x5B, 0xDD, 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC,
1401 0xD4, 0x15, 0xCD, 0x08, 0xFE, 0x42, 0x00, 0x38,
1402 ],
1403 transports: vec![Transport::USB],
1404 };
1405 assertion.allow_list = vec![
1406 too_long_key_handle.clone(),
1407 too_long_key_handle.clone(),
1408 too_long_key_handle.clone(),
1409 ok_key_handle.clone(),
1410 too_long_key_handle,
1411 ];
1412
1413 // ctap1 request
1414 fill_device_ctap1(
1415 &mut device,
1416 cid,
1417 U2F_CHECK_IS_REGISTERED,
1418 SW_CONDITIONS_NOT_SATISFIED,
1419 );
1420 let key_handle = do_credential_list_filtering_ctap1(
1421 &mut device,
1422 &assertion.allow_list,
1423 &assertion.rp,
1424 &assertion.client_data_hash,
1425 )
1426 .expect("Did not find a key_handle, even though it should have");
1427 assertion.allow_list = vec![key_handle];
1428 let (ctap1_request, key_handle) = assertion.ctap1_format().unwrap();
1429 assert_eq!(key_handle, ok_key_handle);
1430 // Check if the request is going to be correct
1431 assert_eq!(ctap1_request, GET_ASSERTION_SAMPLE_REQUEST_CTAP1);
1432
1433 // Now do it again, but parse the actual response
1434 // Pre-flighting is not done automatically
1435 fill_device_ctap1(&mut device, cid, U2F_REQUEST_USER_PRESENCE, SW_NO_ERROR);
1436
1437 let response = device.send_ctap1(&assertion).unwrap();
1438
1439 // Check if response is correct
1440 let expected_auth_data = AuthenticatorData {
1441 rp_id_hash: RpIdHash(RELYING_PARTY_HASH),
1442 flags: AuthenticatorDataFlags::USER_PRESENT,
1443 counter: 0x3B,
1444 credential_data: None,
1445 extensions: Default::default(),
1446 };
1447
1448 let expected_assertion = Assertion {
1449 credentials: Some(ok_key_handle),
1450 signature: vec![
1451 0x30, 0x44, 0x02, 0x20, 0x7B, 0xDE, 0x0A, 0x52, 0xAC, 0x1F, 0x4C, 0x8B, 0x27, 0xE0,
1452 0x03, 0xA3, 0x70, 0xCD, 0x66, 0xA4, 0xC7, 0x11, 0x8D, 0xD2, 0x2D, 0x54, 0x47, 0x83,
1453 0x5F, 0x45, 0xB9, 0x9C, 0x68, 0x42, 0x3F, 0xF7, 0x02, 0x20, 0x3C, 0x51, 0x7B, 0x47,
1454 0x87, 0x7F, 0x85, 0x78, 0x2D, 0xE1, 0x00, 0x86, 0xA7, 0x83, 0xD1, 0xE7, 0xDF, 0x4E,
1455 0x36, 0x39, 0xE7, 0x71, 0xF5, 0xF6, 0xAF, 0xA3, 0x5A, 0xAD, 0x53, 0x73, 0x85, 0x8E,
1456 ],
1457 user: None,
1458 auth_data: expected_auth_data,
1459 };
1460
1461 let expected = vec![GetAssertionResult {
1462 assertion: expected_assertion,
1463 attachment: AuthenticatorAttachment::Unknown,
1464 extensions: Default::default(),
1465 }];
1466 assert_eq!(response, expected);
1467 }
1468
1469 #[test]
1470 fn test_get_assertion_ctap2_pre_flight() {
1471 let client_data = CollectedClientData {
1472 webauthn_type: WebauthnType::Create,
1473 challenge: Challenge::from(vec![0x00, 0x01, 0x02, 0x03]),
1474 origin: String::from("example.com"),
1475 cross_origin: false,
1476 token_binding: Some(TokenBinding::Present(String::from("AAECAw"))),
1477 };
1478 let assertion = GetAssertion::new(
1479 client_data.hash().expect("failed to serialize client data"),
1480 RelyingParty::from("example.com"),
1481 vec![
1482 // This should never be tested, because it gets pre-filtered, since it is too long
1483 // (see max_credential_id_length)
1484 PublicKeyCredentialDescriptor {
1485 id: vec![0x10; 100],
1486 transports: vec![Transport::USB],
1487 },
1488 // One we test and skip
1489 PublicKeyCredentialDescriptor {
1490 id: vec![
1491 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
1492 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
1493 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
1494 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
1495 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
1496 0x11, 0x11, 0x11, 0x11,
1497 ],
1498 transports: vec![Transport::USB],
1499 },
1500 // This one is the 'right' one
1501 PublicKeyCredentialDescriptor {
1502 id: vec![
1503 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26,
1504 0x35, 0xEF, 0xAA, 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3,
1505 0x71, 0x7D, 0xA4, 0x85, 0x34, 0xC8, 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94,
1506 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD, 0x39, 0x6B, 0x64,
1507 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08,
1508 0xFE, 0x42, 0x00, 0x38,
1509 ],
1510 transports: vec![Transport::USB],
1511 },
1512 // We should never test this one
1513 PublicKeyCredentialDescriptor {
1514 id: vec![
1515 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
1516 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
1517 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
1518 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
1519 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
1520 0x22, 0x22, 0x22, 0x22,
1521 ],
1522 transports: vec![Transport::USB],
1523 },
1524 ],
1525 GetAssertionOptions {
1526 user_presence: Some(true),
1527 user_verification: None,
1528 },
1529 Default::default(),
1530 );
1531 let mut device = Device::new("commands/get_assertion").unwrap();
1532 assert_eq!(device.get_protocol(), FidoProtocol::CTAP2);
1533 let mut cid = [0u8; 4];
1534 thread_rng().fill_bytes(&mut cid);
1535 device.set_cid(cid);
1536 device.set_device_info(U2FDeviceInfo {
1537 vendor_name: Vec::new(),
1538 device_name: Vec::new(),
1539 version_interface: 0x02,
1540 version_major: 0x04,
1541 version_minor: 0x01,
1542 version_build: 0x08,
1543 cap_flags: Capability::WINK | Capability::CBOR,
1544 });
1545 device.set_authenticator_info(AuthenticatorInfo {
1546 versions: vec![AuthenticatorVersion::U2F_V2, AuthenticatorVersion::FIDO_2_0],
1547 extensions: vec!["uvm".to_string(), "hmac-secret".to_string()],
1548 aaguid: AAGuid(AAGUID_RAW),
1549 options: AuthenticatorOptions {
1550 platform_device: false,
1551 resident_key: true,
1552 client_pin: Some(false),
1553 user_presence: true,
1554 user_verification: None,
1555 ..Default::default()
1556 },
1557 max_msg_size: Some(1200),
1558 pin_protocols: Some(vec![1]),
1559 max_credential_count_in_list: None,
1560 max_credential_id_length: Some(80),
1561 transports: None,
1562 algorithms: None,
1563 max_ser_large_blob_array: None,
1564 force_pin_change: None,
1565 min_pin_length: None,
1566 firmware_version: None,
1567 max_cred_blob_length: None,
1568 max_rpids_for_set_min_pin_length: None,
1569 preferred_platform_uv_attempts: None,
1570 uv_modality: None,
1571 certifications: None,
1572 remaining_discoverable_credentials: None,
1573 vendor_prototype_config_commands: None,
1574 });
1575
1576 // Sending first GetAssertion with first allow_list-entry, that will return an error
1577 let mut msg = cid.to_vec();
1578 msg.extend(vec![HIDCmd::Cbor.into(), 0x00, 0x90]);
1579 msg.extend(vec![0x2]); // u2f command
1580 msg.extend(vec![
1581 0xa4, // map(4)
1582 0x1, // rpid
1583 0x6b, // text(11)
1584 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, // example.com
1585 0x2, // clientDataHash
1586 0x58, 0x20, //bytes(32)
1587 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f,
1588 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
1589 0x78, 0x52, 0xb8, 0x55, // empty hash
1590 0x3, //allowList
1591 0x81, // array(1)
1592 0xa2, // map(2)
1593 0x62, // text(2)
1594 0x69, 0x64, // id
1595 0x58, // bytes(
1596 ]);
1597 device.add_write(&msg, 0);
1598
1599 msg = cid.to_vec();
1600 msg.extend([0x0]); //SEQ
1601 msg.extend([0x40]); // 64)
1602 msg.extend(&assertion.allow_list[1].id[..58]);
1603 device.add_write(&msg, 0);
1604
1605 msg = cid.to_vec();
1606 msg.extend([0x1]); //SEQ
1607 msg.extend(&assertion.allow_list[1].id[58..64]);
1608 msg.extend(vec![
1609 0x64, // text(4),
1610 0x74, 0x79, 0x70, 0x65, // type
1611 0x6a, // text(10)
1612 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x2D, 0x6B, 0x65, 0x79, // public-key
1613 0x5, // options
1614 0xa1, // map(1)
1615 0x62, // text(2)
1616 0x75, 0x70, // up
1617 0xf4, // false
1618 ]);
1619 device.add_write(&msg, 0);
1620
1621 // fido response
1622 let len = 0x1;
1623 let mut msg = cid.to_vec();
1624 msg.extend(vec![HIDCmd::Cbor.into(), 0x00, len]); // cmd + bcnt
1625 msg.push(0x2e); // Status code: NoCredentials
1626 device.add_read(&msg, 0);
1627
1628 // Sending second GetAssertion with first allow_list-entry, that will return a success
1629 let mut msg = cid.to_vec();
1630 msg.extend(vec![HIDCmd::Cbor.into(), 0x00, 0x90]);
1631 msg.extend(vec![0x2]); // u2f command
1632 msg.extend(vec![
1633 0xa4, // map(4)
1634 0x1, // rpid
1635 0x6b, // text(11)
1636 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, // example.com
1637 0x2, // clientDataHash
1638 0x58, 0x20, //bytes(32)
1639 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f,
1640 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
1641 0x78, 0x52, 0xb8, 0x55, // empty hash
1642 0x3, //allowList
1643 0x81, // array(1)
1644 0xa2, // map(2)
1645 0x62, // text(2)
1646 0x69, 0x64, // id
1647 0x58, // bytes(
1648 ]);
1649 device.add_write(&msg, 0);
1650
1651 msg = cid.to_vec();
1652 msg.extend([0x0]); //SEQ
1653 msg.extend([0x40]); // 64)
1654 msg.extend(&assertion.allow_list[2].id[..58]);
1655 device.add_write(&msg, 0);
1656
1657 msg = cid.to_vec();
1658 msg.extend([0x1]); //SEQ
1659 msg.extend(&assertion.allow_list[2].id[58..64]);
1660 msg.extend(vec![
1661 0x64, // text(4),
1662 0x74, 0x79, 0x70, 0x65, // type
1663 0x6a, // text(10)
1664 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x2D, 0x6B, 0x65, 0x79, // public-key
1665 0x5, // options
1666 0xa1, // map(1)
1667 0x62, // text(2)
1668 0x75, 0x70, // up
1669 0xf4, // false
1670 ]);
1671 device.add_write(&msg, 0);
1672
1673 let mut msg = cid.to_vec();
1674 msg.extend([HIDCmd::Cbor.into(), 0x1, 0x2a]); // cmd + bcnt
1675 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[..57]);
1676 device.add_read(&msg, 0);
1677
1678 let mut msg = cid.to_vec();
1679 msg.extend([0x0]); // SEQ
1680 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[57..116]);
1681 device.add_read(&msg, 0);
1682
1683 let mut msg = cid.to_vec();
1684 msg.extend([0x1]); // SEQ
1685 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[116..175]);
1686 device.add_read(&msg, 0);
1687
1688 let mut msg = cid.to_vec();
1689 msg.extend([0x2]); // SEQ
1690 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[175..234]);
1691 device.add_read(&msg, 0);
1692
1693 let mut msg = cid.to_vec();
1694 msg.extend([0x3]); // SEQ
1695 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[234..293]);
1696 device.add_read(&msg, 0);
1697 let mut msg = cid.to_vec();
1698 msg.extend([0x4]); // SEQ
1699 msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[293..]);
1700 device.add_read(&msg, 0);
1701
1702 assert_matches!(
1703 do_credential_list_filtering_ctap2(
1704 &mut device,
1705 &assertion.allow_list,
1706 &assertion.rp,
1707 None,
1708 ),
1709 Ok(..)
1710 );
1711 }
1712
1713 #[test]
1714 fn test_get_assertion_ctap1_flags() {
1715 // Ensure that only the two low bits of flags are preserved when repackaging a
1716 // CTAP1 response.
1717 let mut sample = GET_ASSERTION_SAMPLE_RESPONSE_CTAP1.to_vec();
1718 sample[0] = 0xff; // Set all 8 flag bits before repackaging
1719 let add_info = PublicKeyCredentialDescriptor {
1720 id: vec![],
1721 transports: vec![],
1722 };
1723 let rp_hash = RpIdHash([0u8; 32]);
1724 let resp = GetAssertionResult::from_ctap1(&sample, &rp_hash, &add_info)
1725 .expect("could not handle response");
1726 assert_eq!(
1727 resp.assertion.auth_data.flags,
1728 AuthenticatorDataFlags::USER_PRESENT | AuthenticatorDataFlags::RESERVED_1
1729 );
1730 }
1731
1732 // Manually assembled according to https://www.w3.org/TR/webauthn-2/#clientdatajson-serialization
1733 const CLIENT_DATA_VEC: [u8; 140] = [
1734 0x7b, 0x22, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, // {"type":
1735 0x22, 0x77, 0x65, 0x62, 0x61, 0x75, 0x74, 0x68, 0x6e, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74,
1736 0x65, 0x22, // "webauthn.create"
1737 0x2c, 0x22, 0x63, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x22,
1738 0x3a, // (,"challenge":
1739 0x22, 0x41, 0x41, 0x45, 0x43, 0x41, 0x77, 0x22, // challenge in base64
1740 0x2c, 0x22, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x22, 0x3a, // ,"origin":
1741 0x22, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d,
1742 0x22, // "example.com"
1743 0x2c, 0x22, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x22,
1744 0x3a, // ,"crossOrigin":
1745 0x66, 0x61, 0x6c, 0x73, 0x65, // false
1746 0x2c, 0x22, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x22,
1747 0x3a, // ,"tokenBinding":
1748 0x7b, 0x22, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3a, // {"status":
1749 0x22, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x22, // "present"
1750 0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, // ,"id":
1751 0x22, 0x41, 0x41, 0x45, 0x43, 0x41, 0x77, 0x22, // "AAECAw"
1752 0x7d, // }
1753 0x7d, // }
1754 ];
1755
1756 const CLIENT_DATA_HASH: [u8; 32] = [
1757 0x75, 0x35, 0x35, 0x7d, 0x49, 0x6e, 0x33, 0xc8, 0x18, 0x7f, 0xea, 0x8d, 0x11, // hash
1758 0x32, 0x64, 0xaa, 0xa4, 0x52, 0x3e, 0x13, 0x40, 0x14, 0x9f, 0xbe, 0x00, 0x3f, // hash
1759 0x10, 0x87, 0x54, 0xc3, 0x2d, 0x80, // hash
1760 ];
1761
1762 const RELYING_PARTY_HASH: [u8; 32] = [
1763 0xA3, 0x79, 0xA6, 0xF6, 0xEE, 0xAF, 0xB9, 0xA5, 0x5E, 0x37, 0x8C, 0x11, 0x80, 0x34, 0xE2,
1764 0x75, 0x1E, 0x68, 0x2F, 0xAB, 0x9F, 0x2D, 0x30, 0xAB, 0x13, 0xD2, 0x12, 0x55, 0x86, 0xCE,
1765 0x19, 0x47,
1766 ];
1767 const KEY_HANDLE: [u8; 64] = [
1768 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35, 0xEF, 0xAA,
1769 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D, 0xA4, 0x85, 0x34, 0xC8,
1770 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD,
1771 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08,
1772 0xFE, 0x42, 0x00, 0x38,
1773 ];
1774
1775 const GET_ASSERTION_SAMPLE_REQUEST_CTAP1: [u8; 138] = [
1776 // CBOR Header
1777 0x0, // CLA
1778 0x2, // INS U2F_Authenticate
1779 0x3, // P1 Flags (user presence)
1780 0x0, // P2
1781 0x0, 0x0, 0x81, // Lc
1782 // NOTE: This has been taken from CTAP2.0 spec, but the clientDataHash has been replaced
1783 // to be able to operate with known values for CollectedClientData (spec doesn't say
1784 // what values led to the provided example hash)
1785 // clientDataHash:
1786 0x75, 0x35, 0x35, 0x7d, 0x49, 0x6e, 0x33, 0xc8, 0x18, 0x7f, 0xea, 0x8d, 0x11, // hash
1787 0x32, 0x64, 0xaa, 0xa4, 0x52, 0x3e, 0x13, 0x40, 0x14, 0x9f, 0xbe, 0x00, 0x3f, // hash
1788 0x10, 0x87, 0x54, 0xc3, 0x2d, 0x80, // hash
1789 // rpIdHash:
1790 0xA3, 0x79, 0xA6, 0xF6, 0xEE, 0xAF, 0xB9, 0xA5, 0x5E, 0x37, 0x8C, 0x11, 0x80, 0x34, 0xE2,
1791 0x75, 0x1E, 0x68, 0x2F, 0xAB, 0x9F, 0x2D, 0x30, 0xAB, 0x13, 0xD2, 0x12, 0x55, 0x86, 0xCE,
1792 0x19, 0x47, // ..
1793 // Key Handle Length (1 Byte):
1794 0x40, // ..
1795 // Key Handle (Key Handle Length Bytes):
1796 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35, 0xEF, 0xAA,
1797 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D, 0xA4, 0x85, 0x34, 0xC8,
1798 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD,
1799 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08,
1800 0xFE, 0x42, 0x00, 0x38, // ..
1801 // Le (Ne=65536):
1802 0x0, 0x0,
1803 ];
1804
1805 const GET_ASSERTION_SAMPLE_REQUEST_CTAP2: [u8; 138] = [
1806 // CBOR Header
1807 0x0, // leading zero
1808 0x2, // CMD U2F_Authenticate
1809 0x3, // Flags (user presence)
1810 0x0, 0x0, // zero bits
1811 0x0, 0x81, // size
1812 // NOTE: This has been taken from CTAP2.0 spec, but the clientDataHash has been replaced
1813 // to be able to operate with known values for CollectedClientData (spec doesn't say
1814 // what values led to the provided example hash)
1815 // clientDataHash:
1816 0x75, 0x35, 0x35, 0x7d, 0x49, 0x6e, 0x33, 0xc8, 0x18, 0x7f, 0xea, 0x8d, 0x11, 0x32, 0x64,
1817 0xaa, 0xa4, 0x52, 0x3e, 0x13, 0x40, 0x14, 0x9f, 0xbe, 0x00, 0x3f, 0x10, 0x87, 0x54, 0xc3,
1818 0x2d, 0x80, // hash
1819 // rpIdHash:
1820 0xA3, 0x79, 0xA6, 0xF6, 0xEE, 0xAF, 0xB9, 0xA5, 0x5E, 0x37, 0x8C, 0x11, 0x80, 0x34, 0xE2,
1821 0x75, 0x1E, 0x68, 0x2F, 0xAB, 0x9F, 0x2D, 0x30, 0xAB, 0x13, 0xD2, 0x12, 0x55, 0x86, 0xCE,
1822 0x19, 0x47, // ..
1823 // Key Handle Length (1 Byte):
1824 0x40, // ..
1825 // Key Handle (Key Handle Length Bytes):
1826 0x3E, 0xBD, 0x89, 0xBF, 0x77, 0xEC, 0x50, 0x97, 0x55, 0xEE, 0x9C, 0x26, 0x35, 0xEF, 0xAA,
1827 0xAC, 0x7B, 0x2B, 0x9C, 0x5C, 0xEF, 0x17, 0x36, 0xC3, 0x71, 0x7D, 0xA4, 0x85, 0x34, 0xC8,
1828 0xC6, 0xB6, 0x54, 0xD7, 0xFF, 0x94, 0x5F, 0x50, 0xB5, 0xCC, 0x4E, 0x78, 0x05, 0x5B, 0xDD,
1829 0x39, 0x6B, 0x64, 0xF7, 0x8D, 0xA2, 0xC5, 0xF9, 0x62, 0x00, 0xCC, 0xD4, 0x15, 0xCD, 0x08,
1830 0xFE, 0x42, 0x00, 0x38, 0x0, 0x0, // 2 trailing zeros from protocol
1831 ];
1832
1833 const GET_ASSERTION_SAMPLE_RESPONSE_CTAP1: [u8; 75] = [
1834 0x01, // User Presence (1 Byte)
1835 0x00, 0x00, 0x00, 0x3B, // Sign Count (4 Bytes)
1836 // Signature (variable Length)
1837 0x30, 0x44, 0x02, 0x20, 0x7B, 0xDE, 0x0A, 0x52, 0xAC, 0x1F, 0x4C, 0x8B, 0x27, 0xE0, 0x03,
1838 0xA3, 0x70, 0xCD, 0x66, 0xA4, 0xC7, 0x11, 0x8D, 0xD2, 0x2D, 0x54, 0x47, 0x83, 0x5F, 0x45,
1839 0xB9, 0x9C, 0x68, 0x42, 0x3F, 0xF7, 0x02, 0x20, 0x3C, 0x51, 0x7B, 0x47, 0x87, 0x7F, 0x85,
1840 0x78, 0x2D, 0xE1, 0x00, 0x86, 0xA7, 0x83, 0xD1, 0xE7, 0xDF, 0x4E, 0x36, 0x39, 0xE7, 0x71,
1841 0xF5, 0xF6, 0xAF, 0xA3, 0x5A, 0xAD, 0x53, 0x73, 0x85, 0x8E,
1842 ];
1843
1844 const GET_ASSERTION_SAMPLE_RESPONSE_CTAP2: [u8; 298] = [
1845 0x00, // status == success
1846 0xA5, // map(5)
1847 0x01, // unsigned(1)
1848 0xA2, // map(2)
1849 0x62, // text(2)
1850 0x69, 0x64, // "id"
1851 0x58, 0x40, // bytes(0x64, ) credential_id
1852 0xF2, 0x20, 0x06, 0xDE, 0x4F, 0x90, 0x5A, 0xF6, 0x8A, 0x43, 0x94, 0x2F, 0x02, 0x4F, 0x2A,
1853 0x5E, 0xCE, 0x60, 0x3D, 0x9C, 0x6D, 0x4B, 0x3D, 0xF8, 0xBE, 0x08, 0xED, 0x01, 0xFC, 0x44,
1854 0x26, 0x46, 0xD0, 0x34, 0x85, 0x8A, 0xC7, 0x5B, 0xED, 0x3F, 0xD5, 0x80, 0xBF, 0x98, 0x08,
1855 0xD9, 0x4F, 0xCB, 0xEE, 0x82, 0xB9, 0xB2, 0xEF, 0x66, 0x77, 0xAF, 0x0A, 0xDC, 0xC3, 0x58,
1856 0x52, 0xEA, 0x6B, 0x9E, // end: credential_id
1857 0x64, // text(4)
1858 0x74, 0x79, 0x70, 0x65, // "type"
1859 0x6A, // text(0x10, )
1860 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x2D, 0x6B, 0x65, 0x79, // "public-key"
1861 0x02, // unsigned(2)
1862 0x58, 0x25, // bytes(0x37, ) auth_data
1863 0x62, 0x5D, 0xDA, 0xDF, 0x74, 0x3F, 0x57, 0x27, 0xE6, 0x6B, 0xBA, 0x8C, 0x2E, 0x38, 0x79,
1864 0x22, 0xD1, 0xAF, 0x43, 0xC5, 0x03, 0xD9, 0x11, 0x4A, 0x8F, 0xBA, 0x10, 0x4D, 0x84, 0xD0,
1865 0x2B, 0xFA, 0x01, 0x00, 0x00, 0x00, 0x11, // end: auth_data
1866 0x03, // unsigned(3)
1867 0x58, 0x47, // bytes(0x71, ) signature
1868 0x30, 0x45, 0x02, 0x20, 0x4A, 0x5A, 0x9D, 0xD3, 0x92, 0x98, 0x14, 0x9D, 0x90, 0x47, 0x69,
1869 0xB5, 0x1A, 0x45, 0x14, 0x33, 0x00, 0x6F, 0x18, 0x2A, 0x34, 0xFB, 0xDF, 0x66, 0xDE, 0x5F,
1870 0xC7, 0x17, 0xD7, 0x5F, 0xB3, 0x50, 0x02, 0x21, 0x00, 0xA4, 0x6B, 0x8E, 0xA3, 0xC3, 0xB9,
1871 0x33, 0x82, 0x1C, 0x6E, 0x7F, 0x5E, 0xF9, 0xDA, 0xAE, 0x94, 0xAB, 0x47, 0xF1, 0x8D, 0xB4,
1872 0x74, 0xC7, 0x47, 0x90, 0xEA, 0xAB, 0xB1, 0x44, 0x11, 0xE7, 0xA0, // end: signature
1873 0x04, // unsigned(4)
1874 0xA3, // map(3)
1875 0x62, // text(2)
1876 0x69, 0x64, // "id"
1877 0x58, 0x20, // bytes(0x32, ) user_id
1878 0x30, 0x82, 0x01, 0x93, 0x30, 0x82, 0x01, 0x38, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x30, 0x82,
1879 0x01, 0x93, 0x30, 0x82, 0x01, 0x38, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x30, 0x82, 0x01, 0x93,
1880 0x30, 0x82, // end: user_id
1881 0x64, // text(4)
1882 0x6E, 0x61, 0x6D, 0x65, // "name"
1883 0x76, // text(0x22, )
1884 0x6A, 0x6F, 0x68, 0x6E, 0x70, 0x73, 0x6D, 0x69, 0x74, 0x68, 0x40, 0x65, 0x78, 0x61, 0x6D,
1885 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, // "[email protected]"
1886 0x6B, // text(0x11, )
1887 0x64, 0x69, 0x73, 0x70, 0x6C, 0x61, 0x79, 0x4E, 0x61, 0x6D, 0x65, // "displayName"
1888 0x6D, // text(0x13, )
1889 0x4A, 0x6F, 0x68, 0x6E, 0x20, 0x50, 0x2E, 0x20, 0x53, 0x6D, 0x69, 0x74,
1890 0x68, // "John P. Smith"
1891 0x05, // unsigned(5)
1892 0x01, // unsigned(1)
1893 ];
1894
1895 mod hmac_secret {
1896 use std::convert::TryFrom;
1897
1898 use crate::{
1899 crypto::{
1900 COSEAlgorithm, COSEEC2Key, COSEKey, COSEKeyType, Curve, PinUvAuthProtocol,
1901 SharedSecret,
1902 },
1903 ctap2::{
1904 attestation::{
1905 AuthenticatorData, AuthenticatorDataFlags, Extension, HmacSecretResponse,
1906 },
1907 client_data::ClientDataHash,
1908 commands::{
1909 get_assertion::{
1910 CalculatedHmacSecretExtension, GetAssertion, GetAssertionExtensions,
1911 HmacGetSecretOrPrf, HmacSecretExtension,
1912 },
1913 CommandError,
1914 },
1915 server::{
1916 AuthenticationExtensionsClientOutputs, AuthenticationExtensionsPRFOutputs,
1917 AuthenticatorAttachment, RelyingParty, RpIdHash,
1918 },
1919 },
1920 transport::platform::device::Device,
1921 Assertion, AuthenticatorInfo, FidoDevice, GetAssertionResult,
1922 };
1923
1924 fn make_test_secret_without_puat(
1925 pin_protocol: u64,
1926 ) -> Result<(SharedSecret, COSEKey), CommandError> {
1927 let fake_client_key = COSEKey {
1928 alg: COSEAlgorithm::ECDH_ES_HKDF256,
1929 key: COSEKeyType::EC2(COSEEC2Key {
1930 curve: Curve::SECP256R1,
1931 x: vec![1],
1932 y: vec![2],
1933 }),
1934 };
1935 let fake_peer_key = COSEKey {
1936 alg: COSEAlgorithm::ECDH_ES_HKDF256,
1937 key: COSEKeyType::EC2(COSEEC2Key {
1938 curve: Curve::SECP256R1,
1939 x: vec![3],
1940 y: vec![4],
1941 }),
1942 };
1943
1944 let pin_protocol = PinUvAuthProtocol::try_from(&AuthenticatorInfo {
1945 pin_protocols: Some(vec![pin_protocol]),
1946 ..Default::default()
1947 })?;
1948
1949 let key = {
1950 let aes_key = 0..32;
1951 let hmac_key = 32..64;
1952 match pin_protocol.id() {
1953 1 => aes_key.collect(),
1954 2 => hmac_key.chain(aes_key).collect(),
1955 _ => unimplemented!(),
1956 }
1957 };
1958
1959 let shared_secret =
1960 SharedSecret::new_test(pin_protocol, key, fake_client_key.clone(), fake_peer_key);
1961
1962 Ok((shared_secret, fake_client_key))
1963 }
1964
1965 #[cfg(not(feature = "crypto_dummy"))]
1966 mod requires_crypto {
1967 use sha2::{Digest, Sha256};
1968
1969 use super::*;
1970 use crate::{
1971 crypto::{CryptoError, PinUvAuthToken},
1972 ctap2::{
1973 client_data::ClientDataHash,
1974 commands::{
1975 client_pin::PinUvAuthTokenPermission,
1976 get_assertion::{
1977 CalculatedHmacSecretExtension, GetAssertion, GetAssertionExtensions,
1978 HmacGetSecretOrPrf, HmacSecretExtension,
1979 },
1980 PinUvAuthResult,
1981 },
1982 server::{
1983 AuthenticationExtensionsPRFInputs, AuthenticationExtensionsPRFValues,
1984 PublicKeyCredentialDescriptor, RelyingParty,
1985 },
1986 },
1987 errors::AuthenticatorError,
1988 };
1989
1990 fn make_test_secret(
1991 pin_protocol: u64,
1992 ) -> Result<(SharedSecret, COSEKey, PinUvAuthToken), CommandError> {
1993 let (shared_secret, fake_client_key) = make_test_secret_without_puat(pin_protocol)?;
1994 let puat = shared_secret.decrypt_pin_token(
1995 PinUvAuthTokenPermission::empty(),
1996 &shared_secret.encrypt(&[0x03; 32])?,
1997 )?;
1998
1999 Ok((shared_secret, fake_client_key, puat))
2000 }
2001
2002 fn get_assertion_process_hmac_secret(
2003 secret_available: bool,
2004 allow_list: Vec<PublicKeyCredentialDescriptor>,
2005 hmac_secret: Option<HmacGetSecretOrPrf>,
2006 ) -> Result<GetAssertion, AuthenticatorError> {
2007 let (shared_secret, _, puat) = make_test_secret(1)?;
2008 GetAssertion::new(
2009 ClientDataHash([0x01; 32]),
2010 RelyingParty::from("example.com"),
2011 allow_list,
2012 Default::default(),
2013 GetAssertionExtensions {
2014 hmac_secret,
2015 ..Default::default()
2016 },
2017 )
2018 .process_hmac_secret_and_prf_extension(
2019 secret_available
2020 .then_some((&shared_secret, &PinUvAuthResult::SuccessGetPinToken(puat))),
2021 )
2022 }
2023
2024 #[test]
2025 fn get_assertion_hmac_secret_and_prf_absent_uses_no_input() {
2026 let get_assertion = get_assertion_process_hmac_secret(true, vec![], None).unwrap();
2027 assert_matches!(get_assertion.extensions.hmac_secret, None);
2028 }
2029
2030 #[test]
2031 fn get_assertion_prf_no_input_uses_unmatched_input() {
2032 let get_assertion = get_assertion_process_hmac_secret(
2033 true,
2034 vec![],
2035 Some(HmacGetSecretOrPrf::PrfUninitialized(
2036 AuthenticationExtensionsPRFInputs {
2037 eval: None,
2038 eval_by_credential: None,
2039 },
2040 )),
2041 )
2042 .unwrap();
2043 assert_matches!(
2044 get_assertion.extensions.hmac_secret,
2045 Some(HmacGetSecretOrPrf::PrfUnmatched)
2046 );
2047 }
2048
2049 #[test]
2050 fn get_assertion_prf_no_secret_uses_unmatched_input() {
2051 let get_assertion = get_assertion_process_hmac_secret(
2052 false,
2053 vec![],
2054 Some(HmacGetSecretOrPrf::PrfUninitialized(
2055 AuthenticationExtensionsPRFInputs {
2056 eval: Some(AuthenticationExtensionsPRFValues {
2057 first: vec![1, 2, 3, 4],
2058 second: None,
2059 }),
2060 eval_by_credential: None,
2061 },
2062 )),
2063 )
2064 .unwrap();
2065 assert_matches!(
2066 get_assertion.extensions.hmac_secret,
2067 Some(HmacGetSecretOrPrf::PrfUnmatched)
2068 );
2069 }
2070
2071 #[test]
2072 fn get_assertion_hmac_get_secret_uses_hmac_get_secret_input() {
2073 let get_assertion = get_assertion_process_hmac_secret(
2074 true,
2075 vec![],
2076 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2077 vec![0x01; 32],
2078 None,
2079 ))),
2080 )
2081 .unwrap();
2082 assert_matches!(
2083 get_assertion.extensions.hmac_secret,
2084 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension {
2085 calculated_hmac: Some(_),
2086 ..
2087 }))
2088 );
2089 }
2090
2091 #[test]
2092 fn get_assertion_hmac_get_secret_bad_length_returns_invalid_input_error() {
2093 let get_assertion = get_assertion_process_hmac_secret(
2094 true,
2095 vec![],
2096 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2097 vec![0x01; 31],
2098 None,
2099 ))),
2100 );
2101 assert_matches!(
2102 get_assertion,
2103 Err(AuthenticatorError::InvalidRelyingPartyInput)
2104 );
2105 }
2106
2107 #[test]
2108 fn get_assertion_prf_eval_uses_eval_input() {
2109 let get_assertion = get_assertion_process_hmac_secret(
2110 true,
2111 vec![],
2112 Some(HmacGetSecretOrPrf::PrfUninitialized(
2113 AuthenticationExtensionsPRFInputs {
2114 eval: Some(AuthenticationExtensionsPRFValues {
2115 first: vec![1, 2, 3, 4],
2116 second: None,
2117 }),
2118 eval_by_credential: None,
2119 },
2120 )),
2121 )
2122 .unwrap();
2123 assert_matches!(
2124 get_assertion.extensions.hmac_secret,
2125 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2126 salt1,
2127 ..
2128 })) if salt1 == Sha256::new_with_prefix(b"WebAuthn PRF")
2129 .chain_update([0x00].iter())
2130 .chain_update([1, 2, 3, 4].iter())
2131 .finalize()
2132 .to_vec()
2133 );
2134 }
2135
2136 #[test]
2137 fn get_assertion_prf_eval_by_credential_unmatched_uses_unmatched_input() {
2138 let get_assertion = get_assertion_process_hmac_secret(
2139 true,
2140 vec![PublicKeyCredentialDescriptor {
2141 id: vec![1, 2, 3, 4],
2142 transports: vec![],
2143 }],
2144 Some(HmacGetSecretOrPrf::PrfUninitialized(
2145 AuthenticationExtensionsPRFInputs {
2146 eval: None,
2147 eval_by_credential: Some(
2148 [(
2149 vec![5, 6, 7, 8],
2150 AuthenticationExtensionsPRFValues {
2151 first: vec![9, 10, 11, 12],
2152 second: None,
2153 },
2154 )]
2155 .into(),
2156 ),
2157 },
2158 )),
2159 )
2160 .unwrap();
2161 assert_matches!(
2162 get_assertion.extensions.hmac_secret,
2163 Some(HmacGetSecretOrPrf::PrfUnmatched)
2164 );
2165 }
2166
2167 #[test]
2168 fn get_assertion_prf_eval_by_credential_matched_uses_eval_by_credential_input() {
2169 let get_assertion = get_assertion_process_hmac_secret(
2170 true,
2171 vec![PublicKeyCredentialDescriptor {
2172 id: vec![1, 2, 3, 4],
2173 transports: vec![],
2174 }],
2175 Some(HmacGetSecretOrPrf::PrfUninitialized(
2176 AuthenticationExtensionsPRFInputs {
2177 eval: None,
2178 eval_by_credential: Some(
2179 [(
2180 vec![1, 2, 3, 4],
2181 AuthenticationExtensionsPRFValues {
2182 first: vec![9, 10, 11, 12],
2183 second: None,
2184 },
2185 )]
2186 .into(),
2187 ),
2188 },
2189 )),
2190 )
2191 .unwrap();
2192 assert_matches!(
2193 get_assertion.extensions.hmac_secret,
2194 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2195 salt1,
2196 ..
2197 })) if salt1 == Sha256::new_with_prefix(b"WebAuthn PRF")
2198 .chain_update([0x00].iter())
2199 .chain_update([9, 10, 11, 12].iter())
2200 .finalize()
2201 .to_vec()
2202 );
2203 }
2204
2205 #[test]
2206 fn get_assertion_prf_eval_and_eval_by_credential_unmatched_uses_eval_input() {
2207 let get_assertion = get_assertion_process_hmac_secret(
2208 true,
2209 vec![PublicKeyCredentialDescriptor {
2210 id: vec![1, 2, 3, 4],
2211 transports: vec![],
2212 }],
2213 Some(HmacGetSecretOrPrf::PrfUninitialized(
2214 AuthenticationExtensionsPRFInputs {
2215 eval: Some(AuthenticationExtensionsPRFValues {
2216 first: vec![13, 14, 15, 16],
2217 second: None,
2218 }),
2219 eval_by_credential: Some(
2220 [(
2221 vec![5, 6, 7, 8],
2222 AuthenticationExtensionsPRFValues {
2223 first: vec![9, 10, 11, 12],
2224 second: None,
2225 },
2226 )]
2227 .into(),
2228 ),
2229 },
2230 )),
2231 )
2232 .unwrap();
2233 assert_matches!(
2234 get_assertion.extensions.hmac_secret,
2235 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2236 salt1,
2237 ..
2238 })) if salt1 == Sha256::new_with_prefix(b"WebAuthn PRF")
2239 .chain_update([0x00].iter())
2240 .chain_update([13, 14, 15, 16].iter())
2241 .finalize()
2242 .to_vec()
2243 );
2244 }
2245
2246 #[test]
2247 fn get_assertion_prf_eval_and_eval_by_credential_matched_uses_eval_by_credential_input()
2248 {
2249 let get_assertion = get_assertion_process_hmac_secret(
2250 true,
2251 vec![PublicKeyCredentialDescriptor {
2252 id: vec![1, 2, 3, 4],
2253 transports: vec![],
2254 }],
2255 Some(HmacGetSecretOrPrf::PrfUninitialized(
2256 AuthenticationExtensionsPRFInputs {
2257 eval: Some(AuthenticationExtensionsPRFValues {
2258 first: vec![13, 14, 15, 16],
2259 second: None,
2260 }),
2261 eval_by_credential: Some(
2262 [(
2263 vec![1, 2, 3, 4],
2264 AuthenticationExtensionsPRFValues {
2265 first: vec![9, 10, 11, 12],
2266 second: None,
2267 },
2268 )]
2269 .into(),
2270 ),
2271 },
2272 )),
2273 )
2274 .unwrap();
2275 assert_matches!(
2276 get_assertion.extensions.hmac_secret,
2277 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2278 salt1,
2279 ..
2280 })) if salt1 == Sha256::new_with_prefix(b"WebAuthn PRF")
2281 .chain_update([0x00].iter())
2282 .chain_update([9, 10, 11, 12].iter())
2283 .finalize()
2284 .to_vec()
2285 );
2286 }
2287
2288 #[test]
2289 fn calculate_hmac_get_secret_pin_protocol_1() -> Result<(), AuthenticatorError> {
2290 let (shared_secret, client_key, puat) = make_test_secret(1)?;
2291 let extension = HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2292 vec![0x01; 32],
2293 Some(vec![0x02; 32]),
2294 ));
2295 let (extension, selected_cred) =
2296 extension.calculate(&shared_secret, &[], Some(&puat))?;
2297
2298 assert_eq!(selected_cred, None);
2299 assert_eq!(
2300 extension,
2301 HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension {
2302 salt1: vec![0x01; 32],
2303 salt2: Some(vec![0x02; 32]),
2304 calculated_hmac: Some(CalculatedHmacSecretExtension {
2305 public_key: client_key,
2306 salt_enc: vec![
2307 117, 226, 8, 41, 23, 33, 18, 187, 242, 160, 77, 61, 43, 18, 67, 61,
2308 170, 97, 245, 245, 17, 42, 232, 186, 255, 190, 82, 1, 81, 152, 175,
2309 39, 113, 130, 62, 169, 215, 202, 143, 80, 116, 195, 117, 22, 39,
2310 64, 79, 110, 216, 117, 7, 144, 87, 73, 144, 75, 255, 173, 169, 201,
2311 122, 160, 48, 157
2312 ],
2313 salt_auth: vec![
2314 36, 74, 81, 146, 64, 28, 73, 44, 75, 111, 14, 79, 173, 146, 212,
2315 227
2316 ],
2317 }),
2318 pin_protocol: None,
2319 }),
2320 );
2321
2322 Ok(())
2323 }
2324
2325 #[test]
2326 fn calculate_hmac_get_secret_wrong_length_salt1() -> Result<(), AuthenticatorError> {
2327 let (shared_secret, _, puat) = make_test_secret(1)?;
2328 for len in [0, 1, 31, 33, 64] {
2329 let extension = HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2330 vec![0x01; len],
2331 None,
2332 ));
2333 let result = extension.calculate(&shared_secret, &[], Some(&puat));
2334 assert_eq!(
2335 result,
2336 Err(CryptoError::WrongSaltLength),
2337 "At salt1 length: {}",
2338 len,
2339 );
2340 }
2341 Ok(())
2342 }
2343
2344 #[test]
2345 fn calculate_hmac_get_secret_wrong_length_salt2() -> Result<(), AuthenticatorError> {
2346 let (shared_secret, _, puat) = make_test_secret(1)?;
2347 for len in [0, 1, 31, 33, 64] {
2348 let extension = HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2349 vec![0x01; 32],
2350 Some(vec![0x02; len]),
2351 ));
2352 let result = extension.calculate(&shared_secret, &[], Some(&puat));
2353 assert_eq!(
2354 result,
2355 Err(CryptoError::WrongSaltLength),
2356 "At salt2 length: {}",
2357 len,
2358 );
2359 }
2360 Ok(())
2361 }
2362
2363 #[test]
2364 fn calculate_prf_eval_pin_protocol_1() -> Result<(), AuthenticatorError> {
2365 let (shared_secret, client_key, puat) = make_test_secret(1)?;
2366 let extension =
2367 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2368 eval: Some(AuthenticationExtensionsPRFValues {
2369 first: vec![0x01; 8],
2370 second: Some(vec![0x02; 8]),
2371 }),
2372 eval_by_credential: None,
2373 });
2374 let (extension, selected_cred) =
2375 extension.calculate(&shared_secret, &[], Some(&puat))?;
2376
2377 assert_eq!(selected_cred, None);
2378 assert_eq!(
2379 extension,
2380 HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2381 // JS: salt1 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(1)])))
2382 salt1: vec![
2383 5, 240, 179, 178, 62, 126, 205, 172, 176, 105, 211, 13, 86, 210, 48,
2384 210, 225, 219, 234, 248, 16, 182, 52, 219, 92, 135, 97, 119, 107, 245,
2385 30, 226
2386 ],
2387 // JS: salt2 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(2)])))
2388 salt2: Some(vec![
2389 96, 107, 65, 234, 77, 176, 251, 24, 193, 188, 98, 23, 59, 240, 212, 6,
2390 104, 176, 40, 242, 104, 190, 32, 124, 226, 244, 19, 160, 8, 105, 253,
2391 106
2392 ]),
2393 calculated_hmac: Some(CalculatedHmacSecretExtension {
2394 public_key: client_key,
2395 // JS: aesKey = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "AES-CBC" }, false, ["encrypt"])
2396 // JS: salt_enc = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, aesKey, new Uint8Array([...salt1, ...salt2]))).slice(0, 64)
2397 // (Need to strip trailing padding block inserted by WebCrypto)
2398 salt_enc: vec![
2399 23, 99, 220, 93, 59, 246, 109, 157, 247, 33, 138, 91, 142, 40, 203,
2400 234, 96, 212, 26, 15, 56, 160, 191, 142, 138, 106, 2, 207, 219,
2401 180, 39, 31, 155, 232, 119, 179, 0, 65, 9, 37, 184, 194, 135, 173,
2402 187, 197, 51, 38, 68, 57, 197, 68, 249, 41, 143, 197, 46, 53, 72,
2403 60, 109, 33, 112, 175
2404 ],
2405 // JS: hmacKeyP1 = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
2406 // JS: salt_auth = new Uint8Array(await crypto.subtle.sign("HMAC", hmacKeyP1, salt_enc)).slice(0, 16)
2407 salt_auth: vec![
2408 27, 222, 224, 22, 170, 39, 171, 5, 98, 207, 176, 58, 23, 108, 223,
2409 174
2410 ],
2411 }),
2412 pin_protocol: None,
2413 }),
2414 );
2415
2416 Ok(())
2417 }
2418
2419 #[test]
2420 fn calculate_prf_eval_by_cred_fallback_to_eval_pin_protocol_1(
2421 ) -> Result<(), AuthenticatorError> {
2422 let (shared_secret, client_key, puat) = make_test_secret(1)?;
2423 let extension =
2424 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2425 eval: Some(AuthenticationExtensionsPRFValues {
2426 first: vec![0x01; 8],
2427 second: Some(vec![0x02; 8]),
2428 }),
2429 eval_by_credential: Some(
2430 [(
2431 vec![1, 2, 3, 4],
2432 AuthenticationExtensionsPRFValues {
2433 first: vec![0x04; 8],
2434 second: Some(vec![0x05; 8]),
2435 },
2436 )]
2437 .iter()
2438 .cloned()
2439 .collect(),
2440 ),
2441 });
2442 let allow_list = [PublicKeyCredentialDescriptor {
2443 id: vec![5, 6, 7, 8],
2444 transports: vec![],
2445 }];
2446 let (extension, selected_cred) =
2447 extension.calculate(&shared_secret, &allow_list, Some(&puat))?;
2448
2449 assert_eq!(selected_cred, None);
2450 assert_eq!(
2451 extension,
2452 HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2453 // JS: salt1 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(1)])))
2454 salt1: vec![
2455 5, 240, 179, 178, 62, 126, 205, 172, 176, 105, 211, 13, 86, 210, 48,
2456 210, 225, 219, 234, 248, 16, 182, 52, 219, 92, 135, 97, 119, 107, 245,
2457 30, 226
2458 ],
2459 // JS: salt2 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(2)])))
2460 salt2: Some(vec![
2461 96, 107, 65, 234, 77, 176, 251, 24, 193, 188, 98, 23, 59, 240, 212, 6,
2462 104, 176, 40, 242, 104, 190, 32, 124, 226, 244, 19, 160, 8, 105, 253,
2463 106
2464 ]),
2465 calculated_hmac: Some(CalculatedHmacSecretExtension {
2466 public_key: client_key,
2467 // JS: aesKey = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "AES-CBC" }, false, ["encrypt"])
2468 // JS: salt_enc = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, aesKey, new Uint8Array([...salt1, ...salt2]))).slice(0, 64)
2469 // (Need to strip trailing padding block inserted by WebCrypto)
2470 salt_enc: vec![
2471 23, 99, 220, 93, 59, 246, 109, 157, 247, 33, 138, 91, 142, 40, 203,
2472 234, 96, 212, 26, 15, 56, 160, 191, 142, 138, 106, 2, 207, 219,
2473 180, 39, 31, 155, 232, 119, 179, 0, 65, 9, 37, 184, 194, 135, 173,
2474 187, 197, 51, 38, 68, 57, 197, 68, 249, 41, 143, 197, 46, 53, 72,
2475 60, 109, 33, 112, 175
2476 ],
2477 // JS: hmacKeyP1 = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
2478 // JS: salt_auth = new Uint8Array(await crypto.subtle.sign("HMAC", hmacKeyP1, salt_enc)).slice(0, 16)
2479 salt_auth: vec![
2480 27, 222, 224, 22, 170, 39, 171, 5, 98, 207, 176, 58, 23, 108, 223,
2481 174
2482 ],
2483 }),
2484 pin_protocol: None,
2485 }),
2486 );
2487
2488 Ok(())
2489 }
2490
2491 #[test]
2492 fn calculate_prf_eval_by_cred_pin_protocol_1() -> Result<(), AuthenticatorError> {
2493 let (shared_secret, client_key, puat) = make_test_secret(1)?;
2494 let cred_id = PublicKeyCredentialDescriptor {
2495 id: vec![1, 2, 3, 4],
2496 transports: vec![],
2497 };
2498 let extension =
2499 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2500 eval: Some(AuthenticationExtensionsPRFValues {
2501 first: vec![0x01; 8],
2502 second: Some(vec![0x02; 8]),
2503 }),
2504 eval_by_credential: Some(
2505 [
2506 (
2507 vec![9, 10, 11, 12],
2508 AuthenticationExtensionsPRFValues {
2509 first: vec![0x06; 8],
2510 second: Some(vec![0x07; 8]),
2511 },
2512 ),
2513 (
2514 cred_id.id.clone(),
2515 AuthenticationExtensionsPRFValues {
2516 first: vec![0x04; 8],
2517 second: Some(vec![0x05; 8]),
2518 },
2519 ),
2520 ]
2521 .iter()
2522 .cloned()
2523 .collect(),
2524 ),
2525 });
2526 let allow_list = [
2527 PublicKeyCredentialDescriptor {
2528 id: vec![5, 6, 7, 8],
2529 transports: vec![],
2530 },
2531 cred_id,
2532 PublicKeyCredentialDescriptor {
2533 id: vec![9, 10, 11, 12],
2534 transports: vec![],
2535 },
2536 ];
2537 let (extension, selected_cred) =
2538 extension.calculate(&shared_secret, &allow_list, Some(&puat))?;
2539
2540 assert_eq!(selected_cred, Some(&allow_list[1]));
2541 assert_eq!(
2542 extension,
2543 HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2544 // JS: salt1 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(4)])))
2545 salt1: vec![
2546 141, 49, 215, 240, 110, 193, 84, 27, 113, 153, 129, 108, 71, 59, 98, 5,
2547 209, 45, 190, 142, 47, 4, 72, 78, 217, 85, 99, 243, 192, 217, 232, 88
2548 ],
2549 // JS: salt2 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(5)])))
2550 salt2: Some(vec![
2551 156, 88, 127, 151, 204, 90, 145, 200, 207, 201, 106, 124, 19, 60, 29,
2552 115, 145, 197, 27, 148, 117, 72, 18, 4, 78, 187, 161, 122, 144, 245,
2553 67, 1
2554 ]),
2555 calculated_hmac: Some(CalculatedHmacSecretExtension {
2556 public_key: client_key,
2557 // JS: aesKey = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "AES-CBC" }, false, ["encrypt"])
2558 // JS: salt_enc = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, aesKey, new Uint8Array([...salt1, ...salt2]))).slice(0, 64)
2559 // (Need to strip trailing padding block inserted by WebCrypto)
2560 salt_enc: vec![
2561 191, 228, 209, 183, 255, 132, 169, 88, 82, 9, 102, 239, 99, 201,
2562 47, 15, 174, 24, 191, 30, 80, 230, 67, 237, 178, 112, 105, 243, 53,
2563 209, 25, 189, 32, 51, 75, 255, 176, 160, 82, 113, 250, 141, 83,
2564 130, 69, 156, 230, 91, 95, 17, 149, 11, 81, 40, 23, 42, 24, 33, 25,
2565 167, 210, 241, 238, 237
2566 ],
2567 // JS: hmacKeyP1 = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
2568 // JS: salt_auth = new Uint8Array(await crypto.subtle.sign("HMAC", hmacKeyP1, salt_enc)).slice(0, 16)
2569 salt_auth: vec![
2570 211, 87, 229, 38, 186, 254, 65, 2, 69, 166, 122, 30, 84, 77, 116,
2571 232
2572 ],
2573 }),
2574 pin_protocol: None,
2575 }),
2576 );
2577
2578 Ok(())
2579 }
2580
2581 #[test]
2582 fn calculate_prf_only_eval_by_cred_pin_protocol_1() -> Result<(), AuthenticatorError> {
2583 let (shared_secret, client_key, puat) = make_test_secret(1)?;
2584 let cred_id = PublicKeyCredentialDescriptor {
2585 id: vec![1, 2, 3, 4],
2586 transports: vec![],
2587 };
2588 let extension =
2589 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2590 eval: None,
2591 eval_by_credential: Some(
2592 [
2593 (
2594 vec![9, 10, 11, 12],
2595 AuthenticationExtensionsPRFValues {
2596 first: vec![0x06; 8],
2597 second: Some(vec![0x07; 8]),
2598 },
2599 ),
2600 (
2601 cred_id.id.clone(),
2602 AuthenticationExtensionsPRFValues {
2603 first: vec![0x04; 8],
2604 second: Some(vec![0x05; 8]),
2605 },
2606 ),
2607 ]
2608 .iter()
2609 .cloned()
2610 .collect(),
2611 ),
2612 });
2613 let allow_list = [
2614 PublicKeyCredentialDescriptor {
2615 id: vec![5, 6, 7, 8],
2616 transports: vec![],
2617 },
2618 cred_id,
2619 PublicKeyCredentialDescriptor {
2620 id: vec![9, 10, 11, 12],
2621 transports: vec![],
2622 },
2623 ];
2624 let (extension, selected_cred) =
2625 extension.calculate(&shared_secret, &allow_list, Some(&puat))?;
2626
2627 assert_eq!(selected_cred, Some(&allow_list[1]));
2628 assert_eq!(
2629 extension,
2630 HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2631 // JS: salt1 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(4)])))
2632 salt1: vec![
2633 141, 49, 215, 240, 110, 193, 84, 27, 113, 153, 129, 108, 71, 59, 98, 5,
2634 209, 45, 190, 142, 47, 4, 72, 78, 217, 85, 99, 243, 192, 217, 232, 88
2635 ],
2636 // JS: salt2 = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...new TextEncoder().encode("WebAuthn PRF"), 0, ...new Uint8Array(8).fill(5)])))
2637 salt2: Some(vec![
2638 156, 88, 127, 151, 204, 90, 145, 200, 207, 201, 106, 124, 19, 60, 29,
2639 115, 145, 197, 27, 148, 117, 72, 18, 4, 78, 187, 161, 122, 144, 245,
2640 67, 1
2641 ]),
2642 calculated_hmac: Some(CalculatedHmacSecretExtension {
2643 public_key: client_key,
2644 // JS: aesKey = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "AES-CBC" }, false, ["encrypt"])
2645 // JS: salt_enc = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, aesKey, new Uint8Array([...salt1, ...salt2]))).slice(0, 64)
2646 // (Need to strip trailing padding block inserted by WebCrypto)
2647 salt_enc: vec![
2648 191, 228, 209, 183, 255, 132, 169, 88, 82, 9, 102, 239, 99, 201,
2649 47, 15, 174, 24, 191, 30, 80, 230, 67, 237, 178, 112, 105, 243, 53,
2650 209, 25, 189, 32, 51, 75, 255, 176, 160, 82, 113, 250, 141, 83,
2651 130, 69, 156, 230, 91, 95, 17, 149, 11, 81, 40, 23, 42, 24, 33, 25,
2652 167, 210, 241, 238, 237
2653 ],
2654 // JS: hmacKeyP1 = await crypto.subtle.importKey("raw", new Uint8Array(32).map((b, i) => i), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
2655 // JS: salt_auth = new Uint8Array(await crypto.subtle.sign("HMAC", hmacKeyP1, salt_enc)).slice(0, 16)
2656 salt_auth: vec![
2657 211, 87, 229, 38, 186, 254, 65, 2, 69, 166, 122, 30, 84, 77, 116,
2658 232
2659 ],
2660 }),
2661 pin_protocol: None,
2662 }),
2663 );
2664
2665 Ok(())
2666 }
2667
2668 #[test]
2669 fn calculate_prf_unmatched_pin_protocol_1() -> Result<(), AuthenticatorError> {
2670 let (shared_secret, _, puat) = make_test_secret(1)?;
2671 let extension =
2672 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2673 eval: None,
2674 eval_by_credential: Some(
2675 [(
2676 vec![1, 2, 3, 4],
2677 AuthenticationExtensionsPRFValues {
2678 first: vec![0x04; 8],
2679 second: Some(vec![0x05; 8]),
2680 },
2681 )]
2682 .iter()
2683 .cloned()
2684 .collect(),
2685 ),
2686 });
2687 let allow_list = [PublicKeyCredentialDescriptor {
2688 id: vec![5, 6, 7, 8],
2689 transports: vec![],
2690 }];
2691 let (extension, selected_cred) =
2692 extension.calculate(&shared_secret, &allow_list, Some(&puat))?;
2693
2694 assert_eq!(selected_cred, None);
2695 assert_eq!(extension, HmacGetSecretOrPrf::PrfUnmatched);
2696
2697 Ok(())
2698 }
2699
2700 #[test]
2701 fn calculate_prf_unmatched_pin_protocol_2() -> Result<(), AuthenticatorError> {
2702 let (shared_secret, _, puat) = make_test_secret(2)?;
2703 let extension =
2704 HmacGetSecretOrPrf::PrfUninitialized(AuthenticationExtensionsPRFInputs {
2705 eval: None,
2706 eval_by_credential: Some(
2707 [(
2708 vec![1, 2, 3, 4],
2709 AuthenticationExtensionsPRFValues {
2710 first: vec![0x04; 8],
2711 second: Some(vec![0x05; 8]),
2712 },
2713 )]
2714 .iter()
2715 .cloned()
2716 .collect(),
2717 ),
2718 });
2719 let allow_list = [PublicKeyCredentialDescriptor {
2720 id: vec![5, 6, 7, 8],
2721 transports: vec![],
2722 }];
2723 let (extension, selected_cred) =
2724 extension.calculate(&shared_secret, &allow_list, Some(&puat))?;
2725
2726 assert_eq!(selected_cred, None);
2727 assert_eq!(extension, HmacGetSecretOrPrf::PrfUnmatched);
2728
2729 Ok(())
2730 }
2731
2732 #[test]
2733 fn finalize_result_hmac_get_secret_input_with_secret_output_becomes_client_output() {
2734 let result = finalize_result_with_hmac_secret_input_and_output(
2735 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2736 vec![],
2737 None,
2738 ))),
2739 Some(HmacSecretResponse::Secret(vec![0x01; ONE_OUTPUT_LEN_PP2])),
2740 )
2741 .expect("Failed to run test");
2742 assert_matches!(
2743 result.extensions,
2744 AuthenticationExtensionsClientOutputs {
2745 hmac_get_secret: Some(_),
2746 prf: None,
2747 ..
2748 }
2749 );
2750 }
2751
2752 #[test]
2753 fn finalize_result_prf_input_with_secret_output_becomes_results_output() {
2754 let result = finalize_result_with_hmac_secret_input_and_output(
2755 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension::new(
2756 vec![],
2757 None,
2758 ))),
2759 Some(HmacSecretResponse::Secret(vec![0x01; ONE_OUTPUT_LEN_PP2])),
2760 )
2761 .expect("Failed to run test");
2762 assert_matches!(
2763 result.extensions,
2764 AuthenticationExtensionsClientOutputs {
2765 hmac_get_secret: None,
2766 prf: Some(AuthenticationExtensionsPRFOutputs {
2767 enabled: None,
2768 results: Some(_),
2769 }),
2770 ..
2771 }
2772 );
2773 }
2774 }
2775
2776 #[test]
2777 #[should_panic(
2778 expected = "unreachable code: hmac-secret inputs from PRF already initialized"
2779 )]
2780 fn calculate_prf_conflict_1() {
2781 let (shared_secret, _) = make_test_secret_without_puat(2).unwrap();
2782 let extension = HmacGetSecretOrPrf::PrfUnmatched;
2783 extension.calculate(&shared_secret, &[], None).unwrap();
2784 }
2785
2786 #[test]
2787 #[should_panic(
2788 expected = "unreachable code: hmac-secret inputs from PRF already initialized"
2789 )]
2790 fn calculate_prf_conflict_2() {
2791 let (shared_secret, client_key) = make_test_secret_without_puat(2).unwrap();
2792 let extension = HmacGetSecretOrPrf::Prf(HmacSecretExtension {
2793 salt1: vec![],
2794 salt2: Some(vec![]),
2795 calculated_hmac: Some(CalculatedHmacSecretExtension {
2796 public_key: client_key,
2797 salt_enc: vec![],
2798 salt_auth: vec![],
2799 }),
2800 pin_protocol: None,
2801 });
2802 extension.calculate(&shared_secret, &[], None).unwrap();
2803 }
2804
2805 fn finalize_result_with_hmac_secret_input_and_output(
2806 hmac_secret_input: Option<HmacGetSecretOrPrf>,
2807 hmac_secret_response: Option<HmacSecretResponse>,
2808 ) -> Result<GetAssertionResult, CommandError> {
2809 let get_assertion = GetAssertion::new(
2810 ClientDataHash([0x01; 32]),
2811 RelyingParty::from("example.com"),
2812 vec![],
2813 Default::default(),
2814 GetAssertionExtensions {
2815 hmac_secret: hmac_secret_input,
2816 ..Default::default()
2817 },
2818 );
2819 let mut result = GetAssertionResult {
2820 assertion: Assertion {
2821 credentials: None,
2822 auth_data: AuthenticatorData {
2823 rp_id_hash: RpIdHash([0x01; 32]),
2824 flags: AuthenticatorDataFlags::empty(),
2825 counter: 0,
2826 credential_data: None,
2827 extensions: Extension {
2828 cred_protect: None,
2829 hmac_secret: hmac_secret_response,
2830 min_pin_length: None,
2831 },
2832 },
2833 signature: vec![],
2834 user: None,
2835 },
2836 attachment: AuthenticatorAttachment::Unknown,
2837 extensions: AuthenticationExtensionsClientOutputs::default(),
2838 };
2839
2840 let mut dev = Device::new_skipping_serialization("commands/get_assertion")
2841 .expect("Failed to create mock Device");
2842 let (shared_secret, _) = make_test_secret_without_puat(2)?;
2843 dev.set_shared_secret(shared_secret);
2844 get_assertion.finalize_result(&dev, &mut result);
2845 Ok(result)
2846 }
2847
2848 /// Encrypted salt output for pin protocol 2: iv || ct
2849 const ONE_OUTPUT_LEN_PP2: usize = 16 + 32;
2850
2851 #[test]
2852 fn finalize_result_no_input_with_no_output_becomes_no_client_output() {
2853 let result = finalize_result_with_hmac_secret_input_and_output(None, None)
2854 .expect("Failed to run test");
2855 assert_matches!(result.extensions.hmac_get_secret, None);
2856 }
2857
2858 #[test]
2859 fn finalize_result_no_input_with_secret_output_becomes_no_client_output() {
2860 let result = finalize_result_with_hmac_secret_input_and_output(
2861 None,
2862 Some(HmacSecretResponse::Secret(vec![0x01; ONE_OUTPUT_LEN_PP2])),
2863 )
2864 .expect("Failed to run test");
2865 assert_matches!(
2866 result.extensions,
2867 AuthenticationExtensionsClientOutputs {
2868 hmac_get_secret: None,
2869 prf: None,
2870 ..
2871 }
2872 );
2873 }
2874
2875 #[test]
2876 fn finalize_result_hmac_get_secret_input_with_no_output_becomes_no_client_output() {
2877 let result = finalize_result_with_hmac_secret_input_and_output(
2878 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2879 vec![],
2880 None,
2881 ))),
2882 None,
2883 )
2884 .expect("Failed to run test");
2885 assert_matches!(
2886 result.extensions,
2887 AuthenticationExtensionsClientOutputs {
2888 hmac_get_secret: None,
2889 prf: None,
2890 ..
2891 }
2892 );
2893 }
2894
2895 #[test]
2896 fn finalize_result_hmac_get_secret_input_with_confirmed_output_becomes_no_client_output() {
2897 let result = finalize_result_with_hmac_secret_input_and_output(
2898 Some(HmacGetSecretOrPrf::HmacGetSecret(HmacSecretExtension::new(
2899 vec![],
2900 None,
2901 ))),
2902 Some(HmacSecretResponse::Confirmed(true)),
2903 )
2904 .expect("Failed to run test");
2905 assert_matches!(
2906 result.extensions,
2907 AuthenticationExtensionsClientOutputs {
2908 hmac_get_secret: None,
2909 prf: None,
2910 ..
2911 }
2912 );
2913 }
2914
2915 #[test]
2916 fn finalize_result_prf_input_with_no_output_becomes_empty_client_output() {
2917 let result = finalize_result_with_hmac_secret_input_and_output(
2918 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension::new(
2919 vec![],
2920 None,
2921 ))),
2922 None,
2923 )
2924 .expect("Failed to run test");
2925 assert_matches!(
2926 result.extensions,
2927 AuthenticationExtensionsClientOutputs {
2928 hmac_get_secret: None,
2929 prf: Some(AuthenticationExtensionsPRFOutputs {
2930 enabled: None,
2931 results: None,
2932 }),
2933 ..
2934 }
2935 );
2936 }
2937
2938 #[test]
2939 fn finalize_result_prf_input_with_confirmed_output_becomes_empty_client_output() {
2940 let result = finalize_result_with_hmac_secret_input_and_output(
2941 Some(HmacGetSecretOrPrf::Prf(HmacSecretExtension::new(
2942 vec![],
2943 None,
2944 ))),
2945 Some(HmacSecretResponse::Confirmed(true)),
2946 )
2947 .expect("Failed to run test");
2948 assert_matches!(
2949 result.extensions,
2950 AuthenticationExtensionsClientOutputs {
2951 hmac_get_secret: None,
2952 prf: Some(AuthenticationExtensionsPRFOutputs {
2953 enabled: None,
2954 results: None,
2955 }),
2956 ..
2957 }
2958 );
2959 }
2960 }
2961 }