yb-core 0.7.0

Secure blob storage on a YubiKey — core library
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
// SPDX-FileCopyrightText: 2025 - 2026 Frederic Ruget <fred@atlant.is> (GitHub: @douzebis)
//
// SPDX-License-Identifier: MIT

//! Hardware PIV backend — communicates directly with the YubiKey PIV applet
//! via PC/SC APDUs (NIST SP 800-73-4).  No external subprocesses required.

use super::{session, tlv, CardLock, DeviceInfo, FlashHandle, MgmtAlgo, PinRef, PivBackend};
use crate::errors::{CardError, CardOp, PcscOp};
use anyhow::{bail, Context, Result};
use session::{serial_from_reader, version_from_reader, PcscSession, SELECT_PIV};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};
use std::thread::ThreadId;

// ---------------------------------------------------------------------------
// HardwarePiv — PivBackend over PC/SC
// ---------------------------------------------------------------------------

/// The PC/SC backend.  Each command opens its own connection, which holds
/// the card lock while open (spec 0048), unless the calling thread holds
/// the card through [`PivBackend::exclusive`]: its commands then go through
/// that one, locked connection.
pub struct HardwarePiv {
    held: Mutex<Vec<Held>>,
}

/// A connection kept open by [`PivBackend::exclusive`].
struct Held {
    reader: String,
    thread: ThreadId,
    depth: usize,
    session: PcscSession,
}

impl HardwarePiv {
    pub fn new() -> Self {
        Self {
            held: Mutex::new(Vec::new()),
        }
    }

    /// Run `f` on the calling thread's held connection to `reader`, or on
    /// a connection of its own.
    fn with_session<T>(
        &self,
        reader: &str,
        f: impl FnOnce(&mut PcscSession) -> Result<T>,
    ) -> Result<T> {
        {
            let mut held = self.held.lock().unwrap();
            if let Some(h) = find_held(&mut held, reader) {
                return f(&mut h.session);
            }
        }
        f(&mut self.open(reader)?)
    }

    /// A new connection to `reader`.  Refused while the calling thread
    /// holds the card: the new connection would wait for that thread's own
    /// lock.
    fn open(&self, reader: &str) -> Result<PcscSession> {
        if find_held(&mut self.held.lock().unwrap(), reader).is_some() {
            bail!("a second connection to the YubiKey while holding it (bug)");
        }
        PcscSession::open(reader)
    }
}

fn find_held<'a>(held: &'a mut [Held], reader: &str) -> Option<&'a mut Held> {
    let me = std::thread::current().id();
    held.iter_mut()
        .find(|h| h.reader == reader && h.thread == me)
}

impl Default for HardwarePiv {
    fn default() -> Self {
        Self::new()
    }
}

