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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::der_parser::Oid;
use crate::extensions::{GeneralName, GeneralSubtree};
use crate::oid_registry::OID_X509_EXT_NAME_CONSTRAINTS;
use crate::unverified_chain::UnverifiedCertificateChain;
use crate::{PolicyEvaluationResult, PolicyFailureReason, ValidationPolicy};
/// id-ce-nameConstraints, RFC 5280 ยง4.2.1.10: 2.5.29.30.
fn name_constraints_oid() -> Oid<'static> {
OID_X509_EXT_NAME_CONSTRAINTS
}
/// A sub-policy of the [`RFC5280Policy`] that polices the nameConstraints extension.
///
/// [`RFC5280Policy`]: crate::rfc5280::RFC5280Policy
pub struct NameConstraintsPolicy;
impl ValidationPolicy for NameConstraintsPolicy {
fn verifying_critical_extensions(&self) -> Vec<Oid<'static>> {
vec![name_constraints_oid()]
}
fn chain_meets_policy_requirements(
&self,
chain: &UnverifiedCertificateChain<'_>,
) -> PolicyEvaluationResult {
// The rules for name constraints come from https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.10.
//
// Some notes:
//
// - RFC 5280 says we MUST validate directoryName constraints, and SHOULD validate rfc822Name, URI, dNSName, and
// iPAddress constraints. However, proper directoryName constraint validation requires a complex comparison
// algorithm. Most implementations skip that and just compare the distinguished names by exact equality. As
// such, we deliberately do not validate directoryName constraints at all: if a certificate's nameConstraints
// extension contains a directoryName subtree, we reject the chain.
// - If there's a constraint we don't support and can't validate, we MUST reject the cert.
//
// Our algorithm is recursive: starting from the root and moving towards the leaf, for each CA
// cert we apply the name constraints to all of the other certificates in the chain. The one exception
// is for self-signed certs where, much like with basic constraints, we briefly pretend that the
// self-signed cert issued itself and enforce its own name constraints on it.
if chain.len() == 1 {
return Self::validate_name_constraints(chain, chain.leaf(), &[0]);
}
for issuer_index in (1..chain.len()).rev() {
let issuer = &chain[issuer_index];
let subject_indices: Vec<usize> = (0..issuer_index).collect();
Self::validate_name_constraints(chain, issuer, &subject_indices)?;
}
Ok(())
}
}
impl NameConstraintsPolicy {
fn validate_name_constraints(
chain: &UnverifiedCertificateChain<'_>,
issuer: &crate::Certificate<'_>,
subject_indices: &[usize],
) -> PolicyEvaluationResult {
// If we couldn't decode these, fail validation.
let constraints = issuer
.tbs_certificate
.name_constraints()
.map_err(|error| {
PolicyFailureReason::new(format!(
"unable to decode name constraints from {:?}: {}",
issuer, error
))
})?;
let Some(constraints) = constraints else {
// No name constraints to enforce, we're done.
return Ok(());
};
let constraints = &constraints.value;
for &i in subject_indices {
let cert = &chain[i];
for name in Self::names(cert)? {
if let Some(permitted) = &constraints.permitted_subtrees {
Self::validate_permitted_subtrees(permitted, &name)?;
}
if let Some(excluded) = &constraints.excluded_subtrees {
Self::validate_excluded_subtrees(excluded, &name)?;
}
}
}
Ok(())
}
fn names<'a>(
cert: &'a crate::Certificate<'a>,
) -> Result<Vec<GeneralName<'a>>, PolicyFailureReason> {
let mut names = vec![GeneralName::DirectoryName(cert.subject().clone())];
let san = cert
.tbs_certificate
.subject_alternative_name()
.map_err(|error| {
PolicyFailureReason::new(format!(
"unable to decode subject alternative name from {:?}: {}",
cert, error
))
})?;
if let Some(san) = san {
for name in &san.value.general_names {
if matches!(name, GeneralName::Invalid(_, _)) {
// The parser surfaces a name it could not decode as `Invalid` rather than
// failing the extension parse. Such a name can never be compared against a
// constraint, so treating it as just another entry would silently exempt it
// from every subtree check. Refuse the chain instead.
return Err(PolicyFailureReason::new(format!(
"unable to decode a subject alternative name from {:?}",
cert
)));
}
names.push(name.clone());
}
}
Ok(names)
}
/// Whether a subtree's base names a form this policy cannot compare against.
///
/// RFC 5280 requires rejecting a chain constrained by something we cannot evaluate, so this
/// is decided by the constraint alone: whether the certificate happens to carry a name of the
/// same form has no bearing on it.
fn constraint_kind_is_unsupported(constraint: &GeneralName<'_>) -> bool {
!matches!(
constraint,
GeneralName::DNSName(_)
| GeneralName::IPAddress(_)
| GeneralName::URI(_)
| GeneralName::DirectoryName(_)
)
}
fn validate_excluded_subtrees(
excluded_subtrees: &[GeneralSubtree<'_>],
name: &GeneralName<'_>,
) -> PolicyEvaluationResult {
// For excluded trees, if _any_ match then the name is forbidden.
for subtree in excluded_subtrees {
let constraint = &subtree.base;
if matches!(constraint, GeneralName::DirectoryName(_))
&& matches!(name, GeneralName::DirectoryName(_))
{
// We immediately reject the chain if there is a directoryName name constraint involved: correct
// validation requires the full RFC 5280 comparison algorithm which we currently do not implement.
return Err(PolicyFailureReason::new(
"directoryName name constraints are not supported",
));
}
if Self::constraint_kind_is_unsupported(constraint) {
// We don't support constraints on these!
//
// Of the set that's currently unsupported, we should probably support rfc822Name (a.k.a. email address).
// For now we're omitting it, but at some point someone is going to run into this limitation and we'll want to come
// back and fix it.
return Err(PolicyFailureReason::new(
"unable to validate excluded subtree, unsupported constraint kind",
));
}
let matched = match (name, constraint) {
(GeneralName::DNSName(name_value), GeneralName::DNSName(constraint_value)) => {
Self::dns_name_matches_constraint(
name_value.as_bytes(),
constraint_value.as_bytes(),
)
}
(GeneralName::IPAddress(name_value), GeneralName::IPAddress(constraint_value)) => {
Self::ip_address_matches_constraint(name_value, constraint_value)
}
(GeneralName::URI(name_value), GeneralName::URI(constraint_value)) => {
Self::uri_name_matches_constraint(
name_value.as_bytes(),
constraint_value.as_bytes(),
)
}
(GeneralName::DirectoryName(_), GeneralName::DirectoryName(_)) => {
unreachable!("handled above")
}
// We support this constraint's kind, but the current name isn't of that type.
_ => continue,
};
if matched {
return Err(PolicyFailureReason::new("name is in an excluded subtree"));
}
}
// No policy rejected this.
Ok(())
}
fn validate_permitted_subtrees(
permitted_subtrees: &[GeneralSubtree<'_>],
name: &GeneralName<'_>,
) -> PolicyEvaluationResult {
let mut evaluated_at_least_one_constraint = false;
for subtree in permitted_subtrees {
let constraint = &subtree.base;
if matches!(constraint, GeneralName::DirectoryName(_))
&& matches!(name, GeneralName::DirectoryName(_))
{
// We immediately reject the chain if there is a directoryName name constraint involved: correct
// validation requires the full RFC 5280 comparison algorithm which we currently do not implement.
return Err(PolicyFailureReason::new(
"directoryName name constraints are not supported",
));
}
if Self::constraint_kind_is_unsupported(constraint) {
// We don't support constraints on these!
//
// Of the set that's currently unsupported, we should probably support rfc822Name (a.k.a. email address).
// For now we're omitting it, but at some point someone is going to run into this limitation and we'll want to come
// back and fix it.
return Err(PolicyFailureReason::new(
"unable to validate permitted subtree, unsupported constraint kind",
));
}
// A match on any of these means we're good.
let matched = match (name, constraint) {
(GeneralName::DNSName(name_value), GeneralName::DNSName(constraint_value)) => {
evaluated_at_least_one_constraint = true;
Self::dns_name_matches_constraint(
name_value.as_bytes(),
constraint_value.as_bytes(),
)
}
(GeneralName::IPAddress(name_value), GeneralName::IPAddress(constraint_value)) => {
evaluated_at_least_one_constraint = true;
Self::ip_address_matches_constraint(name_value, constraint_value)
}
(GeneralName::URI(name_value), GeneralName::URI(constraint_value)) => {
evaluated_at_least_one_constraint = true;
Self::uri_name_matches_constraint(
name_value.as_bytes(),
constraint_value.as_bytes(),
)
}
(GeneralName::DirectoryName(_), GeneralName::DirectoryName(_)) => {
unreachable!("handled above")
}
// We support this constraint's kind, but the current name isn't of that type. This means we
// didn't evaluate this constraint.
_ => continue,
};
if matched {
return Ok(());
}
}
// Uh-oh, nothing matched! This is only a problem if we have at least one constraint for the given type.
if !evaluated_at_least_one_constraint {
return Ok(());
}
Err(PolicyFailureReason::new(
"unable to validate permitted subtree, no matches",
))
}
}