rdnie 0.1.1

Spanish electronic ID card (DNIe) driver over PC/SC: CWA-14890 secure channel, certificates, PIN retry counter and signing
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
// Derived from JMulticard (https://github.com/ctt-gob-es/jmulticard, commit 4ec9494):
// - es.gob.jmulticard.connection.cwa14890.Cwa14890OneV1Connection (Carlos Gamuci, Tomás García-Merás)
// - es.gob.jmulticard.connection.cwa14890.Cwa14890OneV2Connection (Tomás García-Merás)
// - es.gob.jmulticard.card.cwa14890.Cwa14890Card (Carlos Gamuci, Tomás García-Merás)
// - es.gob.jmulticard.card.dnie.Dnie (Tomás García-Merás)
// - es.gob.jmulticard.card.iso7816four.AbstractIso7816FourCard (Tomás García-Merás, Alberto Martínez)
// - es.gob.jmulticard.card.iso7816eight.AbstractIso7816EightCard (Tomás García-Merás)
// - es.gob.jmulticard.apdu.dnie.GetChipInfoApduCommand (Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.GetChallengeApduCommand (Alberto Martínez Cerquero,
//   Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.InternalAuthenticateApduCommand (Carlos Gamuci Millán,
//   Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.ExternalAuthenticateApduCommand (Carlos Gamuci Millán,
//   Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.MseSetApduCommand (Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.MseSetAuthenticationTemplateApduCommand (Tomás García-Merás)
// - es.gob.jmulticard.apdu.iso7816four.MseSetAuthenticationKeyApduCommand (Tomás García-Merás,
//   Carlos Gamuci Millán)
// - es.gob.jmulticard.apdu.iso7816eight.PsoVerifyCertificateApduCommand (Carlos Gamuci Millán,
//   Tomás García-Merás)
// rdnie takes the EUPL 1.1+ branch of the dual licence below.
//
// Controlador Java de la Secretaria de Estado de Administraciones Publicas
// para el DNI electronico.
//
// El Controlador Java para el DNI electronico es un proveedor de seguridad de JCA/JCE
// que permite el acceso y uso del DNI electronico en aplicaciones Java de terceros
// para la realizacion de procesos de autenticacion, firma electronica y validacion
// de firma. Para ello, se implementan las funcionalidades KeyStore y Signature para
// el acceso a los certificados y claves del DNI electronico, asi como la realizacion
// de operaciones criptograficas de firma con el DNI electronico. El Controlador ha
// sido disenado para su funcionamiento independiente del sistema operativo final.
//
// Copyright (C) 2012 Direccion General de Modernizacion Administrativa, Procedimientos
// e Impulso de la Administracion Electronica
//
// Este programa es software libre y utiliza un licenciamiento dual (LGPL 2.1+
// o EUPL 1.1+), lo cual significa que los usuarios podran elegir bajo cual de las
// licencias desean utilizar el codigo fuente. Su eleccion debera reflejarse
// en las aplicaciones que integren o distribuyan el Controlador, ya que determinara
// su compatibilidad con otros componentes.
//
// El Controlador puede ser redistribuido y/o modificado bajo los terminos de la
// Lesser GNU General Public License publicada por la Free Software Foundation,
// tanto en la version 2.1 de la Licencia, o en una version posterior.
//
// El Controlador puede ser redistribuido y/o modificado bajo los terminos de la
// European Union Public License publicada por la Comision Europea,
// tanto en la version 1.1 de la Licencia, o en una version posterior.
//
// Deberia recibir una copia de la GNU Lesser General Public License, si aplica, junto
// con este programa. Si no, consultelo en <http://www.gnu.org/licenses/>.
//
// Deberia recibir una copia de la European Union Public License, si aplica, junto
// con este programa. Si no, consultelo en <http://joinup.ec.europa.eu/software/page/eupl>.
//
// Este programa es distribuido con la esperanza de que sea util, pero
// SIN NINGUNA GARANTIA; incluso sin la garantia implicita de comercializacion
// o idoneidad para un proposito particular.

