tlspuffin/tls/rustls/
anchors.rs1use crate::tls::rustls::msgs::handshake::{
2 DistinguishedName, DistinguishedNames, VecU16OfPayloadU16,
3};
4use crate::tls::rustls::{key, x509};
5
6#[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 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 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#[derive(Debug, Clone)]
48pub struct RootCertStore {
49 pub roots: Vec<OwnedTrustAnchor>,
51}
52
53impl RootCertStore {
54 pub fn empty() -> Self {
56 Self { roots: Vec::new() }
57 }
58
59 pub fn is_empty(&self) -> bool {
61 self.len() == 0
62 }
63
64 pub fn len(&self) -> usize {
66 self.roots.len()
67 }
68
69 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 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 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 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}