Skip to main content

rust_web_server/core/
x509.rs

1//! X.509 certificate validity (notBefore/notAfter) and the RFC 9773 ARI
2//! certificate id, read with a minimal DER walker — shared by ACME renewal
3//! and the TLS certificate-expiry metric, so it isn't behind a feature.
4//! Certificate bytes may come from a CA or a file: every length is checked,
5//! nothing panics on malformed input.
6
7// ── base64url ─────────────────────────────────────────────────────────────────
8
9pub fn base64url(data: &[u8]) -> String {
10    const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
11    let mut out = Vec::with_capacity((data.len() + 2) / 3 * 4);
12    for chunk in data.chunks(3) {
13        let b0 = chunk[0] as usize;
14        let b1 = if chunk.len() > 1 { chunk[1] as usize } else { 0 };
15        let b2 = if chunk.len() > 2 { chunk[2] as usize } else { 0 };
16        out.push(ALPHA[b0 >> 2]);
17        out.push(ALPHA[((b0 & 3) << 4) | (b1 >> 4)]);
18        if chunk.len() > 1 { out.push(ALPHA[((b1 & 0xf) << 2) | (b2 >> 6)]); }
19        if chunk.len() > 2 { out.push(ALPHA[b2 & 0x3f]); }
20    }
21    String::from_utf8(out).unwrap()
22}
23
24// ── Certificate expiry ────────────────────────────────────────────────────────
25
26/// What renewal needs from the leaf certificate: its validity window (Unix
27/// seconds) and its ACME Renewal Information certificate identifier
28/// (RFC 9773 §4.1), when it has an Authority Key Identifier.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct CertInfo {
31    pub not_before: i64,
32    pub not_after: i64,
33    /// `base64url(AKI keyIdentifier) "." base64url(serial)`; `None` without
34    /// an Authority Key Identifier extension.
35    pub cert_id: Option<String>,
36}
37
38/// [`CertInfo`] of the first certificate in the PEM file at `cert_path`;
39/// `None` when it can't be read or parsed.
40/// [`CertInfo`] of the first certificate in PEM text.
41pub fn cert_info_from_pem(pem: &[u8]) -> Option<CertInfo> {
42    cert_info_from_der(&pem_to_first_cert_der(std::str::from_utf8(pem).ok()?)?)
43}
44
45pub fn read_cert_info(cert_path: &str) -> Option<CertInfo> {
46    let pem = std::fs::read_to_string(cert_path).ok()?;
47    cert_info_from_der(&pem_to_first_cert_der(&pem)?)
48}
49
50/// [`CertInfo`] from a DER certificate. CA-supplied bytes: every length is
51/// checked by `read_tlv`, nothing panics on malformed input.
52pub fn cert_info_from_der(cert_der: &[u8]) -> Option<CertInfo> {
53    let (_, cert_body, _) = read_tlv(cert_der, 0)?;
54    let (_, tbs, _) = read_tlv(cert_body, 0)?;
55    let mut pos = 0;
56    if tbs.get(pos) == Some(&0xa0) {
57        pos = read_tlv(tbs, pos)?.2;
58    }
59    let (serial_tag, serial, next) = read_tlv(tbs, pos)?;
60    if serial_tag != 0x02 || serial.is_empty() {
61        return None;
62    }
63    pos = skip_tlvs(tbs, next, 2)?; // signature, issuer
64    let (_, validity, next) = read_tlv(tbs, pos)?;
65    let (nb_tag, nb_val, nb_end) = read_tlv(validity, 0)?;
66    let (na_tag, na_val, _) = read_tlv(validity, nb_end)?;
67    let is_time = |tag: u8| tag == 0x17 || tag == 0x18;
68    if !is_time(nb_tag) || !is_time(na_tag) {
69        return None;
70    }
71    let not_before = parse_asn1_time(nb_val)?;
72    let not_after = parse_asn1_time(na_val)?;
73    pos = skip_tlvs(tbs, next, 2)?; // subject, subjectPublicKeyInfo
74
75    // Optional issuerUniqueID [1], subjectUniqueID [2], then extensions [3].
76    let mut aki: Option<&[u8]> = None;
77    while pos < tbs.len() {
78        let (tag, value, next) = read_tlv(tbs, pos)?;
79        if tag == 0xa3 {
80            aki = authority_key_identifier(value);
81        }
82        pos = next;
83    }
84    let cert_id = aki.map(|key_id| format!("{}.{}", base64url(key_id), base64url(serial)));
85    Some(CertInfo { not_before, not_after, cert_id })
86}
87
88/// The keyIdentifier of the Authority Key Identifier extension
89/// (OID 2.5.29.35) in an `[3] EXPLICIT Extensions` value.
90fn authority_key_identifier(explicit: &[u8]) -> Option<&[u8]> {
91    const AKI_OID: &[u8] = &[0x55, 0x1d, 0x23];
92    let (_, extensions, _) = read_tlv(explicit, 0)?;
93    let mut pos = 0;
94    while pos < extensions.len() {
95        let (_, extension, next) = read_tlv(extensions, pos)?;
96        pos = next;
97        let (oid_tag, oid, mut inner) = read_tlv(extension, 0)?;
98        if oid_tag != 0x06 || oid != AKI_OID {
99            continue;
100        }
101        let (mut tag, mut value, mut after) = read_tlv(extension, inner)?;
102        if tag == 0x01 {
103            // critical BOOLEAN
104            inner = after;
105            (tag, value, after) = read_tlv(extension, inner)?;
106        }
107        let _ = after;
108        if tag != 0x04 {
109            return None;
110        }
111        // OCTET STRING → AuthorityKeyIdentifier SEQUENCE → [0] IMPLICIT keyIdentifier
112        let (_, aki, _) = read_tlv(value, 0)?;
113        let (key_tag, key_id, _) = read_tlv(aki, 0)?;
114        return (key_tag == 0x80 && !key_id.is_empty()).then_some(key_id);
115    }
116    None
117}
118
119fn pem_to_first_cert_der(pem: &str) -> Option<Vec<u8>> {
120    let start = pem.find("-----BEGIN CERTIFICATE-----")?;
121    let after = &pem[start + 27..];
122    let end = after.find("-----END CERTIFICATE-----")?;
123    let b64: String = after[..end].chars().filter(|c| !c.is_whitespace()).collect();
124    base64_decode_std(&b64)
125}
126
127// ── minimal DER TLV parser ────────────────────────────────────────────────────
128
129fn read_tlv(data: &[u8], pos: usize) -> Option<(u8, &[u8], usize)> {
130    if pos >= data.len() { return None; }
131    let tag = data[pos];
132    let mut p = pos + 1;
133    let len = {
134        let b = *data.get(p)?; p += 1;
135        if b < 0x80 { b as usize } else {
136            // At most 4 length bytes: more would overflow the shift (a
137            // panic in debug builds) and no certificate is that large.
138            let n = (b & 0x7f) as usize;
139            if n == 0 || n > 4 { return None; }
140            let mut l = 0usize;
141            for _ in 0..n { l = (l << 8) | *data.get(p)? as usize; p += 1; }
142            l
143        }
144    };
145    let end = p.checked_add(len)?;
146    if end > data.len() { return None; }
147    Some((tag, &data[p..end], end))
148}
149
150fn skip_tlvs(data: &[u8], mut pos: usize, count: usize) -> Option<usize> {
151    for _ in 0..count {
152        let (_, _, next) = read_tlv(data, pos)?;
153        pos = next;
154    }
155    Some(pos)
156}
157
158fn parse_asn1_time(t: &[u8]) -> Option<i64> {
159    // Digits then `Z`: anything else (and any non-ASCII byte, which the
160    // slicing below would split) is not a time rws can read.
161    if t.len() < 2 || !t[..t.len() - 1].iter().all(u8::is_ascii_digit) {
162        return None;
163    }
164    let s = std::str::from_utf8(t).ok()?;
165    if !s.ends_with('Z') { return None; }
166    let s = &s[..s.len() - 1]; // strip 'Z'
167    let (year, rest) = if s.len() == 12 {
168        let yy: i64 = s[..2].parse().ok()?;
169        let year = if yy < 50 { 2000 + yy } else { 1900 + yy };
170        (year, &s[2..])
171    } else if s.len() == 14 {
172        (s[..4].parse().ok()?, &s[4..])
173    } else {
174        return None;
175    };
176    let mo: i64 = rest[0..2].parse().ok()?;
177    let da: i64 = rest[2..4].parse().ok()?;
178    let hr: i64 = rest[4..6].parse().ok()?;
179    let mi: i64 = rest[6..8].parse().ok()?;
180    let se: i64 = rest[8..10].parse().ok()?;
181    let days = days_since_epoch(year, mo, da)?;
182    Some(days * 86400 + hr * 3600 + mi * 60 + se)
183}
184
185pub fn days_since_epoch(year: i64, month: i64, day: i64) -> Option<i64> {
186    // https://howardhinnant.github.io/date_algorithms.html "days_from_civil"
187    let y = if month <= 2 { year - 1 } else { year };
188    let m = if month <= 2 { month + 9 } else { month - 3 };
189    let era = y.div_euclid(400);
190    let yoe = y - era * 400;
191    let doy = (153 * m + 2) / 5 + (day - 1);
192    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
193    Some(era * 146097 + doe - 719468)
194}
195
196// ── standard base64 decoder (no padding required) ────────────────────────────
197
198pub fn base64_decode_std(s: &str) -> Option<Vec<u8>> {
199    let digits: Vec<u8> = s.bytes().filter_map(|b| match b {
200        b'A'..=b'Z' => Some(b - b'A'),
201        b'a'..=b'z' => Some(b - b'a' + 26),
202        b'0'..=b'9' => Some(b - b'0' + 52),
203        b'+' | b'-' => Some(62),
204        b'/' | b'_' => Some(63),
205        b'=' => None,
206        _ => None,
207    }).collect();
208    let mut out = Vec::with_capacity(digits.len() * 3 / 4);
209    for chunk in digits.chunks(4) {
210        let v = chunk.iter().enumerate()
211            .fold(0u32, |acc, (i, &d)| acc | ((d as u32) << (18 - i * 6)));
212        if chunk.len() >= 2 { out.push((v >> 16) as u8); }
213        if chunk.len() >= 3 { out.push((v >> 8) as u8); }
214        if chunk.len() >= 4 { out.push(v as u8); }
215    }
216    Some(out)
217}