dmrtd 0.3.2

eMRTD / ICAO 9303 reader core in pure Rust — BAC, PACE (ECDH-GM P-256), MRZ, LDS parsing, secure messaging. Transport-agnostic (NFC plugs in via a Transceiver trait).
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! Synchronous PACE session state machine for FFI use.
//!
//! Drives the full PACE handshake (MSE:Set AT → GA step 1/2/3/4) as a series
//! of `(next APDU → response)` steps. Like [`BacSession`], no async and no
//! NFC — the caller owns the transceive loop.
//!
//! Supports **ECDH-GM on NIST P-256** (ICAO domain parameter id `12`) and
//! **DH-GM on the RFC 5114 MODP groups** (ids `0`/`1`/`2`); both require the
//! AES cipher. Other curves/groups are rejected at construction.
//!
//! ```text
//!   Start
//!     └─ next() → SendApdu(MSE:Set AT)
//!        └─ feed(9000)
//!   ReadyForStep1
//!     └─ next() → SendApdu(GA step 1)
//!        └─ feed(encrypted-nonce)
//!   ReadyForStep2 { nonce }
//!     └─ next() → SendApdu(GA step 2; terminal mapping public)
//!        └─ feed(ICC mapping public)
//!   ReadyForStep3
//!     └─ next() → SendApdu(GA step 3; terminal ephemeral public)
//!        └─ feed(ICC ephemeral public)
//!   ReadyForStep4 { icc_ephemeral_pub, k_enc, k_mac }
//!     └─ next() → SendApdu(GA step 4; auth token T_IFD)
//!        └─ feed(ICC auth token T_IC)  ← verified against expected
//!   Completed(sm)
//!     └─ next() → Done(sm)
//! ```
//!
//! [`BacSession`]: crate::proto::bac_session::BacSession

use num_bigint::BigUint;
use thiserror::Error;

use crate::crypto::crypto_utils::constant_time_eq;
use crate::lds::asn1_object_identifiers::{
    CipherAlgorithm, MappingType, OiePaceProtocol, TokenAgreementAlgo,
};
use crate::proto::access_key::AccessKey;
use crate::proto::aes_smcipher::AesSmCipher;
use crate::proto::dh_pace::{self, DHPace, DHPaceError};
use crate::proto::domain_parameter;
use crate::proto::ecdh_pace::{ECDHPace, ECDHPaceError};
use crate::proto::iso7816::command_apdu::CommandApdu;
use crate::proto::iso7816::iso7816::{cla, ins};
use crate::proto::iso7816::response_apdu::{ResponseApdu, StatusWord};
use crate::proto::iso7816::sm::SmError;
use crate::proto::mrtd_sm::MrtdSM;
use crate::proto::pace::{self, PaceError};
use crate::proto::public_key_pace::PublicKeyPace;
use crate::proto::ssc::AesSSC;
use crate::utils::big_uint_to_bytes;

/// Action requested by [`PaceSession::next`].
pub enum PaceAction {
    /// Send this APDU and call [`PaceSession::feed_response`] with the reply.
    SendApdu(Vec<u8>),
    /// Handshake complete — take ownership of the secure-messaging session.
    Done(MrtdSM<AesSmCipher>),
}

/// PACE protocol error surface for the session layer.
#[derive(Debug, Error)]
pub enum PaceSessionError {
    #[error("PACE session: token-agreement algorithm not supported here (got {0:?})")]
    UnsupportedAgreement(TokenAgreementAlgo),
    #[error("PACE session: only Generic Mapping (GM) is supported (got {0:?})")]
    UnsupportedMapping(MappingType),
    #[error("PACE session: only AES cipher is supported (got {0:?})")]
    UnsupportedCipher(CipherAlgorithm),
    #[error("PACE session: unsupported curve/parameter id (got id {0})")]
    UnsupportedCurve(u32),
    #[error("PACE session has no outstanding APDU to consume")]
    NoOutstandingApdu,
    #[error("PACE session is waiting for a response; feed_response first")]
    PendingResponse,
    #[error("PACE session already consumed")]
    AlreadyTaken,
    #[error("PACE step failed with status {0}")]
    ChipStatus(StatusWord),
    #[error("PACE step response was empty")]
    EmptyResponse,
    #[error("Invalid response APDU: {0}")]
    InvalidResponse(String),
    #[error("Shared secret has no x coordinate")]
    MissingSharedSecretX,
    #[error("ICC authentication token does not match the expected one")]
    AuthTokenMismatch,

