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 #[allow(clippy::as_conversions)] // We won't exceed u32 errors.
239 pub(crate) fn rank(&self) -> u32 {
240 match &self {
241 // Errors related to certificate validity
242 Self::CertNotValidYet { .. } | Self::CertExpired { .. } => 290,
243 Self::CertNotValidForName(_) => 280,
244 Self::CertRevoked | Self::UnknownRevocationStatus | Self::CrlExpired { .. } => 270,
245 Self::InvalidCrlSignatureForPublicKey | Self::InvalidSignatureForPublicKey => 260,
246 Self::SignatureAlgorithmMismatch => 250,
247 Self::EmptyEkuExtension => 245,
248 Self::RequiredEkuNotFound(_) => 240,
249 Self::NameConstraintViolation => 230,
250 Self::PathLenConstraintViolated => 220,
251 Self::CaUsedAsEndEntity | Self::EndEntityUsedAsCa => 210,
252 Self::IssuerNotCrlSigner => 200,
253
254 // Errors related to supported features used in an invalid way.
255 Self::InvalidCertValidity => 190,
256 Self::InvalidNetworkMaskConstraint => 180,
257 Self::InvalidSerialNumber => 170,
258 Self::InvalidCrlNumber => 160,
259
260 // Errors related to unsupported features.
261 Self::UnsupportedCrlSignatureAlgorithmForPublicKey(_)
262 | Self::UnsupportedSignatureAlgorithmForPublicKey(_) => 150,
263 Self::UnsupportedCrlSignatureAlgorithm(_) | Self::UnsupportedSignatureAlgorithm(_) => {
264 140
265 }
266 Self::UnsupportedCriticalExtension => 130,
267 Self::UnsupportedCertVersion => 130,
268 Self::UnsupportedCrlVersion => 120,
269 Self::UnsupportedDeltaCrl => 110,
270 Self::UnsupportedIndirectCrl => 100,
271 Self::UnsupportedNameType => 95,
272 Self::UnsupportedRevocationReason => 90,
273 Self::UnsupportedRevocationReasonsPartitioning => 80,
274 Self::UnsupportedCrlIssuingDistributionPoint => 70,
275 Self::MaximumPathDepthExceeded => 61,
276
277 // Errors related to malformed data.
278 Self::MalformedDnsIdentifier => 60,
279 Self::MalformedNameConstraint => 50,
280 Self::MalformedExtensions | Self::TrailingData(_) => 40,
281 Self::ExtensionValueInvalid => 30,
282
283 // Generic DER errors.
284 Self::BadDerTime => 20,
285 Self::BadDer => 10,
286
287 // Special case errors - not subject to ranking.
288 Self::MaximumSignatureChecksExceeded => 0,
289 Self::MaximumPathBuildCallsExceeded => 0,
290 Self::MaximumNameConstraintComparisonsExceeded => 0,
291
292 // Default catch all error - should be renamed in the future.
293 Self::UnknownIssuer => 0,
294 }
295 }
296
297 /// Returns true for errors that should be considered fatal during path building. Errors of
298 /// this class should halt any further path building and be returned immediately.
299 #[inline]
300 pub(crate) fn is_fatal(&self) -> bool {
301 matches!(
302 self,
303 Self::MaximumSignatureChecksExceeded
304 | Self::MaximumPathBuildCallsExceeded
305 | Self::MaximumNameConstraintComparisonsExceeded
306 )
307 }
308}
309
310impl From<Error> for ControlFlow<Error, Error> {
311 fn from(value: Error) -> Self {
312 match value {
313 // If an error is fatal, we've exhausted the potential for continued search.
314 err if err.is_fatal() => Self::Break(err),
315 // Otherwise we've rejected one candidate chain, but may continue to search for others.
316 err => Self::Continue(err),
317 }
318 }
319}
320
321impl fmt::Display for Error {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 write!(f, "{self:?}")
324 }
325}
326
327impl core::error::Error for Error {}
328
329/// Additional context for the `CertNotValidForName` error variant.
330///
331/// The contents of this type depend on whether the `alloc` feature is enabled.
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub struct InvalidNameContext {
334 /// Expected server name.
335 #[cfg(feature = "alloc")]
336 pub expected: ServerName<'static>,
337 /// The names presented in the end entity certificate.
338 ///
339 /// These are the subject names as present in the leaf certificate and may contain DNS names
340 /// with or without a wildcard label as well as IP address names.
341 #[cfg(feature = "alloc")]
342 pub presented: Vec<String>,
343}
344
345/// Additional context for the `UnsupportedSignatureAlgorithmForPublicKey` error variant.
346///
347/// The contents of this type depend on whether the `alloc` feature is enabled.
348#[derive(Clone, Debug, PartialEq, Eq)]
349pub struct UnsupportedSignatureAlgorithmForPublicKeyContext {
350 /// The signature algorithm OID.
351 #[cfg(feature = "alloc")]
352 pub signature_algorithm_id: Vec<u8>,
353 /// The public key algorithm OID.
354 #[cfg(feature = "alloc")]
355 pub public_key_algorithm_id: Vec<u8>,
356}
357
358/// Additional context for the `UnsupportedSignatureAlgorithm` error variant.
359///
360/// The contents of this type depend on whether the `alloc` feature is enabled.
361#[derive(Clone, Debug, PartialEq, Eq)]
362pub struct UnsupportedSignatureAlgorithmContext {
363 /// The signature algorithm OID that was unsupported.
364 #[cfg(feature = "alloc")]
365 pub signature_algorithm_id: Vec<u8>,
366 /// Supported algorithms that were available for signature verification.
367 #[cfg(feature = "alloc")]
368 pub supported_algorithms: Vec<AlgorithmIdentifier>,
369}
370
371/// Trailing data was found while parsing DER-encoded input for the named type.
372#[allow(missing_docs)]
373#[non_exhaustive]
374#[derive(Clone, Copy, Debug, Eq, PartialEq)]
375pub enum DerTypeId {
376 BitString,
377 Bool,
378 Certificate,
379 CertificateExtensions,
380 CertificateTbsCertificate,
381 CertRevocationList,
382 CertRevocationListExtension,
383 CrlDistributionPoint,
384 CommonNameInner,
385 CommonNameOuter,
386 DistributionPointName,
387 Extension,
388 GeneralName,
389 RevocationReason,
390 Signature,
391 SignatureAlgorithm,
392 SignedData,
393 SubjectPublicKeyInfo,
394 Time,
395 TrustAnchorV1,
396 TrustAnchorV1TbsCertificate,
397 U8,
398 RevokedCertificate,
399 RevokedCertificateExtension,
400 RevokedCertEntry,
401 IssuingDistributionPoint,
402}