soft-fido2 0.17.0

A pure Rust implementation of FIDO2/WebAuthn CTAP 2.0/2.1 protocol
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
//! Virtual FIDO2 Authenticator Example for Browser Testing
//!
//! This example creates a virtual FIDO2 authenticator using Linux UHID that
//! can be used with real web browsers for WebAuthn testing.
//!
//! # Usage
//!
//! 1. Ensure you have UHID permissions:
//!    ```bash
//!    sudo modprobe uhid
//!    sudo usermod -a -G fido $USER
//!    # Create udev rule:
//!    echo 'KERNEL=="uhid", GROUP="fido", MODE="0660"' | sudo tee /etc/udev/rules.d/90-uhid.rules
//!    sudo udevadm control --reload-rules
//!    # Log out and back in for group membership to take effect
//!    ```
//!
//! 2. Run the authenticator:
//!    ```bash
//!    cargo run --example virtual_authenticator
//!    ```
//!
//! 3. Test with WebAuthn sites:
//!    - Open https://webauthn.firstyear.id.au/ (webauthn-rs demo)
//!    - Or try https://webauthn.io/
//!    - Or https://www.passwordless.dev/test
//!    - The virtual authenticator will appear as a USB security key
//!
//! 4. In your browser:
//!    - Click "Register" or "Create Credential"
//!    - Browser will detect the virtual authenticator
//!    - Authenticator will auto-approve (no user interaction needed)
//!    - Check console output to see what's happening
//!
//! # What This Does
//!
//! - Creates a UHID virtual HID device (appears as USB device to OS)
//! - Implements CTAP2 protocol (FIDO2)
//! - Stores credentials in memory
//! - Auto-approves all user presence/verification requests
//! - Supports discoverable credentials (resident keys)
//! - Works with any WebAuthn-enabled website
//!
//! # Features Demonstrated
//!
//! - Passkey registration and authentication
//! - Discoverable credentials (usernameless login)
//! - User verification (UV)
//! - Multiple credentials per RP
//! - Counter-based replay protection
//! - Extension support (credProtect, hmac-secret)
//! - Custom USB device IDs (vendor ID, product ID, device name)

// This example only works on Linux (requires UHID)
#[cfg(not(target_os = "linux"))]
fn main() {
    eprintln!("This example requires Linux with UHID support.");
}

#[cfg(target_os = "linux")]
use soft_fido2::{
    Authenticator, AuthenticatorCallbacks, AuthenticatorConfig, AuthenticatorOptions, Credential,
    CredentialRef, Error, Result, UpResult, UvResult,
};

#[cfg(target_os = "linux")]
use soft_fido2_transport::{CommandHandler, UhidDevice};

#[cfg(target_os = "linux")]
use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::sync::{Arc, Mutex};
#[cfg(target_os = "linux")]
use std::time::Duration;

/// Wrapper that implements CommandHandler for the high-level Authenticator
#[cfg(target_os = "linux")]
struct AuthenticatorHandler<C: AuthenticatorCallbacks> {
    authenticator: Mutex<Authenticator<C>>,
}

#[cfg(target_os = "linux")]
impl<C: AuthenticatorCallbacks> AuthenticatorHandler<C> {
    fn new(authenticator: Authenticator<C>) -> Self {
        Self {
            authenticator: Mutex::new(authenticator),
        }
    }
}

#[cfg(target_os = "linux")]
impl<C: AuthenticatorCallbacks> CommandHandler for AuthenticatorHandler<C> {
    fn handle_command(
        &mut self,
        cmd: soft_fido2_transport::Cmd,
        data: &[u8],
    ) -> soft_fido2_transport::Result<Vec<u8>> {
        // Only handle CBOR commands (CTAP2)
        if cmd != soft_fido2_transport::Cmd::Cbor {
            return Err(soft_fido2_transport::Error::InvalidCommand);
        }

        let mut auth = self.authenticator.lock().map_err(|_| {
            soft_fido2_transport::Error::Other("Failed to lock authenticator".to_string())
        })?;

        let mut response = Vec::new();
        auth.handle(data, &mut response)
            .map_err(|_| soft_fido2_transport::Error::Other("Command failed".to_string()))?;

        Ok(response)
    }
}