    #[error(transparent)]
    Pace(#[from] PaceError),
    #[error(transparent)]
    Ecdh(#[from] ECDHPaceError),
    #[error(transparent)]
    Dh(#[from] DHPaceError),
    #[error(transparent)]
    Sm(#[from] SmError),
}

/// PACE key-agreement engine — ECDH-GM (P-256) or classical DH (RFC 5114
/// MODP groups). Both expose the same set of operations the session needs,
/// exchanging [`PublicKeyPace`] values and raw KDF seed bytes so the state
/// machine stays agreement-agnostic.
// One per session, as with [`ECDHPace`] — the size difference is paid once and never
// multiplied, so boxing would buy nothing and cost an allocation.
#[allow(clippy::large_enum_variant)]
enum PaceEngine {
    Ecdh(ECDHPace),
    Dh(DHPace),
}

impl PaceEngine {
    /// Generates the main (mapping) key pair.
    fn generate_main_key_pair(&mut self, seed: Option<&[u8]>) -> Result<(), PaceSessionError> {
        match self {
            PaceEngine::Ecdh(e) => e.generate_key_pair(seed)?,
            PaceEngine::Dh(e) => e.generate_key_pair(seed.map(seed_to_u64))?,
        }
        Ok(())
    }

    /// The main public key.
    fn main_pub_key(&self) -> Result<PublicKeyPace, PaceSessionError> {
        match self {
            PaceEngine::Ecdh(e) => Ok(e.get_pub_key()?),
            PaceEngine::Dh(e) => Ok(e.get_pub_key()?),
        }
    }

    /// The ephemeral public key.
    fn ephemeral_pub_key(&self) -> Result<PublicKeyPace, PaceSessionError> {
        match self {
            PaceEngine::Ecdh(e) => Ok(e.get_pub_key_ephemeral()?),
            PaceEngine::Dh(e) => Ok(e.get_pub_key_ephemeral()?),
        }
    }

    /// PACE-GM: from the ICC mapping public and the decrypted nonce, derive the
    /// mapped generator and build the ephemeral key pair against it.
    fn map_and_generate_ephemeral(
        &mut self,
        icc_mapping_pub: &PublicKeyPace,
        nonce: &[u8],
        seed: Option<&[u8]>,
    ) -> Result<(), PaceSessionError> {
        match self {
            PaceEngine::Ecdh(e) => {
                e.map_and_generate_ephemeral(icc_mapping_pub, nonce, seed)?;
            }
            PaceEngine::Dh(e) => {
                let g_prime =
                    e.get_mapped_generator(&icc_mapping_pub.to_relevant_bytes(), nonce)?;
                e.generate_ephemeral_with_custom_generator(
                    BigUint::from_bytes_be(&g_prime),
                    seed.map(seed_to_u64),
                )?;
            }
        }
        Ok(())
    }

    /// Computes the ephemeral shared secret and returns the KDF seed bytes
    /// (the EC x-coordinate for ECDH, the shared integer for DH).
    fn ephemeral_shared_seed(
        &self,
        icc_ephemeral_pub: &PublicKeyPace,
    ) -> Result<Vec<u8>, PaceSessionError> {
        match self {
            PaceEngine::Ecdh(e) => {
                let seed_bytes = e.get_ephemeral_shared_seed(icc_ephemeral_pub)?;
                Ok(seed_bytes)
            }
            PaceEngine::Dh(e) => {
                let shared =
                    e.get_ephemeral_shared_secret(&icc_ephemeral_pub.to_relevant_bytes())?;
                Ok(big_uint_to_bytes(&shared))
            }
        }
    }

    /// Response length (`Le`) to request for the GENERAL AUTHENTICATE steps that
    /// return a public key. ECDH-GM keys fit comfortably in 256 bytes. DH public
    /// keys are modulus-sized: the 1024-bit group (128 B) plus its dynamic-auth
    /// TLV wrapping still fits the short 256-byte `Le`, so only the 2048-bit
    /// groups (256 B, which overflow 256 once wrapped) request an extended
    /// response — avoiding needless extended APDUs that short-only readers may
    /// reject.
    fn pubkey_response_le(&self) -> u32 {
        match self {
            PaceEngine::Ecdh(_) => 256,
            PaceEngine::Dh(e) => {
                // ~8 bytes of 7C / 81|83 TLV wrapping around the public key.
                if e.modulus_byte_len() + 8 <= 256 {
                    256
                } else {
                    65_536
                }
            }
        }
    }
}

/// Folds up to the first 8 bytes of a 32-byte test seed into a `u64`, the seed
/// form the DH engine accepts (used only for deterministic test runs).
fn seed_to_u64(seed: &[u8]) -> u64 {
    let mut b = [0u8; 8];
    let n = seed.len().min(8);
    b[..n].copy_from_slice(&seed[..n]);
    u64::from_be_bytes(b)
}

/// Synchronous PACE handshake state machine.
///
/// Generic over the [`AccessKey`] used to derive `K_π` (e.g. [`DBAKey`] from
/// MRZ or [`CanKey`] from the 6-digit CAN).
///
/// [`DBAKey`]: crate::proto::dba_key::DBAKey
/// [`CanKey`]: crate::proto::can_key::CanKey
pub struct PaceSession<K: AccessKey> {
    key: K,
    protocol: OiePaceProtocol,
    engine: PaceEngine,
    /// Optional seed for the main scalar (test determinism).
    seed_main: Option<[u8; 32]>,
    /// Optional seed for the ephemeral scalar (test determinism).
    seed_ephemeral: Option<[u8; 32]>,
    state: State,
}

enum State {
    Start,
    WaitingForMseSetAt,
    ReadyForStep1,
    WaitingForStep1,
    ReadyForStep2 {
        nonce: Vec<u8>,
    },
    WaitingForStep2 {
        nonce: Vec<u8>,
    },
    ReadyForStep3,
    WaitingForStep3,
    ReadyForStep4 {
        icc_ephemeral_pub: PublicKeyPace,
        k_enc: Vec<u8>,
        k_mac: Vec<u8>,
    },
    WaitingForStep4 {
        k_enc: Vec<u8>,
        k_mac: Vec<u8>,
    },
    Completed(Option<MrtdSM<AesSmCipher>>),
}

impl<K: AccessKey> PaceSession<K> {
    /// Creates a new session, dispatching on the protocol's token-agreement
    /// algorithm: ECDH-GM (NIST P-256) or DH-GM (RFC 5114 MODP groups 0/1/2).
    /// Both require the AES cipher.
    pub fn new(
        key: K,
        protocol: OiePaceProtocol,
        parameter_id: u32,
    ) -> Result<Self, PaceSessionError> {
        match protocol.token_agreement_algorithm {
            TokenAgreementAlgo::Ecdh => Self::new_ecdh(key, protocol, parameter_id),
            TokenAgreementAlgo::Dh => Self::new_dh(key, protocol, parameter_id),
        }
    }

    /// Creates an ECDH-GM session. Fails unless the protocol is ECDH + AES on
    /// NIST P-256.
    pub fn new_ecdh(
        key: K,
        protocol: OiePaceProtocol,
        parameter_id: u32,
    ) -> Result<Self, PaceSessionError> {
        if protocol.token_agreement_algorithm != TokenAgreementAlgo::Ecdh {
            return Err(PaceSessionError::UnsupportedAgreement(
                protocol.token_agreement_algorithm,
            ));
        }
        if protocol.cipher_algorithm != CipherAlgorithm::Aes {
            return Err(PaceSessionError::UnsupportedCipher(
                protocol.cipher_algorithm,
            ));
        }
        if protocol.mapping_type != MappingType::Gm {
            return Err(PaceSessionError::UnsupportedMapping(protocol.mapping_type));
        }
        let supported = domain_parameter::get(parameter_id)
            .map(|entry| {
                entry.is_supported && entry.kind == domain_parameter::DomainParameterType::Ecp
            })
            .unwrap_or(false);
        if !supported {
            return Err(PaceSessionError::UnsupportedCurve(parameter_id));
        }
        Ok(Self {
            key,
            protocol,
            engine: PaceEngine::Ecdh(ECDHPace::new(parameter_id)?),
            seed_main: None,
            seed_ephemeral: None,
            state: State::Start,
        })
    }

    /// Creates a DH-GM session. Fails unless the protocol is DH + AES on a
    /// supported RFC 5114 MODP group (ICAO ids 0/1/2).
    pub fn new_dh(
        key: K,
        protocol: OiePaceProtocol,
        parameter_id: u32,
    ) -> Result<Self, PaceSessionError> {
        if protocol.token_agreement_algorithm != TokenAgreementAlgo::Dh {
            return Err(PaceSessionError::UnsupportedAgreement(
                protocol.token_agreement_algorithm,
            ));
        }
        if protocol.cipher_algorithm != CipherAlgorithm::Aes {
            return Err(PaceSessionError::UnsupportedCipher(
                protocol.cipher_algorithm,
            ));
        }
        if protocol.mapping_type != MappingType::Gm {
            return Err(PaceSessionError::UnsupportedMapping(protocol.mapping_type));
        }
        let engine = dh_pace::get_domain_parameter(parameter_id)?;
        Ok(Self {
            key,
            protocol,
            engine: PaceEngine::Dh(engine),
            seed_main: None,
            seed_ephemeral: None,
            state: State::Start,
        })
    }

    /// Deterministic variant that seeds both the main and ephemeral scalars.
    /// For tests / replaying traces only.
    pub fn new_ecdh_deterministic(
        key: K,
        protocol: OiePaceProtocol,
        parameter_id: u32,
        seed_main: [u8; 32],
        seed_ephemeral: [u8; 32],
    ) -> Result<Self, PaceSessionError> {
        let mut s = Self::new_ecdh(key, protocol, parameter_id)?;
        s.seed_main = Some(seed_main);
        s.seed_ephemeral = Some(seed_ephemeral);
        Ok(s)
    }

    /// Deterministic DH variant (tests / trace replay only).
    pub fn new_dh_deterministic(
        key: K,
        protocol: OiePaceProtocol,
        parameter_id: u32,
        seed_main: [u8; 32],
        seed_ephemeral: [u8; 32],
    ) -> Result<Self, PaceSessionError> {
        let mut s = Self::new_dh(key, protocol, parameter_id)?;
        s.seed_main = Some(seed_main);
        s.seed_ephemeral = Some(seed_ephemeral);
        Ok(s)
    }

    /// Advances the state machine and returns the next action.
    // See `BacSession::next`: a fallible protocol step, not an iterator.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Result<PaceAction, PaceSessionError> {
        match std::mem::replace(&mut self.state, State::Start) {
            State::Start => {
                let data =
                    pace::generate_mse_set_at_data(&self.protocol, self.key.pace_ref_key_tag());
                let cmd = CommandApdu::new(
                    cla::NO_SM,
                    ins::MANAGE_SECURITY_ENVIRONMENT,
                    0xC1,
                    0xA4,
                    Some(data),
                    0,
                )
                .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
                self.state = State::WaitingForMseSetAt;
                Ok(PaceAction::SendApdu(cmd.to_bytes()))
            }
            State::ReadyForStep1 => {
                let data = pace::generate_general_authenticate_data_step1();
                let cmd = CommandApdu::new(
                    cla::COMMAND_CHAINING,
                    ins::GENERAL_AUTHENTICATE,
                    0x00,
                    0x00,
                    Some(data),
                    256,
                )
                .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
                self.state = State::WaitingForStep1;
                Ok(PaceAction::SendApdu(cmd.to_bytes()))
            }
            State::ReadyForStep2 { nonce } => {
                // Generate main key pair; send its public as mapping public.
                self.engine
                    .generate_main_key_pair(self.seed_main.as_ref().map(|s| &s[..]))?;
                let terminal_pub = self.engine.main_pub_key()?;
                let data =
                    pace::generate_general_authenticate_data_step2_or_3(&terminal_pub, false);
                let cmd = CommandApdu::new(
                    cla::COMMAND_CHAINING,
                    ins::GENERAL_AUTHENTICATE,
                    0x00,
                    0x00,
                    Some(data),
                    self.engine.pubkey_response_le(),
                )
                .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
                self.state = State::WaitingForStep2 { nonce };
                Ok(PaceAction::SendApdu(cmd.to_bytes()))
            }
            State::ReadyForStep3 => {
                let terminal_ephemeral_pub = self.engine.ephemeral_pub_key()?;
                let data = pace::generate_general_authenticate_data_step2_or_3(
                    &terminal_ephemeral_pub,
                    true,
                );
                let cmd = CommandApdu::new(
                    cla::COMMAND_CHAINING,
                    ins::GENERAL_AUTHENTICATE,
                    0x00,
                    0x00,
                    Some(data),
                    self.engine.pubkey_response_le(),
                )
                .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
                self.state = State::WaitingForStep3;
                Ok(PaceAction::SendApdu(cmd.to_bytes()))
            }
            State::ReadyForStep4 {
                icc_ephemeral_pub,
                k_enc,
                k_mac,
            } => {
                // Terminal's auth token is computed over the *ICC's* ephemeral key.
                let input = pace::generate_encoding_input_data(&self.protocol, &icc_ephemeral_pub);
                let t_ifd = pace::calculate_auth_token(&self.protocol, &input, &k_mac)?;
                let data = pace::generate_general_authenticate_data_step4(&t_ifd);
                let cmd = CommandApdu::new(
                    cla::NO_SM,
                    ins::GENERAL_AUTHENTICATE,
                    0x00,
                    0x00,
                    Some(data),
                    256,
                )
                .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
                self.state = State::WaitingForStep4 { k_enc, k_mac };
                Ok(PaceAction::SendApdu(cmd.to_bytes()))
            }
            State::Completed(slot) => match slot {
                Some(sm) => {
                    self.state = State::Completed(None);
                    Ok(PaceAction::Done(sm))
                }
                None => {
                    // The SM session was already taken; restore the Completed(None)
                    // state instead of leaving the machine corrupted as `Start`.
                    self.state = State::Completed(None);
                    Err(PaceSessionError::AlreadyTaken)
                }
            },
            other @ (State::WaitingForMseSetAt
            | State::WaitingForStep1
            | State::WaitingForStep2 { .. }
            | State::WaitingForStep3
            | State::WaitingForStep4 { .. }) => {
                self.state = other;
                Err(PaceSessionError::PendingResponse)
            }
        }
    }

    /// Consumes the full APDU response (data || SW) for the most recent
    /// outgoing APDU.
    pub fn feed_response(&mut self, response: &[u8]) -> Result<(), PaceSessionError> {
        let rapdu = ResponseApdu::from_bytes(response)
            .map_err(|e| PaceSessionError::InvalidResponse(e.to_string()))?;
        if rapdu.status != StatusWord::SUCCESS {
            return Err(PaceSessionError::ChipStatus(rapdu.status));
        }

        match std::mem::replace(&mut self.state, State::Start) {
            State::WaitingForMseSetAt => {
                // MSE:Set AT has no data body; SW=9000 already checked.
                self.state = State::ReadyForStep1;
                Ok(())
            }
            State::WaitingForStep1 => {
                let data = rapdu.data.ok_or(PaceSessionError::EmptyResponse)?;
                let encrypted_nonce = pace::parse_step1_response(&data)
                    .map_err(|e| PaceSessionError::InvalidResponse(e.0))?;
                let nonce = pace::decrypt_nonce(&self.protocol, &encrypted_nonce, &self.key)?;
                self.state = State::ReadyForStep2 { nonce };
                Ok(())
            }
            State::WaitingForStep2 { nonce } => {
                let data = rapdu.data.ok_or(PaceSessionError::EmptyResponse)?;
                let icc_mapping_pub =
                    pace::parse_step2_or_3_response(&data, self.protocol.token_agreement_algorithm)
                        .map_err(|e| PaceSessionError::InvalidResponse(e.0))?;

                // Compute mapped generator and rebuild ephemeral key pair.
                self.engine.map_and_generate_ephemeral(
                    &icc_mapping_pub,
                    &nonce,
                    self.seed_ephemeral.as_ref().map(|s| &s[..]),
                )?;
                self.state = State::ReadyForStep3;
                Ok(())
            }
            State::WaitingForStep3 => {
                let data = rapdu.data.ok_or(PaceSessionError::EmptyResponse)?;
                let icc_ephemeral_pub =
                    pace::parse_step2_or_3_response(&data, self.protocol.token_agreement_algorithm)
                        .map_err(|e| PaceSessionError::InvalidResponse(e.0))?;

                // Compute the ephemeral shared secret and derive K_enc / K_mac.
                let seed = self.engine.ephemeral_shared_seed(&icc_ephemeral_pub)?;
                let k_enc = pace::calculate_enc_key(&self.protocol, &seed)?;
                let k_mac = pace::calculate_mac_key(&self.protocol, &seed)?;

                self.state = State::ReadyForStep4 {
                    icc_ephemeral_pub,
                    k_enc,
                    k_mac,
                };
                Ok(())
            }
            State::WaitingForStep4 { k_enc, k_mac } => {
                let data = rapdu.data.ok_or(PaceSessionError::EmptyResponse)?;
                let icc_token = pace::parse_step4_response(&data)
                    .map_err(|e| PaceSessionError::InvalidResponse(e.0))?;

                // ICC's token T_IC is computed over the *terminal's* ephemeral
                // public key — the terminal verifies with that same input.
                let terminal_ephemeral_pub = self.engine.ephemeral_pub_key()?;
                let expected_input =
                    pace::generate_encoding_input_data(&self.protocol, &terminal_ephemeral_pub);
                let expected_token =
                    pace::calculate_auth_token(&self.protocol, &expected_input, &k_mac)?;
                if !constant_time_eq(&expected_token, &icc_token) {
                    return Err(PaceSessionError::AuthTokenMismatch);
                }

                let cipher = AesSmCipher::new(k_enc, k_mac, self.protocol.key_length)?;
                let sm = MrtdSM::new(cipher, AesSSC::default().0);
                self.state = State::Completed(Some(sm));
                Ok(())
            }
            other @ (State::Start
            | State::ReadyForStep1
            | State::ReadyForStep2 { .. }
            | State::ReadyForStep3
            | State::ReadyForStep4 { .. }
            | State::Completed(_)) => {
                self.state = other;
                Err(PaceSessionError::NoOutstandingApdu)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    //! End-to-end PACE loopback — the ICC side is simulated by a second
    //! `ECDHPace` engine seeded independently from the terminal's. The
    //! test drives every APDU exchange through real `next()` /
    //! `feed_response()` calls and asserts that a secure-messaging session
    //! is produced.

    use super::*;
    use crate::crypto::aes::{AesCipher, BlockCipherMode, AES_BLOCK_SIZE};
    use crate::lds::tlv::Tlv;
    use crate::proto::can_key::CanKey;
    use crate::proto::ecdh_pace::NIST_P256_ID;

    fn ecdh_gm_aes128_oid() -> OiePaceProtocol {
        OiePaceProtocol::new(
            "0.4.0.127.0.7.2.2.4.2.2",
            "id-PACE-ECDH-GM-AES-CBC-CMAC-128",
            vec![0, 4, 0, 127, 0, 7, 2, 2, 4, 2, 2],
        )
        .unwrap()
    }

    fn dh_gm_aes128_oid() -> OiePaceProtocol {
        OiePaceProtocol::new(
            "0.4.0.127.0.7.2.2.4.1.2",
            "id-PACE-DH-GM-AES-CBC-CMAC-128",
            vec![0, 4, 0, 127, 0, 7, 2, 2, 4, 1, 2],
        )
        .unwrap()
    }

    /// Replicates the private `seed_to_u64`: folds up to the first 8 bytes of a
    /// seed into a big-endian `u64`, the seed form the DH engine accepts. The
    /// terminal session uses the same derivation, so both sides stay in sync.
    fn seed_u64(seed: &[u8]) -> u64 {
        let mut b = [0u8; 8];
        let n = seed.len().min(8);
        b[..n].copy_from_slice(&seed[..n]);
        u64::from_be_bytes(b)
    }

    fn build_response(data: Option<&[u8]>) -> Vec<u8> {
        let r = ResponseApdu::new(
            StatusWord::SUCCESS,
            data.map(|d| d.to_vec()).filter(|d| !d.is_empty()),
        );
        r.to_bytes()
    }

    fn dyn_auth_wrap(tag: u32, body: &[u8]) -> Vec<u8> {
        // 7C { <tag> <body> }
        let inner = Tlv::encode(tag, body);
        Tlv::encode(0x7C, &inner)
    }

    #[test]
    fn rejects_dh_protocol() {
        let dh_protocol = OiePaceProtocol::new(
            "0.4.0.127.0.7.2.2.4.1.2",
            "id-PACE-DH-GM-AES-CBC-CMAC-128",
            vec![0, 4, 0, 127, 0, 7, 2, 2, 4, 1, 2],
        )
        .unwrap();
        let can = CanKey::new("123456").unwrap();
        match PaceSession::new_ecdh(can, dh_protocol, 2) {
            Err(PaceSessionError::UnsupportedAgreement(_)) => {}
            _ => panic!("expected UnsupportedAgreement"),
        }
    }

    #[test]
    fn rejects_im_mapping_ecdh() {
        // Integrated Mapping is parsed but the engine only implements GM.
        let im_protocol = OiePaceProtocol::new(
            "0.4.0.127.0.7.2.2.4.4.2",
            "id-PACE-ECDH-IM-AES-CBC-CMAC-128",
            vec![0, 4, 0, 127, 0, 7, 2, 2, 4, 4, 2],
        )
        .unwrap();
        let can = CanKey::new("123456").unwrap();
        match PaceSession::new_ecdh(can, im_protocol, NIST_P256_ID) {
            Err(PaceSessionError::UnsupportedMapping(MappingType::Im)) => {}
            Err(e) => panic!("expected UnsupportedMapping(Im), got {e:?}"),
            Ok(_) => panic!("expected UnsupportedMapping(Im), got Ok"),
        }
    }

    #[test]
    fn rejects_im_mapping_dh() {
        let im_protocol = OiePaceProtocol::new(
            "0.4.0.127.0.7.2.2.4.3.2",
            "id-PACE-DH-IM-AES-CBC-CMAC-128",
            vec![0, 4, 0, 127, 0, 7, 2, 2, 4, 3, 2],
        )
        .unwrap();
        let can = CanKey::new("123456").unwrap();
        match PaceSession::new_dh(can, im_protocol, 0) {
            Err(PaceSessionError::UnsupportedMapping(MappingType::Im)) => {}
            Err(e) => panic!("expected UnsupportedMapping(Im), got {e:?}"),
            Ok(_) => panic!("expected UnsupportedMapping(Im), got Ok"),
        }
    }

    #[test]
    fn rejects_unsupported_curve() {
        let can = CanKey::new("123456").unwrap();
        match PaceSession::new_ecdh(can, ecdh_gm_aes128_oid(), 8) {
            Err(PaceSessionError::UnsupportedCurve(8)) => {}
            _ => panic!("expected UnsupportedCurve(8)"),
        }
    }

    #[test]
    fn first_action_is_mse_set_at() {
        let can = CanKey::new("123456").unwrap();
        let mut s = PaceSession::new_ecdh(can, ecdh_gm_aes128_oid(), NIST_P256_ID).unwrap();
        match s.next().unwrap() {
            PaceAction::SendApdu(apdu) => {
                // CLA=00, INS=22, P1=C1, P2=A4
                assert_eq!(&apdu[..4], &[0x00, 0x22, 0xC1, 0xA4]);
            }
            _ => panic!("expected SendApdu"),
        }
    }

    #[test]
    fn next_without_feed_errors() {
        let can = CanKey::new("123456").unwrap();
        let mut s = PaceSession::new_ecdh(can, ecdh_gm_aes128_oid(), NIST_P256_ID).unwrap();
        let _ = s.next().unwrap();
        assert!(s.next().is_err());
    }

    #[test]
    fn feed_before_next_errors() {
        let can = CanKey::new("123456").unwrap();
        let mut s = PaceSession::new_ecdh(can, ecdh_gm_aes128_oid(), NIST_P256_ID).unwrap();
        assert!(s.feed_response(&build_response(None)).is_err());
    }

    #[test]
    fn full_pace_loopback_produces_sm() {
        // ---- setup ----
        let protocol = ecdh_gm_aes128_oid();
        let can = CanKey::new("123456").unwrap();

        // Terminal + simulated ICC use separate seeded engines so the test
        // is deterministic.
        let seed_terminal_main = [0x11u8; 32];
        let seed_terminal_eph = [0x22u8; 32];
        let seed_icc_main = [0x33u8; 32];
        let seed_icc_eph = [0x44u8; 32];

        let mut session = PaceSession::new_ecdh_deterministic(
            can,
            protocol.clone(),
            NIST_P256_ID,
            seed_terminal_main,
            seed_terminal_eph,
        )
        .unwrap();

        // The "chip" side mirror.
        let can_chip = CanKey::new("123456").unwrap();
        let mut icc = ECDHPace::new(NIST_P256_ID).unwrap();

        // ---- Step A: MSE:Set AT ----
        match session.next().unwrap() {
            PaceAction::SendApdu(_) => {}
            _ => panic!("expected MSE:Set AT"),
        }
        session.feed_response(&build_response(None)).unwrap();

        // ---- Step 1: GA step 1 ----
        match session.next().unwrap() {
            PaceAction::SendApdu(_) => {}
            _ => panic!("expected step 1"),
        }
        // Simulated ICC chooses a random 16-byte nonce and encrypts with K_π.
        let nonce = [0x5Au8; 16];
        let cipher = AesCipher::new(protocol.key_length);
        let kpi = can_chip
            .kpi(protocol.cipher_algorithm, protocol.key_length)
            .unwrap();
        let zero_iv = [0u8; AES_BLOCK_SIZE];
        let enc_nonce = cipher
            .encrypt(&nonce, &kpi, Some(&zero_iv), BlockCipherMode::Cbc, false)
            .unwrap();
        let step1_body = dyn_auth_wrap(0x80, &enc_nonce);
        session
            .feed_response(&build_response(Some(&step1_body)))
            .unwrap();

        // ---- Step 2: GA step 2 — mapping public exchange ----
        let _step2_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 2"),
        };
        // Simulated ICC side generates its own key pair and returns its public.
        icc.generate_key_pair(Some(&seed_icc_main)).unwrap();
        let icc_mapping_pub = icc.get_pub_key().unwrap();
        let mut step2_body = vec![0x04];
        step2_body.extend_from_slice(&icc_mapping_pub.to_bytes());
        let step2_response = dyn_auth_wrap(0x82, &step2_body);
        session
            .feed_response(&build_response(Some(&step2_response)))
            .unwrap();

        // ---- Step 3: GA step 3 — ephemeral public exchange ----
        let _step3_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 3"),
        };
        // Chip also computes the mapped generator, then its own ephemeral.
        let terminal_mapping_pk =
            icc_mapping_pub_from_session(&session).expect("terminal's main pubkey after step 2");
        icc.map_and_generate_ephemeral(&terminal_mapping_pk, &nonce, Some(&seed_icc_eph))
            .unwrap();
        let icc_eph_pub = icc.get_pub_key_ephemeral().unwrap();
        let mut step3_body = vec![0x04];
        step3_body.extend_from_slice(&icc_eph_pub.to_bytes());
        let step3_response = dyn_auth_wrap(0x84, &step3_body);
        session
            .feed_response(&build_response(Some(&step3_response)))
            .unwrap();

        // ---- Step 4: GA step 4 — token exchange ----
        let _step4_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 4"),
        };
        // ICC computes its own token over the *terminal's* ephemeral public.
        let terminal_eph_pub = terminal_ephemeral_pub_from_session(&session)
            .expect("terminal ephemeral public after step 3");
        let seed_bytes = icc.get_ephemeral_shared_seed(&terminal_eph_pub).unwrap();
        let icc_k_mac = pace::calculate_mac_key(&protocol, &seed_bytes).unwrap();
        let icc_auth_input = pace::generate_encoding_input_data(&protocol, &terminal_eph_pub);
        let icc_token = pace::calculate_auth_token(&protocol, &icc_auth_input, &icc_k_mac).unwrap();
        let step4_response = dyn_auth_wrap(0x86, &icc_token);
        session
            .feed_response(&build_response(Some(&step4_response)))
            .unwrap();

        // ---- Completion ----
        match session.next().unwrap() {
            PaceAction::Done(sm) => {
                assert_eq!(sm.cipher.ks_enc().len(), 16);
                assert_eq!(sm.cipher.ks_mac().len(), 16);
                assert_eq!(sm.ssc().to_bytes().len(), 16); // AES SSC = 128-bit
            }
            _ => panic!("expected Done"),
        }

        // Re-taking a consumed session must keep returning AlreadyTaken without
        // corrupting the state machine (a second call must not regress to Start).
        assert!(matches!(
            session.next(),
            Err(PaceSessionError::AlreadyTaken)
        ));
        assert!(matches!(
            session.next(),
            Err(PaceSessionError::AlreadyTaken)
        ));
    }

    #[test]
    fn full_pace_dh_loopback_produces_sm() {
        // ---- setup ----
        let protocol = dh_gm_aes128_oid();
        let can = CanKey::new("123456").unwrap();

        let seed_terminal_main = [0x11u8; 32];
        let seed_terminal_eph = [0x22u8; 32];
        let seed_icc_main = [0x33u8; 32];
        let seed_icc_eph = [0x44u8; 32];

        // ICAO domain parameter id 0 = RFC 5114 1024/160.
        let mut session = PaceSession::new_dh_deterministic(
            can,
            protocol.clone(),
            0,
            seed_terminal_main,
            seed_terminal_eph,
        )
        .unwrap();

        // The "chip" side mirror — a second DH engine on the same group.
        let can_chip = CanKey::new("123456").unwrap();
        let mut icc = dh_pace::get_domain_parameter(0).unwrap();

        // ---- Step A: MSE:Set AT ----
        match session.next().unwrap() {
            PaceAction::SendApdu(_) => {}
            _ => panic!("expected MSE:Set AT"),
        }
        session.feed_response(&build_response(None)).unwrap();

        // ---- Step 1: GA step 1 ----
        match session.next().unwrap() {
            PaceAction::SendApdu(_) => {}
            _ => panic!("expected step 1"),
        }
        // Simulated ICC chooses a 16-byte nonce and encrypts with K_π.
        let nonce = [0x5Au8; 16];
        let cipher = AesCipher::new(protocol.key_length);
        let kpi = can_chip
            .kpi(protocol.cipher_algorithm, protocol.key_length)
            .unwrap();
        let zero_iv = [0u8; AES_BLOCK_SIZE];
        let enc_nonce = cipher
            .encrypt(&nonce, &kpi, Some(&zero_iv), BlockCipherMode::Cbc, false)
            .unwrap();
        let step1_body = dyn_auth_wrap(0x80, &enc_nonce);
        session
            .feed_response(&build_response(Some(&step1_body)))
            .unwrap();

        // ---- Step 2: GA step 2 — mapping public exchange ----
        let _step2_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 2"),
        };
        // ICC generates its own DH key pair and returns its raw public (no
        // 0x04 prefix — DH public keys are raw big-endian integers).
        icc.generate_key_pair(Some(seed_u64(&seed_icc_main)))
            .unwrap();
        let icc_mapping_pub = icc.get_pub_key().unwrap();
        let step2_response = dyn_auth_wrap(0x82, &icc_mapping_pub.to_bytes());
        session
            .feed_response(&build_response(Some(&step2_response)))
            .unwrap();

        // ---- Step 3: GA step 3 — ephemeral public exchange ----
        let _step3_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 3"),
        };
        // ICC computes the mapped generator, then its own ephemeral key pair.
        let terminal_mapping_pub =
            icc_mapping_pub_from_session(&session).expect("terminal's main pubkey after step 2");
        let g = icc
            .get_mapped_generator(&terminal_mapping_pub.to_relevant_bytes(), &nonce)
            .unwrap();
        icc.generate_ephemeral_with_custom_generator(
            BigUint::from_bytes_be(&g),
            Some(seed_u64(&seed_icc_eph)),
        )
        .unwrap();
        let icc_eph_pub = icc.get_pub_key_ephemeral().unwrap();
        let step3_response = dyn_auth_wrap(0x84, &icc_eph_pub.to_bytes());
        session
            .feed_response(&build_response(Some(&step3_response)))
            .unwrap();

        // ---- Step 4: GA step 4 — token exchange ----
        let _step4_apdu = match session.next().unwrap() {
            PaceAction::SendApdu(bytes) => bytes,
            _ => panic!("expected step 4"),
        };
        // ICC computes its own token over the *terminal's* ephemeral public.
        let terminal_eph_pub = terminal_ephemeral_pub_from_session(&session)
            .expect("terminal ephemeral public after step 3");
        let seed_bytes = big_uint_to_bytes(
            &icc.get_ephemeral_shared_secret(&terminal_eph_pub.to_relevant_bytes())
                .unwrap(),
        );
        let icc_k_mac = pace::calculate_mac_key(&protocol, &seed_bytes).unwrap();
        let icc_auth_input = pace::generate_encoding_input_data(&protocol, &terminal_eph_pub);
        let icc_token = pace::calculate_auth_token(&protocol, &icc_auth_input, &icc_k_mac).unwrap();
        let step4_response = dyn_auth_wrap(0x86, &icc_token);
        session
            .feed_response(&build_response(Some(&step4_response)))
            .unwrap();

        // ---- Completion ----
        match session.next().unwrap() {
            PaceAction::Done(sm) => {
                assert_eq!(sm.cipher.ks_enc().len(), 16);
                assert_eq!(sm.cipher.ks_mac().len(), 16);
                assert_eq!(sm.ssc().to_bytes().len(), 16); // AES SSC = 128-bit
            }
            _ => panic!("expected Done"),
        }
    }

    /// Test helper — rebuilds the terminal's main (mapping) public by
    /// inspecting the ECDH engine inside a `PaceSession`. Uses the session's
    /// transient state between feed_response(step 2) and next().
    fn icc_mapping_pub_from_session<K: AccessKey>(
        session: &PaceSession<K>,
    ) -> Option<PublicKeyPace> {
        session.engine.main_pub_key().ok()
    }

    fn terminal_ephemeral_pub_from_session<K: AccessKey>(
        session: &PaceSession<K>,
    ) -> Option<PublicKeyPace> {
        session.engine.ephemeral_pub_key().ok()
    }
}