//! CWA-14890 mutual authentication of DNIe 3.0/4.0, as `Cwa14890OneV1Connection.open` runs it.

use rand_core::{OsRng, RngCore};
use rsa::{
    BigUint, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey,
    hazmat::{rsa_decrypt_and_check, rsa_encrypt},
    pkcs8::DecodePublicKey,
    traits::PublicKeyParts,
};
use sha1::{Digest, Sha1};
use sha2::Sha256;
use x509_cert::{
    Certificate,
    der::{Decode, Encode, Header, Reader, SliceReader, asn1::ObjectIdentifier},
};
use zeroize::Zeroize;

use crate::{
    Command, Error, Transport,
    files::{self, Location},
    key_sets::{CA_PUBLIC_KEY_REFERENCE, ComponentRoots, ICC_PRIVATE_KEY_REFERENCE, KeySet},
    secure_messaging::SecureMessaging,
};

const ICC_CERTIFICATE: &[u8] = &[0x3F, 0x00, 0x60, 0x1F];
const COMPONENT_CA_CERTIFICATE: &[u8] = &[0x3F, 0x00, 0x60, 0x20];
const SERIAL_LENGTH: usize = 8;
const CHALLENGE_LENGTH: usize = 8;
const SEED_LENGTH: usize = 32;
const SHA1_LENGTH: usize = 20;
const KEY_REFERENCE_LENGTH: usize = 12;
const FRAME_START: u8 = 0x6A;
const FRAME_END: u8 = 0xBC;
const MSE_SET: u8 = 0x22;

const SHA1_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.5");
const SHA256_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");

// DER DigestInfo headers of PKCS#1 v1.5 (RFC 8017, note 1 of section 9.2).
const SHA1_DIGEST_INFO: &[u8] = &[
    0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
];
const SHA256_DIGEST_INFO: &[u8] = &[
    0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
    0x00, 0x04, 0x20,
];

const INTERNAL_AUTHENTICATION_FAILED: Error =
    Error::SecureChannel("the card failed the internal authentication");
const EXTERNAL_AUTHENTICATION_FAILED: Error =
    Error::SecureChannel("the external authentication could not be built");
const RANDOM_FAILED: Error = Error::SecureChannel("the OS random generator failed");

/// Authenticates card and terminal with `keys` and returns the channel they agree on.
pub(crate) fn open(
    card: &mut dyn Transport,
    keys: &KeySet,
    roots: &ComponentRoots,
) -> Result<SecureMessaging, Error> {
    let serial = padded_serial(card)?;
    let icc_key = icc_public_key(card, roots)?;
    verify_ifd_certificate_chain(card, keys)?;

    let rnd_ifd: [u8; CHALLENGE_LENGTH] = random()?;
    let mut kicc = internal_authentication(card, keys, rnd_ifd, &icc_key)?;
    let rnd_icc = challenge(card)?;
    let mut kifd = external_authentication(card, keys, &serial, rnd_icc, &icc_key)?;

    let channel = SecureMessaging::derive(&kicc, &kifd, rnd_icc, rnd_ifd);
    kicc.zeroize();
    kifd.zeroize();
    Ok(channel)
}

/// The chip serial from `GET CHIP INFO`, left-padded to 8 bytes.
fn padded_serial(card: &mut dyn Transport) -> Result<Vec<u8>, Error> {
    let serial = send(card, 0x90, 0xB8, 0x00, 0x00, vec![], Some(7))?;
    let mut padded = vec![0; SERIAL_LENGTH.saturating_sub(serial.len())];
    padded.extend(serial);
    Ok(padded)
}

/// The public key of the X.509 component certificate, once its chain checks out as
/// `cwa_verify_icc_certificates` of `OpenSC` checks it, ending in any of `roots`.
fn icc_public_key(card: &mut dyn Transport, roots: &ComponentRoots) -> Result<RsaPublicKey, Error> {
    let ca = read_certificate(card, COMPONENT_CA_CERTIFICATE)?;
    let icc = read_certificate(card, ICC_CERTIFICATE)?;
    if !roots.iter().any(|root| ca.is_signed_by(root)) {
        return Err(Error::SecureChannel(
            "the component certificate chain is not signed by the DNIe root",
        ));
    }
    if !icc.is_signed_by(&ca.public_key()?) {
        return Err(Error::SecureChannel(
            "the component certificate is not signed by its CA",
        ));
    }
    icc.public_key()
}