/// UHID Virtual Authenticator Runner
///
/// Manages the complete stack: UHID I/O → CTAP HID protocol → Authenticator
#[cfg(target_os = "linux")]
struct UhidAuthenticator<C: AuthenticatorCallbacks> {
    device: UhidDevice,
    handler: soft_fido2_transport::CtapHidHandler<AuthenticatorHandler<C>>,
}

#[cfg(target_os = "linux")]
impl<C: AuthenticatorCallbacks> UhidAuthenticator<C> {
    fn new(authenticator: Authenticator<C>, config: &AuthenticatorConfig) -> Result<Self> {
        let device = UhidDevice::create_fido_device_with_ids(
            config.device_name.as_deref(),
            config.vendor_id,
            config.product_id,
            config.device_version,
        )
        .map_err(|_| Error::Other)?;

        let auth_handler = AuthenticatorHandler::new(authenticator);
        let handler = soft_fido2_transport::CtapHidHandler::new(auth_handler);

        Ok(Self { device, handler })
    }

    /// Process one HID packet (non-blocking)
    ///
    /// Returns Ok(true) if a packet was processed, Ok(false) if no packet available.
    fn process_one(&mut self) -> Result<bool> {
        let mut packet_data = [0u8; 64];

        // Try to read a packet (non-blocking)
        match self.device.read_packet(&mut packet_data) {
            Ok(Some(_len)) => {
                // Parse packet
                let packet = soft_fido2_transport::Packet::from_bytes(packet_data);

                // Process through CTAP HID handler
                let response_packets = self
                    .handler
                    .process_packet(packet)
                    .map_err(|_| Error::Other)?;

                // Write response packets
                for response_packet in response_packets {
                    self.device
                        .write_packet(response_packet.as_bytes())
                        .map_err(|_| Error::Other)?;
                }

                Ok(true)
            }
            Ok(None) => Ok(false), // No packet available
            Err(_) => Err(Error::Timeout),
        }
    }

