Skip to content

Commit

Permalink
x509-cert: rework the profile of builder
Browse files Browse the repository at this point in the history
This is now providing a trait to be implemented by the consumer.

A number of implementation are available, including ones trying to abide
by CABF Baseline Requirements.

Fixes #1281
  • Loading branch information
baloo committed Jan 21, 2024
1 parent 345ac96 commit 7213a65
Show file tree
Hide file tree
Showing 5 changed files with 545 additions and 217 deletions.
183 changes: 24 additions & 159 deletions x509-cert/src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
//! X509 Certificate builder

use alloc::vec;
use core::fmt;
use core::{fmt};
use der::{asn1::BitString, referenced::OwnedToRef, Encode};
use signature::{rand_core::CryptoRngCore, Keypair, RandomizedSigner, Signer};
use spki::{
AlgorithmIdentifier, DynSignatureAlgorithmIdentifier, EncodePublicKey, ObjectIdentifier,
SignatureBitStringEncoding, SubjectPublicKeyInfoOwned, SubjectPublicKeyInfoRef,
SignatureBitStringEncoding, SubjectPublicKeyInfoOwned,
};

use crate::{
certificate::{Certificate, TbsCertificate, Version},
ext::{
pkix::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, KeyUsages, SubjectKeyIdentifier,
},
AsExtension, Extension, Extensions,
AsExtension, Extensions,
},
name::Name,
request::{attributes::AsAttribute, CertReq, CertReqInfo, ExtensionReq},
serial_number::SerialNumber,
time::Validity,
};

pub mod profile;

use self::profile::sealed::Profile;

const NULL_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("0.0.0");

