[edge] Device certificates: mTLS on hosts with device_certs only (asked per SNI), chain to the Domi CA bundle and the allow list in the handshake, checked again per request; 403 without one
This commit is contained in:
@@ -126,6 +126,7 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
|
|||||||
reason: e.to_string(),
|
reason: e.to_string(),
|
||||||
})?;
|
})?;
|
||||||
tls.set_cert_resolver(shared.certs.clone());
|
tls.set_cert_resolver(shared.certs.clone());
|
||||||
|
tls.set_client_cert_verifier(shared.devices.clone());
|
||||||
tls.enable_h2();
|
tls.enable_h2();
|
||||||
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
|
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
|
||||||
|
|
||||||
|
|||||||
@@ -137,6 +137,13 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
};
|
};
|
||||||
ctx.host = Some(host.clone());
|
ctx.host = Some(host.clone());
|
||||||
|
|
||||||
|
if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) {
|
||||||
|
// No certificate on this connection (one that is presented but not allowed never
|
||||||
|
// gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream.
|
||||||
|
respond_empty(session, 403).await?;
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
let mut shared_access = false;
|
let mut shared_access = false;
|
||||||
if !host.cfg.share_links {
|
if !host.cfg.share_links {
|
||||||
share::strip_any_token(session)?;
|
share::strip_any_token(session)?;
|
||||||
@@ -412,6 +419,19 @@ impl EdgeProxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Did this connection present a device certificate that the current config allows? The
|
||||||
|
/// handshake already checked the chain and the list; this checks again against the runtime
|
||||||
|
/// serving the request, so a revocation also ends requests on connections made before it.
|
||||||
|
fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool {
|
||||||
|
let Some(trust) = rt.device_trust.as_ref() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
session
|
||||||
|
.digest()
|
||||||
|
.and_then(|d| d.ssl_digest.as_ref())
|
||||||
|
.is_some_and(|s| !s.cert_digest.is_empty() && trust.allows(&s.cert_digest))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||||
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -118,6 +118,8 @@ pub struct Runtime {
|
|||||||
pub file_cert_expiry: HashMap<String, i64>,
|
pub file_cert_expiry: HashMap<String, i64>,
|
||||||
/// Loaded when any host has share links.
|
/// Loaded when any host has share links.
|
||||||
pub share_key: Option<Arc<ShareKey>>,
|
pub share_key: Option<Arc<ShareKey>>,
|
||||||
|
/// Loaded when any host has `device_certs`.
|
||||||
|
pub device_trust: Option<Arc<crate::tls::DeviceTrust>>,
|
||||||
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
|
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
|
||||||
/// built from a parsed config.
|
/// built from a parsed config.
|
||||||
pub sha256: String,
|
pub sha256: String,
|
||||||
@@ -400,6 +402,38 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let device_hosts: std::collections::HashSet<String> = cfg
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.device_certs)
|
||||||
|
.map(|h| h.hostname.clone())
|
||||||
|
.collect();
|
||||||
|
let device_trust = match (&cfg.device_certs, device_hosts.is_empty()) {
|
||||||
|
(_, true) => None,
|
||||||
|
(None, false) => {
|
||||||
|
return Err(EdgeError::Config {
|
||||||
|
path: PathBuf::from("<config>"),
|
||||||
|
message: "a host needs device certificates but the config names no CA bundle"
|
||||||
|
.into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(Some(dc), false) => {
|
||||||
|
let read = |p: &str| {
|
||||||
|
std::fs::read(p).map_err(|source| EdgeError::Read {
|
||||||
|
path: PathBuf::from(p),
|
||||||
|
source,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let trust =
|
||||||
|
crate::tls::DeviceTrust::new(&read(&dc.ca)?, &read(&dc.allow)?, device_hosts)
|
||||||
|
.map_err(|message| EdgeError::Config {
|
||||||
|
path: PathBuf::from(&dc.ca),
|
||||||
|
message,
|
||||||
|
})?;
|
||||||
|
Some(Arc::new(trust))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let forward_auth = match &cfg.forward_auth {
|
let forward_auth = match &cfg.forward_auth {
|
||||||
Some(fa) => Some(ForwardAuthRt {
|
Some(fa) => Some(ForwardAuthRt {
|
||||||
upstream: upstream(&fa.upstream)?,
|
upstream: upstream(&fa.upstream)?,
|
||||||
@@ -438,6 +472,7 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
|||||||
file_certs,
|
file_certs,
|
||||||
file_cert_expiry,
|
file_cert_expiry,
|
||||||
share_key,
|
share_key,
|
||||||
|
device_trust,
|
||||||
sha256: String::new(),
|
sha256: String::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,6 +94,8 @@ pub enum AdminError {
|
|||||||
pub struct Shared {
|
pub struct Shared {
|
||||||
current: ArcSwap<Runtime>,
|
current: ArcSwap<Runtime>,
|
||||||
pub certs: Arc<CertStore>,
|
pub certs: Arc<CertStore>,
|
||||||
|
/// The listener's device-certificate check; its trust follows the runtime.
|
||||||
|
pub devices: Arc<crate::tls::DeviceVerifier>,
|
||||||
generation: AtomicU64,
|
generation: AtomicU64,
|
||||||
changed: tokio::sync::watch::Sender<u64>,
|
changed: tokio::sync::watch::Sender<u64>,
|
||||||
trial: Mutex<Option<Trial>>,
|
trial: Mutex<Option<Trial>>,
|
||||||
@@ -133,10 +135,13 @@ impl Shared {
|
|||||||
};
|
};
|
||||||
let certs = Arc::new(CertStore::default());
|
let certs = Arc::new(CertStore::default());
|
||||||
certs.replace_files(rt.file_certs.clone());
|
certs.replace_files(rt.file_certs.clone());
|
||||||
|
let devices = Arc::new(crate::tls::DeviceVerifier::default());
|
||||||
|
devices.replace(rt.device_trust.clone());
|
||||||
let (changed, _) = tokio::sync::watch::channel(1);
|
let (changed, _) = tokio::sync::watch::channel(1);
|
||||||
let s = Arc::new(Shared {
|
let s = Arc::new(Shared {
|
||||||
current: ArcSwap::from_pointee(rt),
|
current: ArcSwap::from_pointee(rt),
|
||||||
certs,
|
certs,
|
||||||
|
devices,
|
||||||
generation: AtomicU64::new(1),
|
generation: AtomicU64::new(1),
|
||||||
changed,
|
changed,
|
||||||
trial: Mutex::new(None),
|
trial: Mutex::new(None),
|
||||||
@@ -182,6 +187,7 @@ impl Shared {
|
|||||||
|
|
||||||
fn install(&self, rt: Arc<Runtime>) {
|
fn install(&self, rt: Arc<Runtime>) {
|
||||||
self.certs.replace_files(rt.file_certs.clone());
|
self.certs.replace_files(rt.file_certs.clone());
|
||||||
|
self.devices.replace(rt.device_trust.clone());
|
||||||
self.current.store(rt);
|
self.current.store(rt);
|
||||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||||
self.notify();
|
self.notify();
|
||||||
|
|||||||
+203
-4
@@ -5,10 +5,11 @@
|
|||||||
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
|
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
|
||||||
//! without touching connections in flight.
|
//! without touching connections in flight.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use arc_swap::ArcSwap;
|
use arc_swap::ArcSwap;
|
||||||
|
use rustls::server::danger::ClientCertVerifier;
|
||||||
use rustls::server::{ClientHello, ResolvesServerCert};
|
use rustls::server::{ClientHello, ResolvesServerCert};
|
||||||
use rustls::sign::CertifiedKey;
|
use rustls::sign::CertifiedKey;
|
||||||
use rustls_pki_types::pem::PemObject;
|
use rustls_pki_types::pem::PemObject;
|
||||||
@@ -48,10 +49,14 @@ impl ResolvesServerCert for CertStore {
|
|||||||
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
||||||
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
|
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
|
||||||
let name = hello.server_name()?.to_ascii_lowercase();
|
let name = hello.server_name()?.to_ascii_lowercase();
|
||||||
if let Some(k) = self.files.load().get(&name) {
|
let found = match self.files.load().get(&name) {
|
||||||
return Some(k.clone());
|
Some(k) => Some(k.clone()),
|
||||||
|
None => self.certs.load().get(&name).cloned(),
|
||||||
|
};
|
||||||
|
if found.is_some() {
|
||||||
|
set_hello_sni(&name);
|
||||||
}
|
}
|
||||||
self.certs.load().get(&name).cloned()
|
found
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,3 +82,197 @@ pub fn not_after(cert_pem: &[u8]) -> Option<i64> {
|
|||||||
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
|
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
|
||||||
Some(cert.validity().not_after.timestamp())
|
Some(cert.validity().not_after.timestamp())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ device certificates
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
/// The server name of the handshake this thread is working on, set by
|
||||||
|
/// [`CertStore::resolve`]. rustls calls the certificate resolver and then, in the same
|
||||||
|
/// call on the same thread, asks the client verifier whether to request a certificate;
|
||||||
|
/// this is how a request goes out only for hosts with `device_certs` (rustls's verifier
|
||||||
|
/// has no per-name hook). Taken (cleared) when read.
|
||||||
|
static HELLO_SNI: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_hello_sni(name: &str) {
|
||||||
|
HELLO_SNI.with(|s| *s.borrow_mut() = Some(name.to_owned()));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_hello_sni() -> Option<String> {
|
||||||
|
HELLO_SNI.with(|s| s.borrow_mut().take())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one config says about device certificates.
|
||||||
|
pub struct DeviceTrust {
|
||||||
|
inner: Arc<dyn ClientCertVerifier>,
|
||||||
|
/// SHA-256 of every allowed device certificate (DER).
|
||||||
|
allow: HashSet<[u8; 32]>,
|
||||||
|
/// Hosts that ask for a device certificate.
|
||||||
|
hosts: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for DeviceTrust {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("DeviceTrust")
|
||||||
|
.field("allowed", &self.allow.len())
|
||||||
|
.field("hosts", &self.hosts)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sha256(der: &[u8]) -> [u8; 32] {
|
||||||
|
let d = ring::digest::digest(&ring::digest::SHA256, der);
|
||||||
|
let mut out = [0u8; 32];
|
||||||
|
out.copy_from_slice(d.as_ref());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceTrust {
|
||||||
|
/// From the CA bundle and allow list control wrote (PEM). An empty allow list is valid
|
||||||
|
/// (no device gets in); an empty or unreadable CA bundle is not.
|
||||||
|
pub fn new(ca_pem: &[u8], allow_pem: &[u8], hosts: HashSet<String>) -> Result<Self, String> {
|
||||||
|
let mut roots = rustls::RootCertStore::empty();
|
||||||
|
for c in CertificateDer::pem_slice_iter(ca_pem) {
|
||||||
|
let c = c.map_err(|e| format!("cannot parse the device CA bundle: {e}"))?;
|
||||||
|
roots
|
||||||
|
.add(c)
|
||||||
|
.map_err(|e| format!("the device CA bundle has an unusable certificate: {e}"))?;
|
||||||
|
}
|
||||||
|
if roots.is_empty() {
|
||||||
|
return Err("the device CA bundle has no certificate".into());
|
||||||
|
}
|
||||||
|
let mut allow = HashSet::new();
|
||||||
|
for c in CertificateDer::pem_slice_iter(allow_pem) {
|
||||||
|
let c = c.map_err(|e| format!("cannot parse the device allow list: {e}"))?;
|
||||||
|
allow.insert(sha256(c.as_ref()));
|
||||||
|
}
|
||||||
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
|
let inner =
|
||||||
|
rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider)
|
||||||
|
.allow_unauthenticated()
|
||||||
|
.build()
|
||||||
|
.map_err(|e| format!("cannot build the device certificate check: {e}"))?;
|
||||||
|
Ok(DeviceTrust {
|
||||||
|
inner,
|
||||||
|
allow,
|
||||||
|
hosts,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allows(&self, cert_sha256: &[u8]) -> bool {
|
||||||
|
<[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The listener's client verifier. Lives as long as the process; each config brings its own
|
||||||
|
/// [`DeviceTrust`] (none when no host needs device certificates).
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct DeviceVerifier {
|
||||||
|
trust: ArcSwap<Option<Arc<DeviceTrust>>>,
|
||||||
|
/// CA names for the certificate request. rustls wants a borrowed slice, so each new set
|
||||||
|
/// is leaked once; it changes only when the intermediate does (about once a year).
|
||||||
|
hints: std::sync::RwLock<&'static [rustls::DistinguishedName]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DeviceVerifier {
|
||||||
|
fn default() -> Self {
|
||||||
|
DeviceVerifier {
|
||||||
|
trust: ArcSwap::from_pointee(None),
|
||||||
|
hints: std::sync::RwLock::new(&[]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceVerifier {
|
||||||
|
pub fn replace(&self, t: Option<Arc<DeviceTrust>>) {
|
||||||
|
if let Some(t) = &t {
|
||||||
|
let new = t.inner.root_hint_subjects();
|
||||||
|
if let Ok(mut h) = self.hints.write()
|
||||||
|
&& !same_names(&h, new)
|
||||||
|
{
|
||||||
|
*h = Box::leak(new.to_vec().into_boxed_slice());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.trust.store(Arc::new(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current(&self) -> Option<Arc<DeviceTrust>> {
|
||||||
|
self.trust.load().as_ref().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn no_devices() -> rustls::Error {
|
||||||
|
rustls::Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientCertVerifier for DeviceVerifier {
|
||||||
|
fn offer_client_auth(&self) -> bool {
|
||||||
|
let Some(t) = self.current() else {
|
||||||
|
let _ = take_hello_sni();
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
match take_hello_sni() {
|
||||||
|
Some(name) => t.hosts.contains(&name),
|
||||||
|
// Called once per connection before the hello is read: say yes, so rustls keeps
|
||||||
|
// what it needs in case the host asks; the real answer comes after the hello.
|
||||||
|
None => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_auth_mandatory(&self) -> bool {
|
||||||
|
// A missing certificate is a 403 from the proxy, like Caddy's route, not a failed
|
||||||
|
// handshake.
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
|
||||||
|
// So a browser offers only Domi device certificates in its picker.
|
||||||
|
self.hints.read().map(|h| *h).unwrap_or(&[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_client_cert(
|
||||||
|
&self,
|
||||||
|
end_entity: &CertificateDer<'_>,
|
||||||
|
intermediates: &[CertificateDer<'_>],
|
||||||
|
now: rustls_pki_types::UnixTime,
|
||||||
|
) -> Result<rustls::server::danger::ClientCertVerified, rustls::Error> {
|
||||||
|
let t = self.current().ok_or_else(no_devices)?;
|
||||||
|
t.inner.verify_client_cert(end_entity, intermediates, now)?;
|
||||||
|
if !t.allows(&sha256(end_entity.as_ref())) {
|
||||||
|
return Err(rustls::Error::InvalidCertificate(
|
||||||
|
rustls::CertificateError::Revoked,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(rustls::server::danger::ClientCertVerified::assertion())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &rustls::DigitallySignedStruct,
|
||||||
|
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||||
|
let t = self.current().ok_or_else(no_devices)?;
|
||||||
|
t.inner.verify_tls12_signature(message, cert, dss)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &rustls::DigitallySignedStruct,
|
||||||
|
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||||
|
let t = self.current().ok_or_else(no_devices)?;
|
||||||
|
t.inner.verify_tls13_signature(message, cert, dss)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||||
|
rustls::crypto::ring::default_provider()
|
||||||
|
.signature_verification_algorithms
|
||||||
|
.supported_schemes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_names(a: &[rustls::DistinguishedName], b: &[rustls::DistinguishedName]) -> bool {
|
||||||
|
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.as_ref() == y.as_ref())
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user