use pki_types::{CertificateDer, TrustAnchor};
use crate::cert::{Cert, EndEntityOrCa};
use crate::crl::IssuingDistributionPoint;
use crate::der::{self, FromDer};
use crate::{
signed_data, subject_name, time, CertRevocationList, Error, SignatureVerificationAlgorithm,
};
#[derive(Debug, Copy, Clone)]
pub struct RevocationOptionsBuilder<'a> {
crls: &'a [&'a dyn CertRevocationList],
depth: RevocationCheckDepth,
status_requirement: UnknownStatusPolicy,
}
impl<'a> RevocationOptionsBuilder<'a> {
pub fn new(crls: &'a [&'a dyn CertRevocationList]) -> Result<Self, CrlsRequired> {
if crls.is_empty() {
return Err(CrlsRequired(()));
}
Ok(Self {
crls,
depth: RevocationCheckDepth::Chain,
status_requirement: UnknownStatusPolicy::Deny,
})
}
pub fn with_depth(mut self, depth: RevocationCheckDepth) -> Self {
self.depth = depth;
self
}
pub fn allow_unknown_status(mut self) -> Self {
self.status_requirement = UnknownStatusPolicy::Allow;
self
}
pub fn forbid_unknown_status(mut self) -> Self {
self.status_requirement = UnknownStatusPolicy::Deny;
self
}
pub fn build(self) -> RevocationOptions<'a> {
RevocationOptions {
crls: self.crls,
depth: self.depth,
status_requirement: self.status_requirement,
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct RevocationOptions<'a> {
crls: &'a [&'a dyn CertRevocationList],
depth: RevocationCheckDepth,
status_requirement: UnknownStatusPolicy,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum RevocationCheckDepth {
EndEntity,
Chain,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum UnknownStatusPolicy {
Allow,
Deny,
}
#[derive(Debug, Copy, Clone)]
pub struct CrlsRequired(());
pub(crate) struct ChainOptions<'a> {
pub(crate) eku: KeyUsage,
pub(crate) supported_sig_algs: &'a [&'a dyn SignatureVerificationAlgorithm],
pub(crate) trust_anchors: &'a [TrustAnchor<'a>],
pub(crate) intermediate_certs: &'a [CertificateDer<'a>],
pub(crate) revocation: Option<RevocationOptions<'a>>,
}
pub(crate) fn build_chain(opts: &ChainOptions, cert: &Cert, time: time::Time) -> Result<(), Error> {
build_chain_inner(opts, cert, time, 0, &mut 0_usize)
}
fn build_chain_inner(
opts: &ChainOptions,
cert: &Cert,
time: time::Time,
sub_ca_count: usize,
signatures: &mut usize,
) -> Result<(), Error> {
let used_as_ca = used_as_ca(&cert.ee_or_ca);
check_issuer_independent_properties(cert, time, used_as_ca, sub_ca_count, opts.eku.inner)?;
match used_as_ca {
UsedAsCa::Yes => {
const MAX_SUB_CA_COUNT: usize = 6;
if sub_ca_count >= MAX_SUB_CA_COUNT {
return Err(Error::UnknownIssuer);
}
}
UsedAsCa::No => {
assert_eq!(0, sub_ca_count);
}
}
let subject_common_name_contents = if opts
.eku
.inner
.key_purpose_id_equals(EKU_SERVER_AUTH.oid_value)
&& used_as_ca == UsedAsCa::No
{
subject_name::SubjectCommonNameContents::DnsName
} else {
subject_name::SubjectCommonNameContents::Ignore
};
let result = loop_while_non_fatal_error(
Error::UnknownIssuer,
opts.trust_anchors,
|trust_anchor: &TrustAnchor| {
let trust_anchor_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
if cert.issuer != trust_anchor_subject {
return Err(Error::UnknownIssuer);
}
let name_constraints = trust_anchor
.name_constraints
.as_ref()
.map(|der| untrusted::Input::from(der.as_ref()));
untrusted::read_all_optional(name_constraints, Error::BadDer, |value| {
subject_name::check_name_constraints(value, cert, subject_common_name_contents)
})?;
check_signatures(
opts.supported_sig_algs,
cert,
trust_anchor,
opts.revocation,
signatures,
)?;
Ok(())
},
);
let err = match result {
Ok(()) => return Ok(()),
Err(err) => err,
};
loop_while_non_fatal_error(err, opts.intermediate_certs, |cert_der| {
let potential_issuer =
Cert::from_der(untrusted::Input::from(cert_der), EndEntityOrCa::Ca(cert))?;
if potential_issuer.subject != cert.issuer {
return Err(Error::UnknownIssuer);
}
let mut prev = cert;
loop {
if potential_issuer.spki == prev.spki && potential_issuer.subject == prev.subject {
return Err(Error::UnknownIssuer);
}
match &prev.ee_or_ca {
EndEntityOrCa::EndEntity => {
break;
}
EndEntityOrCa::Ca(child_cert) => {
prev = child_cert;
}
}
}
untrusted::read_all_optional(potential_issuer.name_constraints, Error::BadDer, |value| {
subject_name::check_name_constraints(value, cert, subject_common_name_contents)
})?;
let next_sub_ca_count = match used_as_ca {
UsedAsCa::No => sub_ca_count,
UsedAsCa::Yes => sub_ca_count + 1,
};
build_chain_inner(opts, &potential_issuer, time, next_sub_ca_count, signatures)
})
}
fn check_signatures(
supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
cert_chain: &Cert,
trust_anchor: &TrustAnchor,
revocation: Option<RevocationOptions>,
signatures: &mut usize,
) -> Result<(), Error> {
let mut spki_value = untrusted::Input::from(trust_anchor.subject_public_key_info.as_ref());
let mut issuer_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
let mut issuer_key_usage = None; let mut cert = cert_chain;
loop {
*signatures += 1;
if *signatures > 100 {
return Err(Error::MaximumSignatureChecksExceeded);
}
signed_data::verify_signed_data(supported_sig_algs, spki_value, &cert.signed_data)?;
if let Some(revocation_opts) = &revocation {
check_crls(
supported_sig_algs,
cert,
issuer_subject,
spki_value,
issuer_key_usage,
revocation_opts,
)?;
}
match &cert.ee_or_ca {
EndEntityOrCa::Ca(child_cert) => {
spki_value = cert.spki;
issuer_subject = cert.subject;
issuer_key_usage = cert.key_usage;
cert = child_cert;
}
EndEntityOrCa::EndEntity => {
break;
}
}
}
Ok(())
}
struct CertNotRevoked(());
impl CertNotRevoked {
fn assertion() -> Self {
Self(())
}
}
fn check_crls(
supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
cert: &Cert,
issuer_subject: untrusted::Input,
issuer_spki: untrusted::Input,
issuer_ku: Option<untrusted::Input>,
revocation: &RevocationOptions,
) -> Result<Option<CertNotRevoked>, Error> {
assert_eq!(cert.issuer, issuer_subject);
if let (RevocationCheckDepth::EndEntity, EndEntityOrCa::Ca(_)) =
(revocation.depth, &cert.ee_or_ca)
{
return Ok(None);
}
let crl = revocation
.crls
.iter()
.find(|candidate_crl| crl_authoritative(**candidate_crl, cert));
use UnknownStatusPolicy::*;
let crl = match (crl, revocation.status_requirement) {
(Some(crl), _) => crl,
(None, Allow) => return Ok(None),
(None, _) => return Err(Error::UnknownRevocationStatus),
};
crl.verify_signature(supported_sig_algs, issuer_spki.as_slice_less_safe())
.map_err(crl_signature_err)?;
KeyUsageMode::CrlSign.check(issuer_ku)?;
let cert_serial = cert.serial.as_slice_less_safe();
match crl.find_serial(cert_serial)? {
None => Ok(Some(CertNotRevoked::assertion())),
Some(_) => Err(Error::CertRevoked),
}
}
fn crl_authoritative(crl: &dyn CertRevocationList, cert: &Cert<'_>) -> bool {
if crl.issuer() != cert.issuer() {
return false;
}
let crl_idp = match (
cert.crl_distribution_points(),
crl.issuing_distribution_point(),
) {
(cert_dps, None) => return cert_dps.is_none(),
(_, Some(crl_idp)) => {
match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
Ok(crl_idp) => crl_idp,
Err(_) => return false, }
}
};
crl_idp.authoritative_for(cert)
}
fn crl_signature_err(err: Error) -> Error {
match err {
Error::UnsupportedSignatureAlgorithm => Error::UnsupportedCrlSignatureAlgorithm,
Error::UnsupportedSignatureAlgorithmForPublicKey => {
Error::UnsupportedCrlSignatureAlgorithmForPublicKey
}
Error::InvalidSignatureForPublicKey => Error::InvalidCrlSignatureForPublicKey,
_ => err,
}
}
fn check_issuer_independent_properties(
cert: &Cert,
time: time::Time,
used_as_ca: UsedAsCa,
sub_ca_count: usize,
eku: ExtendedKeyUsage,
) -> Result<(), Error> {
cert.validity
.read_all(Error::BadDer, |value| check_validity(value, time))?;
untrusted::read_all_optional(cert.basic_constraints, Error::BadDer, |value| {
check_basic_constraints(value, used_as_ca, sub_ca_count)
})?;
untrusted::read_all_optional(cert.eku, Error::BadDer, |value| eku.check(value))?;
Ok(())
}
fn check_validity(input: &mut untrusted::Reader, time: time::Time) -> Result<(), Error> {
let not_before = time::Time::from_der(input)?;
let not_after = time::Time::from_der(input)?;
if not_before > not_after {
return Err(Error::InvalidCertValidity);
}
if time < not_before {
return Err(Error::CertNotValidYet);
}
if time > not_after {
return Err(Error::CertExpired);
}
Ok(())
}
#[derive(Clone, Copy, PartialEq)]
enum UsedAsCa {
Yes,
No,
}
fn used_as_ca(ee_or_ca: &EndEntityOrCa) -> UsedAsCa {
match ee_or_ca {
EndEntityOrCa::EndEntity => UsedAsCa::No,
EndEntityOrCa::Ca(..) => UsedAsCa::Yes,
}
}
fn check_basic_constraints(
input: Option<&mut untrusted::Reader>,
used_as_ca: UsedAsCa,
sub_ca_count: usize,
) -> Result<(), Error> {
let (is_ca, path_len_constraint) = match input {
Some(input) => {
let is_ca = bool::from_der(input)?;
let path_len_constraint = if !input.at_end() {
Some(usize::from(u8::from_der(input)?))
} else {
None
};
(is_ca, path_len_constraint)
}
None => (false, None),
};
match (used_as_ca, is_ca, path_len_constraint) {
(UsedAsCa::No, true, _) => Err(Error::CaUsedAsEndEntity),
(UsedAsCa::Yes, false, _) => Err(Error::EndEntityUsedAsCa),
(UsedAsCa::Yes, true, Some(len)) if sub_ca_count > len => {
Err(Error::PathLenConstraintViolated)
}
_ => Ok(()),
}
}
#[derive(Clone, Copy)]
pub struct KeyUsage {
inner: ExtendedKeyUsage,
}
impl KeyUsage {
pub const fn server_auth() -> Self {
Self {
inner: ExtendedKeyUsage::RequiredIfPresent(EKU_SERVER_AUTH),
}
}
pub const fn client_auth() -> Self {
Self {
inner: ExtendedKeyUsage::RequiredIfPresent(EKU_CLIENT_AUTH),
}
}
pub const fn required(oid: &'static [u8]) -> Self {
Self {
inner: ExtendedKeyUsage::Required(KeyPurposeId::new(oid)),
}
}
}
#[derive(Clone, Copy)]
enum ExtendedKeyUsage {
Required(KeyPurposeId),
RequiredIfPresent(KeyPurposeId),
}
impl ExtendedKeyUsage {
fn check(&self, input: Option<&mut untrusted::Reader>) -> Result<(), Error> {
let input = match (input, self) {
(Some(input), _) => input,
(None, Self::RequiredIfPresent(_)) => return Ok(()),
(None, Self::Required(_)) => return Err(Error::RequiredEkuNotFound),
};
loop {
let value = der::expect_tag(input, der::Tag::OID)?;
if self.key_purpose_id_equals(value) {
input.skip_to_end();
break;
}
if input.at_end() {
return Err(Error::RequiredEkuNotFound);
}
}
Ok(())
}
fn key_purpose_id_equals(&self, value: untrusted::Input<'_>) -> bool {
match self {
ExtendedKeyUsage::Required(eku) => *eku,
ExtendedKeyUsage::RequiredIfPresent(eku) => *eku,
}
.oid_value
== value
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct KeyPurposeId {
oid_value: untrusted::Input<'static>,
}
impl KeyPurposeId {
const fn new(oid: &'static [u8]) -> Self {
Self {
oid_value: untrusted::Input::from(oid),
}
}
}
const EKU_SERVER_AUTH: KeyPurposeId = KeyPurposeId::new(&oid!(1, 3, 6, 1, 5, 5, 7, 3, 1));
const EKU_CLIENT_AUTH: KeyPurposeId = KeyPurposeId::new(&oid!(1, 3, 6, 1, 5, 5, 7, 3, 2));
#[repr(u8)]
#[derive(Clone, Copy)]
enum KeyUsageMode {
CrlSign = 6,
}
impl KeyUsageMode {
fn check(self, input: Option<untrusted::Input>) -> Result<(), Error> {
let bit_string = match input {
Some(input) => {
der::expect_tag(&mut untrusted::Reader::new(input), der::Tag::BitString)?
}
None => return Ok(()),
};
let flags = der::bit_string_flags(bit_string)?;
#[allow(clippy::as_conversions)] match flags.bit_set(self as usize) {
true => Ok(()),
false => Err(Error::IssuerNotCrlSigner),
}
}
}
fn loop_while_non_fatal_error<V>(
default_error: Error,
values: V,
mut f: impl FnMut(V::Item) -> Result<(), Error>,
) -> Result<(), Error>
where
V: IntoIterator,
{
let mut error = default_error;
for v in values {
match f(v) {
Ok(()) => return Ok(()),
err @ Err(Error::MaximumSignatureChecksExceeded) => return err,
Err(new_error) => error = error.most_specific(new_error),
}
}
Err(error)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::BorrowedCertRevocationList;
#[test]
fn eku_key_purpose_id() {
assert!(ExtendedKeyUsage::RequiredIfPresent(EKU_SERVER_AUTH)
.key_purpose_id_equals(EKU_SERVER_AUTH.oid_value))
}
#[test]
#[allow(clippy::as_conversions, clippy::redundant_clone, clippy::clone_on_copy)]
fn test_revocation_opts_builder() {
let result = RevocationOptionsBuilder::new(&[]);
assert!(matches!(result, Err(CrlsRequired(_))));
#[cfg(feature = "alloc")]
{
let err = result.unwrap_err();
println!("{:?}", err.clone());
}
let crl = include_bytes!("../tests/crls/crl.valid.der");
let crl =
&BorrowedCertRevocationList::from_der(&crl[..]).unwrap() as &dyn CertRevocationList;
let crls = [crl];
let builder = RevocationOptionsBuilder::new(&crls[..]).unwrap();
#[cfg(feature = "alloc")]
{
println!("{:?}", builder);
_ = builder.clone();
}
let opts = builder.build();
assert_eq!(opts.depth, RevocationCheckDepth::Chain);
assert_eq!(opts.status_requirement, UnknownStatusPolicy::Deny);
assert_eq!(opts.crls.len(), 1);
let opts = RevocationOptionsBuilder::new(&crls[..])
.unwrap()
.with_depth(RevocationCheckDepth::EndEntity)
.build();
assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
assert_eq!(opts.status_requirement, UnknownStatusPolicy::Deny);
assert_eq!(opts.crls.len(), 1);
let opts = RevocationOptionsBuilder::new(&crls[..])
.unwrap()
.allow_unknown_status()
.build();
assert_eq!(opts.depth, RevocationCheckDepth::Chain);
assert_eq!(opts.status_requirement, UnknownStatusPolicy::Allow);
assert_eq!(opts.crls.len(), 1);
let opts = RevocationOptionsBuilder::new(&crls[..])
.unwrap()
.allow_unknown_status()
.with_depth(RevocationCheckDepth::EndEntity)
.build();
assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
assert_eq!(opts.status_requirement, UnknownStatusPolicy::Allow);
assert_eq!(opts.crls.len(), 1);
let opts = RevocationOptionsBuilder::new(&crls[..])
.unwrap()
.forbid_unknown_status()
.with_depth(RevocationCheckDepth::EndEntity)
.build();
assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
assert_eq!(opts.status_requirement, UnknownStatusPolicy::Deny);
assert_eq!(opts.crls.len(), 1);
#[cfg(feature = "alloc")]
{
println!("{:?}", opts.clone());
}
}
#[test]
fn test_crl_authoritative_issuer_mismatch() {
let crl = include_bytes!("../tests/crls/crl.valid.der");
let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
let ee = include_bytes!("../tests/client_auth_revocation/no_ku_chain.ee.der");
let ee = Cert::from_der(untrusted::Input::from(&ee[..]), EndEntityOrCa::EndEntity).unwrap();
assert!(!crl_authoritative(&crl, &ee));
}
#[test]
fn test_crl_authoritative_no_idp_no_cert_dp() {
let crl =
include_bytes!("../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
let ee = include_bytes!("../tests/client_auth_revocation/ku_chain.ee.der");
let ee = Cert::from_der(untrusted::Input::from(&ee[..]), EndEntityOrCa::EndEntity).unwrap();
assert!(crl_authoritative(&crl, &ee));
}
#[test]
#[cfg(feature = "alloc")]
fn test_too_many_signatures() {
use crate::types::CertificateDer;
use crate::{extract_trust_anchor, ECDSA_P256_SHA256};
use crate::{EndEntityCert, Time};
let alg = &rcgen::PKCS_ECDSA_P256_SHA256;
let make_issuer = || {
let mut ca_params = rcgen::CertificateParams::new(Vec::new());
ca_params
.distinguished_name
.push(rcgen::DnType::OrganizationName, "Bogus Subject");
ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
ca_params.key_usages = vec![
rcgen::KeyUsagePurpose::KeyCertSign,
rcgen::KeyUsagePurpose::DigitalSignature,
rcgen::KeyUsagePurpose::CrlSign,
];
ca_params.alg = alg;
rcgen::Certificate::from_params(ca_params).unwrap()
};
let ca_cert = make_issuer();
let ca_cert_der = CertificateDer::from(ca_cert.serialize_der().unwrap());
let mut intermediates = Vec::with_capacity(101);
let mut issuer = ca_cert;
for _ in 0..101 {
let intermediate = make_issuer();
let intermediate_der = intermediate.serialize_der_with_signer(&issuer).unwrap();
intermediates.push(intermediate_der);
issuer = intermediate;
}
let mut ee_params = rcgen::CertificateParams::new(vec!["example.com".to_string()]);
ee_params.is_ca = rcgen::IsCa::ExplicitNoCa;
ee_params.alg = alg;
let ee_cert = rcgen::Certificate::from_params(ee_params).unwrap();
let ee_cert_der = CertificateDer::from(ee_cert.serialize_der_with_signer(&issuer).unwrap());
let anchors = &[extract_trust_anchor(&ca_cert_der).unwrap()];
let time = Time::from_seconds_since_unix_epoch(0x1fed_f00d);
let cert = EndEntityCert::try_from(&ee_cert_der).unwrap();
let intermediates_der = intermediates
.iter()
.map(|x| CertificateDer::from(x.as_ref()))
.collect::<Vec<_>>();
let result = build_chain(
&ChainOptions {
eku: KeyUsage::server_auth(),
supported_sig_algs: &[ECDSA_P256_SHA256],
trust_anchors: anchors,
intermediate_certs: &intermediates_der,
revocation: None,
},
cert.inner(),
time,
);
assert!(matches!(result, Err(Error::MaximumSignatureChecksExceeded)));
}
}