Debian Codegraph @

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

raw
1 use crate::crypto::{CryptoError, PinUvAuthParam, PinUvAuthToken};
2 use crate::ctap2::commands::client_pin::{GetPinRetries, GetUvRetries, PinError};
3 use crate::ctap2::commands::get_info::AuthenticatorInfo;
4 use crate::ctap2::server::UserVerificationRequirement;
5 use crate::errors::AuthenticatorError;
6 use crate::transport::errors::{ApduErrorStatus, HIDError};
7 use crate::transport::{FidoDevice, VirtualFidoDevice};
8 use serde_cbor::{error::Error as CborError, Value};
9 use serde_json as json;
10 use std::error::Error as StdErrorT;
11 use std::fmt;
12
13 pub mod authenticator_config;
14 pub mod bio_enrollment;
15 pub mod client_pin;
16 pub mod credential_management;
17 pub mod get_assertion;
18 pub mod get_info;
19 pub mod get_next_assertion;
20 pub mod get_version;
21 pub mod make_credentials;
22 pub mod reset;
23 pub mod selection;
24
25 /// Retryable wraps an error type and may ask manager to retry sending a
26 /// command, this is useful for ctap1 where token will reply with "condition not
27 /// sufficient" because user needs to press the button.
28 #[derive(Debug)]
29 pub enum Retryable<T> {
30 Retry,
31 Error(T),
32 }
33
34 impl<T> Retryable<T> {
35 pub fn is_retry(&self) -> bool {
36 matches!(*self, Retryable::Retry)
37 }
38
39 pub fn is_error(&self) -> bool {
40 !self.is_retry()
41 }
42 }
43
44 impl<T> From<T> for Retryable<T> {
45 fn from(e: T) -> Self {
46 Retryable::Error(e)
47 }
48 }
49
50 pub trait RequestCtap1: fmt::Debug {
51 type Output: CtapResponse;
52 // E.g.: For GetAssertion, which key-handle is currently being tested
53 type AdditionalInfo;
54
55 /// Serializes a request into FIDO v1.x / CTAP1 / U2F format.
56 ///
57 /// See [`crate::u2ftypes::CTAP1RequestAPDU::serialize()`]
58 fn ctap1_format(&self) -> Result<(Vec<u8>, Self::AdditionalInfo), HIDError>;
59
60 /// Deserializes a response from FIDO v1.x / CTAP1 / U2Fv2 format.
61 fn handle_response_ctap1<Dev: FidoDevice>(
62 &self,
63 dev: &mut Dev,
64 status: Result<(), ApduErrorStatus>,
65 input: &[u8],
66 add_info: &Self::AdditionalInfo,
67 ) -> Result<Self::Output, Retryable<HIDError>>;
68
69 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
70 &self,
71 dev: &mut Dev,
72 ) -> Result<Self::Output, HIDError>;
73 }
74
75 pub trait RequestCtap2: fmt::Debug {
76 type Output: CtapResponse;
77
78 fn command(&self) -> Command;
79
80 fn wire_format(&self) -> Result<Vec<u8>, HIDError>;
81
82 fn handle_response_ctap2<Dev: FidoDevice>(
83 &self,
84 dev: &mut Dev,
85 input: &[u8],
86 ) -> Result<Self::Output, HIDError>;
87
88 fn send_to_virtual_device<Dev: VirtualFidoDevice>(
89 &self,
90 dev: &mut Dev,
91 ) -> Result<Self::Output, HIDError>;
92 }
93
94 // Sadly, needs to be 'static to enable us in tests to collect them in a Vec
95 // but all of them are 'static, so this is currently no problem.
96 pub trait CtapResponse: std::fmt::Debug + 'static {}
97
98 #[derive(Debug, Clone)]
99 pub enum PinUvAuthResult {
100 /// Request is CTAP1 and does not need PinUvAuth
101 RequestIsCtap1,
102 /// Device is not capable of CTAP2
103 DeviceIsCtap1,
104 /// Device does not support UV or PINs
105 NoAuthTypeSupported,
106 /// Request doesn't want user verification (uv = "discouraged")
107 NoAuthRequired,
108 /// Device is CTAP2.0 and has internal UV capability
109 UsingInternalUv,
110 /// Successfully established PinUvAuthToken via GetPinToken (CTAP2.0)
111 SuccessGetPinToken(PinUvAuthToken),
112 /// Successfully established PinUvAuthToken via UV (CTAP2.1)
113 SuccessGetPinUvAuthTokenUsingUvWithPermissions(PinUvAuthToken),
114 /// Successfully established PinUvAuthToken via Pin (CTAP2.1)
115 SuccessGetPinUvAuthTokenUsingPinWithPermissions(PinUvAuthToken),
116 }
117
118 impl PinUvAuthResult {
119 pub(crate) fn get_pin_uv_auth_token(&self) -> Option<PinUvAuthToken> {
120 match self {
121 PinUvAuthResult::RequestIsCtap1
122 | PinUvAuthResult::DeviceIsCtap1
123 | PinUvAuthResult::NoAuthTypeSupported
124 | PinUvAuthResult::NoAuthRequired
125 | PinUvAuthResult::UsingInternalUv => None,
126 PinUvAuthResult::SuccessGetPinToken(token) => Some(token.clone()),
127 PinUvAuthResult::SuccessGetPinUvAuthTokenUsingUvWithPermissions(token) => {
128 Some(token.clone())
129 }
130 PinUvAuthResult::SuccessGetPinUvAuthTokenUsingPinWithPermissions(token) => {
131 Some(token.clone())
132 }
133 }
134 }
135 }
136
137 /// Helper-trait to determine pin_uv_auth_param from PIN or UV.
138 pub(crate) trait PinUvAuthCommand: RequestCtap2 {
139 fn set_pin_uv_auth_param(
140 &mut self,
141 pin_uv_auth_token: Option<PinUvAuthToken>,
142 ) -> Result<(), AuthenticatorError>;
143 fn get_pin_uv_auth_param(&self) -> Option<&PinUvAuthParam>;
144 fn set_uv_option(&mut self, uv: Option<bool>);
145 fn get_rp_id(&self) -> Option<&String>;
146 fn can_skip_user_verification(
147 &mut self,
148 info: &AuthenticatorInfo,
149 uv_req: UserVerificationRequirement,
150 ) -> bool;
151 }
152
153 pub(crate) fn repackage_pin_errors<D: FidoDevice>(
154 dev: &mut D,
155 error: HIDError,
156 ) -> AuthenticatorError {
157 match error {
158 HIDError::Command(CommandError::StatusCode(StatusCode::PinInvalid, _)) => {
159 // If the given PIN was wrong, determine no. of left retries
160 let cmd = GetPinRetries::new();
161 // Treat any error as if the device returned a valid response without a pinRetries
162 // field.
163 let resp = dev.send_cbor(&cmd).unwrap_or_default();
164 AuthenticatorError::PinError(PinError::InvalidPin(resp.pin_retries))
165 }
166 HIDError::Command(CommandError::StatusCode(StatusCode::PinAuthBlocked, _)) => {
167 AuthenticatorError::PinError(PinError::PinAuthBlocked)
168 }
169 HIDError::Command(CommandError::StatusCode(StatusCode::PinBlocked, _)) => {
170 AuthenticatorError::PinError(PinError::PinBlocked)
171 }
172 HIDError::Command(CommandError::StatusCode(StatusCode::PinRequired, _)) => {
173 AuthenticatorError::PinError(PinError::PinRequired)
174 }
175 HIDError::Command(CommandError::StatusCode(StatusCode::PinNotSet, _)) => {
176 AuthenticatorError::PinError(PinError::PinNotSet)
177 }
178 HIDError::Command(CommandError::StatusCode(StatusCode::PinAuthInvalid, _)) => {
179 AuthenticatorError::PinError(PinError::PinAuthInvalid)
180 }
181 HIDError::Command(CommandError::StatusCode(StatusCode::UvInvalid, _)) => {
182 // If the internal UV failed, determine no. of left retries
183 let cmd = GetUvRetries::new();
184 // Treat any error as if the device returned a valid response without a uvRetries
185 // field.
186 let resp = dev.send_cbor(&cmd).unwrap_or_default();
187 AuthenticatorError::PinError(PinError::InvalidUv(resp.uv_retries))
188 }
189 HIDError::Command(CommandError::StatusCode(StatusCode::UvBlocked, _)) => {
190 AuthenticatorError::PinError(PinError::UvBlocked)
191 }
192 // TODO(MS): Add "PinPolicyViolated"
193 err => AuthenticatorError::HIDError(err),
194 }
195 }
196
197 // Spec: https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#authenticator-api
198 // and: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#authenticator-api
199 #[repr(u8)]
200 #[derive(Debug, PartialEq, Clone)]
201 pub enum Command {
202 MakeCredentials = 0x01,
203 GetAssertion = 0x02,
204 GetInfo = 0x04,
205 ClientPin = 0x06,
206 Reset = 0x07,
207 GetNextAssertion = 0x08,
208 BioEnrollment = 0x09,
209 CredentialManagement = 0x0A,
210 Selection = 0x0B,
211 AuthenticatorConfig = 0x0D,
212 BioEnrollmentPreview = 0x40,
213 CredentialManagementPreview = 0x41,
214 }
215
216 #[derive(Debug)]
217 pub enum StatusCode {
218 /// Indicates successful response.
219 OK,
220 /// The command is not a valid CTAP command.
221 InvalidCommand,
222 /// The command included an invalid parameter.
223 InvalidParameter,
224 /// Invalid message or item length.
225 InvalidLength,
226 /// Invalid message sequencing.
227 InvalidSeq,
228 /// Message timed out.
229 Timeout,
230 /// Channel busy.
231 ChannelBusy,
232 /// Command requires channel lock.
233 LockRequired,
234 /// Command not allowed on this cid.
235 InvalidChannel,
236 /// Invalid/unexpected CBOR error.
237 CBORUnexpectedType,
238 /// Error when parsing CBOR.
239 InvalidCBOR,
240 /// Missing non-optional parameter.
241 MissingParameter,
242 /// Limit for number of items exceeded.
243 LimitExceeded,
244 /// Unsupported extension.
245 UnsupportedExtension,
246 /// Valid credential found in the exclude list.
247 CredentialExcluded,
248 /// Processing (Lengthy operation is in progress).
249 Processing,
250 /// Credential not valid for the authenticator.
251 InvalidCredential,
252 /// Authentication is waiting for user interaction.
253 UserActionPending,
254 /// Processing, lengthy operation is in progress.
255 OperationPending,
256 /// No request is pending.
257 NoOperations,
258 /// Authenticator does not support requested algorithm.
259 UnsupportedAlgorithm,
260 /// Not authorized for requested operation.
261 OperationDenied,
262 /// Internal key storage is full.
263 KeyStoreFull,
264 /// No outstanding operations.
265 NoOperationPending,
266 /// Unsupported option.
267 UnsupportedOption,
268 /// Not a valid option for current operation.
269 InvalidOption,
270 /// Pending keep alive was cancelled.
271 KeepaliveCancel,
272 /// No valid credentials provided.
273 NoCredentials,
274 /// Timeout waiting for user interaction.
275 UserActionTimeout,
276 /// Continuation command, such as, authenticatorGetNextAssertion not
277 /// allowed.
278 NotAllowed,
279 /// PIN Invalid.
280 PinInvalid,
281 /// PIN Blocked.
282 PinBlocked,
283 /// PIN authentication,pinAuth, verification failed.
284 PinAuthInvalid,
285 /// PIN authentication,pinAuth, blocked. Requires power recycle to reset.
286 PinAuthBlocked,
287 /// No PIN has been set.
288 PinNotSet,
289 /// PIN is required for the selected operation.
290 PinRequired,
291 /// PIN policy violation. Currently only enforces minimum length.
292 PinPolicyViolation,
293 /// pinToken expired on authenticator.
294 PinTokenExpired,
295 /// Authenticator cannot handle this request due to memory constraints.
296 RequestTooLarge,
297 /// The current operation has timed out.
298 ActionTimeout,
299 /// User presence is required for the requested operation.
300 UpRequired,
301 /// built-in user verification is disabled.
302 UvBlocked,
303 /// A checksum did not match.
304 IntegrityFailure,
305 /// The requested subcommand is either invalid or not implemented.
306 InvalidSubcommand,
307 /// built-in user verification unsuccessful. The platform SHOULD retry.
308 UvInvalid,
309 /// The permissions parameter contains an unauthorized permission.
310 UnauthorizedPermission,
311 /// Other unspecified error.
312 Other,
313
314 /// Unknown status.
315 Unknown(u8),
316 }
317
318 impl StatusCode {
319 fn is_ok(&self) -> bool {
320 matches!(*self, StatusCode::OK)
321 }
322
323 fn device_busy(&self) -> bool {
324 matches!(*self, StatusCode::ChannelBusy)
325 }
326 }
327
328 impl From<u8> for StatusCode {
329 fn from(value: u8) -> StatusCode {
330 match value {
331 0x00 => StatusCode::OK,
332 0x01 => StatusCode::InvalidCommand,
333 0x02 => StatusCode::InvalidParameter,
334 0x03 => StatusCode::InvalidLength,
335 0x04 => StatusCode::InvalidSeq,
336 0x05 => StatusCode::Timeout,
337 0x06 => StatusCode::ChannelBusy,
338 0x0A => StatusCode::LockRequired,
339 0x0B => StatusCode::InvalidChannel,
340 0x11 => StatusCode::CBORUnexpectedType,
341 0x12 => StatusCode::InvalidCBOR,
342 0x14 => StatusCode::MissingParameter,
343 0x15 => StatusCode::LimitExceeded,
344 0x16 => StatusCode::UnsupportedExtension,
345 0x19 => StatusCode::CredentialExcluded,
346 0x21 => StatusCode::Processing,
347 0x22 => StatusCode::InvalidCredential,
348 0x23 => StatusCode::UserActionPending,
349 0x24 => StatusCode::OperationPending,
350 0x25 => StatusCode::NoOperations,
351 0x26 => StatusCode::UnsupportedAlgorithm,
352 0x27 => StatusCode::OperationDenied,
353 0x28 => StatusCode::KeyStoreFull,
354 0x2A => StatusCode::NoOperationPending,
355 0x2B => StatusCode::UnsupportedOption,
356 0x2C => StatusCode::InvalidOption,
357 0x2D => StatusCode::KeepaliveCancel,
358 0x2E => StatusCode::NoCredentials,
359 0x2f => StatusCode::UserActionTimeout,
360 0x30 => StatusCode::NotAllowed,
361 0x31 => StatusCode::PinInvalid,
362 0x32 => StatusCode::PinBlocked,
363 0x33 => StatusCode::PinAuthInvalid,
364 0x34 => StatusCode::PinAuthBlocked,
365 0x35 => StatusCode::PinNotSet,
366 0x36 => StatusCode::PinRequired,
367 0x37 => StatusCode::PinPolicyViolation,
368 0x38 => StatusCode::PinTokenExpired,
369 0x39 => StatusCode::RequestTooLarge,
370 0x3A => StatusCode::ActionTimeout,
371 0x3B => StatusCode::UpRequired,
372 0x3C => StatusCode::UvBlocked,
373 0x3D => StatusCode::IntegrityFailure,
374 0x3E => StatusCode::InvalidSubcommand,
375 0x3F => StatusCode::UvInvalid,
376 0x40 => StatusCode::UnauthorizedPermission,
377 0x7F => StatusCode::Other,
378 othr => StatusCode::Unknown(othr),
379 }
380 }
381 }
382
383 #[cfg(test)]
384 impl From<StatusCode> for u8 {
385 fn from(v: StatusCode) -> u8 {
386 match v {
387 StatusCode::OK => 0x00,
388 StatusCode::InvalidCommand => 0x01,
389 StatusCode::InvalidParameter => 0x02,
390 StatusCode::InvalidLength => 0x03,
391 StatusCode::InvalidSeq => 0x04,
392 StatusCode::Timeout => 0x05,
393 StatusCode::ChannelBusy => 0x06,
394 StatusCode::LockRequired => 0x0A,
395 StatusCode::InvalidChannel => 0x0B,
396 StatusCode::CBORUnexpectedType => 0x11,
397 StatusCode::InvalidCBOR => 0x12,
398 StatusCode::MissingParameter => 0x14,
399 StatusCode::LimitExceeded => 0x15,
400 StatusCode::UnsupportedExtension => 0x16,
401 StatusCode::CredentialExcluded => 0x19,
402 StatusCode::Processing => 0x21,
403 StatusCode::InvalidCredential => 0x22,
404 StatusCode::UserActionPending => 0x23,
405 StatusCode::OperationPending => 0x24,
406 StatusCode::NoOperations => 0x25,
407 StatusCode::UnsupportedAlgorithm => 0x26,
408 StatusCode::OperationDenied => 0x27,
409 StatusCode::KeyStoreFull => 0x28,
410 StatusCode::NoOperationPending => 0x2A,
411 StatusCode::UnsupportedOption => 0x2B,
412 StatusCode::InvalidOption => 0x2C,
413 StatusCode::KeepaliveCancel => 0x2D,
414 StatusCode::NoCredentials => 0x2E,
415 StatusCode::UserActionTimeout => 0x2f,
416 StatusCode::NotAllowed => 0x30,
417 StatusCode::PinInvalid => 0x31,
418 StatusCode::PinBlocked => 0x32,
419 StatusCode::PinAuthInvalid => 0x33,
420 StatusCode::PinAuthBlocked => 0x34,
421 StatusCode::PinNotSet => 0x35,
422 StatusCode::PinRequired => 0x36,
423 StatusCode::PinPolicyViolation => 0x37,
424 StatusCode::PinTokenExpired => 0x38,
425 StatusCode::RequestTooLarge => 0x39,
426 StatusCode::ActionTimeout => 0x3A,
427 StatusCode::UpRequired => 0x3B,
428 StatusCode::UvBlocked => 0x3C,
429 StatusCode::IntegrityFailure => 0x3D,
430 StatusCode::InvalidSubcommand => 0x3E,
431 StatusCode::UvInvalid => 0x3F,
432 StatusCode::UnauthorizedPermission => 0x40,
433 StatusCode::Other => 0x7F,
434
435 StatusCode::Unknown(othr) => othr,
436 }
437 }
438 }
439
440 #[derive(Debug)]
441 pub enum CommandError {
442 InputTooSmall,
443 MissingRequiredField(&'static str),
444 Deserializing(CborError),
445 Serializing(CborError),
446 StatusCode(StatusCode, Option<Value>),
447 Json(json::Error),
448 Crypto(CryptoError),
449 UnsupportedPinProtocol,
450 }
451
452 impl fmt::Display for CommandError {
453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
454 match *self {
455 CommandError::InputTooSmall => write!(f, "CommandError: Input is too small"),
456 CommandError::MissingRequiredField(field) => {
457 write!(f, "CommandError: Missing required field {field}")
458 }
459 CommandError::Deserializing(ref e) => {
460 write!(f, "CommandError: Error while parsing: {e}")
461 }
462 CommandError::Serializing(ref e) => {
463 write!(f, "CommandError: Error while serializing: {e}")
464 }
465 CommandError::StatusCode(ref code, ref value) => {
466 write!(f, "CommandError: Unexpected code: {code:?} ({value:?})")
467 }
468 CommandError::Json(ref e) => write!(f, "CommandError: Json serializing error: {e}"),
469 CommandError::Crypto(ref e) => write!(f, "CommandError: Crypto error: {e:?}"),
470 CommandError::UnsupportedPinProtocol => {
471 write!(f, "CommandError: Pin protocol is not supported")
472 }
473 }
474 }
475 }
476
477 impl StdErrorT for CommandError {}