git clone https://garage44.eu/jeroen/pinnacle.git.. /tls/src/x509.rs
//! X.509 certificates (RFC 5280), as far as a TLS client needs them: what a
//! certificate says (who, whose key, signed by whom, valid when, for which
//! names, whether it may sign others), and whether a chain from a server's
//! certificate reaches a root this device trusts.
use crate::der::{self, Reader};
use alloc::vec::Vec;
use pinnacle_crypto::rsa::{self, Hash};
use pinnacle_crypto::{ecdsa, ed25519};
/// A certificate's public key.
#[derive(Clone, Copy, Debug)]
pub enum Key<'a> {
Rsa {
n: &'a [u8],
e: &'a [u8],
},
/// An uncompressed point on P-256 or P-384.
P256(&'a [u8]),
P384(&'a [u8]),
Ed25519(&'a [u8; 32]),
}
/// How a certificate is signed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Algorithm {
RsaPkcs1(Hash),
Ecdsa(Hash),
Ed25519,
}
#[derive(Clone, Debug)]
pub struct Certificate<'a> {
/// The signed part, as it was encoded.
pub tbs: &'a [u8],
pub algorithm: Algorithm,
pub signature: &'a [u8],
/// The issuer's and the subject's names, as encoded: compared whole.
pub issuer: &'a [u8],
pub subject: &'a [u8],
/// Seconds since 1970.
pub not_before: i64,
pub not_after: i64,
pub key: Key<'a>,
/// Whether it may sign other certificates (basic constraints), and
/// how many below it may.
pub ca: bool,
pub path_len: Option<u8>,
/// Key usage, when given: whether it may sign certificates.
pub signs_certificates: Option<bool>,
/// Whether it is for TLS servers, when extended key usage says.
pub server_auth: Option<bool>,
/// The DNS names it is for.
pub names: Vec<&'a str>,
}
const RSA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];
const RSA_SHA256: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b];
const RSA_SHA384: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0c];
const RSA_SHA512: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0d];
const EC: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
const P256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07];
const P384: &[u8] = &[0x2b, 0x81, 0x04, 0x00, 0x22];
const ECDSA_SHA256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
const ECDSA_SHA384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
const ECDSA_SHA512: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x04];
/// Ed25519 (RFC 8410), as a key and as a signature alike.
pub(crate) const ED25519: &[u8] = &[0x2b, 0x65, 0x70];
const KEY_USAGE: &[u8] = &[0x55, 0x1d, 0x0f];
const SUBJECT_ALT_NAME: &[u8] = &[0x55, 0x1d, 0x11];
const BASIC_CONSTRAINTS: &[u8] = &[0x55, 0x1d, 0x13];
const EXTENDED_KEY_USAGE: &[u8] = &[0x55, 0x1d, 0x25];
const SERVER_AUTH: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01];
fn algorithm(value: &[u8]) -> Option<Algorithm> {
let oid = Reader::new(value).expect(der::OID)?;
Some(match oid {
RSA_SHA256 => Algorithm::RsaPkcs1(Hash::Sha256),
RSA_SHA384 => Algorithm::RsaPkcs1(Hash::Sha384),
RSA_SHA512 => Algorithm::RsaPkcs1(Hash::Sha512),
ECDSA_SHA256 => Algorithm::Ecdsa(Hash::Sha256),
ECDSA_SHA384 => Algorithm::Ecdsa(Hash::Sha384),
ECDSA_SHA512 => Algorithm::Ecdsa(Hash::Sha512),
ED25519 => Algorithm::Ed25519,
_ => return None,
})
}
/// A BIT STRING's bytes: whole bytes only.
fn bits(value: &[u8]) -> Option<&[u8]> {
let (&unused, rest) = value.split_first()?;
(unused == 0).then_some(rest)
}
/// Days since 1970 of a date (Howard Hinnant's days-from-civil).
fn days(year: i64, month: i64, day: i64) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// A UTCTime (YYMMDDHHMMSSZ) or GeneralizedTime (YYYYMMDDHHMMSSZ), as
/// seconds since 1970.
fn time(tlv: der::Tlv) -> Option<i64> {
let text = core::str::from_utf8(tlv.value).ok()?;
let text = text.strip_suffix('Z')?;
let (year, rest) = match tlv.tag {
der::UTC_TIME if text.len() == 12 => {
let yy: i64 = text[..2].parse().ok()?;
(if yy < 50 { 2000 + yy } else { 1900 + yy }, &text[2..])
}
der::GENERALIZED_TIME if text.len() == 14 => (text[..4].parse().ok()?, &text[4..]),
_ => return None,
};
if !rest.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let field = |i: usize| rest[i..i + 2].parse::<i64>().ok();
let (month, day, hour, minute, second) = (field(0)?, field(2)?, field(4)?, field(6)?, field(8)?);
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
return None;
}
Some(days(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second)
}
fn public_key(spki: &[u8]) -> Option<Key<'_>> {
let mut r = Reader::new(spki);
let mut alg = Reader::new(r.expect(der::SEQUENCE)?);
let key = bits(r.expect(der::BIT_STRING)?)?;
match alg.expect(der::OID)? {
RSA => {
let mut k = Reader::new(Reader::new(key).expect(der::SEQUENCE)?);
let n = k.expect(der::INTEGER)?;
let e = k.expect(der::INTEGER)?;
Some(Key::Rsa { n, e })
}
EC => match alg.expect(der::OID)? {
P256 if key.len() == 65 => Some(Key::P256(key)),
P384 if key.len() == 97 => Some(Key::P384(key)),
_ => None,
},
ED25519 => Some(Key::Ed25519(key.try_into().ok()?)),
_ => None,
}
}
impl<'a> Certificate<'a> {
/// Reads a certificate. `None` for one this cannot read, or one with a
/// critical extension it does not know, which must not be accepted.
pub fn parse(der: &'a [u8]) -> Option<Certificate<'a>> {
let mut outer = Reader::new(Reader::new(der).expect(der::SEQUENCE)?);
let tbs = outer.read()?;
if tbs.tag != der::SEQUENCE {
return None;
}
let algorithm = algorithm(outer.expect(der::SEQUENCE)?)?;
let signature = bits(outer.expect(der::BIT_STRING)?)?;
let mut t = Reader::new(tbs.value);
// Version 3 only: [0] EXPLICIT INTEGER 2.
let version = Reader::new(t.optional(0xa0)?.value).expect(der::INTEGER)?;
if version != [2] {
return None;
}
t.expect(der::INTEGER)?; // the serial number
if self::algorithm(t.expect(der::SEQUENCE)?)? != algorithm {
return None;
}
let issuer = t.read()?.whole;
let mut validity = Reader::new(t.expect(der::SEQUENCE)?);
let not_before = time(validity.read()?)?;
let not_after = time(validity.read()?)?;
let subject = t.read()?.whole;
let key = public_key(t.expect(der::SEQUENCE)?)?;
let mut cert = Certificate {
tbs: tbs.whole,
algorithm,
signature,
issuer,
subject,
not_before,
not_after,
key,
ca: false,
path_len: None,
signs_certificates: None,
server_auth: None,
names: Vec::new(),
};
// Unique identifiers, then extensions.
t.optional(0x81);
t.optional(0x82);
if let Some(extensions) = t.optional(0xa3) {
let mut list = Reader::new(Reader::new(extensions.value).expect(der::SEQUENCE)?);
while !list.is_empty() {
let mut ext = Reader::new(list.expect(der::SEQUENCE)?);
let oid = ext.expect(der::OID)?;
let critical = ext.optional(der::BOOLEAN).is_some_and(|b| b.value == [0xff]);
let value = ext.expect(der::OCTET_STRING)?;
if !cert.extension(oid, value)? && critical {
return None;
}
}
}
Some(cert)
}
/// Reads an extension it knows. `Some(false)` for one it does not,
/// `None` for one it knows and cannot read.
fn extension(&mut self, oid: &[u8], value: &'a [u8]) -> Option<bool> {
match oid {
BASIC_CONSTRAINTS => {
let mut r = Reader::new(Reader::new(value).expect(der::SEQUENCE)?);
self.ca = r.optional(der::BOOLEAN).is_some_and(|b| b.value == [0xff]);
if let Some(len) = r.optional(der::INTEGER) {
self.path_len = (len.value.len() == 1).then_some(len.value[0]);
}
}
KEY_USAGE => {
let usage = Reader::new(value).expect(der::BIT_STRING)?;
// keyCertSign is bit 5 of the first byte (bit 0 its top).
let first = usage.get(1).copied().unwrap_or(0);
self.signs_certificates = Some(first & 0x04 != 0);
}
EXTENDED_KEY_USAGE => {
let mut r = Reader::new(Reader::new(value).expect(der::SEQUENCE)?);
let mut server = false;
while !r.is_empty() {
server |= r.expect(der::OID)? == SERVER_AUTH;
}
self.server_auth = Some(server);
}
SUBJECT_ALT_NAME => {
let mut r = Reader::new(Reader::new(value).expect(der::SEQUENCE)?);
while !r.is_empty() {
let name = r.read()?;
// dNSName: [2] IA5String.
if name.tag == 0x82 {
self.names.push(core::str::from_utf8(name.value).ok()?);
}
}
}
_ => return Some(false),
}
Some(true)
}
/// Whether `child`'s signature is by this certificate's key.
pub fn signed(&self, child: &Certificate) -> bool {
verify(&self.key, child.algorithm, child.tbs, child.signature)
}
/// Whether it is for `host` (its DNS names; `*.` stands for one label).
pub fn for_host(&self, host: &str) -> bool {
self.names.iter().any(|name| name_matches(name, host))
}
}
/// Whether `signature` over `message` is by `key`, signed the way
/// `algorithm` says.
pub fn verify(key: &Key, algorithm: Algorithm, message: &[u8], signature: &[u8]) -> bool {
match (algorithm, key) {
(Algorithm::RsaPkcs1(hash), Key::Rsa { n, e }) => {
rsa::PublicKey::new(n, e).is_some_and(|k| k.verify_pkcs1(hash, message, signature))
}
(Algorithm::Ecdsa(hash), Key::P256(point)) => ecdsa::verify(
&ecdsa::P256,
point,
&hash.digest(&[message])[..hash.size()],
signature,
),
(Algorithm::Ecdsa(hash), Key::P384(point)) => ecdsa::verify(
&ecdsa::P384,
point,
&hash.digest(&[message])[..hash.size()],
signature,
),
(Algorithm::Ed25519, Key::Ed25519(public)) => signature
.try_into()
.is_ok_and(|signature| ed25519::verify(public, message, signature)),
_ => false,
}
}
/// A certificate's DNS name against the host asked for, case aside. A
/// wildcard stands for exactly the leftmost label, never for an IP address
/// or a top-level domain.
fn name_matches(name: &str, host: &str) -> bool {
let host = host.trim_end_matches('.');
if let Some(suffix) = name.strip_prefix("*.") {
let Some((first, rest)) = host.split_once('.') else {
return false;
};
!first.is_empty()
&& suffix.contains('.')
&& rest.eq_ignore_ascii_case(suffix)
&& !host.bytes().all(|b| b.is_ascii_digit() || b == b'.')
} else {
name.eq_ignore_ascii_case(host)
}
}
/// Why a server's certificates were not accepted.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
/// A certificate that cannot be read.
Unreadable,
/// The server's certificate is not for the host asked for.
WrongName,
/// One is not valid at this time (expired, or not yet).
Expired,
/// The server's certificate is not for TLS servers.
NotForServers,
/// The chain reaches no root this device trusts.
Untrusted,
}
/// The longest chain followed.
const MAX_DEPTH: usize = 8;
/// Checks the certificates a server sent (its own first, then any that
/// sign it) for `host` at `now` (seconds since 1970) against the roots
/// this device trusts (DER).
pub fn verify_chain(chain: &[&[u8]], roots: &[&[u8]], host: &str, now: i64) -> Result<(), Error> {
walk(
chain,
roots,
host,
|c| c.not_before <= now && now <= c.not_after,
|_| {},
)
}
/// As [`verify_chain`] with no time to check by, for a device whose clock
/// is not set yet: the chain to a root, and the span of time in which every
/// certificate of it is valid, seconds since 1970 (from, until). A time a
/// server gives over the connection is to be believed only within it.
pub fn chain_window(chain: &[&[u8]], roots: &[&[u8]], host: &str) -> Result<(i64, i64), Error> {
let mut window = (i64::MIN, i64::MAX);
walk(
chain,
roots,
host,
|_| true,
|c| {
window = (window.0.max(c.not_before), window.1.min(c.not_after));
},
)?;
if window.0 > window.1 {
return Err(Error::Expired);
}
Ok(window)
}
/// The chain from the leaf to a root, each certificate on it `valid` and
/// handed to `seen`, the root's too.
fn walk(
chain: &[&[u8]],
roots: &[&[u8]],
host: &str,
valid: impl Fn(&Certificate) -> bool,
mut seen: impl FnMut(&Certificate),
) -> Result<(), Error> {
let certs: Vec<Certificate> = chain
.iter()
.map(|c| Certificate::parse(c))
.collect::<Option<_>>()
.ok_or(Error::Unreadable)?;
let leaf = certs.first().ok_or(Error::Unreadable)?;
if !leaf.for_host(host) {
return Err(Error::WrongName);
}
if leaf.server_auth == Some(false) {
return Err(Error::NotForServers);
}
let may_sign = |c: &Certificate| c.ca && c.signs_certificates != Some(false);
let mut current = leaf;
for depth in 0..MAX_DEPTH {
if !valid(current) {
return Err(Error::Expired);
}
seen(current);
// A trusted root that signs it ends the chain.
let root = roots
.iter()
.filter_map(|r| Certificate::parse(r))
.find(|root| root.subject == current.issuer && valid(root) && root.signed(current));
if let Some(root) = root {
seen(&root);
return Ok(());
}
// Else a certificate the server sent that may sign, and does.
current = certs
.iter()
.skip(1)
.find(|c| {
c.subject == current.issuer
&& may_sign(c)
&& c.path_len.is_none_or(|len| usize::from(len) >= depth)
&& c.signed(current)
})
.ok_or(Error::Untrusted)?;
}
Err(Error::Untrusted)
}