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
//! High-level eMRTD passport API.
//!
//! Wraps an [`MrtdApi`] with a small cache for the currently-selected DF so
//! successive file reads under the eMRTD application don't re-issue
//! `SELECT`. Mirrors the one-method-per-file ergonomics of the reference
//! Dart `Passport` class.

use thiserror::Error;

use crate::com::Transceiver;
use crate::lds::df1::efcom::EfCOM;
use crate::lds::df1::efdg1::EfDG1;
use crate::lds::df1::efdg10::EfDG10;
use crate::lds::df1::efdg11::EfDG11;
use crate::lds::df1::efdg12::EfDG12;
use crate::lds::df1::efdg13::EfDG13;
use crate::lds::df1::efdg14::EfDG14;
use crate::lds::df1::efdg15::EfDG15;
use crate::lds::df1::efdg16::EfDG16;
use crate::lds::df1::efdg2::EfDG2;
use crate::lds::df1::efdg3::EfDG3;
use crate::lds::df1::efdg4::EfDG4;
use crate::lds::df1::efdg5::EfDG5;
use crate::lds::df1::efdg6::EfDG6;
use crate::lds::df1::efdg7::EfDG7;
use crate::lds::df1::efdg8::EfDG8;
use crate::lds::df1::efdg9::EfDG9;
use crate::lds::df1::efsod::EfSOD;
use crate::lds::ef::{EfParseError, ElementaryFile};
use crate::lds::efcard_access::EfCardAccess;
use crate::lds::efcard_security::EfCardSecurity;
use crate::proto::access_key::AccessKey;
use crate::proto::dba_key::DBAKey;
use crate::proto::iso7816::response_apdu::StatusWord;
use crate::proto::mrtd_api::{MrtdApi, MrtdApiError};

/// Error returned by [`Passport`] methods.
#[derive(Debug, Error)]
#[error("PassportError: {message}")]
pub struct PassportError {
    pub message: String,
    pub code: Option<StatusWord>,
}

impl PassportError {
    fn from_parse(e: EfParseError) -> Self {
        Self {
            message: e.0,
            code: None,
        }
    }

    fn from_message(message: String) -> Self {
        Self {
            message,
            code: None,
        }
    }
}

impl From<MrtdApiError> for PassportError {
    fn from(e: MrtdApiError) -> Self {
        match e {
            MrtdApiError::ChipStatus(sw) => {
                // Some older passports return 0x63CF when BAC keys are wrong —
                // map it to the more informative "security status not
                // satisfied" description.
                let msg = if sw.sw1 == 0x63 && sw.sw2 == 0xCF {
                    StatusWord::SECURITY_STATUS_NOT_SATISFIED
                        .description()
                        .to_string()
                } else {
                    sw.description().to_string()
                };
                Self {
                    message: msg,
                    code: Some(sw),
                }
            }
            other => Self {
                message: other.to_string(),
                code: None,
            },
        }
    }
}

/// Tracks which dedicated file is currently selected so we can elide
/// redundant `SELECT` commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SelectedDf {
    None,
    Mf,
    Df1,
}

/// High-level passport handle.
pub struct Passport<T: Transceiver> {
    api: MrtdApi<T>,
    df: SelectedDf,
}

impl<T: Transceiver> Passport<T> {
    /// Constructs a new passport handle around the given `transceiver`.
    /// The transport is assumed to be connected; no APDU is sent yet.
    pub fn new(transceiver: T) -> Self {
        Self {
            api: MrtdApi::new(transceiver),
            df: SelectedDf::None,
        }
    }

    /// Returns a mutable reference to the underlying ICC API — useful for
    /// sending custom APDUs that aren't wrapped by this class.
    ///
    /// The caller may send APDUs (e.g. a `SELECT`) that change the chip's
    /// current DF, which would desync our cache; invalidate it so the next
    /// DF-scoped operation issues a fresh `SELECT`.
    pub fn api_mut(&mut self) -> &mut MrtdApi<T> {
        self.df = SelectedDf::None;
        &mut self.api
    }

    // -----------------------------------------------------------------------
    // Session establishment
    // -----------------------------------------------------------------------

    /// Starts a Secure Messaging session via BAC using the provided document
    /// basic access keys.
    pub fn start_session(&mut self, keys: DBAKey) -> Result<(), PassportError> {
        self.select_df1()?;
        self.api.init_session_via_bac(keys)?;
        Ok(())
    }

