use core::fmt;
use core::time::Duration;
use std::error::Error;
use std::time::{SystemTime, UNIX_EPOCH};
use rustls_pki_types::pem::PemObject as _;
use rustls_pki_types::{CertificateDer, TrustAnchor, UnixTime};
use sha2::{Digest as _, Sha256};
use webpki::{EndEntityCert, ExtendedKeyUsageValidator, KeyPurposeIdIter};
use x509_cert::Certificate;
use x509_cert::der::{Decode as _, Encode as _};
use x509_cert::ext::pkix::name::GeneralName;
use x509_cert::ext::pkix::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAltName, SubjectKeyIdentifier,
};
use x509_cert::spki::SubjectPublicKeyInfoRef;
use super::{KeyReference, KeyResolutionError, KeyResolver, KeyRole};
use crate::jose::{Jwk, base64url};
const EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";
const SECP256R1: &str = "1.2.840.10045.3.1.7";
const SECP384R1: &str = "1.3.132.0.34";
#[cfg(feature = "secp256k1")]
const SECP256K1: &str = "1.3.132.0.10";
const ED25519: &str = "1.3.101.112";
const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
const MIN_RSA_BITS: usize = 2048;
#[derive(Clone)]
pub struct X509Resolver {
anchors: Vec<Anchor>,
}
#[derive(Clone)]
struct Anchor {
der: CertificateDer<'static>,
not_before: i64,
not_after: i64,
}
impl X509Resolver {
pub const MAX_CHAIN_LENGTH: usize = 10;
pub fn new<I, C>(anchors: I) -> Result<Self, X509Error>
where
I: IntoIterator<Item = C>,
C: Into<Vec<u8>>,
{
let anchors = anchors
.into_iter()
.enumerate()
.map(|(index, anchor)| {
let der = CertificateDer::from(anchor.into());
let certificate = X509Certificate::parse(&der)
.map_err(|e| X509Error::invalid_certificate(index, e))?;
webpki::anchor_from_trusted_cert(&der)
.map_err(|e| X509Error::invalid_certificate(index, e))?;
if !certificate.may_issue() {
return Err(X509Error::TrustAnchorNotCa { index });
}
Ok(Anchor {
der,
not_before: certificate.not_before,
not_after: certificate.not_after,
})
})
.collect::<Result<_, _>>()?;
Ok(Self { anchors })
}
pub fn from_pem(pem: &str) -> Result<Self, X509Error> {
let anchors = CertificateDer::pem_slice_iter(pem.as_bytes())
.map(|certificate| certificate.map(|certificate| certificate.to_vec()))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| X509Error::InvalidPem(e.to_string()))?;
if anchors.is_empty() {
return Err(X509Error::InvalidPem("no certificate".to_owned()));
}
Self::new(anchors)
}
pub fn anchors(&self) -> impl Iterator<Item = &[u8]> {
self.anchors.iter().map(|anchor| anchor.der.as_ref())
}
pub fn validate(&self, chain: &[Vec<u8>], now: i64) -> Result<Jwk, X509Error> {
let (leaf_der, intermediates) = chain.split_first().ok_or(X509Error::EmptyChain)?;
if chain.len() > Self::MAX_CHAIN_LENGTH {
return Err(X509Error::ChainTooLong {
length: chain.len(),
max: Self::MAX_CHAIN_LENGTH,
});
}
let certificates = chain
.iter()
.enumerate()
.map(|(index, certificate)| {
X509Certificate::parse(certificate)
.map_err(|e| X509Error::invalid_certificate(index, e))
})
.collect::<Result<Vec<_>, _>>()?;
let leaf = &certificates[0];
if leaf.is_self_issued() {
return Err(X509Error::SelfSigned);
}
let time = u64::try_from(now)
.map(|now| UnixTime::since_unix_epoch(Duration::from_secs(now)))
.map_err(|_| X509Error::InvalidTime(now))?;
let anchors = self
.anchors
.iter()
.map(|anchor| webpki::anchor_from_trusted_cert(&anchor.der))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| X509Error::PathValidation(Box::new(e)))?;
let check_path = |path: &webpki::VerifiedPath<'_>| {
for intermediate in path.intermediate_certificates() {
let der = intermediate.der();
let may_issue = certificates
.iter()
.find(|certificate| certificate.der == der.as_ref())
.is_some_and(X509Certificate::may_issue);
if !may_issue {
return Err(webpki::Error::EndEntityUsedAsCa);
}
}
anchor_validity(path.anchor(), anchors.iter().zip(&self.anchors), now)
};
let intermediates: Vec<CertificateDer<'_>> = intermediates
.iter()
.map(|certificate| CertificateDer::from(certificate.as_slice()))
.collect();
let leaf_der = CertificateDer::from(leaf_der.as_slice());
let end_entity =
EndEntityCert::try_from(&leaf_der).map_err(|e| X509Error::invalid_certificate(0, e))?;
end_entity
.verify_for_usage(
webpki::ALL_VERIFICATION_ALGS,
&anchors,
&intermediates,
time,
AnyExtendedKeyUsage,
None,
Some(&check_path),
)
.map_err(|e| X509Error::PathValidation(Box::new(e)))?;
if !leaf.may_sign_tokens() {
return Err(X509Error::KeyUsage);
}
leaf.public_key()
}
}
impl fmt::Debug for X509Resolver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("X509Resolver")
.field("anchors", &self.anchors.len())
.finish()
}
}
#[async_trait::async_trait]
impl KeyResolver for X509Resolver {
async fn resolve_key(
&self,
key: &KeyReference,
role: KeyRole,
) -> Result<Jwk, KeyResolutionError> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| {
i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
});
self.resolve_key_at(key, role, now).await
}
async fn resolve_key_at(
&self,
key: &KeyReference,
_: KeyRole,
now: i64,
) -> Result<Jwk, KeyResolutionError> {
match key {
KeyReference::X509Chain(chain) => {
self.validate(chain, now).map_err(KeyResolutionError::new)
}
other => Err(KeyResolutionError::unsupported(other)),
}
}
}
fn anchor_validity<'a>(
used: &TrustAnchor<'_>,
configured: impl IntoIterator<Item = (&'a TrustAnchor<'a>, &'a Anchor)>,
now: i64,
) -> Result<(), webpki::Error> {
let mut error = webpki::Error::UnknownIssuer;
for (anchor, certificate) in configured {
if anchor.subject != used.subject
|| anchor.subject_public_key_info != used.subject_public_key_info
|| anchor.name_constraints != used.name_constraints
{
continue;
}
match outside_validity(now, certificate.not_before, certificate.not_after) {
None => return Ok(()),
Some(outside) => error = outside,
}
}
Err(error)
}
fn outside_validity(now: i64, not_before: i64, not_after: i64) -> Option<webpki::Error> {
let time = |seconds: i64| {
UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(seconds).unwrap_or(0)))
};
if now < not_before {
Some(webpki::Error::CertNotValidYet {
time: time(now),
not_before: time(not_before),
})
} else if now > not_after {
Some(webpki::Error::CertExpired {
time: time(now),
not_after: time(not_after),
})
} else {
None
}
}
struct AnyExtendedKeyUsage;
impl ExtendedKeyUsageValidator for AnyExtendedKeyUsage {
fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), webpki::Error> {
for purpose in iter {
purpose?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Usage {
digital_signature: bool,
non_repudiation: bool,
key_cert_sign: bool,
}
#[derive(Clone, PartialEq, Eq)]
pub struct X509Certificate {
der: Vec<u8>,
subject: String,
issuer: String,
self_issued: bool,
ca: bool,
dns_names: Vec<String>,
uris: Vec<String>,
not_before: i64,
not_after: i64,
subject_key_identifier: Option<Vec<u8>>,
authority_key_identifier: Option<Vec<u8>>,
key_usage: Option<Usage>,
public_key: Vec<u8>,
}
impl X509Certificate {
pub fn from_der(der: &[u8]) -> Result<Self, X509Error> {
Self::parse(der).map_err(|e| X509Error::invalid_certificate(0, e))
}
fn parse(der: &[u8]) -> Result<Self, x509_cert::der::Error> {
let certificate = Certificate::from_der(der)?;
let tbs = certificate.tbs_certificate();
let (mut dns_names, mut uris) = (Vec::new(), Vec::new());
if let Some((_, SubjectAltName(names))) = tbs.get_extension::<SubjectAltName>()? {
for name in names {
match name {
GeneralName::DnsName(name) => dns_names.push(name.to_string()),
GeneralName::UniformResourceIdentifier(uri) => uris.push(uri.to_string()),
_ => {}
}
}
}
let subject_key_identifier = tbs
.get_extension::<SubjectKeyIdentifier>()?
.map(|(_, identifier)| identifier.0.as_bytes().to_vec());
let authority_key_identifier = tbs
.get_extension::<AuthorityKeyIdentifier>()?
.and_then(|(_, identifier)| identifier.key_identifier)
.map(|identifier| identifier.as_bytes().to_vec());
let key_usage = tbs.get_extension::<KeyUsage>()?.map(|(_, usage)| Usage {
digital_signature: usage.digital_signature(),
non_repudiation: usage.non_repudiation(),
key_cert_sign: usage.key_cert_sign(),
});
let ca = tbs
.get_extension::<BasicConstraints>()?
.is_some_and(|(_, constraints)| constraints.ca);
let seconds = |time: x509_cert::time::Time| {
i64::try_from(time.to_unix_duration().as_secs()).unwrap_or(i64::MAX)
};
Ok(Self {
der: der.to_vec(),
subject: tbs.subject().to_string(),
issuer: tbs.issuer().to_string(),
self_issued: tbs.subject().to_der()? == tbs.issuer().to_der()?,
ca,
dns_names,
uris,
not_before: seconds(tbs.validity().not_before),
not_after: seconds(tbs.validity().not_after),
subject_key_identifier,
authority_key_identifier,
key_usage,
public_key: tbs.subject_public_key_info().to_der()?,
})
}
pub fn der(&self) -> &[u8] {
&self.der
}
pub fn subject(&self) -> &str {
&self.subject
}
pub fn issuer(&self) -> &str {
&self.issuer
}
pub fn is_self_issued(&self) -> bool {
self.self_issued
}
pub fn is_ca(&self) -> bool {
self.ca
}
pub fn dns_names(&self) -> &[String] {
&self.dns_names
}
pub fn uris(&self) -> &[String] {
&self.uris
}
pub fn not_before(&self) -> i64 {
self.not_before
}
pub fn not_after(&self) -> i64 {
self.not_after
}
pub fn subject_key_identifier(&self) -> Option<&[u8]> {
self.subject_key_identifier.as_deref()
}
pub fn authority_key_identifier(&self) -> Option<&[u8]> {
self.authority_key_identifier.as_deref()
}
pub fn sha256_thumbprint(&self) -> String {
base64url::encode(&Sha256::digest(&self.der))
}
pub fn public_key(&self) -> Result<Jwk, X509Error> {
jwk_from_spki(&self.public_key)
}
pub fn binds(&self, identifier: &str) -> bool {
let Ok(url) = url::Url::parse(identifier) else {
return false;
};
if url.scheme() != "https"
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return false;
}
let Some(url::Host::Domain(host)) = url.host() else {
return false;
};
let canonical = url.as_str();
let written_canonically = identifier == canonical
|| (url.path() == "/" && canonical.strip_suffix('/') == Some(identifier));
written_canonically
&& self
.dns_names
.iter()
.any(|name| !name.contains('*') && name.eq_ignore_ascii_case(host))
}
fn may_issue(&self) -> bool {
self.ca && self.key_usage.is_none_or(|usage| usage.key_cert_sign)
}
fn may_sign_tokens(&self) -> bool {
self.key_usage.is_none_or(|usage| {
(usage.digital_signature || usage.non_repudiation) && !usage.key_cert_sign
})
}
}
impl fmt::Debug for X509Certificate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("X509Certificate")
.field("subject", &self.subject)
.field("issuer", &self.issuer)
.field("dns_names", &self.dns_names)
.field("uris", &self.uris)
.field("not_before", &self.not_before)
.field("not_after", &self.not_after)
.finish_non_exhaustive()
}
}
fn jwk_from_spki(der: &[u8]) -> Result<Jwk, X509Error> {
let invalid = |e: &dyn fmt::Display| X509Error::InvalidKey(e.to_string());
let spki = SubjectPublicKeyInfoRef::from_der(der).map_err(|e| invalid(&e))?;
let key = spki.subject_public_key.raw_bytes();
let algorithm = spki.algorithm.oid.to_string();
match algorithm.as_str() {
EC_PUBLIC_KEY => {
let curve = spki
.algorithm
.parameters_oid()
.map_err(|e| invalid(&e))?
.to_string();
match curve.as_str() {
SECP256R1 => Jwk::from_p256_public(key).map_err(|e| invalid(&e)),
SECP384R1 => p384_jwk(key),
#[cfg(feature = "secp256k1")]
SECP256K1 => Jwk::from_secp256k1_public(key).map_err(|e| invalid(&e)),
_ => Err(X509Error::UnsupportedKey(format!("elliptic curve {curve}"))),
}
}
ED25519 => Jwk::from_ed25519_public(key).map_err(|e| invalid(&e)),
RSA_ENCRYPTION => {
let jwk = Jwk::from_pkcs1_der(key).map_err(|e| invalid(&e))?;
let (modulus, _) = jwk.rsa_public_components().map_err(|e| invalid(&e))?;
let bits = modulus
.iter()
.position(|&byte| byte != 0)
.map_or(0, |first| {
(modulus.len() - first) * 8 - modulus[first].leading_zeros() as usize
});
if bits < MIN_RSA_BITS {
return Err(X509Error::UnsupportedKey(format!(
"RSA key of {bits} bits, shorter than {MIN_RSA_BITS}"
)));
}
Ok(jwk)
}
_ => Err(X509Error::UnsupportedKey(format!("algorithm {algorithm}"))),
}
}
fn p384_jwk(point: &[u8]) -> Result<Jwk, X509Error> {
const COORDINATE: usize = 48;
let invalid = || X509Error::InvalidKey("not an uncompressed P-384 point".to_owned());
let (tag, coordinates) = point.split_first().ok_or_else(invalid)?;
if *tag != 0x04 || coordinates.len() != 2 * COORDINATE {
return Err(invalid());
}
let (x, y) = coordinates.split_at(COORDINATE);
serde_json::from_value(serde_json::json!({
"kty": "EC",
"crv": "P-384",
"x": base64url::encode(x),
"y": base64url::encode(y),
}))
.map_err(|e| X509Error::InvalidKey(e.to_string()))
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum X509Error {
#[error("the certificate chain is empty")]
EmptyChain,
#[error("the certificate chain has {length} certificates, more than {max}")]
ChainTooLong {
length: usize,
max: usize,
},
#[error("certificate {index} is invalid: {source}")]
InvalidCertificate {
index: usize,
#[source]
source: Box<dyn Error + Send + Sync>,
},
#[error("invalid PEM: {0}")]
InvalidPem(String),
#[error("the signing certificate is self-signed")]
SelfSigned,
#[error("the validation time {0} is before 1970")]
InvalidTime(i64),
#[error("the certificate chain does not validate: {0}")]
PathValidation(#[source] Box<dyn Error + Send + Sync>),
#[error("trust anchor {index} is not a CA certificate")]
TrustAnchorNotCa {
index: usize,
},
#[error("the signing certificate's key usage does not allow signing a token")]
KeyUsage,
#[error("unsupported certificate key: {0}")]
UnsupportedKey(String),
#[error("invalid certificate key: {0}")]
InvalidKey(String),
}
impl X509Error {
fn invalid_certificate<E: Error + Send + Sync + 'static>(index: usize, source: E) -> Self {
Self::InvalidCertificate {
index,
source: Box::new(source),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validity_is_inclusive_at_both_ends() {
for now in [100, 150, 200] {
assert!(outside_validity(now, 100, 200).is_none(), "{now}");
}
assert!(matches!(
outside_validity(99, 100, 200),
Some(webpki::Error::CertNotValidYet { .. })
));
assert!(matches!(
outside_validity(201, 100, 200),
Some(webpki::Error::CertExpired { .. })
));
}
#[test]
fn anchor_validity_is_that_of_the_anchor_the_path_was_verified_under() {
use rustls_pki_types::Der;
let anchor = |constraints: Option<&'static [u8]>| TrustAnchor {
subject: Der::from_slice(b"subject"),
subject_public_key_info: Der::from_slice(b"key"),
name_constraints: constraints.map(Der::from_slice),
};
let valid = |not_before, not_after| Anchor {
der: CertificateDer::from(Vec::new()),
not_before,
not_after,
};
let (unconstrained, constrained) = (anchor(None), anchor(Some(b"allowed.example")));
let (expired, current) = (valid(100, 200), valid(150, 300));
let now = 250;
let configured = [(&unconstrained, &expired), (&constrained, ¤t)];
assert!(matches!(
anchor_validity(&unconstrained, configured, now),
Err(webpki::Error::CertExpired { .. })
));
assert!(anchor_validity(&constrained, configured, now).is_ok());
for configured in [
[(&unconstrained, &expired), (&unconstrained, ¤t)],
[(&unconstrained, ¤t), (&unconstrained, &expired)],
] {
assert!(anchor_validity(&unconstrained, configured, now).is_ok());
}
let other = TrustAnchor {
subject: Der::from_slice(b"other"),
..anchor(None)
};
assert!(matches!(
anchor_validity(&other, configured, now),
Err(webpki::Error::UnknownIssuer)
));
}
fn certificate(dns_names: &[&str], uris: &[&str], usage: Option<Usage>) -> X509Certificate {
X509Certificate {
der: Vec::new(),
subject: "CN=example".to_owned(),
issuer: "CN=ca".to_owned(),
self_issued: false,
ca: false,
dns_names: dns_names.iter().map(|&name| name.to_owned()).collect(),
uris: uris.iter().map(|&uri| uri.to_owned()).collect(),
not_before: 0,
not_after: 0,
subject_key_identifier: None,
authority_key_identifier: None,
key_usage: usage,
public_key: Vec::new(),
}
}
#[test]
fn binds_only_canonical_https_urls() {
let named = certificate(&["issuer.example", "xn--mnchen-3ya.example"], &[], None);
for bound in [
"https://issuer.example",
"https://issuer.example/",
"https://issuer.example/tenant/1",
"https://issuer.example:8443/tenant/",
"https://xn--mnchen-3ya.example",
] {
assert!(named.binds(bound), "{bound}");
}
for unbound in [
"https://victim.example",
"https://issuer.example.victim.example",
"https://victim.example@issuer.example",
"https://victim.example:pw@issuer.example/",
"https://issuer.example\\@victim.example",
"https://issuer.example?x=https://victim.example",
"https://issuer.example#https://victim.example",
" https://issuer.example",
"https://issuer.example ",
"https:issuer.example",
"https:\\\\issuer.example",
"https://issuer.exam\tple",
"https://ISSUER.example",
"HTTPS://issuer.example",
"https://issuer.example.",
"https://issuer.example:443",
"https://%69ssuer.example",
"https://\u{ff49}ssuer.example",
"https://m\u{fc}nchen.example",
"http://issuer.example",
"issuer.example",
"did:web:issuer.example",
"",
] {
assert!(!named.binds(unbound), "{unbound:?}");
}
let address = certificate(&["192.168.1.1"], &[], None);
for unbound in [
"https://192.168.1.1",
"https://0xc0.0xa8.1.1",
"https://3232235777",
] {
assert!(!address.binds(unbound), "{unbound}");
}
let wild = certificate(&["*.issuer.example", "*", ""], &[], None);
for unbound in [
"https://a.issuer.example",
"https://*.issuer.example",
"https://",
] {
assert!(!wild.binds(unbound), "{unbound}");
}
}
#[test]
fn uri_names_bind_nothing() {
let uris = [
"https://victim.example",
"did:web:victim.example",
"https://issuer.example/tenant",
"",
];
let without_dns_names = certificate(&[], &uris, None);
for uri in uris {
assert!(!without_dns_names.binds(uri), "{uri:?}");
}
let with_dns_name = certificate(&["issuer.example"], &uris, None);
assert!(with_dns_name.binds("https://issuer.example/tenant"));
for unbound in ["https://victim.example", "did:web:victim.example", ""] {
assert!(!with_dns_name.binds(unbound), "{unbound:?}");
}
}
#[test]
fn key_usage_decides_what_a_key_signs() {
let usage = |digital_signature, non_repudiation, key_cert_sign| {
Some(Usage {
digital_signature,
non_repudiation,
key_cert_sign,
})
};
let leaf = |usage| certificate(&[], &[], usage);
for signs in [
None,
usage(true, false, false),
usage(false, true, false),
usage(true, true, false),
] {
assert!(leaf(signs).may_sign_tokens(), "{signs:?}");
}
for refused in [
usage(false, false, false),
usage(true, false, true),
usage(false, true, true),
usage(false, false, true),
] {
assert!(!leaf(refused).may_sign_tokens(), "{refused:?}");
}
let ca = |usage| X509Certificate {
ca: true,
..certificate(&[], &[], usage)
};
assert!(ca(None).may_issue());
assert!(ca(usage(false, false, true)).may_issue());
assert!(ca(usage(true, false, true)).may_issue());
assert!(!ca(usage(true, false, false)).may_issue());
assert!(!leaf(usage(false, false, true)).may_issue());
assert!(!leaf(None).may_issue());
}
#[test]
fn p384_points_are_uncompressed() {
let mut point = vec![0x04];
point.extend([0x11; 48]);
point.extend([0x22; 48]);
let jwk = serde_json::to_value(p384_jwk(&point).unwrap()).unwrap();
assert_eq!(jwk["crv"], "P-384");
assert_eq!(
base64url::decode(jwk["x"].as_str().unwrap()).unwrap(),
[0x11; 48]
);
assert_eq!(
base64url::decode(jwk["y"].as_str().unwrap()).unwrap(),
[0x22; 48]
);
let mut compressed = vec![0x02];
compressed.extend([0x11; 48]);
for invalid in [&compressed[..], &point[..96], &[]] {
assert!(matches!(p384_jwk(invalid), Err(X509Error::InvalidKey(_))));
}
}
}