utility-pki 0.1.0

TLS and certificate profiles of the German energy sector (BDEW AS4, BSI TR-03116-3, BSI TR-02102-2) as Rust data: check sessions, SM-PKI certificates and OpenSSL configurations
Documentation
//! A strict, read-only DER reader for the fixed X.509 schema.
//!
//! It accepts only low tag numbers, definite lengths in their minimal encoding, and
//! nothing after the last element. There is no generic recursion: the caller walks the
//! certificate schema, so nesting depth is bounded by that schema (at most seven levels).
//! It never panics: every byte access goes through `get` or `split_at_checked`.

use core::fmt;

/// Why a certificate could not be read, and where.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParseError {
    offset: usize,
    reason: &'static str,
}

impl ParseError {
    pub(crate) const fn new(offset: usize, reason: &'static str) -> Self {
        Self { offset, reason }
    }

    /// The byte offset in the input where reading failed.
    pub const fn offset(&self) -> usize {
        self.offset
    }

    /// What was wrong, in words.
    pub const fn reason(&self) -> &'static str {
        self.reason
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "not a DER X.509 certificate: {} (at byte {})", self.reason, self.offset)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseError {}

pub(crate) type Result<T> = core::result::Result<T, ParseError>;

pub(crate) const SEQUENCE: u8 = 0x30;
pub(crate) const SET: u8 = 0x31;
pub(crate) const INTEGER: u8 = 0x02;
pub(crate) const BIT_STRING: u8 = 0x03;
pub(crate) const OCTET_STRING: u8 = 0x04;
pub(crate) const NULL: u8 = 0x05;
pub(crate) const OID: u8 = 0x06;
pub(crate) const BOOLEAN: u8 = 0x01;
pub(crate) const UTF8_STRING: u8 = 0x0C;
pub(crate) const PRINTABLE_STRING: u8 = 0x13;
pub(crate) const IA5_STRING: u8 = 0x16;
pub(crate) const UTC_TIME: u8 = 0x17;
pub(crate) const GENERALIZED_TIME: u8 = 0x18;

/// One element: its tag, its content and the offset of the content in the input.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Tlv<'a> {
    pub tag: u8,
    pub content: &'a [u8],
    pub offset: usize,
}

impl<'a> Tlv<'a> {
    pub fn reader(&self) -> Reader<'a> {
        Reader { data: self.content, offset: self.offset }
    }

    pub fn err(&self, reason: &'static str) -> ParseError {
        ParseError::new(self.offset, reason)
    }
}

/// A cursor over the content of one constructed element.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Reader<'a> {
    data: &'a [u8],
    offset: usize,
}

impl<'a> Reader<'a> {
    pub const fn new(data: &'a [u8]) -> Self {
        Self { data, offset: 0 }
    }

    pub const fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    pub fn peek_tag(&self) -> Option<u8> {
        self.data.first().copied()
    }

    fn err(&self, reason: &'static str) -> ParseError {
        ParseError::new(self.offset, reason)
    }

    /// Reads any element.
    pub fn any(&mut self) -> Result<Tlv<'a>> {
        let (&tag, rest) = self.data.split_first().ok_or_else(|| self.err("unexpected end of data"))?;
        if tag & 0x1F == 0x1F {
            return Err(self.err("high tag numbers are not used in X.509"));
        }
        let (&first, rest) = rest.split_first().ok_or_else(|| self.err("missing length"))?;
        let (len, rest) = match first {
            0..=0x7F => (usize::from(first), rest),
            0x80 => return Err(self.err("indefinite length is not DER")),
            0x81..=0x84 => {
                let n = usize::from(first & 0x7F);
                let (bytes, rest) = rest.split_at_checked(n).ok_or_else(|| self.err("truncated length"))?;
                let mut len = 0usize;
                for &b in bytes {
                    len = (len << 8) | usize::from(b);
                }
                let minimal = bytes.first().is_some_and(|&b| b != 0)
                    && len >= 0x80
                    && (n == 1 || len >= 1 << (8 * (n - 1)));
                if !minimal {
                    return Err(self.err("length not in its shortest form"));
                }
                (len, rest)
            }
            _ => return Err(self.err("length too large")),
        };
        let header = self.data.len() - rest.len();
        let (content, rest) =
            rest.split_at_checked(len).ok_or_else(|| self.err("length beyond the end of data"))?;
        let tlv = Tlv { tag, content, offset: self.offset + header };
        self.offset += header + len;
        self.data = rest;
        Ok(tlv)
    }

    /// Reads an element that must have this tag.
    pub fn read(&mut self, tag: u8, what: &'static str) -> Result<Tlv<'a>> {
        if self.peek_tag() != Some(tag) {
            return Err(self.err(what));
        }
        self.any()
    }

    /// Reads an element if the next one has this tag.
    pub fn optional(&mut self, tag: u8) -> Result<Option<Tlv<'a>>> {
        if self.peek_tag() == Some(tag) { self.any().map(Some) } else { Ok(None) }
    }

    /// Fails unless everything has been read.
    pub fn finish(&self, what: &'static str) -> Result<()> {
        if self.is_empty() { Ok(()) } else { Err(self.err(what)) }
    }
}

