1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use crate::cert::{certificate_serial_number, Cert};
use crate::{
cert::{parse_cert_internal, EndEntityOrCa},
der, Error,
};
#[derive(Debug)]
pub struct TrustAnchor<'a> {
pub subject: &'a [u8],
pub spki: &'a [u8],
pub name_constraints: Option<&'a [u8]>,
}
#[derive(Debug)]
pub struct TlsServerTrustAnchors<'a>(pub &'a [TrustAnchor<'a>]);
#[derive(Debug)]
pub struct TlsClientTrustAnchors<'a>(pub &'a [TrustAnchor<'a>]);
impl<'a> TrustAnchor<'a> {
pub fn try_from_cert_der(cert_der: &'a [u8]) -> Result<Self, Error> {
let cert_der = untrusted::Input::from(cert_der);
match parse_cert_internal(
cert_der,
EndEntityOrCa::EndEntity,
possibly_invalid_certificate_serial_number,
) {
Ok(cert) => Ok(Self::from(cert)),
Err(Error::UnsupportedCertVersion) => parse_cert_v1(cert_der).or(Err(Error::BadDer)),
Err(err) => Err(err),
}
}
}
fn possibly_invalid_certificate_serial_number(input: &mut untrusted::Reader) -> Result<(), Error> {
skip(input, der::Tag::Integer)
}
impl<'a> From<Cert<'a>> for TrustAnchor<'a> {
fn from(cert: Cert<'a>) -> Self {
Self {
subject: cert.subject.as_slice_less_safe(),
spki: cert.spki.value().as_slice_less_safe(),
name_constraints: cert.name_constraints.map(|nc| nc.as_slice_less_safe()),
}
}
}
fn parse_cert_v1(cert_der: untrusted::Input) -> Result<TrustAnchor, Error> {
cert_der.read_all(Error::BadDer, |cert_der| {
der::nested(cert_der, der::Tag::Sequence, Error::BadDer, |cert_der| {
let anchor = der::nested(cert_der, der::Tag::Sequence, Error::BadDer, |tbs| {
certificate_serial_number(tbs)?;
skip(tbs, der::Tag::Sequence)?;
skip(tbs, der::Tag::Sequence)?;
skip(tbs, der::Tag::Sequence)?;
let subject = der::expect_tag_and_get_value(tbs, der::Tag::Sequence)?;
let spki = der::expect_tag_and_get_value(tbs, der::Tag::Sequence)?;
Ok(TrustAnchor {
subject: subject.as_slice_less_safe(),
spki: spki.as_slice_less_safe(),
name_constraints: None,
})
});
skip(cert_der, der::Tag::Sequence)?;
skip(cert_der, der::Tag::BitString)?;
anchor
})
})
}
fn skip(input: &mut untrusted::Reader, tag: der::Tag) -> Result<(), Error> {
der::expect_tag_and_get_value(input, tag).map(|_| ())
}