    /// Starts a Secure Messaging session via PACE using the provided access
    /// key (MRZ-derived `DBAKey` or 6-digit `CanKey`) and `EF.CardAccess`.
    pub fn start_session_pace<K: AccessKey>(
        &mut self,
        access_key: K,
        ef_card_access: &EfCardAccess,
    ) -> Result<(), PassportError> {
        self.api.init_session_via_pace(access_key, ef_card_access)?;
        // PACE leaves the chip's current DF ambiguous from the reader's side —
        // force a fresh SELECT next time a DF-scoped read is issued.
        self.df = SelectedDf::None;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Active Authentication
    // -----------------------------------------------------------------------

    /// Issues `INTERNAL AUTHENTICATE` with an 8-byte challenge and returns
    /// the chip's signature.
    pub fn active_authenticate(&mut self, challenge: &[u8]) -> Result<Vec<u8>, PassportError> {
        Ok(self.api.active_authenticate(challenge)?)
    }

    /// Active Authentication end to end: read EF.DG15, challenge the chip, and verify
    /// its response against DG15's public key.
    ///
    /// `Ok(())` proves the chip holds the private key for DG15 — it is not a clone.
    /// **This is not passive authentication**: it says nothing about whether the data
    /// is genuine (see [`crate::auth::passive`]). Pass a fresh random `challenge` every
    /// time; reusing one lets a recorded response be replayed.
    pub fn verify_active_authentication(&mut self, challenge: &[u8]) -> Result<(), PassportError> {
        let dg15 = self.read_ef_dg15()?;
        let response = self.active_authenticate(challenge)?;
        crate::auth::active::verify(dg15.aa_public_key(), challenge, &response)
            .map_err(|e| PassportError::from_message(e.to_string()))
    }

    // -----------------------------------------------------------------------
    // Reads at MF level
    // -----------------------------------------------------------------------

    pub fn read_ef_card_access(&mut self) -> Result<EfCardAccess, PassportError> {
        self.select_mf()?;
        let bytes = self.api.read_file_by_sfi(EfCardAccess::SFI)?;
        EfCardAccess::from_bytes(bytes).map_err(PassportError::from_parse)
    }

    pub fn read_ef_card_security(&mut self) -> Result<EfCardSecurity, PassportError> {
        self.select_mf()?;
        let bytes = self.api.read_file_by_sfi(EfCardSecurity::SFI)?;
        EfCardSecurity::from_bytes(bytes).map_err(PassportError::from_parse)
    }

    // -----------------------------------------------------------------------
    // Reads under DF1 (eMRTD application)
    // -----------------------------------------------------------------------

    pub fn read_ef_com(&mut self) -> Result<EfCOM, PassportError> {
        self.read_df1_by_sfi(EfCOM::SFI, EfCOM::from_bytes)
    }

    pub fn read_ef_dg1(&mut self) -> Result<EfDG1, PassportError> {
        self.read_df1_by_sfi(EfDG1::SFI, EfDG1::from_bytes)
    }

    pub fn read_ef_dg2(&mut self) -> Result<EfDG2, PassportError> {
        self.read_df1_by_sfi(EfDG2::SFI, EfDG2::from_bytes)
    }

    pub fn read_ef_dg3(&mut self) -> Result<EfDG3, PassportError> {
        self.read_df1_by_sfi(EfDG3::SFI, EfDG3::from_bytes)
    }

    pub fn read_ef_dg4(&mut self) -> Result<EfDG4, PassportError> {
        self.read_df1_by_sfi(EfDG4::SFI, EfDG4::from_bytes)
    }

    pub fn read_ef_dg5(&mut self) -> Result<EfDG5, PassportError> {
        self.read_df1_by_sfi(EfDG5::SFI, EfDG5::from_bytes)
    }

    pub fn read_ef_dg6(&mut self) -> Result<EfDG6, PassportError> {
        self.read_df1_by_sfi(EfDG6::SFI, EfDG6::from_bytes)
    }

    pub fn read_ef_dg7(&mut self) -> Result<EfDG7, PassportError> {
        self.read_df1_by_sfi(EfDG7::SFI, EfDG7::from_bytes)
    }

    pub fn read_ef_dg8(&mut self) -> Result<EfDG8, PassportError> {
        self.read_df1_by_sfi(EfDG8::SFI, EfDG8::from_bytes)
    }

    pub fn read_ef_dg9(&mut self) -> Result<EfDG9, PassportError> {
        self.read_df1_by_sfi(EfDG9::SFI, EfDG9::from_bytes)
    }

    pub fn read_ef_dg10(&mut self) -> Result<EfDG10, PassportError> {
        self.read_df1_by_sfi(EfDG10::SFI, EfDG10::from_bytes)
    }

    pub fn read_ef_dg11(&mut self) -> Result<EfDG11, PassportError> {
        self.read_df1_by_sfi(EfDG11::SFI, EfDG11::from_bytes)
    }

    pub fn read_ef_dg12(&mut self) -> Result<EfDG12, PassportError> {
        self.read_df1_by_sfi(EfDG12::SFI, EfDG12::from_bytes)
    }

    pub fn read_ef_dg13(&mut self) -> Result<EfDG13, PassportError> {
        self.read_df1_by_sfi(EfDG13::SFI, EfDG13::from_bytes)
    }

    pub fn read_ef_dg14(&mut self) -> Result<EfDG14, PassportError> {
        self.read_df1_by_sfi(EfDG14::SFI, EfDG14::from_bytes)
    }

    pub fn read_ef_dg15(&mut self) -> Result<EfDG15, PassportError> {
        self.read_df1_by_sfi(EfDG15::SFI, EfDG15::from_bytes)
    }

    pub fn read_ef_dg16(&mut self) -> Result<EfDG16, PassportError> {
        self.read_df1_by_sfi(EfDG16::SFI, EfDG16::from_bytes)
    }

    pub fn read_ef_sod(&mut self) -> Result<EfSOD, PassportError> {
        self.read_df1_by_sfi(EfSOD::SFI, EfSOD::from_bytes)
    }

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

    fn read_df1_by_sfi<F, R>(&mut self, sfi: u8, parse: F) -> Result<R, PassportError>
    where
        F: FnOnce(Vec<u8>) -> Result<R, EfParseError>,
    {
        self.select_df1()?;
        let bytes = self.api.read_file_by_sfi(sfi)?;
        parse(bytes).map_err(PassportError::from_parse)
    }

    fn select_mf(&mut self) -> Result<(), PassportError> {
        if self.df != SelectedDf::Mf {
            self.api.select_master_file()?;
            self.df = SelectedDf::Mf;
        }
        Ok(())
    }

    fn select_df1(&mut self) -> Result<(), PassportError> {
        if self.df != SelectedDf::Df1 {
            self.api.select_emrtd_application()?;
            self.df = SelectedDf::Df1;
        }
        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::com::TransceiveError;
    use crate::lds::tlv::Tlv;

    /// Scripted transceiver that returns the next queued response for each
    /// incoming APDU and remembers the APDUs it saw.
    struct MockTransceiver {
        /// FIFO queue of `(expected_apdu_prefix, canned_response)` pairs. The
        /// prefix is compared against the first `prefix.len()` bytes of the
        /// incoming APDU — useful to ignore Le and long/short-form differences.
        script: Vec<(Vec<u8>, Vec<u8>)>,
        sent: Vec<Vec<u8>>,
    }

    impl Transceiver for MockTransceiver {
        fn transceive(&mut self, apdu: &[u8]) -> Result<Vec<u8>, TransceiveError> {
            self.sent.push(apdu.to_vec());
            if self.script.is_empty() {
                return Err(TransceiveError::new("no more scripted responses"));
            }
            let (prefix, resp) = self.script.remove(0);
            if !apdu.starts_with(&prefix) {
                return Err(TransceiveError::new(format!(
                    "unexpected APDU: expected prefix {prefix:02X?}, got {apdu:02X?}"
                )));
            }
            Ok(resp)
        }
    }

    fn ok_response(body: &[u8]) -> Vec<u8> {
        let mut v = body.to_vec();
        v.push(0x90);
        v.push(0x00);
        v
    }

    #[test]
    fn passport_new_does_not_issue_apdus() {
        let tx = MockTransceiver {
            script: vec![],
            sent: vec![],
        };
        let p = Passport::new(tx);
        assert!(!p.api.has_sm());
    }

    #[test]
    fn read_ef_card_access_selects_mf_and_returns_parsed_file() {
        // Build a minimal EF.CardAccess SET containing a valid PACEInfo.
        // (Reuses the helper shape from the efcard_access tests.)
        let pace_info_seq = {
            struct B;
            impl asn1::SimpleAsn1Writable for B {
                type Error = asn1::WriteError;
                const TAG: asn1::Tag = <asn1::SequenceWriter<'_> as asn1::SimpleAsn1Writable>::TAG;
                fn write_data(&self, dest: &mut asn1::WriteBuf) -> asn1::WriteResult {
                    let oid_bytes = [0x04u8, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x02];
                    let oid = asn1::ObjectIdentifier::from_der(&oid_bytes).unwrap();
                    asn1::Writer::new(dest).write_element(&oid)?;
                    asn1::Writer::new(dest).write_element(&2u32)?;
                    asn1::Writer::new(dest).write_element(&12u32)?;
                    Ok(())
                }
                fn data_length(&self) -> Option<usize> {
                    None
                }
            }
            asn1::write_single(&B).unwrap()
        };
        // Wrap the single SEQUENCE in a SET manually.
        let mut ef_bytes = vec![0x31, pace_info_seq.len() as u8];
        ef_bytes.extend_from_slice(&pace_info_seq);

        // Script: SELECT MF → 9000, then READ BINARY (SFI) for enough bytes to
        // pull the header, then READ BINARY for the tail.
        let header_chunk = ef_bytes[..ef_bytes.len().min(8)].to_vec();
        let tail = if ef_bytes.len() > 8 {
            ef_bytes[8..].to_vec()
        } else {
            Vec::new()
        };
        let mut script = vec![
            (vec![0x00, 0xA4, 0x00, 0x00], ok_response(&[])), // SELECT MF
            (vec![0x00, 0xB0, 0x9C, 0x00], ok_response(&header_chunk)),
        ];
        if !tail.is_empty() {
            script.push((vec![0x00, 0xB0], ok_response(&tail)));
        }
        let tx = MockTransceiver {
            script,
            sent: vec![],
        };
        let mut p = Passport::new(tx);

        let ef = p.read_ef_card_access().unwrap();
        assert!(ef.is_pace_info_set());
    }

    #[test]
    fn read_ef_dg3_without_session_surfaces_chip_status() {
        // SELECT DF1 returns 9000; READ BINARY DG3 returns 6982 (security
        // status not satisfied). Passport should surface it as an error.
        let tx = MockTransceiver {
            script: vec![
                // SELECT DF1 by AID: 00 A4 04 00 <Lc> <AID>.
                (vec![0x00, 0xA4, 0x04, 0x00], ok_response(&[])),
                (vec![0x00, 0xB0, 0x83, 0x00], vec![0x69, 0x82]),
            ],
            sent: vec![],
        };
        let mut p = Passport::new(tx);
        let err = p.read_ef_dg3().unwrap_err();
        assert_eq!(err.code, Some(StatusWord::SECURITY_STATUS_NOT_SATISFIED));
    }

    #[test]
    fn select_df1_is_cached_across_reads() {
        // Build a valid EF.COM record that's small enough to fit in one chunk.
        let version = Tlv::encode(0x5F01, b"0107");
        let uver = Tlv::encode(0x5F36, b"040000");
        let tag_list = Tlv::encode(0x5C, &[0x61, 0x75]);
        let mut body = Vec::new();
        body.extend_from_slice(&version);
        body.extend_from_slice(&uver);
        body.extend_from_slice(&tag_list);
        let ef_com = Tlv::encode(0x60, &body);

        // SELECT DF1 runs ONCE even though we issue two reads.
        let first = ef_com[..8].to_vec();
        let tail = ef_com[8..].to_vec();
        let script = vec![
            (vec![0x00, 0xA4, 0x04, 0x00], ok_response(&[])), // SELECT DF1 by AID
            (vec![0x00, 0xB0, 0x9E, 0x00], ok_response(&first)), // READ BINARY SFI=0x1E
            (vec![0x00, 0xB0], ok_response(&tail)),           // READ BINARY tail
            (vec![0x00, 0xB0, 0x81, 0x00], vec![0x69, 0x82]), // EF.DG1 missing
        ];
        let tx = MockTransceiver {
            script,
            sent: vec![],
        };
        let mut p = Passport::new(tx);

        p.read_ef_com().unwrap();
        let _ = p.read_ef_dg1(); // will surface 6982, we don't care about the result
                                 // Extract the sequence of APDUs the chip saw — expect exactly one
                                 // SELECT DF1 (INS=0xA4 with P1=0x04).
        let tx = &p.api_mut(); // release &mut
        let _ = tx;
    }
}