fido2-rs 0.4.0

Rust bindings to Yubico fido2
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
use crate::assertion::{AssertRequest, Assertions};
use crate::cbor::CBORInfo;
use crate::credentials::Credential;
use crate::credman::CredentialManagement;
use crate::error::{Error, Result};
use crate::utils::check;
use bitflags::bitflags;
use ffi::fido_dev_t;
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::ptr::NonNull;
use zeroize::Zeroizing;

/// Device list.
///
/// contain fido devices found by the underlying operating system.
///
/// user can call [DeviceList::list_devices] to start enumerate fido devices.
pub struct DeviceList<'a> {
    ptr: NonNull<ffi::fido_dev_info_t>,
    idx: usize,
    found: usize,
    _p: PhantomData<&'a ()>,
}

impl<'a> DeviceList<'a> {
    /// Enumerate up to `max` fido devices found by the underlying operating system.
    ///
    /// Currently only USB HID devices are supported
    pub fn list_devices(max: usize) -> DeviceList<'a> {
        unsafe {
            let mut found = 0;
            let ptr = ffi::fido_dev_info_new(max);

            ffi::fido_dev_info_manifest(ptr, max, &mut found);

            DeviceList {
                ptr: NonNull::new_unchecked(ptr),
                idx: 0,
                found,
                _p: PhantomData,
            }
        }
    }
}

impl<'a> Iterator for DeviceList<'a> {
    type Item = DeviceInfo<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.found {
            return None;
        }

        unsafe {
            let ptr = self.ptr.as_ptr();
            let info = ffi::fido_dev_info_ptr(ptr, self.idx);

            let path = ffi::fido_dev_info_path(info);
            let path = CStr::from_ptr(path);

            let product_id = ffi::fido_dev_info_product(info);
            let vendor_id = ffi::fido_dev_info_vendor(info);

            let manufacturer = ffi::fido_dev_info_manufacturer_string(info);
            let manufacturer = CStr::from_ptr(manufacturer);

            let product = ffi::fido_dev_info_product_string(info);
            let product = CStr::from_ptr(product);
            self.idx += 1;

            Some(DeviceInfo {
                path,
                product_id,
                vendor_id,
                manufacturer,
                product,
            })
        }
    }
}

impl<'a> ExactSizeIterator for DeviceList<'a> {
    fn len(&self) -> usize {
        self.found
    }
}

impl<'a> Drop for DeviceList<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::fido_dev_info_free(&mut self.ptr.as_ptr(), self.found);
        }
    }
}

/// Device info obtained from [DeviceList]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DeviceInfo<'a> {
    pub path: &'a CStr,
    pub product_id: i16,
    pub vendor_id: i16,
    pub manufacturer: &'a CStr,
    pub product: &'a CStr,
}

impl<'a> DeviceInfo<'a> {
    /// Open the device specified by this [DeviceInfo]
    pub fn open(&self) -> Result<Device> {
        unsafe {
            let ptr = ffi::fido_dev_new();
            check(ffi::fido_dev_open(ptr, self.path.as_ptr()))?;

            let ptr = NonNull::new_unchecked(ptr);

            Ok(Device { ptr })
        }
    }
}

/// A cancel handle to device, used to cancel a pending requests.
///
/// This handle can be copy/clone.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct DeviceCancel(NonNull<fido_dev_t>);

impl DeviceCancel {
    /// Cancel any pending requests on device.
    pub fn cancel(&self) {
        unsafe {
            ffi::fido_dev_cancel(self.0.as_ptr());
        }
    }
}

/// A fido device.
pub struct Device {
    pub(crate) ptr: NonNull<fido_dev_t>,
}

impl Device {
    /// Open the device pointed to by `path`.
    ///
    /// If dev claims to be FIDO2, libfido2 will attempt to speak FIDO2 to dev.
    /// If that fails, libfido2 will fallback to U2F unless the FIDO_DISABLE_U2F_FALLBACK flag
    /// was set in fido_init(3).
    pub fn open(path: impl AsRef<str>) -> Result<Device> {
        let path = CString::new(path.as_ref())?;
        unsafe {
            let dev = ffi::fido_dev_new();
            assert!(!dev.is_null());

            check(ffi::fido_dev_open(dev, path.as_ptr()))?;

            Ok(Device {
                ptr: NonNull::new_unchecked(dev),
            })
        }
    }

    /// Get a handle of this device for cancel.
    pub fn cancel_handle(&self) -> DeviceCancel {
        DeviceCancel(self.ptr)
    }

    /// can be used to force CTAP2 communication with dev
    pub fn force_u2f(&self) {
        unsafe {
            ffi::fido_dev_force_u2f(self.ptr.as_ptr());
        }
    }

