use crate::{
cert::{Cert, EndEntityOrCa},
der, signed_data, subject_name, time, CertRevocationList, Error, SignatureAlgorithm,
TrustAnchor,
};
pub(crate) struct ChainOptions<'a> {
pub(crate) eku: KeyUsage,
pub(crate) supported_sig_algs: &'a [&'a SignatureAlgorithm],
pub(crate) trust_anchors: &'a [TrustAnchor<'a>],
pub(crate) intermediate_certs: &'a [&'a [u8]],
pub(crate) crls: &'a [&'a dyn CertRevocationList],
}
pub(crate) fn build_chain(opts: &ChainOptions, cert: &Cert, time: time::Time) -> Result<(), Error> {
build_chain_inner(opts, cert, time, 0)
}
fn build_chain_inner(
opts: &ChainOptions,
cert: &Cert,
time: time::Time,
sub_ca_count: 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);
if cert.issuer != trust_anchor_subject {
return Err(Error::UnknownIssuer);
}
let name_constraints = trust_anchor.name_constraints.map(untrusted::Input::from);
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.crls)?;
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.value() == prev.spki.value()
&& 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)
})
}
fn check_signatures(
supported_sig_algs: &[&SignatureAlgorithm],
cert_chain: &Cert,
trust_anchor: &TrustAnchor,
crls: &[&dyn CertRevocationList],
) -> Result<(), Error> {
let mut spki_value = untrusted::Input::from(trust_anchor.spki);
let mut issuer_subject = untrusted::Input::from(trust_anchor.subject);
let mut issuer_key_usage = None; let mut cert = cert_chain;
loop {
signed_data::verify_signed_data(supported_sig_algs, spki_value, &cert.signed_data)?;
if !crls.is_empty() {
check_crls(
supported_sig_algs,
cert,
issuer_subject,
spki_value,
issuer_key_usage,
crls,
)?;
}
match &cert.ee_or_ca {
EndEntityOrCa::Ca(child_cert) => {
spki_value = cert.spki.value();
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: &[&SignatureAlgorithm],
cert: &Cert,
issuer_subject: untrusted::Input,
issuer_spki: untrusted::Input,
issuer_ku: Option<untrusted::Input>,
crls: &[&dyn CertRevocationList],
) -> Result<Option<CertNotRevoked>, Error> {
assert_eq!(cert.issuer, issuer_subject);
let crl = match crls
.iter()
.find(|candidate_crl| candidate_crl.issuer() == cert.issuer())
{
Some(crl) => crl,
None => return Ok(None),
};
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_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 = der::time_choice(input)?;
let not_after = der::time_choice(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 = der::optional_boolean(input)?;
let path_len_constraint = if !input.at_end() {
let value = der::small_nonnegative_integer(input)?;
Some(usize::from(value))
} 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_and_get_value(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),
}
}
}
#[allow(clippy::identity_op)] const EKU_SERVER_AUTH: KeyPurposeId = KeyPurposeId::new(&[(40 * 1) + 3, 6, 1, 5, 5, 7, 3, 1]);
#[allow(clippy::identity_op)] const EKU_CLIENT_AUTH: KeyPurposeId = KeyPurposeId::new(&[(40 * 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) => input,
None => return Ok(()),
};
let flags = der::bit_string_flags(&mut untrusted::Reader::new(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,
f: impl Fn(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(new_error) => error = error.most_specific(new_error),
}
}
Err(error)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eku_key_purpose_id() {
assert!(ExtendedKeyUsage::RequiredIfPresent(EKU_SERVER_AUTH)
.key_purpose_id_equals(EKU_SERVER_AUTH.oid_value))
}
}