1use alloc::vec::Vec;
2use core::hash::{Hash, Hasher};
3
4use pki_types::CertificateRevocationListDer;
5use webpki::{CertRevocationList, ExpirationPolicy, RevocationCheckDepth, UnknownStatusPolicy};
6
7use crate::crypto::{CryptoProvider, Identity, SignatureScheme, WebPkiSupportedAlgorithms};
8use crate::error::ApiMisuse;
9use crate::sync::Arc;
10use crate::verify::{
11 HandshakeSignatureValid, ServerIdentity, ServerVerifier, SignatureVerificationInput,
12 VerifiedIdentity,
13};
14use crate::webpki::verify::{
15 ParsedCertificate, verify_identity_signed_by_trust_anchor_impl, verify_tls12_signature,
16 verify_tls13_signature,
17};
18use crate::webpki::{VerifierBuilderError, parse_crls, verify_server_name};
19#[cfg(doc)]
20use crate::{ClientConfig, ConfigBuilder, crypto};
21use crate::{DynHasher, Error, RootCertStore};
22
23#[derive(Debug, Clone)]
27pub struct ServerVerifierBuilder {
28 roots: Arc<RootCertStore>,
29 crls: Vec<CertificateRevocationListDer<'static>>,
30 revocation_check_depth: RevocationCheckDepth,
31 unknown_revocation_policy: UnknownStatusPolicy,
32 revocation_expiration_policy: ExpirationPolicy,
33 supported_algs: WebPkiSupportedAlgorithms,
34}
35
36impl ServerVerifierBuilder {
37 pub(crate) fn new(
38 roots: Arc<RootCertStore>,
39 supported_algs: WebPkiSupportedAlgorithms,
40 ) -> Self {
41 Self {
42 roots,
43 crls: Vec::new(),
44 revocation_check_depth: RevocationCheckDepth::Chain,
45 unknown_revocation_policy: UnknownStatusPolicy::Deny,
46 revocation_expiration_policy: ExpirationPolicy::Ignore,
47 supported_algs,
48 }
49 }
50
51 pub fn with_crls(
55 mut self,
56 crls: impl IntoIterator<Item = CertificateRevocationListDer<'static>>,
57 ) -> Self {
58 self.crls.extend(crls);
59 self
60 }
61
62 pub fn only_check_end_entity_revocation(mut self) -> Self {
72 self.revocation_check_depth = RevocationCheckDepth::EndEntity;
73 self
74 }
75
76 pub fn allow_unknown_revocation_status(mut self) -> Self {
85 self.unknown_revocation_policy = UnknownStatusPolicy::Allow;
86 self
87 }
88
89 pub fn enforce_revocation_expiration(mut self) -> Self {
98 self.revocation_expiration_policy = ExpirationPolicy::Enforce;
99 self
100 }
101
102 pub fn build(self) -> Result<WebPkiServerVerifier, VerifierBuilderError> {
117 if self.roots.is_empty() {
118 return Err(VerifierBuilderError::NoRootAnchors);
119 }
120
121 Ok(WebPkiServerVerifier::new(
122 self.roots,
123 parse_crls(self.crls)?,
124 self.revocation_check_depth,
125 self.unknown_revocation_policy,
126 self.revocation_expiration_policy,
127 self.supported_algs,
128 ))
129 }
130}
131
132#[derive(Debug, Hash)]
134pub struct WebPkiServerVerifier {
135 roots: Arc<RootCertStore>,
136 crls: Vec<CertRevocationList<'static>>,
137 revocation_check_depth: RevocationCheckDepth,
138 unknown_revocation_policy: UnknownStatusPolicy,
139 revocation_expiration_policy: ExpirationPolicy,
140 supported: WebPkiSupportedAlgorithms,
141}
142
143impl WebPkiServerVerifier {
144 pub fn builder(roots: Arc<RootCertStore>, provider: &CryptoProvider) -> ServerVerifierBuilder {
153 ServerVerifierBuilder::new(roots, provider.signature_verification_algorithms)
154 }
155
156 pub(crate) fn new_without_revocation(
159 roots: impl Into<Arc<RootCertStore>>,
160 supported_algs: WebPkiSupportedAlgorithms,
161 ) -> Self {
162 Self::new(
163 roots,
164 Vec::default(),
165 RevocationCheckDepth::Chain,
166 UnknownStatusPolicy::Allow,
167 ExpirationPolicy::Ignore,
168 supported_algs,
169 )
170 }
171
172 pub(crate) fn new(
184 roots: impl Into<Arc<RootCertStore>>,
185 crls: Vec<CertRevocationList<'static>>,
186 revocation_check_depth: RevocationCheckDepth,
187 unknown_revocation_policy: UnknownStatusPolicy,
188 revocation_expiration_policy: ExpirationPolicy,
189 supported: WebPkiSupportedAlgorithms,
190 ) -> Self {
191 Self {
192 roots: roots.into(),
193 crls,
194 revocation_check_depth,
195 unknown_revocation_policy,
196 revocation_expiration_policy,
197 supported,
198 }
199 }
200}
201
202impl ServerVerifier for WebPkiServerVerifier {
203 fn verify_identity<'a>(
214 &self,
215 identity: &ServerIdentity<'a, '_>,
216 ) -> Result<VerifiedIdentity<'a>, Error> {
217 let certificates = match identity.identity {
218 Identity::X509(certificates) => certificates,
219 Identity::RawPublicKey(_) => {
220 return Err(ApiMisuse::UnverifiableCertificateType.into());
221 }
222 };
223
224 let cert = ParsedCertificate::try_from(&certificates.end_entity)?;
225 let crl_refs = self.crls.iter().collect::<Vec<_>>();
226 let revocation = if self.crls.is_empty() {
227 None
228 } else {
229 Some(
232 webpki::RevocationOptionsBuilder::new(crl_refs.as_slice())
233 .unwrap()
236 .with_depth(self.revocation_check_depth)
237 .with_status_policy(self.unknown_revocation_policy)
238 .with_expiration_policy(self.revocation_expiration_policy)
239 .build(),
240 )
241 };
242
243 verify_identity_signed_by_trust_anchor_impl(
246 &cert,
247 &self.roots,
248 &certificates.intermediates,
249 revocation,
250 identity.now,
251 self.supported.all,
252 )?;
253
254 verify_server_name(&cert, identity.server_name)?;
255 Ok(VerifiedIdentity::assertion(identity.identity.clone()))
256 }
257
258 fn verify_tls12_signature(
259 &self,
260 input: &SignatureVerificationInput<'_>,
261 ) -> Result<HandshakeSignatureValid, Error> {
262 verify_tls12_signature(input, &self.supported)
263 }
264
265 fn verify_tls13_signature(
266 &self,
267 input: &SignatureVerificationInput<'_>,
268 ) -> Result<HandshakeSignatureValid, Error> {
269 verify_tls13_signature(input, &self.supported)
270 }
271
272 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
273 self.supported.supported_schemes()
274 }
275
276 fn request_ocsp_response(&self) -> bool {
277 false
278 }
279
280 fn hash_config(&self, h: &mut dyn Hasher) {
281 self.hash(&mut DynHasher(h));
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use alloc::vec::Vec;
288 use std::{println, vec};
289
290 use pki_types::pem::PemObject;
291 use pki_types::{CertificateDer, CertificateRevocationListDer};
292
293 use super::{VerifierBuilderError, WebPkiServerVerifier};
294 use crate::RootCertStore;
295 use crate::crypto::TEST_PROVIDER;
296 use crate::sync::Arc;
297
298 fn load_crls(crls_der: &[&[u8]]) -> Vec<CertificateRevocationListDer<'static>> {
299 crls_der
300 .iter()
301 .map(|pem_bytes| CertificateRevocationListDer::from_pem_slice(pem_bytes).unwrap())
302 .collect()
303 }
304
305 fn test_crls() -> Vec<CertificateRevocationListDer<'static>> {
306 load_crls(&[
307 include_bytes!("../../../test-ca/ecdsa-p256/client.revoked.crl.pem").as_slice(),
308 include_bytes!("../../../test-ca/rsa-2048/client.revoked.crl.pem").as_slice(),
309 ])
310 }
311
312 fn load_roots(roots_der: &[&[u8]]) -> Arc<RootCertStore> {
313 let mut roots = RootCertStore::empty();
314 roots_der.iter().for_each(|der| {
315 roots
316 .add(CertificateDer::from(der.to_vec()))
317 .unwrap()
318 });
319 roots.into()
320 }
321
322 fn test_roots() -> Arc<RootCertStore> {
323 load_roots(&[
324 include_bytes!("../../../test-ca/ecdsa-p256/ca.der").as_slice(),
325 include_bytes!("../../../test-ca/rsa-2048/ca.der").as_slice(),
326 ])
327 }
328
329 #[test]
330 fn test_with_invalid_crls() {
331 let result = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
333 .with_crls(vec![CertificateRevocationListDer::from(vec![0xFF])])
334 .build();
335 assert!(matches!(result, Err(VerifierBuilderError::InvalidCrl(_))));
336 }
337
338 #[test]
339 fn test_with_crls_multiple_calls() {
340 let initial_crls = test_crls();
342 let extra_crls =
343 load_crls(&[
344 include_bytes!("../../../test-ca/eddsa/client.revoked.crl.pem").as_slice(),
345 ]);
346
347 let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
348 .with_crls(initial_crls.clone())
349 .with_crls(extra_crls.clone());
350
351 assert_eq!(builder.crls.len(), initial_crls.len() + extra_crls.len());
353 println!("{builder:?}");
355 builder.build().unwrap();
356 }
357
358 #[test]
359 fn test_builder_no_roots() {
360 let result =
362 WebPkiServerVerifier::builder(RootCertStore::empty().into(), &TEST_PROVIDER).build();
363 assert!(matches!(result, Err(VerifierBuilderError::NoRootAnchors)));
364 }
365
366 #[test]
367 fn test_server_verifier_ee_only() {
368 let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
370 .only_check_end_entity_revocation();
371 println!("{builder:?}");
373 builder.build().unwrap();
374 }
375
376 #[test]
377 fn test_server_verifier_allow_unknown() {
378 let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
381 .allow_unknown_revocation_status();
382 println!("{builder:?}");
384 builder.build().unwrap();
385 }
386
387 #[test]
388 fn test_server_verifier_allow_unknown_ee_only() {
389 let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
392 .allow_unknown_revocation_status()
393 .only_check_end_entity_revocation();
394 println!("{builder:?}");
396 builder.build().unwrap();
397 }
398
399 #[test]
400 fn test_server_verifier_enforce_expiration() {
401 let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
404 .enforce_revocation_expiration();
405 println!("{builder:?}");
407 builder.build().unwrap();
408 }
409}