    /// Run the authenticator event loop
    fn run(&mut self) -> Result<()> {
        let mut request_count = 0u64;

        loop {
            match self.process_one() {
                Ok(true) => {
                    request_count += 1;
                }
                Ok(false) => {
                    // No packet available, sleep briefly
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(Error::Timeout) => {
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(e) => {
                    eprintln!("✗ Error processing packet: {:?}", e);
                    std::thread::sleep(Duration::from_millis(100));
                }
            }

            // Print stats every 100 requests
            if request_count > 0 && request_count.is_multiple_of(100) {
                eprintln!("  [Stats] Processed {} requests", request_count);
            }
        }
    }
}

/// Virtual authenticator callbacks with user-friendly logging
#[cfg(target_os = "linux")]
struct VirtualAuthCallbacks {
    credentials: Arc<Mutex<HashMap<Vec<u8>, Credential>>>,
}

#[cfg(target_os = "linux")]
impl VirtualAuthCallbacks {
    fn new() -> Self {
        Self {
            credentials: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

#[cfg(target_os = "linux")]
impl AuthenticatorCallbacks for VirtualAuthCallbacks {
    fn request_up(&self, info: &str, user: Option<&str>, rp: &str) -> Result<UpResult> {
        println!("\n  [UP] 👆 User Presence Requested");
        println!("       Info: {}", info);
        if let Some(u) = user {
            println!("       User: {}", u);
        }
        println!("       RP: {}", rp);
        println!("       ✓ AUTO-APPROVED");
        Ok(UpResult::Accepted)
    }

    fn request_uv(&self, info: &str, user: Option<&str>, rp: &str) -> Result<UvResult> {
        println!("\n  [UV] 🔐 User Verification Requested");
        println!("       Info: {}", info);
        if let Some(u) = user {
            println!("       User: {}", u);
        }
        println!("       RP: {}", rp);
        println!("       ✓ AUTO-APPROVED (biometric/PIN simulated)");
        Ok(UvResult::Accepted)
    }

    fn write_credential(&self, cred: &CredentialRef) -> Result<()> {
        let mut store = self.credentials.lock().unwrap();
        store.insert(cred.id.to_vec(), cred.to_owned());

        println!("\n✓ CREDENTIAL REGISTERED");
        println!("  RP ID: {}", cred.rp_id);
        if let Some(user_name) = cred.user_name {
            println!("  User: {}", user_name);
        }
        if let Some(rp_name) = cred.rp_name {
            println!("  RP Name: {}", rp_name);
        }
        println!("  User ID: {} bytes", cred.user_id.len());
        println!("  Credential ID: {} bytes", cred.id.len());
        println!("  Discoverable: {}", cred.discoverable);
        if let Some(cp) = cred.cred_protect {
            println!("  CredProtect: 0x{:02x}", cp);
        }
        if let Some(cr) = cred.cred_random {
            println!(
                "  CredRandom: {} bytes (hmac-secret enabled)",
                cr.as_slice().len()
            );
        } else {
            println!("  CredRandom: None (hmac-secret NOT enabled)");
        }
        println!("  Total credentials stored: {}\n", store.len());

        Ok(())
    }

    fn read_credential(&self, cred_id: &[u8]) -> Result<Option<Credential>> {
        let store = self.credentials.lock().unwrap();
        match store.get(cred_id) {
            Some(cred) => {
                println!("\n  [AUTH] 🔑 Credential Retrieved");
                println!("         RP: {}", cred.rp.id);
                if let Some(ref name) = cred.user.name {
                    println!("         User: {}", name);
                }
                println!("         Sign count: {}", cred.sign_count);
                if cred.extensions.cred_random.is_some() {
                    println!("         CredRandom: present (hmac-secret available)");
                } else {
                    println!("         CredRandom: None (hmac-secret NOT available)");
                }
                Ok(Some(cred.clone()))
            }
            None => {
                println!("\n  [AUTH] ✗ Credential not found");
                Ok(None)
            }
        }
    }

    fn delete_credential(&self, cred_id: &[u8]) -> Result<()> {
        let mut store = self.credentials.lock().unwrap();
        store.remove(cred_id);
        println!("  [DELETE] Credential removed\n");
        Ok(())
    }

    fn list_credentials(&self, rp_id: &str, user_id: Option<&[u8]>) -> Result<Vec<Credential>> {
        let store = self.credentials.lock().unwrap();
        let filtered: Vec<Credential> = store
            .values()
            .filter(|c| {
                if c.rp.id != rp_id {
                    return false;
                }
                if let Some(uid) = user_id {
                    c.user.id == uid
                } else {
                    true
                }
            })
            .cloned()
            .collect();

        println!(
            "  [READ] Found {} credential(s) for RP: {}",
            filtered.len(),
            rp_id
        );
        Ok(filtered)
    }

    fn enumerate_rps(&self) -> Result<Vec<(String, Option<String>, usize)>> {
        let store = self.credentials.lock().unwrap();
        let mut rp_map: HashMap<String, (Option<String>, usize)> = HashMap::new();

        for cred in store.values() {
            let entry = rp_map
                .entry(cred.rp.id.clone())
                .or_insert((cred.rp.name.clone(), 0));
            entry.1 += 1;
        }

        let result: Vec<(String, Option<String>, usize)> = rp_map
            .into_iter()
            .map(|(rp_id, (rp_name, count))| (rp_id, rp_name, count))
            .collect();

        println!("  [RPS] Enumerated {} RPs", result.len());
        Ok(result)
    }

    fn credential_count(&self) -> Result<usize> {
        let store = self.credentials.lock().unwrap();
        let count = store.len();
        println!("  [COUNT] Total credentials stored: {}", count);
        Ok(count)
    }

    fn get_timestamp_ms(&self) -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
}

#[cfg(target_os = "linux")]
fn main() -> Result<()> {
    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║  Virtual FIDO2 Authenticator (UHID)                      ║");
    println!("╚═══════════════════════════════════════════════════════════╝\n");

    // Create callbacks
    let callbacks = VirtualAuthCallbacks::new();

    // Configure authenticator with full FIDO2 capabilities
    let config = AuthenticatorConfig::builder()
        .aaguid([
            // Custom AAGUID for soft-fido2
            0x73, 0x6f, 0x66, 0x74, 0x2d, 0x66, 0x69, 0x64, 0x6f, 0x32, 0x2d, 0x76, 0x69, 0x72,
            0x74, 0x75,
        ])
        .max_credentials(100)
        // Note: Default algorithm is ES256 (-7), which is the only one currently implemented
        .extensions(vec![
            "credProtect".to_string(),
            "hmac-secret".to_string(),
            "largeBlobKey".to_string(),
        ])
        .options(
            AuthenticatorOptions::new()
                .with_resident_keys(true) // Support discoverable credentials
                .with_user_presence(true) // Support UP
                .with_user_verification(Some(true)) // Support UV capability
                .with_client_pin(None) // UV available via PIN
                .with_pin_uv_auth_token(Some(true)) // Support PIN/UV authentication
                .with_make_cred_uv_not_required(Some(true)), // Flexible UV (not always required)
        )
        .device_name("Custom FIDO2 Authenticator".to_string())
        .vendor_id(0x1234)
        .product_id(0x5678)
        .device_version(0x0100)
        .build();

    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║  Authenticator Configuration                              ║");
    println!("╚═══════════════════════════════════════════════════════════╝");
    println!("  AAGUID: soft-fido2-virtu");
    println!("  Algorithms: ES256 (-7)");
    println!("  Resident Keys (rk): ✓ Supported");
    println!("  Force Resident Keys: ✓ Enabled by default");
    println!("  User Presence (up): ✓ Supported (auto-approved)");
    println!("  User Verification (uv): ✓ Supported (auto-approved)");
    println!("  UV Token: PIN/UV auth token (pinUvAuthToken=true)");
    println!("  UV Flexibility: makeCredUvNotRqd=true (flexible UV behavior)");
    println!("  Extensions: credProtect, hmac-secret, largeBlobKey");
    println!("  Max Credentials: 100");
    println!();
    println!("  NOTE: Configuration optimized for WebAuthn test compatibility:");
    println!("        - force_resident_keys=true (all credentials stored)");
    println!("        - makeCredUvNotRqd=true (consistent UV behavior)");
    println!();

    // Create authenticator
    // Note: Using clientPin=true + makeCredUvNotRqd=true provides flexible UV behavior:
    // - UV is available when requested (via PIN simulation)
    // - Credentials can be created without UV when not required
    // - This ensures consistent UV behavior across different userVerification preferences
    // We auto-approve all UV requests in callbacks (no actual PIN verification)
    let auth = Authenticator::with_config(callbacks, config.clone())?;

    // Create UHID virtual device
    println!("Creating UHID virtual device...");
    let mut uhid_auth = UhidAuthenticator::new(auth, &config).map_err(|e| {
        eprintln!("\n✗ Failed to create UHID device: {:?}", e);
        eprintln!("\nTroubleshooting:");
        eprintln!("  1. Check UHID module: sudo modprobe uhid");
        eprintln!("  2. Check permissions: groups | grep fido");
        eprintln!("  3. Check udev rules: cat /etc/udev/rules.d/90-uhid.rules");
        eprintln!("  4. Log out and back in if you just added the group");
        eprintln!();
        e
    })?;

    println!("✓ UHID device created successfully!\n");
    println!("╔═══════════════════════════════════════════════════════════╗");
    println!("║  Authenticator Ready - Waiting for WebAuthn requests...  ║");
    println!("╚═══════════════════════════════════════════════════════════╝\n");

    println!("Test with:");
    println!("  • https://webauthn.firstyear.id.au/ (webauthn-rs demo)");
    println!("  • https://webauthn.io/");
    println!("  • https://www.passwordless.dev/test");
    println!();
    println!("Press Ctrl+C to stop\n");

    // Run event loop
    uhid_auth.run()
}