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
//! ICAO 9303 secure messaging handler.
//!
//! [`MrtdSM`] implements [`SecureMessaging`] by combining an [`SmCipher`]
//! (3DES or AES) with a monotonically-incrementing SSC. Protecting a
//! [`CommandApdu`] wraps the header + data into `DO'85'` or `DO'87'`, appends
//! the expected length in `DO'97'`, and authenticates the whole message with
//! a `DO'8E'` MAC. Unprotecting performs the reverse.

use crate::crypto::aes::AES_BLOCK_SIZE;
use crate::crypto::crypto_utils::constant_time_eq;
use crate::crypto::des::DesedeCipher;
use crate::crypto::iso9797;
use crate::lds::asn1_object_identifiers::CipherAlgorithm;
use crate::lds::tlv::{DecodedTv, Tlv};
use crate::proto::iso7816::command_apdu::CommandApdu;
use crate::proto::iso7816::iso7816::cla;
use crate::proto::iso7816::iso7816::ins;
use crate::proto::iso7816::response_apdu::{ResponseApdu, StatusWord};
use crate::proto::iso7816::sm::{
    self, SecureMessaging, SmError, TAG_DO85, TAG_DO87, TAG_DO8E, TAG_DO99,
};
use crate::proto::iso7816::smcipher::SmCipher;
use crate::proto::ssc::Ssc;

/// ICAO 9303 secure messaging handler.
pub struct MrtdSM<C: SmCipher> {
    pub cipher: C,
    ssc: Ssc,
}

impl<C: SmCipher> MrtdSM<C> {
    /// Creates a new [`MrtdSM`] with the given cipher and initial SSC.
    pub fn new(cipher: C, ssc: Ssc) -> Self {
        Self { cipher, ssc }
    }

    /// Replaces the current SSC.
    pub fn set_ssc(&mut self, ssc: Ssc) {
        self.ssc = ssc;
    }

    /// Returns the current SSC.
    pub fn ssc(&self) -> &Ssc {
        &self.ssc
    }

    // -----------------------------------------------------------------------
    // Cipher-specific helpers
    // -----------------------------------------------------------------------

    fn block_len(&self) -> Result<usize, SmError> {
        match self.cipher.cipher_algorithm() {
            CipherAlgorithm::Aes => Ok(AES_BLOCK_SIZE),
            CipherAlgorithm::DeSede => Ok(DesedeCipher::BLOCK_SIZE),
        }
    }

    /// Builds the encrypted data DO (`DO'85'` for extended READ BINARY, else
    /// `DO'87'`).
    fn generate_data_do(&self, cmd: &CommandApdu) -> Result<Vec<u8>, SmError> {
        match cmd.data.as_ref() {
            Some(data) if !data.is_empty() => {
                let block_len = self.block_len()?;
                let padded = iso9797::pad(data, block_len)
                    .map_err(|e| SmError(format!("ISO 9797 pad: {e}")))?;
                let edata = self.cipher.encrypt(&padded, Some(&self.ssc))?;
                let out = if cmd.ins == ins::READ_BINARY_EXT {
                    sm::do85(&edata)
                } else {
                    sm::do87(&edata, true)
                };
                Ok(out)
            }
            _ => Ok(Vec::new()),
        }
    }

    fn generate_m(
        &self,
        cmd: &CommandApdu,
        data_do: &[u8],
        do97: &[u8],
    ) -> Result<Vec<u8>, SmError> {
        let block_len = self.block_len()?;
        let padded_header = iso9797::pad(&cmd.raw_header(), block_len)
            .map_err(|e| SmError(format!("ISO 9797 pad: {e}")))?;
        let mut out = padded_header;
        out.extend_from_slice(data_do);
        out.extend_from_slice(do97);
        Ok(out)
    }

    fn generate_n(&self, m: &[u8]) -> Result<Vec<u8>, SmError> {
        let block_len = self.block_len()?;
        let mut up_n = self.ssc.to_bytes();
        up_n.extend_from_slice(m);
        iso9797::pad(&up_n, block_len).map_err(|e| SmError(format!("ISO 9797 pad: {e}")))
    }

    fn generate_k(&self, data: &[u8]) -> Result<Vec<u8>, SmError> {
        let block_len = self.block_len()?;
        let mut up_k = self.ssc.to_bytes();
        up_k.extend_from_slice(data);
        iso9797::pad(&up_k, block_len).map_err(|e| SmError(format!("ISO 9797 pad: {e}")))
    }

