mod der;
use core::fmt;
pub use der::ParseError;
use der::{Reader, Result, Tlv};
use crate::cert::{CertSignature, ExtendedKeyUsage, Extension, KeyUsage};
use crate::profile::{Allowed, Curve, Profile, PublicKey};
const ID_EC_PUBLIC_KEY: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01];
const RSA_ENCRYPTION: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01];
const RSASSA_PSS: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0A];
const ED25519: &[u8] = &[0x2B, 0x65, 0x70];
const SHA256: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];
const SHA384: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02];
const SHA512: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03];
const AT_CN: &[u8] = &[0x55, 0x04, 0x03];
const AT_O: &[u8] = &[0x55, 0x04, 0x0A];
const AT_OU: &[u8] = &[0x55, 0x04, 0x0B];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Oid<'a>(&'a [u8]);
impl<'a> Oid<'a> {
pub const fn as_bytes(&self) -> &'a [u8] {
self.0
}
fn write_name(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const NAMES: &[(&[u8], &str)] = &[
(ID_EC_PUBLIC_KEY, "id-ecPublicKey"),
(RSA_ENCRYPTION, "rsaEncryption"),
(RSASSA_PSS, "RSASSA-PSS"),
(&[0x2B, 0x81, 0x04, 0x00, 0x0A], "secp256k1"),
];
if let Some(e) = Extension::from_oid(self.0) {
write!(f, " ({e})")
} else if let Some(e) = ExtendedKeyUsage::from_oid(self.0) {
write!(f, " ({e})")
} else if let Some((_, n)) = NAMES.iter().find(|(o, _)| *o == self.0) {
write!(f, " ({n})")
} else {
Ok(())
}
}
}
impl fmt::Display for Oid<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut arcs = self.0.iter();
let mut value: u64 = 0;
let mut first = true;
let mut overflow = false;
for &b in arcs.by_ref() {
overflow |= value > (u64::MAX >> 7);
value = (value << 7) | u64::from(b & 0x7F);
if b & 0x80 != 0 {
continue;
}
if first {
let (a, b) = match value {
0..=39 => (0, value),
40..=79 => (1, value - 40),
_ => (2, value - 80),
};
write!(f, "{a}.{b}")?;
first = false;
} else {
write!(f, ".{value}")?;
}
value = 0;
}
if overflow {
f.write_str("(overflow)")?;
}
self.write_name(f)
}
}
#[derive(Clone, Copy, Debug)]
struct Ext<'a> {
oid: &'a [u8],
critical: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct Certificate<'a> {
version: u8,
serial: &'a [u8],
sig_oid: &'a [u8],
sig_params: Option<Tlv<'a>>,
not_before: i64,
not_after: i64,
subject: Tlv<'a>,
key_alg: &'a [u8],
key_params: Option<Tlv<'a>>,
key: &'a [u8],
extensions: Option<Tlv<'a>>,
key_usage: Option<u16>,
is_ca: bool,
eku: Option<Tlv<'a>>,
san: Option<Tlv<'a>>,
}
impl<'a> Certificate<'a> {
pub fn from_der(der: &'a [u8]) -> Result<Self> {
let mut top = Reader::new(der);
let cert = top.read(der::SEQUENCE, "expected a Certificate SEQUENCE")?;
top.finish("trailing data after the certificate")?;
let mut outer = cert.reader();
let tbs = outer.read(der::SEQUENCE, "expected TBSCertificate")?;
let (sig_oid, sig_params) = algorithm(&mut outer, "expected signatureAlgorithm")?;
der::bit_string(&outer.read(der::BIT_STRING, "expected signatureValue")?)?;
outer.finish("trailing data in Certificate")?;
let mut fields = tbs.reader();
let version = match fields.optional(0xA0)? {
None => 1,
Some(explicit) => {
let mut version_field = explicit.reader();
let int = version_field.read(der::INTEGER, "expected version INTEGER")?;
version_field.finish("trailing data in version")?;
match der::integer(&int)? {
[1] => 2,
[2] => 3,
_ => return Err(int.err("version must be v2 or v3 when present (DER omits v1)")),
}
}
};
let serial = der::integer(&fields.read(der::INTEGER, "expected serialNumber")?)?;
let (inner_oid, inner_params) = algorithm(&mut fields, "expected signature AlgorithmIdentifier")?;
if inner_oid != sig_oid || inner_params.map(|p| p.content) != sig_params.map(|p| p.content) {
return Err(ParseError::new(
tbs.offset,
"signature algorithms in TBSCertificate and Certificate differ",
));
}
fields.read(der::SEQUENCE, "expected issuer Name")?;
let validity = fields.read(der::SEQUENCE, "expected Validity")?;
let mut times = validity.reader();
let not_before = der::time(×.any()?)?;
let not_after = der::time(×.any()?)?;
times.finish("trailing data in Validity")?;
let subject = fields.read(der::SEQUENCE, "expected subject Name")?;
validate_name(&subject)?;
let spki = fields.read(der::SEQUENCE, "expected SubjectPublicKeyInfo")?;
let mut spki_fields = spki.reader();
let (key_alg, key_params) = algorithm(&mut spki_fields, "expected public key AlgorithmIdentifier")?;
let (key, _) = der::bit_string(&spki_fields.read(der::BIT_STRING, "expected subjectPublicKey")?)?;
spki_fields.finish("trailing data in SubjectPublicKeyInfo")?;
fields.optional(0x81)?;
fields.optional(0x82)?;
let extensions = match fields.optional(0xA3)? {
None => None,
Some(explicit) => {
let mut list_field = explicit.reader();
let list = list_field.read(der::SEQUENCE, "expected Extensions SEQUENCE")?;
list_field.finish("trailing data in extensions")?;
if list.content.is_empty() {
return Err(list.err("empty Extensions"));
}
Some(list)
}
};
fields.finish("trailing data in TBSCertificate")?;
let mut cert = Self {
version,
serial,
sig_oid,
sig_params,
not_before,
not_after,
subject,
key_alg,
key_params,
key,
extensions,
key_usage: None,
is_ca: false,
eku: None,
san: None,
};
cert.read_extensions()?;
Ok(cert)
}
fn read_extensions(&mut self) -> Result<()> {
let Some(list) = self.extensions else { return Ok(()) };
let mut r = list.reader();
while !r.is_empty() {
let ext = r.read(der::SEQUENCE, "expected Extension")?;
let mut e = ext.reader();
let oid = der::oid(&e.read(der::OID, "expected extnID")?)?;
if let Some(c) = e.optional(der::BOOLEAN)? {
if !der::boolean(&c)? {
return Err(c.err("critical FALSE must be omitted in DER"));
}
}
let value = e.read(der::OCTET_STRING, "expected extnValue")?;
e.finish("trailing data in Extension")?;
let mut v = value.reader();
let inner = v.any()?;
v.finish("trailing data in extension value")?;
match Extension::from_oid(oid) {
Some(Extension::KeyUsage) if self.key_usage.is_none() => {
self.key_usage = Some(key_usage(&inner)?);
}
Some(Extension::BasicConstraints) if !self.is_ca => self.is_ca = basic_constraints(&inner)?,
Some(Extension::ExtendedKeyUsage) if self.eku.is_none() => {
self.eku = Some(seq_of(&inner, der::OID, "malformed ExtendedKeyUsage")?);
}
Some(Extension::SubjectAltName) if self.san.is_none() => {
self.san = Some(general_names(&inner)?);
}
_ => {}
}
}
Ok(())
}
fn exts(&self) -> impl Iterator<Item = Ext<'a>> + 'a {
let mut r = self.extensions.map_or(Reader::new(&[]), |l| l.reader());
core::iter::from_fn(move || {
let ext = r.any().ok()?;
let mut e = ext.reader();
let oid = e.any().ok()?.content;
let critical = e.peek_tag() == Some(der::BOOLEAN);
Some(Ext { oid, critical })
})
}
fn has(&self, ext: Extension) -> bool {
self.exts().any(|e| e.oid == ext.oid())
}
pub const fn version(&self) -> u8 {
self.version
}
pub fn public_key(&self) -> Option<PublicKey> {
match self.key_alg {
ID_EC_PUBLIC_KEY => {
let p = self.key_params?;
let curve = (p.tag == der::OID).then(|| Curve::from_oid(p.content)).flatten()?;
ec_point_fits(curve, self.key).then_some(PublicKey::Ec(curve))
}
RSA_ENCRYPTION
if !self.key_params.is_some_and(|p| p.tag == der::NULL && p.content.is_empty()) =>
{
None
}
RSA_ENCRYPTION | RSASSA_PSS => rsa_bits(self.key).map(PublicKey::Rsa),
ED25519 if self.key_params.is_none() && self.key.len() == 32 => Some(PublicKey::Ed25519),
_ => None,
}
}
pub fn signature(&self) -> Option<CertSignature> {
let p = self.sig_params;
let absent = p.is_none();
let null_or_absent = p.is_none_or(|p| p.tag == der::NULL && p.content.is_empty());
match self.sig_oid {
[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, n @ 0x02..=0x04] if absent => Some(match n {
0x02 => CertSignature::EcdsaSha256,
0x03 => CertSignature::EcdsaSha384,
_ => CertSignature::EcdsaSha512,
}),
[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, n @ 0x0B..=0x0D] if null_or_absent => {
Some(match n {
0x0B => CertSignature::RsaPkcs1Sha256,
0x0C => CertSignature::RsaPkcs1Sha384,
_ => CertSignature::RsaPkcs1Sha512,
})
}
RSASSA_PSS => match pss_hash(p?)? {
SHA256 => Some(CertSignature::RsaPssSha256),
SHA384 => Some(CertSignature::RsaPssSha384),
SHA512 => Some(CertSignature::RsaPssSha512),
_ => None,
},
ED25519 if absent => Some(CertSignature::Ed25519),
_ => None,
}
}
pub fn validity_days(&self) -> u32 {
let secs = self.not_after.saturating_sub(self.not_before).max(0);
u32::try_from((secs + 86_399) / 86_400).unwrap_or(u32::MAX)
}
pub const fn validity(&self) -> (i64, i64) {
(self.not_before, self.not_after)
}
fn attributes(&self, ty: &'static [u8]) -> impl Iterator<Item = &'a str> + 'a {
let mut rdns = self.subject.reader();
let mut atvs = Reader::new(&[]);
core::iter::from_fn(move || {
loop {
if atvs.is_empty() {
atvs = rdns.any().ok()?.reader();
}
let atv = atvs.any().ok()?;
let mut a = atv.reader();
let oid = a.any().ok()?.content;
if oid == ty {
return der::string(&a.any().ok()?).ok();
}
}
})
}
fn single(&self, ty: &'static [u8]) -> Option<&'a str> {
let mut it = self.attributes(ty);
let first = it.next()?;
it.next().is_none().then_some(first)
}
pub fn mp_id(&self) -> Option<&'a str> {
self.single(AT_OU)
}
pub fn organization(&self) -> Option<&'a str> {
self.single(AT_O)
}
pub fn common_name(&self) -> Option<&'a str> {
self.single(AT_CN)
}
fn names(&self, tag: u8) -> impl Iterator<Item = &'a str> + 'a {
let mut r = self.san.map_or(Reader::new(&[]), |s| s.reader());
core::iter::from_fn(move || {
loop {
let gn = r.any().ok()?;
if gn.tag == tag {
return core::str::from_utf8(gn.content).ok();
}
}
})
}
pub fn dns_names(&self) -> impl Iterator<Item = &'a str> + 'a {
self.names(0x82)
}
pub fn uris(&self) -> impl Iterator<Item = &'a str> + 'a {
self.names(0x86)
}
pub fn endpoint_uri(&self) -> Option<&'a str> {
let mut it = self.uris();
let first = it.next()?;
it.next().is_none().then_some(first)
}
pub const fn is_ca(&self) -> bool {
self.is_ca
}
pub fn has_key_usage(&self, usage: KeyUsage) -> bool {
self.key_usage.is_some_and(|bits| bits & (1 << usage.bit()) != 0)
}
fn eku_oids(&self) -> impl Iterator<Item = &'a [u8]> + 'a {
let mut r = self.eku.map_or(Reader::new(&[]), |e| e.reader());
core::iter::from_fn(move || r.any().ok().map(|t| t.content))
}
pub fn has_extended_key_usage(&self, purpose: ExtendedKeyUsage) -> bool {
self.eku_oids().any(|o| o == purpose.oid())
}
}
fn algorithm<'a>(r: &mut Reader<'a>, what: &'static str) -> Result<(&'a [u8], Option<Tlv<'a>>)> {
let seq = r.read(der::SEQUENCE, what)?;
let mut a = seq.reader();
let oid = der::oid(&a.read(der::OID, "expected algorithm OID")?)?;
let params = if a.is_empty() { None } else { Some(a.any()?) };
a.finish("trailing data in AlgorithmIdentifier")?;
Ok((oid, params))
}
fn validate_name(name: &Tlv<'_>) -> Result<()> {
let mut rdns = name.reader();
while !rdns.is_empty() {
let rdn = rdns.read(der::SET, "expected RelativeDistinguishedName SET")?;
let mut atvs = rdn.reader();
if atvs.is_empty() {
return Err(rdn.err("empty RelativeDistinguishedName"));
}
while !atvs.is_empty() {
let atv = atvs.read(der::SEQUENCE, "expected AttributeTypeAndValue")?;
let mut a = atv.reader();
let oid = der::oid(&a.read(der::OID, "expected attribute type")?)?;
let value = a.any()?;
a.finish("trailing data in AttributeTypeAndValue")?;
if [AT_CN, AT_O, AT_OU].contains(&oid) {
der::string(&value)?;
}
}
}
Ok(())
}
fn key_usage(inner: &Tlv<'_>) -> Result<u16> {
if inner.tag != der::BIT_STRING {
return Err(inner.err("malformed KeyUsage"));
}
let (bits, unused) = der::bit_string(inner)?;
let last_used = bits.last().is_some_and(|&b| b & (1 << unused) != 0);
if bits.len() > 2 || !last_used {
return Err(inner.err("KeyUsage is not a DER named-bit list"));
}
let mut out = 0u16;
for (i, &byte) in bits.iter().enumerate() {
for j in 0..8 {
if byte & (0x80 >> j) != 0 {
out |= 1 << (i * 8 + j);
}
}
}
Ok(out)
}
fn basic_constraints(inner: &Tlv<'_>) -> Result<bool> {
if inner.tag != der::SEQUENCE {
return Err(inner.err("malformed BasicConstraints"));
}
let mut r = inner.reader();
let ca = match r.optional(der::BOOLEAN)? {
Some(b) if der::boolean(&b)? => true,
Some(b) => return Err(b.err("cA FALSE must be omitted in DER")),
None => false,
};
if let Some(p) = r.optional(der::INTEGER)? {
der::integer(&p)?;
}
r.finish("trailing data in BasicConstraints")?;
Ok(ca)
}
fn seq_of<'a>(inner: &Tlv<'a>, tag: u8, what: &'static str) -> Result<Tlv<'a>> {
if inner.tag != der::SEQUENCE || inner.content.is_empty() {
return Err(inner.err(what));
}
let mut r = inner.reader();
while !r.is_empty() {
let item = r.read(tag, what)?;
if tag == der::OID {
der::oid(&item)?;
}
}
Ok(*inner)
}
fn general_names<'a>(inner: &Tlv<'a>) -> Result<Tlv<'a>> {
if inner.tag != der::SEQUENCE || inner.content.is_empty() {
return Err(inner.err("malformed SubjectAltName"));
}
let mut r = inner.reader();
while !r.is_empty() {
let gn = r.any()?;
match gn.tag {
0x81 | 0x82 | 0x86 => {
der::ia5(&gn)?;
}
0xA0 | 0xA3 | 0xA4 | 0xA5 | 0x87 | 0x88 => {}
_ => return Err(gn.err("unknown GeneralName")),
}
}
Ok(*inner)
}
fn ec_point_fits(curve: Curve, point: &[u8]) -> bool {
let n = match curve {
Curve::P256 | Curve::BrainpoolP256r1 => 32,
Curve::P384 | Curve::BrainpoolP384r1 => 48,
Curve::BrainpoolP512r1 => 64,
Curve::P521 => 66,
};
match point.first() {
Some(0x04) => point.len() == 1 + 2 * n,
Some(0x02 | 0x03) => point.len() == 1 + n,
_ => false,
}
}
fn rsa_bits(key: &[u8]) -> Option<u16> {
let mut r = Reader::new(key);
let seq = r.read(der::SEQUENCE, "").ok()?;
let mut s = seq.reader();
let modulus = der::integer(&s.read(der::INTEGER, "").ok()?).ok()?;
der::integer(&s.read(der::INTEGER, "").ok()?).ok()?;
s.finish("").ok()?;
r.finish("").ok()?;
let modulus = match modulus {
[0, rest @ ..] => rest,
[first, ..] if first & 0x80 != 0 => return None,
m => m,
};
let lead = modulus.first()?.leading_zeros();
let bits = (modulus.len() * 8).checked_sub(usize::try_from(lead).ok()?)?;
Some(u16::try_from(bits).unwrap_or(u16::MAX))
}
fn pss_hash(params: Tlv<'_>) -> Option<&[u8]> {
fn hash_alg<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
let alg = r.read(der::SEQUENCE, "").ok()?;
let mut a = alg.reader();
let oid = der::oid(&a.read(der::OID, "").ok()?).ok()?;
if let Some(p) = a.optional(der::NULL).ok()? {
if !p.content.is_empty() {
return None;
}
}
a.finish("").ok()?;
Some(oid)
}
if params.tag != der::SEQUENCE {
return None;
}
let mut r = params.reader();
let hash = hash_alg(&mut r.read(0xA0, "").ok()?.reader())?;
let mgf = r.read(0xA1, "").ok()?;
let mut m = mgf.reader();
let mut mgf_seq = m.read(der::SEQUENCE, "").ok()?.reader();
let mgf1 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x08];
if der::oid(&mgf_seq.read(der::OID, "").ok()?).ok()? != mgf1 || hash_alg(&mut mgf_seq)? != hash {
return None;
}
let salt = der::integer(&r.read(0xA2, "").ok()?.reader().read(der::INTEGER, "").ok()?).ok()?;
let expected: &[u8] = match hash {
SHA256 => &[32],
SHA384 => &[48],
SHA512 => &[64],
_ => return None,
};
(salt == expected && r.is_empty()).then_some(hash)
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
(0..=haystack.len().saturating_sub(needle.len()))
.any(|i| haystack.get(i..i + needle.len()) == Some(needle))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Escaped<'a>(&'a str);
impl fmt::Display for Escaped<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for c in self.0.chars() {
if c.is_ascii_graphic() || c == ' ' {
fmt::Write::write_char(f, c)?;
} else {
write!(f, "\\u{{{:x}}}", u32::from(c))?;
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CertViolation<'a> {
Version(u8),
SerialTooLong(usize),
Signature(CertSignature),
UnknownSignature(Oid<'a>),
Key(PublicKey),
UnknownKey(Oid<'a>),
ExplicitCurve,
Validity {
days: u32,
max: u32,
},
ValidityInverted,
ExtensionMissing(Extension),
ExtensionNotAllowed(Oid<'a>),
ExtensionDuplicate(Oid<'a>),
Criticality {
extension: Oid<'a>,
critical: bool,
},
KeyUsageMissing(KeyUsage),
ExtendedKeyUsageMissing(ExtendedKeyUsage),
ExtendedKeyUsageNotAllowed(Oid<'a>),
CaCertificate,
Wildcard(&'a str),
TooManyDnsNames {
count: usize,
max: u8,
},
DnsNameMissing,
UriCount {
count: usize,
expected: u8,
},
Organization {
expected: &'static str,
found: Option<&'a str>,
},
OrganizationalUnit {
count: usize,
},
CommonName {
expected: &'static str,
},
}
impl fmt::Display for CertViolation<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Version(v) => write!(f, "X.509 v{v} certificate, v3 required"),
Self::SerialTooLong(n) => write!(f, "serial number of {n} octets, at most 20 allowed"),
Self::Signature(s) => write!(f, "certificate signature {s} is not allowed"),
Self::UnknownSignature(o) => write!(f, "certificate signature algorithm {o} is not supported"),
Self::Key(k) => write!(f, "certificate key {k} is not allowed"),
Self::UnknownKey(o) => write!(f, "certificate key {o} is not supported"),
Self::ExplicitCurve => f.write_str("EC key with explicit parameters, a named curve is required"),
Self::Validity { days, max } => {
write!(f, "certificate valid for {days} days, at most {max} allowed")
}
Self::ValidityInverted => f.write_str("notAfter is before notBefore"),
Self::ExtensionMissing(e) => write!(f, "extension {e} is required"),
Self::ExtensionNotAllowed(o) => write!(f, "extension {o} is not allowed"),
Self::ExtensionDuplicate(o) => write!(f, "extension {o} appears more than once"),
Self::Criticality { extension, critical: true } => {
write!(f, "extension {extension} must be critical")
}
Self::Criticality { extension, critical: false } => {
write!(f, "extension {extension} must not be critical")
}
Self::KeyUsageMissing(u) => write!(f, "KeyUsage {u} is required"),
Self::ExtendedKeyUsageMissing(e) => write!(f, "ExtendedKeyUsage {e} is required"),
Self::ExtendedKeyUsageNotAllowed(o) => write!(f, "ExtendedKeyUsage {o} is not allowed"),
Self::CaCertificate => f.write_str("a CA certificate (cA = TRUE) is not allowed"),
Self::Wildcard(s) => write!(f, "wildcard in SubjectAltName entry \"{}\"", Escaped(s)),
Self::TooManyDnsNames { count, max } => {
write!(f, "{count} DNS names in SubjectAltName, at most {max} allowed")
}
Self::DnsNameMissing => f.write_str("a server certificate needs a DNS name in SubjectAltName"),
Self::UriCount { count, expected } => {
write!(f, "{count} URIs in SubjectAltName, exactly {expected} required (the AS4 endpoint)")
}
Self::Organization { expected, found: Some(o) } => {
write!(f, "organisation (O) \"{}\", \"{expected}\" required", Escaped(o))
}
Self::Organization { expected, found: None } => {
write!(f, "organisation (O) \"{expected}\" required exactly once")
}
Self::OrganizationalUnit { count } => {
write!(f, "{count} organisational units (OU), exactly one (the MP-ID) required")
}
Self::CommonName { expected } => write!(f, "common name (CN) must contain \"{expected}\""),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CertReport<'a> {
items: [Option<CertViolation<'a>>; CertReport::CAPACITY],
len: usize,
truncated: bool,
}
impl<'a> CertReport<'a> {
pub const CAPACITY: usize = 16;
const fn new() -> Self {
Self { items: [None; Self::CAPACITY], len: 0, truncated: false }
}
fn push(&mut self, v: CertViolation<'a>) {
match self.items.get_mut(self.len) {
Some(slot) => {
*slot = Some(v);
self.len += 1;
}
None => self.truncated = true,
}
}
pub const fn is_ok(&self) -> bool {
self.len == 0 && !self.truncated
}
pub const fn truncated(&self) -> bool {
self.truncated
}
pub fn violations(&self) -> impl Iterator<Item = CertViolation<'a>> + '_ {
self.items.iter().take(self.len).filter_map(|v| *v)
}
}
impl Profile {
#[allow(clippy::too_many_lines)]
pub fn check_certificate<'a>(&self, cert: &Certificate<'a>) -> CertReport<'a> {
let rules = &self.cert;
let mut r = CertReport::new();
if cert.version != 3 {
r.push(CertViolation::Version(cert.version));
}
if cert.serial.len() > 20 {
r.push(CertViolation::SerialTooLong(cert.serial.len()));
}
if matches!(rules.signatures, Allowed::Only { .. }) {
match cert.signature() {
Some(s) if !rules.signatures.allows(&s) => r.push(CertViolation::Signature(s)),
Some(_) => {}
None => r.push(CertViolation::UnknownSignature(Oid(cert.sig_oid))),
}
}
if matches!(rules.keys, Allowed::Only { .. }) {
match cert.public_key() {
Some(k) if !rules.keys.iter().any(|rule| rule.accepts(k)) => r.push(CertViolation::Key(k)),
Some(_) => {}
None => match cert.key_params {
Some(p) if cert.key_alg == ID_EC_PUBLIC_KEY && p.tag == der::OID => {
r.push(CertViolation::UnknownKey(Oid(p.content)));
}
_ if cert.key_alg == ID_EC_PUBLIC_KEY => r.push(CertViolation::ExplicitCurve),
_ => r.push(CertViolation::UnknownKey(Oid(cert.key_alg))),
},
}
}
if cert.not_after < cert.not_before {
r.push(CertViolation::ValidityInverted);
} else if let Some(max) = rules.max_validity_days {
if cert.not_after - cert.not_before > i64::from(max) * 86_400 {
r.push(CertViolation::Validity { days: cert.validity_days(), max });
}
}
for (i, ext) in cert.exts().enumerate() {
match cert.exts().take(i).filter(|e| e.oid == ext.oid).count() {
0 => {}
1 => {
r.push(CertViolation::ExtensionDuplicate(Oid(ext.oid)));
continue;
}
_ => continue,
}
let known = Extension::from_oid(ext.oid);
if matches!(rules.extensions, Allowed::Only { .. })
&& !known.is_some_and(|k| rules.extensions.allows(&k))
{
r.push(CertViolation::ExtensionNotAllowed(Oid(ext.oid)));
continue;
}
if let (Some(critical), Some(k)) = (rules.critical, known) {
let must = critical.contains(&k);
if ext.critical != must {
r.push(CertViolation::Criticality { extension: Oid(ext.oid), critical: must });
}
}
}
let required = rules.extensions.required();
for &ext in required {
if !cert.has(ext) {
r.push(CertViolation::ExtensionMissing(ext));
}
}
let reported = |e: Extension| required.contains(&e) && !cert.has(e);
if !reported(Extension::KeyUsage) {
for &usage in rules.key_usage {
if !cert.has_key_usage(usage) {
r.push(CertViolation::KeyUsageMissing(usage));
}
}
}
if let Allowed::Only { required: must, .. } = rules.extended_key_usage {
if !reported(Extension::ExtendedKeyUsage) {
for &purpose in must {
if !cert.has_extended_key_usage(purpose) {
r.push(CertViolation::ExtendedKeyUsageMissing(purpose));
}
}
}
for oid in cert.eku_oids() {
if !ExtendedKeyUsage::from_oid(oid).is_some_and(|e| rules.extended_key_usage.allows(&e)) {
r.push(CertViolation::ExtendedKeyUsageNotAllowed(Oid(oid)));
}
}
}
if rules.end_entity && cert.is_ca {
r.push(CertViolation::CaCertificate);
}
let san = &rules.san;
if !san.wildcards {
for name in cert.names(0x81).chain(cert.dns_names()).chain(cert.uris()) {
if name.bytes().any(|b| b == b'*') {
r.push(CertViolation::Wildcard(name));
}
}
}
let dns = cert.dns_names().count();
if let Some(max) = san.max_dns_names {
if dns > usize::from(max) {
r.push(CertViolation::TooManyDnsNames { count: dns, max });
}
}
if san.dns_name_for_server_auth
&& dns == 0
&& cert.has_extended_key_usage(ExtendedKeyUsage::ServerAuth)
{
r.push(CertViolation::DnsNameMissing);
}
if let Some(expected) = san.uris {
let count = cert.uris().count();
if count != usize::from(expected) {
r.push(CertViolation::UriCount { count, expected });
}
}
let subject = &rules.subject;
if let Some(expected) = subject.organization {
let found = cert.organization();
if found != Some(expected) {
r.push(CertViolation::Organization { expected, found });
}
}
if subject.organizational_unit {
let count = cert.attributes(AT_OU).count();
if count != 1 {
r.push(CertViolation::OrganizationalUnit { count });
}
}
if let Some(expected) = subject.common_name_contains {
let marked = cert.common_name().is_some_and(|cn| {
cn.as_bytes().get(1..).is_some_and(|rest| contains(rest, expected.as_bytes()))
});
if !marked {
r.push(CertViolation::CommonName { expected });
}
}
r
}
}