libwebauthn 0.5.1

FIDO2 (WebAuthn) and FIDO U2F platform library for Linux written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::time::Duration;

use async_trait::async_trait;
use tracing::{debug, instrument, trace, warn};

use crate::proto::ctap2::cbor::{self, CborRequest};
use crate::proto::ctap2::{Ctap2BioEnrollmentResponse, Ctap2CommandCode};
use crate::transport::Channel;
use crate::unwrap_field;
use crate::webauthn::error::{CtapError, Error, PlatformError};

use super::model::Ctap2ClientPinResponse;
use super::{
    Ctap2AuthenticatorConfigRequest, Ctap2BioEnrollmentRequest, Ctap2ClientPinRequest,
    Ctap2CredentialManagementRequest, Ctap2CredentialManagementResponse, Ctap2GetAssertionRequest,
    Ctap2GetAssertionResponse, Ctap2GetInfoResponse, Ctap2MakeCredentialRequest,
    Ctap2MakeCredentialResponse,
};

const TIMEOUT_GET_INFO: Duration = Duration::from_millis(250);

macro_rules! parse_cbor {
    ($type:ty, $data:expr) => {{
        match cbor::from_slice::<$type>($data) {
            Ok(f) => f,
            Err(e) => {
                tracing::error!(
                    "Failed to parse {} from CBOR-data provided by the device. Parsing error: {:?}",
                    stringify!($type),
                    e
                );
                return Err(Error::Platform(PlatformError::InvalidDeviceResponse));
            }
        }
    }};
}

#[async_trait]
pub trait Ctap2 {
    async fn ctap2_get_info(&mut self) -> Result<Ctap2GetInfoResponse, Error>;
    async fn ctap2_make_credential(
        &mut self,
        request: &Ctap2MakeCredentialRequest,
        timeout: Duration,
    ) -> Result<Ctap2MakeCredentialResponse, Error>;
    async fn ctap2_client_pin(
        &mut self,
        request: &Ctap2ClientPinRequest,
        timeout: Duration,
    ) -> Result<Ctap2ClientPinResponse, Error>;
    async fn ctap2_get_assertion(
        &mut self,
        request: &Ctap2GetAssertionRequest,
        timeout: Duration,
    ) -> Result<Ctap2GetAssertionResponse, Error>;
    async fn ctap2_get_next_assertion(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2GetAssertionResponse, Error>;
    async fn ctap2_selection(&mut self, timeout: Duration) -> Result<(), Error>;
    async fn ctap2_authenticator_config(
        &mut self,
        request: &Ctap2AuthenticatorConfigRequest,
        timeout: Duration,
    ) -> Result<(), Error>;
    async fn ctap2_bio_enrollment(
        &mut self,
        request: &Ctap2BioEnrollmentRequest,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentResponse, Error>;
    async fn ctap2_credential_management(
        &mut self,
        request: &Ctap2CredentialManagementRequest,
        timeout: Duration,
    ) -> Result<Ctap2CredentialManagementResponse, Error>;
}

#[async_trait]
impl<C> Ctap2 for C
where
    C: Channel,
{
    #[instrument(skip_all)]
    async fn ctap2_get_info(&mut self) -> Result<Ctap2GetInfoResponse, Error> {
        let cbor_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetInfo);
        self.cbor_send(&cbor_request, TIMEOUT_GET_INFO).await?;
        let cbor_response = self.cbor_recv(TIMEOUT_GET_INFO).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        let data = unwrap_field!(cbor_response.data);
        let ctap_response = parse_cbor!(Ctap2GetInfoResponse, &data);
        debug!("CTAP2 GetInfo successful");
        trace!(?ctap_response);
        Ok(ctap_response)
    }

    #[instrument(skip_all)]
    async fn ctap2_make_credential(
        &mut self,
        request: &Ctap2MakeCredentialRequest,
        timeout: Duration,
    ) -> Result<Ctap2MakeCredentialResponse, Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        let data = unwrap_field!(cbor_response.data);
        trace!("MakeCredential: {:?}", data);
        let ctap_response = parse_cbor!(Ctap2MakeCredentialResponse, &data);
        debug!("CTAP2 MakeCredential successful");
        trace!(?ctap_response);
        Ok(ctap_response)
    }

