qualia_client_core/
webizen_x509.rs1use sha2::{Digest, Sha256};
7use x509_parser::prelude::*;
8
9use crate::webizen_trust::TrustStore;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct PathVerifyResult {
14 pub accepted: bool,
15 pub reason_code: &'static str,
16 pub detail: String,
17}
18
19impl PathVerifyResult {
20 pub fn accept(reason: &'static str, detail: impl Into<String>) -> Self {
22 Self {
23 accepted: true,
24 reason_code: reason,
25 detail: detail.into(),
26 }
27 }
28 pub fn reject(reason: &'static str, detail: impl Into<String>) -> Self {
30 Self {
31 accepted: false,
32 reason_code: reason,
33 detail: detail.into(),
34 }
35 }
36}
37
38pub fn pem_to_ders(pem: &str) -> Result<Vec<Vec<u8>>, String> {
40 let mut out = Vec::new();
41 let mut rest = pem.as_bytes();
42 loop {
43 match rustls_pemfile::read_one_from_slice(rest) {
44 Ok(Some((item, rem))) => {
45 rest = rem;
46 match item {
47 rustls_pemfile::Item::X509Certificate(der) => out.push(der.to_vec()),
48 _ => {}
49 }
50 }
51 Ok(None) => break,
52 Err(e) => {
53 if out.is_empty() {
54 return Err(format!("PEM parse: {e:?}"));
55 }
56 break;
57 }
58 }
59 }
60 if out.is_empty() {
61 return Err("no CERTIFICATE blocks in PEM".into());
62 }
63 Ok(out)
64}
65
66pub fn spki_sha256_hex(cert_der: &[u8]) -> Result<String, String> {
68 let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| format!("x509 parse: {e}"))?;
69 let spki = cert.public_key().raw;
70 let mut h = Sha256::new();
71 h.update(spki);
72 Ok(hex::encode(h.finalize()))
73}
74
75pub fn spki_pin_matches(leaf_pem_or_der: &str, expected_hex: &str) -> Result<bool, String> {
77 let ders = if leaf_pem_or_der.contains("BEGIN CERTIFICATE") {
78 pem_to_ders(leaf_pem_or_der)?
79 } else {
80 return Err("leaf must be PEM CERTIFICATE".into());
82 };
83 let leaf = ders.first().ok_or("empty leaf")?;
84 let got = spki_sha256_hex(leaf)?;
85 Ok(got.eq_ignore_ascii_case(expected_hex.trim()))
86}
87
88pub fn verify_chain_against_enabled_roots(
96 leaf_pem: &str,
97 intermediate_pems: &[&str],
98 store: &TrustStore,
99) -> PathVerifyResult {
100 let leaf_ders = match pem_to_ders(leaf_pem) {
101 Ok(d) => d,
102 Err(e) => return PathVerifyResult::reject("leaf_pem_invalid", e),
103 };
104 let leaf_der = match leaf_ders.first() {
105 Some(d) => d.as_slice(),
106 None => return PathVerifyResult::reject("leaf_empty", "no leaf certificate"),
107 };
108 let leaf = match X509Certificate::from_der(leaf_der) {
109 Ok((_, c)) => c,
110 Err(e) => return PathVerifyResult::reject("leaf_parse", format!("{e}")),
111 };
112
113 let mut intermediate_ders: Vec<Vec<u8>> = Vec::new();
114 for p in intermediate_pems {
115 if p.trim().is_empty() {
116 continue;
117 }
118 match pem_to_ders(p) {
119 Ok(ders) => intermediate_ders.extend(ders),
120 Err(e) => {
121 return PathVerifyResult::reject("intermediate_pem_invalid", e);
122 }
123 }
124 }
125
126 let mut roots: Vec<(String, Vec<u8>)> = Vec::new();
127 for a in store
128 .anchors
129 .iter()
130 .filter(|a| a.enabled && a.kind == crate::webizen_trust::AnchorKind::PemRoot)
131 {
132 if let Ok(ders) = pem_to_ders(&a.material) {
133 for d in ders {
134 if X509Certificate::from_der(&d).is_ok() {
135 roots.push((a.id.clone(), d));
136 }
137 }
138 }
139 }
140 if roots.is_empty() {
141 return PathVerifyResult::reject(
142 "no_enabled_roots",
143 "no enabled PEM roots in trust store — chain verify fails closed",
144 );
145 }
146
147 for (id, root_der) in &roots {
149 let Ok((_, root)) = X509Certificate::from_der(root_der) else {
150 continue;
151 };
152 if leaf.verify_signature(Some(root.public_key())).is_ok() {
153 return PathVerifyResult::accept(
154 "leaf_signed_by_enabled_root",
155 format!("verified against root {id}"),
156 );
157 }
158 if leaf.tbs_certificate.subject == root.tbs_certificate.subject
159 && leaf.tbs_certificate.subject == leaf.tbs_certificate.issuer
160 && leaf.verify_signature(None).is_ok()
161 {
162 return PathVerifyResult::accept(
163 "self_signed_matches_enabled_root",
164 format!("self-signed leaf matches enabled root {id}"),
165 );
166 }
167 }
168
169 for inter_der in &intermediate_ders {
171 let Ok((_, inter)) = X509Certificate::from_der(inter_der) else {
172 continue;
173 };
174 if leaf.verify_signature(Some(inter.public_key())).is_err() {
175 continue;
176 }
177 for (id_r, root_der) in &roots {
178 let Ok((_, root)) = X509Certificate::from_der(root_der) else {
179 continue;
180 };
181 if inter.verify_signature(Some(root.public_key())).is_ok() {
182 return PathVerifyResult::accept(
183 "leaf_via_intermediate_to_enabled_root",
184 format!("chain to root {id_r}"),
185 );
186 }
187 }
188 }
189
190 PathVerifyResult::reject(
191 "chain_not_anchored",
192 "leaf/intermediates did not verify to any enabled PEM root",
193 )
194}
195
196pub fn root_cert_store_from_trust(store: &TrustStore) -> Result<rustls::RootCertStore, String> {
198 let mut roots = rustls::RootCertStore::empty();
199 let mut n = 0usize;
200 for a in store
201 .anchors
202 .iter()
203 .filter(|a| a.enabled && a.kind == crate::webizen_trust::AnchorKind::PemRoot)
204 {
205 let ders = pem_to_ders(&a.material)?;
206 for der in ders {
207 let cert = rustls::pki_types::CertificateDer::from(der);
208 roots
209 .add(cert)
210 .map_err(|e| format!("add root to RootCertStore: {e}"))?;
211 n += 1;
212 }
213 }
214 if n == 0 {
215 return Err("no enabled PEM roots to build RootCertStore".into());
216 }
217 Ok(roots)
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
222pub enum AgentTlsMode {
223 CustomRootsOnly { n_roots: usize },
225 SystemDefault,
227}
228
229pub fn agent_tls_mode(store: &TrustStore) -> AgentTlsMode {
231 let n = store
232 .anchors
233 .iter()
234 .filter(|a| a.enabled && a.kind == crate::webizen_trust::AnchorKind::PemRoot)
235 .count();
236 if n > 0 {
237 AgentTlsMode::CustomRootsOnly { n_roots: n }
238 } else {
239 AgentTlsMode::SystemDefault
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246 use crate::webizen_trust::{AnchorKind, TrustAnchor, TrustStore};
247
248 #[test]
250 fn empty_roots_fail_closed() {
251 let store = TrustStore::new();
252 let r = verify_chain_against_enabled_roots(
253 "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n",
254 &[],
255 &store,
256 );
257 assert!(!r.accepted);
258 assert!(
260 r.reason_code == "no_enabled_roots"
261 || r.reason_code == "leaf_parse"
262 || r.reason_code == "leaf_pem_invalid"
263 );
264 }
265
266 #[test]
267 fn agent_mode_system_when_no_pem() {
268 assert_eq!(
269 agent_tls_mode(&TrustStore::new()),
270 AgentTlsMode::SystemDefault
271 );
272 }
273
274 #[test]
275 fn agent_mode_custom_when_pem_enabled() {
276 let mut s = TrustStore::new();
277 s.anchors.push(TrustAnchor {
278 id: "pem:t".into(),
279 label: "t".into(),
280 kind: AnchorKind::PemRoot,
281 material: "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n".into(),
282 enabled: true,
283 notes: "".into(),
284 added_unix: 1,
285 jurisdiction: None,
286 signature_algorithm: None,
287 });
288 match agent_tls_mode(&s) {
289 AgentTlsMode::CustomRootsOnly { n_roots } => assert_eq!(n_roots, 1),
290 _ => panic!("expected custom"),
291 }
292 }
293}