Skip to main content

kaniop_radius/reconcile/
tls.rs

1//! EAP/RADIUS certificate preflight checks.
2//!
3//! The official Kanidm RADIUS entrypoint expects files for a certificate chain
4//! and matching private key. Reject invalid referenced Kubernetes Secret data
5//! before modifying the active Deployment or Kanidm credentials.
6//!
7//! This only validates PEM structure, certificate validity dates and leaf/key
8//! correspondence. It does not issue certificates or establish which CA a NAS
9//! device trusts; clients must trust the operator-supplied certificate chain.
10
11use std::cmp::Ordering;
12
13use openssl::asn1::Asn1Time;
14use openssl::pkey::PKey;
15use openssl::x509::X509;
16use thiserror::Error;
17
18/// Errors deliberately omit certificate/key data and sensitive identifiers.
19#[derive(Debug, Error, PartialEq, Eq)]
20pub enum RadiusTlsError {
21    #[error("RADIUS EAP TLS certificate chain is missing or invalid")]
22    InvalidCertificate,
23    #[error("RADIUS EAP TLS private key is missing or invalid")]
24    InvalidPrivateKey,
25    #[error("RADIUS EAP TLS certificate public key does not match private key")]
26    KeyMismatch,
27    #[error("RADIUS EAP TLS server certificate is not yet valid")]
28    NotYetValid,
29    #[error("RADIUS EAP TLS server certificate has expired")]
30    Expired,
31    #[error("RADIUS EAP TLS CA bundle is invalid")]
32    InvalidCaBundle,
33}
34
35/// Validate the expected keys from a user-owned TLS Secret.
36///
37/// The first certificate in cert_chain_pem must be the leaf certificate.
38/// ca_bundle_pem is optional; a provided empty or invalid bundle is an error.
39/// Neither source bytes nor parsed key material are retained or returned.
40pub fn validate_eap_tls_material(
41    cert_chain_pem: &[u8],
42    private_key_pem: &[u8],
43    ca_bundle_pem: Option<&[u8]>,
44) -> Result<(), RadiusTlsError> {
45    let chain =
46        X509::stack_from_pem(cert_chain_pem).map_err(|_| RadiusTlsError::InvalidCertificate)?;
47    let leaf = chain.first().ok_or(RadiusTlsError::InvalidCertificate)?;
48
49    let key = PKey::private_key_from_pem(private_key_pem)
50        .map_err(|_| RadiusTlsError::InvalidPrivateKey)?;
51    let public = leaf
52        .public_key()
53        .map_err(|_| RadiusTlsError::InvalidCertificate)?;
54    if !public.public_eq(&key) {
55        return Err(RadiusTlsError::KeyMismatch);
56    }
57
58    let now = Asn1Time::days_from_now(0).map_err(|_| RadiusTlsError::InvalidCertificate)?;
59    if leaf
60        .not_before()
61        .compare(&now)
62        .map_err(|_| RadiusTlsError::InvalidCertificate)?
63        == Ordering::Greater
64    {
65        return Err(RadiusTlsError::NotYetValid);
66    }
67    if leaf
68        .not_after()
69        .compare(&now)
70        .map_err(|_| RadiusTlsError::InvalidCertificate)?
71        != Ordering::Greater
72    {
73        return Err(RadiusTlsError::Expired);
74    }
75
76    if let Some(ca_bundle_pem) = ca_bundle_pem {
77        let certs =
78            X509::stack_from_pem(ca_bundle_pem).map_err(|_| RadiusTlsError::InvalidCaBundle)?;
79        if certs.is_empty() {
80            return Err(RadiusTlsError::InvalidCaBundle);
81        }
82    }
83
84    Ok(())
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    use openssl::hash::MessageDigest;
92    use openssl::rsa::Rsa;
93    use openssl::x509::X509Name;
94
95    fn self_signed_certificate() -> (Vec<u8>, Vec<u8>) {
96        let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
97        let mut subject = X509Name::builder().unwrap();
98        subject
99            .append_entry_by_text("CN", "radius.example.com")
100            .unwrap();
101        let subject = subject.build();
102        let mut cert = X509::builder().unwrap();
103        cert.set_version(2).unwrap();
104        cert.set_subject_name(&subject).unwrap();
105        cert.set_issuer_name(&subject).unwrap();
106        cert.set_pubkey(&key).unwrap();
107        let not_before = Asn1Time::days_from_now(0).unwrap();
108        let not_after = Asn1Time::days_from_now(30).unwrap();
109        cert.set_not_before(&not_before).unwrap();
110        cert.set_not_after(&not_after).unwrap();
111        cert.sign(&key, MessageDigest::sha256()).unwrap();
112        (
113            cert.build().to_pem().unwrap(),
114            key.private_key_to_pem_pkcs8().unwrap(),
115        )
116    }
117
118    #[test]
119    fn accepts_valid_matching_material_and_ca() {
120        let (cert, key) = self_signed_certificate();
121        assert_eq!(validate_eap_tls_material(&cert, &key, None), Ok(()));
122        assert_eq!(validate_eap_tls_material(&cert, &key, Some(&cert)), Ok(()));
123    }
124
125    #[test]
126    fn rejects_invalid_certificate_and_key_without_leaking_bytes() {
127        let (cert, key) = self_signed_certificate();
128        assert_eq!(
129            validate_eap_tls_material(b"invalid cert", &key, None),
130            Err(RadiusTlsError::InvalidCertificate)
131        );
132        assert_eq!(
133            validate_eap_tls_material(&cert, b"invalid key secret", None),
134            Err(RadiusTlsError::InvalidPrivateKey)
135        );
136        let error = validate_eap_tls_material(&cert, b"invalid key secret", None)
137            .unwrap_err()
138            .to_string();
139        assert!(!error.contains("invalid key secret"));
140    }
141
142    #[test]
143    fn rejects_mismatching_private_key_and_bad_ca() {
144        let (cert, _key) = self_signed_certificate();
145        let (_other_cert, other_key) = self_signed_certificate();
146        assert_eq!(
147            validate_eap_tls_material(&cert, &other_key, None),
148            Err(RadiusTlsError::KeyMismatch)
149        );
150        let (cert, key) = self_signed_certificate();
151        assert_eq!(
152            validate_eap_tls_material(&cert, &key, Some(b"not a PEM certificate")),
153            Err(RadiusTlsError::InvalidCaBundle)
154        );
155    }
156}