    #[instrument(skip_all)]
    async fn ctap2_get_assertion(
        &mut self,
        request: &Ctap2GetAssertionRequest,
        timeout: Duration,
    ) -> Result<Ctap2GetAssertionResponse, Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        let data = unwrap_field!(cbor_response.data);
        trace!("GetAssertion: {:?}", data);
        let ctap_response = parse_cbor!(Ctap2GetAssertionResponse, &data);
        debug!("CTAP2 GetAssertion successful");
        trace!(?ctap_response);
        Ok(ctap_response)
    }

    #[instrument(skip_all)]
    async fn ctap2_get_next_assertion(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2GetAssertionResponse, Error> {
        debug!("CTAP2 GetNextAssertion request");
        let cbor_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetNextAssertion);
        self.cbor_send(&cbor_request, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        let data = unwrap_field!(cbor_response.data);
        let ctap_response = parse_cbor!(Ctap2GetAssertionResponse, &data);
        debug!("CTAP2 GetNextAssertion successful");
        trace!(?ctap_response);
        Ok(ctap_response)
    }

    #[instrument(skip_all)]
    async fn ctap2_selection(&mut self, timeout: Duration) -> Result<(), Error> {
        debug!("CTAP2 Authenticator Selection request");
        let cbor_request = CborRequest::new(Ctap2CommandCode::AuthenticatorSelection);

        self.cbor_send(&cbor_request, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => {
                return Ok(());
            }
            error => {
                warn!(?error, "Selection request failed with status code");
                return Err(Error::Ctap(error));
            }
        }
    }

    #[instrument(skip_all)]
    async fn ctap2_client_pin(
        &mut self,
        request: &Ctap2ClientPinRequest,
        timeout: Duration,
    ) -> Result<Ctap2ClientPinResponse, Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        if let Some(data) = cbor_response.data {
            let ctap_response = parse_cbor!(Ctap2ClientPinResponse, &data);
            debug!("CTAP2 ClientPin successful");
            trace!(?ctap_response);
            Ok(ctap_response)
        } else {
            // Seems like a bug in serde_indexed: https://github.com/trussed-dev/serde-indexed/issues/10
            // Can't deserialize an empty vec[], even though everything is optional and marked as default.
            // So we work around it here by creating our own default value.
            Ok(Ctap2ClientPinResponse::default())
        }
    }

    #[instrument(skip_all)]
    async fn ctap2_authenticator_config(
        &mut self,
        request: &Ctap2AuthenticatorConfigRequest,
        timeout: Duration,
    ) -> Result<(), Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => {
                return Ok(());
            }
            error => {
                warn!(
                    ?error,
                    "Authenticator config request failed with status code"
                );
                return Err(Error::Ctap(error));
            }
        }
    }

    #[instrument(skip_all)]
    async fn ctap2_bio_enrollment(
        &mut self,
        request: &Ctap2BioEnrollmentRequest,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentResponse, Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        if let Some(data) = cbor_response.data {
            let ctap_response = parse_cbor!(Ctap2BioEnrollmentResponse, &data);
            debug!("CTAP2 BioEnrollment successful");
            trace!(?ctap_response);
            Ok(ctap_response)
        } else {
            // Seems like a bug in serde_indexed: https://github.com/trussed-dev/serde-indexed/issues/10
            // Can't deserialize an empty vec[], even though everything is optional and marked as default.
            // So we work around it here by creating our own default value.
            Ok(Ctap2BioEnrollmentResponse::default())
        }
    }

    #[instrument(skip_all)]
    async fn ctap2_credential_management(
        &mut self,
        request: &Ctap2CredentialManagementRequest,
        timeout: Duration,
    ) -> Result<Ctap2CredentialManagementResponse, Error> {
        trace!(?request);
        self.cbor_send(&request.try_into()?, timeout).await?;
        let cbor_response = self.cbor_recv(timeout).await?;
        match cbor_response.status_code {
            CtapError::Ok => (),
            error => return Err(Error::Ctap(error)),
        };
        if let Some(data) = cbor_response.data {
            let ctap_response = parse_cbor!(Ctap2CredentialManagementResponse, &data);
            debug!("CTAP2 CredentialManagement successful");
            trace!(?ctap_response);
            Ok(ctap_response)
        } else {
            // Seems like a bug in serde_indexed: https://github.com/trussed-dev/serde-indexed/issues/10
            // Can't deserialize an empty vec[], even though everything is optional and marked as default.
            // So we work around it here by creating our own default value.
            Ok(Ctap2CredentialManagementResponse::default())
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use serde_bytes::ByteBuf;

    use crate::proto::ctap2::cbor::{CborRequest, CborResponse};
    use crate::proto::ctap2::model::{
        Ctap2AuthenticatorConfigRequest, Ctap2BioEnrollmentRequest, Ctap2ClientPinRequest,
        Ctap2CredentialManagementRequest, Ctap2GetAssertionRequest, Ctap2MakeCredentialRequest,
        Ctap2PinUvAuthProtocol,
    };
    use crate::proto::ctap2::Ctap2CommandCode;
    use crate::transport::mock::channel::MockChannel;
    use crate::webauthn::error::{CtapError, Error};

    use super::Ctap2;

    const TIMEOUT: Duration = Duration::from_secs(1);

    fn error_response(status_code: CtapError) -> CborResponse {
        CborResponse {
            status_code,
            data: None,
        }
    }

    #[tokio::test]
    async fn ctap2_get_info_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let expected_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetInfo);
        channel.push_command_pair(expected_request, error_response(CtapError::Other));

        let result = channel.ctap2_get_info().await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::Other)));
    }

    // Regression test: cable's `cbor_send` blocks for the BLE handshake before
    // the per-leg timeout applies, so the protocol layer must not add an outer
    // wall-clock timeout that fires while the channel is still handshaking.
    #[tokio::test]
    async fn ctap2_get_info_tolerates_slow_cbor_send() {
        let mut channel = MockChannel::new();
        channel.set_pre_send_delay(super::TIMEOUT_GET_INFO + Duration::from_millis(50));
        let expected_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetInfo);
        channel.push_command_pair(expected_request, error_response(CtapError::Other));

        let result = channel.ctap2_get_info().await;
        assert_eq!(
            result.err(),
            Some(Error::Ctap(CtapError::Other)),
            "GetInfo must not impose a wall-clock timeout that fires before \
             the channel's own cbor_send returns"
        );
    }

    #[tokio::test]
    async fn ctap2_make_credential_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2MakeCredentialRequest::dummy();
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(expected_request, error_response(CtapError::OperationDenied));

        let result = channel.ctap2_make_credential(&request, TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::OperationDenied)));
    }

    #[tokio::test]
    async fn ctap2_get_assertion_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2GetAssertionRequest {
            relying_party_id: "example.org".to_owned(),
            client_data_hash: ByteBuf::from(vec![0u8; 32]),
            allow: vec![],
            extensions: None,
            options: None,
            pin_auth_param: None,
            pin_auth_proto: None,
        };
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(expected_request, error_response(CtapError::NoCredentials));

        let result = channel.ctap2_get_assertion(&request, TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::NoCredentials)));
    }

    #[tokio::test]
    async fn ctap2_get_next_assertion_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let expected_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetNextAssertion);
        // Simulate the authenticator returning CTAP2_ERR_NOT_ALLOWED (0x30),
        // which is the spec-defined error when no further assertion is
        // available within the 30-second window.
        channel.push_command_pair(expected_request, error_response(CtapError::NotAllowed));

        let result = channel.ctap2_get_next_assertion(TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::NotAllowed)));
    }

    #[tokio::test]
    async fn ctap2_get_next_assertion_does_not_parse_data_on_error() {
        let mut channel = MockChannel::new();
        let expected_request = CborRequest::new(Ctap2CommandCode::AuthenticatorGetNextAssertion);
        // Per CTAP 2.2 ยง8, when the status byte is non-zero the trailing bytes
        // are undefined. Make sure the library surfaces the status error and
        // never reaches the CBOR parser, regardless of payload contents.
        let response = CborResponse {
            status_code: CtapError::Other,
            data: Some(vec![0xff, 0xff, 0xff, 0xff]),
        };
        channel.push_command_pair(expected_request, response);

        let result = channel.ctap2_get_next_assertion(TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::Other)));
    }

    #[tokio::test]
    async fn ctap2_client_pin_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2ClientPinRequest::new_get_key_agreement(Ctap2PinUvAuthProtocol::One);
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(expected_request, error_response(CtapError::PINBlocked));

        let result = channel.ctap2_client_pin(&request, TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::PINBlocked)));
    }

    #[tokio::test]
    async fn ctap2_selection_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let expected_request = CborRequest::new(Ctap2CommandCode::AuthenticatorSelection);
        // Selection returns Ok(()) on success, so cover the error path
        // explicitly.
        channel.push_command_pair(
            expected_request,
            error_response(CtapError::UserActionTimeout),
        );

        let result = channel.ctap2_selection(TIMEOUT).await;
        assert_eq!(
            result.err(),
            Some(Error::Ctap(CtapError::UserActionTimeout))
        );
    }

    #[tokio::test]
    async fn ctap2_authenticator_config_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2AuthenticatorConfigRequest::new_toggle_always_uv();
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(
            expected_request,
            error_response(CtapError::UnauthorizedPermission),
        );

        let result = channel.ctap2_authenticator_config(&request, TIMEOUT).await;
        assert_eq!(
            result.err(),
            Some(Error::Ctap(CtapError::UnauthorizedPermission))
        );
    }

    #[tokio::test]
    async fn ctap2_bio_enrollment_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2BioEnrollmentRequest {
            modality: None,
            subcommand: None,
            subcommand_params: None,
            protocol: None,
            uv_auth_param: None,
            get_modality: Some(true),
            use_legacy_preview: false,
        };
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(expected_request, error_response(CtapError::InvalidOption));

        let result = channel.ctap2_bio_enrollment(&request, TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::InvalidOption)));
    }

    #[tokio::test]
    async fn ctap2_credential_management_propagates_non_ok_status() {
        let mut channel = MockChannel::new();
        let request = Ctap2CredentialManagementRequest {
            subcommand: None,
            subcommand_params: None,
            protocol: None,
            uv_auth_param: None,
            use_legacy_preview: false,
        };
        let expected_request: CborRequest = (&request).try_into().unwrap();
        channel.push_command_pair(expected_request, error_response(CtapError::PINRequired));

        let result = channel.ctap2_credential_management(&request, TIMEOUT).await;
        assert_eq!(result.err(), Some(Error::Ctap(CtapError::PINRequired)));
    }
}