/// The content of a DER BOOLEAN; DER allows only 0x00 and 0xFF.
pub(crate) fn boolean(tlv: &Tlv<'_>) -> Result<bool> {
    match tlv.content {
        [0xFF] => Ok(true),
        [0x00] => Ok(false),
        _ => Err(tlv.err("BOOLEAN is not DER")),
    }
}

/// Checks that an INTEGER is minimally encoded and returns its content.
pub(crate) fn integer<'a>(tlv: &Tlv<'a>) -> Result<&'a [u8]> {
    match tlv.content {
        [] => Err(tlv.err("empty INTEGER")),
        [0x00, next, ..] if next & 0x80 == 0 => Err(tlv.err("INTEGER not minimal")),
        [0xFF, next, ..] if next & 0x80 != 0 => Err(tlv.err("INTEGER not minimal")),
        c => Ok(c),
    }
}

/// Checks that an OBJECT IDENTIFIER is well formed and returns its content.
pub(crate) fn oid<'a>(tlv: &Tlv<'a>) -> Result<&'a [u8]> {
    let c = tlv.content;
    // Every arc ends with a byte < 0x80 and does not start with 0x80 (non-minimal).
    let well_formed = c.last().is_some_and(|&b| b & 0x80 == 0)
        && c.first().is_some_and(|&b| b != 0x80)
        && c.iter().zip(c.iter().skip(1)).all(|(&p, &n)| !(p & 0x80 == 0 && n == 0x80));
    if well_formed { Ok(c) } else { Err(tlv.err("malformed OBJECT IDENTIFIER")) }
}

/// The content of a BIT STRING without its unused-bits byte, and that count.
pub(crate) fn bit_string<'a>(tlv: &Tlv<'a>) -> Result<(&'a [u8], u8)> {
    let (&unused, bits) = tlv.content.split_first().ok_or_else(|| tlv.err("empty BIT STRING"))?;
    let last = bits.last().copied().unwrap_or(0);
    // DER: at most 7 unused bits, none without data, and the unused bits are zero.
    if unused > 7 || (bits.is_empty() && unused != 0) || last & ((1u8 << unused) - 1) != 0 {
        return Err(tlv.err("BIT STRING is not DER"));
    }
    Ok((bits, unused))
}

/// A directory string attribute (CN, O, OU): UTF8String, PrintableString or IA5String.
pub(crate) fn string<'a>(tlv: &Tlv<'a>) -> Result<&'a str> {
    let s = core::str::from_utf8(tlv.content).map_err(|_| tlv.err("string is not valid UTF-8"))?;
    let ok = match tlv.tag {
        UTF8_STRING => true,
        PRINTABLE_STRING => s.bytes().all(|b| b.is_ascii_alphanumeric() || b" '()+,-./:=?".contains(&b)),
        IA5_STRING => s.is_ascii(),
        _ => false,
    };
    if ok { Ok(s) } else { Err(tlv.err("attribute string type or characters not allowed")) }
}

/// An IA5String GeneralName (rfc822Name, dNSName, uniformResourceIdentifier).
pub(crate) fn ia5<'a>(tlv: &Tlv<'a>) -> Result<&'a str> {
    core::str::from_utf8(tlv.content)
        .ok()
        .filter(|s| s.is_ascii())
        .ok_or_else(|| tlv.err("GeneralName is not an IA5String"))
}