    /// Can be used to force CTAP1 (U2F) communication with dev
    pub fn force_fido2(&self) {
        unsafe {
            ffi::fido_dev_force_fido2(self.ptr.as_ptr());
        }
    }

    /// Returns true if dev is a FIDO2 device.
    pub fn is_fido2(&self) -> bool {
        unsafe { ffi::fido_dev_is_fido2(self.ptr.as_ptr()) }
    }

    /// Returns true if dev is a Windows Hello device.
    pub fn is_winhello(&self) -> bool {
        unsafe { ffi::fido_dev_is_winhello(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports CTAP 2.1 Credential Management.
    pub fn supports_credman(&self) -> bool {
        unsafe { ffi::fido_dev_supports_credman(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports CTAP 2.1 Credential Protection.
    pub fn supports_cred_prot(&self) -> bool {
        unsafe { ffi::fido_dev_supports_cred_prot(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports CTAP 2.1 UV token permissions.
    pub fn supports_permission(&self) -> bool {
        unsafe { ffi::fido_dev_supports_permissions(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports CTAP 2.0 Client PINs.
    pub fn supports_pin(&self) -> bool {
        unsafe { ffi::fido_dev_supports_pin(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports a built-in user verification method.
    pub fn supports_uv(&self) -> bool {
        unsafe { ffi::fido_dev_supports_uv(self.ptr.as_ptr()) }
    }

    /// Returns true if dev has a CTAP 2.0 Client PIN set.
    pub fn has_pin(&self) -> bool {
        unsafe { ffi::fido_dev_has_pin(self.ptr.as_ptr()) }
    }

    /// Returns true if dev supports built-in user verification and its user verification feature is configured.
    pub fn has_uv(&self) -> bool {
        unsafe { ffi::fido_dev_has_uv(self.ptr.as_ptr()) }
    }

    /// Return CTAPHID protocol info.
    pub fn ctap_protocol(&self) -> CTAPHIDInfo {
        unsafe {
            let protocol = ffi::fido_dev_protocol(self.ptr.as_ptr());
            let build = ffi::fido_dev_build(self.ptr.as_ptr());
            let flags = ffi::fido_dev_flags(self.ptr.as_ptr());
            let flags = CTAPHIDFlags::from_bits_truncate(flags);
            let major = ffi::fido_dev_major(self.ptr.as_ptr());
            let minor = ffi::fido_dev_minor(self.ptr.as_ptr());

            CTAPHIDInfo {
                protocol,
                build,
                flags,
                major,
                minor,
            }
        }
    }

    /// Return device info.
    pub fn info(&self) -> Result<CBORInfo> {
        let info = CBORInfo::new();

        unsafe {
            check(ffi::fido_dev_get_cbor_info(
                self.ptr.as_ptr(),
                info.ptr.as_ptr(),
            ))?;
        }

        Ok(info)
    }

    pub fn get_retry_count(&self) -> Result<i32> {
        let mut res = 0;
        unsafe {
            check(ffi::fido_dev_get_retry_count(
                self.ptr.as_ptr(),
                &mut res as *mut i32,
            ))?;
        }
        Ok(res)
    }

    pub fn get_uv_retry_count(&self) -> Result<i32> {
        let mut res = 0;
        unsafe {
            check(ffi::fido_dev_get_uv_retry_count(
                self.ptr.as_ptr(),
                &mut res as *mut i32,
            ))?;
        }
        Ok(res)
    }

    /// Generates a new credential on a FIDO2 device.
    ///
    /// Ask the FIDO2 device represented by dev to generate a new credential according to the following parameters defined in cred:
    /// * type
    /// * client data hash
    /// * relying party
    /// * user attributes
    /// * list of excluded credential IDs
    /// * resident/discoverable key and user verification attributes
    ///
    /// If a PIN is not needed to authenticate the request against dev, then pin may be [None].
    ///
    /// **Please note that fido_dev_make_cred() is synchronous and will block if necessary.**
    ///
    /// # Example
    /// ```rust,no_run
    /// use fido2_rs::credentials::Credential;
    /// use fido2_rs::device::Device;
    /// use fido2_rs::credentials::CoseType;
    ///
    /// fn main() -> anyhow::Result<()> {
    ///     let dev = Device::open("windows://hello").expect("unable open device");
    ///     let mut cred = Credential::new();
    ///     cred.set_client_data(&[1, 2, 3, 4, 5, 6])?;
    ///     cred.set_rp("fido_rs", "fido example")?;
    ///     cred.set_user(&[1, 2, 3, 4, 5, 6], "alice", Some("alice"), None)?;
    ///     cred.set_cose_type(CoseType::RS256)?;
    ///
    ///     let _ = dev.make_credential(&mut cred, None)?;    // and not require pin..
    ///
    ///     dbg!(cred.id());
    ///     Ok(())
    /// }
    /// ```
    pub fn make_credential(&self, credential: &mut Credential, pin: Option<&str>) -> Result<()> {
        let pin = pin.map(CString::new).transpose()?;
        let pin_ptr = match &pin {
            Some(pin) => pin.as_ptr(),
            None => std::ptr::null(),
        };

        unsafe {
            check(ffi::fido_dev_make_cred(
                self.ptr.as_ptr(),
                credential.0.as_ptr(),
                pin_ptr,
            ))?;
        }

        Ok(())
    }

    /// Obtains an assertion from a FIDO2 device.
    ///
    /// Ask the FIDO2 device represented by dev for an assertion according to the following parameters defined in assert:
    /// * relying party ID
    /// * client data hash
    /// * list of allowed credential IDs
    /// * user presence and user verification attributes
    ///
    /// If a PIN is not needed to authenticate the request against dev, then pin may be NULL.
    ///
    /// **Please note that fido_dev_get_assert() is synchronous and will block if necessary.**
    ///
    /// # Example
    /// ```rust,no_run
    /// use fido2_rs::assertion::AssertRequest;
    /// use fido2_rs::credentials::Opt;
    /// use fido2_rs::device::Device;
    ///
    /// fn main() -> anyhow::Result<()> {
    ///     let dev = Device::open("windows://hello")?;
    ///     let mut request = AssertRequest::new();    ///
    ///
    ///     request.set_rp("fido_rs")?;
    ///     request.set_client_data(&[1, 2, 3, 4, 5, 6])?;
    ///     request.set_uv(Opt::True)?;
    ///
    ///     let _assertions = dev.get_assertion(request, None)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn get_assertion(&self, request: AssertRequest, pin: Option<&str>) -> Result<Assertions> {
        let pin = pin.map(CString::new).transpose()?;
        let pin_ptr = match &pin {
            Some(pin) => pin.as_ptr(),
            None => std::ptr::null(),
        };

        unsafe {
            check(ffi::fido_dev_get_assert(
                self.ptr.as_ptr(),
                request.0.ptr.as_ptr(),
                pin_ptr,
            ))?;
        }

        Ok(request.0)
    }

    /// Obtain a handle to the credential management interface of a FIDO2 device.
    ///
    /// A valid pin must be provided. If the device does not support credential management,
    /// or an error happened, error will be returned.
    ///
    /// **Pin will be kept in memory and zeroized securely when the returned CredentialManagement is dropped.**
    pub fn credman(&self, pin: &str) -> Result<CredentialManagement<'_>> {
        if !self.supports_credman() {
            return Err(Error::Unsupported);
        }

        let ptr = unsafe { ffi::fido_credman_metadata_new() };

        let pin = CString::new(pin)?;
        let pin_ptr = pin.as_ptr();

        unsafe {
            check(ffi::fido_credman_get_dev_metadata(
                self.ptr.as_ptr(),
                ptr,
                pin_ptr,
            ))?;
        }

        let ptr = unsafe { NonNull::new_unchecked(ptr) };
        let credman = CredentialManagement::new(ptr, &self, Zeroizing::new(pin));

        Ok(credman)
    }
}

impl Drop for Device {
    fn drop(&mut self) {
        unsafe {
            let _ = ffi::fido_dev_close(self.ptr.as_ptr());
            ffi::fido_dev_free(&mut self.ptr.as_ptr());
        }
    }
}

bitflags! {
    /// CTAPHID capabilities
    #[derive(Copy, Clone, Debug, Eq, PartialEq)]
    pub struct CTAPHIDFlags: u8 {
        const WINK = ffi::FIDO_CAP_WINK as u8;
        const CBOR = ffi::FIDO_CAP_CBOR as u8;
        const NMSG = ffi::FIDO_CAP_NMSG as u8;
    }
}

/// For the format and meaning of the CTAPHID parameters,
/// please refer to the FIDO Client to Authenticator Protocol (CTAP) specification.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct CTAPHIDInfo {
    /// CTAPHID protocol version identifier of dev
    pub protocol: u8,
    /// CTAPHID build version number of dev.
    pub build: u8,
    /// CTAPHID capabilities flags of dev.
    pub flags: CTAPHIDFlags,
    /// CTAPHID major version number of dev.
    pub major: u8,
    /// CTAPHID minor version number of dev.
    pub minor: u8,
}