/// Error type
Expand Down Expand Up @@ -73,156 +74,12 @@ impl From<signature::Error> for Error {
/// Result type
pub type Result<T> = core::result::Result<T, Error>;

/// The type of certificate to build
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Profile {
/// Build a root CA certificate
Root,
/// Build an intermediate sub CA certificate
SubCA {
/// issuer Name,
/// represents the name signing the certificate
issuer: Name,
/// pathLenConstraint INTEGER (0..MAX) OPTIONAL
/// BasicConstraints as defined in [RFC 5280 Section 4.2.1.9].
path_len_constraint: Option<u8>,
},
/// Build an end certificate
Leaf {
/// issuer Name,
/// represents the name signing the certificate
issuer: Name,
/// should the key agreement flag of KeyUsage be enabled
enable_key_agreement: bool,
/// should the key encipherment flag of KeyUsage be enabled
enable_key_encipherment: bool,
/// should the subject key identifier extension be included
///
/// From [RFC 5280 Section 4.2.1.2]:
/// For end entity certificates, subject key identifiers SHOULD be
/// derived from the public key. Two common methods for generating key
/// identifiers from the public key are identified above.
#[cfg(feature = "hazmat")]
include_subject_key_identifier: bool,
},
#[cfg(feature = "hazmat")]
/// Opt-out of the default extensions
Manual {
/// issuer Name,
/// represents the name signing the certificate
/// A `None` will make it a self-signed certificate
issuer: Option<Name>,
},
}

impl Profile {
fn get_issuer(&self, subject: &Name) -> Name {
match self {
Profile::Root => subject.clone(),
Profile::SubCA { issuer, .. } => issuer.clone(),
Profile::Leaf { issuer, .. } => issuer.clone(),
#[cfg(feature = "hazmat")]
Profile::Manual { issuer, .. } => issuer.as_ref().unwrap_or(subject).clone(),
}
}

fn build_extensions(
&self,
spk: SubjectPublicKeyInfoRef<'_>,
issuer_spk: SubjectPublicKeyInfoRef<'_>,
tbs: &TbsCertificate,
) -> Result<vec::Vec<Extension>> {
#[cfg(feature = "hazmat")]
// User opted out of default extensions set.
if let Profile::Manual { .. } = self {
return Ok(vec::Vec::default());
}

let mut extensions: vec::Vec<Extension> = vec::Vec::new();

match self {
#[cfg(feature = "hazmat")]
Profile::Leaf {
include_subject_key_identifier: false,
..
} => {}
_ => extensions.push(
SubjectKeyIdentifier::try_from(spk)?.to_extension(&tbs.subject, &extensions)?,
),
}

// Build Authority Key Identifier
match self {
Profile::Root => {}
_ => {
extensions.push(
AuthorityKeyIdentifier::try_from(issuer_spk.clone())?
.to_extension(&tbs.subject, &extensions)?,
);
}
}

// Build Basic Contraints extensions
extensions.push(match self {
Profile::Root => BasicConstraints {
ca: true,
path_len_constraint: None,
}
.to_extension(&tbs.subject, &extensions)?,
Profile::SubCA {
path_len_constraint,
..
} => BasicConstraints {
ca: true,
path_len_constraint: *path_len_constraint,
}
.to_extension(&tbs.subject, &extensions)?,
Profile::Leaf { .. } => BasicConstraints {
ca: false,
path_len_constraint: None,
}
.to_extension(&tbs.subject, &extensions)?,
#[cfg(feature = "hazmat")]
Profile::Manual { .. } => unreachable!(),
});

// Build Key Usage extension
match self {
Profile::Root | Profile::SubCA { .. } => {
extensions.push(
KeyUsage(KeyUsages::KeyCertSign | KeyUsages::CRLSign)
.to_extension(&tbs.subject, &extensions)?,
);
}
Profile::Leaf {
enable_key_agreement,
enable_key_encipherment,
..
} => {
let mut key_usage = KeyUsages::DigitalSignature | KeyUsages::NonRepudiation;
if *enable_key_encipherment {
key_usage |= KeyUsages::KeyEncipherment;
}
if *enable_key_agreement {
key_usage |= KeyUsages::KeyAgreement;
}

extensions.push(KeyUsage(key_usage).to_extension(&tbs.subject, &extensions)?);
}
#[cfg(feature = "hazmat")]
Profile::Manual { .. } => unreachable!(),
}

Ok(extensions)
}
}

/// X509 Certificate builder
///
/// ```
/// use der::Decode;
/// use x509_cert::spki::SubjectPublicKeyInfoOwned;
/// use x509_cert::builder::{CertificateBuilder, Profile, Builder};
/// use x509_cert::builder::{CertificateBuilder, Builder, profile};
/// use x509_cert::name::Name;
/// use x509_cert::serial_number::SerialNumber;
/// use x509_cert::time::Validity;
Expand All @@ -242,8 +99,11 @@ impl Profile {
///
/// let serial_number = SerialNumber::from(42u32);
/// let validity = Validity::from_now(Duration::new(5, 0)).unwrap();
/// let profile = Profile::Root;
/// let subject = Name::from_str("CN=World domination corporation,O=World domination Inc,C=US").unwrap();
/// let profile = profile::cabf::Root {
/// subject,
/// emits_ocsp_response: false,
/// };
///
/// let pub_key = SubjectPublicKeyInfoOwned::try_from(RSA_2048_DER).expect("get rsa pub key");
///
Expand All @@ -252,33 +112,35 @@ impl Profile {
/// profile,
/// serial_number,
/// validity,
/// subject,
/// pub_key,
/// )
/// .expect("Create certificate builder");
///
/// let cert = builder.build(&signer).expect("Create certificate");
/// ```
pub struct CertificateBuilder {
pub struct CertificateBuilder<P> {
tbs: TbsCertificate,
extensions: Extensions,
profile: Profile,
profile: P,
}

impl CertificateBuilder {
impl<P> CertificateBuilder<P>
where
P: Profile,
{
/// Creates a new certificate builder
pub fn new(
profile: Profile,
profile: P,
serial_number: SerialNumber,
mut validity: Validity,
subject: Name,
subject_public_key_info: SubjectPublicKeyInfoOwned,
) -> Result<Self> {
let signature_alg = AlgorithmIdentifier {
oid: NULL_OID,
parameters: None,
};

let subject = profile.get_subject();
let issuer = profile.get_issuer(&subject);

validity.not_before.rfc5280_adjust_utc_time()?;
Expand Down Expand Up @@ -454,7 +316,10 @@ pub trait Builder: Sized {
}
}

impl Builder for CertificateBuilder {
impl<P> Builder for CertificateBuilder<P>
where
P: Profile,
{
type Output = Certificate;

fn finalize<S>(&mut self, cert_signer: &S) -> Result<vec::Vec<u8>>
Expand Down
39 changes: 39 additions & 0 deletions x509-cert/src/builder/profile.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@





pub mod cabf;
//pub mod piv;

pub(crate) mod sealed {
use alloc::vec;
use spki::{
SubjectPublicKeyInfoRef,
};

use crate::{
builder::Result,
certificate::{TbsCertificate},
ext::{
Extension,
},
name::Name,
};

pub trait Profile {
fn get_issuer(&self, subject: &Name) -> Name;

fn get_subject(&self) -> Name;

fn build_extensions(
&self,
spk: SubjectPublicKeyInfoRef<'_>,
issuer_spk: SubjectPublicKeyInfoRef<'_>,
tbs: &TbsCertificate,
) -> Result<vec::Vec<Extension>>;
}
}

#[cfg(feature = "hazmat")]
pub use sealed::Profile;

0 comments on commit 7213a65

Please sign in to comment.