webpki/
error.rs

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