const MALFORMED_CERTIFICATE: Error = Error::SecureChannel("malformed component certificate");

/// An X.509 certificate with its `tbsCertificate` exactly as the card stores it.
struct StoredCertificate {
    certificate: Certificate,
    tbs: Vec<u8>,
}

/// Reads the certificate at `path`; any data after it is ignored.
fn read_certificate(card: &mut dyn Transport, path: &[u8]) -> Result<StoredCertificate, Error> {
    let location = Location::new(path).ok_or(MALFORMED_CERTIFICATE)?;
    let encoded = files::read(card, &location).map_err(|error| match error {
        Error::Status(_) => Error::SecureChannel("the component certificate chain is missing"),
        other => other,
    })?;
    decode_certificate(&encoded).ok_or(MALFORMED_CERTIFICATE)
}

fn decode_certificate(encoded: &[u8]) -> Option<StoredCertificate> {
    let whole = SliceReader::new(encoded).ok()?.tlv_bytes().ok()?;
    let certificate = Certificate::from_der(whole).ok()?;
    let mut reader = SliceReader::new(whole).ok()?;
    Header::decode(&mut reader).ok()?;
    let tbs = reader.tlv_bytes().ok()?.to_vec();
    Some(StoredCertificate { certificate, tbs })
}

/// Checks `challenge ‖ component certificate ‖ answer`, the fuzz layout of the internal
/// authentication of a PIN channel without IDESP, and returns whether a root signed the certificate.
#[cfg(any(test, fuzzing))]
pub(crate) fn check_answers(input: &[u8], roots: &ComponentRoots) -> Result<bool, Error> {
    let keys = KeySet::for_card(None, crate::key_sets::Channel::Pin);
    let (challenge, rest) = input
        .split_at_checked(CHALLENGE_LENGTH + keys.terminal_chr.len())
        .ok_or(MALFORMED_CERTIFICATE)?;
    let encoded = SliceReader::new(rest)
        .and_then(|mut reader| reader.tlv_bytes())
        .map_err(|_| MALFORMED_CERTIFICATE)?;
    let certificate = decode_certificate(encoded).ok_or(MALFORMED_CERTIFICATE)?;
    let signed = roots.iter().any(|root| certificate.is_signed_by(root));
    let answer = &rest[encoded.len()..];
    validate_internal_authentication(
        answer,
        challenge,
        &keys.private_key(),
        &certificate.public_key()?,
    )?;
    Ok(signed)
}

impl StoredCertificate {
    fn public_key(&self) -> Result<RsaPublicKey, Error> {
        let spki = self
            .certificate
            .tbs_certificate
            .subject_public_key_info
            .to_der()
            .map_err(|_| MALFORMED_CERTIFICATE)?;
        RsaPublicKey::from_public_key_der(&spki).map_err(|_| MALFORMED_CERTIFICATE)
    }

    /// Whether `issuer` signed the stored TBS with PKCS#1 v1.5 and SHA-1 or SHA-256.
    fn is_signed_by(&self, issuer: &RsaPublicKey) -> bool {
        let oid = self.certificate.signature_algorithm.oid;
        let (prefix, digest) = if oid == SHA1_WITH_RSA {
            (SHA1_DIGEST_INFO, Sha1::digest(&self.tbs).to_vec())
        } else if oid == SHA256_WITH_RSA {
            (SHA256_DIGEST_INFO, Sha256::digest(&self.tbs).to_vec())
        } else {
            return false;
        };
        let Some(signature) = self.certificate.signature.as_bytes() else {
            return false;
        };
        let scheme = Pkcs1v15Sign {
            hash_len: Some(digest.len()),
            prefix: prefix.into(),
        };
        issuer.verify(scheme, &digest, signature).is_ok()
    }
}

