yb-core 0.5.1

Secure blob storage on a YubiKey — core library
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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
// SPDX-FileCopyrightText: 2025 - 2026 Frederic Ruget <fred@atlant.is> (GitHub: @douzebis)
//
// SPDX-License-Identifier: MIT

//! In-memory PIV backend with real P-256 cryptography, used for unit tests.
//!
//! `VirtualPiv` implements the full `PivBackend` trait including ECDH,
//! signing, key generation, and certificate management — without any
//! hardware or PC/SC dependency.  Auth state (PIN retries, management key
//! authentication) is tracked in memory and resets when the struct is dropped.
//!
//! # WARNING
//!
//! Fixture files loaded by `VirtualPiv::from_fixture` contain **disposable
//! test key material**.  Never use these keys to protect real data and never
//! confuse them with production YubiKey credentials.

use super::{DeviceInfo, MgmtAlgo, PinRef, PivBackend};
use crate::errors::{CardError, CardOp, ErrCtx, PcscCode, PcscOp};
use anyhow::{anyhow, bail, Result};
use p256::{elliptic_curve::sec1::ToEncodedPoint, PublicKey, SecretKey};
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    path::Path,
    sync::{Arc, Mutex},
};

// ---------------------------------------------------------------------------
// Public-key point encoding helpers
// ---------------------------------------------------------------------------

fn pubkey_to_uncompressed(pk: &PublicKey) -> Vec<u8> {
    pk.to_encoded_point(false).as_bytes().to_vec()
}

// ---------------------------------------------------------------------------
// Per-slot key material
// ---------------------------------------------------------------------------

struct SlotKey {
    secret: SecretKey,
    public_point: Vec<u8>, // 65-byte uncompressed P-256 point
    cert_der: Option<Vec<u8>>,
    /// Generated on the card (vs. imported), as GET METADATA reports it.
    generated: bool,
}

impl SlotKey {
    fn from_secret(secret: SecretKey) -> Self {
        let public_point = pubkey_to_uncompressed(&secret.public_key());
        Self {
            secret,
            public_point,
            cert_der: None,
            generated: false,
        }
    }

    fn generate() -> Self {
        Self {
            generated: true,
            ..Self::from_secret(SecretKey::random(&mut OsRng))
        }
    }

    fn from_scalar_hex(hex: &str) -> Result<Self> {
        let bytes = hex::decode(hex).map_err(|e| anyhow!("slot key hex: {e}"))?;
        let secret = SecretKey::from_slice(&bytes).map_err(|e| anyhow!("slot key scalar: {e}"))?;
        Ok(Self::from_secret(secret))
    }
}

// ---------------------------------------------------------------------------
// Fault injection (spec 0022 §5)
// ---------------------------------------------------------------------------

/// A failure to inject into a [`VirtualPiv`], to test recovery paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Fault {
    /// The Nth object write from now (1-based) is rejected; the object is
    /// left unchanged.
    WriteFails(usize),
    /// SET MANAGEMENT KEY is rejected; the key is unchanged.
    SetManagementKeyRejected,
    /// SET MANAGEMENT KEY is applied, but reported as failed (lost reply).
    SetManagementKeyLostReply,
    /// The card is lost during SET MANAGEMENT KEY, after applying the
    /// change or not.  Every later authentication fails until
    /// [`VirtualPiv::clear_faults`] (which simulates reconnecting).
    CardLostDuringSetManagementKey { applied: bool },
    /// `generate_certificate` replaces the key in the slot, then fails
    /// before writing the certificate (the old certificate remains).
    GenerateCertificateFailsAfterKey,
    /// The Nth object write from now (1-based) fails for lack of space
    /// (`SW 6A84`) and, as measured on hardware (spec 0022, M2), deletes
    /// the object.
    StorageFull(usize),
    /// The next PIN or PUK change is rejected by the card's complexity
    /// policy (`SW 6985`); nothing changes.
    ChangeReferenceComplexity,
}

// ---------------------------------------------------------------------------
// Internal mutable state
// ---------------------------------------------------------------------------

struct VirtualState {
    reader: String,
    serial: u32,
    version: String,