impl PivBackend for HardwarePiv {
    fn exclusive(&self, reader: &str) -> Result<CardLock<'_>> {
        let release = {
            let reader = reader.to_owned();
            move || {
                let me = std::thread::current().id();
                let mut held = self.held.lock().unwrap();
                if let Some(i) = held
                    .iter()
                    .position(|h| h.reader == reader && h.thread == me)
                {
                    held[i].depth -= 1;
                    if held[i].depth == 0 {
                        // Closing the connection ends its transaction.
                        held.swap_remove(i);
                    }
                }
            }
        };
        if let Some(h) = find_held(&mut self.held.lock().unwrap(), reader) {
            h.depth += 1;
            return Ok(CardLock::new(release));
        }
        let session = PcscSession::open(reader)?;
        self.held.lock().unwrap().push(Held {
            reader: reader.to_owned(),
            thread: std::thread::current().id(),
            depth: 1,
            session,
        });
        Ok(CardLock::new(release))
    }

    fn list_readers(&self) -> Result<Vec<String>> {
        let ctx = pcsc::Context::establish(pcsc::Scope::User)
            .map_err(|e| CardError::pcsc(PcscOp::Establish, e))?;
        let mut buf = vec![0u8; 65536];
        let readers: Vec<String> = match ctx.list_readers(&mut buf) {
            // No readers is not an error for listing: the caller decides.
            Err(pcsc::Error::NoReadersAvailable) => return Ok(Vec::new()),
            other => other.map_err(|e| CardError::pcsc(PcscOp::ListReaders, e))?,
        }
        .map(|cstr| cstr.to_string_lossy().into_owned())
        .collect();
        Ok(readers)
    }

    fn list_devices(&self) -> Result<Vec<DeviceInfo>> {
        let readers = self.list_readers()?;
        let mut devices = Vec::new();
        for reader in &readers {
            if let Ok(serial) = serial_from_reader(reader) {
                let version = version_from_reader(reader).unwrap_or_else(|| "unknown".to_owned());
                devices.push(DeviceInfo {
                    serial,
                    version,
                    reader: reader.clone(),
                });
            }
        }
        Ok(devices)
    }

    fn read_object(&self, reader: &str, id: u32) -> Result<Vec<u8>> {
        self.with_session(reader, |session| session.get_data(id))
    }

    fn write_object(&self, reader: &str, id: u32, data: &[u8], management_key: &str) -> Result<()> {
        self.with_session(reader, |session| {
            session.authenticate_once(management_key)?;
            session.put_data(id, data)
        })
    }

    fn authenticate_management_key(&self, reader: &str, management_key: &str) -> Result<()> {
        self.with_session(reader, |session| {
            session.authenticate_management_key(management_key)
        })
    }

    fn verify_pin(&self, reader: &str, pin: &str) -> Result<()> {
        self.with_session(reader, |session| session.verify_pin(pin))
    }

    fn send_apdu(&self, reader: &str, apdu: &[u8]) -> Result<Vec<u8>> {
        self.with_session(reader, |session| {
            session.transmit_check(apdu, CardOp::Command)
        })
    }

    fn change_reference(&self, reader: &str, which: PinRef, old: &str, new: &str) -> Result<()> {
        self.with_session(reader, |session| session.change_reference(which, old, new))
    }

    fn reset_blocked_piv(&self, reader: &str) -> Result<()> {
        self.with_session(reader, |session| {
            session.transmit_check(&[0x00, 0xFB, 0x00, 0x00], CardOp::ResetPiv)?;
            Ok(())
        })
    }

    fn ecdh(
        &self,
        reader: &str,
        slot: u8,
        peer_point: &[u8],
        pin: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.with_session(reader, |session| {
            if let Some(p) = pin {
                session.verify_pin(p)?;
            }
            session.general_authenticate_ecdh(slot, peer_point)
        })
    }

    fn ecdsa_sign(
        &self,
        reader: &str,
        slot: u8,
        digest: &[u8],
        pin: Option<&str>,
    ) -> Result<[u8; 64]> {
        self.with_session(reader, |session| {
            if let Some(p) = pin {
                session.verify_pin(p)?;
            }
            session.general_authenticate_sign_raw(slot, digest)
        })
    }

    fn object_size(&self, reader: &str, id: u32) -> Result<Option<usize>> {
        self.with_session(reader, |session| session.try_get_data_size(id))
    }

    fn read_certificate(&self, reader: &str, slot: u8) -> Result<Vec<u8>> {
        let object_id = slot_to_object_id(slot)?;
        let raw = self.with_session(reader, |session| {
            session.get_data_as(object_id, CardOp::ReadCertificate(slot))
        })?;
        // Cert TLV: 53 <len> [ 70 <len> <DER cert> 71 01 00 FE 00 ]
        // get_data already stripped the outer 53 wrapper.
        // Now parse the inner TLV for tag 0x70.
        let inner = crate::auxiliaries::parse_tlv_flat(&raw);
        inner
            .get(&0x70)
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("cert object for slot 0x{slot:02x}: missing tag 0x70"))
    }

    fn generate_key(
        &self,
        reader: &str,
        slot: u8,
        management_key: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.with_session(reader, |session| {
            if let Some(key) = management_key {
                session.authenticate_management_key(key)?;
            }
            session.generate_key(slot)
        })
    }

    fn read_printed_object_with_pin(&self, reader: &str, pin: &str) -> Result<Vec<u8>> {
        use crate::auxiliaries::OBJ_PRINTED;
        self.with_session(reader, |session| {
            session.verify_pin(pin)?;
            session.get_data(OBJ_PRINTED)
        })
    }

    fn management_key_algorithm(&self, reader: &str) -> Result<MgmtAlgo> {
        self.with_session(reader, |session| session.management_key_algorithm())
    }

    fn set_management_key(
        &self,
        reader: &str,
        old_key_hex: &str,
        new_key_hex: &str,
        algo: MgmtAlgo,
    ) -> Result<()> {
        let new_bytes = zeroize::Zeroizing::new(
            hex::decode(new_key_hex).context("decoding new management key")?,
        );
        algo.check_key_len(&new_bytes)?;
        self.with_session(reader, |session| {
            session.authenticate_management_key(old_key_hex)?;
            // SET MANAGEMENT KEY: INS=0xFF, P1=0xFF, P2=0xFF (no touch)
            // Data: <algorithm id> 9B (management key tag) <len> <key bytes>
            let mut apdu = vec![
                0x00,
                0xFF,
                0xFF,
                0xFF,
                (3 + new_bytes.len()) as u8,
                algo.id(),
                0x9B,
                new_bytes.len() as u8,
            ];
            apdu.extend_from_slice(&new_bytes);
            session.transmit_check(&apdu, CardOp::SetMgmtKey)?;
            session.set_cached_management_key_algorithm(algo);
            // Authenticated with the old key, which no longer is the card's.
            session.forget_authentication();
            Ok(())
        })
    }

    fn generate_certificate(
        &self,
        reader: &str,
        slot: u8,
        subject: &str,
        management_key: &str,
        pin: Option<&str>,
    ) -> Result<Vec<u8>> {
        use crate::auxiliaries::parse_subject_dn;
        use rcgen::{
            CertificateParams, KeyPair, RemoteKeyPair, SignatureAlgorithm, PKCS_ECDSA_P256_SHA256,
        };
        use sha2::{Digest, Sha256};
        use std::sync::Mutex;

        // ---- Step 1: authenticate, generate key ----
        let mut session = self.open(reader)?;
        session.authenticate_management_key(management_key)?;
        let mgmt_key_owned = management_key.to_owned();
        let pubkey_point = session.generate_key(slot)?;
        drop(session);

        // ---- Step 2: self-signed certificate via rcgen + YubiKey SIGN ----
        let reader_owned = reader.to_owned();
        let pin_owned = pin.map(|p| p.to_owned());

        struct YubikeyRemotePair {
            slot: u8,
            pubkey_point: Vec<u8>,
            session: Mutex<PcscSession>,
        }

        impl RemoteKeyPair for YubikeyRemotePair {
            fn public_key(&self) -> &[u8] {
                &self.pubkey_point
            }

            fn sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, rcgen::Error> {
                let digest = Sha256::digest(msg);
                let mut s = self.session.lock().unwrap();
                s.general_authenticate_sign(self.slot, &digest)
                    .map_err(|_| rcgen::Error::RemoteKeyError)
            }

            fn algorithm(&self) -> &'static SignatureAlgorithm {
                &PKCS_ECDSA_P256_SHA256
            }
        }

        let mut sign_session = self.open(&reader_owned)?;
        if let Some(ref p) = pin_owned {
            sign_session.verify_pin(p)?;
        }
        let remote = YubikeyRemotePair {
            slot,
            pubkey_point: pubkey_point.clone(),
            session: Mutex::new(sign_session),
        };
        let key_pair = KeyPair::from_remote(Box::new(remote))
            .map_err(|e| anyhow::anyhow!("rcgen KeyPair: {e}"))?;

        let mut params = CertificateParams::new(vec![])
            .map_err(|e| anyhow::anyhow!("CertificateParams: {e}"))?;
        params.distinguished_name = parse_subject_dn(subject);
        params.not_before = rcgen::date_time_ymd(2000, 1, 1);
        params.not_after = rcgen::date_time_ymd(9999, 12, 31);

        let cert = params
            .self_signed(&key_pair)
            .map_err(|e| anyhow::anyhow!("self_signed: {e}"))?;
        let cert_der = cert.der().to_vec();
        drop(key_pair); // releases sign_session before opening write_session

        // ---- Step 3: import certificate ----
        let object_id = slot_to_object_id(slot)?;
        let mut write_session = self.open(&reader_owned)?;
        write_session.authenticate_management_key(&mgmt_key_owned)?;
        // Cert TLV: 53 <len> [ 70 <len> <DER> 71 01 00 FE 00 ]
        let mut inner = tlv::encode_tlv(0x70, &cert_der);
        inner.extend_from_slice(&[0x71, 0x01, 0x00, 0xFE, 0x00]);
        write_session.put_data(object_id, &inner)?;

        Ok(cert_der)
    }

    fn start_flash(&self, reader: &str, on_ms: u64, off_ms: u64) -> Box<dyn FlashHandle> {
        let stop = Arc::new(AtomicBool::new(false));
        let stop_clone = Arc::clone(&stop);
        let reader_owned = reader.to_owned();

        let _ = std::thread::Builder::new()
            .name("yb-flash".to_owned())
            .spawn(move || {
                flash_loop(&reader_owned, on_ms, off_ms, &stop_clone);
            });

        Box::new(HardwareFlash { stop })
    }
}

