Skip to main content

webpki/
cert.rs

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