1use core::fmt::Debug;
2
3use pki_types::{SignatureVerificationAlgorithm, UnixTime};
4
5use crate::error::Error;
6use crate::verify_cert::{Budget, PathNode, Role};
7use crate::{DerTypeId, der, public_values_eq};
8
9mod types;
10pub use types::{
11 BorrowedCertRevocationList, BorrowedRevokedCert, CertRevocationList, RevocationReason,
12};
13#[cfg(feature = "alloc")]
14pub use types::{OwnedCertRevocationList, OwnedRevokedCert};
15
16#[derive(Debug, Copy, Clone)]
18pub struct RevocationOptionsBuilder<'a> {
19 crls: &'a [&'a CertRevocationList<'a>],
20
21 depth: RevocationCheckDepth,
22
23 status_policy: UnknownStatusPolicy,
24
25 expiration_policy: ExpirationPolicy,
26}
27
28impl<'a> RevocationOptionsBuilder<'a> {
29 pub fn new(crls: &'a [&'a CertRevocationList<'a>]) -> Result<Self, CrlsRequired> {
46 if crls.is_empty() {
47 return Err(CrlsRequired(()));
48 }
49
50 Ok(Self {
51 crls,
52 depth: RevocationCheckDepth::Chain,
53 status_policy: UnknownStatusPolicy::Deny,
54 expiration_policy: ExpirationPolicy::Ignore,
55 })
56 }
57
58 pub fn with_depth(mut self, depth: RevocationCheckDepth) -> Self {
62 self.depth = depth;
63 self
64 }
65
66 pub fn with_status_policy(mut self, policy: UnknownStatusPolicy) -> Self {
68 self.status_policy = policy;
69 self
70 }
71
72 pub fn with_expiration_policy(mut self, policy: ExpirationPolicy) -> Self {
74 self.expiration_policy = policy;
75 self
76 }
77
78 pub fn build(self) -> RevocationOptions<'a> {
80 RevocationOptions {
81 crls: self.crls,
82 depth: self.depth,
83 status_policy: self.status_policy,
84 expiration_policy: self.expiration_policy,
85 }
86 }
87}
88
89#[derive(Debug, Copy, Clone)]
92pub struct RevocationOptions<'a> {
93 pub(crate) crls: &'a [&'a CertRevocationList<'a>],
94 pub(crate) depth: RevocationCheckDepth,
95 pub(crate) status_policy: UnknownStatusPolicy,
96 pub(crate) expiration_policy: ExpirationPolicy,
97}
98
99impl RevocationOptions<'_> {
100 #[expect(clippy::too_many_arguments)]
101 pub(crate) fn check(
102 &self,
103 path: &PathNode<'_>,
104 issuer_subject: untrusted::Input<'_>,
105 issuer_spki: untrusted::Input<'_>,
106 issuer_ku: Option<untrusted::Input<'_>>,
107 supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
108 budget: &mut Budget,
109 time: UnixTime,
110 ) -> Result<Option<CertNotRevoked>, Error> {
111 assert!(public_values_eq(path.cert.issuer, issuer_subject));
112
113 if let (RevocationCheckDepth::EndEntity, Role::Issuer) = (self.depth, path.role()) {
116 return Ok(None);
117 }
118
119 let mut best_crl: Option<&CertRevocationList<'_>> = None;
120
121 for crl in self.crls.iter().copied() {
122 if !crl.authoritative(path) {
123 continue;
124 }
125
126 let best_so_far = best_crl.get_or_insert(crl);
127
128 if crl.issuer() != best_so_far.issuer()
131 || crl.issuing_distribution_point() != best_so_far.issuing_distribution_point()
132 {
133 continue;
134 }
135
136 if crl.crl_number() > best_so_far.crl_number() {
138 best_crl = Some(crl);
139 }
140 }
141
142 use UnknownStatusPolicy::*;
143 let crl = match (best_crl, self.status_policy) {
144 (Some(crl), _) => crl,
145 (None, Allow) => return Ok(None),
148 (None, _) => return Err(Error::UnknownRevocationStatus),
150 };
151
152 crl.verify_signature(supported_sig_algs, issuer_spki, budget)
157 .map_err(crl_signature_err)?;
158
159 if self.expiration_policy == ExpirationPolicy::Enforce {
160 crl.check_expiration(time)?;
161 }
162
163 KeyUsageMode::CrlSign.check(issuer_ku)?;
165
166 let cert_serial = path.cert.serial.as_slice_less_safe();
168 match crl.find_serial(cert_serial)? {
169 None => Ok(Some(CertNotRevoked::assertion())),
170 Some(_) => Err(Error::CertRevoked),
171 }
172 }
173}
174
175#[repr(u8)]
177#[derive(Clone, Copy)]
178enum KeyUsageMode {
179 CrlSign = 6,
186 }
189
190impl KeyUsageMode {
191 fn check(self, input: Option<untrusted::Input<'_>>) -> Result<(), Error> {
193 untrusted::read_all_optional(
194 input,
195 Error::TrailingData(DerTypeId::KeyUsageExtension),
196 |reader| {
197 let Some(reader) = reader else {
198 return Ok(());
202 };
203
204 let bit_string = der::expect_tag(reader, der::Tag::BitString)?;
205 let flags = der::bit_string_flags(bit_string)?;
206 #[expect(clippy::as_conversions)] match flags.bit_set(self as usize) {
208 true => Ok(()),
209 false => Err(Error::IssuerNotCrlSigner),
210 }
211 },
212 )
213 }
214}
215
216fn crl_signature_err(err: Error) -> Error {
220 match err {
221 Error::UnsupportedSignatureAlgorithm(cx) => Error::UnsupportedCrlSignatureAlgorithm(cx),
222 Error::UnsupportedSignatureAlgorithmForPublicKey(cx) => {
223 Error::UnsupportedCrlSignatureAlgorithmForPublicKey(cx)
224 }
225 Error::InvalidSignatureForPublicKey => Error::InvalidCrlSignatureForPublicKey,
226 _ => err,
227 }
228}
229
230#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
232pub enum RevocationCheckDepth {
233 EndEntity,
235 Chain,
237}
238
239#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
241pub enum UnknownStatusPolicy {
242 Allow,
245 Deny,
248}
249
250#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
252pub enum ExpirationPolicy {
253 Enforce,
256 Ignore,
258}
259
260pub(crate) struct CertNotRevoked(());
263
264impl CertNotRevoked {
265 fn assertion() -> Self {
267 Self(())
268 }
269}
270
271#[derive(Debug, Copy, Clone)]
272pub struct CrlsRequired(pub(crate) ());
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279
280 #[test]
281 #[cfg_attr(feature = "alloc", allow(clippy::redundant_clone))]
283 fn test_revocation_opts_builder() {
284 let result = RevocationOptionsBuilder::new(&[]);
286 assert!(matches!(result, Err(CrlsRequired(_))));
287
288 {
290 let err = result.unwrap_err();
291 std::println!("{:?}", err.clone());
292 }
293
294 let crl = include_bytes!("../../tests/crls/crl.valid.der");
296 let crl = BorrowedCertRevocationList::from_der(&crl[..])
297 .unwrap()
298 .into();
299 let crls = [&crl];
300 let builder = RevocationOptionsBuilder::new(&crls).unwrap();
301 #[cfg(feature = "alloc")]
302 #[allow(clippy::clone_on_copy)]
303 {
304 std::println!("{builder:?}");
306 _ = builder.clone();
307 }
308
309 let opts = builder.build();
310 assert_eq!(opts.depth, RevocationCheckDepth::Chain);
311 assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
312 assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
313 assert_eq!(opts.crls.len(), 1);
314
315 let opts = RevocationOptionsBuilder::new(&crls)
317 .unwrap()
318 .with_depth(RevocationCheckDepth::EndEntity)
319 .build();
320 assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
321 assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
322 assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
323 assert_eq!(opts.crls.len(), 1);
324
325 let opts = RevocationOptionsBuilder::new(&crls)
328 .unwrap()
329 .with_status_policy(UnknownStatusPolicy::Allow)
330 .build();
331 assert_eq!(opts.depth, RevocationCheckDepth::Chain);
332 assert_eq!(opts.status_policy, UnknownStatusPolicy::Allow);
333 assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
334 assert_eq!(opts.crls.len(), 1);
335
336 let opts = RevocationOptionsBuilder::new(&crls)
338 .unwrap()
339 .with_status_policy(UnknownStatusPolicy::Allow)
340 .with_depth(RevocationCheckDepth::EndEntity)
341 .build();
342 assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
343 assert_eq!(opts.status_policy, UnknownStatusPolicy::Allow);
344 assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
345 assert_eq!(opts.crls.len(), 1);
346
347 let opts = RevocationOptionsBuilder::new(&crls)
349 .unwrap()
350 .with_status_policy(UnknownStatusPolicy::Deny)
351 .with_depth(RevocationCheckDepth::EndEntity)
352 .build();
353 assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
354 assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
355 assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
356 assert_eq!(opts.crls.len(), 1);
357
358 let opts = RevocationOptionsBuilder::new(&crls)
361 .unwrap()
362 .with_expiration_policy(ExpirationPolicy::Enforce)
363 .build();
364 assert_eq!(opts.depth, RevocationCheckDepth::Chain);
365 assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
366 assert_eq!(opts.expiration_policy, ExpirationPolicy::Enforce);
367 assert_eq!(opts.crls.len(), 1);
368
369 #[cfg(feature = "alloc")]
371 {
372 std::println!("{:?}", opts.clone());
373 }
374 }
375}