/// Lets the card verify the CA CVC against its root key, then the terminal CVC against the CA.
fn verify_ifd_certificate_chain(card: &mut dyn Transport, keys: &KeySet) -> Result<(), Error> {
    set_public_key_to_verification(card, &CA_PUBLIC_KEY_REFERENCE)?;
    verify_certificate(card, keys.ca_cvc)?;
    set_public_key_to_verification(card, &keys.ca_chr)?;
    verify_certificate(card, keys.terminal_cvc)
}

fn set_public_key_to_verification(card: &mut dyn Transport, reference: &[u8]) -> Result<(), Error> {
    send(card, 0x00, MSE_SET, 0x81, 0xB6, tlv(0x83, reference), None)
        .map_err(|error| {
            refusal(
                error,
                "the card refused to select the key that verifies certificates",
            )
        })
        .map(drop)
}

fn verify_certificate(card: &mut dyn Transport, cvc: &[u8]) -> Result<(), Error> {
    send(card, 0x00, 0x2A, 0x00, 0xAE, cvc.to_vec(), None)
        .map_err(|error| refusal(error, "the card refused to verify the terminal certificate"))
        .map(drop)
}

fn refusal(error: Error, reason: &'static str) -> Error {
    match error {
        Error::Status(_) => Error::SecureChannel(reason),
        other => other,
    }
}

/// Selects the terminal and ICC keys, has the card sign `RND.IFD ‖ CHR` and returns `Kicc`.
fn internal_authentication(
    card: &mut dyn Transport,
    keys: &KeySet,
    rnd_ifd: [u8; CHALLENGE_LENGTH],
    icc_key: &RsaPublicKey,
) -> Result<[u8; SEED_LENGTH], Error> {
    let mut terminal_reference = [0; KEY_REFERENCE_LENGTH];
    terminal_reference[KEY_REFERENCE_LENGTH - keys.terminal_chr.len()..]
        .copy_from_slice(&keys.terminal_chr);
    let mut template = tlv(0x83, &terminal_reference);
    template.extend(tlv(0x84, &ICC_PRIVATE_KEY_REFERENCE));
    send(card, 0x00, MSE_SET, 0xC1, 0xA4, template, None)
        .map_err(|error| refusal(error, "the card refused to select the authentication keys"))?;

    let challenge = [&rnd_ifd[..], &keys.terminal_chr].concat();
    let answer = send(card, 0x00, 0x88, 0x00, 0x00, challenge.clone(), None)?;
    validate_internal_authentication(&answer, &challenge, &keys.private_key(), icc_key)
}

/// Recovers `6A ‖ PRND1 ‖ Kicc ‖ SHA-1(PRND1 ‖ Kicc ‖ RND.IFD ‖ CHR) ‖ BC` from the card's answer.
fn validate_internal_authentication(
    answer: &[u8],
    challenge: &[u8],
    terminal_key: &RsaPrivateKey,
    icc_key: &RsaPublicKey,
) -> Result<[u8; SEED_LENGTH], Error> {
    if icc_key.size() < 2 + SEED_LENGTH + SHA1_LENGTH {
        return Err(INTERNAL_AUTHENTICATION_FAILED);
    }
    let sigmin = rsa_decrypt_and_check(terminal_key, Some(&mut OsRng), &uint(answer))
        .map_err(|_| INTERNAL_AUTHENTICATION_FAILED)?;
    if &sigmin >= icc_key.n() {
        return Err(INTERNAL_AUTHENTICATION_FAILED);
    }
    let frame = [sigmin.clone(), icc_key.n() - &sigmin]
        .iter()
        .filter_map(|sig| rsa_encrypt(icc_key, sig).ok())
        .filter_map(|frame| bytes(&frame, icc_key.size()))
        .find(|frame| is_framed(frame))
        .ok_or(INTERNAL_AUTHENTICATION_FAILED)?;

    let hash_start = frame.len() - 1 - SHA1_LENGTH;
    let kicc_start = hash_start - SEED_LENGTH;
    let expected = Sha1::new()
        .chain_update(&frame[1..hash_start])
        .chain_update(challenge)
        .finalize();
    if expected[..] != frame[hash_start..frame.len() - 1] {
        return Err(INTERNAL_AUTHENTICATION_FAILED);
    }
    let mut kicc = [0; SEED_LENGTH];
    kicc.copy_from_slice(&frame[kicc_start..hash_start]);
    Ok(kicc)
}