    /// Decrypts a `DO'85'` or `DO'87'` data object.
    fn decrypt_data_do(&self, dtv: Option<&DecodedTv>) -> Result<Option<Vec<u8>>, SmError> {
        let Some(dtv) = dtv else {
            return Ok(None);
        };
        if dtv.value.is_empty() {
            return Ok(None);
        }

        let tag = dtv.tag.value;
        if tag != TAG_DO85 && tag != TAG_DO87 {
            return Err(SmError(format!(
                "Can't decrypt invalid data DO with tag={tag:X}"
            )));
        }

        let is_do87 = tag == TAG_DO87;
        // DO'87' carries a leading padding-content indicator: 0x01 = the
        // plaintext was ISO 9797-1 padded, 0x02 = it was not. Any other value is
        // malformed and must be rejected rather than silently treated as
        // unpadded. DO'85' has no indicator and is always padded.
        let (padded, cipher_input): (bool, &[u8]) = if is_do87 {
            match dtv.value[0] {
                0x01 => (true, &dtv.value[1..]),
                0x02 => (false, &dtv.value[1..]),
                other => {
                    return Err(SmError(format!(
                        "Invalid DO'87' padding-content indicator: {other:#04X}"
                    )))
                }
            }
        } else {
            (true, &dtv.value[..])
        };
        let mut data = self.cipher.decrypt(cipher_input, Some(&self.ssc))?;
        if padded {
            let block_len = self.block_len()?;
            data = iso9797::unpad(&data, block_len)
                .map_err(|e| SmError(format!("ISO 9797 unpad: {e}")))?
                .to_vec();
        }
        Ok(Some(data))
    }

    fn parse_data_do(rapdu: &ResponseApdu) -> Result<Option<DecodedTv>, SmError> {
        let Some(data) = rapdu.data.as_ref() else {
            return Ok(None);
        };
        if data.is_empty() {
            return Ok(None);
        }
        let first = data[0] as u32;
        if first != TAG_DO85 && first != TAG_DO87 {
            return Ok(None);
        }
        let decoded = Tlv::decode(data).map_err(|e| SmError(format!("Invalid data DO: {e}")))?;
        Ok(Some(decoded))
    }

    fn parse_do99(rapdu: &ResponseApdu, offset: usize) -> Result<DecodedTv, SmError> {
        let data = rapdu
            .data
            .as_ref()
            .ok_or_else(|| SmError("Missing DO'99' in response APDU".into()))?;
        if offset >= data.len() || data[offset] as u32 != TAG_DO99 {
            return Err(SmError(
                "Missing DO'99' in response APDU or invalid offset".into(),
            ));
        }
        Tlv::decode(&data[offset..]).map_err(|e| SmError(format!("Invalid DO99: {e}")))
    }

    fn parse_do8e(rapdu: &ResponseApdu, offset: usize) -> Result<DecodedTv, SmError> {
        let data = rapdu
            .data
            .as_ref()
            .ok_or_else(|| SmError("Missing DO'8E' in response APDU".into()))?;
        if offset >= data.len() || data[offset] as u32 != TAG_DO8E {
            return Err(SmError(
                "Missing DO'8E' in response APDU or invalid offset".into(),
            ));
        }
        Tlv::decode(&data[offset..]).map_err(|e| SmError(format!("Invalid DO8E: {e}")))
    }

    fn mask_cla(cla_byte: u8) -> u8 {
        cla_byte | cla::SM_HEADER_AUTHN
    }
}

impl<C: SmCipher> SecureMessaging for MrtdSM<C> {
    fn protect(&mut self, cmd: &CommandApdu) -> Result<CommandApdu, SmError> {
        // Increment SSC BEFORE encrypting — mirrors the reference.
        self.ssc.increment();

        let mut masked = cmd.clone();
        masked.cla = Self::mask_cla(masked.cla);

        let data_do = self.generate_data_do(&masked)?;
        let do97 = sm::do97(masked.ne);
        let m = self.generate_m(&masked, &data_do, &do97)?;
        let n = self.generate_n(&m)?;
        let cc = self.cipher.mac(&n)?;
        let do8e = sm::do8e(&cc);

        let mut combined = data_do;
        combined.extend_from_slice(&do97);
        combined.extend_from_slice(&do8e);

        masked.data = Some(combined);
        masked.ne = 256;
        Ok(masked)
    }

