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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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::{allocation_error, check, cstring_from_ptr_or_empty};
use bitflags::bitflags;
use ffi::fido_dev_t;
use std::ffi::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 {
ptr: NonNull<ffi::fido_dev_info_t>,
idx: usize,
found: usize,
capacity: usize,
}
impl DeviceList {
/// 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) -> Result<DeviceList> {
unsafe {
let mut found = 0;
let ptr = ffi::fido_dev_info_new(max);
let ptr = NonNull::new(ptr).ok_or_else(allocation_error)?;
if let Err(err) = check(ffi::fido_dev_info_manifest(ptr.as_ptr(), max, &mut found)) {
let mut raw = ptr.as_ptr();
ffi::fido_dev_info_free(&mut raw, max);
return Err(err.into());
}
Ok(DeviceList {
ptr,
idx: 0,
found,
capacity: max,
})
}
}
}
impl Iterator for DeviceList {
type Item = DeviceInfo;
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 = cstring_from_ptr_or_empty(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 = cstring_from_ptr_or_empty(manufacturer);
let product = ffi::fido_dev_info_product_string(info);
let product = cstring_from_ptr_or_empty(product);
self.idx += 1;
Some(DeviceInfo {
path,
product_id,
vendor_id,
manufacturer,
product,
})
}
}
}
impl ExactSizeIterator for DeviceList {
fn len(&self) -> usize {
self.found - self.idx
}
}
impl Drop for DeviceList {
fn drop(&mut self) {
unsafe {
let mut raw = self.ptr.as_ptr();
ffi::fido_dev_info_free(&mut raw, self.capacity);
}
}
}
/// Device info obtained from [DeviceList]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeviceInfo {
pub path: CString,
pub product_id: i16,
pub vendor_id: i16,
pub manufacturer: CString,
pub product: CString,
}
impl DeviceInfo {
/// Open the device specified by this [DeviceInfo]
pub fn open(&self) -> Result<Device> {
unsafe {
let ptr = ffi::fido_dev_new();
let ptr = NonNull::new(ptr).ok_or_else(allocation_error)?;
if let Err(err) = check(ffi::fido_dev_open(ptr.as_ptr(), self.path.as_ptr())) {
let mut raw = ptr.as_ptr();
ffi::fido_dev_free(&mut raw);
return Err(err.into());
}
Ok(Device { ptr })
}
}
}
/// A cancel handle to device, used to cancel a pending requests.
///
/// This handle can be copy/clone and cannot outlive the device it cancels.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct DeviceCancel<'a> {
ptr: NonNull<fido_dev_t>,
_p: PhantomData<&'a Device>,
}
impl DeviceCancel<'_> {
/// Cancel any pending requests on device.
pub fn cancel(&self) {
unsafe {
ffi::fido_dev_cancel(self.ptr.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();
let dev = NonNull::new(dev).ok_or_else(allocation_error)?;
if let Err(err) = check(ffi::fido_dev_open(dev.as_ptr(), path.as_ptr())) {
let mut raw = dev.as_ptr();
ffi::fido_dev_free(&mut raw);
return Err(err.into());
}
Ok(Device { ptr: dev })
}
}
/// Get a handle of this device for cancel.
pub fn cancel_handle(&self) -> DeviceCancel<'_> {
DeviceCancel {
ptr: self.ptr,
_p: PhantomData,
}
}
/// Can be used to force CTAP1 (U2F) communication with dev.
pub fn force_u2f(&self) {
unsafe {
ffi::fido_dev_force_u2f(self.ptr.as_ptr());
}
}
/// Can be used to force CTAP2 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.
///
/// If the device has a PIN set, a valid PIN must be provided as `Some(pin)`.
/// For devices with no PIN configured, pass `None`.
///
/// If the device does not support credential management, or an error happened,
/// an error will be returned.
///
/// **Pin will be kept in memory and zeroized securely when the returned CredentialManagement is dropped.**
pub fn credman(&self, pin: Option<&str>) -> Result<CredentialManagement<'_>> {
if !self.supports_credman() {
return Err(Error::Unsupported);
}
let pin = pin.map(CString::new).transpose()?;
let pin_ptr = match &pin {
Some(pin) => pin.as_ptr(),
None => std::ptr::null(),
};
let ptr = unsafe { ffi::fido_credman_metadata_new() };
let ptr = NonNull::new(ptr).ok_or_else(allocation_error)?;
unsafe {
if let Err(err) = check(ffi::fido_credman_get_dev_metadata(
self.ptr.as_ptr(),
ptr.as_ptr(),
pin_ptr,
)) {
let mut raw = ptr.as_ptr();
ffi::fido_credman_metadata_free(&mut raw);
return Err(err.into());
}
}
let credman = CredentialManagement::new(ptr, self, pin.map(Zeroizing::new));
Ok(credman)
}
/// Set or change the FIDO2 device PIN.
///
/// If `old_pin` is `None`, this sets the initial PIN on a device that has no
/// PIN configured yet. If `old_pin` is `Some(...)`, this changes the PIN from
/// `old_pin` to `new_pin`.
///
/// **Please note that `fido_dev_set_pin()` is synchronous and will block if necessary.**
pub fn set_pin(&self, new_pin: &str, old_pin: Option<&str>) -> Result<()> {
let new_pin = CString::new(new_pin)?;
let old_pin = old_pin.map(CString::new).transpose()?;
let old_pin_ptr = match &old_pin {
Some(p) => p.as_ptr(),
None => std::ptr::null(),
};
unsafe {
check(ffi::fido_dev_set_pin(
self.ptr.as_ptr(),
new_pin.as_ptr(),
old_pin_ptr,
))?;
}
Ok(())
}
/// Perform a factory reset of the FIDO2 application on the device.
///
/// This erases all FIDO2 credentials, the device PIN, and all largeBlob data.
/// Other applets (PIV, OpenPGP, etc.) are not affected.
///
/// The CTAP2 specification requires the device to have been powered on within
/// approximately 10 seconds for a reset to succeed. If the device has been
/// connected for longer, it will return `FIDO_ERR_NOT_ALLOWED`.
///
/// **Please note that `fido_dev_reset()` is synchronous and will block if necessary.**
pub fn reset(&self) -> Result<()> {
unsafe {
check(ffi::fido_dev_reset(self.ptr.as_ptr()))?;
}
Ok(())
}
/// Read a largeBlob entry from the device, decrypting it with the given key.
///
/// The `key` is a 32-byte `largeBlobKey` obtained from a credential's
/// `large_blob_key()` (via `make_credential` or `get_assertion` with the
/// `LARGEBLOB_KEY` extension).
///
/// Returns the decrypted data, or an error if no entry matches the key.
///
/// No PIN is required for reads.
///
/// **Please note that `fido_dev_largeblob_get()` is synchronous and will block if necessary.**
pub fn largeblob_get(&self, key: &[u8]) -> Result<Vec<u8>> {
let mut data_ptr: *mut u8 = std::ptr::null_mut();
let mut data_len: usize = 0;
unsafe {
check(ffi::fido_dev_largeblob_get(
self.ptr.as_ptr(),
key.as_ptr(),
key.len(),
&mut data_ptr,
&mut data_len,
))?;
if data_ptr.is_null() {
return Ok(Vec::new());
}
let data = std::slice::from_raw_parts(data_ptr, data_len).to_vec();
libc::free(data_ptr as *mut libc::c_void);
Ok(data)
}
}
/// Store data as a largeBlob entry on the device, encrypted with the given key.
///
/// The `key` is a 32-byte `largeBlobKey` obtained from a credential's
/// `large_blob_key()`. If an entry for this key already exists, it is
/// overwritten.
///
/// PIN is required for write operations.
///
/// # Storage
///
/// The largeBlob array is **shared across all credentials** and is very
/// small — typically 1024–4096 bytes total, with ~28 bytes of encryption
/// overhead per entry. Not suitable for sensitive data: the encryption key
/// is transmitted in the clear and the array can be read without user
/// verification. See the [CTAP 2.1 spec, §6.10][spec] for details.
///
/// [spec]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#authenticatorLargeBlobs
///
/// **Please note that `fido_dev_largeblob_set()` is synchronous and will block if necessary.**
pub fn largeblob_set(&self, key: &[u8], data: &[u8], pin: &str) -> Result<()> {
let pin = CString::new(pin)?;
unsafe {
check(ffi::fido_dev_largeblob_set(
self.ptr.as_ptr(),
key.as_ptr(),
key.len(),
data.as_ptr(),
data.len(),
pin.as_ptr(),
))?;
}
Ok(())
}
/// Remove a largeBlob entry from the device.
///
/// The `key` is a 32-byte `largeBlobKey` identifying the entry to remove.
///
/// PIN is required for remove operations.
///
/// **Please note that `fido_dev_largeblob_remove()` is synchronous and will block if necessary.**
pub fn largeblob_remove(&self, key: &[u8], pin: &str) -> Result<()> {
let pin = CString::new(pin)?;
unsafe {
check(ffi::fido_dev_largeblob_remove(
self.ptr.as_ptr(),
key.as_ptr(),
key.len(),
pin.as_ptr(),
))?;
}
Ok(())
}
/// Read the raw serialized largeBlob CBOR array from the device.
///
/// Returns the full CBOR-encoded byte array. An empty device returns `[0x80]`
/// (the CBOR encoding of an empty array).
///
/// No PIN is required for reads.
///
/// **Please note that `fido_dev_largeblob_get_array()` is synchronous and will block if necessary.**
pub fn largeblob_get_array(&self) -> Result<Vec<u8>> {
let mut data_ptr: *mut u8 = std::ptr::null_mut();
let mut data_len: usize = 0;
unsafe {
check(ffi::fido_dev_largeblob_get_array(
self.ptr.as_ptr(),
&mut data_ptr,
&mut data_len,
))?;
if data_ptr.is_null() {
return Ok(Vec::new());
}
let data = std::slice::from_raw_parts(data_ptr, data_len).to_vec();
libc::free(data_ptr as *mut libc::c_void);
Ok(data)
}
}
/// Replace the entire largeBlob CBOR array on the device.
///
/// Pass `&[0x80]` (empty CBOR array) to erase all entries.
///
/// PIN is required for write operations.
///
/// **Please note that `fido_dev_largeblob_set_array()` is synchronous and will block if necessary.**
pub fn largeblob_set_array(&self, data: &[u8], pin: &str) -> Result<()> {
let pin = CString::new(pin)?;
unsafe {
check(ffi::fido_dev_largeblob_set_array(
self.ptr.as_ptr(),
data.as_ptr(),
data.len(),
pin.as_ptr(),
))?;
}
Ok(())
}
}
impl Drop for Device {
fn drop(&mut self) {
unsafe {
let _ = ffi::fido_dev_close(self.ptr.as_ptr());
let mut raw = self.ptr.as_ptr();
ffi::fido_dev_free(&mut raw);
}
}
}
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,
}