Skip to main content

x509/
lib.rs

1// x509 -- certificates (RFC 5280) for all of JFLib: netio's TLS and https, netpkt's TLS core and
2// simulators.  A program's own private PKI (Ed25519, RFC 8410; built and signed here) and the
3// public web PKI (RSA and P-256 / P-384 keys; RSA PKCS #1 v1.5 / PSS and ECDSA signatures with
4// SHA-256 / 384 / 512), parsed strictly; no I/O, no clock (the caller passes the time)
5//
6//   der                                     the DER reader and writer certificates need
7//   IpAddr                                  addresses in names (octets, parse, RFC 5952 text)
8//   Cert::parse(der) -> Option<Cert>        subject / issuer, validity, key, CA flag, names,
9//                                           key and extended key usage, name constraints,
10//                                           unknown critical extensions noticed
11//   cert.fingerprint() -> SHA-256 (hex)     fingerprint_bytes(), fingerprint_text() (colons)
12//   cert.signed_by(&issuer) -> bool         self_signed(), names(host), name_list(), bytes()
13//   cert.verify(alg, data, sig)             a signature made with the certificate's key
14//   verify_chain(&[leaf, ...], &anchors, now, name, usage) -> Result<(), String>   builds a
15//                                           path through the given intermediates to an anchor;
16//                                           verify_path: the same, and that path (to the anchor)
17//   CertBuilder { .. }.sign(&issuer_cert_or_self, &issuer_key) -> DER     (Ed25519)
18//   CertBuilder { spki, .. }.sign_key(issuer, &PrivateKey, extra) -> DER   any key, signed by any
19//   PrivateKey: Ed25519, ECDSA (P-256 / P-384), RSA; PKCS #8 / SEC 1 / PKCS #1 (key.rs)
20//   ocsp::check(der, &cert, &issuer, now)   an OCSP response (RFC 6960); request, CertId,
21//                                           ResponseBuilder for a private CA's responder (ocsp.rs)
22//   CsrBuilder { dns, .. }.sign(&key), Csr::parse   certificate requests (PKCS #10, csr.rs)
23//
24// Not checked: CRLs, certificate policies (OCSP: the ocsp module; a certificate's responders,
25// caIssuers and TLS features are read).  Name constraints are processed
26// for DNS names, IP addresses, e-mail addresses (rfc822Name), URIs (their host) and directory
27// names (a byte-wise prefix of the subject's RDNs); a CA that constrains another form refuses
28// every certificate below it that has a name of that form (RFC 5280 4.2.1.10).  They apply to
29// the leaf and to the intermediates below the CA, self-issued ones excepted (6.1.3 (b)).
30
31#![no_std]
32#![forbid(unsafe_code)]
33
34extern crate alloc;
35
36pub mod csr;
37pub mod der;
38mod ip;
39mod key;
40pub mod ocsp;
41
42pub use csr::{Csr, CsrBuilder};
43pub use ip::IpAddr;
44pub use key::{spki_of, PrivateKey};
45
46use alloc::format;
47use alloc::string::String;
48use alloc::vec::Vec;
49
50use crypto::ecdsa::Curve;
51use crypto::ed25519::Keypair;
52use crypto::HashAlg;
53
54use crate::der::Der;
55
56pub const OID_ED25519: &[u64] = &[1, 3, 101, 112];
57const OID_CN: &[u64] = &[2, 5, 4, 3];
58const OID_O: &[u64] = &[2, 5, 4, 10];
59const OID_BASIC: &[u64] = &[2, 5, 29, 19];
60const OID_KEY_USAGE: &[u64] = &[2, 5, 29, 15];
61const OID_EKU: &[u64] = &[2, 5, 29, 37];
62const OID_SAN: &[u64] = &[2, 5, 29, 17];
63const OID_SKI: &[u64] = &[2, 5, 29, 14];
64const OID_AKI: &[u64] = &[2, 5, 29, 35];
65const OID_NAME_CONSTRAINTS: &[u64] = &[2, 5, 29, 30];
66const OID_POLICIES: &[u64] = &[2, 5, 29, 32];
67const OID_POLICY_CONSTRAINTS: &[u64] = &[2, 5, 29, 36];
68const OID_INHIBIT_ANY: &[u64] = &[2, 5, 29, 54];
69const OID_RSA: &[u64] = &[1, 2, 840, 113549, 1, 1, 1];
70const OID_RSA_PSS: &[u64] = &[1, 2, 840, 113549, 1, 1, 10];
71const OID_MGF1: &[u64] = &[1, 2, 840, 113549, 1, 1, 8];
72const OID_RSA_SHA256: &[u64] = &[1, 2, 840, 113549, 1, 1, 11];
73const OID_RSA_SHA384: &[u64] = &[1, 2, 840, 113549, 1, 1, 12];
74const OID_RSA_SHA512: &[u64] = &[1, 2, 840, 113549, 1, 1, 13];
75const OID_EC: &[u64] = &[1, 2, 840, 10045, 2, 1];
76const OID_P256: &[u64] = &[1, 2, 840, 10045, 3, 1, 7];
77const OID_P384: &[u64] = &[1, 3, 132, 0, 34];
78const OID_ECDSA_SHA256: &[u64] = &[1, 2, 840, 10045, 4, 3, 2];
79const OID_ECDSA_SHA384: &[u64] = &[1, 2, 840, 10045, 4, 3, 3];
80const OID_ECDSA_SHA512: &[u64] = &[1, 2, 840, 10045, 4, 3, 4];
81const OID_SHA256: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 2, 1];
82const OID_SHA384: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 2, 2];
83const OID_SHA512: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 2, 3];
84const OID_SERVER_AUTH: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 3, 1];
85const OID_CLIENT_AUTH: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 3, 2];
86const OID_ANY_EKU: &[u64] = &[2, 5, 29, 37, 0];
87const OID_OCSP_SIGNING: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 3, 9];
88const OID_AIA: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 1, 1];
89const OID_AD_OCSP: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 48, 1];
90const OID_AD_CA_ISSUERS: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 48, 2];
91const OID_TLS_FEATURE: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 1, 24];
92const OID_OCSP_NOCHECK: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 48, 1, 5];
93
94/// the TLS feature of a certificate that must come with a stapled OCSP response (RFC 7633:
95/// status_request)
96pub const TLS_FEATURE_STATUS_REQUEST: u16 = 5;
97
98/// key usage bits as they appear in the first byte
99pub const KU_DIGITAL_SIGNATURE: u8 = 0x80;
100pub const KU_KEY_CERT_SIGN: u8 = 0x04;
101pub const KU_CRL_SIGN: u8 = 0x02;
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum Usage {
106    Server,
107    Client,
108}
109
110/// a public key
111#[derive(Clone, Debug, Default, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum PubKey {
114    /// a key type this code does not use
115    #[default]
116    Other,
117    Ed25519([u8; 32]),
118    /// modulus and exponent, big-endian without leading zero bytes
119    Rsa { n: Vec<u8>, e: Vec<u8> },
120    /// an uncompressed point (04 || x || y)
121    Ec { curve: Curve, point: Vec<u8> },
122}
123
124/// a signature algorithm (of certificates and of TLS handshakes)
125#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum SigAlg {
128    #[default]
129    Unknown,
130    Ed25519,
131    RsaPkcs1(HashAlg),
132    /// salt length None: any (TLS fixes it to the hash length)
133    RsaPss(HashAlg, Option<usize>),
134    Ecdsa(HashAlg),
135}
136
137/// the name constraints of a CA
138#[derive(Clone, Debug, Default, PartialEq, Eq)]
139pub struct NameConstraints {
140    pub permitted_dns: Vec<String>,
141    pub excluded_dns: Vec<String>,
142    /// address and mask (4 + 4 or 16 + 16 bytes)
143    pub permitted_ip: Vec<Vec<u8>>,
144    pub excluded_ip: Vec<Vec<u8>>,
145    /// rfc822Name subtrees, lower case: a mailbox ("a@example.com"), all mailboxes of a host
146    /// ("example.com") or of the subdomains of a domain (".example.com")
147    pub permitted_email: Vec<String>,
148    pub excluded_email: Vec<String>,
149    /// uniformResourceIdentifier subtrees, lower case: the URI's host ("example.com") or the
150    /// subdomains of a domain (".example.com")
151    pub permitted_uri: Vec<String>,
152    pub excluded_uri: Vec<String>,
153    /// directoryName subtrees (the DER of a Name): the subject begins with its RDNs
154    pub permitted_dn: Vec<Vec<u8>>,
155    pub excluded_dn: Vec<Vec<u8>>,
156    /// the GeneralName tags of constrained forms not processed here (otherName 0xa0,
157    /// x400Address 0xa3, ediPartyName 0xa5, registeredID 0x88)
158    pub other_forms: Vec<u8>,
159}
160
161#[derive(Clone, Debug, Default, PartialEq, Eq)]
162pub struct Cert {
163    pub der: Vec<u8>,
164    pub tbs: Vec<u8>,
165    pub serial: Vec<u8>,
166    /// the raw DER of the issuer and subject names (compared byte for byte)
167    pub issuer: Vec<u8>,
168    pub subject: Vec<u8>,
169    pub subject_cn: String,
170    /// the subject's organization, the issuer's common name and organization (for dialogs)
171    pub subject_org: String,
172    pub issuer_cn: String,
173    pub issuer_org: String,
174    pub not_before: i64,
175    pub not_after: i64,
176    /// Ed25519 public key (empty for other key types)
177    pub public_key: Vec<u8>,
178    pub key: PubKey,
179    pub ed25519_signed: bool,
180    pub sig_alg: SigAlg,
181    pub signature: Vec<u8>,
182    /// 1 or 3
183    pub version: u8,
184    pub name_constraints: Option<NameConstraints>,
185    pub is_ca: bool,
186    pub path_len: Option<u64>,
187    pub key_usage: Option<u8>,
188    pub eku: Vec<Vec<u8>>,
189    pub dns: Vec<String>,
190    pub ips: Vec<IpAddr>,
191    /// rfc822Name entries of the subject alternative name and emailAddress attributes of the
192    /// subject (lower case): what e-mail name constraints apply to
193    pub emails: Vec<String>,
194    /// uniformResourceIdentifier entries of the subject alternative name
195    pub uris: Vec<String>,
196    /// directoryName entries of the subject alternative name (the DER of each Name)
197    pub dirs: Vec<Vec<u8>>,
198    /// the tags of subject alternative names of other forms (otherName 0xa0, x400Address 0xa3,
199    /// ediPartyName 0xa5, registeredID 0x88)
200    pub other_names: Vec<u8>,
201    pub ski: Vec<u8>,
202    /// the keyIdentifier of the authority key identifier (empty without one): which key of the
203    /// issuer signed it (ACME's renewal information names a certificate by it)
204    pub aki: Vec<u8>,
205    /// the OCSP responders of the authority information access (URIs, RFC 5280 4.2.2.1)
206    pub ocsp_urls: Vec<String>,
207    /// where the issuer's certificate is (caIssuers URIs of the authority information access)
208    pub ca_issuers: Vec<String>,
209    /// the TLS features the certificate demands (RFC 7633): TLS_FEATURE_STATUS_REQUEST is
210    /// "must staple", a TLS client that asks for a stapled OCSP response refuses it without one
211    /// (netio: Revocation::Stapled or Required with Trust::Anchors, System or Custom; with
212    /// Revocation::Off, Trust::Pinned or Trust::Any it asks for none and does not look)
213    pub tls_features: Vec<u16>,
214    /// id-pkix-ocsp-nocheck (RFC 6960 4.2.2.2.1): an OCSP responder's certificate that is not
215    /// checked for revocation itself
216    pub ocsp_nocheck: bool,
217    /// a critical extension this code does not understand (such a certificate is rejected)
218    pub unknown_critical: bool,
219}
220
221fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
222    let y = if m <= 2 { y - 1 } else { y };
223    let era = y.div_euclid(400);
224    let yoe = y - era * 400;
225    let mp = (m + 9) % 12;
226    let doy = (153 * mp + 2) / 5 + d - 1;
227    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
228    era * 146_097 + doe - 719_468
229}
230
231pub(crate) fn civil_from_days(z: i64) -> (i64, i64, i64) {
232    let z = z + 719_468;
233    let era = z.div_euclid(146_097);
234    let doe = z - era * 146_097;
235    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
236    let y = yoe + era * 400;
237    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
238    let mp = (5 * doy + 2) / 153;
239    let d = doy - (153 * mp + 2) / 5 + 1;
240    let m = if mp < 10 { mp + 3 } else { mp - 9 };
241    (if m <= 2 { y + 1 } else { y }, m, d)
242}
243
244fn digits(s: &[u8]) -> Option<i64> {
245    if s.is_empty() || !s.iter().all(|c| c.is_ascii_digit()) {
246        return None;
247    }
248    Some(s.iter().fold(0i64, |a, c| a * 10 + (c - b'0') as i64))
249}
250
251/// UTCTime / GeneralizedTime (Z, seconds) -> seconds since 1970
252pub(crate) fn parse_time(tag: u8, c: &[u8]) -> Option<i64> {
253    let (y, rest) = match tag {
254        der::UTC_TIME if c.len() == 13 => {
255            let yy = digits(&c[..2])?;
256            (if yy >= 50 { 1900 + yy } else { 2000 + yy }, &c[2..])
257        }
258        der::GEN_TIME if c.len() == 15 => (digits(&c[..4])?, &c[4..]),
259        _ => return None,
260    };
261    if rest[10] != b'Z' {
262        return None;
263    }
264    let (mo, d, h, mi, s) = (digits(&rest[0..2])?, digits(&rest[2..4])?, digits(&rest[4..6])?, digits(&rest[6..8])?, digits(&rest[8..10])?);
265    let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
266    let dim = match mo {
267        2 => 28 + leap as i64,
268        4 | 6 | 9 | 11 => 30,
269        _ => 31,
270    };
271    if !(1..=12).contains(&mo) || !(1..=dim).contains(&d) || h > 23 || mi > 59 || s > 59 {
272        return None;
273    }
274    Some(days_from_civil(y, mo, d) * 86_400 + h * 3600 + mi * 60 + s)
275}
276
277fn encode_time(t: i64) -> Vec<u8> {
278    let (y, m, d) = civil_from_days(t.div_euclid(86_400));
279    let s = t.rem_euclid(86_400);
280    let (h, mi, se) = (s / 3600, s / 60 % 60, s % 60);
281    if (1950..2050).contains(&y) {
282        der::tlv(der::UTC_TIME, format!("{:02}{:02}{:02}{:02}{:02}{:02}Z", y % 100, m, d, h, mi, se).as_bytes())
283    } else {
284        der::tlv(der::GEN_TIME, format!("{:04}{:02}{:02}{:02}{:02}{:02}Z", y, m, d, h, mi, se).as_bytes())
285    }
286}
287
288fn is_ed25519_alg(alg: &[u8]) -> bool {
289    let mut d = Der::new(alg);
290    d.read(der::OID) == Some(&der::oid_bytes(OID_ED25519)[..]) && d.is_empty()
291}
292
293pub(crate) fn oid_is(o: &[u8], arcs: &[u64]) -> bool {
294    o == der::oid_bytes(arcs)
295}
296
297fn hash_of(o: &[u8]) -> Option<HashAlg> {
298    if oid_is(o, OID_SHA256) {
299        Some(HashAlg::Sha256)
300    } else if oid_is(o, OID_SHA384) {
301        Some(HashAlg::Sha384)
302    } else if oid_is(o, OID_SHA512) {
303        Some(HashAlg::Sha512)
304    } else {
305        None
306    }
307}
308
309/// an AlgorithmIdentifier's hash (parameters absent or NULL)
310fn hash_alg_id(alg: &[u8]) -> Option<HashAlg> {
311    let mut d = Der::new(alg);
312    let h = hash_of(d.read(der::OID)?)?;
313    d.optional(der::NULL);
314    d.is_empty().then_some(h)
315}
316
317/// the signature algorithm of an AlgorithmIdentifier's content
318pub(crate) fn sig_alg(alg: &[u8]) -> SigAlg {
319    if is_ed25519_alg(alg) {
320        return SigAlg::Ed25519;
321    }
322    let mut d = Der::new(alg);
323    let Some(o) = d.read(der::OID) else { return SigAlg::Unknown };
324    for (arcs, h) in [(OID_RSA_SHA256, HashAlg::Sha256), (OID_RSA_SHA384, HashAlg::Sha384), (OID_RSA_SHA512, HashAlg::Sha512)] {
325        if oid_is(o, arcs) {
326            d.optional(der::NULL);
327            return if d.is_empty() { SigAlg::RsaPkcs1(h) } else { SigAlg::Unknown };
328        }
329    }
330    for (arcs, h) in [(OID_ECDSA_SHA256, HashAlg::Sha256), (OID_ECDSA_SHA384, HashAlg::Sha384), (OID_ECDSA_SHA512, HashAlg::Sha512)] {
331        if oid_is(o, arcs) {
332            return if d.is_empty() { SigAlg::Ecdsa(h) } else { SigAlg::Unknown };
333        }
334    }
335    if oid_is(o, OID_RSA_PSS) {
336        // RSASSA-PSS-params: [0] hash, [1] MGF1(hash), [2] salt length; SHA-1 defaults refused
337        let pss = |mut d: Der| -> Option<SigAlg> {
338            let mut p = d.seq()?;
339            let h = hash_alg_id(Der::new(p.read(0xa0)?).read(der::SEQUENCE)?)?;
340            let mut mgf = Der::new(Der::new(p.read(0xa1)?).read(der::SEQUENCE)?);
341            if !oid_is(mgf.read(der::OID)?, OID_MGF1) || hash_alg_id(mgf.read(der::SEQUENCE)?)? != h {
342                return None;
343            }
344            let salt = match p.optional(0xa2) {
345                Some(x) => Der::new(x).u64()? as usize,
346                None => 20,
347            };
348            if let Some(t) = p.optional(0xa3) {
349                if Der::new(t).u64()? != 1 {
350                    return None;
351                }
352            }
353            (p.is_empty() && d.is_empty()).then_some(SigAlg::RsaPss(h, Some(salt)))
354        };
355        return pss(d).unwrap_or(SigAlg::Unknown);
356    }
357    SigAlg::Unknown
358}
359
360/// the key of a SubjectPublicKeyInfo
361pub(crate) fn pub_key(alg: &[u8], key: &[u8]) -> PubKey {
362    if is_ed25519_alg(alg) {
363        return match <[u8; 32]>::try_from(key) {
364            Ok(k) => PubKey::Ed25519(k),
365            Err(_) => PubKey::Other,
366        };
367    }
368    let mut d = Der::new(alg);
369    let Some(o) = d.read(der::OID) else { return PubKey::Other };
370    if oid_is(o, OID_RSA) {
371        let rsa = || -> Option<PubKey> {
372            let mut k = Der::new(key).seq()?;
373            let n = k.read(der::INTEGER)?;
374            let e = k.read(der::INTEGER)?;
375            (k.is_empty() && n.first().is_some_and(|b| b & 0x80 == 0)).then(|| PubKey::Rsa { n: Vec::from(strip_zeros(n)), e: Vec::from(strip_zeros(e)) })
376        };
377        return rsa().unwrap_or(PubKey::Other);
378    }
379    if oid_is(o, OID_EC) {
380        let Some(c) = d.read(der::OID) else { return PubKey::Other };
381        let curve = if oid_is(c, OID_P256) {
382            Curve::P256
383        } else if oid_is(c, OID_P384) {
384            Curve::P384
385        } else {
386            return PubKey::Other;
387        };
388        if key.len() == 1 + 2 * curve.bytes() && key[0] == 4 {
389            return PubKey::Ec { curve, point: Vec::from(key) };
390        }
391    }
392    PubKey::Other
393}
394
395/// the subtrees of one kind (permitted or excluded) of a NameConstraints
396#[derive(Default)]
397struct Subtrees {
398    dns: Vec<String>,
399    ips: Vec<Vec<u8>>,
400    email: Vec<String>,
401    uri: Vec<String>,
402    dn: Vec<Vec<u8>>,
403}
404
405/// GeneralSubtrees (SIZE (1..MAX)); minimum and maximum must be absent (RFC 5280 4.2.1.10)
406fn subtrees(b: &[u8], out: &mut Subtrees, other: &mut Vec<u8>) -> Option<()> {
407    let mut d = Der::new(b);
408    if d.is_empty() {
409        return None;
410    }
411    while !d.is_empty() {
412        let mut st = d.seq()?;
413        let (tag, v, _) = st.next()?;
414        if !st.is_empty() {
415            return None;
416        }
417        match tag {
418            0x81 => out.email.push(ascii(v)?.to_ascii_lowercase()),
419            0x82 => out.dns.push(ascii(v)?.to_ascii_lowercase()),
420            0x86 => out.uri.push(ascii(v)?.to_ascii_lowercase()),
421            0x87 if v.len() == 8 || v.len() == 32 => out.ips.push(Vec::from(v)),
422            0xa4 => out.dn.push(Vec::from(Der::new(v).read_raw(der::SEQUENCE)?)),
423            0xa0 | 0xa3 | 0xa5 | 0x88 => {
424                if !other.contains(&tag) {
425                    other.push(tag);
426                }
427            }
428            _ => return None,
429        }
430    }
431    Some(())
432}
433
434/// an IA5String's bytes as text (None for bytes above 0x7f)
435pub(crate) fn ascii(v: &[u8]) -> Option<String> {
436    v.is_ascii().then(|| String::from_utf8_lossy(v).into_owned())
437}
438
439/// a dNSName of a subject alternative name in the preferred name syntax (RFC 5280 4.2.1.6,
440/// RFC 1034 3.5 with RFC 1123 2.1): labels of letters, digits and inner hyphens, at most 63
441/// bytes each and 253 in all; "*" only as the whole first label
442pub(crate) fn dns_name_ok(n: &str) -> bool {
443    let rest = n.strip_prefix("*.").unwrap_or(n);
444    if n.is_empty() || n.len() > 253 || rest.is_empty() {
445        return false;
446    }
447    rest.split('.').all(|l| {
448        let b = l.as_bytes();
449        !b.is_empty() && b.len() <= 63 && b[0] != b'-' && b[b.len() - 1] != b'-' && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
450    })
451}
452
453const OID_EMAIL_ATTR: &[u64] = &[1, 2, 840, 113549, 1, 9, 1];
454
455/// the emailAddress attributes of a Name
456fn emails_of(name: &[u8]) -> Vec<String> {
457    let mut out = Vec::new();
458    let mut d = Der::new(name);
459    while let Some(set) = d.read(der::SET) {
460        let mut s = Der::new(set);
461        while let Some(atv) = s.seq() {
462            let mut a = atv;
463            if a.read(der::OID) == Some(&der::oid_bytes(OID_EMAIL_ATTR)[..]) {
464                if let Some((_, v, _)) = a.next() {
465                    out.push(String::from_utf8_lossy(v).to_ascii_lowercase());
466                }
467            }
468        }
469    }
470    out
471}
472
473/// the common name of a Name
474pub(crate) fn cn_of(name: &[u8]) -> String {
475    attr_of(name, OID_CN)
476}
477
478/// the first attribute of a type in a Name (common name, organization, ...)
479fn attr_of(name: &[u8], oid: &[u64]) -> String {
480    let mut d = Der::new(name);
481    while let Some(set) = d.read(der::SET) {
482        let mut s = Der::new(set);
483        while let Some(atv) = s.seq() {
484            let mut a = atv;
485            if a.read(der::OID) == Some(&der::oid_bytes(oid)[..]) {
486                if let Some((_, v, _)) = a.next() {
487                    return String::from_utf8_lossy(v).into_owned();
488                }
489            }
490        }
491    }
492    String::new()
493}
494
495/// an RSA key of a certificate: at least 2048 bits and a whole number of bytes (the CA/Browser
496/// Forum's floor; crypto::rsa takes 1024 bits and more, for simulators)
497fn rsa_key(n: &[u8], e: &[u8]) -> Option<crypto::rsa::PublicKey> {
498    crypto::rsa::PublicKey::new(n, e).filter(|k| k.bits() >= 2048 && k.bits() % 8 == 0)
499}
500
501/// the content of a non-negative DER INTEGER -> its big-endian bytes without the sign byte;
502/// None when it is empty, negative or not in the shortest form (a 00 before a byte below 0x80)
503/// the bytes after the leading zero bytes of a number (all of them for 0: no bytes)
504fn strip_zeros(b: &[u8]) -> &[u8] {
505    &b[b.iter().position(|&x| x != 0).unwrap_or(b.len())..]
506}
507
508fn der_unsigned(b: &[u8]) -> Option<&[u8]> {
509    match b {
510        [] => None,
511        [0, next, ..] if next & 0x80 == 0 => None,
512        [0, rest @ ..] if !rest.is_empty() => Some(rest),
513        [first, ..] if first & 0x80 != 0 => None,
514        _ => Some(b),
515    }
516}
517
518impl Cert {
519    pub fn parse(bytes: &[u8]) -> Option<Cert> {
520        let mut top = Der::new(bytes);
521        let mut cert = top.seq()?;
522        if !top.is_empty() {
523            return None;
524        }
525        let tbs_raw = cert.read_raw(der::SEQUENCE)?;
526        let alg = cert.read(der::SEQUENCE)?;
527        let sig = cert.bits()?;
528        if !cert.is_empty() {
529            return None;
530        }
531        let mut t = Der::new(tbs_raw).seq()?;
532        let sa = sig_alg(alg);
533        let mut c = Cert { der: Vec::from(bytes), tbs: Vec::from(tbs_raw), signature: Vec::from(sig), ed25519_signed: sa == SigAlg::Ed25519, sig_alg: sa, ..Cert::default() };
534        // version [0] EXPLICIT INTEGER: v3, or v1 without it (old root certificates)
535        c.version = match t.optional(0xa0) {
536            Some(v) if Der::new(v).u64()? == 2 => 3,
537            Some(_) => return None,
538            None => 1,
539        };
540        c.serial = Vec::from(t.read(der::INTEGER)?);
541        let inner_alg = t.read(der::SEQUENCE)?;
542        if inner_alg != alg {
543            return None;
544        }
545        c.issuer = Vec::from(t.read_raw(der::SEQUENCE)?);
546        let mut val = t.seq()?;
547        let (tag, nb, _) = val.next()?;
548        c.not_before = parse_time(tag, nb)?;
549        let (tag, na, _) = val.next()?;
550        c.not_after = parse_time(tag, na)?;
551        let subj = t.read_raw(der::SEQUENCE)?;
552        c.subject = Vec::from(subj);
553        c.subject_cn = cn_of(Der::new(subj).read(der::SEQUENCE)?);
554        c.subject_org = attr_of(Der::new(subj).read(der::SEQUENCE)?, OID_O);
555        c.issuer_cn = cn_of(Der::new(&c.issuer).read(der::SEQUENCE)?);
556        c.issuer_org = attr_of(Der::new(&c.issuer).read(der::SEQUENCE)?, OID_O);
557        c.emails = emails_of(Der::new(subj).read(der::SEQUENCE)?);
558        let mut spki = t.seq()?;
559        let kalg = spki.read(der::SEQUENCE)?;
560        let key = spki.bits()?;
561        c.key = pub_key(kalg, key);
562        if let PubKey::Ed25519(k) = &c.key {
563            c.public_key = Vec::from(&k[..]);
564        }
565        // optional issuerUniqueID [1], subjectUniqueID [2]: not accepted
566        if let Some(ext) = t.read(0xa3) {
567            if c.version != 3 {
568                return None;
569            }
570            let mut list = Der::new(ext).seq()?;
571            let mut seen: Vec<Vec<u8>> = Vec::new();
572            while !list.is_empty() {
573                let mut e = list.seq()?;
574                let id = Vec::from(e.read(der::OID)?);
575                if seen.contains(&id) {
576                    return None; // an extension twice
577                }
578                seen.push(id.clone());
579                let critical = if e.peek_tag() == Some(der::BOOLEAN) { e.bool()? } else { false };
580                let val = e.read(der::OCTET_STRING)?;
581                let is = |o: &[u64]| id == der::oid_bytes(o);
582                if is(OID_BASIC) {
583                    let mut b = Der::new(val).seq()?;
584                    if b.peek_tag() == Some(der::BOOLEAN) {
585                        c.is_ca = b.bool()?;
586                    }
587                    if b.peek_tag() == Some(der::INTEGER) {
588                        c.path_len = Some(b.u64()?);
589                    }
590                } else if is(OID_KEY_USAGE) {
591                    let mut k = Der::new(val);
592                    let bs = k.read(der::BIT_STRING)?;
593                    c.key_usage = Some(*bs.get(1).unwrap_or(&0));
594                } else if is(OID_EKU) {
595                    // KeyPurposeId SEQUENCE SIZE (1..MAX): an empty one would allow every purpose
596                    let mut k = Der::new(val).seq()?;
597                    while let Some(o) = k.read(der::OID) {
598                        c.eku.push(Vec::from(o));
599                    }
600                    if c.eku.is_empty() || !k.is_empty() {
601                        return None;
602                    }
603                } else if is(OID_SAN) {
604                    // GeneralNames SIZE (1..MAX), every entry well-formed: a name that cannot be
605                    // read could not be held against a name constraint either
606                    let mut k = Der::new(val).seq()?;
607                    if k.is_empty() {
608                        return None;
609                    }
610                    while !k.is_empty() {
611                        let (tag, v, _) = k.next()?;
612                        match tag {
613                            0x82 => {
614                                let n = ascii(v)?.to_ascii_lowercase();
615                                if !dns_name_ok(&n) {
616                                    return None;
617                                }
618                                c.dns.push(n);
619                            }
620                            0x87 if v.len() == 4 => c.ips.push(IpAddr::V4([v[0], v[1], v[2], v[3]])),
621                            0x87 if v.len() == 16 => {
622                                let mut a = [0u8; 16];
623                                a.copy_from_slice(v);
624                                c.ips.push(IpAddr::V6(a));
625                            }
626                            0x81 => c.emails.push(ascii(v)?.to_ascii_lowercase()),
627                            0x86 => c.uris.push(ascii(v)?.to_ascii_lowercase()),
628                            0xa4 => c.dirs.push(Vec::from(Der::new(v).read_raw(der::SEQUENCE)?)),
629                            0xa0 | 0xa3 | 0xa5 | 0x88 => c.other_names.push(tag),
630                            _ => return None,
631                        }
632                    }
633                } else if is(OID_SKI) {
634                    if critical {
635                        return None; // MUST be non-critical (RFC 5280 4.2.1.2)
636                    }
637                    c.ski = Vec::from(Der::new(val).read(der::OCTET_STRING)?);
638                } else if is(OID_NAME_CONSTRAINTS) {
639                    // permittedSubtrees or excludedSubtrees MUST be present (RFC 5280 4.2.1.10)
640                    let mut k = Der::new(val).seq()?;
641                    let (p, x) = (k.optional(0xa0), k.optional(0xa1));
642                    if (p.is_none() && x.is_none()) || !k.is_empty() {
643                        return None;
644                    }
645                    let (mut pt, mut xt, mut other) = (Subtrees::default(), Subtrees::default(), Vec::new());
646                    if let Some(p) = p {
647                        subtrees(p, &mut pt, &mut other)?;
648                    }
649                    if let Some(x) = x {
650                        subtrees(x, &mut xt, &mut other)?;
651                    }
652                    c.name_constraints = Some(NameConstraints {
653                        permitted_dns: pt.dns,
654                        excluded_dns: xt.dns,
655                        permitted_ip: pt.ips,
656                        excluded_ip: xt.ips,
657                        permitted_email: pt.email,
658                        excluded_email: xt.email,
659                        permitted_uri: pt.uri,
660                        excluded_uri: xt.uri,
661                        permitted_dn: pt.dn,
662                        excluded_dn: xt.dn,
663                        other_forms: other,
664                    });
665                } else if is(OID_AKI) && critical {
666                    return None; // MUST be non-critical (RFC 5280 4.2.1.1)
667                } else if is(OID_AKI) {
668                    // keyIdentifier [0], when there is one; the rest is not looked at
669                    if let Some(mut k) = Der::new(val).seq() {
670                        if let Some(id) = k.optional(0x80) {
671                            c.aki = Vec::from(id);
672                        }
673                    }
674                } else if is(OID_AIA) {
675                    // AuthorityInfoAccessSyntax: SEQUENCE SIZE (1..MAX) OF AccessDescription
676                    // (accessMethod, accessLocation); MUST be non-critical (RFC 5280 4.2.2.1)
677                    if critical {
678                        return None;
679                    }
680                    let mut top = Der::new(val);
681                    let mut k = top.seq()?;
682                    if k.is_empty() || !top.is_empty() {
683                        return None;
684                    }
685                    while !k.is_empty() {
686                        let mut ad = k.seq()?;
687                        let method = ad.read(der::OID)?;
688                        let (tag, loc, _) = ad.next()?;
689                        // a GeneralName: [0] to [8] (only URIs are used)
690                        if !ad.is_empty() || !matches!(tag, 0xa0 | 0x81 | 0x82 | 0xa3 | 0xa4 | 0xa5 | 0x86 | 0x87 | 0x88) {
691                            return None;
692                        }
693                        if tag == 0x86 {
694                            let uri = ascii(loc)?;
695                            if oid_is(method, OID_AD_OCSP) {
696                                c.ocsp_urls.push(uri);
697                            } else if oid_is(method, OID_AD_CA_ISSUERS) {
698                                c.ca_issuers.push(uri);
699                            }
700                        }
701                    }
702                } else if is(OID_TLS_FEATURE) {
703                    // Features ::= SEQUENCE OF INTEGER (RFC 7633 6), each a TLS extension type
704                    let mut top = Der::new(val);
705                    let mut k = top.seq()?;
706                    if !top.is_empty() {
707                        return None;
708                    }
709                    while !k.is_empty() {
710                        let v = k.u64()?;
711                        c.tls_features.push(u16::try_from(v).ok()?);
712                    }
713                } else if is(OID_OCSP_NOCHECK) {
714                    // its value is NULL
715                    if val != [der::NULL, 0] {
716                        return None;
717                    }
718                    c.ocsp_nocheck = true;
719                } else if is(OID_POLICIES) || is(OID_POLICY_CONSTRAINTS) || is(OID_INHIBIT_ANY) {
720                    // known; policies are not enforced
721                } else if critical {
722                    c.unknown_critical = true;
723                }
724            }
725        }
726        if !t.is_empty() {
727            return None;
728        }
729        Some(c)
730    }
731
732    /// its SubjectPublicKeyInfo as it stands in the certificate (DER): what keys are pinned by
733    /// and a certificate request carries
734    pub fn spki(&self) -> Vec<u8> {
735        self.spki_parts().map(|(whole, _)| Vec::from(whole)).unwrap_or_default()
736    }
737
738    /// the SubjectPublicKeyInfo and the bytes of its subjectPublicKey (the BIT STRING's)
739    pub(crate) fn spki_parts(&self) -> Option<(&[u8], &[u8])> {
740        let mut t = Der::new(&self.tbs).seq()?;
741        t.optional(0xa0);
742        for tag in [der::INTEGER, der::SEQUENCE, der::SEQUENCE, der::SEQUENCE, der::SEQUENCE] {
743            t.read(tag)?;
744        }
745        let whole = t.read_raw(der::SEQUENCE)?;
746        let mut s = Der::new(whole).seq()?;
747        s.read(der::SEQUENCE)?;
748        Some((whole, s.bits()?))
749    }
750
751    /// whether its extended key usage allows signing OCSP responses (id-kp-OCSPSigning: a
752    /// responder its CA delegated to, RFC 6960 4.2.2.2)
753    pub fn ocsp_signer(&self) -> bool {
754        let want = der::oid_bytes(OID_OCSP_SIGNING);
755        self.eku.iter().any(|e| *e == want)
756    }
757
758    /// whether it must come with a stapled OCSP response (RFC 7633)
759    pub fn must_staple(&self) -> bool {
760        self.tls_features.contains(&TLS_FEATURE_STATUS_REQUEST)
761    }
762
763    /// SHA-256 of the certificate
764    pub fn fingerprint_bytes(&self) -> [u8; 32] {
765        crypto::sha256(&self.der)
766    }
767
768    /// the fingerprint in hex with colons, as certificate dialogs write it
769    pub fn fingerprint_text(&self) -> String {
770        let v: Vec<String> = self.fingerprint_bytes().iter().map(|b| format!("{:02X}", b)).collect();
771        v.join(":")
772    }
773
774    /// it names itself as issuer and its own key made the signature
775    pub fn self_signed(&self) -> bool {
776        self.signed_by(self)
777    }
778
779    /// its Ed25519 key (None for another kind)
780    pub fn ed25519_key(&self) -> Option<[u8; 32]> {
781        match &self.key {
782            PubKey::Ed25519(k) => Some(*k),
783            _ => None,
784        }
785    }
786
787    /// what its names are, for a dialog: the DNS names, then the addresses
788    pub fn name_list(&self) -> Vec<String> {
789        let mut v = self.dns.clone();
790        for ip in &self.ips {
791            v.push(format!("{}", ip));
792        }
793        v
794    }
795
796    /// bytes it holds (an estimate for a memory budget)
797    pub fn bytes(&self) -> usize {
798        self.der.len() + self.tbs.len() + self.subject.len() + self.issuer.len() + self.signature.len() + 256
799    }
800
801    /// SHA-256 of the certificate (hex)
802    pub fn fingerprint(&self) -> String {
803        crypto::hex(&crypto::sha256(&self.der))
804    }
805
806    /// whether a signature over `data` was made with this certificate's key
807    pub fn verify(&self, alg: SigAlg, data: &[u8], sig: &[u8]) -> bool {
808        match (&self.key, alg) {
809            (PubKey::Ed25519(pk), SigAlg::Ed25519) => match <[u8; 64]>::try_from(sig) {
810                Ok(s) => crypto::ed25519::verify(pk, data, &s),
811                Err(_) => false,
812            },
813            (PubKey::Rsa { n, e }, SigAlg::RsaPkcs1(h)) => rsa_key(n, e).is_some_and(|k| k.verify_pkcs1(h, &h.digest(data), sig)),
814            (PubKey::Rsa { n, e }, SigAlg::RsaPss(h, salt)) => rsa_key(n, e).is_some_and(|k| k.verify_pss(h, &h.digest(data), sig, salt)),
815            (PubKey::Ec { curve, point }, SigAlg::Ecdsa(h)) => {
816                // Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }, strictly DER: nothing
817                // after the SEQUENCE or in it after s, both integers in their shortest form, so a
818                // signature has one encoding (Wycheproof's InvalidEncoding cases)
819                let rs = || -> Option<(&[u8], &[u8])> {
820                    let mut outer = Der::new(sig);
821                    let mut d = outer.seq()?;
822                    let r = der_unsigned(d.read(der::INTEGER)?)?;
823                    let s = der_unsigned(d.read(der::INTEGER)?)?;
824                    (outer.is_empty() && d.is_empty()).then_some((r, s))
825                };
826                rs().is_some_and(|(r, s)| crypto::ecdsa::verify(*curve, point, &h.digest(data), r, s))
827            }
828            _ => false,
829        }
830    }
831
832    /// whether `issuer` signed this certificate
833    pub fn signed_by(&self, issuer: &Cert) -> bool {
834        self.issuer == issuer.subject && issuer.verify(self.sig_alg, &self.tbs, &self.signature)
835    }
836
837    /// whether the extended key usage allows this purpose (no extended key usage: every purpose)
838    pub fn eku_allows(&self, u: Usage) -> bool {
839        if self.eku.is_empty() {
840            return true;
841        }
842        let want = der::oid_bytes(if u == Usage::Server { OID_SERVER_AUTH } else { OID_CLIENT_AUTH });
843        self.eku.iter().any(|e| *e == want)
844    }
845
846    // a CA on the path whose extended key usage names purposes passes on only those (or any
847    // purpose: anyExtendedKeyUsage); without the extension it does not restrict
848    fn ca_eku_allows(&self, u: Usage) -> bool {
849        let any = der::oid_bytes(OID_ANY_EKU);
850        self.eku_allows(u) || self.eku.iter().any(|e| *e == any)
851    }
852
853    /// whether the certificate names this host (DNS name, case-insensitive; IP address)
854    pub fn names(&self, host: &str) -> bool {
855        if let Some(ip) = IpAddr::parse(host.trim_matches(['[', ']'])) {
856            return self.ips.contains(&ip);
857        }
858        let h = host.to_ascii_lowercase();
859        let h = h.strip_suffix('.').unwrap_or(&h);
860        self.dns.iter().any(|d| {
861            d == h
862                || d.strip_prefix("*.").is_some_and(|base| {
863                    base.contains('.') && h.split_once('.').is_some_and(|(label, rest)| !label.is_empty() && rest == base)
864                })
865        })
866    }
867}
868
869/// whether a DNS name lies in a constraint subtree ("example.com": it and its subdomains;
870/// ".example.com": subdomains only)
871fn dns_in(name: &str, base: &str) -> bool {
872    if base.is_empty() {
873        return true;
874    }
875    if let Some(b) = base.strip_prefix('.') {
876        return name.ends_with(base) && name.len() > b.len();
877    }
878    name == base || below(name, base)
879}
880
881// name is a subdomain of base ("a.b.c" of "b.c")
882fn below(name: &str, base: &str) -> bool {
883    name.len() > base.len() && name.ends_with(base) && name.as_bytes()[name.len() - base.len() - 1] == b'.'
884}
885
886/// a wildcard "*.d" stands for every name one label below d: whether every one of them lies
887/// in a constraint subtree (every: a permitted one must hold them all) or some of them does
888/// (an excluded one must hold none: "*.example.com" stands for "host.example.com" too)
889fn wild_in(d: &str, base: &str, every: bool) -> bool {
890    if base.is_empty() {
891        return true;
892    }
893    let b = base.strip_prefix('.').unwrap_or(base);
894    // x.d lies below b for every x when d is b or below it (also in ".b": x.d is a subdomain)
895    if d == b || below(d, b) {
896        return true;
897    }
898    // a plain base one label below d is one of the names
899    !every && !base.starts_with('.') && below(b, d) && !b[..b.len() - d.len() - 1].contains('.')
900}
901
902fn ip_in(ip: &IpAddr, range: &[u8]) -> bool {
903    let a: &[u8] = match ip {
904        IpAddr::V4(a) => a,
905        IpAddr::V6(a) => a,
906    };
907    let half = range.len() / 2;
908    a.len() == half && a.iter().zip(&range[..half]).zip(&range[half..]).all(|((x, net), m)| x & m == net & m)
909}
910
911/// the RDNs of a Name (the DER of a SEQUENCE of SETs), each as its whole DER
912fn rdns(name: &[u8]) -> Option<Vec<&[u8]>> {
913    let mut d = Der::new(name).seq()?;
914    let mut out = Vec::new();
915    while !d.is_empty() {
916        out.push(d.read_raw(der::SET)?);
917    }
918    Some(out)
919}
920
921/// whether a Name lies in a directoryName subtree: it begins with the subtree's RDNs, byte for
922/// byte (no string preparation)
923fn dn_in(name: &[u8], base: &[u8]) -> bool {
924    match (rdns(name), rdns(base)) {
925        (Some(n), Some(b)) => b.len() <= n.len() && n.iter().zip(&b).all(|(x, y)| x == y),
926        _ => false,
927    }
928}
929
930/// whether an e-mail address lies in an rfc822Name subtree: the mailbox itself, every mailbox
931/// of a host ("example.com"), or of the subdomains of a domain (".example.com")
932fn email_in(addr: &str, base: &str) -> bool {
933    if base.contains('@') {
934        return addr == base;
935    }
936    let Some((_, host)) = addr.rsplit_once('@') else { return false };
937    match base.strip_prefix('.') {
938        Some(_) => host.ends_with(base),
939        None => host == base,
940    }
941}
942
943/// the host of a URI ("scheme://[user@]host[:port]/..."); None without an authority or with an
944/// address instead of a name (RFC 5280: such a URI cannot pass a URI constraint)
945fn uri_host(uri: &str) -> Option<&str> {
946    let rest = uri.split_once("://")?.1;
947    let auth = rest.split(['/', '?', '#']).next()?;
948    let host = auth.rsplit_once('@').map_or(auth, |(_, h)| h);
949    if host.starts_with('[') {
950        return None;
951    }
952    let host = host.split(':').next()?;
953    (!host.is_empty() && IpAddr::parse(host).is_none()).then_some(host)
954}
955
956/// whether a URI's host lies in a uniformResourceIdentifier subtree
957fn uri_in(host: &str, base: &str) -> bool {
958    match base.strip_prefix('.') {
959        Some(_) => host.ends_with(base),
960        None => host == base,
961    }
962}
963
964/// a certificate's names against the name constraints of a CA above it on the path
965fn constraints_allow(c: &Cert, nc: &NameConstraints) -> bool {
966    // permitted: every name of a form must lie in one subtree of that form (when there are
967    // any); excluded: none may lie in one
968    fn check<T>(names: &[T], permitted: &[String], excluded: &[String], within: impl Fn(&T, &str, bool) -> bool) -> bool {
969        names.iter().all(|n| !excluded.iter().any(|b| within(n, b, false)) && (permitted.is_empty() || permitted.iter().any(|b| within(n, b, true))))
970    }
971    // a wildcard is checked for the names it stands for, not for its base alone
972    let dns_ok = check(&c.dns, &nc.permitted_dns, &nc.excluded_dns, |d: &String, b: &str, every| match d.strip_prefix("*.") {
973        Some(w) => wild_in(w, b, every),
974        None => dns_in(d, b),
975    });
976    let ip_ok = c.ips.iter().all(|ip| !nc.excluded_ip.iter().any(|r| ip_in(ip, r)) && (nc.permitted_ip.is_empty() || nc.permitted_ip.iter().any(|r| ip_in(ip, r))));
977    let email_ok = check(&c.emails, &nc.permitted_email, &nc.excluded_email, |e: &String, b: &str, _| email_in(e, b));
978    let uri_ok = if nc.permitted_uri.is_empty() && nc.excluded_uri.is_empty() {
979        true
980    } else {
981        c.uris.iter().all(|u| match uri_host(u) {
982            Some(h) => !nc.excluded_uri.iter().any(|b| uri_in(h, b)) && (nc.permitted_uri.is_empty() || nc.permitted_uri.iter().any(|b| uri_in(h, b))),
983            None => false,
984        })
985    };
986    // directory names: the subject (when it has RDNs) and the directoryName alternative names
987    let subject_has_rdns = rdns(&c.subject).is_some_and(|r| !r.is_empty());
988    let dn_ok = (!subject_has_rdns || dn_ok_one(&c.subject, nc)) && c.dirs.iter().all(|n| dn_ok_one(n, nc));
989    // a form constrained here that this code does not process: refused (RFC 5280 4.2.1.10)
990    let other_ok = !c.other_names.iter().any(|t| nc.other_forms.contains(t));
991    dns_ok && ip_ok && email_ok && uri_ok && dn_ok && other_ok
992}
993
994fn dn_ok_one(name: &[u8], nc: &NameConstraints) -> bool {
995    !nc.excluded_dn.iter().any(|b| dn_in(name, b)) && (nc.permitted_dn.is_empty() || nc.permitted_dn.iter().any(|b| dn_in(name, b)))
996}
997
998/// a Name without RDNs (a CA's subject MUST NOT be one, RFC 5280 4.1.2.6)
999fn empty_name(name: &[u8]) -> bool {
1000    rdns(name).is_none_or(|r| r.is_empty())
1001}
1002
1003/// a certificate whose issuer and subject are the same name (RFC 5280 6.1: self-issued)
1004fn self_issued(c: &Cert) -> bool {
1005    c.issuer == c.subject
1006}
1007
1008/// check a chain (leaf first) against trusted anchors: a path from the leaf through the other
1009/// certificates of the chain (in any order) to an anchor
1010pub fn verify_chain(chain: &[Cert], anchors: &[Cert], now: i64, name: Option<&str>, usage: Usage) -> Result<(), String> {
1011    find_path(chain, anchors, now, name, usage).map(|_| ())
1012}
1013
1014/// verify_chain, and the path it found: the leaf, the intermediates of the chain it went
1015/// through (in their order up), the anchor (a root the chain left out: what a TLSA record of
1016/// usage PKIX-TA may name, RFC 7671 5.4)
1017pub fn verify_path(chain: &[Cert], anchors: &[Cert], now: i64, name: Option<&str>, usage: Usage) -> Result<Vec<Cert>, String> {
1018    let (below, anchor) = find_path(chain, anchors, now, name, usage)?;
1019    Ok(below.iter().map(|&i| &chain[i]).chain(core::iter::once(&anchors[anchor])).cloned().collect())
1020}
1021
1022/// the path of verify_chain: the indices into chain (leaf first) and the anchor's index
1023fn find_path(chain: &[Cert], anchors: &[Cert], now: i64, name: Option<&str>, usage: Usage) -> Result<(Vec<usize>, usize), String> {
1024    let leaf = chain.first().ok_or("kein Zertifikat")?;
1025    check_leaf(leaf, now, name, usage)?;
1026    let mut why = String::from("keine vertrauenswürdige Zertifizierungsstelle");
1027    let mut used = alloc::vec![false; chain.len()];
1028    let mut below = alloc::vec![0usize];
1029    let mut budget = 64u32;
1030    match path(chain, anchors, now, usage, &mut used, &mut below, &mut budget, &mut why) {
1031        Some(a) => Ok((below, a)),
1032        None => Err(why),
1033    }
1034}
1035
1036/// the checks of verify_chain that concern the leaf alone: no unknown critical extension,
1037/// valid at `now`, for this usage (extended key usage), allowed to sign (key usage
1038/// digitalSignature), no CA's extensions on a certificate that is no CA (keyCertSign, name
1039/// constraints: RFC 5280 4.2.1.9, 4.2.1.10), and the name.  netio::roots asks them after a
1040/// system's verifier said yes to the path, so the leaf follows the same rules everywhere
1041pub fn check_leaf(leaf: &Cert, now: i64, name: Option<&str>, usage: Usage) -> Result<(), String> {
1042    if leaf.unknown_critical {
1043        return Err(String::from("unbekannte kritische Erweiterung"));
1044    }
1045    if now < leaf.not_before || now > leaf.not_after {
1046        return Err(String::from("Zertifikat abgelaufen oder noch nicht gültig"));
1047    }
1048    if !leaf.eku_allows(usage) {
1049        return Err(String::from("Zertifikat nicht für diesen Zweck"));
1050    }
1051    if leaf.key_usage.is_some_and(|k| k & KU_DIGITAL_SIGNATURE == 0) {
1052        return Err(String::from("Zertifikat darf nicht signieren"));
1053    }
1054    // keyCertSign only with cA, name constraints only in CAs (RFC 5280 4.2.1.9, 4.2.1.10)
1055    if (leaf.key_usage.is_some_and(|k| k & KU_KEY_CERT_SIGN != 0) && !leaf.is_ca) || (leaf.name_constraints.is_some() && !leaf.is_ca) {
1056        return Err(String::from("Zertifikat mit Erweiterungen einer Zertifizierungsstelle"));
1057    }
1058    if let Some(n) = name {
1059        if !leaf.names(n) {
1060            return Err(format!("Zertifikat gilt nicht für {}", n));
1061        }
1062    }
1063    Ok(())
1064}
1065
1066/// whether a CA may sign above the certificates of `below` (indices into chain, leaf first):
1067/// its path length counts the intermediates that are not self-issued (RFC 5280 6.1.4 (l)), its
1068/// name constraints apply to the leaf and to those intermediates (6.1.3 (b))
1069fn ca_admits(ca: &Cert, chain: &[Cert], below: &[usize]) -> Result<(), &'static str> {
1070    let intermediates = below[1..].iter().filter(|&&i| !self_issued(&chain[i])).count();
1071    if ca.path_len.is_some_and(|p| (p as usize) < intermediates) {
1072        return Err("die Zertifikatskette ist länger, als die Zertifizierungsstelle erlaubt");
1073    }
1074    if let Some(nc) = &ca.name_constraints {
1075        let named = below.iter().enumerate().filter(|&(k, &i)| k == 0 || !self_issued(&chain[i]));
1076        if !named.into_iter().all(|(_, &i)| constraints_allow(&chain[i], nc)) {
1077            return Err("der Name ist für diese Zertifizierungsstelle nicht erlaubt");
1078        }
1079    }
1080    Ok(())
1081}
1082
1083/// a path upwards from the last certificate of `below`
1084#[allow(clippy::too_many_arguments)]
1085fn path(chain: &[Cert], anchors: &[Cert], now: i64, usage: Usage, used: &mut [bool], below: &mut Vec<usize>, budget: &mut u32, why: &mut String) -> Option<usize> {
1086    if below.len() > 9 {
1087        *why = String::from("Zertifikatskette zu lang");
1088        return None;
1089    }
1090    let cur = &chain[*below.last().unwrap_or(&0)];
1091    for (ai, a) in anchors.iter().enumerate().filter(|(_, a)| a.subject == cur.issuer) {
1092        if !cur.signed_by(a) {
1093            continue;
1094        }
1095        if now < a.not_before || now > a.not_after {
1096            *why = String::from("die Zertifizierungsstelle ist abgelaufen");
1097            continue;
1098        }
1099        if !(a.is_ca || a.version == 1) || a.unknown_critical || a.key_usage.is_some_and(|k| k & KU_KEY_CERT_SIGN == 0) || empty_name(&a.subject) {
1100            *why = String::from("Vertrauensanker ist keine Zertifizierungsstelle");
1101            continue;
1102        }
1103        if let Err(e) = ca_admits(a, chain, below) {
1104            *why = String::from(e);
1105            continue;
1106        }
1107        if !a.ca_eku_allows(usage) {
1108            *why = String::from("die Zertifizierungsstelle ist nicht für diesen Zweck");
1109            continue;
1110        }
1111        return Some(ai);
1112    }
1113    for i in 1..chain.len() {
1114        let next = &chain[i];
1115        if used[i] || next.subject != cur.issuer {
1116            continue;
1117        }
1118        // certificates with equal names and keys would otherwise make this a factorial search
1119        // of signature checks
1120        if *budget == 0 {
1121            *why = String::from("Zertifikatskette zu komplex");
1122            return None;
1123        }
1124        *budget -= 1;
1125        if !cur.signed_by(next) {
1126            continue;
1127        }
1128        if !next.is_ca || next.unknown_critical || now < next.not_before || now > next.not_after || next.key_usage.is_some_and(|k| k & KU_KEY_CERT_SIGN == 0) || empty_name(&next.subject) {
1129            *why = String::from("ungültige Zwischenzertifizierungsstelle");
1130            continue;
1131        }
1132        if let Err(e) = ca_admits(next, chain, below) {
1133            *why = String::from(e);
1134            continue;
1135        }
1136        // a CA whose extended key usage names other purposes cannot certify this one
1137        if !next.ca_eku_allows(usage) {
1138            *why = String::from("die Zertifizierungsstelle ist nicht für diesen Zweck");
1139            continue;
1140        }
1141        used[i] = true;
1142        below.push(i);
1143        if let Some(a) = path(chain, anchors, now, usage, used, below, budget, why) {
1144            return Some(a);
1145        }
1146        below.pop();
1147        used[i] = false;
1148    }
1149    None
1150}
1151
1152pub(crate) fn name(cn: &str, org: &str) -> Vec<u8> {
1153    let mut rdns = Vec::new();
1154    if !org.is_empty() {
1155        rdns.push(der::set(&[&der::seq(&[&der::oid(OID_O), &der::utf8(org)])]));
1156    }
1157    rdns.push(der::set(&[&der::seq(&[&der::oid(OID_CN), &der::utf8(cn)])]));
1158    let parts: Vec<&[u8]> = rdns.iter().map(|v| v.as_slice()).collect();
1159    der::seq(&parts)
1160}
1161
1162pub(crate) fn ext(oid: &[u64], critical: bool, value: &[u8]) -> Vec<u8> {
1163    if critical {
1164        der::seq(&[&der::oid(oid), &der::boolean(true), &der::octets(value)])
1165    } else {
1166        der::seq(&[&der::oid(oid), &der::octets(value)])
1167    }
1168}
1169
1170/// what a new certificate says
1171#[derive(Clone, Debug, Default)]
1172pub struct CertBuilder {
1173    pub serial: [u8; 16],
1174    pub cn: String,
1175    pub org: String,
1176    pub not_before: i64,
1177    pub not_after: i64,
1178    pub public_key: [u8; 32],
1179    pub is_ca: bool,
1180    pub dns: Vec<String>,
1181    pub ips: Vec<IpAddr>,
1182    pub server_auth: bool,
1183    pub client_auth: bool,
1184    /// the subject's key as a SubjectPublicKeyInfo (PrivateKey::spki, spki_of); empty: the
1185    /// Ed25519 key `public_key`
1186    pub spki: Vec<u8>,
1187    /// OCSP responders to name in the authority information access (http URIs)
1188    pub ocsp_urls: Vec<String>,
1189    /// a leaf that must come with a stapled OCSP response (the TLS feature status_request,
1190    /// RFC 7633)
1191    pub must_staple: bool,
1192    /// a leaf that signs OCSP responses for its issuer (id-kp-OCSPSigning, with
1193    /// id-pkix-ocsp-nocheck)
1194    pub ocsp_signing: bool,
1195}
1196
1197/// the AlgorithmIdentifier of a signature (None for PSS, which certificates here do not use)
1198pub(crate) fn alg_id(alg: SigAlg) -> Option<Vec<u8>> {
1199    let hash_oid = |h: HashAlg, rsa: bool| match (h, rsa) {
1200        (HashAlg::Sha256, true) => Some(OID_RSA_SHA256),
1201        (HashAlg::Sha384, true) => Some(OID_RSA_SHA384),
1202        (HashAlg::Sha512, true) => Some(OID_RSA_SHA512),
1203        (HashAlg::Sha256, false) => Some(OID_ECDSA_SHA256),
1204        (HashAlg::Sha384, false) => Some(OID_ECDSA_SHA384),
1205        (HashAlg::Sha512, false) => Some(OID_ECDSA_SHA512),
1206        _ => None,
1207    };
1208    match alg {
1209        SigAlg::Ed25519 => Some(der::seq(&[&der::oid(OID_ED25519)])),
1210        SigAlg::Ecdsa(h) => Some(der::seq(&[&der::oid(hash_oid(h, false)?)])),
1211        SigAlg::RsaPkcs1(h) => Some(der::seq(&[&der::oid(hash_oid(h, true)?), &[der::NULL, 0]])),
1212        _ => None,
1213    }
1214}
1215
1216/// a DER Extension (oid, the critical flag, the DER value) for CertBuilder::sign_ext
1217pub fn extension(oid: &[u64], critical: bool, value: &[u8]) -> Vec<u8> {
1218    ext(oid, critical, value)
1219}
1220
1221impl CertBuilder {
1222    /// the DER certificate, signed by `key`; `issuer`: the issuing certificate (None: self
1223    /// signed with the builder's own name)
1224    pub fn sign(&self, issuer: Option<&Cert>, key: &Keypair) -> Vec<u8> {
1225        self.sign_ext(issuer, key, &[])
1226    }
1227
1228    /// sign with further extensions (each one from `extension`: name constraints, a CA's
1229    /// extended key usage ...); one with the OID of an extension the builder writes itself
1230    /// replaces that one (basic constraints without a path length, other key usages)
1231    pub fn sign_ext(&self, issuer: Option<&Cert>, key: &Keypair, extra: &[Vec<u8>]) -> Vec<u8> {
1232        let alg = der::seq(&[&der::oid(OID_ED25519)]);
1233        self.build(issuer, &alg, extra, &mut |tbs| Some(Vec::from(&key.sign(tbs)[..]))).unwrap_or_default()
1234    }
1235
1236    /// the DER certificate for the key `spki` (any key), signed by `key` (any key: ECDSA with
1237    /// the hash of its curve, RSA with PKCS #1 v1.5 and SHA-256, Ed25519) with further
1238    /// extensions as sign_ext; None when `spki` is not a SubjectPublicKeyInfo
1239    pub fn sign_key(&self, issuer: Option<&Cert>, key: &PrivateKey, extra: &[Vec<u8>]) -> Option<Vec<u8>> {
1240        let alg = key.cert_alg();
1241        let id = alg_id(alg)?;
1242        self.build(issuer, &id, extra, &mut |tbs| key.sign(alg, tbs, &[]))
1243    }
1244
1245    fn build(&self, issuer: Option<&Cert>, alg: &[u8], extra: &[Vec<u8>], sign: &mut dyn FnMut(&[u8]) -> Option<Vec<u8>>) -> Option<Vec<u8>> {
1246        let mut serial = self.serial;
1247        serial[0] &= 0x7f; // positive
1248        let subject = name(&self.cn, &self.org);
1249        let issuer_name = issuer.map_or(subject.clone(), |i| i.subject.clone());
1250        let validity = der::seq(&[&encode_time(self.not_before), &encode_time(self.not_after)]);
1251        let (spki, key_bits) = if self.spki.is_empty() {
1252            (der::seq(&[&der::seq(&[&der::oid(OID_ED25519)]), &der::bits(&self.public_key)]), Vec::from(&self.public_key[..]))
1253        } else {
1254            let mut d = Der::new(&self.spki).seq()?;
1255            d.read(der::SEQUENCE)?;
1256            let bits = Vec::from(d.bits()?);
1257            (self.spki.clone(), bits)
1258        };
1259        let ski = crypto::sha256(&key_bits);
1260        let mut exts: Vec<Vec<u8>> = Vec::new();
1261        if self.is_ca {
1262            exts.push(ext(OID_BASIC, true, &der::seq(&[&der::boolean(true), &der::small_int(0)])));
1263            exts.push(ext(OID_KEY_USAGE, true, &der::tlv(der::BIT_STRING, &[1, KU_KEY_CERT_SIGN | KU_CRL_SIGN])));
1264        } else {
1265            exts.push(ext(OID_BASIC, true, &der::seq(&[])));
1266            exts.push(ext(OID_KEY_USAGE, true, &der::tlv(der::BIT_STRING, &[7, KU_DIGITAL_SIGNATURE])));
1267            let mut eku: Vec<Vec<u8>> = Vec::new();
1268            if self.server_auth {
1269                eku.push(der::oid(OID_SERVER_AUTH));
1270            }
1271            if self.client_auth {
1272                eku.push(der::oid(OID_CLIENT_AUTH));
1273            }
1274            if self.ocsp_signing {
1275                eku.push(der::oid(OID_OCSP_SIGNING));
1276                exts.push(ext(OID_OCSP_NOCHECK, false, &[der::NULL, 0]));
1277            }
1278            if self.must_staple {
1279                exts.push(ext(OID_TLS_FEATURE, false, &der::seq(&[&der::small_int(TLS_FEATURE_STATUS_REQUEST as u64)])));
1280            }
1281            if !eku.is_empty() {
1282                let parts: Vec<&[u8]> = eku.iter().map(|v| v.as_slice()).collect();
1283                exts.push(ext(OID_EKU, false, &der::seq(&parts)));
1284            }
1285        }
1286        if !self.dns.is_empty() || !self.ips.is_empty() {
1287            let mut names: Vec<Vec<u8>> = self.dns.iter().map(|d| der::tlv(0x82, d.as_bytes())).collect();
1288            for ip in &self.ips {
1289                names.push(match ip {
1290                    IpAddr::V4(a) => der::tlv(0x87, a),
1291                    IpAddr::V6(a) => der::tlv(0x87, a),
1292                });
1293            }
1294            let parts: Vec<&[u8]> = names.iter().map(|v| v.as_slice()).collect();
1295            exts.push(ext(OID_SAN, false, &der::seq(&parts)));
1296        }
1297        if !self.ocsp_urls.is_empty() {
1298            let ads: Vec<Vec<u8>> = self.ocsp_urls.iter().map(|u| der::seq(&[&der::oid(OID_AD_OCSP), &der::tlv(0x86, u.as_bytes())])).collect();
1299            let parts: Vec<&[u8]> = ads.iter().map(|v| v.as_slice()).collect();
1300            exts.push(ext(OID_AIA, false, &der::seq(&parts)));
1301        }
1302        exts.push(ext(OID_SKI, false, &der::octets(&ski[..20])));
1303        let aki_src = issuer.map_or(ski[..20].to_vec(), |i| if i.ski.is_empty() { crypto::sha256(&i.public_key)[..20].to_vec() } else { i.ski.clone() });
1304        exts.push(ext(OID_AKI, false, &der::seq(&[&der::tlv(0x80, &aki_src)])));
1305        let oid_of = |e: &[u8]| Der::new(e).seq().and_then(|mut d| d.read(der::OID).map(Vec::from));
1306        let replaced: Vec<Vec<u8>> = extra.iter().filter_map(|e| oid_of(e)).collect();
1307        exts.retain(|e| oid_of(e).is_none_or(|o| !replaced.contains(&o)));
1308        exts.extend(extra.iter().cloned());
1309        let ext_parts: Vec<&[u8]> = exts.iter().map(|v| v.as_slice()).collect();
1310        let tbs = der::seq(&[
1311            &der::explicit(0, &der::small_int(2)),
1312            &der::int_u(&serial),
1313            alg,
1314            &issuer_name,
1315            &validity,
1316            &subject,
1317            &spki,
1318            &der::explicit(3, &der::seq(&ext_parts)),
1319        ]);
1320        let sig = sign(&tbs)?;
1321        Some(der::seq(&[&tbs, alg, &der::bits(&sig)]))
1322    }
1323}
1324
1325/// the PKCS#8 form of an Ed25519 private key (for interoperable PEM files)
1326pub fn ed25519_pkcs8(seed: &[u8; 32]) -> Vec<u8> {
1327    der::seq(&[&der::small_int(0), &der::seq(&[&der::oid(OID_ED25519)]), &der::octets(&der::octets(seed))])
1328}
1329
1330/// the seed of a PKCS#8 Ed25519 private key
1331pub fn ed25519_from_pkcs8(b: &[u8]) -> Option<[u8; 32]> {
1332    let mut d = Der::new(b).seq()?;
1333    if d.u64()? != 0 || !is_ed25519_alg(d.read(der::SEQUENCE)?) {
1334        return None;
1335    }
1336    let inner = d.read(der::OCTET_STRING)?;
1337    let seed = Der::new(inner).read(der::OCTET_STRING)?;
1338    (seed.len() == 32).then(|| {
1339        let mut s = [0u8; 32];
1340        s.copy_from_slice(seed);
1341        s
1342    })
1343}