    fn unprotect(&mut self, rapdu: &ResponseApdu) -> Result<ResponseApdu, SmError> {
        // A protected exchange is answered with DO'99' and DO'8E' even when the command
        // returns no data, so a bare status word carries no MAC and has been
        // authenticated by nobody.
        if rapdu.data.as_ref().is_none_or(|d| d.is_empty()) {
            // Which makes an unprotected *success* the dangerous shape: anyone able to
            // modify the channel can strip the secure-messaging wrapper from a response
            // whose command returns no data — SELECT, MSE:Set AT — and have the reader
            // treat it as having succeeded. "Nothing to check" is not "checked and
            // fine".
            if rapdu.status == StatusWord::SUCCESS {
                return Err(SmError(
                    "Unprotected success on a secure-messaging session: no DO'8E' to verify".into(),
                ));
            }

            // An unprotected *error*, by contrast, is how the chip says secure messaging
            // itself failed (6987/6988) or that it rejected the command before applying
            // SM at all. It cannot be authenticated and is not being trusted — it is
            // handed up as the status it is, so the caller keeps a diagnosis rather than
            // an opaque SM failure. The SSC deliberately does not advance: the session
            // cannot continue from here either way.
            return Ok(rapdu.clone());
        }

        // A body is present, so it is verified whatever the status claims — including
        // when the status says secure messaging failed. A status word sitting outside
        // the MAC is not evidence of anything.
        self.ssc.increment();

        let data_do = Self::parse_data_do(rapdu)?;
        let data_do_len = data_do.as_ref().map(|d| d.encoded_len).unwrap_or(0);
        let do99 = Self::parse_do99(rapdu, data_do_len)?;
        let do8e_start = data_do_len + do99.encoded_len;
        let do8e = Self::parse_do8e(rapdu, do8e_start)?;

        let body = rapdu
            .data
            .as_ref()
            .ok_or_else(|| SmError("Missing response data".into()))?;
        let k = self.generate_k(&body[..do8e_start])?;
        let cc = self.cipher.mac(&k)?;
        if !constant_time_eq(&cc, &do8e.value) {
            return Err(SmError("Invalid MAC of response APDU".into()));
        }

        let data = self.decrypt_data_do(data_do.as_ref())?;
        let status = StatusWord::from_bytes(&do99.value, 0)
            .map_err(|e| SmError(format!("Invalid SW in DO'99': {e}")))?;
        Ok(ResponseApdu::new(status, data))
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::des_smcipher::DesSmCipher;

    fn build_sm() -> MrtdSM<DesSmCipher> {
        // ICAO 9303 p11 Appendix D.3 BAC session keys (used across the book).
        let k_enc = hex::decode("979EC13B1CBFE9DCD01AB0FED307EAE5").unwrap();
        let k_mac = hex::decode("F1CB1F1FB5ADF208806B89DC579DC1F8").unwrap();
        let cipher = DesSmCipher::new(k_enc, k_mac).unwrap();
        let ssc = Ssc::new(&hex::decode("887022120C06C226").unwrap(), 64).unwrap();
        MrtdSM::new(cipher, ssc)
    }

    #[test]
    fn protect_masks_cla_and_appends_do8e() {
        let mut sm = build_sm();
        let cmd = CommandApdu::new(
            0x00,
            ins::SELECT_FILE,
            0x02,
            0x0C,
            Some(vec![0x01, 0x1E]),
            0,
        )
        .unwrap();
        let p = sm.protect(&cmd).unwrap();
        assert_eq!(p.cla & cla::SM_HEADER_AUTHN, cla::SM_HEADER_AUTHN);
        // Protected APDU has data = DO'87' || DO'8E' (no DO'97' since ne=0).
        let body = p.data.unwrap();
        // DO'8E' tag must appear somewhere in the body (at the end).
        assert!(body.contains(&(TAG_DO8E as u8)));
    }

    #[test]
    fn protect_increments_ssc() {
        let mut sm = build_sm();
        let before = sm.ssc().to_bytes();
        let cmd = CommandApdu::new(0x00, 0xA4, 0x02, 0x0C, Some(vec![0x01, 0x1E]), 0).unwrap();
        sm.protect(&cmd).unwrap();
        let after = sm.ssc().to_bytes();
        assert_ne!(before, after);
    }

    #[test]
    fn unprotect_passthrough_on_sm_data_missing() {
        let mut sm = build_sm();
        let rapdu = ResponseApdu::new(StatusWord::SM_DATA_MISSING, None);
        let out = sm.unprotect(&rapdu).unwrap();
        assert_eq!(out.status, StatusWord::SM_DATA_MISSING);
    }

    /// The bypass this guard used to allow.
    ///
    /// A protected command that returns no data still answers with DO'99' and DO'8E'.
    /// Anyone able to modify the channel could strip that wrapper, return a bare 9000,
    /// and have the reader record the command as having succeeded without a MAC ever
    /// being checked.
    #[test]
    fn unprotect_rejects_an_unprotected_success() {
        let mut sm = build_sm();
        let rapdu = ResponseApdu::new(StatusWord::SUCCESS, None);

        let err = sm.unprotect(&rapdu).unwrap_err();

        assert!(err.0.contains("Unprotected success"), "{}", err.0);
    }

    /// Rejecting it is only half the job: a session that carried on from here would do
    /// so with a counter the chip does not share, and every later MAC would fail for a
    /// reason that has nothing to do with the real fault.
    #[test]
    fn a_rejected_response_does_not_advance_the_ssc() {
        let mut sm = build_sm();
        let before = sm.ssc().to_bytes();

        let _ = sm.unprotect(&ResponseApdu::new(StatusWord::SUCCESS, None));
        assert_eq!(sm.ssc().to_bytes(), before, "rejected success");

        let _ = sm.unprotect(&ResponseApdu::new(StatusWord::SM_DATA_MISSING, None));
        assert_eq!(sm.ssc().to_bytes(), before, "passed-through error");
    }

    /// An error status outside the MAC is not evidence that the body inside it is
    /// unworthy of checking — so a status-bearing response that carries one is verified
    /// like any other rather than waved through on the strength of its status word.
    #[test]
    fn an_sm_error_carrying_a_body_is_still_verified() {
        let mut sm = build_sm();
        let mut body = sm::do99(0x9000);
        body.extend_from_slice(&sm::do8e(&[0u8; 8]));

        let rapdu = ResponseApdu::new(StatusWord::SM_DATA_MISSING, Some(body));

        assert!(
            sm.unprotect(&rapdu).is_err(),
            "a bogus MAC must fail even when the status claims SM already failed"
        );
    }

    #[test]
    fn decrypt_rejects_invalid_do87_indicator() {
        let sm = build_sm();
        // DO'87' whose leading padding-content indicator is neither 0x01 nor
        // 0x02 must be rejected before any decryption is attempted.
        let mut body = vec![0x05u8];
        body.extend_from_slice(&[0u8; 8]); // block-aligned dummy ciphertext
        let tlv = Tlv::encode(TAG_DO87, &body);
        let dtv = Tlv::decode(&tlv).unwrap();
        let err = sm.decrypt_data_do(Some(&dtv)).unwrap_err();
        assert!(err.0.contains("padding-content indicator"));
    }

    #[test]
    fn unprotect_rejects_mac_mismatch() {
        let mut sm = build_sm();
        // Bogus SM response: DO'99' with SW=9000 + DO'8E' with zero MAC.
        let do99 = sm::do99(0x9000);
        let do8e = sm::do8e(&[0u8; 8]);
        let mut body = do99;
        body.extend_from_slice(&do8e);
        let rapdu = ResponseApdu::new(StatusWord::SUCCESS, Some(body));
        assert!(sm.unprotect(&rapdu).is_err());
    }

    #[test]
    fn protect_then_unprotect_via_loopback_roundtrip() {
        // Build two SMs with identical state; use one to protect, the other to
        // unprotect — this confirms the MAC / SSC handshake ticks in lock-step.
        let mut writer = build_sm();
        let mut reader = build_sm();

        let cmd = CommandApdu::new(
            0x00,
            ins::READ_BINARY,
            0x00,
            0x00,
            None,
            4, // short Le
        )
        .unwrap();
        let protected = writer.protect(&cmd).unwrap();

        // Forge a plausible response: encrypt 4 bytes of plaintext, build DO'87' + DO'99' + DO'8E'.
        let plaintext = vec![0xABu8, 0xCD, 0xEF, 0x01];
        let padded = iso9797::pad(&plaintext, DesedeCipher::BLOCK_SIZE).unwrap();
        // Use reader's cipher to produce ciphertext with the (incremented) SSC.
        reader.ssc.increment();
        let ct = reader.cipher.encrypt(&padded, Some(&reader.ssc)).unwrap();
        // Reset to a fresh reader so unprotect performs its own increment.
        let mut reader = build_sm();

        let do87 = sm::do87(&ct, true);
        let do99 = sm::do99(0x9000);
        let mut body = do87.clone();
        body.extend_from_slice(&do99);

        // Compute MAC over k = SSC(incremented) || body.
        reader.ssc.increment();
        let mut k = reader.ssc.to_bytes();
        k.extend_from_slice(&body);
        let k_padded = iso9797::pad(&k, DesedeCipher::BLOCK_SIZE).unwrap();
        let cc = reader.cipher.mac(&k_padded).unwrap();
        // Rewind the SSC so unprotect re-increments it back to the same point.
        reader.ssc = build_sm().ssc;

        let do8e = sm::do8e(&cc);
        let mut body = do87;
        body.extend_from_slice(&do99);
        body.extend_from_slice(&do8e);

        let rapdu = ResponseApdu::new(StatusWord::SUCCESS, Some(body));
        let out = reader.unprotect(&rapdu).unwrap();
        assert_eq!(out.status, StatusWord::SUCCESS);
        assert_eq!(out.data.unwrap(), plaintext);

        // And `protected` is a real APDU (sanity).
        assert!(protected.data.is_some());
    }
}