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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
/*
This file is part of gnix (https://codeberg.org/metamuffin/gnix)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use anyhow::{anyhow, Context, Result};
use log::debug;
use rustls::{
crypto::CryptoProvider,
server::{ClientHello, ResolvesServerCert},
sign::CertifiedKey,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fs::read_to_string,
io::Cursor,
path::{Path, PathBuf},
sync::Arc,
};
use webpki::EndEntityCert;
#[derive(Debug)]
pub struct CertPool {
provider: &'static Arc<CryptoProvider>,
domains: HashMap<String, Arc<CertifiedKey>>,
wildcards: HashMap<String, Arc<CertifiedKey>>,
fallback: Option<Arc<CertifiedKey>>,
}
#[derive(Serialize, Deserialize)]
pub struct CertPackage {
pub name: String,
pub cert: String,
pub key: String,
}
impl Default for CertPool {
fn default() -> Self {
Self {
provider: CryptoProvider::get_default().unwrap(),
domains: Default::default(),
wildcards: Default::default(),
fallback: None,
}
}
}
impl CertPackage {
fn create_from(path: &Path) -> Result<Option<CertPackage>> {
let keypath = path.join("privkey.pem");
let certpath = if path.join("fullchain.pem").exists() {
path.join("fullchain.pem")
} else {
path.join("cert.pem")
};
Ok(if keypath.exists() && certpath.exists() {
debug!("creating cert package at {path:?}");
Some(CertPackage {
name: path.to_string_lossy().to_string(),
cert: read_to_string(certpath)?,
key: read_to_string(keypath)?,
})
} else {
None
})
}
pub fn create_from_recursive(roots: &[PathBuf]) -> Result<Vec<CertPackage>> {
let mut out = Vec::new();
for r in roots {
Self::create_package_recursion(r, &mut out)?;
}
Ok(out)
}
fn create_package_recursion(path: &Path, out: &mut Vec<CertPackage>) -> Result<()> {
if !path.is_dir() {
return Ok(());
}
for e in path.read_dir()? {
let p = e?.path();
if p.is_dir() {
Self::create_package_recursion(&p, out)?;
}
}
out.extend(Self::create_from(path)?);
Ok(())
}
}
impl CertPool {
pub fn add_package(&mut self, cp: CertPackage) -> Result<()> {
let certs = rustls_pemfile::certs(&mut Cursor::new(cp.cert))
.try_collect::<Vec<_>>()
.context("parsing tls certs")?;
let key = rustls_pemfile::private_key(&mut Cursor::new(cp.key))
.context("parsing tls private key")?
.ok_or(anyhow!("private key missing"))?;
let skey = self.provider.key_provider.load_private_key(key)?;
for c in &certs {
let eec = EndEntityCert::try_from(c).unwrap();
for name in eec.valid_dns_names() {
let ck = CertifiedKey::new(certs.clone(), skey.clone());
if let Some(name) = name.strip_prefix("*.") {
debug!("loaded wildcard key for {name:?}");
self.wildcards.insert(name.to_owned(), Arc::new(ck));
} else {
debug!("loaded key for {name:?}");
self.domains.insert(name.to_owned(), Arc::new(ck));
}
}
}
Ok(())
}
}
impl ResolvesServerCert for CertPool {
fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
let sname = client_hello.server_name()?;
Some(
self.domains
.get(sname)
.or_else(|| {
// Removing first label seems fine since wildcards are not recursive.
sname
.split_once(".")
.and_then(|(_, sname)| self.wildcards.get(sname))
})
.or(self.fallback.as_ref())?
.clone(),
)
}
}
|