tlspuffin/tls/rustls/
anchors.rs

1use crate::tls::rustls::msgs::handshake::{
2    DistinguishedName, DistinguishedNames, VecU16OfPayloadU16,
3};
4use crate::tls::rustls::{key, x509};
5
6/// A trust anchor, commonly known as a "Root Certificate."
7#[derive(Debug, Clone)]
8pub struct OwnedTrustAnchor {
9    subject: Vec<u8>,
10    spki: Vec<u8>,
11    name_constraints: Option<Vec<u8>>,
12}
13
14impl OwnedTrustAnchor {
15    /// Get a `webpki::TrustAnchor` by borrowing the owned elements.
16    pub fn to_trust_anchor(&self) -> webpki::TrustAnchor<'_> {
17        webpki::TrustAnchor {
18            subject: &self.subject,
19            spki: &self.spki,
20            name_constraints: self.name_constraints.as_deref(),
21        }
22    }
23
24    /// Constructs an `OwnedTrustAnchor` from its components.
25    ///
26    /// `subject` is the subject field of the trust anchor.
27    ///
28    /// `spki` is the `subjectPublicKeyInfo` field of the trust anchor.
29    ///
30    /// `name_constraints` is the value of a DER-encoded name constraints to
31    /// apply for this trust anchor, if any.
32    pub fn from_subject_spki_name_constraints(
33        subject: impl Into<Vec<u8>>,
34        spki: impl Into<Vec<u8>>,
35        name_constraints: Option<impl Into<Vec<u8>>>,
36    ) -> Self {
37        Self {
38            subject: subject.into(),
39            spki: spki.into(),
40            name_constraints: name_constraints.map(|x| x.into()),
41        }
42    }
43}
44
45/// A container for root certificates able to provide a root-of-trust
46/// for connection authentication.
47#[derive(Debug, Clone)]
48pub struct RootCertStore {
49    /// The list of roots.
50    pub roots: Vec<OwnedTrustAnchor>,
51}
52
53impl RootCertStore {
54    /// Make a new, empty `RootCertStore`.
55    pub fn empty() -> Self {
56        Self { roots: Vec::new() }
57    }
58
59    /// Return true if there are no certificates.
60    pub fn is_empty(&self) -> bool {
61        self.len() == 0
62    }
63
64    /// Say how many certificates are in the container.
65    pub fn len(&self) -> usize {
66        self.roots.len()
67    }
68
69    /// Return the Subject Names for certificates in the container.
70    pub fn subjects(&self) -> DistinguishedNames {
71        let mut r = VecU16OfPayloadU16(Vec::new());
72
73        for ota in &self.roots {
74            let mut name = Vec::new();
75            name.extend_from_slice(&ota.subject);
76            x509::wrap_in_sequence(&mut name);
77            r.0.push(DistinguishedName::new(name));
78        }
79
80        r
81    }
82
83    /// Add a single DER-encoded certificate to the store.
84    pub fn add(&mut self, der: &key::Certificate) -> Result<(), webpki::Error> {
85        let ta = webpki::TrustAnchor::try_from_cert_der(&der.0)?;
86        let ota = OwnedTrustAnchor::from_subject_spki_name_constraints(
87            ta.subject,
88            ta.spki,
89            ta.name_constraints,
90        );
91        self.roots.push(ota);
92        Ok(())
93    }
94
95    /// Adds all the given TrustAnchors `anchors`.  This does not
96    /// fail.
97    pub fn add_server_trust_anchors(
98        &mut self,
99        trust_anchors: impl Iterator<Item = OwnedTrustAnchor>,
100    ) {
101        self.roots.extend(trust_anchors)
102    }
103
104    /// Parse the given DER-encoded certificates and add all that can be parsed
105    /// in a best-effort fashion.
106    ///
107    /// This is because large collections of root certificates often
108    /// include ancient or syntactically invalid certificates.
109    ///
110    /// Returns the number of certificates added, and the number that were ignored.
111    pub fn add_parsable_certificates(&mut self, der_certs: &[Vec<u8>]) -> (usize, usize) {
112        let mut valid_count = 0;
113        let mut invalid_count = 0;
114
115        for der_cert in der_certs {
116            match self.add(&key::Certificate(der_cert.clone())) {
117                Ok(_) => valid_count += 1,
118                Err(_err) => invalid_count += 1,
119            }
120        }
121
122        (valid_count, invalid_count)
123    }
124}