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