libwebauthn 0.7.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
use crate::proto::ctap2::cbor;
use crate::{
    ops::webauthn::UserVerificationRequirement,
    pin::PinUvAuthProtocol,
    proto::ctap2::{
        Ctap2, Ctap2AuthTokenPermissionRole, Ctap2BioEnrollmentFingerprintKind,
        Ctap2BioEnrollmentModality, Ctap2BioEnrollmentRequest, Ctap2BioEnrollmentTemplateId,
        Ctap2ClientPinRequest, Ctap2GetInfoResponse, Ctap2LastEnrollmentSampleStatus,
        Ctap2UserVerifiableRequest,
    },
    transport::Channel,
    unwrap_field,
    webauthn::{
        error::{CtapError, Error, PlatformError},
        handle_errors,
        pin_uv_auth_token::{user_verification, UsedPinUvAuthToken},
    },
    UvUpdate,
};
use async_trait::async_trait;
use serde_bytes::ByteBuf;
use std::time::Duration;
use tracing::{info, warn};

#[async_trait]
pub trait BioEnrollment {
    async fn get_bio_modality(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentModality, Error>;
    async fn get_fingerprint_sensor_info(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentFingerprintSensorInfo, Error>;
    async fn get_bio_enrollments(
        &mut self,
        timeout: Duration,
    ) -> Result<Vec<Ctap2BioEnrollmentTemplateId>, Error>;
    async fn remove_bio_enrollment(
        &mut self,
        template_id: &[u8],
        timeout: Duration,
    ) -> Result<(), Error>;
    async fn rename_bio_enrollment(
        &mut self,
        template_id: &[u8],
        template_friendly_name: &str,
        timeout: Duration,
    ) -> Result<(), Error>;
    async fn start_new_bio_enrollment(
        &mut self,
        enrollment_timeout: Option<Duration>,
        timeout: Duration,
    ) -> Result<(Vec<u8>, Ctap2LastEnrollmentSampleStatus, u64), Error>;
    async fn capture_next_bio_enrollment_sample(
        &mut self,
        template_id: &[u8],
        enrollment_timeout: Option<Duration>,
        timeout: Duration,
    ) -> Result<(Ctap2LastEnrollmentSampleStatus, u64), Error>;
    async fn cancel_current_bio_enrollment(&mut self, timeout: Duration) -> Result<(), Error>;
}

#[derive(Debug, Clone)]
pub struct Ctap2BioEnrollmentFingerprintSensorInfo {
    pub fingerprint_kind: Ctap2BioEnrollmentFingerprintKind,
    pub max_capture_samples_required_for_enroll: Option<u64>,
    /// Not returned/supported by BioEnrollmentPreview
    pub max_template_friendly_name: Option<u64>,
}

#[async_trait]
impl<C> BioEnrollment for C
where
    C: Channel,
{
    async fn get_bio_modality(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentModality, Error> {
        let req = Ctap2BioEnrollmentRequest::new_get_modality();
        // No UV needed
        let resp = self.ctap2_bio_enrollment(&req, timeout).await?;
        match resp.modality {
            Some(modality) => Ok(modality),
            None => {
                warn!("Channel did not return modality.");
                Err(Error::Ctap(CtapError::Other))
            }
        }
    }

    async fn get_fingerprint_sensor_info(
        &mut self,
        timeout: Duration,
    ) -> Result<Ctap2BioEnrollmentFingerprintSensorInfo, Error> {
        let req = Ctap2BioEnrollmentRequest::new_fingerprint_sensor_info();
        // No UV needed
        let resp = self.ctap2_bio_enrollment(&req, timeout).await?;
        let Some(fingerprint_kind) = resp.fingerprint_kind else {
            warn!("Channel did not return fingerprint_kind in sensor info.");
            return Err(Error::Ctap(CtapError::Other));
        };
        Ok(Ctap2BioEnrollmentFingerprintSensorInfo {
            fingerprint_kind,
            max_capture_samples_required_for_enroll: resp.max_capture_samples_required_for_enroll,
            max_template_friendly_name: resp.max_template_friendly_name,
        })
    }

    async fn get_bio_enrollments(
        &mut self,
        timeout: Duration,
    ) -> Result<Vec<Ctap2BioEnrollmentTemplateId>, Error> {
        let mut req = Ctap2BioEnrollmentRequest::new_enumerate_enrollments();

        let resp = loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        };
        Ok(resp?.template_infos.unwrap_or_default())
    }

    async fn remove_bio_enrollment(
        &mut self,
        template_id: &[u8],
        timeout: Duration,
    ) -> Result<(), Error> {
        let mut req = Ctap2BioEnrollmentRequest::new_remove_enrollment(template_id);

        loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        }?;

        // "If there is an exiting enrollment with passed in templateInfo, delete that enrollment and return CTAP2_OK."
        // So, the resulting Response will be empty on success.
        Ok(())
    }

    async fn rename_bio_enrollment(
        &mut self,
        template_id: &[u8],
        template_friendly_name: &str,
        timeout: Duration,
    ) -> Result<(), Error> {
        let mut req =
            Ctap2BioEnrollmentRequest::new_rename_enrollment(template_id, template_friendly_name);
        loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        }?;
        // "If there is an exiting enrollment with passed in templateInfo, delete that enrollment and return CTAP2_OK."
        // So, the resulting Response will be empty on success.
        Ok(())
    }

