Skip to main content

webpki/
cert.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 pki_types::SubjectPublicKeyInfoDer;
17use pki_types::{CertificateDer, DnsName};
18
19use crate::der::{self, CONSTRUCTED, CONTEXT_SPECIFIC, DerIterator, FromDer, Tag};
20use crate::error::{DerTypeId, Error};
21use crate::public_values_eq;
22use crate::signed_data::SignedData;
23use crate::subject_name::{GeneralName, NameIterator, WildcardDnsNameRef};
24use crate::x509::{
25    DistributionPointName, Extension, ExtensionOid, remember_extension, set_extension_once,
26};
27
28/// A parsed X509 certificate.
29pub struct Cert<'a> {
30    pub(crate) serial: untrusted::Input<'a>,
31    pub(crate) signed_data: SignedData<'a>,
32    pub(crate) issuer: untrusted::Input<'a>,
33    pub(crate) validity: untrusted::Input<'a>,
34    pub(crate) subject: untrusted::Input<'a>,
35    pub(crate) spki: untrusted::Input<'a>,
36
37    pub(crate) basic_constraints: Option<untrusted::Input<'a>>,
38    // key usage (KU) extension (if any). When validating certificate revocation lists (CRLs) this
39    // field will be consulted to determine if the cert is allowed to sign CRLs. For cert validation
40    // this field is ignored (for more detail see in `verify_cert.rs` and
41    // `check_issuer_independent_properties`).
42    pub(crate) key_usage: Option<untrusted::Input<'a>>,
43    pub(crate) eku: Option<untrusted::Input<'a>>,
44    pub(crate) name_constraints: Option<untrusted::Input<'a>>,
45    pub(crate) subject_alt_name: Option<untrusted::Input<'a>>,
46    pub(crate) crl_distribution_points: Option<untrusted::Input<'a>>,
47    pub(crate) scts: Option<untrusted::Input<'a>>,
48
49    der: CertificateDer<'a>,
50}
51
52impl<'a> Cert<'a> {
53    pub(crate) fn from_der(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
54        let (tbs, signed_data) =
55            cert_der.read_all(Error::TrailingData(DerTypeId::Certificate), |cert_der| {
56                der::nested(
57                    cert_der,
58                    Tag::Sequence,
59                    Error::TrailingData(DerTypeId::SignedData),
60                    |der| {
61                        // limited to SEQUENCEs of size 2^16 or less.
62                        SignedData::from_der(der, der::TWO_BYTE_DER_SIZE)
63                    },
64                )
65            })?;
66
67        tbs.read_all(
68            Error::TrailingData(DerTypeId::CertificateTbsCertificate),
69            |tbs| {
70                version3(tbs)?;
71
72                let serial = lenient_certificate_serial_number(tbs)?;
73
74                let signature = der::expect_tag(tbs, Tag::Sequence)?;
75                // TODO: In mozilla::pkix, the comparison is done based on the
76                // normalized value (ignoring whether or not there is an optional NULL
77                // parameter for RSA-based algorithms), so this may be too strict.
78                if !public_values_eq(signature, signed_data.algorithm) {
79                    return Err(Error::SignatureAlgorithmMismatch);
80                }
81
82                let issuer = der::expect_tag(tbs, Tag::Sequence)?;
83                let validity = der::expect_tag(tbs, Tag::Sequence)?;
84                let subject = der::expect_tag(tbs, Tag::Sequence)?;
85                let spki = der::expect_tag(tbs, Tag::Sequence)?;
86
87                // In theory there could be fields [1] issuerUniqueID and [2]
88                // subjectUniqueID, but in practice there never are, and to keep the
89                // code small and simple we don't accept any certificates that do
90                // contain them.
91
92                let mut cert = Cert {
93                    signed_data,
94                    serial,
95                    issuer,
96                    validity,
97                    subject,
98                    spki,
99
100                    basic_constraints: None,
101                    key_usage: None,
102                    eku: None,
103                    name_constraints: None,
104                    subject_alt_name: None,
105                    crl_distribution_points: None,
106                    scts: None,
107
108                    der: CertificateDer::from(cert_der.as_slice_less_safe()),
109                };
110
111                // Skip over optional and unhandled:
112                //
113                // issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
114                //                      -- If present, version MUST be v2 or v3
115                // subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
116                //                      -- If present, version MUST be v2 or v3
117                for (tag, id) in [
118                    (Tag::ContextSpecificPrimitive1, DerTypeId::IssuerUniqueId),
119                    (Tag::ContextSpecificPrimitive2, DerTypeId::SubjectUniqueId),
120                ] {
121                    if tbs.peek(tag.into()) {
122                        der::nested(tbs, tag, Error::TrailingData(id), |tagged| {
123                            tagged.skip_to_end();
124                            Ok(())
125                        })?;
126                    }
127                }
128
129                // When used to read X509v3 Certificate.tbsCertificate.extensions, we allow
130                // the extensions to be empty.  This is in spite of RFC5280:
131                //
132                //   "If present, this field is a SEQUENCE of one or more certificate extensions."
133                //
134                // Unfortunately other implementations don't get this right, eg:
135                // - https://github.com/golang/go/issues/52319
136                // - https://github.com/openssl/openssl/issues/20877
137                const ALLOW_EMPTY: bool = true;
138
139                if !tbs.at_end() {
140                    der::nested(
141                        tbs,
142                        Tag::ContextSpecificConstructed3,
143                        Error::TrailingData(DerTypeId::CertificateExtensions),
144                        |tagged| {
145                            der::nested_of_mut(
146                                tagged,
147                                Tag::Sequence,
148                                Tag::Sequence,
149                                Error::TrailingData(DerTypeId::Extension),
150                                ALLOW_EMPTY,
151                                |extension| {
152                                    remember_cert_extension(
153                                        &mut cert,
154                                        &Extension::from_der(extension)?,
155                                    )
156                                },
157                            )
158                        },
159                    )?;
160                }
161
162                Ok(cert)
163            },
164        )
165    }
166
167    /// Returns a list of valid DNS names provided in the subject alternative names extension
168    ///
169    /// This function must not be used to implement custom DNS name verification.
170    /// Checking that a certificate is valid for a given subject name should always be done with
171    /// [EndEntityCert::verify_is_valid_for_subject_name].
172    ///
173    /// [EndEntityCert::verify_is_valid_for_subject_name]: crate::EndEntityCert::verify_is_valid_for_subject_name
174    pub fn valid_dns_names(&self) -> impl Iterator<Item = &'a str> {
175        NameIterator::new(self.subject_alt_name).filter_map(|result| {
176            let GeneralName::DnsName(presented_id) = result.ok()? else {
177                return None;
178            };
179
180            // if the name could be converted to a DNS name, return it; otherwise,
181            // keep going.
182            let dns_str = core::str::from_utf8(presented_id.as_slice_less_safe()).ok()?;
183            match DnsName::try_from(dns_str) {
184                Ok(_) => Some(dns_str),
185                Err(_) => {
186                    match WildcardDnsNameRef::try_from_ascii(presented_id.as_slice_less_safe()) {
187                        Ok(wildcard_dns_name) => Some(wildcard_dns_name.as_str()),
188                        Err(_) => None,
189                    }
190                }
191            }
192        })
193    }
194
195    /// Returns a list of valid URI names provided in the subject alternative names extension
196    ///
197    /// This function returns URIs as strings without performing validation beyond checking that
198    /// they are valid UTF-8.
199    pub fn valid_uri_names(&self) -> impl Iterator<Item = &'a str> {
200        NameIterator::new(self.subject_alt_name).filter_map(|result| {
201            let GeneralName::UniformResourceIdentifier(presented_id) = result.ok()? else {
202                return None;
203            };
204
205            // if the URI can be converted to a valid UTF-8 string, return it; otherwise,
206            // keep going.
207            core::str::from_utf8(presented_id.as_slice_less_safe()).ok()
208        })
209    }
210
211    /// Raw certificate serial number.
212    ///
213    /// This is in big-endian byte order, in twos-complement encoding.
214    ///
215    /// If the caller were to add an `INTEGER` tag and suitable length, this
216    /// would become a valid DER encoding.
217    pub fn serial(&self) -> &[u8] {
218        self.serial.as_slice_less_safe()
219    }
220
221    /// Raw DER-encoded certificate issuer.
222    ///
223    /// This does not include the outer `SEQUENCE` tag or length.
224    pub fn issuer(&self) -> &[u8] {
225        self.issuer.as_slice_less_safe()
226    }
227
228    /// Raw DER encoded certificate subject.
229    ///
230    /// This does not include the outer `SEQUENCE` tag or length.
231    pub fn subject(&self) -> &[u8] {
232        self.subject.as_slice_less_safe()
233    }
234
235    /// Get the RFC 5280-compliant [`SubjectPublicKeyInfoDer`] (SPKI) of this [`Cert`].
236    ///
237    /// This **does** include the outer `SEQUENCE` tag and length.
238    #[cfg(feature = "alloc")]
239    pub fn subject_public_key_info(&self) -> SubjectPublicKeyInfoDer<'static> {
240        // Our SPKI representation contains only the content of the RFC 5280 SEQUENCE
241        // So we wrap the SPKI contents back into a properly-encoded ASN.1 SEQUENCE
242        SubjectPublicKeyInfoDer::from(der::asn1_wrap(
243            Tag::Sequence,
244            self.spki.as_slice_less_safe(),
245        ))
246    }
247
248    /// Returns an iterator over the certificate's cRLDistributionPoints extension values, if any.
249    pub(crate) fn crl_distribution_points(
250        &self,
251    ) -> Option<impl Iterator<Item = Result<CrlDistributionPoint<'a>, Error>>> {
252        self.crl_distribution_points.map(DerIterator::new)
253    }
254
255    /// Raw DER-encoded representation of the certificate.
256    pub fn der(&self) -> CertificateDer<'a> {
257        self.der.clone() // This is cheap, just cloning a reference.
258    }
259}
260
261// mozilla::pkix supports v1, v2, v3, and v4, including both the implicit
262// (correct) and explicit (incorrect) encoding of v1. We allow only v3.
263fn version3(input: &mut untrusted::Reader<'_>) -> Result<(), Error> {
264    der::nested(
265        input,
266        Tag::ContextSpecificConstructed0,
267        Error::UnsupportedCertVersion,
268        |input| {
269            let version = u8::from_der(input)?;
270            if version != 2 {
271                // v3
272                return Err(Error::UnsupportedCertVersion);
273            }
274            Ok(())
275        },
276    )
277}
278
279pub(crate) fn lenient_certificate_serial_number<'a>(
280    input: &mut untrusted::Reader<'a>,
281) -> Result<untrusted::Input<'a>, Error> {
282    // https://tools.ietf.org/html/rfc5280#section-4.1.2.2:
283    // * Conforming CAs MUST NOT use serialNumber values longer than 20 octets."
284    // * "The serial number MUST be a positive integer [...]"
285    //
286    // However, we don't enforce these constraints, as there are widely-deployed trust anchors
287    // and many X.509 implementations in common use that violate these constraints. This is called
288    // out by the same section of RFC 5280 as cited above:
289    //   Note: Non-conforming CAs may issue certificates with serial numbers
290    //   that are negative or zero.  Certificate users SHOULD be prepared to
291    //   gracefully handle such certificates.
292    der::expect_tag(input, Tag::Integer)
293}
294
295fn remember_cert_extension<'a>(
296    cert: &mut Cert<'a>,
297    extension: &Extension<'a>,
298) -> Result<(), Error> {
299    // We don't do anything with certificate policies so we can safely ignore
300    // all policy-related stuff. We assume that the policy-related extensions
301    // are not marked critical.
302
303    use ExtensionOid::*;
304
305    remember_extension(extension, |id| {
306        let out = match id {
307            // id-ce-keyUsage 2.5.29.15.
308            Standard(15) => &mut cert.key_usage,
309
310            // id-ce-subjectAltName 2.5.29.17
311            Standard(17) => &mut cert.subject_alt_name,
312
313            // id-ce-basicConstraints 2.5.29.19
314            Standard(19) => &mut cert.basic_constraints,
315
316            // id-ce-nameConstraints 2.5.29.30
317            Standard(30) => &mut cert.name_constraints,
318
319            // id-ce-cRLDistributionPoints 2.5.29.31
320            Standard(31) => &mut cert.crl_distribution_points,
321
322            // id-ce-extKeyUsage 2.5.29.37
323            Standard(37) => &mut cert.eku,
324
325            // signedCertificateTimestampList 1.3.6.1.4.1.11129.2.4.2
326            SignedCertificateTimestampList => &mut cert.scts,
327
328            // Unsupported extension
329            _ => return extension.unsupported(),
330        };
331
332        set_extension_once(out, || {
333            extension.value.read_all(Error::BadDer, |value| match id {
334                // Unlike the other extensions we remember KU is a BitString and not a Sequence. We
335                // read the raw bytes here and parse at the time of use.
336                Standard(15) => Ok(value.read_bytes_to_end()),
337
338                // signedCertificateTimestampList is an OCTET STRING
339                SignedCertificateTimestampList => der::expect_tag(value, Tag::OctetString),
340
341                // All other remembered certificate extensions are wrapped in a Sequence.
342                _ => der::expect_tag(value, Tag::Sequence),
343            })
344        })
345    })
346}
347
348/// A certificate revocation list (CRL) distribution point, describing a source of
349/// CRL information for a given certificate as described in RFC 5280 section 4.2.3.13[^1].
350///
351/// [^1]: <https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.13>
352pub(crate) struct CrlDistributionPoint<'a> {
353    /// distributionPoint describes the location of CRL information.
354    distribution_point: Option<untrusted::Input<'a>>,
355
356    /// reasons holds a bit flag set of certificate revocation reasons associated with the
357    /// CRL distribution point.
358    pub(crate) reasons: Option<der::BitStringFlags<'a>>,
359
360    /// when the CRL issuer is not the certificate issuer, crl_issuer identifies the issuer of the
361    /// CRL.
362    pub(crate) crl_issuer: Option<untrusted::Input<'a>>,
363}
364
365impl<'a> CrlDistributionPoint<'a> {
366    /// Return the distribution point names (if any).
367    pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
368        self.distribution_point
369            .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
370            .transpose()
371    }
372}
373
374impl<'a> FromDer<'a> for CrlDistributionPoint<'a> {
375    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
376        // RFC 5280 section §4.2.1.13:
377        //   A DistributionPoint consists of three fields, each of which is optional:
378        //   distributionPoint, reasons, and cRLIssuer.
379        let mut result = CrlDistributionPoint {
380            distribution_point: None,
381            reasons: None,
382            crl_issuer: None,
383        };
384
385        der::nested(
386            reader,
387            Tag::Sequence,
388            Error::TrailingData(Self::TYPE_ID),
389            |der| {
390                const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
391                const REASONS_TAG: u8 = CONTEXT_SPECIFIC | 1;
392                const CRL_ISSUER_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED | 2;
393
394                while !der.at_end() {
395                    let (tag, value) = der::read_tag_and_get_value(der)?;
396                    match tag {
397                        DISTRIBUTION_POINT_TAG => {
398                            set_extension_once(&mut result.distribution_point, || Ok(value))?
399                        }
400                        REASONS_TAG => set_extension_once(&mut result.reasons, || {
401                            der::bit_string_flags(value)
402                        })?,
403                        CRL_ISSUER_TAG => set_extension_once(&mut result.crl_issuer, || Ok(value))?,
404                        _ => return Err(Error::BadDer),
405                    }
406                }
407
408                // RFC 5280 section §4.2.1.13:
409                //   a DistributionPoint MUST NOT consist of only the reasons field; either distributionPoint or
410                //   cRLIssuer MUST be present.
411                match (result.distribution_point, result.crl_issuer) {
412                    (None, None) => Err(Error::MalformedExtensions),
413                    _ => Ok(result),
414                }
415            },
416        )
417    }
418
419    const TYPE_ID: DerTypeId = DerTypeId::CrlDistributionPoint;
420}
421
422#[cfg(test)]
423mod tests {
424    #[cfg(feature = "alloc")]
425    use alloc::vec::Vec;
426
427    use super::*;
428    #[cfg(feature = "alloc")]
429    use crate::crl::RevocationReason;
430
431    #[test]
432    // Note: cert::parse_cert is crate-local visibility, and EndEntityCert doesn't expose the
433    //       inner Cert, or the serial number. As a result we test that the raw serial value
434    //       is read correctly here instead of in tests/integration.rs.
435    fn test_serial_read() {
436        let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
437        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
438        assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
439
440        let ee = include_bytes!("../tests/misc/serial_large_positive.der");
441        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
442        assert_eq!(
443            cert.serial.as_slice_less_safe(),
444            &[
445                0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
446                68, 209
447            ]
448        )
449    }
450
451    #[cfg(feature = "alloc")]
452    #[test]
453    fn test_spki_read() {
454        let ee = include_bytes!("../tests/ed25519/ee.der");
455        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
456        // How did I get this lovely string of hex bytes?
457        // openssl x509 -in tests/ed25519/ee.der -pubkey -noout > pubkey.pem
458        // openssl ec -pubin -in pubkey.pem -outform DER -out pubkey.der
459        // xxd -plain -cols 1 pubkey.der
460        let expected_spki = [
461            0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
462            0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
463            0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
464            0x47, 0x5c,
465        ];
466        assert_eq!(expected_spki, *cert.subject_public_key_info())
467    }
468
469    #[test]
470    #[cfg(feature = "alloc")]
471    fn test_crl_distribution_point_netflix() {
472        let ee = include_bytes!("../tests/netflix/ee.der");
473        let inter = include_bytes!("../tests/netflix/inter.der");
474        let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
475        let cert =
476            Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
477
478        // The end entity certificate shouldn't have a distribution point.
479        assert!(ee_cert.crl_distribution_points.is_none());
480
481        // We expect to be able to parse the intermediate certificate's CRL distribution points.
482        let crl_distribution_points = cert
483            .crl_distribution_points()
484            .expect("missing distribution points extension")
485            .collect::<Result<Vec<_>, Error>>()
486            .expect("failed to parse distribution points");
487
488        // There should be one distribution point present.
489        assert_eq!(crl_distribution_points.len(), 1);
490        let crl_distribution_point = crl_distribution_points
491            .first()
492            .expect("missing distribution point");
493
494        // The distribution point shouldn't have revocation reasons listed.
495        assert!(crl_distribution_point.reasons.is_none());
496
497        // The distribution point shouldn't have a CRL issuer listed.
498        assert!(crl_distribution_point.crl_issuer.is_none());
499
500        // We should be able to parse the distribution point name.
501        let distribution_point_name = crl_distribution_point
502            .names()
503            .expect("failed to parse distribution point names")
504            .expect("missing distribution point name");
505
506        // We expect the distribution point name to be a sequence of GeneralNames, not a name
507        // relative to the CRL issuer.
508        let names = match distribution_point_name {
509            DistributionPointName::NameRelativeToCrlIssuer => {
510                panic!("unexpected name relative to crl issuer")
511            }
512            DistributionPointName::FullName(names) => names,
513        };
514
515        // The general names should parse.
516        let names = names
517            .collect::<Result<Vec<_>, Error>>()
518            .expect("failed to parse general names");
519
520        // There should be one general name.
521        assert_eq!(names.len(), 1);
522        let name = names.first().expect("missing general name");
523
524        // The general name should be a URI matching the expected value.
525        match name {
526            GeneralName::UniformResourceIdentifier(uri) => {
527                assert_eq!(
528                    uri.as_slice_less_safe(),
529                    "http://s.symcb.com/pca3-g3.crl".as_bytes()
530                );
531            }
532            _ => panic!("unexpected general name type"),
533        }
534    }
535
536    #[test]
537    #[cfg(feature = "alloc")]
538    fn test_crl_distribution_point_with_reasons() {
539        let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
540        let cert =
541            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
542
543        // We expect to be able to parse the intermediate certificate's CRL distribution points.
544        let crl_distribution_points = cert
545            .crl_distribution_points()
546            .expect("missing distribution points extension")
547            .collect::<Result<Vec<_>, Error>>()
548            .expect("failed to parse distribution points");
549
550        // There should be one distribution point present.
551        assert_eq!(crl_distribution_points.len(), 1);
552        let crl_distribution_point = crl_distribution_points
553            .first()
554            .expect("missing distribution point");
555
556        // The distribution point should include the expected revocation reasons, and no others.
557        let reasons = crl_distribution_point
558            .reasons
559            .as_ref()
560            .expect("missing revocation reasons");
561        let expected = &[
562            RevocationReason::KeyCompromise,
563            RevocationReason::AffiliationChanged,
564        ];
565        for reason in RevocationReason::iter() {
566            #[expect(clippy::as_conversions)]
567            // revocation reason is u8, infallible to convert to usize.
568            match expected.contains(&reason) {
569                true => assert!(reasons.bit_set(reason as usize)),
570                false => assert!(!reasons.bit_set(reason as usize)),
571            }
572        }
573    }
574
575    #[test]
576    #[cfg(feature = "alloc")]
577    fn test_crl_distribution_point_with_crl_issuer() {
578        let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
579        let cert =
580            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
581
582        // We expect to be able to parse the intermediate certificate's CRL distribution points.
583        let crl_distribution_points = cert
584            .crl_distribution_points()
585            .expect("missing distribution points extension")
586            .collect::<Result<Vec<_>, Error>>()
587            .expect("failed to parse distribution points");
588
589        // There should be one distribution point present.
590        assert_eq!(crl_distribution_points.len(), 1);
591        let crl_distribution_point = crl_distribution_points
592            .first()
593            .expect("missing distribution point");
594
595        // The CRL issuer should be present, but not anything else.
596        assert!(crl_distribution_point.crl_issuer.is_some());
597        assert!(crl_distribution_point.distribution_point.is_none());
598        assert!(crl_distribution_point.reasons.is_none());
599    }
600
601    #[test]
602    #[cfg(feature = "alloc")]
603    fn test_crl_distribution_point_bad_der() {
604        // Created w/
605        //   ascii2der -i tests/crl_distrib_point/unknown_tag.der.txt -o tests/crl_distrib_point/unknown_tag.der
606        let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
607        let cert =
608            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
609
610        // We expect there to be a distribution point extension, but parsing it should fail
611        // due to the unknown tag in the SEQUENCE.
612        let result = cert
613            .crl_distribution_points()
614            .expect("missing distribution points extension")
615            .collect::<Result<Vec<_>, Error>>();
616        assert!(matches!(result, Err(Error::BadDer)));
617    }
618
619    #[test]
620    #[cfg(feature = "alloc")]
621    fn test_crl_distribution_point_only_reasons() {
622        // Created w/
623        //   ascii2der -i tests/crl_distrib_point/only_reasons.der.txt -o tests/crl_distrib_point/only_reasons.der
624        let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
625        let cert =
626            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
627
628        // We expect there to be a distribution point extension, but parsing it should fail
629        // because no distribution points or cRLIssuer are set in the SEQUENCE, just reason codes.
630        let result = cert
631            .crl_distribution_points()
632            .expect("missing distribution points extension")
633            .collect::<Result<Vec<_>, Error>>();
634        assert!(matches!(result, Err(Error::MalformedExtensions)));
635    }
636
637    #[test]
638    #[cfg(feature = "alloc")]
639    fn test_crl_distribution_point_name_relative_to_issuer() {
640        let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
641        let cert =
642            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
643
644        // We expect to be able to parse the intermediate certificate's CRL distribution points.
645        let crl_distribution_points = cert
646            .crl_distribution_points()
647            .expect("missing distribution points extension")
648            .collect::<Result<Vec<_>, Error>>()
649            .expect("failed to parse distribution points");
650
651        // There should be one distribution point present.
652        assert_eq!(crl_distribution_points.len(), 1);
653        let crl_distribution_point = crl_distribution_points
654            .first()
655            .expect("missing distribution point");
656
657        assert!(crl_distribution_point.crl_issuer.is_none());
658        assert!(crl_distribution_point.reasons.is_none());
659
660        // We should be able to parse the distribution point name.
661        let distribution_point_name = crl_distribution_point
662            .names()
663            .expect("failed to parse distribution point names")
664            .expect("missing distribution point name");
665
666        // We expect the distribution point name to be a name relative to the CRL issuer.
667        assert!(matches!(
668            distribution_point_name,
669            DistributionPointName::NameRelativeToCrlIssuer
670        ));
671    }
672
673    #[test]
674    #[cfg(feature = "alloc")]
675    fn test_crl_distribution_point_unknown_name_tag() {
676        // Created w/
677        //   ascii2der -i tests/crl_distrib_point/unknown_dp_name_tag.der.txt > tests/crl_distrib_point/unknown_dp_name_tag.der
678        let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.der");
679        let cert =
680            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
681
682        // We expect to be able to parse the intermediate certificate's CRL distribution points.
683        let crl_distribution_points = cert
684            .crl_distribution_points()
685            .expect("missing distribution points extension")
686            .collect::<Result<Vec<_>, Error>>()
687            .expect("failed to parse distribution points");
688
689        // There should be one distribution point present.
690        assert_eq!(crl_distribution_points.len(), 1);
691        let crl_distribution_point = crl_distribution_points
692            .first()
693            .expect("missing distribution point");
694
695        // Parsing the distrubition point names should fail due to the unknown name tag.
696        let result = crl_distribution_point.names();
697        assert!(matches!(result, Err(Error::BadDer)))
698    }
699
700    #[test]
701    #[cfg(feature = "alloc")]
702    fn test_crl_distribution_point_multiple() {
703        let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
704        let cert =
705            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
706
707        // We expect to be able to parse the intermediate certificate's CRL distribution points.
708        let crl_distribution_points = cert
709            .crl_distribution_points()
710            .expect("missing distribution points extension")
711            .collect::<Result<Vec<_>, Error>>()
712            .expect("failed to parse distribution points");
713
714        // There should be two distribution points present.
715        let (point_a, point_b) = (
716            crl_distribution_points
717                .first()
718                .expect("missing first distribution point"),
719            crl_distribution_points
720                .get(1)
721                .expect("missing second distribution point"),
722        );
723
724        fn get_names<'a>(
725            point: &'a CrlDistributionPoint<'a>,
726        ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
727            match point
728                .names()
729                .expect("failed to parse distribution point names")
730                .expect("missing distribution point name")
731            {
732                DistributionPointName::NameRelativeToCrlIssuer => {
733                    panic!("unexpected relative name")
734                }
735                DistributionPointName::FullName(names) => names,
736            }
737        }
738
739        fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
740            match name {
741                GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
742                _ => panic!("unexpected name type"),
743            }
744        }
745
746        // We expect to find three URIs across the two distribution points.
747        let expected_names = [
748            "http://example.com/crl.1.der".as_bytes(),
749            "http://example.com/crl.2.der".as_bytes(),
750            "http://example.com/crl.3.der".as_bytes(),
751        ];
752        let all_names = get_names(point_a)
753            .chain(get_names(point_b))
754            .collect::<Result<Vec<_>, Error>>()
755            .expect("failed to parse names");
756
757        assert_eq!(
758            all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
759            expected_names
760        );
761    }
762}