Debian Codegraph @

third_party/rust/authenticator/src/ctap2/preflight.rs

raw
1 use super::client_data::ClientDataHash;
2 use super::commands::get_assertion::{GetAssertion, GetAssertionExtensions, GetAssertionOptions};
3 use super::commands::{CtapResponse, PinUvAuthCommand, RequestCtap1, Retryable};
4 use crate::consts::{PARAMETER_SIZE, U2F_AUTHENTICATE, U2F_CHECK_IS_REGISTERED};
5 use crate::crypto::PinUvAuthToken;
6 use crate::ctap2::server::{PublicKeyCredentialDescriptor, RelyingParty};
7 use crate::errors::AuthenticatorError;
8 use crate::transport::errors::{ApduErrorStatus, HIDError};
9 use crate::transport::{FidoDevice, FidoProtocol, VirtualFidoDevice};
10 use crate::u2ftypes::CTAP1RequestAPDU;
11 use sha2::{Digest, Sha256};
12
13 /// This command is used to check which key_handle is valid for this
14 /// token. This is sent before a GetAssertion command, to determine which
15 /// is valid for a specific token and which key_handle GetAssertion
16 /// should send to the token. Or before a MakeCredential command, to determine
17 /// if this token is already registered or not.
18 #[derive(Debug)]
19 pub struct CheckKeyHandle<'assertion> {
20 pub key_handle: &'assertion [u8],
21 pub client_data_hash: &'assertion [u8],
22 pub rp: &'assertion RelyingParty,
23 }
24
25 type EmptyResponse = ();
26 impl CtapResponse for EmptyResponse {}
27
28 impl<'assertion> RequestCtap1 for CheckKeyHandle<'assertion> {
29 type Output = EmptyResponse;
30 type AdditionalInfo = ();
31
32 fn ctap1_format(&self) -> Result<(Vec<u8>, Self::AdditionalInfo), HIDError> {
33 // In theory, we only need to do this for up=true, for up=false, we could
34 // use U2F_DONT_ENFORCE_USER_PRESENCE_AND_SIGN instead and use the answer directly.
35 // But that would involve another major refactoring to implement, and so we accept
36 // that we will send the final request twice to the authenticator. Once with
37 // U2F_CHECK_IS_REGISTERED followed by U2F_DONT_ENFORCE_USER_PRESENCE_AND_SIGN.
38 let flags = U2F_CHECK_IS_REGISTERED;
39 let mut auth_data = Vec::with_capacity(2 * PARAMETER_SIZE + 1 + self.key_handle.len());
40
41 auth_data.extend_from_slice(self.client_data_hash);
42 auth_data.extend_from_slice(self.rp.hash().as_ref());
43 auth_data.extend_from_slice(&[self.key_handle.len() as u8]);
44 auth_data.extend_from_slice(self.key_handle);
45 let cmd = U2F_AUTHENTICATE;
46 let apdu = CTAP1RequestAPDU::serialize(cmd, flags, &auth_data)?;
47 Ok((apdu, ()))
48 }
49
50 fn handle_response_ctap1<Dev: FidoDevice>(
51 &self,
52 _dev: &mut Dev,
53 status: Result<(), ApduErrorStatus>,
54 _input: &[u8],
55 _add_info: &Self::AdditionalInfo,
56 ) -> Result<Self::Output, Retryable<HIDError>> {
57 // From the U2F-spec: https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-raw-message-formats-v1.2-ps-20170411.html#registration-request-message---u2f_register
58 // if the control byte is set to 0x07 by the FIDO Client, the U2F token is supposed to
59 // simply check whether the provided key handle was originally created by this token,
60 // and whether it was created for the provided application parameter. If so, the U2F
61 // token MUST respond with an authentication response
62 // message:error:test-of-user-presence-required (note that despite the name this
63 // signals a success condition). If the key handle was not created by this U2F
64 // token, or if it was created for a different application parameter, the token MUST
65 // respond with an authentication response message:error:bad-key-handle.
66 match status {
67 Ok(_) | Err(ApduErrorStatus::ConditionsNotSatisfied) => Ok(()),
68 Err(e) => Err(Retryable::Error(HIDError::ApduStatus(e))),
69 }
70 }
71
72 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
73 &self,
74 dev: &mut Dev,
75 ) -> Result<Self::Output, HIDError> {
76 dev.check_key_handle(self)
77 }
78 }
79
80 /// "pre-flight": In order to determine whether authenticatorMakeCredential's excludeList or
81 /// authenticatorGetAssertion's allowList contain credential IDs that are already
82 /// present on an authenticator, a platform typically invokes authenticatorGetAssertion
83 /// with the "up" option key set to false and optionally pinUvAuthParam one or more times.
84 /// For CTAP1, the resulting list will always be of length 1.
85 pub(crate) fn do_credential_list_filtering_ctap1<Dev: FidoDevice>(
86 dev: &mut Dev,
87 cred_list: &[PublicKeyCredentialDescriptor],
88 rp: &RelyingParty,
89 client_data_hash: &ClientDataHash,
90 ) -> Option<PublicKeyCredentialDescriptor> {
91 let key_handle = cred_list
92 .iter()
93 // key-handles in CTAP1 are limited to 255 bytes, but are not limited in CTAP2.
94 // Filter out key-handles that are too long (can happen if this is a CTAP2-request,
95 // but the token only speaks CTAP1).
96 .filter(|key_handle| key_handle.id.len() < 256)
97 .find_map(|key_handle| {
98 let check_command = CheckKeyHandle {
99 key_handle: key_handle.id.as_ref(),
100 client_data_hash: client_data_hash.as_ref(),
101 rp,
102 };
103 let res = dev.send_ctap1(&check_command);
104 match res {
105 Ok(_) => Some(key_handle.clone()),
106 _ => None,
107 }
108 });
109 key_handle
110 }
111
112 /// "pre-flight": In order to determine whether authenticatorMakeCredential's excludeList or
113 /// authenticatorGetAssertion's allowList contain credential IDs that are already
114 /// present on an authenticator, a platform typically invokes authenticatorGetAssertion
115 /// with the "up" option key set to false and optionally pinUvAuthParam one or more times.
116 pub(crate) fn do_credential_list_filtering_ctap2<Dev: FidoDevice>(
117 dev: &mut Dev,
118 cred_list: &[PublicKeyCredentialDescriptor],
119 rp: &RelyingParty,
120 pin_uv_auth_token: Option<PinUvAuthToken>,
121 ) -> Result<Vec<PublicKeyCredentialDescriptor>, AuthenticatorError> {
122 let info = dev
123 .get_authenticator_info()
124 .ok_or(HIDError::DeviceNotInitialized)?;
125 let mut cred_list = cred_list.to_vec();
126 // Step 1.0: Find out how long the exclude_list/allow_list is allowed to be
127 // If the token doesn't tell us, we assume a length of 1
128 let mut chunk_size = match info.max_credential_count_in_list {
129 // Length 0 is not allowed by the spec, so we assume the device can't be trusted, which means
130 // falling back to a chunk size of 1 as the bare minimum.
131 None | Some(0) => 1,
132 Some(x) => x,
133 };
134
135 // Step 1.1: The device only supports keys up to a certain length.
136 // Filter out all keys that are longer, because they can't be
137 // from this device anyways.
138 match info.max_credential_id_length {
139 None => { /* no-op */ }
140 // Length 0 is not allowed by the spec, so we assume the device can't be trusted, which means
141 // falling back to a chunk size of 1 as the bare minimum.
142 Some(0) => {
143 chunk_size = 1;
144 }
145 Some(max_key_length) => {
146 cred_list.retain(|k| k.id.len() <= max_key_length);
147 }
148 }
149
150 let chunked_list = cred_list.chunks(chunk_size);
151
152 // Step 2: If we have more than one chunk: Loop over all, doing GetAssertion
153 // and if one of them comes back with a success, use only that chunk.
154 let mut final_list = Vec::new();
155 for chunk in chunked_list {
156 let mut silent_assert = GetAssertion::new(
157 ClientDataHash(Sha256::digest("").into()),
158 rp.clone(),
159 chunk.to_vec(),
160 GetAssertionOptions {
161 user_verification: None, // defaults to Some(false) if puap is absent
162 user_presence: Some(false),
163 },
164 GetAssertionExtensions::default(),
165 );
166 silent_assert.set_pin_uv_auth_param(pin_uv_auth_token.clone())?;
167 match dev.send_msg(&silent_assert) {
168 Ok(mut response) => {
169 // This chunk contains a key_handle that is already known to the device.
170 // Filter out all credentials the device returned. Those are valid.
171 let credential_ids = response
172 .iter_mut()
173 .filter_map(|result| {
174 // CTAP 2.0 devices can omit the credentials in their response,
175 // if the given allowList was only 1 entry long. If so, we have
176 // to fill it in ourselfs.
177 if chunk.len() == 1 && result.assertion.credentials.is_none() {
178 Some(chunk[0].clone())
179 } else {
180 result.assertion.credentials.take()
181 }
182 })
183 .collect();
184 // Replace credential_id_list with the valid credentials
185 final_list = credential_ids;
186 break;
187 }
188 Err(_) => {
189 // No-op: Go to next chunk.
190 // NOTE: while we expect a StatusCode::NoCredentials error here, some tokens return
191 // other values.
192 continue;
193 }
194 }
195 }
196
197 // Step 3: Now ExcludeList/AllowList is either empty or has one batch with a 'known' credential.
198 // Send it as a normal Request and expect a "CredentialExcluded"-error in case of
199 // MakeCredential or a Success in case of GetAssertion
200 Ok(final_list)
201 }
202
203 pub(crate) fn silently_discover_credentials<Dev: FidoDevice>(
204 dev: &mut Dev,
205 cred_list: &[PublicKeyCredentialDescriptor],
206 rp: &RelyingParty,
207 client_data_hash: &ClientDataHash,
208 ) -> Vec<PublicKeyCredentialDescriptor> {
209 if dev.get_protocol() == FidoProtocol::CTAP2 {
210 if let Ok(cred_list) = do_credential_list_filtering_ctap2(dev, cred_list, rp, None) {
211 return cred_list;
212 }
213 } else if let Some(key_handle) =
214 do_credential_list_filtering_ctap1(dev, cred_list, rp, client_data_hash)
215 {
216 return vec![key_handle];
217 }
218 vec![]
219 }
220
221 #[cfg(test)]
222 pub mod tests {
223 use super::*;
224 use crate::{
225 crypto::{COSEAlgorithm, COSEEC2Key, COSEKey, COSEKeyType, Curve},
226 ctap2::{
227 attestation::{
228 AAGuid, AttestedCredentialData, AuthenticatorData, AuthenticatorDataFlags,
229 Extension,
230 },
231 commands::{CommandError, StatusCode},
232 server::{AuthenticationExtensionsClientOutputs, AuthenticatorAttachment, Transport},
233 },
234 transport::{
235 device_selector::tests::{make_device_simple_u2f, make_device_with_pin},
236 hid::HIDDevice,
237 platform::device::Device,
238 },
239 Assertion, GetAssertionResult,
240 };
241
242 fn new_relying_party(name: &str) -> RelyingParty {
243 RelyingParty {
244 id: String::from(name),
245 name: Some(String::from(name)),
246 }
247 }
248
249 fn new_silent_assert(
250 rp: &RelyingParty,
251 allow_list: &[PublicKeyCredentialDescriptor],
252 ) -> GetAssertion {
253 GetAssertion::new(
254 ClientDataHash(Sha256::digest("").into()),
255 rp.clone(),
256 allow_list.to_vec(),
257 GetAssertionOptions {
258 user_verification: None, // defaults to Some(false) if puap is absent
259 user_presence: Some(false),
260 },
261 GetAssertionExtensions::default(),
262 )
263 }
264
265 fn new_credential(fill: u8, repeat: usize) -> PublicKeyCredentialDescriptor {
266 PublicKeyCredentialDescriptor {
267 id: vec![fill; repeat],
268 transports: vec![Transport::USB],
269 }
270 }
271
272 fn new_assertion_response(
273 rp: &RelyingParty,
274 cred: Option<&PublicKeyCredentialDescriptor>,
275 ) -> GetAssertionResult {
276 let credential_data = cred.map(|cred| AttestedCredentialData {
277 aaguid: AAGuid::default(),
278 credential_id: cred.id.clone(),
279 credential_public_key: COSEKey {
280 alg: COSEAlgorithm::RS256,
281 key: COSEKeyType::EC2(COSEEC2Key {
282 curve: Curve::SECP256R1,
283 x: vec![],
284 y: vec![],
285 }),
286 },
287 });
288 GetAssertionResult {
289 assertion: Assertion {
290 credentials: cred.cloned(),
291 auth_data: AuthenticatorData {
292 rp_id_hash: rp.hash(),
293 flags: AuthenticatorDataFlags::empty(),
294 counter: 0,
295 credential_data,
296 extensions: Extension::default(),
297 },
298 signature: vec![],
299 user: None,
300 },
301 attachment: AuthenticatorAttachment::Platform,
302 extensions: AuthenticationExtensionsClientOutputs::default(),
303 }
304 }
305
306 fn new_check_key_handle<'a>(
307 rp: &'a RelyingParty,
308 client_data_hash: &'a ClientDataHash,
309 cred: &'a PublicKeyCredentialDescriptor,
310 ) -> CheckKeyHandle<'a> {
311 CheckKeyHandle {
312 key_handle: cred.id.as_ref(),
313 client_data_hash: client_data_hash.as_ref(),
314 rp,
315 }
316 }
317
318 #[test]
319 fn test_preflight_ctap1_empty() {
320 let mut dev = Device::new("preflight").unwrap();
321 make_device_simple_u2f(&mut dev);
322 let client_data_hash = ClientDataHash(Sha256::digest("").into());
323 let rp = new_relying_party("preflight test");
324 let res = silently_discover_credentials(&mut dev, &[], &rp, &client_data_hash);
325 assert!(res.is_empty());
326 }
327
328 #[test]
329 fn test_preflight_ctap1_multiple_replies() {
330 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
331 make_device_simple_u2f(&mut dev);
332 let rp = new_relying_party("preflight test");
333 let cdh = ClientDataHash(Sha256::digest("").into());
334 let allow_list = vec![
335 new_credential(4, 4),
336 new_credential(3, 4),
337 new_credential(2, 4),
338 new_credential(1, 4),
339 ];
340 dev.add_upcoming_ctap1_request(&new_check_key_handle(&rp, &cdh, &allow_list[0]));
341 dev.add_upcoming_ctap_error(HIDError::ApduStatus(
342 ApduErrorStatus::WrongData, // Not a registered cred
343 ));
344 dev.add_upcoming_ctap1_request(&new_check_key_handle(&rp, &cdh, &allow_list[1]));
345 dev.add_upcoming_ctap_error(HIDError::ApduStatus(
346 ApduErrorStatus::WrongData, // Not a registered cred
347 ));
348 dev.add_upcoming_ctap1_request(&new_check_key_handle(&rp, &cdh, &allow_list[2]));
349 dev.add_upcoming_ctap_response(()); // Valid credential - the code exits here now and doesn't even look at the last one
350
351 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &cdh);
352 assert_eq!(res, vec![allow_list[2].clone()]);
353 }
354
355 #[test]
356 fn test_preflight_ctap1_too_long_entries() {
357 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
358 make_device_simple_u2f(&mut dev);
359 let rp = new_relying_party("preflight test");
360 let cdh = ClientDataHash(Sha256::digest("").into());
361 let allow_list = vec![
362 new_credential(4, 300), // ctap1 limit is 256
363 new_credential(3, 4),
364 new_credential(2, 4),
365 new_credential(1, 4),
366 ];
367 // allow_list[0] is filtered out due to its size
368 dev.add_upcoming_ctap1_request(&new_check_key_handle(&rp, &cdh, &allow_list[1]));
369 dev.add_upcoming_ctap_error(HIDError::ApduStatus(
370 ApduErrorStatus::WrongData, // Not a registered cred
371 ));
372 dev.add_upcoming_ctap1_request(&new_check_key_handle(&rp, &cdh, &allow_list[2]));
373 dev.add_upcoming_ctap_response(()); // Valid credential - the code exits here now and doesn't even look at the last one
374
375 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &cdh);
376 assert_eq!(res, vec![allow_list[2].clone()]);
377 }
378
379 #[test]
380 fn test_preflight_ctap2_empty() {
381 let mut dev = Device::new("preflight").unwrap();
382 make_device_with_pin(&mut dev);
383 let rp = new_relying_party("preflight test");
384 let client_data_hash = ClientDataHash(Sha256::digest("").into());
385 let res = silently_discover_credentials(&mut dev, &[], &rp, &client_data_hash);
386 assert!(res.is_empty());
387 }
388
389 #[test]
390 fn test_preflight_ctap20_no_cred_data() {
391 // CTAP2.0 tokens are allowed to not send any credential-data in their
392 // response, if the allow-list is of length one. See https://github.com/mozilla/authenticator-rs/issues/319
393 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
394 make_device_with_pin(&mut dev);
395 let rp = new_relying_party("preflight test");
396 let client_data_hash = ClientDataHash(Sha256::digest("").into());
397 let allow_list = vec![new_credential(1, 4)];
398 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &allow_list));
399 dev.add_upcoming_ctap_response(vec![new_assertion_response(&rp, None)]);
400 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
401 assert_eq!(res, allow_list);
402 }
403
404 #[test]
405 fn test_preflight_ctap2_one_valid_entry() {
406 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
407 make_device_with_pin(&mut dev);
408 let rp = new_relying_party("preflight test");
409 let client_data_hash = ClientDataHash(Sha256::digest("").into());
410 let allow_list = vec![new_credential(1, 4)];
411 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &allow_list));
412 dev.add_upcoming_ctap_response(vec![new_assertion_response(&rp, Some(&allow_list[0]))]);
413 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
414 assert_eq!(res, allow_list);
415 }
416
417 #[test]
418 fn test_preflight_ctap2_multiple_entries() {
419 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
420 make_device_with_pin(&mut dev);
421 let rp = new_relying_party("preflight test");
422 let client_data_hash = ClientDataHash(Sha256::digest("").into());
423 let allow_list = vec![
424 new_credential(3, 4),
425 new_credential(2, 4),
426 new_credential(1, 4),
427 new_credential(0, 4),
428 ];
429 // Our test device doesn't say how many allow_list-entries it supports, so our code
430 // defaults to one. Thus three requests, with three answers. Only one of them
431 // valid.
432 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &[allow_list[0].clone()]));
433 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &[allow_list[1].clone()]));
434 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &[allow_list[2].clone()]));
435 dev.add_upcoming_ctap_error(HIDError::Command(CommandError::StatusCode(
436 StatusCode::NoCredentials,
437 None,
438 )));
439 dev.add_upcoming_ctap_error(HIDError::Command(CommandError::StatusCode(
440 StatusCode::NoCredentials,
441 None,
442 )));
443 dev.add_upcoming_ctap_response(vec![new_assertion_response(&rp, Some(&allow_list[2]))]);
444 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
445 assert_eq!(res, vec![allow_list[2].clone()]);
446 }
447
448 #[test]
449 fn test_preflight_ctap2_multiple_replies() {
450 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
451 make_device_with_pin(&mut dev);
452 let rp = new_relying_party("preflight test");
453 let client_data_hash = ClientDataHash(Sha256::digest("").into());
454 let allow_list = vec![
455 new_credential(4, 4),
456 new_credential(3, 4),
457 new_credential(2, 4),
458 new_credential(1, 4),
459 ];
460 let mut info = dev.get_authenticator_info().unwrap().clone();
461 info.max_credential_count_in_list = Some(5);
462 dev.set_authenticator_info(info);
463 // Our test device now says that it supports 5 allow_list-entries,
464 // so we can send all of them in one request
465 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &allow_list));
466 dev.add_upcoming_ctap_response(vec![
467 new_assertion_response(&rp, Some(&allow_list[1])),
468 new_assertion_response(&rp, Some(&allow_list[2])),
469 new_assertion_response(&rp, Some(&allow_list[3])),
470 ]);
471 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
472 assert_eq!(res, allow_list[1..].to_vec());
473 }
474
475 #[test]
476 fn test_preflight_ctap2_multiple_replies_some_invalid() {
477 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
478 make_device_with_pin(&mut dev);
479 let rp = new_relying_party("preflight test");
480 let client_data_hash = ClientDataHash(Sha256::digest("").into());
481 let allow_list = vec![
482 new_credential(4, 4),
483 new_credential(3, 4),
484 new_credential(2, 4),
485 new_credential(1, 4),
486 ];
487 let mut info = dev.get_authenticator_info().unwrap().clone();
488 info.max_credential_count_in_list = Some(5);
489 dev.set_authenticator_info(info);
490 // Our test device now says that it supports 5 allow_list-entries,
491 // so we can send all of them in one request
492 dev.add_upcoming_ctap2_request(&new_silent_assert(&rp, &allow_list));
493 dev.add_upcoming_ctap_response(vec![
494 new_assertion_response(&rp, Some(&allow_list[1])),
495 new_assertion_response(&rp, None), // This will be ignored
496 new_assertion_response(&rp, Some(&allow_list[2])),
497 new_assertion_response(&rp, None), // This will be ignored
498 ]);
499 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
500 assert_eq!(res, allow_list[1..=2].to_vec());
501 }
502
503 #[test]
504 fn test_preflight_ctap2_too_long_entries() {
505 let mut dev = Device::new_skipping_serialization("preflight").unwrap();
506 make_device_with_pin(&mut dev);
507 let rp = new_relying_party("preflight test");
508 let client_data_hash = ClientDataHash(Sha256::digest("").into());
509 let allow_list = vec![
510 new_credential(4, 50), // too long
511 new_credential(3, 4),
512 new_credential(2, 50), // too long
513 new_credential(1, 4),
514 ];
515 let mut info = dev.get_authenticator_info().unwrap().clone();
516 info.max_credential_count_in_list = Some(5);
517 info.max_credential_id_length = Some(20);
518 dev.set_authenticator_info(info);
519 // Our test device now says that it supports 5 allow_list-entries,
520 // so we can send all of them in one request, except for those
521 // that got pre-filtered, as they were too long.
522 dev.add_upcoming_ctap2_request(&new_silent_assert(
523 &rp,
524 &[allow_list[1].clone(), allow_list[3].clone()],
525 ));
526 dev.add_upcoming_ctap_response(vec![new_assertion_response(&rp, Some(&allow_list[1]))]);
527 let res = silently_discover_credentials(&mut dev, &allow_list, &rp, &client_data_hash);
528 assert_eq!(res, vec![allow_list[1].clone()]);
529 }
530 }