use std::fmt;
use der::{Decode, Reader, SliceReader};
use flate2::{Decompress, FlushDecompress, Status};
use crate::{
Error, Transport,
files::{self, Location},
pkcs15,
};
const CDF: &[u8] = &[0x50, 0x15, 0x60, 0x04];
const PRKDF: &[u8] = &[0x50, 0x15, 0x60, 0x01];
const COMPRESSION_HEADER: usize = 8;
const MAX_INFLATED: u64 = 16 * 1024;
pub const INTERMEDIATE_CA_LABEL: &str = "CertCAIntermediaDGP";
pub const SIGNATURE_LABEL: &str = "CertFirmaDigital";
#[non_exhaustive]
pub struct Certificate {
pub der: Vec<u8>,
pub label: String,
pub key: KeyReference,
}
#[derive(Clone, PartialEq, Eq)]
pub struct KeyReference {
pub(crate) id: Vec<u8>,
pub(crate) file: [u8; 2],
}
impl fmt::Debug for Certificate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Certificate").finish_non_exhaustive()
}
}
impl fmt::Debug for KeyReference {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyReference").finish_non_exhaustive()
}
}
pub(crate) struct Loaded {
pub(crate) der: Vec<u8>,
pub(crate) label: String,
pub(crate) key: Option<KeyReference>,
}
impl Loaded {
pub(crate) fn keyed(&self) -> Option<Certificate> {
Some(Certificate {
der: self.der.clone(),
label: self.label.clone(),
key: self.key.clone()?,
})
}
}
pub(crate) fn load(card: &mut dyn Transport) -> Result<Vec<Loaded>, Error> {
let listed = pkcs15::entries(&files::read(card, &location(CDF)?)?, true)?;
let mut ders = Vec::with_capacity(listed.len());
for entry in &listed {
ders.push(stored_x509(files::read(card, &location(&entry.path)?)?)?);
}
let keys = pkcs15::entries(&files::read(card, &location(PRKDF)?)?, false)?;
let mut certificates = Vec::with_capacity(ders.len());
for (entry, der) in listed.into_iter().zip(ders) {
let key = match keys.iter().find(|key| key.id == entry.id) {
Some(key) => {
let file = location(&key.path)?
.last_file()
.ok_or(Error::MalformedPkcs15)?;
Some(KeyReference { id: entry.id, file })
}
None => None,
};
certificates.push(Loaded {
der,
label: entry.label,
key,
});
}
Ok(certificates)
}
fn location(path: &[u8]) -> Result<Location, Error> {
Location::new(path).ok_or(Error::MalformedPkcs15)
}
pub(crate) fn stored_x509(stored: Vec<u8>) -> Result<Vec<u8>, Error> {
x509(&decompressed(stored)).ok_or(Error::MalformedPkcs15)
}
fn x509(stored: &[u8]) -> Option<Vec<u8>> {
let der = SliceReader::new(stored).ok()?.tlv_bytes().ok()?;
x509_cert::Certificate::from_der(der).ok()?;
Some(der.to_vec())
}
fn decompressed(stored: Vec<u8>) -> Vec<u8> {
inflate(&stored).unwrap_or(stored)
}
fn inflate(stored: &[u8]) -> Option<Vec<u8>> {
let stream = stored.get(COMPRESSION_HEADER..)?;
let mut inflater = Decompress::new(true);
let mut der = Vec::new();
loop {
der.reserve(1024);
let consumed = usize::try_from(inflater.total_in()).ok()?;
let produced = inflater.total_out();
let status = inflater
.decompress_vec(&stream[consumed..], &mut der, FlushDecompress::None)
.ok()?;
if inflater.total_out() > MAX_INFLATED {
return None;
}
if status == Status::StreamEnd {
return Some(der);
}
if inflater.total_out() == produced {
return None;
}
}
}
#[cfg(test)]
mod tests;