    async fn start_new_bio_enrollment(
        &mut self,
        enrollment_timeout: Option<Duration>,
        timeout: Duration,
    ) -> Result<(Vec<u8>, Ctap2LastEnrollmentSampleStatus, u64), Error> {
        let mut req = Ctap2BioEnrollmentRequest::new_start_new_enrollment(enrollment_timeout);

        let resp = loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        }?;

        let remaining_samples = unwrap_field!(resp.remaining_samples);
        let template_id = unwrap_field!(resp.template_id);
        let sample_status = unwrap_field!(resp.last_enroll_sample_status);
        Ok((template_id.into_vec(), sample_status, remaining_samples))
    }

    async fn capture_next_bio_enrollment_sample(
        &mut self,
        template_id: &[u8],
        enrollment_timeout: Option<Duration>,
        timeout: Duration,
    ) -> Result<(Ctap2LastEnrollmentSampleStatus, u64), Error> {
        let mut req =
            Ctap2BioEnrollmentRequest::new_next_enrollment(template_id, enrollment_timeout);

        let resp = loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        }?;

        let remaining_samples = unwrap_field!(resp.remaining_samples);
        let sample_status = unwrap_field!(resp.last_enroll_sample_status);
        Ok((sample_status, remaining_samples))
    }

    async fn cancel_current_bio_enrollment(&mut self, timeout: Duration) -> Result<(), Error> {
        let mut req = Ctap2BioEnrollmentRequest::new_cancel_current_enrollment();

        loop {
            let uv_auth_used = user_verification(
                self,
                UserVerificationRequirement::Preferred,
                &mut req,
                timeout,
            )
            .await?;

            // On success, this is an all-empty Ctap2AuthenticatorConfigResponse
            handle_errors!(
                self,
                self.ctap2_bio_enrollment(&req, timeout).await,
                uv_auth_used,
                timeout
            )
        }?;

        // "Authenticator on receiving such command, cancels current ongoing enrollment, if any, and returns CTAP2_OK."
        // So, the resulting Response will be empty on success.
        Ok(())
    }
}

impl Ctap2UserVerifiableRequest for Ctap2BioEnrollmentRequest {
    fn ensure_uv_set(&mut self) {
        // No-op
    }

    fn calculate_and_set_uv_auth(
        &mut self,
        uv_proto: &dyn PinUvAuthProtocol,
        uv_auth_token: &[u8],
    ) -> Result<(), Error> {
        // pinUvAuthParam (0x05): authenticate(pinUvAuthToken, fingerprint (0x01) || enumerateEnrollments (0x04)).
        let subcommand = self
            .subcommand
            .ok_or(Error::Platform(PlatformError::InvalidDeviceResponse))?;
        let mut data = vec![
            Ctap2BioEnrollmentModality::Fingerprint as u8,
            subcommand as u8,
        ];
        // e.g. "Authenticator calls verify(pinUvAuthToken, fingerprint (0x01) || removeEnrollment (0x06) || subCommandParams, pinUvAuthParam)"
        if let Some(params) = &self.subcommand_params {
            data.extend(cbor::to_vec(&params)?);
        }
        let uv_auth_param = uv_proto.authenticate(uv_auth_token, &data)?;
        self.protocol = Some(uv_proto.version());
        self.uv_auth_param = Some(ByteBuf::from(uv_auth_param));
        Ok(())
    }

