Skip to main content

utility_pki/
cert.rs

1//! What a profile requires of a TLS certificate, as data. The check itself, which reads
2//! DER, is in the `x509` module behind the feature of the same name.
3
4use core::fmt;
5
6use crate::profile::{Allowed, KeyRule};
7
8macro_rules! oid_enum {
9    (
10        $(#[$meta:meta])*
11        $name:ident {
12            $( $(#[$vmeta:meta])* $variant:ident = [$($byte:literal),+] => $label:literal, )+
13        }
14    ) => {
15        $(#[$meta])*
16        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17        #[non_exhaustive]
18        pub enum $name {
19            $( $(#[$vmeta])* $variant, )+
20        }
21
22        impl $name {
23            /// Every variant.
24            pub const ALL: &'static [Self] = &[$(Self::$variant),+];
25
26            /// The object identifier, as DER content bytes.
27            pub const fn oid(self) -> &'static [u8] {
28                match self {
29                    $( Self::$variant => &[$($byte),+], )+
30                }
31            }
32
33            /// The variant with this object identifier.
34            pub fn from_oid(oid: &[u8]) -> Option<Self> {
35                Self::ALL.iter().copied().find(|v| v.oid() == oid)
36            }
37        }
38
39        impl fmt::Display for $name {
40            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41                f.write_str(match self {
42                    $( Self::$variant => $label, )+
43                })
44            }
45        }
46    };
47}
48
49oid_enum! {
50    /// An X.509 certificate extension (RFC 5280 §4.2).
51    Extension {
52        /// 2.5.29.35
53        AuthorityKeyIdentifier = [0x55, 0x1D, 0x23] => "AuthorityKeyIdentifier",
54        /// 2.5.29.14
55        SubjectKeyIdentifier = [0x55, 0x1D, 0x0E] => "SubjectKeyIdentifier",
56        /// 2.5.29.15
57        KeyUsage = [0x55, 0x1D, 0x0F] => "KeyUsage",
58        /// 2.5.29.16
59        PrivateKeyUsagePeriod = [0x55, 0x1D, 0x10] => "PrivateKeyUsagePeriod",
60        /// 2.5.29.32
61        CertificatePolicies = [0x55, 0x1D, 0x20] => "CertificatePolicies",
62        /// 2.5.29.17
63        SubjectAltName = [0x55, 0x1D, 0x11] => "SubjectAltName",
64        /// 2.5.29.18
65        IssuerAltName = [0x55, 0x1D, 0x12] => "IssuerAltName",
66        /// 2.5.29.19
67        BasicConstraints = [0x55, 0x1D, 0x13] => "BasicConstraints",
68        /// 2.5.29.37
69        ExtendedKeyUsage = [0x55, 0x1D, 0x25] => "ExtendedKeyUsage",
70        /// 2.5.29.31
71        CrlDistributionPoints = [0x55, 0x1D, 0x1F] => "CRLDistributionPoints",
72        /// 1.3.6.1.5.5.7.1.1
73        AuthorityInfoAccess = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01] => "AuthorityInfoAccess",
74    }
75}
76
77oid_enum! {
78    /// An extended key usage purpose (RFC 5280 §4.2.1.12).
79    ExtendedKeyUsage {
80        /// TLS server authentication, 1.3.6.1.5.5.7.3.1.
81        ServerAuth = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01] => "serverAuth",
82        /// TLS client authentication, 1.3.6.1.5.5.7.3.2.
83        ClientAuth = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02] => "clientAuth",
84    }
85}
86
87/// The algorithm the issuer signed a certificate with.
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
89#[non_exhaustive]
90pub enum CertSignature {
91    /// ecdsa-with-SHA256.
92    EcdsaSha256,
93    /// ecdsa-with-SHA384.
94    EcdsaSha384,
95    /// ecdsa-with-SHA512.
96    EcdsaSha512,
97    /// sha256WithRSAEncryption (PKCS#1 v1.5).
98    RsaPkcs1Sha256,
99    /// sha384WithRSAEncryption (PKCS#1 v1.5).
100    RsaPkcs1Sha384,
101    /// sha512WithRSAEncryption (PKCS#1 v1.5).
102    RsaPkcs1Sha512,
103    /// RSASSA-PSS with SHA-256.
104    RsaPssSha256,
105    /// RSASSA-PSS with SHA-384.
106    RsaPssSha384,
107    /// RSASSA-PSS with SHA-512.
108    RsaPssSha512,
109    /// Ed25519.
110    Ed25519,
111}
112
113impl fmt::Display for CertSignature {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(match self {
116            Self::EcdsaSha256 => "ecdsa-with-SHA256",
117            Self::EcdsaSha384 => "ecdsa-with-SHA384",
118            Self::EcdsaSha512 => "ecdsa-with-SHA512",
119            Self::RsaPkcs1Sha256 => "sha256WithRSAEncryption",
120            Self::RsaPkcs1Sha384 => "sha384WithRSAEncryption",
121            Self::RsaPkcs1Sha512 => "sha512WithRSAEncryption",
122            Self::RsaPssSha256 => "RSASSA-PSS with SHA-256",
123            Self::RsaPssSha384 => "RSASSA-PSS with SHA-384",
124            Self::RsaPssSha512 => "RSASSA-PSS with SHA-512",
125            Self::Ed25519 => "Ed25519",
126        })
127    }
128}
129
130/// A KeyUsage bit (RFC 5280 §4.2.1.3).
131#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
132#[non_exhaustive]
133pub enum KeyUsage {
134    /// Bit 0.
135    DigitalSignature,
136    /// Bit 1 (contentCommitment).
137    NonRepudiation,
138    /// Bit 2.
139    KeyEncipherment,
140    /// Bit 3.
141    DataEncipherment,
142    /// Bit 4.
143    KeyAgreement,
144    /// Bit 5.
145    KeyCertSign,
146    /// Bit 6.
147    CrlSign,
148    /// Bit 7.
149    EncipherOnly,
150    /// Bit 8.
151    DecipherOnly,
152}
153
154impl KeyUsage {
155    /// The bit number in the KeyUsage BIT STRING.
156    pub const fn bit(self) -> u8 {
157        self as u8
158    }
159}
160
161impl fmt::Display for KeyUsage {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.write_str(match self {
164            Self::DigitalSignature => "digitalSignature",
165            Self::NonRepudiation => "nonRepudiation",
166            Self::KeyEncipherment => "keyEncipherment",
167            Self::DataEncipherment => "dataEncipherment",
168            Self::KeyAgreement => "keyAgreement",
169            Self::KeyCertSign => "keyCertSign",
170            Self::CrlSign => "cRLSign",
171            Self::EncipherOnly => "encipherOnly",
172            Self::DecipherOnly => "decipherOnly",
173        })
174    }
175}
176
177/// Rules for the SubjectAltName extension.
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub struct SanRules {
180    /// Whether `*` may appear in any name.
181    pub wildcards: bool,
182    /// Most dNSName entries, if limited.
183    pub max_dns_names: Option<u8>,
184    /// A certificate with the serverAuth purpose must carry a dNSName.
185    pub dns_name_for_server_auth: bool,
186    /// Exact number of uniformResourceIdentifier entries, if prescribed.
187    pub uris: Option<u8>,
188}
189
190/// Rules for the subject's distinguished name.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub struct SubjectRules {
193    /// The organisation (O) must be exactly this.
194    pub organization: Option<&'static str>,
195    /// Exactly one organisational unit (OU) must be present.
196    pub organizational_unit: bool,
197    /// The common name (CN) must contain this after at least one character (the `<org>` of
198    /// CP SM-PKI Tab. 23's `<org>.EMT.MAK[<extension>]`).
199    pub common_name_contains: Option<&'static str>,
200}
201
202/// What a profile requires of a TLS certificate (its own or the peer's).
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204pub struct CertRules {
205    /// The certificate's public key.
206    pub keys: Allowed<KeyRule>,
207    /// The issuer's signature algorithm.
208    pub signatures: Allowed<CertSignature>,
209    /// Longest validity (notAfter − notBefore) in days. "Two years" is encoded as 731, so a
210    /// two-year certificate across a leap day passes; one without a leap day may be one day
211    /// longer than two calendar years and still pass.
212    pub max_validity_days: Option<u32>,
213    /// Extensions: with `Only`, any extension not listed is not allowed.
214    pub extensions: Allowed<Extension>,
215    /// `Some`: exactly these extensions must be critical, every other present one must not
216    /// be. `None`: criticality is not restricted.
217    pub critical: Option<&'static [Extension]>,
218    /// KeyUsage bits that must be set. Other bits are not restricted.
219    pub key_usage: &'static [KeyUsage],
220    /// Extended key usage purposes.
221    pub extended_key_usage: Allowed<ExtendedKeyUsage>,
222    /// BasicConstraints must not say cA = TRUE.
223    pub end_entity: bool,
224    /// SubjectAltName.
225    pub san: SanRules,
226    /// Subject name.
227    pub subject: SubjectRules,
228}
229
230impl CertRules {
231    /// No certificate rules.
232    pub const ANY: Self = Self {
233        keys: Allowed::Any,
234        signatures: Allowed::Any,
235        max_validity_days: None,
236        extensions: Allowed::Any,
237        critical: None,
238        key_usage: &[],
239        extended_key_usage: Allowed::Any,
240        end_entity: false,
241        san: SanRules { wildcards: true, max_dns_names: None, dns_name_for_server_auth: false, uris: None },
242        subject: SubjectRules { organization: None, organizational_unit: false, common_name_contains: None },
243    };
244}