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    use super::*;
425    #[cfg(feature = "alloc")]
426    use crate::crl::RevocationReason;
427    use std::prelude::v1::*;
428
429    #[test]
430    // Note: cert::parse_cert is crate-local visibility, and EndEntityCert doesn't expose the
431    //       inner Cert, or the serial number. As a result we test that the raw serial value
432    //       is read correctly here instead of in tests/integration.rs.
433    fn test_serial_read() {
434        let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
435        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
436        assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
437
438        let ee = include_bytes!("../tests/misc/serial_large_positive.der");
439        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
440        assert_eq!(
441            cert.serial.as_slice_less_safe(),
442            &[
443                0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
444                68, 209
445            ]
446        )
447    }
448
449    #[cfg(feature = "alloc")]
450    #[test]
451    fn test_spki_read() {
452        let ee = include_bytes!("../tests/ed25519/ee.der");
453        let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
454        // How did I get this lovely string of hex bytes?
455        // openssl x509 -in tests/ed25519/ee.der -pubkey -noout > pubkey.pem
456        // openssl ec -pubin -in pubkey.pem -outform DER -out pubkey.der
457        // xxd -plain -cols 1 pubkey.der
458        let expected_spki = [
459            0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
460            0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
461            0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
462            0x47, 0x5c,
463        ];
464        assert_eq!(expected_spki, *cert.subject_public_key_info())
465    }
466
467    #[test]
468    #[cfg(feature = "alloc")]
469    fn test_crl_distribution_point_netflix() {
470        let ee = include_bytes!("../tests/netflix/ee.der");
471        let inter = include_bytes!("../tests/netflix/inter.der");
472        let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
473        let cert =
474            Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
475
476        // The end entity certificate shouldn't have a distribution point.
477        assert!(ee_cert.crl_distribution_points.is_none());
478
479        // We expect to be able to parse the intermediate certificate's CRL distribution points.
480        let crl_distribution_points = cert
481            .crl_distribution_points()
482            .expect("missing distribution points extension")
483            .collect::<Result<Vec<_>, Error>>()
484            .expect("failed to parse distribution points");
485
486        // There should be one distribution point present.
487        assert_eq!(crl_distribution_points.len(), 1);
488        let crl_distribution_point = crl_distribution_points
489            .first()
490            .expect("missing distribution point");
491
492        // The distribution point shouldn't have revocation reasons listed.
493        assert!(crl_distribution_point.reasons.is_none());
494
495        // The distribution point shouldn't have a CRL issuer listed.
496        assert!(crl_distribution_point.crl_issuer.is_none());
497
498        // We should be able to parse the distribution point name.
499        let distribution_point_name = crl_distribution_point
500            .names()
501            .expect("failed to parse distribution point names")
502            .expect("missing distribution point name");
503
504        // We expect the distribution point name to be a sequence of GeneralNames, not a name
505        // relative to the CRL issuer.
506        let names = match distribution_point_name {
507            DistributionPointName::NameRelativeToCrlIssuer => {
508                panic!("unexpected name relative to crl issuer")
509            }
510            DistributionPointName::FullName(names) => names,
511        };
512
513        // The general names should parse.
514        let names = names
515            .collect::<Result<Vec<_>, Error>>()
516            .expect("failed to parse general names");
517
518        // There should be one general name.
519        assert_eq!(names.len(), 1);
520        let name = names.first().expect("missing general name");
521
522        // The general name should be a URI matching the expected value.
523        match name {
524            GeneralName::UniformResourceIdentifier(uri) => {
525                assert_eq!(
526                    uri.as_slice_less_safe(),
527                    "http://s.symcb.com/pca3-g3.crl".as_bytes()
528                );
529            }
530            _ => panic!("unexpected general name type"),
531        }
532    }
533
534    #[test]
535    #[cfg(feature = "alloc")]
536    fn test_crl_distribution_point_with_reasons() {
537        let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
538        let cert =
539            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
540
541        // We expect to be able to parse the intermediate certificate's CRL distribution points.
542        let crl_distribution_points = cert
543            .crl_distribution_points()
544            .expect("missing distribution points extension")
545            .collect::<Result<Vec<_>, Error>>()
546            .expect("failed to parse distribution points");
547
548        // There should be one distribution point present.
549        assert_eq!(crl_distribution_points.len(), 1);
550        let crl_distribution_point = crl_distribution_points
551            .first()
552            .expect("missing distribution point");
553
554        // The distribution point should include the expected revocation reasons, and no others.
555        let reasons = crl_distribution_point
556            .reasons
557            .as_ref()
558            .expect("missing revocation reasons");
559        let expected = &[
560            RevocationReason::KeyCompromise,
561            RevocationReason::AffiliationChanged,
562        ];
563        for reason in RevocationReason::iter() {
564            #[expect(clippy::as_conversions)]
565            // revocation reason is u8, infallible to convert to usize.
566            match expected.contains(&reason) {
567                true => assert!(reasons.bit_set(reason as usize)),
568                false => assert!(!reasons.bit_set(reason as usize)),
569            }
570        }
571    }
572
573    #[test]
574    #[cfg(feature = "alloc")]
575    fn test_crl_distribution_point_with_crl_issuer() {
576        let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
577        let cert =
578            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
579
580        // We expect to be able to parse the intermediate certificate's CRL distribution points.
581        let crl_distribution_points = cert
582            .crl_distribution_points()
583            .expect("missing distribution points extension")
584            .collect::<Result<Vec<_>, Error>>()
585            .expect("failed to parse distribution points");
586
587        // There should be one distribution point present.
588        assert_eq!(crl_distribution_points.len(), 1);
589        let crl_distribution_point = crl_distribution_points
590            .first()
591            .expect("missing distribution point");
592
593        // The CRL issuer should be present, but not anything else.
594        assert!(crl_distribution_point.crl_issuer.is_some());
595        assert!(crl_distribution_point.distribution_point.is_none());
596        assert!(crl_distribution_point.reasons.is_none());
597    }
598
599    #[test]
600    #[cfg(feature = "alloc")]
601    fn test_crl_distribution_point_bad_der() {
602        // Created w/
603        //   ascii2der -i tests/crl_distrib_point/unknown_tag.der.txt -o tests/crl_distrib_point/unknown_tag.der
604        let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
605        let cert =
606            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
607
608        // We expect there to be a distribution point extension, but parsing it should fail
609        // due to the unknown tag in the SEQUENCE.
610        let result = cert
611            .crl_distribution_points()
612            .expect("missing distribution points extension")
613            .collect::<Result<Vec<_>, Error>>();
614        assert!(matches!(result, Err(Error::BadDer)));
615    }
616
617    #[test]
618    #[cfg(feature = "alloc")]
619    fn test_crl_distribution_point_only_reasons() {
620        // Created w/
621        //   ascii2der -i tests/crl_distrib_point/only_reasons.der.txt -o tests/crl_distrib_point/only_reasons.der
622        let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
623        let cert =
624            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
625
626        // We expect there to be a distribution point extension, but parsing it should fail
627        // because no distribution points or cRLIssuer are set in the SEQUENCE, just reason codes.
628        let result = cert
629            .crl_distribution_points()
630            .expect("missing distribution points extension")
631            .collect::<Result<Vec<_>, Error>>();
632        assert!(matches!(result, Err(Error::MalformedExtensions)));
633    }
634
635    #[test]
636    #[cfg(feature = "alloc")]
637    fn test_crl_distribution_point_name_relative_to_issuer() {
638        let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
639        let cert =
640            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
641
642        // We expect to be able to parse the intermediate certificate's CRL distribution points.
643        let crl_distribution_points = cert
644            .crl_distribution_points()
645            .expect("missing distribution points extension")
646            .collect::<Result<Vec<_>, Error>>()
647            .expect("failed to parse distribution points");
648
649        // There should be one distribution point present.
650        assert_eq!(crl_distribution_points.len(), 1);
651        let crl_distribution_point = crl_distribution_points
652            .first()
653            .expect("missing distribution point");
654
655        assert!(crl_distribution_point.crl_issuer.is_none());
656        assert!(crl_distribution_point.reasons.is_none());
657
658        // We should be able to parse the distribution point name.
659        let distribution_point_name = crl_distribution_point
660            .names()
661            .expect("failed to parse distribution point names")
662            .expect("missing distribution point name");
663
664        // We expect the distribution point name to be a name relative to the CRL issuer.
665        assert!(matches!(
666            distribution_point_name,
667            DistributionPointName::NameRelativeToCrlIssuer
668        ));
669    }
670
671    #[test]
672    #[cfg(feature = "alloc")]
673    fn test_crl_distribution_point_unknown_name_tag() {
674        // Created w/
675        //   ascii2der -i tests/crl_distrib_point/unknown_dp_name_tag.der.txt > tests/crl_distrib_point/unknown_dp_name_tag.der
676        let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.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 one distribution point present.
688        assert_eq!(crl_distribution_points.len(), 1);
689        let crl_distribution_point = crl_distribution_points
690            .first()
691            .expect("missing distribution point");
692
693        // Parsing the distrubition point names should fail due to the unknown name tag.
694        let result = crl_distribution_point.names();
695        assert!(matches!(result, Err(Error::BadDer)))
696    }
697
698    #[test]
699    #[cfg(feature = "alloc")]
700    fn test_crl_distribution_point_multiple() {
701        let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
702        let cert =
703            Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
704
705        // We expect to be able to parse the intermediate certificate's CRL distribution points.
706        let crl_distribution_points = cert
707            .crl_distribution_points()
708            .expect("missing distribution points extension")
709            .collect::<Result<Vec<_>, Error>>()
710            .expect("failed to parse distribution points");
711
712        // There should be two distribution points present.
713        let (point_a, point_b) = (
714            crl_distribution_points
715                .first()
716                .expect("missing first distribution point"),
717            crl_distribution_points
718                .get(1)
719                .expect("missing second distribution point"),
720        );
721
722        fn get_names<'a>(
723            point: &'a CrlDistributionPoint<'a>,
724        ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
725            match point
726                .names()
727                .expect("failed to parse distribution point names")
728                .expect("missing distribution point name")
729            {
730                DistributionPointName::NameRelativeToCrlIssuer => {
731                    panic!("unexpected relative name")
732                }
733                DistributionPointName::FullName(names) => names,
734            }
735        }
736
737        fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
738            match name {
739                GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
740                _ => panic!("unexpected name type"),
741            }
742        }
743
744        // We expect to find three URIs across the two distribution points.
745        let expected_names = [
746            "http://example.com/crl.1.der".as_bytes(),
747            "http://example.com/crl.2.der".as_bytes(),
748            "http://example.com/crl.3.der".as_bytes(),
749        ];
750        let all_names = get_names(point_a)
751            .chain(get_names(point_b))
752            .collect::<Result<Vec<_>, Error>>()
753            .expect("failed to parse names");
754
755        assert_eq!(
756            all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
757            expected_names
758        );
759    }
760}