    pin: String,
    puk: String,
    management_key_hex: String, // hex-encoded raw key bytes
    mgmt_algo: MgmtAlgo,
    pin_retries: u8,
    puk_retries: u8,

    pin_verified: bool,
    mgmt_authenticated: bool,

    // PIV key slots: slot byte → SlotKey
    key_slots: HashMap<u8, SlotKey>,
    // PIV data objects: object ID → raw bytes (stored as the value inside 53 wrapper)
    objects: HashMap<u32, Vec<u8>>,

    // Injected faults, and whether the card is "lost" (see `Fault`).
    faults: Vec<Fault>,
    card_lost: bool,

    // Number of card-changing operations (object writes, SET MANAGEMENT
    // KEY, key generation), for tests asserting "nothing was written".
    writes: usize,
}

impl VirtualState {
    /// Remove and return the first injected fault matching `pred`.
    fn take_fault(&mut self, pred: impl Fn(&Fault) -> bool) -> Option<Fault> {
        let pos = self.faults.iter().position(pred)?;
        Some(self.faults.remove(pos))
    }

    /// Count one object write against the first pending write fault
    /// (`WriteFails` or `StorageFull`); return it if this write must fail.
    fn write_fault(&mut self) -> Option<Fault> {
        let pos = self
            .faults
            .iter()
            .position(|f| matches!(f, Fault::WriteFails(_) | Fault::StorageFull(_)))?;
        let (Fault::WriteFails(n) | Fault::StorageFull(n)) = &mut self.faults[pos] else {
            return None;
        };
        *n -= 1;
        (*n == 0).then(|| self.faults.remove(pos))
    }
}

impl VirtualState {
    fn default_state(serial: u32, reader: String, version: String) -> Self {
        Self {
            reader,
            serial,
            version,
            pin: "123456".to_owned(),
            puk: "12345678".to_owned(),
            management_key_hex: "010203040506070801020304050607080102030405060708".to_owned(),
            mgmt_algo: MgmtAlgo::Tdes,
            pin_retries: 3,
            puk_retries: 3,
            pin_verified: false,
            mgmt_authenticated: false,
            key_slots: HashMap::new(),
            objects: HashMap::new(),
            faults: Vec::new(),
            card_lost: false,
            writes: 0,
        }
    }
}

// ---------------------------------------------------------------------------
// Fixture deserialization
// ---------------------------------------------------------------------------

#[derive(Deserialize, Serialize)]
struct Fixture {
    #[serde(default)]
    identity: FixtureIdentity,
    #[serde(default)]
    credentials: FixtureCredentials,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    slots: HashMap<String, FixtureSlot>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    objects: HashMap<String, String>,
}

#[derive(Deserialize, Serialize)]
struct FixtureIdentity {
    #[serde(default = "default_serial")]
    serial: u32,
    #[serde(default = "default_version")]
    version: String,
    #[serde(default = "default_reader")]
    reader: String,
}

impl Default for FixtureIdentity {
    fn default() -> Self {
        Self {
            serial: default_serial(),
            version: default_version(),
            reader: default_reader(),
        }
    }
}

fn default_serial() -> u32 {
    99_999_999
}
fn default_version() -> String {
    "5.4.3".to_owned()
}
fn default_reader() -> String {
    "Virtual YubiKey 00 00".to_owned()
}

#[derive(Deserialize, Serialize, Default)]
struct FixtureCredentials {
    #[serde(default = "default_pin")]
    pin: String,
    #[serde(default = "default_puk")]
    puk: String,
    #[serde(default = "default_mgmt_key")]
    management_key: String,
    /// `TDES` (default), `AES128`, `AES192` or `AES256`.  Firmware 5.7+
    /// YubiKeys ship with an AES-192 management key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    management_key_algorithm: Option<String>,
    /// PIN tries left (default 3); 0 builds a card with a blocked PIN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pin_retries: Option<u8>,
    /// PUK tries left (default 3).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    puk_retries: Option<u8>,
}

fn default_pin() -> String {
    "123456".to_owned()
}
fn default_puk() -> String {
    "12345678".to_owned()
}
fn default_mgmt_key() -> String {
    "010203040506070801020304050607080102030405060708".to_owned()
}