// ---------------------------------------------------------------------------
// HardwareFlash — flash handle for real YubiKey
// ---------------------------------------------------------------------------

pub struct HardwareFlash {
    stop: Arc<AtomicBool>,
}

impl FlashHandle for HardwareFlash {}

impl Drop for HardwareFlash {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

/// Background loop: blink the LED on the YubiKey.
///
/// ## How the LED is controlled
///
/// The YubiKey has no dedicated "blink" command.  The LED lights when the card
/// processes an APDU and goes dark when power is removed.  Specifically:
///
/// - `SCardConnect` powers the card up (brief transient flash).
/// - `SELECT PIV` (00 A4 04 00 05 A0 00 00 03 08) lights the LED while the
///   card is processing — the LED stays on as long as the connection is open.
/// - `SCardDisconnect(SCARD_UNPOWER_CARD)` cuts power immediately → LED off.
/// - Keeping the connection open indefinitely leaves the LED continuously lit.
///
/// ## Cycle structure
///
/// To produce a clean blink the loop reconnects on every cycle:
///
/// ```text
/// connect (power-up transient)
/// loop:
///   SELECT_PIV → LED on
///   sleep on_ms
///   disconnect(UnpowerCard) → LED off
///   sleep off_ms
///   connect (power-up transient, absorbed into next on-period)
/// ```
///
/// The power-up transient on `connect` is brief and indistinguishable from the
/// intentional flash because it is immediately followed by SELECT_PIV.
///
/// ## Known residual noise
///
/// A faint off/on dip (~50 ms) occurs every ~3 seconds regardless of timing.
/// This is intrinsic YubiKey firmware behavior (observed on YubiKey 5 series):
/// the device performs a periodic internal housekeeping operation that briefly
/// interrupts LED state.  It cannot be suppressed from the host side; we accept
/// it as an unavoidable artifact.
///
/// Any PC/SC error (card removed, USB glitch) silently terminates the loop.
/// The thread never panics the process.
fn flash_loop(reader: &str, on_ms: u64, off_ms: u64, stop: &AtomicBool) {
    let ctx = match pcsc::Context::establish(pcsc::Scope::User) {
        Ok(c) => c,
        Err(_) => return,
    };
    let reader_cstr = match std::ffi::CString::new(reader) {
        Ok(s) => s,
        Err(_) => return,
    };
    let mut buf = vec![0u8; pcsc::MAX_BUFFER_SIZE_EXTENDED];

    // Sleep helpers: check stop flag every 10 ms for responsiveness.
    let on_ticks = (on_ms / 10).max(1);
    let off_ticks = (off_ms / 10).max(1);

    // Initial connect before the loop.
    // Use Exclusive mode so UnpowerCard takes effect immediately with no
    // other holders keeping the card powered.
    let mut card = match ctx.connect(
        &reader_cstr,
        pcsc::ShareMode::Exclusive,
        pcsc::Protocols::ANY,
    ) {
        Ok(c) => c,
        Err(_) => return,
    };

    loop {
        if stop.load(Ordering::Relaxed) {
            // Unpower before exiting so the LED goes dark immediately.
            let _ = card.disconnect(pcsc::Disposition::UnpowerCard);
            return;
        }
        // SELECT PIV → LED on.
        if card.transmit(SELECT_PIV, &mut buf).is_err() {
            return;
        }
        // Hold on-period — check stop flag every 10 ms.
        for _ in 0..on_ticks {
            if stop.load(Ordering::Relaxed) {
                // Unpower immediately so the LED goes dark without delay.
                let _ = card.disconnect(pcsc::Disposition::UnpowerCard);
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        // UnpowerCard → LED off immediately.
        if card.disconnect(pcsc::Disposition::UnpowerCard).is_err() {
            return;
        }
        // Off-period — check stop flag every 10 ms.
        for _ in 0..off_ticks {
            if stop.load(Ordering::Relaxed) {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        // Reconnect — power-up transient is absorbed into the next on-period.
        card = match ctx.connect(
            &reader_cstr,
            pcsc::ShareMode::Exclusive,
            pcsc::Protocols::ANY,
        ) {
            Ok(c) => c,
            Err(_) => return,
        };
    }
}

// ---------------------------------------------------------------------------
// PIV slot → object ID mapping
// ---------------------------------------------------------------------------

/// Map a PIV slot byte to its data object ID (NIST SP 800-73-4 Table 3).
pub fn slot_to_object_id(slot: u8) -> Result<u32> {
    match slot {
        0x9a => Ok(0x5F_C105),
        0x9c => Ok(0x5F_C10A),
        0x9d => Ok(0x5F_C10B),
        0x9e => Ok(0x5F_C101),
        0x82 => Ok(0x5F_C10D),
        0x83 => Ok(0x5F_C10E),
        0x84 => Ok(0x5F_C10F),
        0x85 => Ok(0x5F_C110),
        0x86 => Ok(0x5F_C111),
        0x87 => Ok(0x5F_C112),
        0x88 => Ok(0x5F_C113),
        0x89 => Ok(0x5F_C114),
        0x8a => Ok(0x5F_C115),
        0x8b => Ok(0x5F_C116),
        0x8c => Ok(0x5F_C117),
        0x8d => Ok(0x5F_C118),
        0x8e => Ok(0x5F_C119),
        0x8f => Ok(0x5F_C11A),
        0x90 => Ok(0x5F_C11B),
        0x91 => Ok(0x5F_C11C),
        0x92 => Ok(0x5F_C11D),
        0x93 => Ok(0x5F_C11E),
        0x94 => Ok(0x5F_C11F),
        0x95 => Ok(0x5F_C120),
        _ => bail!("unsupported PIV slot 0x{slot:02x}"),
    }
}