rdnie 0.3.0

Spanish electronic ID card (DNIe) driver over PC/SC: CWA-14890 secure channel, certificates, PIN retry counter and signing
Documentation
// Derived from JMulticard: see LICENSE.jmulticard.md.

//! 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,
    channel::{CommandChannel, PlainChannel},
    files::{self, Location},
    key_sets::{CA_PUBLIC_KEY_REFERENCE, ComponentRoots, ICC_PRIVATE_KEY_REFERENCE, KeySet},
    secure_messaging::{SecureChannel, 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 over `card`.
pub(crate) fn open<'a>(
    mut card: PlainChannel<'a>,
    keys: &KeySet,
    roots: &ComponentRoots,
) -> Result<SecureChannel<'a>, Error> {
    let state = handshake(&mut card, keys, roots)?;
    Ok(SecureChannel::new(state, card))
}

/// Authenticates through `outer` with `keys` and returns the agreed channel over the card beneath.
pub(crate) fn open_inside<'a>(
    outer: SecureChannel<'a>,
    keys: &KeySet,
    roots: &ComponentRoots,
) -> Result<SecureChannel<'a>, Error> {
    outer.open_inside(|channel| handshake(channel, keys, roots))
}

fn handshake(
    card: &mut dyn CommandChannel,
    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`, as the card gives it.
pub(crate) fn chip_serial(card: &mut dyn CommandChannel) -> Result<Vec<u8>, Error> {
    send(card, 0x90, 0xB8, 0x00, 0x00, vec![], Some(7))
}

/// The chip serial left-padded to 8 bytes.
fn padded_serial(card: &mut dyn CommandChannel) -> Result<Vec<u8>, Error> {
    let serial = chip_serial(card)?;
    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 CommandChannel,
    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 CommandChannel,
    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_generation(
        crate::key_sets::KeyGeneration::Second,
        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 CommandChannel, 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 CommandChannel,
    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 CommandChannel, 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 CommandChannel,
    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 CommandChannel) -> 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 CommandChannel,
    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 CommandChannel,
    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;