#[derive(Deserialize, Serialize)]
struct FixtureSlot {
    private_key_hex: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    cert_der_hex: Option<String>,
    /// The key was generated on the card (default: imported).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    generated: bool,
}

// ---------------------------------------------------------------------------
// Test fixtures
// ---------------------------------------------------------------------------

/// The test fixtures of `yb-core/tests/fixtures`, compiled in.  Other
/// crates' tests use them from here, so that they need no path outside
/// their own package (spec 0029 §5).  Test data: only with the
/// `virtual-piv` feature.
#[cfg(any(feature = "virtual-piv", test))]
pub mod fixtures {
    /// Factory-default credentials, no key.
    pub const DEFAULT: &str = include_str!("../../tests/fixtures/default.yaml");
    /// A set-up card (PIN 654321, PUK 87654321, factory management key)
    /// with a key in slot 0x82 and no certificate.
    pub const WITH_KEY: &str = include_str!("../../tests/fixtures/with_key.yaml");
    /// Like `WITH_KEY`, on firmware 5.7.1 with an AES-192 management key.
    pub const AES192: &str = include_str!("../../tests/fixtures/aes192.yaml");
}

// ---------------------------------------------------------------------------
// VirtualPiv
// ---------------------------------------------------------------------------

/// In-memory PIV backend for unit tests.  Implements the full `PivBackend`
/// trait with real P-256 cryptography but no hardware or PC/SC dependency.
pub struct VirtualPiv {
    state: Arc<Mutex<VirtualState>>,
}

impl VirtualPiv {
    /// Create a `VirtualPiv` with default test credentials and an empty store.
    pub fn new() -> Self {
        let id = FixtureIdentity::default();
        Self {
            state: Arc::new(Mutex::new(VirtualState::default_state(
                id.serial, id.reader, id.version,
            ))),
        }
    }

    /// Load a `VirtualPiv` from a YAML fixture file.
    ///
    /// # WARNING
    /// Fixture files contain disposable test key material.
    /// Never use them with real data.
    pub fn from_fixture(path: &Path) -> Result<Self> {
        let text =
            std::fs::read_to_string(path).map_err(|e| anyhow!("reading fixture {path:?}: {e}"))?;
        Self::from_fixture_yaml(&text).map_err(|e| anyhow!("fixture {path:?}: {e}"))
    }

    /// Load a `VirtualPiv` from fixture YAML text, e.g. one of the
    /// `fixtures` constants (feature `virtual-piv`).
    pub fn from_fixture_yaml(text: &str) -> Result<Self> {
        let fixture: Fixture =
            serde_yaml::from_str(text).map_err(|e| anyhow!("parsing fixture: {e}"))?;

        let mut state = VirtualState::default_state(
            fixture.identity.serial,
            fixture.identity.reader,
            fixture.identity.version,
        );
        state.pin = fixture.credentials.pin;
        state.puk = fixture.credentials.puk;
        state.management_key_hex = fixture.credentials.management_key;
        if let Some(n) = fixture.credentials.pin_retries {
            state.pin_retries = n;
        }
        if let Some(n) = fixture.credentials.puk_retries {
            state.puk_retries = n;
        }
        if let Some(ref name) = fixture.credentials.management_key_algorithm {
            state.mgmt_algo = MgmtAlgo::from_name(name)
                .ok_or_else(|| anyhow!("fixture: unknown management_key_algorithm '{name}'"))?;
        }

        for (slot_str, slot_fixture) in &fixture.slots {
            let slot_byte = u8::from_str_radix(slot_str.trim_start_matches("0x"), 16)
                .map_err(|_| anyhow!("invalid slot key in fixture: {slot_str}"))?;
            let mut key = SlotKey::from_scalar_hex(&slot_fixture.private_key_hex)?;
            key.generated = slot_fixture.generated;
            if let Some(ref cert_hex) = slot_fixture.cert_der_hex {
                key.cert_der = Some(
                    hex::decode(cert_hex)
                        .map_err(|e| anyhow!("fixture slot {slot_str} cert: {e}"))?,
                );
            }
            state.key_slots.insert(slot_byte, key);
        }

        for (id_str, data_hex) in &fixture.objects {
            let id = u32::from_str_radix(id_str.trim_start_matches("0x"), 16)
                .map_err(|_| anyhow!("invalid object ID in fixture: {id_str}"))?;
            let data =
                hex::decode(data_hex).map_err(|e| anyhow!("fixture object {id_str}: {e}"))?;
            state.objects.insert(id, data);
        }

        Ok(Self {
            state: Arc::new(Mutex::new(state)),
        })
    }

