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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::fmt;
use crate::crypto::SignatureVerifier;
use crate::diagnostic::VerificationDiagnostic;
use crate::store::CertificateStore;
use crate::unverified_chain::UnverifiedCertificateChain;
use crate::validated_chain::ValidatedCertificateChain;
use crate::{Certificate, CertificateExt, PolicyFailureReason, ValidationPolicy};
/// Reports a diagnostic to an optional callback, building it only if a callback
/// is present.
macro_rules! diagnose {
($diagnostics:expr, $diagnostic:expr) => {
if let Some(callback) = $diagnostics.as_deref_mut() {
callback($diagnostic);
}
};
}
/// Validates an X.509 certificate chain against a set of root certificates and
/// a [`ValidationPolicy`], using the crypto backend selected by this crate's
/// feature flags.
///
/// ```ignore
/// let validator = x509_validator::Validator::with_policy(roots, policy);
/// ```
pub struct Validator<'a, P> {
/// The trusted root certificates used to anchor chain validation.
root_certificates: CertificateStore<'a>,
crypto: &'a dyn SignatureVerifier,
/// The policy applied to candidate chains during validation.
policy: P,
}
impl<'a, P> Validator<'a, P>
where
P: ValidationPolicy,
{
/// Creates a validator with the given root certificates, policy and backend.
///
/// - Parameters:
/// - root_certificates: The trusted root certificates.
/// - policy: The verification policy.
pub fn with_policy_and_backend(
root_certificates: CertificateStore<'a>,
policy: P,
crypto: &'a dyn SignatureVerifier,
) -> Self {
Self {
root_certificates,
crypto,
policy,
}
}
/// Creates a validator with the given root certificates and policy, using
/// the crypto backend selected by this crate's feature flags.
///
/// - Parameters:
/// - root_certificates: The trusted root certificates.
/// - policy: The verification policy.
///
/// # Panics
///
/// Validation panics unless exactly one backend feature is enabled, since
/// no single default backend can be determined otherwise; see
/// [`crate::crypto::default_provider`].
pub fn with_policy(root_certificates: CertificateStore<'a>, policy: P) -> Self {
Self::with_policy_and_backend(root_certificates, policy, crate::crypto::default_provider())
}
/// Validates a leaf certificate by building chains through intermediate certificates to the root store.
///
/// - Parameters:
/// - leaf: The leaf certificate to validate.
/// - intermediates: A store of intermediate certificates that may form part of the chain.
/// - Returns: A [`ChainValidationResult`] indicating whether the certificate is valid.
pub fn validate(
&self,
leaf: &Certificate<'a>,
intermediates: &CertificateStore<'a>,
) -> ChainValidationResult<'a> {
self.validate_inner(leaf, intermediates, None)
}
/// Validates a leaf certificate by building chains through intermediate certificates to the root store,
/// reporting each step to a callback.
///
/// - Parameters:
/// - leaf: The leaf certificate to validate.
/// - intermediates: A store of intermediate certificates that may form part of the chain.
/// - diagnostic_callback: A closure invoked with diagnostic events during validation.
/// - Returns: A [`ChainValidationResult`] indicating whether the certificate is valid.
pub fn validate_with_diagnostics(
&self,
leaf: &Certificate<'a>,
intermediates: &CertificateStore<'a>,
diagnostic_callback: &mut dyn FnMut(VerificationDiagnostic<'a>),
) -> ChainValidationResult<'a> {
self.validate_inner(leaf, intermediates, Some(diagnostic_callback))
}
fn validate_inner(
&self,
leaf: &Certificate<'a>,
intermediates: &CertificateStore<'a>,
mut diagnostics: Option<&mut dyn FnMut(VerificationDiagnostic<'a>)>,
) -> ChainValidationResult<'a> {
// First check: does this leaf certificate contain critical extensions that are not satisfied by the policy?
// If so, reject the chain.
if has_unhandled_critical_extensions(leaf, &self.policy) {
diagnose!(
diagnostics,
VerificationDiagnostic::leaf_certificate_has_unhandled_critical_extension(
leaf.clone(),
self.policy
.verifying_critical_extensions(),
)
);
return Err(vec![PolicyFailure::new(
UnverifiedCertificateChain::new(vec![leaf.clone()]),
PolicyFailureReason::new("leaf certificate has unhandled critical extension"),
)]);
}
let mut policy_failures = Vec::new();
// Second check: is this leaf _already in_ the certificate store? If it is, we can just trust it directly.
//
// Note that this requires an _exact match_: if there isn't an exact match, we'll fall back to chain building,
// which may let us chain through another variant of this certificate and build a valid chain. This is a very
// deliberate choice: certificates that assert the same combination of (subject, public key, SAN) but different
// extensions or policies should not be tolerated by this check, and will be ignored.
let leaf_key = leaf.subject_key();
if self
.root_certificates
.find_by_subject(&leaf_key)
.iter()
.any(|c| c == leaf)
{
let chain = UnverifiedCertificateChain::new(vec![leaf.clone()]);
match self
.policy
.chain_meets_policy_requirements(&chain)
{
Ok(()) => {
// We're good!
diagnose!(
diagnostics,
VerificationDiagnostic::found_valid_certificate_chain(vec![leaf.clone()])
);
return Ok(ValidatedCertificateChain::new_unchecked(vec![leaf.clone()]));
}
Err(reason) => {
diagnose!(
diagnostics,
VerificationDiagnostic::leaf_certificate_is_in_the_root_store_but_does_not_meet_policy(leaf.clone(), reason.clone())
);
policy_failures.push(PolicyFailure::new(chain, reason));
}
}
}
let mut stack: Vec<Vec<Certificate<'a>>> = vec![vec![leaf.clone()]];
// This is essentially a DFS of the certificate tree. We attempt to iteratively build up possible chains.
while let Some(partial_chain) = stack.pop() {
diagnose!(
diagnostics,
VerificationDiagnostic::searching_for_issuer_of_partial_chain(
partial_chain.clone(),
)
);
let tip = partial_chain.last().unwrap();
let issuer_key = tip.issuer_key();
// We want to search for parents. Our preferred parent comes from the root store, as this will potentially
// produce smaller chains.
let mut root_candidates = self
.root_certificates
.find_by_subject(&issuer_key)
.to_vec();
// We then want to sort by suitability.
sort_by_suitability_for_issuing(&mut root_candidates, tip);
if !root_candidates.is_empty() {
diagnose!(
diagnostics,
VerificationDiagnostic::found_candidate_issuers_of_partial_chain_in_root_store(
partial_chain.clone(),
root_candidates.clone(),
)
);
}
// Each of these is now potentially a valid unverified chain.
for candidate in &root_candidates {
if should_skip_adding_certificate(
candidate,
&partial_chain,
self.crypto,
&self.policy,
&mut diagnostics,
) {
continue;
}
let mut chain_certs = partial_chain.clone();
chain_certs.push(candidate.clone());
let chain = UnverifiedCertificateChain::new(chain_certs.clone());
match self
.policy
.chain_meets_policy_requirements(&chain)
{
Ok(()) => {
// We're good!
diagnose!(
diagnostics,
VerificationDiagnostic::found_valid_certificate_chain(
chain_certs.clone(),
)
);
return Ok(ValidatedCertificateChain::new_unchecked(chain_certs));
}
Err(reason) => {
diagnose!(
diagnostics,
VerificationDiagnostic::chain_fails_to_meet_policy(
chain_certs,
reason.clone(),
)
);
policy_failures.push(PolicyFailure::new(chain, reason));
}
}
}
let mut intermediate_candidates = intermediates
.find_by_subject(&issuer_key)
.to_vec();
// We then want to sort by suitability.
sort_by_suitability_for_issuing(&mut intermediate_candidates, tip);
if !intermediate_candidates.is_empty() {
diagnose!(
diagnostics,
VerificationDiagnostic::found_candidate_issuers_of_partial_chain_in_intermediate_store(
partial_chain.clone(),
intermediate_candidates.clone(),
)
);
}
// we need to reverse the order of the already sorted intermediates because
// we will push them on to the `stack` which in turn will
// consume them in the reverse order that they have been pushed onto the stack
for candidate in intermediate_candidates
.into_iter()
.rev()
{
if should_skip_adding_certificate(
&candidate,
&partial_chain,
self.crypto,
&self.policy,
&mut diagnostics,
) {
continue;
}
let mut next = partial_chain.clone();
next.push(candidate);
stack.push(next);
}
}
diagnose!(
diagnostics,
VerificationDiagnostic::could_not_validate_leaf_certificate(leaf.clone())
);
Err(policy_failures)
}
}
fn has_unhandled_critical_extensions(
cert: &Certificate<'_>,
policy: &impl ValidationPolicy,
) -> bool {
let handled = policy.verifying_critical_extensions();
cert.tbs_certificate
.iter_extensions()
.any(|ext| ext.critical && !handled.contains(&ext.oid))
}
fn sort_by_suitability_for_issuing<'a>(
candidates: &mut [Certificate<'a>],
subject: &Certificate<'a>,
) {
// First, an early exit. If the subject doesn't have an AKI extension, we don't need
// to do anything.
let subject_aki = subject.authority_key_identifier();
// Medium preference if we have no SKI. The SKI is present: if the two match, this is
// higher preference; if they don't match, it's lower.
let rank = |candidate: &Certificate<'a>| -> u8 {
match (subject_aki, candidate.subject_key_identifier()) {
(Some(aki), Some(ski)) if aki == ski => 0,
(_, None) => 1,
(None, Some(_)) => 1,
(Some(_), Some(_)) => 2,
}
};
candidates.sort_by_key(rank);
}
fn should_skip_adding_certificate<'a>(
candidate: &Certificate<'a>,
partial_chain: &[Certificate<'a>],
crypto: &dyn SignatureVerifier,
policy: &impl ValidationPolicy,
diagnostics: &mut Option<&mut dyn FnMut(VerificationDiagnostic<'a>)>,
) -> bool {
// We want to confirm that the certificate has no unhandled critical extensions. If it does, we can't build the chain.
if has_unhandled_critical_extensions(candidate, policy) {
diagnose!(
diagnostics,
VerificationDiagnostic::issuer_has_unhandled_critical_extension(
candidate.clone(),
partial_chain.to_vec(),
policy.verifying_critical_extensions(),
)
);
return true;
}
// We don't want to re-add the same certificate to the chain: that will always produce a chain that
// could have been shorter.
if partial_chain
.iter()
.any(|existing| existing.has_same_identity_as(candidate))
{
diagnose!(
diagnostics,
VerificationDiagnostic::issuer_is_already_in_the_chain(
partial_chain.to_vec(),
candidate.clone(),
)
);
return true;
}
// We check the signature here: if the signature isn't valid, don't try to apply policy.
let tip = partial_chain.last().unwrap();
let signature_verifies = crypto
.verify_signature(
&tip.signature_algorithm,
candidate.public_key(),
tip.tbs_certificate.as_ref(),
tip.signature_value.as_ref(),
)
.is_ok();
if !signature_verifies {
diagnose!(
diagnostics,
VerificationDiagnostic::issuer_has_not_signed_certificate(
candidate.clone(),
partial_chain.to_vec(),
)
);
}
!signature_verifies
}
/// The result of validating a certificate chain.
///
/// The error case carries every chain that was built and rejected, each with
/// the reason it was rejected, in the order the implementation considered them.
pub type ChainValidationResult<'a> = Result<ValidatedCertificateChain<'a>, Vec<PolicyFailure<'a>>>;
/// A chain that was built but rejected by policy, and why.
#[derive(Clone)]
pub struct PolicyFailure<'a> {
pub chain: UnverifiedCertificateChain<'a>,
pub policy_failure_reason: PolicyFailureReason,
}
impl<'a> PolicyFailure<'a> {
pub fn new(
chain: UnverifiedCertificateChain<'a>,
policy_failure_reason: PolicyFailureReason,
) -> Self {
Self {
chain,
policy_failure_reason,
}
}
}
impl fmt::Display for PolicyFailure<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.policy_failure_reason)
}
}
impl fmt::Debug for PolicyFailure<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} (chain of {})",
self.policy_failure_reason,
self.chain.len()
)
}
}