    fn permissions(&self) -> Ctap2AuthTokenPermissionRole {
        Ctap2AuthTokenPermissionRole::BIO_ENROLLMENT
    }

    fn permissions_rpid(&self) -> Option<&str> {
        None
    }

    fn can_use_uv(&self, info: &Ctap2GetInfoResponse) -> bool {
        info.option_enabled("uvBioEnroll")
    }

    fn handle_legacy_preview(&mut self, info: &Ctap2GetInfoResponse) {
        if let Some(options) = &info.options {
            // According to Spec, we would also need to verify the token only
            // supports FIDO_2_1_PRE, but let's be a bit less strict here and
            // accept it simply reporting preview-support, but not the real one.
            if options.get("bioEnroll") != Some(&true)
                && options.get("userVerificationMgmtPreview") == Some(&true)
            {
                self.use_legacy_preview = true;
            }
        }
    }

    fn needs_shared_secret(&self, _get_info_response: &Ctap2GetInfoResponse) -> bool {
        false
    }
}

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

    use serde_bytes::ByteBuf;
    use serde_indexed::SerializeIndexed;

    use super::BioEnrollment;
    use crate::proto::ctap2::cbor::{self, CborRequest, CborResponse};
    use crate::proto::ctap2::{
        Ctap2BioEnrollmentRequest, Ctap2CommandCode, Ctap2GetInfoResponse,
        Ctap2LastEnrollmentSampleStatus,
    };
    use crate::transport::mock::channel::MockChannel;

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

    // Indexed map enrollBegin returns: templateId (0x04), lastEnrollSampleStatus (0x05), remainingSamples (0x06).
    #[derive(SerializeIndexed)]
    struct EnrollBeginResponse {
        #[serde(index = 0x04)]
        template_id: ByteBuf,
        #[serde(index = 0x05)]
        last_enroll_sample_status: Ctap2LastEnrollmentSampleStatus,
        #[serde(index = 0x06)]
        remaining_samples: u64,
    }

    // GetInfo for a device without any UV, so user_verification returns without a PIN/UV round-trip.
    fn push_no_uv_get_info(channel: &mut MockChannel) {
        let info = Ctap2GetInfoResponse::default();
        let req = CborRequest::new(Ctap2CommandCode::AuthenticatorGetInfo);
        let resp = CborResponse::new_success_from_slice(&cbor::to_vec(&info).unwrap());
        channel.push_command_pair(req, resp);
    }

    #[tokio::test]
    async fn start_new_bio_enrollment_returns_raw_template_id() {
        let template = [0x1D_u8; 16];
        let mut channel = MockChannel::new();
        push_no_uv_get_info(&mut channel);

        let req = Ctap2BioEnrollmentRequest::new_start_new_enrollment(None);
        let fixture = EnrollBeginResponse {
            template_id: ByteBuf::from(template.to_vec()),
            last_enroll_sample_status: Ctap2LastEnrollmentSampleStatus::Ctap2EnrollFeedbackFpGood,
            remaining_samples: 4,
        };
        let resp = CborResponse::new_success_from_slice(&cbor::to_vec(&fixture).unwrap());
        channel.push_command_pair((&req).try_into().unwrap(), resp);

        let (template_id, _status, remaining) = channel
            .start_new_bio_enrollment(None, TIMEOUT)
            .await
            .unwrap();
        assert_eq!(remaining, 4);
        // Raw template id, not a CBOR byte string (0x50 || template = 17 bytes).
        assert_eq!(template_id.len(), template.len());
        assert_eq!(template_id, template.to_vec());
    }
}