    /// Return the reader name this virtual device responds to.
    pub fn reader_name(&self) -> String {
        self.state.lock().unwrap().reader.clone()
    }

    /// Inject a failure (see [`Fault`]).  Faults fire once, in the order
    /// the matching operations happen.
    pub fn inject_fault(&self, fault: Fault) {
        self.state.lock().unwrap().faults.push(fault);
    }

    /// Number of card-changing operations so far (object writes, SET
    /// MANAGEMENT KEY, key generation).
    pub fn write_count(&self) -> usize {
        self.state.lock().unwrap().writes
    }

    /// Drop pending faults and "reconnect" a lost card.
    pub fn clear_faults(&self) {
        let mut s = self.state.lock().unwrap();
        s.faults.clear();
        s.card_lost = false;
    }

    /// Serialize the current state back to a YAML fixture file.
    ///
    /// This lets subprocess tests persist state written by one `yb` invocation
    /// (e.g. `format`) so that subsequent invocations start from that state.
    fn do_save_fixture(&self, path: &Path) -> Result<()> {
        let s = self.state.lock().unwrap();
        let mut slots = HashMap::new();
        for (slot_byte, key) in &s.key_slots {
            let scalar_bytes = key.secret.to_bytes();
            slots.insert(
                format!("0x{slot_byte:02x}"),
                FixtureSlot {
                    private_key_hex: hex::encode(scalar_bytes),
                    cert_der_hex: key.cert_der.as_deref().map(hex::encode),
                    generated: key.generated,
                },
            );
        }
        let mut objects = HashMap::new();
        for (id, data) in &s.objects {
            objects.insert(format!("0x{id:06x}"), hex::encode(data));
        }
        let fixture = Fixture {
            identity: FixtureIdentity {
                serial: s.serial,
                version: s.version.clone(),
                reader: s.reader.clone(),
            },
            credentials: FixtureCredentials {
                pin: s.pin.clone(),
                puk: s.puk.clone(),
                management_key: s.management_key_hex.clone(),
                management_key_algorithm: match s.mgmt_algo {
                    MgmtAlgo::Tdes => None,
                    MgmtAlgo::Aes128 => Some("AES128".to_owned()),
                    MgmtAlgo::Aes192 => Some("AES192".to_owned()),
                    MgmtAlgo::Aes256 => Some("AES256".to_owned()),
                },
                pin_retries: (s.pin_retries != 3).then_some(s.pin_retries),
                puk_retries: (s.puk_retries != 3).then_some(s.puk_retries),
            },
            slots,
            objects,
        };
        let yaml =
            serde_yaml::to_string(&fixture).map_err(|e| anyhow!("serializing fixture: {e}"))?;
        std::fs::write(path, yaml).map_err(|e| anyhow!("writing fixture {path:?}: {e}"))?;
        Ok(())
    }
}

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

impl PivBackend for VirtualPiv {
    fn list_readers(&self) -> Result<Vec<String>> {
        Ok(vec![self.state.lock().unwrap().reader.clone()])
    }

    fn list_devices(&self) -> Result<Vec<DeviceInfo>> {
        let s = self.state.lock().unwrap();
        Ok(vec![DeviceInfo {
            serial: s.serial,
            version: s.version.clone(),
            reader: s.reader.clone(),
        }])
    }

    fn read_object(&self, reader: &str, id: u32) -> Result<Vec<u8>> {
        let s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        s.objects
            .get(&id)
            .cloned()
            .ok_or_else(|| CardError::status(CardOp::ReadObject(id), 0x6A, 0x82).into())
    }

    fn object_size(&self, reader: &str, id: u32) -> Result<Option<usize>> {
        let s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        Ok(s.objects.get(&id).map(|v| v.len()))
    }