fn challenge(card: &mut dyn Transport) -> Result<[u8; CHALLENGE_LENGTH], Error> {
    send(card, 0x00, 0x84, 0x00, 0x00, vec![], Some(8))?
        .try_into()
        .map_err(|_| Error::SecureChannel("the card challenge is not 8 bytes long"))
}

/// Sends `min(SIG, N.IFD − SIG)` of `6A ‖ PRND2 ‖ Kifd ‖ SHA-1(PRND2 ‖ Kifd ‖ RND.ICC ‖ SN.ICC) ‖ BC`
/// encrypted for the card, and returns `Kifd`.
fn external_authentication(
    card: &mut dyn Transport,
    keys: &KeySet,
    serial: &[u8],
    rnd_icc: [u8; CHALLENGE_LENGTH],
    icc_key: &RsaPublicKey,
) -> Result<[u8; SEED_LENGTH], Error> {
    let terminal_key = keys.private_key();
    let mut prnd2 = vec![0; terminal_key.size() - 2 - SEED_LENGTH - SHA1_LENGTH];
    OsRng
        .try_fill_bytes(&mut prnd2)
        .map_err(|_| RANDOM_FAILED)?;
    let kifd: [u8; SEED_LENGTH] = random()?;
    let hash = Sha1::new()
        .chain_update(&prnd2)
        .chain_update(kifd)
        .chain_update(rnd_icc)
        .chain_update(serial)
        .finalize();
    let frame = [&[FRAME_START][..], &prnd2, &kifd, &hash, &[FRAME_END]].concat();

    let sig = rsa_decrypt_and_check(&terminal_key, Some(&mut OsRng), &uint(&frame))
        .map_err(|_| EXTERNAL_AUTHENTICATION_FAILED)?;
    let sigmin = (terminal_key.n() - &sig).min(sig);
    let token = rsa_encrypt(icc_key, &sigmin).map_err(|_| EXTERNAL_AUTHENTICATION_FAILED)?;
    let token = bytes(&token, icc_key.size()).ok_or(EXTERNAL_AUTHENTICATION_FAILED)?;
    send(card, 0x00, 0x82, 0x00, 0x00, token, None)
        .map_err(|error| refusal(error, "the card refused the external authentication"))?;
    Ok(kifd)
}

fn random<const N: usize>() -> Result<[u8; N], Error> {
    let mut bytes = [0; N];
    OsRng
        .try_fill_bytes(&mut bytes)
        .map_err(|_| RANDOM_FAILED)?;
    Ok(bytes)
}

fn is_framed(frame: &[u8]) -> bool {
    frame.first() == Some(&FRAME_START) && frame.last() == Some(&FRAME_END)
}

fn uint(bytes: &[u8]) -> BigUint {
    BigUint::from_bytes_be(bytes)
}

/// `value` big-endian, left-padded to `length` bytes; `None` if it does not fit.
fn bytes(value: &BigUint, length: usize) -> Option<Vec<u8>> {
    let value = value.to_bytes_be();
    let mut padded = vec![0; length.checked_sub(value.len())?];
    padded.extend(value);
    Some(padded)
}

fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {
    let length = u8::try_from(value.len()).expect("key references are short");
    [&[tag, length][..], value].concat()
}

/// Sends a plain command and returns its data if the card accepts it.
fn send(
    card: &mut dyn Transport,
    cla: u8,
    ins: u8,
    p1: u8,
    p2: u8,
    data: Vec<u8>,
    le: Option<u16>,
) -> Result<Vec<u8>, Error> {
    card.transmit(&Command {
        cla,
        ins,
        p1,
        p2,
        data,
        le,
    })?
    .into_success()
}

#[cfg(test)]
pub(crate) mod tests;