summaryrefslogtreecommitdiff
path: root/packet-detector/src/validator.rs
blob: 92e64d72d39e68d41823e8a03948dbeff9c4f887 (plain)
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
//! Certificate chain validation - signature only

use anyhow::{anyhow, Result};
use rustls::pki_types::CertificateDer;
use x509_parser::prelude::*;

pub struct ValidationResult {
    pub valid: bool,
    pub subject: String,
    pub issuer: String,
    pub error: Option<String>,
}

impl ValidationResult {
    fn fail(subject: String, issuer: String, err: impl ToString) -> Self {
        Self { valid: false, subject, issuer, error: Some(err.to_string()) }
    }
}

pub struct CertValidator {
    ca_der: Vec<u8>,
}

impl CertValidator {
    pub fn with_ca_file(path: &str) -> Result<Self> {
        let pem = std::fs::read_to_string(path)?;
        let der = rustls_pemfile::certs(&mut pem.as_bytes())
            .next()
            .ok_or_else(|| anyhow!("No cert in PEM"))??;
        Ok(Self { ca_der: der.to_vec() })
    }

    pub fn validate(&self, chain: &[Vec<u8>]) -> ValidationResult {
        let Some(ee_der) = chain.first() else {
            return ValidationResult::fail(String::new(), String::new(), "Empty chain");
        };

        let (subject, issuer) = match X509Certificate::from_der(ee_der) {
            Ok((_, c)) => (c.subject().to_string(), c.issuer().to_string()),
            Err(e) => return ValidationResult::fail(String::new(), String::new(), format!("{e:?}")),
        };

        let ca = CertificateDer::from(self.ca_der.clone());
        let anchor = match webpki::anchor_from_trusted_cert(&ca) {
            Ok(a) => a,
            Err(e) => return ValidationResult::fail(subject, issuer, format!("CA: {e:?}")),
        };

        let cert = CertificateDer::from(ee_der.clone());
        let ee = match webpki::EndEntityCert::try_from(&cert) {
            Ok(c) => c,
            Err(e) => return ValidationResult::fail(subject, issuer, format!("{e:?}")),
        };

        let intermediates: Vec<_> = chain[1..].iter().map(|c| CertificateDer::from(c.clone())).collect();
        let algos = webpki::ALL_VERIFICATION_ALGS;
        let time = webpki::types::UnixTime::since_unix_epoch(std::time::Duration::from_secs(4102444800)); // 2100

        match ee.verify_for_usage(algos, &[anchor], &intermediates, time, webpki::KeyUsage::client_auth(), None, None) {
            Ok(_) => ValidationResult { valid: true, subject, issuer, error: None },
            Err(e) => ValidationResult::fail(subject, issuer, format!("{e:?}")),
        }
    }
}