/// Seconds since 1970-01-01T00:00:00Z of a DER UTCTime or GeneralizedTime (Zulu, with
/// seconds, as RFC 5280 ยง4.1.2.5 requires).
pub(crate) fn time(tlv: &Tlv<'_>) -> Result<i64> {
    let bad = || tlv.err("time is not DER (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)");
    let (year, rest) = match (tlv.tag, tlv.content.len()) {
        (UTC_TIME, 13) => {
            let (yy, rest) = tlv.content.split_at_checked(2).ok_or_else(bad)?;
            let yy = digits(yy).ok_or_else(bad)?;
            // RFC 5280 ยง4.1.2.5.1: YY >= 50 is 19YY, otherwise 20YY.
            (if yy >= 50 { 1900 + yy } else { 2000 + yy }, rest)
        }
        (GENERALIZED_TIME, 15) => {
            let (yyyy, rest) = tlv.content.split_at_checked(4).ok_or_else(bad)?;
            let year = digits(yyyy).ok_or_else(bad)?;
            // RFC 5280 ยง4.1.2.5: dates through 2049 MUST be UTCTime.
            if year < 2050 {
                return Err(tlv.err("GeneralizedTime before 2050 (RFC 5280 requires UTCTime)"));
            }
            (year, rest)
        }
        _ => return Err(bad()),
    };
    let [m0, m1, d0, d1, h0, h1, i0, i1, s0, s1, b'Z'] = rest else { return Err(bad()) };
    let month = digits(&[*m0, *m1]).ok_or_else(bad)?;
    let day = digits(&[*d0, *d1]).ok_or_else(bad)?;
    let hour = digits(&[*h0, *h1]).ok_or_else(bad)?;
    let minute = digits(&[*i0, *i1]).ok_or_else(bad)?;
    let second = digits(&[*s0, *s1]).ok_or_else(bad)?;
    if !(1..=12).contains(&month)
        || day == 0
        || day > days_in_month(year, month)
        || hour > 23
        || minute > 59
        || second > 59
    {
        return Err(bad());
    }
    let days = days_from_civil(year, month, day);
    Ok(days * 86_400 + i64::from(hour * 3600 + minute * 60 + second))
}

fn digits(b: &[u8]) -> Option<u32> {
    b.iter().try_fold(0u32, |acc, &c| c.is_ascii_digit().then(|| acc * 10 + u32::from(c - b'0')))
}

const fn days_in_month(year: u32, month: u32) -> u32 {
    match month {
        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Days since 1970-01-01 (Howard Hinnant's `days_from_civil`).
fn days_from_civil(year: u32, month: u32, day: u32) -> i64 {
    let y = i64::from(year) - i64::from(month <= 2);
    let era = y.div_euclid(400);
    let yoe = y - era * 400;
    let m = i64::from(month);
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tlv(tag: u8, content: &[u8]) -> Tlv<'_> {
        Tlv { tag, content, offset: 0 }
    }

    #[test]
    fn lengths_must_be_minimal_and_definite() {
        assert!(Reader::new(&[0x30, 0x80, 0x00, 0x00]).any().is_err());
        assert!(Reader::new(&[0x30, 0x81, 0x01, 0x00]).any().is_err());
        assert!(Reader::new(&[0x30, 0x82, 0x00, 0x81]).any().is_err());
        assert!(Reader::new(&[0x30, 0x05, 0x00]).any().is_err());
        let ok = [0x04, 0x81, 0x80];
        let mut long = ok.to_vec();
        long.extend([0u8; 0x80]);
        assert!(Reader::new(&long).any().is_ok());
    }

    #[test]
    fn times() {
        assert_eq!(time(&tlv(UTC_TIME, b"700101000000Z")).unwrap(), 0);
        assert_eq!(time(&tlv(UTC_TIME, b"000301000000Z")).unwrap(), 951_868_800);
        assert_eq!(time(&tlv(GENERALIZED_TIME, b"20500101000000Z")).unwrap(), 2_524_608_000);
        assert!(time(&tlv(UTC_TIME, b"700230000000Z")).is_err());
        assert!(time(&tlv(UTC_TIME, b"7001010000Z")).is_err());
        assert!(time(&tlv(UTC_TIME, b"700101000000+0100")).is_err());
        assert!(time(&tlv(GENERALIZED_TIME, b"20491231235959Z")).is_err());
    }

    #[test]
    fn der_primitives() {
        assert!(boolean(&tlv(BOOLEAN, &[0x01])).is_err());
        assert!(integer(&tlv(INTEGER, &[0x00, 0x01])).is_err());
        assert!(integer(&tlv(INTEGER, &[0x00, 0x80])).is_ok());
        assert!(oid(&tlv(OID, &[0x55, 0x80, 0x01])).is_err());
        assert!(bit_string(&tlv(BIT_STRING, &[0x07, 0x81])).is_err());
        assert_eq!(bit_string(&tlv(BIT_STRING, &[0x07, 0x80])).unwrap(), (&[0x80u8][..], 7));
        assert!(string(&tlv(PRINTABLE_STRING, b"a*b")).is_err());
        assert!(string(&tlv(0x1E, b"ab")).is_err());
        assert!(string(&tlv(0x81, b"ab")).is_err());
        assert!(ia5(&tlv(0x82, "รค".as_bytes())).is_err());
    }
}