    fn write_object(&self, reader: &str, id: u32, data: &[u8], management_key: &str) -> Result<()> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        do_authenticate_management_key(&mut s, management_key)?;
        match s.write_fault() {
            Some(Fault::StorageFull(_)) => {
                s.objects.remove(&id);
                return Err(CardError::status(CardOp::WriteObject(id), 0x6A, 0x84).into());
            }
            Some(_) => bail!("virtual: injected failure writing object 0x{id:06x}"),
            None => {}
        }
        if data.is_empty() {
            s.objects.remove(&id);
        } else {
            s.objects.insert(id, data.to_vec());
        }
        s.writes += 1;
        Ok(())
    }

    fn authenticate_management_key(&self, reader: &str, management_key: &str) -> Result<()> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        do_authenticate_management_key(&mut s, management_key)
    }

    fn verify_pin(&self, reader: &str, pin: &str) -> Result<()> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        do_verify_pin(&mut s, pin)
    }

    /// Emulates GET METADATA (INS 0xF7) for the management key (9B), the
    /// PIN/PUK (80/81), with a truthful "is default" flag (tag 0x05), and
    /// the key slots (algorithm EC P-256, origin; `6A82` for an empty
    /// slot).  Every other APDU returns empty data.
    fn send_apdu(&self, reader: &str, apdu: &[u8]) -> Result<Vec<u8>> {
        let s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        let is_default = |current: &str, factory: &str| u8::from(current == factory);
        match apdu {
            [0x00, 0xF7, 0x00, 0x9B, ..] => {
                let default = is_default(
                    &s.management_key_hex.to_ascii_lowercase(),
                    &default_mgmt_key(),
                );
                // Algorithm; policy (PIN n/a, touch never); default flag.
                Ok(vec![
                    0x01,
                    0x01,
                    s.mgmt_algo.id(),
                    0x02,
                    0x02,
                    0x00,
                    0x01,
                    0x05,
                    0x01,
                    default,
                ])
            }
            [0x00, 0xF7, 0x00, 0x80, ..] => {
                let default = is_default(&s.pin, &default_pin());
                Ok(vec![0x05, 0x01, default, 0x06, 0x02, 3, s.pin_retries])
            }
            [0x00, 0xF7, 0x00, 0x81, ..] => {
                let default = is_default(&s.puk, &default_puk());
                Ok(vec![0x05, 0x01, default, 0x06, 0x02, 3, s.puk_retries])
            }
            [0x00, 0xF7, 0x00, slot, ..] => match s.key_slots.get(slot) {
                // Algorithm EC P-256; policy (PIN once, touch never); origin.
                Some(key) => Ok(vec![
                    0x01,
                    0x01,
                    0x11,
                    0x02,
                    0x02,
                    0x02,
                    0x01,
                    0x03,
                    0x01,
                    if key.generated { 0x01 } else { 0x02 },
                ]),
                None => Err(CardError::status(CardOp::Command, 0x6A, 0x82).into()),
            },
            _ => Ok(vec![]),
        }
    }

    fn ecdsa_sign(
        &self,
        reader: &str,
        slot: u8,
        digest: &[u8],
        pin: Option<&str>,
    ) -> Result<[u8; 64]> {
        use p256::ecdsa::{signature::hazmat::PrehashSigner, SigningKey};
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        if let Some(p) = pin {
            do_verify_pin(&mut s, p)?;
        }
        let slot_key = s
            .key_slots
            .get(&slot)
            .ok_or_else(|| anyhow!("virtual: no key in slot 0x{slot:02x}"))?;
        let signing_key = SigningKey::from(slot_key.secret.clone());
        // Sign the pre-computed SHA-256 digest directly (no double-hashing).
        let sig: p256::ecdsa::Signature = signing_key
            .sign_prehash(digest)
            .map_err(|e| anyhow!("virtual: ECDSA sign: {e}"))?;
        let sig_bytes = sig.to_bytes();
        Ok(sig_bytes.into())
    }

    fn ecdh(
        &self,
        reader: &str,
        slot: u8,
        peer_point: &[u8],
        pin: Option<&str>,
    ) -> Result<Vec<u8>> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        if let Some(p) = pin {
            do_verify_pin(&mut s, p)?;
        }
        let slot_key = s
            .key_slots
            .get(&slot)
            .ok_or_else(|| anyhow!("virtual: no key in slot 0x{slot:02x}"))?;

        let peer = PublicKey::from_sec1_bytes(peer_point)
            .map_err(|e| anyhow!("virtual: invalid peer point: {e}"))?;

        // ECDH: scalar multiply to get the shared secret (x-coordinate, 32 bytes).
        let shared =
            p256::ecdh::diffie_hellman(slot_key.secret.to_nonzero_scalar(), peer.as_affine());
        Ok(shared.raw_secret_bytes().to_vec())
    }

    fn read_certificate(&self, reader: &str, slot: u8) -> Result<Vec<u8>> {
        let s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        s.key_slots
            .get(&slot)
            .and_then(|k| k.cert_der.clone())
            .ok_or_else(|| CardError::status(CardOp::ReadCertificate(slot), 0x6A, 0x82).into())
    }

    fn generate_key(
        &self,
        reader: &str,
        slot: u8,
        management_key: Option<&str>,
    ) -> Result<Vec<u8>> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        if let Some(key) = management_key {
            do_authenticate_management_key(&mut s, key)?;
        } else if !s.mgmt_authenticated {
            bail!("virtual: management key authentication required for generate_key");
        }
        let key = SlotKey::generate();
        let point = key.public_point.clone();
        s.key_slots.insert(slot, key);
        s.writes += 1;
        Ok(point)
    }

    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};

        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        if let Some(p) = pin {
            do_verify_pin(&mut s, p)?;
        }
        do_authenticate_management_key(&mut s, management_key)?;

        // Generate a fresh key in the slot.
        let slot_key = SlotKey::generate();

        // Like hardware, key generation and certificate import are separate
        // steps: the key can be replaced while the old certificate remains.
        if s.take_fault(|f| *f == Fault::GenerateCertificateFailsAfterKey)
            .is_some()
        {
            let old_cert = s.key_slots.get(&slot).and_then(|k| k.cert_der.clone());
            let mut replaced = slot_key;
            replaced.cert_der = old_cert;
            s.key_slots.insert(slot, replaced);
            s.writes += 1;
            bail!("virtual: injected failure writing the certificate for slot 0x{slot:02x}");
        }
        // Export as PKCS#8 DER so rcgen can build a KeyPair from it.
        use p256::pkcs8::EncodePrivateKey;
        // pkcs8_der must remain alive until key_pair is built; it is zeroed on drop.
        let pkcs8_der = slot_key
            .secret
            .to_pkcs8_der()
            .map_err(|e| anyhow!("virtual: secret to PKCS8: {e}"))?;

        // KeyPair::try_from accepts raw PKCS#8 DER bytes.
        let key_pair = KeyPair::try_from(pkcs8_der.as_bytes())
            .map_err(|e| anyhow!("virtual: rcgen KeyPair: {e}"))?;

        let mut params = CertificateParams::new(vec![])
            .map_err(|e| anyhow!("virtual: 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!("virtual: self_signed: {e}"))?;
        let cert_der = cert.der().to_vec();

        // Store key + cert in the slot.
        let mut stored_key = slot_key;
        stored_key.cert_der = Some(cert_der.clone());
        s.key_slots.insert(slot, stored_key);
        s.writes += 1;

        Ok(cert_der)
    }

    fn read_printed_object_with_pin(&self, reader: &str, pin: &str) -> Result<Vec<u8>> {
        use crate::auxiliaries::OBJ_PRINTED;
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        do_verify_pin(&mut s, pin)?;
        s.objects
            .get(&OBJ_PRINTED)
            .cloned()
            .ok_or_else(|| CardError::status(CardOp::ReadObject(OBJ_PRINTED), 0x6A, 0x82).into())
    }

    fn management_key_algorithm(&self, reader: &str) -> Result<MgmtAlgo> {
        let s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        Ok(s.mgmt_algo)
    }

    fn set_management_key(
        &self,
        reader: &str,
        old_key_hex: &str,
        new_key_hex: &str,
        algo: MgmtAlgo,
    ) -> Result<()> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        do_authenticate_management_key(&mut s, old_key_hex)?;
        let new_bytes = hex::decode(new_key_hex).map_err(|e| anyhow!("new key hex: {e}"))?;
        algo.check_key_len(&new_bytes)?;

        let fault = s.take_fault(|f| {
            matches!(
                f,
                Fault::SetManagementKeyRejected
                    | Fault::SetManagementKeyLostReply
                    | Fault::CardLostDuringSetManagementKey { .. }
            )
        });
        let apply = !matches!(
            fault,
            Some(Fault::SetManagementKeyRejected)
                | Some(Fault::CardLostDuringSetManagementKey { applied: false })
        );
        if apply {
            s.management_key_hex = new_key_hex.to_owned();
            s.writes += 1;
            s.mgmt_algo = algo;
        }
        if let Some(Fault::CardLostDuringSetManagementKey { .. }) = fault {
            s.card_lost = true;
        }
        match fault {
            Some(f) => bail!("virtual: injected SET MANAGEMENT KEY failure ({f:?})"),
            None => Ok(()),
        }
    }

    fn change_reference(&self, reader: &str, which: PinRef, old: &str, new: &str) -> Result<()> {
        let mut s = self.state.lock().unwrap();
        check_reader(&s, reader)?;
        let op = match which {
            PinRef::Pin => CardOp::ChangePin,
            PinRef::Puk => CardOp::ChangePuk,
        };
        let (current, retries) = match which {
            PinRef::Pin => (s.pin.clone(), s.pin_retries),
            PinRef::Puk => (s.puk.clone(), s.puk_retries),
        };
        // As the card: blocked, then wrong old value, then policy.
        if retries == 0 {
            return Err(CardError::status(op, 0x69, 0x83).into());
        }
        if old != current {
            let left = retries - 1;
            match which {
                PinRef::Pin => s.pin_retries = left,
                PinRef::Puk => s.puk_retries = left,
            }
            return Err(CardError::status(op, 0x63, 0xC0 | left).into());
        }
        if s.take_fault(|f| *f == Fault::ChangeReferenceComplexity)
            .is_some()
        {
            return Err(CardError::status(op, 0x69, 0x85).into());
        }
        match which {
            PinRef::Pin => {
                s.pin = new.to_owned();
                s.pin_retries = 3;
            }
            PinRef::Puk => {
                s.puk = new.to_owned();
                s.puk_retries = 3;
            }
        }
        s.writes += 1;
        Ok(())
    }

    fn save_fixture(&self, path: &std::path::Path) -> Result<()> {
        self.do_save_fixture(path)
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

fn check_reader(s: &VirtualState, reader: &str) -> Result<()> {
    // No reader name in the error (spec 0025 §3).
    if reader != s.reader {
        bail!("virtual: unknown reader");
    }
    Ok(())
}

fn do_verify_pin(s: &mut VirtualState, pin: &str) -> Result<()> {
    // Fail as the card does (spec 0025 §4).
    if s.pin_retries == 0 {
        return Err(CardError::status(CardOp::VerifyPin, 0x69, 0x83).into());
    }
    if pin != s.pin {
        s.pin_retries -= 1;
        return Err(CardError::status(CardOp::VerifyPin, 0x63, 0xC0 | s.pin_retries).into());
    }
    s.pin_verified = true;
    s.pin_retries = 3;
    Ok(())
}

fn do_authenticate_management_key(s: &mut VirtualState, key_hex: &str) -> Result<()> {
    if s.card_lost {
        return Err(CardError::Pcsc {
            op: PcscOp::Transmit,
            code: PcscCode::RemovedCard,
        }
        .into());
    }
    // Like the hardware path: a key of the wrong length for the card's
    // algorithm is rejected before any authentication attempt.
    let key_bytes = hex::decode(key_hex).map_err(|e| anyhow!("decoding management key: {e}"))?;
    s.mgmt_algo.check_key_len(&key_bytes)?;
    if key_hex != s.management_key_hex {
        let ctx = ErrCtx {
            algo: Some(s.mgmt_algo),
        };
        return Err(CardError::status(CardOp::MgmtAuth, 0x69, 0x82)
            .with_ctx(ctx)
            .into());
    }
    s.mgmt_authenticated = true;
    Ok(())
}