Skip to main content

webpki/
error.rs

1#[cfg(feature = "alloc")]
2use alloc::string::String;
3#[cfg(feature = "alloc")]
4use alloc::vec::Vec;
5use core::fmt;
6use core::ops::ControlFlow;
7
8use pki_types::UnixTime;
9#[cfg(feature = "alloc")]
10use pki_types::{AlgorithmIdentifier, ServerName};
11
12use crate::verify_cert::RequiredEkuNotFoundContext;
13
14/// An error that occurs during certificate validation or name validation.
15#[derive(Clone, Debug, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum Error {
18    /// The encoding of some ASN.1 DER-encoded item is invalid.
19    BadDer,
20
21    /// The encoding of an ASN.1 DER-encoded time is invalid.
22    BadDerTime,
23
24    /// A CA certificate is being used as an end-entity certificate.
25    CaUsedAsEndEntity,
26
27    /// A certificate's public key is explicitly distrusted.
28    CertDistrusted,
29
30    /// The certificate is expired; i.e. the time it is being validated for is
31    /// later than the certificate's notAfter time.
32    CertExpired {
33        /// The validation time.
34        time: UnixTime,
35        /// The notAfter time of the certificate.
36        not_after: UnixTime,
37    },
38
39    /// The certificate is not valid for the name it is being validated for.
40    CertNotValidForName(InvalidNameContext),
41
42    /// The certificate is not valid yet; i.e. the time it is being validated
43    /// for is earlier than the certificate's notBefore time.
44    CertNotValidYet {
45        /// The validation time.
46        time: UnixTime,
47        /// The notBefore time of the certificate.
48        not_before: UnixTime,
49    },
50
51    /// The certificate, or one of its issuers, has been revoked.
52    CertRevoked,
53
54    /// The CRL is expired; i.e. the verification time is not before the time
55    /// in the CRL nextUpdate field.
56    CrlExpired {
57        /// The validation time.
58        time: UnixTime,
59        /// The nextUpdate time of the CRL.
60        next_update: UnixTime,
61    },
62
63    /// The certificate has an Extended Key Usage extension without any EKU values.
64    EmptyEkuExtension,
65
66    /// An end-entity certificate is being used as a CA certificate.
67    EndEntityUsedAsCa,
68
69    /// An end-entity certificate has the keyCertSign bit set in its KeyUsage extension.
70    EndEntityCertHasCertSignKeyUsage,
71
72    /// An X.509 extension is invalid.
73    ExtensionValueInvalid,
74
75    /// The certificate validity period (notBefore, notAfter) is invalid; e.g.
76    /// the notAfter time is earlier than the notBefore time.
77    InvalidCertValidity,
78
79    /// A CRL number extension was invalid:
80    ///  - it was mis-encoded
81    ///  - it was negative
82    ///  - it was too long
83    InvalidCrlNumber,
84
85    /// A CRL number extension was missing from a CRL.
86    MissingCrlNumber,
87
88    /// A iPAddress name constraint was invalid:
89    /// - it had a sparse network mask (ie, cannot be written in CIDR form).
90    /// - it was too long or short
91    InvalidNetworkMaskConstraint,
92
93    /// A serial number was invalid:
94    ///  - it was misencoded
95    ///  - it was negative
96    ///  - it was too long
97    InvalidSerialNumber,
98
99    /// The CRL signature is invalid for the issuer's public key.
100    InvalidCrlSignatureForPublicKey,
101
102    /// The signature is invalid for the given public key.
103    InvalidSignatureForPublicKey,
104
105    /// An intermediate certificate was missing the keyCertSign bit in its KeyUsage extension.
106    ///
107    /// See [RFC 5280 section 4.2.1.3] and [RFC 5280 section 6.1.4] step (n). Note that this is
108    /// only enforced for intermediate certificates, not for trust anchors.
109    ///
110    /// [RFC 5280 section 4.2.1.3]: https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3
111    /// [RFC 5280 section 6.1.4]: https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.4
112    IssuerNotCertSigner,
113
114    /// A CRL was signed by an issuer that has a KeyUsage bitstring that does not include
115    /// the cRLSign key usage bit.
116    IssuerNotCrlSigner,
117
118    /// An end-entity certificate's KeyUsage extension does not assert the digitalSignature bit.
119    ///
120    /// This bit is required to use the certificate's public key to verify a signature with
121    /// [`EndEntityCert::verify_signature()`]. See [RFC 5280 section 4.2.1.3]. Note that this is
122    /// only enforced when a KeyUsage extension is present.
123    ///
124    /// [`EndEntityCert::verify_signature()`]: crate::EndEntityCert::verify_signature
125    /// [RFC 5280 section 4.2.1.3]: https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3
126    KeyUsageMissingDigitalSignature,
127
128    /// A presented or reference DNS identifier was malformed, potentially
129    /// containing invalid characters or invalid labels.
130    MalformedDnsIdentifier,
131
132    /// The certificate extensions are malformed.
133    ///
134    /// In particular, webpki requires the DNS name(s) be in the subjectAltName
135    /// extension as required by the CA/Browser Forum Baseline Requirements
136    /// and as recommended by RFC6125.
137    MalformedExtensions,
138
139    /// A name constraint was malformed, potentially containing invalid characters,
140    /// invalid labels, or an empty sequence where at least one item is required.
141    MalformedNameConstraint,
142
143    /// The maximum number of name constraint comparisons has been reached.
144    MaximumNameConstraintComparisonsExceeded,
145
146    /// The maximum number of internal path building calls has been reached. Path complexity is too great.
147    MaximumPathBuildCallsExceeded,
148
149    /// The path search was terminated because it became too deep.
150    MaximumPathDepthExceeded,
151
152    /// The maximum number of signature checks has been reached. Path complexity is too great.
153    MaximumSignatureChecksExceeded,
154
155    /// The certificate violates one or more name constraints.
156    NameConstraintViolation,
157
158    /// The certificate violates one or more path length constraints.
159    PathLenConstraintViolated,
160
161    /// The certificate is not valid for the Extended Key Usage for which it is
162    /// being validated.
163    RequiredEkuNotFound(RequiredEkuNotFoundContext),
164
165    /// The algorithm in the TBSCertificate "signature" field of a certificate
166    /// does not match the algorithm in the signature of the certificate.
167    SignatureAlgorithmMismatch,
168
169    /// Trailing data was found while parsing DER-encoded input for the named type.
170    TrailingData(DerTypeId),
171
172    /// A valid issuer for the certificate could not be found.
173    UnknownIssuer,
174
175    /// The certificate's revocation status could not be determined.
176    UnknownRevocationStatus,
177
178    /// The certificate is not a v3 X.509 certificate.
179    ///
180    /// This error may be also reported if the certificate version field
181    /// is malformed.
182    UnsupportedCertVersion,
183
184    /// The certificate contains an unsupported critical extension.
185    UnsupportedCriticalExtension,
186
187    /// The CRL contains an issuing distribution point with no distribution point name,
188    /// or a distribution point name relative to an issuer.
189    UnsupportedCrlIssuingDistributionPoint,
190
191    /// The CRL is not a v2 X.509 CRL.
192    ///
193    /// The RFC 5280 web PKI profile mandates only version 2 be used. See section
194    /// 5.1.2.1 for more information.
195    ///
196    /// This error may also be reported if the CRL version field is malformed.
197    UnsupportedCrlVersion,
198
199    /// The CRL is an unsupported "delta" CRL.
200    UnsupportedDeltaCrl,
201
202    /// The CRL contains unsupported "indirect" entries.
203    UnsupportedIndirectCrl,
204
205    /// The `ServerName` contained an unsupported type of value.
206    UnsupportedNameType,
207
208    /// The revocation reason is not in the set of supported revocation reasons.
209    UnsupportedRevocationReason,
210
211    /// The CRL is partitioned by revocation reasons.
212    UnsupportedRevocationReasonsPartitioning,
213
214    /// The signature algorithm for a signature is not in the set of supported
215    /// signature algorithms given.
216    UnsupportedCrlSignatureAlgorithm(UnsupportedSignatureAlgorithmContext),
217
218    /// The signature algorithm for a signature is not in the set of supported
219    /// signature algorithms given.
220    UnsupportedSignatureAlgorithm(UnsupportedSignatureAlgorithmContext),
221
222    /// The signature's algorithm does not match the algorithm of the public
223    /// key it is being validated for. This may be because the public key
224    /// algorithm's OID isn't recognized (e.g. DSA), or the public key
225    /// algorithm's parameters don't match the supported parameters for that
226    /// algorithm (e.g. ECC keys for unsupported curves), or the public key
227    /// algorithm and the signature algorithm simply don't match (e.g.
228    /// verifying an RSA signature with an ECC public key).
229    UnsupportedCrlSignatureAlgorithmForPublicKey(UnsupportedSignatureAlgorithmForPublicKeyContext),
230
231    /// The signature's algorithm does not match the algorithm of the public
232    /// key it is being validated for. This may be because the public key
233    /// algorithm's OID isn't recognized (e.g. DSA), or the public key
234    /// algorithm's parameters don't match the supported parameters for that
235    /// algorithm (e.g. ECC keys for unsupported curves), or the public key
236    /// algorithm and the signature algorithm simply don't match (e.g.
237    /// verifying an RSA signature with an ECC public key).
238    UnsupportedSignatureAlgorithmForPublicKey(UnsupportedSignatureAlgorithmForPublicKeyContext),
239}
240
241impl Error {
242    // Compare the Error with the new error by rank, returning the higher rank of the two as
243    // the most specific error.
244    pub(crate) fn most_specific(self, new: Self) -> Self {
245        // Assign an error a numeric value ranking it by specificity.
246        if self.rank() >= new.rank() { self } else { new }
247    }
248
249    // Return a numeric indication of how specific the error is, where an error with a higher rank
250    // is considered more useful to an end user than an error with a lower rank. This is used by
251    // Error::most_specific to compare two errors in order to return which is more specific.
252    pub(crate) fn rank(&self) -> u32 {
253        match &self {
254            // Errors related to certificate validity
255            Self::CertNotValidYet { .. } | Self::CertExpired { .. } => 290,
256            Self::CertNotValidForName(_) => 280,
257            Self::CertDistrusted
258            | Self::CertRevoked
259            | Self::UnknownRevocationStatus
260            | Self::CrlExpired { .. } => 270,
261            Self::InvalidCrlSignatureForPublicKey | Self::InvalidSignatureForPublicKey => 260,
262            Self::SignatureAlgorithmMismatch => 250,
263            Self::EmptyEkuExtension => 245,
264            Self::RequiredEkuNotFound(_) => 240,
265            Self::NameConstraintViolation => 230,
266            Self::PathLenConstraintViolated => 220,
267            Self::IssuerNotCertSigner => 215,
268            Self::CaUsedAsEndEntity | Self::EndEntityUsedAsCa => 210,
269            Self::EndEntityCertHasCertSignKeyUsage => 205,
270            Self::KeyUsageMissingDigitalSignature => 202,
271            Self::IssuerNotCrlSigner => 200,
272
273            // Errors related to supported features used in an invalid way.
274            Self::InvalidCertValidity => 190,
275            Self::InvalidNetworkMaskConstraint => 180,
276            Self::InvalidSerialNumber => 170,
277            Self::InvalidCrlNumber | Self::MissingCrlNumber => 160,
278
279            // Errors related to unsupported features.
280            Self::UnsupportedCrlSignatureAlgorithmForPublicKey(_)
281            | Self::UnsupportedSignatureAlgorithmForPublicKey(_) => 150,
282            Self::UnsupportedCrlSignatureAlgorithm(_) | Self::UnsupportedSignatureAlgorithm(_) => {
283                140
284            }
285            Self::UnsupportedCriticalExtension => 130,
286            Self::UnsupportedCertVersion => 130,
287            Self::UnsupportedCrlVersion => 120,
288            Self::UnsupportedDeltaCrl => 110,
289            Self::UnsupportedIndirectCrl => 100,
290            Self::UnsupportedNameType => 95,
291            Self::UnsupportedRevocationReason => 90,
292            Self::UnsupportedRevocationReasonsPartitioning => 80,
293            Self::UnsupportedCrlIssuingDistributionPoint => 70,
294            Self::MaximumPathDepthExceeded => 61,
295
296            // Errors related to malformed data.
297            Self::MalformedDnsIdentifier => 60,
298            Self::MalformedNameConstraint => 50,
299            Self::MalformedExtensions | Self::TrailingData(_) => 40,
300            Self::ExtensionValueInvalid => 30,
301
302            // Generic DER errors.
303            Self::BadDerTime => 20,
304            Self::BadDer => 10,
305
306            // Special case errors - not subject to ranking.
307            Self::MaximumSignatureChecksExceeded => 0,
308            Self::MaximumPathBuildCallsExceeded => 0,
309            Self::MaximumNameConstraintComparisonsExceeded => 0,
310
311            // Default catch all error - should be renamed in the future.
312            Self::UnknownIssuer => 0,
313        }
314    }
315
316    /// Returns true for errors that should be considered fatal during path building. Errors of
317    /// this class should halt any further path building and be returned immediately.
318    #[inline]
319    pub(crate) fn is_fatal(&self) -> bool {
320        matches!(
321            self,
322            Self::MaximumSignatureChecksExceeded
323                | Self::MaximumPathBuildCallsExceeded
324                | Self::MaximumNameConstraintComparisonsExceeded
325        )
326    }
327}
328
329impl From<Error> for ControlFlow<Error, Error> {
330    fn from(value: Error) -> Self {
331        match value {
332            // If an error is fatal, we've exhausted the potential for continued search.
333            err if err.is_fatal() => Self::Break(err),
334            // Otherwise we've rejected one candidate chain, but may continue to search for others.
335            err => Self::Continue(err),
336        }
337    }
338}
339
340impl fmt::Display for Error {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        write!(f, "{self:?}")
343    }
344}
345
346impl core::error::Error for Error {}
347
348/// Additional context for the `CertNotValidForName` error variant.
349///
350/// The contents of this type depend on whether the `alloc` feature is enabled.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct InvalidNameContext {
353    /// Expected server name.
354    #[cfg(feature = "alloc")]
355    pub expected: ServerName<'static>,
356    /// The names presented in the end entity certificate.
357    ///
358    /// These are the subject names as present in the leaf certificate and may contain DNS names
359    /// with or without a wildcard label as well as IP address names.
360    #[cfg(feature = "alloc")]
361    pub presented: Vec<String>,
362}
363
364/// Additional context for the `UnsupportedSignatureAlgorithmForPublicKey` error variant.
365///
366/// The contents of this type depend on whether the `alloc` feature is enabled.
367#[derive(Clone, Debug, PartialEq, Eq)]
368pub struct UnsupportedSignatureAlgorithmForPublicKeyContext {
369    /// The signature algorithm OID.
370    #[cfg(feature = "alloc")]
371    pub signature_algorithm_id: Vec<u8>,
372    /// The public key algorithm OID.
373    #[cfg(feature = "alloc")]
374    pub public_key_algorithm_id: Vec<u8>,
375}
376
377/// Additional context for the `UnsupportedSignatureAlgorithm` error variant.
378///
379/// The contents of this type depend on whether the `alloc` feature is enabled.
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct UnsupportedSignatureAlgorithmContext {
382    /// The signature algorithm OID that was unsupported.
383    #[cfg(feature = "alloc")]
384    pub signature_algorithm_id: Vec<u8>,
385    /// Supported algorithms that were available for signature verification.
386    #[cfg(feature = "alloc")]
387    pub supported_algorithms: Vec<AlgorithmIdentifier>,
388}
389
390/// Trailing data was found while parsing DER-encoded input for the named type.
391#[expect(missing_docs)]
392#[non_exhaustive]
393#[derive(Clone, Copy, Debug, Eq, PartialEq)]
394pub enum DerTypeId {
395    BitString,
396    Bool,
397    Certificate,
398    CertificateExtensions,
399    CertificateTbsCertificate,
400    CertRevocationList,
401    CertRevocationListExtension,
402    CrlDistributionPoint,
403    CommonNameInner,
404    CommonNameOuter,
405    DistributionPointName,
406    Extension,
407    GeneralName,
408    RevocationReason,
409    Signature,
410    SignatureAlgorithm,
411    SignedData,
412    SubjectPublicKeyInfo,
413    Time,
414    TrustAnchorV1,
415    TrustAnchorV1TbsCertificate,
416    U8,
417    RevokedCertificate,
418    RevokedCertificateExtension,
419    RevokedCertEntry,
420    IssuingDistributionPoint,
421    IssuerUniqueId,
422    SubjectUniqueId,
423    KeyUsageExtension,
424}