1use rustls::pki_types::{CertificateDer, CertificateRevocationListDer};
4use serde::Deserialize;
5use std::{
6 fs::File,
7 io::Read,
8 num::NonZeroU32,
9 path::{Path, PathBuf},
10 time::Duration,
11};
12use x509_parser::prelude::{parse_x509_certificate, parse_x509_crl};
13mod ocsp;
14pub use ocsp::validate_ocsp;
15
16#[derive(Debug, thiserror::Error, PartialEq, Eq)]
17pub enum Invalid {
18 #[error("invalid certificate, trust anchor or status evidence")]
19 Evidence,
20 #[error("certificate revoked")]
21 Revoked,
22}
23pub type Result<T> = std::result::Result<T, Invalid>;
24
25#[derive(Clone, Deserialize)]
26#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
27pub enum Revocation {
28 Crl {
29 files: Vec<PathBuf>,
30 },
31 Ocsp {
32 files: Vec<PathBuf>,
33 max_age_s: Option<NonZeroU32>,
34 },
35}
36pub fn read_import(path: &Path) -> Result<Vec<u8>> {
37 const MAX: u64 = 4 * 1024 * 1024;
38 let mut bytes = Vec::new();
39 File::open(path)
40 .map_err(|_| Invalid::Evidence)?
41 .take(MAX + 1)
42 .read_to_end(&mut bytes)
43 .map_err(|_| Invalid::Evidence)?;
44 if bytes.is_empty() || bytes.len() as u64 > MAX {
45 return Err(Invalid::Evidence);
46 }
47 Ok(bytes)
48}
49pub fn crls(
53 files: &[PathBuf],
54 now: i64,
55) -> Result<(Vec<CertificateRevocationListDer<'static>>, i64)> {
56 if now < 0 || files.is_empty() || files.len() > 32 {
57 return Err(Invalid::Evidence);
58 }
59 let mut until = i64::MAX;
60 let mut crls = Vec::new();
61 let mut issuers = std::collections::HashSet::new();
62 for file in files {
63 let bytes = read_import(file)?;
64 let (trailing, crl) = parse_x509_crl(&bytes).map_err(|_| Invalid::Evidence)?;
65 if !issuers.insert(crl.issuer().as_raw().to_vec())
68 || crl
69 .extensions()
70 .iter()
71 .any(|e| matches!(e.oid.to_string().as_str(), "2.5.29.27" | "2.5.29.28"))
72 || crl.iter_revoked_certificates().any(|r| {
73 r.extensions()
74 .iter()
75 .any(|e| e.oid.to_string() == "2.5.29.29")
76 })
77 {
78 return Err(Invalid::Evidence);
79 }
80 let expiry = crl.next_update().ok_or(Invalid::Evidence)?.timestamp();
81 if !trailing.is_empty() || crl.last_update().timestamp() > now || expiry <= now {
82 return Err(Invalid::Evidence);
83 }
84 until = until.min(expiry);
85 crls.push(CertificateRevocationListDer::from(bytes));
86 }
87 Ok((crls, until))
88}