Debian Codegraph @

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

raw
1 pub mod attestation;
2 pub mod client_data;
3 #[allow(dead_code)] // TODO(MS): Remove me asap
4 pub mod commands;
5 pub mod preflight;
6 pub mod server;
7 pub(crate) mod utils;
8
9 use crate::authenticatorservice::{RegisterArgs, SignArgs};
10 use crate::crypto::COSEAlgorithm;
11 use crate::ctap2::client_data::ClientDataHash;
12 use crate::ctap2::commands::authenticator_config::{
13 AuthConfigCommand, AuthConfigResult, AuthenticatorConfig,
14 };
15 use crate::ctap2::commands::bio_enrollment::{
16 BioEnrollment, BioEnrollmentCommand, BioEnrollmentResult, FingerprintSensorInfo,
17 };
18 use crate::ctap2::commands::client_pin::{
19 ChangeExistingPin, Pin, PinError, PinUvAuthTokenPermission, SetNewPin,
20 };
21 use crate::ctap2::commands::credential_management::{
22 CredManagementCommand, CredentialList, CredentialListEntry, CredentialManagement,
23 CredentialManagementResult, CredentialRpListEntry,
24 };
25 use crate::ctap2::commands::get_assertion::{GetAssertion, GetAssertionOptions};
26 use crate::ctap2::commands::make_credentials::{
27 dummy_make_credentials_cmd, MakeCredentials, MakeCredentialsOptions,
28 };
29 use crate::ctap2::commands::reset::Reset;
30 use crate::ctap2::commands::{
31 repackage_pin_errors, CommandError, PinUvAuthCommand, PinUvAuthResult, RequestCtap2, StatusCode,
32 };
33 use crate::ctap2::preflight::{
34 do_credential_list_filtering_ctap1, do_credential_list_filtering_ctap2,
35 silently_discover_credentials,
36 };
37 use crate::ctap2::server::{
38 CredentialProtectionPolicy, RelyingParty, ResidentKeyRequirement, UserVerificationRequirement,
39 };
40 use crate::errors::{AuthenticatorError, UnsupportedOption};
41 use crate::statecallback::StateCallback;
42 use crate::status_update::{send_status, BioEnrollmentCmd, CredManagementCmd, InteractiveUpdate};
43 use crate::transport::device_selector::{Device, DeviceSelectorEvent};
44 use crate::transport::{errors::HIDError, hid::HIDDevice, FidoDevice, FidoDeviceIO, FidoProtocol};
45 use crate::{ManageResult, ResetResult, StatusPinUv, StatusUpdate};
46 use std::sync::mpsc::{channel, RecvError, Sender};
47 use std::thread;
48 use std::time::Duration;
49
50 use self::commands::get_info::AuthenticatorVersion;
51
52 macro_rules! unwrap_option {
53 ($item: expr, $callback: expr) => {
54 match $item {
55 Some(r) => r,
56 None => {
57 $callback.call(Err(AuthenticatorError::Platform));
58 return false;
59 }
60 }
61 };
62 }
63
64 macro_rules! unwrap_result {
65 ($item: expr, $callback: expr) => {
66 match $item {
67 Ok(r) => r,
68 Err(e) => {
69 $callback.call(Err(e.into()));
70 return false;
71 }
72 }
73 };
74 }
75
76 macro_rules! handle_errors {
77 ($error: expr, $status: expr, $callback: expr, $pin_uv_auth_result: expr, $skip_uv: expr) => {
78 let mut _dummy_skip_puap = false;
79 let mut _dummy_cached_puat = false;
80 handle_errors!(
81 $error,
82 $status,
83 $callback,
84 $pin_uv_auth_result,
85 $skip_uv,
86 _dummy_skip_puap,
87 _dummy_cached_puat
88 )
89 };
90 ($error: expr, $status: expr, $callback: expr, $pin_uv_auth_result: expr, $skip_uv: expr, $skip_puap: expr) => {
91 let mut _dummy_cached_puat = false;
92 handle_errors!(
93 $error,
94 $status,
95 $callback,
96 $pin_uv_auth_result,
97 $skip_uv,
98 $skip_puap,
99 _dummy_cached_puat
100 )
101 };
102 ($error: expr, $status: expr, $callback: expr, $pin_uv_auth_result: expr, $skip_uv: expr, $skip_puap: expr, $cached_puat: expr) => {
103 match $error {
104 HIDError::Command(CommandError::StatusCode(StatusCode::ChannelBusy, _)) => {
105 // Channel busy. Client SHOULD retry the request after a short delay.
106 thread::sleep(Duration::from_millis(100));
107 continue;
108 }
109 HIDError::Command(CommandError::StatusCode(StatusCode::OperationDenied, _))
110 | HIDError::Command(CommandError::StatusCode(StatusCode::PinAuthInvalid, _))
111 if matches!($pin_uv_auth_result, PinUvAuthResult::UsingInternalUv) =>
112 {
113 // This should only happen for CTAP2.0 tokens that use internal UV and failed
114 // (e.g. wrong fingerprint used), while doing GetAssertion or MakeCredentials.
115 send_status(
116 &$status,
117 StatusUpdate::PinUvError(StatusPinUv::InvalidUv(None)),
118 );
119 $skip_puap = false;
120 continue;
121 }
122 HIDError::Command(CommandError::StatusCode(StatusCode::PinRequired, _))
123 if matches!($pin_uv_auth_result, PinUvAuthResult::UsingInternalUv) =>
124 {
125 // This should only happen for CTAP2.0 tokens that use internal UV and failed
126 // repeatedly, so that we have to fall back to PINs
127 $skip_uv = true;
128 $skip_puap = false;
129 continue;
130 }
131 HIDError::Command(CommandError::StatusCode(StatusCode::UvBlocked, _))
132 if matches!(
133 $pin_uv_auth_result,
134 PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(..)
135 ) =>
136 {
137 // This should only happen for CTAP2.1 tokens that use internal UV and failed
138 // repeatedly, so that we have to fall back to PINs
139 $skip_uv = true;
140 $skip_puap = false;
141 continue;
142 }
143 HIDError::Command(CommandError::StatusCode(StatusCode::CredentialExcluded, _)) => {
144 $callback.call(Err(AuthenticatorError::CredentialExcluded));
145 break;
146 }
147 HIDError::Command(CommandError::StatusCode(StatusCode::PinAuthInvalid, _))
148 if $cached_puat =>
149 {
150 // We used the cached PUAT, but it was invalid. So we just try again
151 // without the cached one and potentially trigger a new PIN/UV entry from
152 // the user. This happens e.g. if the PUAT expires, or we get an all-zeros
153 // PUAT from outside for whatever reason, etc.
154 $cached_puat = false;
155 $skip_puap = false;
156 continue;
157 }
158 e => {
159 warn!("error happened: {e}");
160 $callback.call(Err(AuthenticatorError::HIDError(e)));
161 break;
162 }
163 }
164 };
165 }
166
167 fn ask_user_for_pin(
168 was_invalid: bool,
169 retries: Option<u8>,
170 status: &Sender<StatusUpdate>,
171 ) -> Result<Pin, AuthenticatorError> {
172 info!("PIN Error that requires user interaction detected. Sending it back and waiting for a reply");
173 let (tx, rx) = channel();
174 if was_invalid {
175 send_status(
176 status,
177 crate::StatusUpdate::PinUvError(StatusPinUv::InvalidPin(tx, retries)),
178 );
179 } else {
180 send_status(
181 status,
182 crate::StatusUpdate::PinUvError(StatusPinUv::PinRequired(tx)),
183 );
184 }
185 match rx.recv() {
186 Ok(pin) => Ok(pin),
187 Err(RecvError) => {
188 // recv() can only fail, if the other side is dropping the Sender.
189 info!("Callback dropped the channel. Aborting.");
190 Err(AuthenticatorError::CancelledByUser)
191 }
192 }
193 }
194
195 /// Try to fetch PinUvAuthToken from the device and derive from it PinUvAuthParam.
196 /// Prefer UV, fallback to PIN.
197 /// Prefer newer pinUvAuth-methods, if supported by the device.
198 fn get_pin_uv_auth_param<Dev: FidoDevice, T: PinUvAuthCommand + RequestCtap2>(
199 cmd: &mut T,
200 dev: &mut Dev,
201 permission: PinUvAuthTokenPermission,
202 skip_uv: bool,
203 uv_req: UserVerificationRequirement,
204 alive: &dyn Fn() -> bool,
205 pin: &Option<Pin>,
206 ) -> Result<PinUvAuthResult, AuthenticatorError> {
207 // CTAP 2.1 is very specific that the request should either include pinUvAuthParam
208 // OR uv=true, but not both at the same time. We now have to decide which (if either)
209 // to send. We may omit both values. Will never send an explicit uv=false, because
210 // a) this is the default, and
211 // b) some CTAP 2.0 authenticators return UnsupportedOption when uv=false.
212
213 // We ensure both pinUvAuthParam and uv are not set to start.
214 cmd.set_pin_uv_auth_param(None)?;
215 cmd.set_uv_option(None);
216
217 // Skip user verification if we're using CTAP1 or if the device does not support CTAP2.
218 let info = match (dev.get_protocol(), dev.get_authenticator_info()) {
219 (FidoProtocol::CTAP2, Some(info)) => info,
220 _ => return Ok(PinUvAuthResult::DeviceIsCtap1),
221 };
222
223 // Only use UV, if the device supports it and we don't skip it
224 // which happens as a fallback, if UV-usage failed too many times
225 // Note: In theory, we could also repeatedly query GetInfo here and check
226 // if uv is set to Some(true), as tokens should set it to Some(false)
227 // if UV is blocked (too many failed attempts). But the CTAP2.0-spec is
228 // vague and I don't trust all tokens to implement it that way. So we
229 // keep track of it ourselves, using `skip_uv`.
230 let supports_uv = info.options.user_verification == Some(true);
231 let supports_pin = info.options.client_pin.is_some();
232 let pin_configured = info.options.client_pin == Some(true);
233
234 // Check if the combination of device-protection and request-options
235 // are allowing for 'discouraged', meaning no auth required.
236 if cmd.can_skip_user_verification(info, uv_req) {
237 return Ok(PinUvAuthResult::NoAuthRequired);
238 }
239
240 // Device does not support any (remaining) auth-method
241 if (skip_uv || !supports_uv) && !supports_pin {
242 if supports_uv && uv_req == UserVerificationRequirement::Required {
243 // We should always set the uv option in the Required case, but the CTAP 2.1 spec
244 // says 'Platforms MUST NOT include the "uv" option key if the authenticator does
245 // not support built-in user verification.' This is to work around some CTAP 2.0
246 // authenticators which incorrectly error out with CTAP2_ERR_UNSUPPORTED_OPTION
247 // when the "uv" option is set. The RP that requested UV will (hopefully) reject our
248 // response in the !supports_uv case.
249 cmd.set_uv_option(Some(true));
250 }
251 return Ok(PinUvAuthResult::NoAuthTypeSupported);
252 }
253
254 // Device supports PINs, but a PIN is not configured. Signal that we
255 // can complete the operation if the user sets a PIN first.
256 if (skip_uv || !supports_uv) && !pin_configured {
257 return Err(AuthenticatorError::PinError(PinError::PinNotSet));
258 }
259
260 if info.options.pin_uv_auth_token == Some(true) {
261 if !skip_uv && supports_uv {
262 // CTAP 2.1 - UV
263 let pin_auth_token = dev
264 .get_pin_uv_auth_token_using_uv_with_permissions(permission, cmd.get_rp_id(), alive)
265 .map_err(|e| repackage_pin_errors(dev, e))?;
266 cmd.set_pin_uv_auth_param(Some(pin_auth_token.clone()))?;
267 Ok(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(pin_auth_token))
268 } else {
269 // CTAP 2.1 - PIN
270 // We did not take the `!skip_uv && supports_uv` branch, so we have
271 // `(skip_uv || !supports_uv)`. Moreover we did not exit early in the
272 // `(skip_uv || !supports_uv) && !pin_configured` case. So we have
273 // `pin_configured`.
274 let pin_auth_token = dev
275 .get_pin_uv_auth_token_using_pin_with_permissions(
276 pin,
277 permission,
278 cmd.get_rp_id(),
279 alive,
280 )
281 .map_err(|e| repackage_pin_errors(dev, e))?;
282 cmd.set_pin_uv_auth_param(Some(pin_auth_token.clone()))?;
283 Ok(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingPinWithPermissions(pin_auth_token))
284 }
285 } else {
286 // CTAP 2.0 fallback
287 if !skip_uv && supports_uv && pin.is_none() {
288 // If the device supports internal user-verification (e.g. fingerprints),
289 // skip PIN-stuff
290
291 // We may need the shared secret for HMAC-extension, so we
292 // have to establish one
293 if info.supports_hmac_secret() {
294 let _shared_secret = dev.establish_shared_secret(alive)?;
295 }
296 // CTAP 2.1, Section 6.1.1, Step 1.1.2.1.2.
297 cmd.set_uv_option(Some(true));
298 return Ok(PinUvAuthResult::UsingInternalUv);
299 }
300
301 let pin_auth_token = dev
302 .get_pin_token(pin, alive)
303 .map_err(|e| repackage_pin_errors(dev, e))?;
304 cmd.set_pin_uv_auth_param(Some(pin_auth_token.clone()))?;
305 Ok(PinUvAuthResult::SuccessGetPinToken(pin_auth_token))
306 }
307 }
308
309 /// PUAP, as per spec: PinUvAuthParam
310 /// Determines, if we need to establish a PinUvAuthParam, based on the
311 /// capabilities of the device and the incoming request.
312 /// If it is needed, tries to establish one and save it inside the Request.
313 /// Returns Ok() if we can proceed with sending the actual Request to
314 /// the device, Err() otherwise.
315 /// Handles asking the user for a PIN, if needed and sending StatusUpdates
316 /// regarding PIN and UV usage.
317 #[allow(clippy::too_many_arguments)]
318 fn determine_puap_if_needed<Dev: FidoDevice, T: PinUvAuthCommand + RequestCtap2>(
319 cmd: &mut T,
320 dev: &mut Dev,
321 mut skip_uv: bool,
322 permission: PinUvAuthTokenPermission,
323 uv_req: UserVerificationRequirement,
324 status: &Sender<StatusUpdate>,
325 alive: &dyn Fn() -> bool,
326 pin: &mut Option<Pin>,
327 ) -> Result<PinUvAuthResult, AuthenticatorError> {
328 while alive() {
329 debug!("-----------------------------------------------------------------");
330 debug!("Getting pinUvAuthParam");
331 match get_pin_uv_auth_param(cmd, dev, permission, skip_uv, uv_req, alive, pin) {
332 Ok(r) => {
333 return Ok(r);
334 }
335
336 Err(AuthenticatorError::PinError(PinError::PinRequired)) => {
337 let new_pin = ask_user_for_pin(false, None, status)?;
338 *pin = Some(new_pin);
339 skip_uv = true;
340 continue;
341 }
342 Err(AuthenticatorError::PinError(PinError::InvalidPin(retries))) => {
343 let new_pin = ask_user_for_pin(true, retries, status)?;
344 *pin = Some(new_pin);
345 continue;
346 }
347 Err(AuthenticatorError::PinError(PinError::InvalidUv(retries))) => {
348 if retries == Some(0) {
349 skip_uv = true;
350 }
351 send_status(
352 status,
353 StatusUpdate::PinUvError(StatusPinUv::InvalidUv(retries)),
354 )
355 }
356 Err(e @ AuthenticatorError::PinError(PinError::PinAuthBlocked)) => {
357 send_status(
358 status,
359 StatusUpdate::PinUvError(StatusPinUv::PinAuthBlocked),
360 );
361 error!("Error when determining pinAuth: {:?}", e);
362 return Err(e);
363 }
364 Err(e @ AuthenticatorError::PinError(PinError::PinBlocked)) => {
365 send_status(status, StatusUpdate::PinUvError(StatusPinUv::PinBlocked));
366 error!("Error when determining pinAuth: {:?}", e);
367 return Err(e);
368 }
369 Err(e @ AuthenticatorError::PinError(PinError::PinNotSet)) => {
370 send_status(status, StatusUpdate::PinUvError(StatusPinUv::PinNotSet));
371 error!("Error when determining pinAuth: {:?}", e);
372 return Err(e);
373 }
374 Err(AuthenticatorError::PinError(PinError::UvBlocked)) => {
375 skip_uv = true;
376 send_status(status, StatusUpdate::PinUvError(StatusPinUv::UvBlocked))
377 }
378 // Used for CTAP2.0 UV (fingerprints)
379 Err(AuthenticatorError::PinError(PinError::PinAuthInvalid)) => {
380 skip_uv = true;
381 send_status(
382 status,
383 StatusUpdate::PinUvError(StatusPinUv::InvalidUv(None)),
384 )
385 }
386 Err(e) => {
387 error!("Error when determining pinAuth: {:?}", e);
388 return Err(e);
389 }
390 }
391 }
392 Err(AuthenticatorError::CancelledByUser)
393 }
394
395 pub fn register<Dev: FidoDevice>(
396 dev: &mut Dev,
397 args: RegisterArgs,
398 status: Sender<crate::StatusUpdate>,
399 callback: StateCallback<crate::Result<crate::RegisterResult>>,
400 alive: &dyn Fn() -> bool,
401 ) -> bool {
402 let mut options = MakeCredentialsOptions::default();
403
404 if dev.get_protocol() == FidoProtocol::CTAP2 {
405 let info = match dev.get_authenticator_info() {
406 Some(info) => info,
407 None => {
408 callback.call(Err(HIDError::DeviceNotInitialized.into()));
409 return false;
410 }
411 };
412
413 // Set options based on the arguments and the device info.
414 // The user verification option will be set in `determine_puap_if_needed`.
415 options.resident_key = match args.resident_key_req {
416 ResidentKeyRequirement::Required => Some(true),
417 ResidentKeyRequirement::Preferred => {
418 // Use a resident key if the authenticator supports it
419 Some(info.options.resident_key)
420 }
421 ResidentKeyRequirement::Discouraged => Some(false),
422 }
423 } else {
424 // Check that the request can be processed by a CTAP1 device.
425 // See CTAP 2.1 Section 10.2. Some additional checks are performed in
426 // MakeCredentials::RequestCtap1
427 if args.resident_key_req == ResidentKeyRequirement::Required {
428 callback.call(Err(AuthenticatorError::UnsupportedOption(
429 UnsupportedOption::ResidentKey,
430 )));
431 return false;
432 }
433 if args.user_verification_req == UserVerificationRequirement::Required {
434 callback.call(Err(AuthenticatorError::UnsupportedOption(
435 UnsupportedOption::UserVerification,
436 )));
437 return false;
438 }
439 if !args
440 .pub_cred_params
441 .iter()
442 .any(|x| x.alg == COSEAlgorithm::ES256)
443 {
444 callback.call(Err(AuthenticatorError::UnsupportedOption(
445 UnsupportedOption::PubCredParams,
446 )));
447 return false;
448 }
449 }
450
451 // Client extension processing for credProtect:
452 // "When enforceCredentialProtectionPolicy is true, and credentialProtectionPolicy's value is
453 // [not "Optional"], the platform SHOULD NOT create the credential in a way that does not
454 // implement the requested protection policy. (For example, by creating it on an authenticator
455 // that does not support this extension.)"
456 let dev_supports_cred_protect = dev
457 .get_authenticator_info()
458 .map_or(false, |info| info.supports_cred_protect());
459 if args.extensions.enforce_credential_protection_policy == Some(true)
460 && args.extensions.credential_protection_policy
461 != Some(CredentialProtectionPolicy::UserVerificationOptional)
462 && !dev_supports_cred_protect
463 {
464 callback.call(Err(AuthenticatorError::UnsupportedOption(
465 UnsupportedOption::CredProtect,
466 )));
467 return false;
468 }
469
470 let mut makecred = MakeCredentials::new(
471 ClientDataHash(args.client_data_hash),
472 args.relying_party,
473 Some(args.user),
474 args.pub_cred_params,
475 args.exclude_list,
476 options,
477 args.extensions.into(),
478 );
479
480 let mut skip_uv = false;
481 let mut pin = args.pin;
482 while alive() {
483 // Requesting both because pre-flighting (credential list filtering)
484 // can potentially send GetAssertion-commands
485 let permissions =
486 PinUvAuthTokenPermission::MakeCredential | PinUvAuthTokenPermission::GetAssertion;
487
488 let pin_uv_auth_result = unwrap_result!(
489 determine_puap_if_needed(
490 &mut makecred,
491 dev,
492 skip_uv,
493 permissions,
494 args.user_verification_req,
495 &status,
496 alive,
497 &mut pin,
498 ),
499 callback
500 );
501 // Do "pre-flight": Filter the exclude-list
502 if dev.get_protocol() == FidoProtocol::CTAP2 {
503 makecred.exclude_list = unwrap_result!(
504 do_credential_list_filtering_ctap2(
505 dev,
506 &makecred.exclude_list,
507 &makecred.rp,
508 pin_uv_auth_result.get_pin_uv_auth_token(),
509 ),
510 callback
511 );
512 } else {
513 let key_handle = do_credential_list_filtering_ctap1(
514 dev,
515 &makecred.exclude_list,
516 &makecred.rp,
517 &makecred.client_data_hash,
518 );
519 // That handle was already registered with the token
520 if key_handle.is_some() {
521 // Now we need to send a dummy registration request, to make the token blink
522 // Spec says "dummy appid and invalid challenge". We use the same, as we do for
523 // making the token blink upon device selection.
524 send_status(&status, crate::StatusUpdate::PresenceRequired);
525 let msg = dummy_make_credentials_cmd();
526 let _ = dev.send_msg_cancellable(&msg, alive); // Ignore answer, return "CredentialExcluded"
527 callback.call(Err(AuthenticatorError::CredentialExcluded));
528 return false;
529 }
530 }
531
532 debug!("------------------------------------------------------------------");
533 debug!("{makecred:?} using {pin_uv_auth_result:?}");
534 debug!("------------------------------------------------------------------");
535 send_status(&status, crate::StatusUpdate::PresenceRequired);
536 let resp = dev.send_msg_cancellable(&makecred, alive);
537 match resp {
538 Ok(result) => {
539 callback.call(Ok(result));
540 return true;
541 }
542 Err(e) => {
543 handle_errors!(e, status, callback, pin_uv_auth_result, skip_uv);
544 }
545 }
546 }
547 false
548 }
549
550 pub fn sign<Dev: FidoDevice>(
551 dev: &mut Dev,
552 args: SignArgs,
553 status: Sender<crate::StatusUpdate>,
554 callback: StateCallback<crate::Result<crate::SignResult>>,
555 alive: &dyn Fn() -> bool,
556 ) -> bool {
557 if dev.get_protocol() == FidoProtocol::CTAP1 {
558 // Check that the request can be processed by a CTAP1 device.
559 // See CTAP 2.1 Section 10.3. Some additional checks are performed in
560 // GetAssertion::RequestCtap1
561 if args.user_verification_req == UserVerificationRequirement::Required {
562 callback.call(Err(AuthenticatorError::UnsupportedOption(
563 UnsupportedOption::UserVerification,
564 )));
565 return false;
566 }
567 if args.allow_list.is_empty() {
568 callback.call(Err(AuthenticatorError::UnsupportedOption(
569 UnsupportedOption::EmptyAllowList,
570 )));
571 return false;
572 }
573 }
574
575 let mut allow_list = args.allow_list;
576 let mut rp_id = RelyingParty::from(args.relying_party_id);
577 let client_data_hash = ClientDataHash(args.client_data_hash);
578 if let Some(ref app_id) = args.extensions.app_id {
579 if !allow_list.is_empty() {
580 // Try to silently discover U2F credentials that require the FIDO App ID extension. If
581 // any are found, we should use the alternate RP ID instead of the provided RP ID.
582 let alt_rp_id = RelyingParty::from(app_id);
583 let silent_creds =
584 silently_discover_credentials(dev, &allow_list, &alt_rp_id, &client_data_hash);
585 if !silent_creds.is_empty() {
586 allow_list = silent_creds;
587 rp_id = alt_rp_id;
588 }
589 }
590 }
591
592 let mut get_assertion = GetAssertion::new(
593 client_data_hash,
594 rp_id,
595 allow_list,
596 GetAssertionOptions {
597 user_presence: Some(args.user_presence_req),
598 user_verification: None,
599 },
600 args.extensions.into(),
601 );
602
603 let mut skip_uv = false;
604 let mut pin = args.pin;
605 while alive() {
606 let pin_uv_auth_result = unwrap_result!(
607 determine_puap_if_needed(
608 &mut get_assertion,
609 dev,
610 skip_uv,
611 PinUvAuthTokenPermission::GetAssertion,
612 args.user_verification_req,
613 &status,
614 alive,
615 &mut pin,
616 ),
617 callback
618 );
619
620 // Do "pre-flight": Filter the allow-list
621 let original_allow_list_was_empty = get_assertion.allow_list.is_empty();
622 if dev.get_protocol() == FidoProtocol::CTAP2 {
623 get_assertion.allow_list = unwrap_result!(
624 do_credential_list_filtering_ctap2(
625 dev,
626 &get_assertion.allow_list,
627 &get_assertion.rp,
628 pin_uv_auth_result.get_pin_uv_auth_token(),
629 ),
630 callback
631 );
632 } else {
633 let key_handle = do_credential_list_filtering_ctap1(
634 dev,
635 &get_assertion.allow_list,
636 &get_assertion.rp,
637 &get_assertion.client_data_hash,
638 );
639 match key_handle {
640 Some(key_handle) => {
641 get_assertion.allow_list = vec![key_handle];
642 }
643 None => {
644 get_assertion.allow_list.clear();
645 }
646 }
647 }
648
649 // If the incoming list was not empty, but the filtered list is, we have to error out
650 if !original_allow_list_was_empty && get_assertion.allow_list.is_empty() {
651 // We have to collect a user interaction
652 send_status(&status, crate::StatusUpdate::PresenceRequired);
653 let msg = dummy_make_credentials_cmd();
654 let _ = dev.send_msg_cancellable(&msg, alive); // Ignore answer, return "NoCredentials"
655 callback.call(Err(HIDError::Command(CommandError::StatusCode(
656 StatusCode::NoCredentials,
657 None,
658 ))
659 .into()));
660 return false;
661 }
662
663 // Use the shared secret in the extensions, if requested
664 get_assertion = match get_assertion.process_hmac_secret_and_prf_extension(
665 dev.get_shared_secret().map(|s| (s, &pin_uv_auth_result)),
666 ) {
667 Ok(value) => value,
668 Err(e) => {
669 callback.call(Err(e));
670 return false;
671 }
672 };
673
674 debug!("------------------------------------------------------------------");
675 debug!("{get_assertion:?} using {pin_uv_auth_result:?}");
676 debug!("------------------------------------------------------------------");
677 send_status(&status, crate::StatusUpdate::PresenceRequired);
678 let mut results = match dev.send_msg_cancellable(&get_assertion, alive) {
679 Ok(results) => results,
680 Err(e) => {
681 handle_errors!(e, status, callback, pin_uv_auth_result, skip_uv);
682 }
683 };
684 if results.len() == 1 {
685 callback.call(Ok(results.swap_remove(0)));
686 return true;
687 }
688 let (tx, rx) = channel();
689 let user_entities = results
690 .iter()
691 .filter_map(|x| x.assertion.user.clone())
692 .collect();
693 send_status(
694 &status,
695 crate::StatusUpdate::SelectResultNotice(tx, user_entities),
696 );
697 match rx.recv() {
698 Ok(Some(index)) if index < results.len() => {
699 callback.call(Ok(results.swap_remove(index)));
700 return true;
701 }
702 _ => {
703 callback.call(Err(AuthenticatorError::CancelledByUser));
704 return true;
705 }
706 }
707 }
708 false
709 }
710
711 pub(crate) fn reset_helper<T: From<ResetResult>>(
712 dev: &mut Device,
713 selector: Sender<DeviceSelectorEvent>,
714 status: Sender<crate::StatusUpdate>,
715 callback: StateCallback<crate::Result<T>>,
716 keep_alive: &dyn Fn() -> bool,
717 ) {
718 let reset = Reset {};
719 info!("Device {:?} continues with the reset process", dev.id());
720
721 debug!("------------------------------------------------------------------");
722 debug!("{:?}", reset);
723 debug!("------------------------------------------------------------------");
724 send_status(&status, crate::StatusUpdate::PresenceRequired);
725 let resp = dev.send_cbor_cancellable(&reset, keep_alive);
726 if resp.is_ok() {
727 // The DeviceSelector could already be dead, but it might also wait
728 // for us to respond, in order to cancel all other tokens in case
729 // we skipped the "blinking"-action and went straight for the actual
730 // request.
731 let _ = selector.send(DeviceSelectorEvent::SelectedToken(dev.id()));
732 }
733
734 match resp {
735 Ok(()) => callback.call(Ok(T::from(()))),
736 Err(HIDError::DeviceNotSupported) | Err(HIDError::UnsupportedCommand) => {}
737 Err(HIDError::Command(CommandError::StatusCode(StatusCode::ChannelBusy, _))) => {}
738 Err(e) => {
739 warn!("error happened: {}", e);
740 callback.call(Err(AuthenticatorError::HIDError(e)));
741 }
742 }
743 }
744
745 pub(crate) fn set_or_change_pin_helper<T: From<()>>(
746 dev: &mut Device,
747 mut current_pin: Option<Pin>,
748 new_pin: Pin,
749 status: Sender<crate::StatusUpdate>,
750 callback: StateCallback<crate::Result<T>>,
751 alive: &dyn Fn() -> bool,
752 ) {
753 let mut shared_secret = match dev.establish_shared_secret(alive) {
754 Ok(s) => s,
755 Err(e) => {
756 callback.call(Err(AuthenticatorError::HIDError(e)));
757 return;
758 }
759 };
760
761 let authinfo = match dev.get_authenticator_info() {
762 Some(i) => i.clone(),
763 None => {
764 callback.call(Err(HIDError::DeviceNotInitialized.into()));
765 return;
766 }
767 };
768
769 // If the device has a min PIN use that, otherwise default to 4 according to Spec
770 if new_pin.as_bytes().len() < authinfo.min_pin_length.unwrap_or(4) as usize {
771 callback.call(Err(AuthenticatorError::PinError(PinError::PinIsTooShort)));
772 return;
773 }
774
775 // As per Spec: "Maximum PIN Length: UTF-8 representation MUST NOT exceed 63 bytes"
776 if new_pin.as_bytes().len() >= 64 {
777 callback.call(Err(AuthenticatorError::PinError(PinError::PinIsTooLong(
778 new_pin.as_bytes().len(),
779 ))));
780 return;
781 }
782
783 // Check if a client-pin is already set, or if a new one should be created
784 let res = if Some(true) == authinfo.options.client_pin {
785 let mut res;
786 let mut was_invalid = false;
787 let mut retries = None;
788 loop {
789 // current_pin will only be Some() in the interactive mode (running `manage()`)
790 // In case that PIN is wrong, we want to avoid an endless-loop here with re-trying
791 // that wrong PIN all the time. So we `take()` it, and only test it once.
792 // If that PIN is wrong, we fall back to the "ask_user_for_pin"-method.
793 let curr_pin = match current_pin.take() {
794 None => match ask_user_for_pin(was_invalid, retries, &status) {
795 Ok(pin) => pin,
796 Err(e) => {
797 callback.call(Err(e));
798 return;
799 }
800 },
801 Some(pin) => pin,
802 };
803
804 res = ChangeExistingPin::new(&authinfo, &shared_secret, &curr_pin, &new_pin)
805 .map_err(HIDError::Command)
806 .and_then(|msg| dev.send_cbor_cancellable(&msg, alive))
807 .map_err(|e| repackage_pin_errors(dev, e));
808
809 if let Err(AuthenticatorError::PinError(PinError::InvalidPin(r))) = res {
810 was_invalid = true;
811 retries = r;
812 // We need to re-establish the shared secret for the next round.
813 match dev.establish_shared_secret(alive) {
814 Ok(s) => {
815 shared_secret = s;
816 }
817 Err(e) => {
818 callback.call(Err(AuthenticatorError::HIDError(e)));
819 return;
820 }
821 };
822
823 continue;
824 } else {
825 break;
826 }
827 }
828 res
829 } else {
830 dev.send_cbor_cancellable(&SetNewPin::new(&shared_secret, &new_pin), alive)
831 .map_err(AuthenticatorError::HIDError)
832 };
833 // the callback is expecting `Result<(), AuthenticatorError>`, but `ChangeExistingPin`
834 // and `SetNewPin` return the default `ClientPinResponse` on success. Just discard it.
835 callback.call(res.map(|_| T::from(())));
836 }
837
838 pub(crate) fn bio_enrollment(
839 dev: &mut Device,
840 puat_result: Option<PinUvAuthResult>,
841 command: BioEnrollmentCmd,
842 status: Sender<crate::StatusUpdate>,
843 callback: StateCallback<crate::Result<crate::ManageResult>>,
844 alive: &dyn Fn() -> bool,
845 ) -> bool {
846 let authinfo = match dev.get_authenticator_info() {
847 Some(i) => i,
848 None => {
849 callback.call(Err(HIDError::DeviceNotInitialized.into()));
850 return false;
851 }
852 };
853
854 if authinfo.options.bio_enroll.is_none()
855 && authinfo.options.user_verification_mgmt_preview.is_none()
856 {
857 callback.call(Err(AuthenticatorError::HIDError(
858 HIDError::UnsupportedCommand,
859 )));
860 return false;
861 }
862
863 let use_legacy_preview = authinfo.options.bio_enroll.is_none();
864
865 // We are not allowed to request the BE-permission using UV, so we have to skip UV
866 let mut skip_uv = authinfo.options.uv_bio_enroll != Some(true);
867 // Currently not used, but if we want, we can just set the value here.
868 let timeout = None;
869
870 let mut bio_cmd = match &command {
871 BioEnrollmentCmd::StartNewEnrollment(_name) => BioEnrollment::new(
872 BioEnrollmentCommand::EnrollBegin(timeout),
873 use_legacy_preview,
874 ),
875 BioEnrollmentCmd::DeleteEnrollment(id) => BioEnrollment::new(
876 BioEnrollmentCommand::RemoveEnrollment(id.clone()),
877 use_legacy_preview,
878 ),
879 BioEnrollmentCmd::ChangeName(id, name) => BioEnrollment::new(
880 BioEnrollmentCommand::SetFriendlyName((id.clone(), name.clone())),
881 use_legacy_preview,
882 ),
883 BioEnrollmentCmd::GetEnrollments => BioEnrollment::new(
884 BioEnrollmentCommand::EnumerateEnrollments,
885 use_legacy_preview,
886 ),
887 BioEnrollmentCmd::GetFingerprintSensorInfo => BioEnrollment::new(
888 BioEnrollmentCommand::GetFingerprintSensorInfo,
889 use_legacy_preview,
890 ),
891 };
892
893 let mut skip_puap = false;
894 let mut cached_puat = false; // If we were provided with a cached puat from the outside
895 let mut pin_uv_auth_result = puat_result
896 .clone()
897 .unwrap_or(PinUvAuthResult::NoAuthRequired);
898 // See, if we have a cached PUAT with matching permissions.
899 match puat_result {
900 Some(PinUvAuthResult::SuccessGetPinToken(t))
901 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(t))
902 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingPinWithPermissions(t))
903 if !authinfo.versions.contains(&AuthenticatorVersion::FIDO_2_1) // Only 2.1 has a permission-system
904 || use_legacy_preview // Preview doesn't use permissions
905 || t.permissions
906 .contains(PinUvAuthTokenPermission::BioEnrollment) =>
907 {
908 skip_puap = true;
909 cached_puat = true;
910 unwrap_result!(bio_cmd.set_pin_uv_auth_param(Some(t)), callback);
911 }
912 _ => {}
913 }
914 let mut pin = None;
915 while alive() {
916 if !skip_puap {
917 pin_uv_auth_result = unwrap_result!(
918 determine_puap_if_needed(
919 &mut bio_cmd,
920 dev,
921 skip_uv,
922 PinUvAuthTokenPermission::BioEnrollment,
923 UserVerificationRequirement::Preferred,
924 &status,
925 alive,
926 &mut pin,
927 ),
928 callback
929 );
930 }
931
932 debug!("------------------------------------------------------------------");
933 debug!("{bio_cmd:?} using {pin_uv_auth_result:?}");
934 debug!("------------------------------------------------------------------");
935
936 let resp = dev.send_cbor_cancellable(&bio_cmd, alive);
937 match resp {
938 Ok(result) => {
939 skip_puap = true;
940 match bio_cmd.subcommand {
941 BioEnrollmentCommand::EnrollBegin(..)
942 | BioEnrollmentCommand::EnrollCaptureNextSample(..) => {
943 let template_id =
944 if let BioEnrollmentCommand::EnrollCaptureNextSample((id, ..)) =
945 bio_cmd.subcommand
946 {
947 id
948 } else {
949 unwrap_option!(result.template_id, callback)
950 };
951 let last_enroll_sample_status =
952 unwrap_option!(result.last_enroll_sample_status, callback);
953 let remaining_samples = unwrap_option!(result.remaining_samples, callback);
954
955 send_status(
956 &status,
957 StatusUpdate::InteractiveManagement(
958 InteractiveUpdate::BioEnrollmentUpdate((
959 BioEnrollmentResult::SampleStatus(
960 last_enroll_sample_status,
961 remaining_samples,
962 ),
963 Some(pin_uv_auth_result.clone()),
964 )),
965 ),
966 );
967
968 if remaining_samples == 0 {
969 if let BioEnrollmentCmd::StartNewEnrollment(Some(ref name)) = command {
970 bio_cmd.subcommand = BioEnrollmentCommand::SetFriendlyName((
971 template_id.to_vec(),
972 name.clone(),
973 ));
974 // We have to regenerate PUAP here. PUAT hasn't changed, but the content
975 // of the command has changed, and that is part of the PUAP-calculation
976 unwrap_result!(
977 bio_cmd.set_pin_uv_auth_param(
978 pin_uv_auth_result.get_pin_uv_auth_token()
979 ),
980 callback
981 );
982 continue;
983 } else {
984 let auth_info =
985 unwrap_option!(dev.refresh_authenticator_info(), callback);
986 send_status(
987 &status,
988 StatusUpdate::InteractiveManagement(
989 InteractiveUpdate::BioEnrollmentUpdate((
990 BioEnrollmentResult::AddSuccess(auth_info.clone()),
991 Some(pin_uv_auth_result),
992 )),
993 ),
994 );
995 return true;
996 }
997 } else {
998 bio_cmd.subcommand = BioEnrollmentCommand::EnrollCaptureNextSample((
999 template_id,
1000 timeout,
1001 ));
1002 // We have to regenerate PUAP here. PUAT hasn't changed, but the content
1003 // of the command has changed, and that is part of the PUAP-calculation
1004 unwrap_result!(
1005 bio_cmd.set_pin_uv_auth_param(
1006 pin_uv_auth_result.get_pin_uv_auth_token()
1007 ),
1008 callback
1009 );
1010 continue;
1011 }
1012 }
1013 BioEnrollmentCommand::EnumerateEnrollments => {
1014 let list = result.template_infos.iter().map(|x| x.into()).collect();
1015 send_status(
1016 &status,
1017 StatusUpdate::InteractiveManagement(
1018 InteractiveUpdate::BioEnrollmentUpdate((
1019 BioEnrollmentResult::EnrollmentList(list),
1020 Some(pin_uv_auth_result),
1021 )),
1022 ),
1023 );
1024 return true;
1025 }
1026 BioEnrollmentCommand::SetFriendlyName(_) => {
1027 let res = match command {
1028 BioEnrollmentCmd::StartNewEnrollment(..) => {
1029 let auth_info =
1030 unwrap_option!(dev.refresh_authenticator_info(), callback);
1031 BioEnrollmentResult::AddSuccess(auth_info.clone())
1032 }
1033 _ => BioEnrollmentResult::UpdateSuccess,
1034 };
1035 send_status(
1036 &status,
1037 StatusUpdate::InteractiveManagement(
1038 InteractiveUpdate::BioEnrollmentUpdate((
1039 res,
1040 Some(pin_uv_auth_result),
1041 )),
1042 ),
1043 );
1044 return true;
1045 }
1046 BioEnrollmentCommand::RemoveEnrollment(_) => {
1047 let auth_info = unwrap_option!(dev.refresh_authenticator_info(), callback);
1048 send_status(
1049 &status,
1050 StatusUpdate::InteractiveManagement(
1051 InteractiveUpdate::BioEnrollmentUpdate((
1052 BioEnrollmentResult::DeleteSuccess(auth_info.clone()),
1053 Some(pin_uv_auth_result),
1054 )),
1055 ),
1056 );
1057 return true;
1058 }
1059 BioEnrollmentCommand::CancelCurrentEnrollment => {
1060 callback.call(Ok(ManageResult::Success));
1061 return true;
1062 }
1063 BioEnrollmentCommand::GetFingerprintSensorInfo => {
1064 let fingerprint_kind = unwrap_option!(result.fingerprint_kind, callback);
1065 let max_capture_samples_required_for_enroll = unwrap_option!(
1066 result.max_capture_samples_required_for_enroll,
1067 callback
1068 );
1069 // FIDO_2_1_PRE-devices do not report this field. So we leave it optional.
1070 let max_template_friendly_name = result.max_template_friendly_name;
1071 send_status(
1072 &status,
1073 StatusUpdate::InteractiveManagement(
1074 InteractiveUpdate::BioEnrollmentUpdate((
1075 BioEnrollmentResult::FingerprintSensorInfo(
1076 FingerprintSensorInfo {
1077 fingerprint_kind,
1078 max_capture_samples_required_for_enroll,
1079 max_template_friendly_name,
1080 },
1081 ),
1082 Some(pin_uv_auth_result),
1083 )),
1084 ),
1085 );
1086 return true;
1087 }
1088 };
1089 }
1090 Err(e) => {
1091 handle_errors!(
1092 e,
1093 status,
1094 callback,
1095 pin_uv_auth_result,
1096 skip_uv,
1097 skip_puap,
1098 cached_puat
1099 );
1100 }
1101 }
1102 }
1103 false
1104 }
1105
1106 pub(crate) fn credential_management(
1107 dev: &mut Device,
1108 puat_result: Option<PinUvAuthResult>,
1109 command: CredManagementCmd,
1110 status: Sender<crate::StatusUpdate>,
1111 callback: StateCallback<crate::Result<crate::ManageResult>>,
1112 alive: &dyn Fn() -> bool,
1113 ) -> bool {
1114 let mut skip_uv = false;
1115 let authinfo = match dev.get_authenticator_info() {
1116 Some(i) => i.clone(),
1117 None => {
1118 callback.call(Err(HIDError::DeviceNotInitialized.into()));
1119 return false;
1120 }
1121 };
1122
1123 if authinfo.options.cred_mgmt != Some(true)
1124 && authinfo.options.credential_mgmt_preview != Some(true)
1125 {
1126 callback.call(Err(AuthenticatorError::HIDError(
1127 HIDError::UnsupportedCommand,
1128 )));
1129 return false;
1130 }
1131
1132 let use_legacy_preview = authinfo.options.cred_mgmt != Some(true);
1133
1134 // FIDO_2_1_PRE-devices do not support UpdateUserInformation.
1135 if use_legacy_preview
1136 && !authinfo.versions.contains(&AuthenticatorVersion::FIDO_2_1)
1137 && matches!(command, CredManagementCmd::UpdateUserInformation(..))
1138 {
1139 callback.call(Err(AuthenticatorError::HIDError(
1140 HIDError::UnsupportedCommand,
1141 )));
1142 return false;
1143 }
1144
1145 // If puap is provided, we can skip puap-determination (i.e. PIN entry)
1146 let mut cred_management = match command {
1147 CredManagementCmd::GetCredentials => {
1148 CredentialManagement::new(CredManagementCommand::GetCredsMetadata, use_legacy_preview)
1149 }
1150 CredManagementCmd::DeleteCredential(cred_id) => CredentialManagement::new(
1151 CredManagementCommand::DeleteCredential(cred_id),
1152 use_legacy_preview,
1153 ),
1154 CredManagementCmd::UpdateUserInformation(cred_id, user) => CredentialManagement::new(
1155 CredManagementCommand::UpdateUserInformation((cred_id, user)),
1156 use_legacy_preview,
1157 ),
1158 };
1159 let mut credential_result = CredentialList::new();
1160 let mut remaining_rps = 0;
1161 let mut remaining_cred_ids = 0;
1162 let mut current_rp = 0;
1163 let mut skip_puap = false;
1164 let mut cached_puat = false; // If we were provided with a cached puat from the outside
1165 let mut pin_uv_auth_result = puat_result
1166 .clone()
1167 .unwrap_or(PinUvAuthResult::NoAuthRequired);
1168 // See, if we have a cached PUAT with matching permissions.
1169 match puat_result {
1170 Some(PinUvAuthResult::SuccessGetPinToken(t))
1171 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(t))
1172 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingPinWithPermissions(t))
1173 if !authinfo.versions.contains(&AuthenticatorVersion::FIDO_2_1) // Only 2.1 has a permission-system
1174 || use_legacy_preview // Preview doesn't use permissions
1175 || t.permissions
1176 .contains(PinUvAuthTokenPermission::CredentialManagement) =>
1177 {
1178 skip_puap = true;
1179 cached_puat = true;
1180 unwrap_result!(cred_management.set_pin_uv_auth_param(Some(t)), callback);
1181 }
1182 _ => {}
1183 }
1184 let mut pin = None;
1185 while alive() {
1186 if !skip_puap {
1187 pin_uv_auth_result = unwrap_result!(
1188 determine_puap_if_needed(
1189 &mut cred_management,
1190 dev,
1191 skip_uv,
1192 PinUvAuthTokenPermission::CredentialManagement,
1193 UserVerificationRequirement::Preferred,
1194 &status,
1195 alive,
1196 &mut pin,
1197 ),
1198 callback
1199 );
1200 }
1201
1202 debug!("------------------------------------------------------------------");
1203 debug!("{cred_management:?} using {pin_uv_auth_result:?}");
1204 debug!("------------------------------------------------------------------");
1205
1206 let resp = dev.send_cbor_cancellable(&cred_management, alive);
1207 match resp {
1208 Ok(result) => {
1209 skip_puap = true;
1210 match cred_management.subcommand {
1211 CredManagementCommand::GetCredsMetadata => {
1212 let existing_resident_credentials_count =
1213 unwrap_option!(result.existing_resident_credentials_count, callback);
1214 let max_possible_remaining_resident_credentials_count = unwrap_option!(
1215 result.max_possible_remaining_resident_credentials_count,
1216 callback
1217 );
1218 credential_result.existing_resident_credentials_count =
1219 existing_resident_credentials_count;
1220 credential_result.max_possible_remaining_resident_credentials_count =
1221 max_possible_remaining_resident_credentials_count;
1222 if existing_resident_credentials_count > 0 {
1223 cred_management.subcommand = CredManagementCommand::EnumerateRPsBegin;
1224 // We have to regenerate PUAP here. PUAT hasn't changed, but the content
1225 // of the command has changed, and that is part of the PUAP-calculation
1226 unwrap_result!(
1227 cred_management.set_pin_uv_auth_param(
1228 pin_uv_auth_result.get_pin_uv_auth_token()
1229 ),
1230 callback
1231 );
1232 continue;
1233 } else {
1234 // This token doesn't have any resident keys, but its not an error,
1235 // so we send an empty list.
1236 send_status(
1237 &status,
1238 StatusUpdate::InteractiveManagement(
1239 InteractiveUpdate::CredentialManagementUpdate((
1240 CredentialManagementResult::CredentialList(
1241 credential_result,
1242 ),
1243 Some(pin_uv_auth_result),
1244 )),
1245 ),
1246 );
1247 return true;
1248 }
1249 }
1250 CredManagementCommand::EnumerateRPsBegin
1251 | CredManagementCommand::EnumerateRPsGetNextRP => {
1252 if matches!(
1253 cred_management.subcommand,
1254 CredManagementCommand::EnumerateRPsBegin
1255 ) {
1256 let total_rps = unwrap_option!(result.total_rps, callback);
1257 if total_rps == 0 {
1258 // This token doesn't have any RPs, but its not an error,
1259 // so we return an Ok with an empty list.
1260 send_status(
1261 &status,
1262 StatusUpdate::InteractiveManagement(
1263 InteractiveUpdate::CredentialManagementUpdate((
1264 CredentialManagementResult::CredentialList(
1265 credential_result,
1266 ),
1267 Some(pin_uv_auth_result),
1268 )),
1269 ),
1270 );
1271 return true;
1272 }
1273 remaining_rps = total_rps - 1;
1274 } else {
1275 remaining_rps -= 1;
1276 }
1277
1278 let rp = unwrap_option!(result.rp, callback);
1279 let rp_id_hash = unwrap_option!(result.rp_id_hash, callback);
1280 let rp_res = CredentialRpListEntry {
1281 rp,
1282 rp_id_hash,
1283 credentials: vec![],
1284 };
1285 credential_result.credential_list.push(rp_res);
1286 if remaining_rps > 0 {
1287 cred_management.subcommand =
1288 CredManagementCommand::EnumerateRPsGetNextRP;
1289 } else {
1290 // We have queried all RPs, now start querying the corresponding credentials for each RP
1291 cred_management.subcommand =
1292 CredManagementCommand::EnumerateCredentialsBegin(
1293 credential_result.credential_list[0].rp_id_hash.clone(),
1294 );
1295 }
1296 // We have to regenerate PUAP here. PUAT hasn't changed, but the content
1297 // of the command has changed, and that is part of the PUAP-calculation
1298 unwrap_result!(
1299 cred_management
1300 .set_pin_uv_auth_param(pin_uv_auth_result.get_pin_uv_auth_token()),
1301 callback
1302 );
1303 continue;
1304 }
1305 CredManagementCommand::EnumerateCredentialsBegin(..)
1306 | CredManagementCommand::EnumerateCredentialsGetNextCredential => {
1307 let user = unwrap_option!(result.user, callback);
1308 let credential_id = unwrap_option!(result.credential_id, callback);
1309 let public_key = unwrap_option!(result.public_key, callback);
1310 let cred_protect = unwrap_option!(result.cred_protect, callback);
1311 let large_blob_key = result.large_blob_key;
1312
1313 if matches!(
1314 cred_management.subcommand,
1315 CredManagementCommand::EnumerateCredentialsBegin(..)
1316 ) {
1317 remaining_cred_ids =
1318 unwrap_option!(result.total_credentials, callback) - 1;
1319 } else {
1320 remaining_cred_ids -= 1;
1321 }
1322 // We might have to change the global variable, but need the unmodified below
1323 let current_rp_backup = current_rp;
1324 let mut we_are_done = false;
1325 if remaining_cred_ids > 0 {
1326 cred_management.subcommand =
1327 CredManagementCommand::EnumerateCredentialsGetNextCredential;
1328 } else {
1329 current_rp += 1;
1330 // We have all credentials from this RP. Starting with the next RP.
1331 if current_rp < credential_result.credential_list.len() {
1332 cred_management.subcommand =
1333 CredManagementCommand::EnumerateCredentialsBegin(
1334 credential_result.credential_list[current_rp]
1335 .rp_id_hash
1336 .clone(),
1337 );
1338 // We have to regenerate PUAP here. PUAT hasn't changed, but the content
1339 // of the command has changed, and that is part of the PUAP-calculation
1340 unwrap_result!(
1341 cred_management.set_pin_uv_auth_param(
1342 pin_uv_auth_result.get_pin_uv_auth_token()
1343 ),
1344 callback
1345 );
1346 } else {
1347 // Finally done iterating over all RPs and their Credentials
1348 we_are_done = true;
1349 }
1350 }
1351 let key = CredentialListEntry {
1352 user,
1353 credential_id,
1354 public_key,
1355 cred_protect,
1356 large_blob_key,
1357 };
1358 credential_result.credential_list[current_rp_backup]
1359 .credentials
1360 .push(key);
1361 if we_are_done {
1362 send_status(
1363 &status,
1364 StatusUpdate::InteractiveManagement(
1365 InteractiveUpdate::CredentialManagementUpdate((
1366 CredentialManagementResult::CredentialList(
1367 credential_result,
1368 ),
1369 Some(pin_uv_auth_result),
1370 )),
1371 ),
1372 );
1373 return true;
1374 } else {
1375 continue;
1376 }
1377 }
1378 CredManagementCommand::DeleteCredential(_) => {
1379 send_status(
1380 &status,
1381 StatusUpdate::InteractiveManagement(
1382 InteractiveUpdate::CredentialManagementUpdate((
1383 CredentialManagementResult::DeleteSucess,
1384 Some(pin_uv_auth_result),
1385 )),
1386 ),
1387 );
1388 return true;
1389 }
1390 CredManagementCommand::UpdateUserInformation(_) => {
1391 send_status(
1392 &status,
1393 StatusUpdate::InteractiveManagement(
1394 InteractiveUpdate::CredentialManagementUpdate((
1395 CredentialManagementResult::UpdateSuccess,
1396 Some(pin_uv_auth_result),
1397 )),
1398 ),
1399 );
1400 return true;
1401 }
1402 };
1403 }
1404 Err(e) => {
1405 handle_errors!(
1406 e,
1407 status,
1408 callback,
1409 pin_uv_auth_result,
1410 skip_uv,
1411 skip_puap,
1412 cached_puat
1413 );
1414 }
1415 }
1416 }
1417 false
1418 }
1419
1420 pub(crate) fn configure_authenticator(
1421 dev: &mut Device,
1422 puat_result: Option<PinUvAuthResult>,
1423 cfg_subcommand: AuthConfigCommand,
1424 status: Sender<crate::StatusUpdate>,
1425 callback: StateCallback<crate::Result<crate::ManageResult>>,
1426 alive: &dyn Fn() -> bool,
1427 ) -> bool {
1428 let mut authcfg = AuthenticatorConfig::new(cfg_subcommand);
1429 let mut skip_uv = false;
1430 let authinfo = match dev.get_authenticator_info() {
1431 Some(i) => i.clone(),
1432 None => {
1433 callback.call(Err(HIDError::DeviceNotInitialized.into()));
1434 return false;
1435 }
1436 };
1437
1438 if authinfo.options.authnr_cfg != Some(true) {
1439 callback.call(Err(AuthenticatorError::HIDError(
1440 HIDError::UnsupportedCommand,
1441 )));
1442 return false;
1443 }
1444
1445 let mut skip_puap = false;
1446 let mut cached_puat = false; // If we were provided with a cached puat from the outside
1447 let mut pin_uv_auth_result = puat_result
1448 .clone()
1449 .unwrap_or(PinUvAuthResult::NoAuthRequired);
1450 match puat_result {
1451 Some(PinUvAuthResult::SuccessGetPinToken(t))
1452 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(t))
1453 | Some(PinUvAuthResult::SuccessGetPinUvAuthTokenUsingPinWithPermissions(t))
1454 if t.permissions
1455 .contains(PinUvAuthTokenPermission::AuthenticatorConfiguration) =>
1456 {
1457 skip_puap = true;
1458 cached_puat = true;
1459 unwrap_result!(authcfg.set_pin_uv_auth_param(Some(t)), callback);
1460 }
1461 _ => {}
1462 }
1463 let mut pin = None;
1464 while alive() {
1465 // We can use the AuthenticatorConfiguration-command only in two cases:
1466 // 1. The device also supports the uv_acfg-permission (otherwise we can't establish a PUAP)
1467 // 2. The device is NOT protected by PIN/UV (yet). This allows organizations to configure
1468 // the token, before handing them out.
1469 // If authinfo.options.uv_acfg is not supported, this will return UnauthorizedPermission
1470 if !skip_puap {
1471 pin_uv_auth_result = unwrap_result!(
1472 determine_puap_if_needed(
1473 &mut authcfg,
1474 dev,
1475 skip_uv,
1476 PinUvAuthTokenPermission::AuthenticatorConfiguration,
1477 UserVerificationRequirement::Preferred,
1478 &status,
1479 alive,
1480 &mut pin,
1481 ),
1482 callback
1483 );
1484 }
1485
1486 debug!("------------------------------------------------------------------");
1487 debug!("{authcfg:?} using {pin_uv_auth_result:?}");
1488 debug!("------------------------------------------------------------------");
1489
1490 let resp = dev.send_cbor_cancellable(&authcfg, alive);
1491 match resp {
1492 Ok(()) => {
1493 let auth_info = unwrap_option!(dev.refresh_authenticator_info(), callback);
1494 send_status(
1495 &status,
1496 StatusUpdate::InteractiveManagement(InteractiveUpdate::AuthConfigUpdate((
1497 AuthConfigResult::Success(auth_info.clone()),
1498 Some(pin_uv_auth_result),
1499 ))),
1500 );
1501 return true;
1502 }
1503 Err(e) => {
1504 handle_errors!(
1505 e,
1506 status,
1507 callback,
1508 pin_uv_auth_result,
1509 skip_uv,
1510 skip_puap,
1511 cached_puat
1512 );
1513 }
1514 }
1515 }
1516 false
1517 }