[edge] Device certificates as Caddy does them: no certificate on a device host fails the handshake, a Host other than the SNI name is 421; diff corpus gains six device cases
This commit is contained in:
Generated
+1
@@ -1102,6 +1102,7 @@ dependencies = [
|
||||
"ianitor-core",
|
||||
"ianitor-edge",
|
||||
"ianitor-testkit",
|
||||
"rcgen",
|
||||
"rustls",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
|
||||
@@ -121,10 +121,11 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
|
||||
connector: Connector::new(None),
|
||||
},
|
||||
);
|
||||
let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen {
|
||||
address: rt.cfg.https_listen.clone(),
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
let mut tls =
|
||||
TlsSettings::with_callbacks(Box::new(tls::SniRecorder)).map_err(|e| EdgeError::Listen {
|
||||
address: rt.cfg.https_listen.clone(),
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
tls.set_cert_resolver(shared.certs.clone());
|
||||
tls.set_client_cert_verifier(shared.devices.clone());
|
||||
tls.enable_h2();
|
||||
|
||||
@@ -131,6 +131,13 @@ impl ProxyHttp for EdgeProxy {
|
||||
let rt = self.shared.current();
|
||||
ctx.rt = Some(rt.clone());
|
||||
ctx.host_header = host_header(session.req_header());
|
||||
if rt.device_trust.is_some() && sni_mismatch(session, &hostname(&ctx.host_header)) {
|
||||
// Like Caddy once client certificates are configured: a request for another host
|
||||
// than the one the TLS connection was opened for is refused, so a connection
|
||||
// that was never asked for a certificate cannot reach a device host.
|
||||
respond_empty(session, 421).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else {
|
||||
respond_empty(session, 404).await?;
|
||||
return Ok(true);
|
||||
@@ -419,6 +426,18 @@ impl EdgeProxy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Was this TLS connection opened (by SNI) for another host than the request names?
|
||||
fn sni_mismatch(session: &Session, host: &str) -> bool {
|
||||
let Some(s) = session.digest().and_then(|d| d.ssl_digest.as_ref()) else {
|
||||
return false;
|
||||
};
|
||||
match s.extension.get::<crate::tls::ConnSni>() {
|
||||
Some(crate::tls::ConnSni(Some(sni))) => sni != host,
|
||||
// TLS without a recorded name: refuse rather than guess.
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
+24
-3
@@ -220,9 +220,10 @@ impl ClientCertVerifier for DeviceVerifier {
|
||||
}
|
||||
|
||||
fn client_auth_mandatory(&self) -> bool {
|
||||
// A missing certificate is a 403 from the proxy, like Caddy's route, not a failed
|
||||
// handshake.
|
||||
false
|
||||
// Only asked when a certificate was requested, i.e. on a device host: there a
|
||||
// handshake without one fails, as with Caddy (its allow-list check refuses an empty
|
||||
// certificate list in the handshake too).
|
||||
self.current().is_some()
|
||||
}
|
||||
|
||||
fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
|
||||
@@ -276,3 +277,23 @@ impl ClientCertVerifier for DeviceVerifier {
|
||||
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())
|
||||
}
|
||||
|
||||
/// The server name a TLS connection was opened for, kept in the connection's digest so the
|
||||
/// proxy can compare it with the `Host` header.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnSni(pub Option<String>);
|
||||
|
||||
/// Records [`ConnSni`] when a handshake completes.
|
||||
pub struct SniRecorder;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl pingora::listeners::TlsAccept for SniRecorder {
|
||||
async fn handshake_complete_callback(
|
||||
&self,
|
||||
tls: &pingora::protocols::tls::TlsRef,
|
||||
) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||
Some(Arc::new(ConnSni(
|
||||
tls.server_name().map(|s| s.to_ascii_lowercase()),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ mod unix {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn no_certificate_is_a_403_and_never_reaches_the_upstream() {
|
||||
async fn no_certificate_is_refused_and_never_reaches_the_upstream() {
|
||||
let echo = Echo::start("app").await;
|
||||
let p = pki();
|
||||
let (_, phone_pem) = device(&p, "phone");
|
||||
@@ -151,11 +151,11 @@ mod unix {
|
||||
edge.roots(),
|
||||
&Req::get("locked.test", "/"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status, 403);
|
||||
.await;
|
||||
assert!(r.is_err(), "no certificate got in: {r:?}");
|
||||
assert!(echo.requests().is_empty());
|
||||
// The Host header cannot move a certificate-less connection onto the locked host.
|
||||
// The Host header cannot move a certificate-less connection onto the locked host:
|
||||
// 421, as Caddy answers once client certificates are configured.
|
||||
let r = client::https(
|
||||
edge.https,
|
||||
"open.test",
|
||||
@@ -164,7 +164,7 @@ mod unix {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(r.status, 200);
|
||||
assert_eq!(r.status, 421);
|
||||
assert!(echo.requests().is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ ianitor-testkit.workspace = true
|
||||
tokio.workspace = true
|
||||
serde_json.workspace = true
|
||||
rustls.workspace = true
|
||||
rcgen.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ianitor-control = { path = "../../crates/control" }
|
||||
|
||||
+157
-3
@@ -113,6 +113,10 @@ impl Env {
|
||||
"rr.test",
|
||||
&format!("upstreams = [\"{}\", \"{}\"]\n", rr_a.url(), rr_b.url()),
|
||||
),
|
||||
host(
|
||||
"device.test",
|
||||
&format!("upstreams = [\"{}\"]\ndevice_certs = true\n", app.url()),
|
||||
),
|
||||
];
|
||||
let sources: Vec<SourceFile> = hosts
|
||||
.iter()
|
||||
@@ -145,6 +149,17 @@ impl Env {
|
||||
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("creds/api_key"), format!("{SECRET}\n")).unwrap();
|
||||
let d = devices();
|
||||
std::fs::write(
|
||||
dir.join(&format!("certs/{}", compile::DEVICE_CA_FILE)),
|
||||
&d.ca_pem,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join(&format!("certs/{}", compile::DEVICE_ALLOW_FILE)),
|
||||
&d.allow_pem,
|
||||
)
|
||||
.unwrap();
|
||||
Env {
|
||||
dir,
|
||||
ca,
|
||||
@@ -294,6 +309,12 @@ pub enum Action {
|
||||
sni: &'static str,
|
||||
req: Req,
|
||||
},
|
||||
/// HTTPS presenting a client certificate when asked.
|
||||
HttpsDevice {
|
||||
sni: &'static str,
|
||||
req: Req,
|
||||
who: Device,
|
||||
},
|
||||
Http {
|
||||
req: Req,
|
||||
},
|
||||
@@ -578,6 +599,34 @@ pub fn corpus() -> Vec<Case> {
|
||||
),
|
||||
https("round robin 1", "rr.test", Req::get("rr.test", "/")),
|
||||
https("round robin 2", "rr.test", Req::get("rr.test", "/")),
|
||||
device("no device certificate", "device.test", Device::None),
|
||||
device(
|
||||
"Domi device certificate on the allow list",
|
||||
"device.test",
|
||||
Device::Allowed,
|
||||
),
|
||||
device(
|
||||
"Domi device certificate not on the allow list",
|
||||
"device.test",
|
||||
Device::Unlisted,
|
||||
),
|
||||
device(
|
||||
"self-signed certificate with a device's subject",
|
||||
"device.test",
|
||||
Device::SelfSigned,
|
||||
),
|
||||
device(
|
||||
"client certificate on a host that does not ask for one",
|
||||
"plain.test",
|
||||
Device::SelfSigned,
|
||||
),
|
||||
Case {
|
||||
name: "Host header naming the device host on another connection",
|
||||
action: Action::Https {
|
||||
sni: "plain.test",
|
||||
req: Req::get("device.test", "/"),
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -644,6 +693,22 @@ pub async fn run_case(case: &Case, t: &Target, roots: Arc<RootCertStore>) -> Obs
|
||||
Action::Https { sni, req } => client::https(t.https, sni, roots, req)
|
||||
.await
|
||||
.map_or_else(failed, |r| observe(&r, t)),
|
||||
Action::HttpsDevice { sni, req, who } => {
|
||||
let answer = match who {
|
||||
Device::None => client::https(t.https, sni, roots, req).await,
|
||||
_ => client::https_with_cert(t.https, sni, roots, &devices().cert(*who), req).await,
|
||||
};
|
||||
match answer {
|
||||
Ok(r) => observe(&r, t),
|
||||
// The two TLS stacks word their alerts differently; a refused handshake is
|
||||
// what is compared (495, nginx's "SSL certificate error", as a marker).
|
||||
Err(_) => Observation {
|
||||
status: 495,
|
||||
headers: BTreeMap::new(),
|
||||
body: "handshake refused".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
Action::Http { req } => client::http(t.http, req)
|
||||
.await
|
||||
.map_or_else(failed, |r| observe(&r, t)),
|
||||
@@ -764,9 +829,9 @@ pub const KNOWN_DIVERGENCES: &[Divergence] = &[
|
||||
rule: Rule::Status {
|
||||
case: "absolute-form target, other host",
|
||||
ianitor: 400,
|
||||
caddy: 404,
|
||||
caddy: 421,
|
||||
},
|
||||
reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target (404 here)",
|
||||
reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target, which is not the SNI name (421 once a host checks device certificates; 404 without)",
|
||||
},
|
||||
Divergence {
|
||||
id: "KD-9",
|
||||
@@ -908,7 +973,9 @@ fn short(o: &Observation) -> Observation {
|
||||
/// The host a case is about (its SNI, or the Host header of plain-HTTP cases).
|
||||
pub fn case_host(case: &Case) -> String {
|
||||
match &case.action {
|
||||
Action::Https { sni, .. } | Action::Websocket { sni, .. } => (*sni).to_owned(),
|
||||
Action::Https { sni, .. }
|
||||
| Action::HttpsDevice { sni, .. }
|
||||
| Action::Websocket { sni, .. } => (*sni).to_owned(),
|
||||
Action::Http { req } => req
|
||||
.headers
|
||||
.iter()
|
||||
@@ -1008,3 +1075,90 @@ fn differences(i: &Observation, c: &Observation) -> Vec<String> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Which client certificate a device case presents.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Device {
|
||||
/// No client certificate at all.
|
||||
None,
|
||||
/// Issued by the Domi intermediate and on the allow list.
|
||||
Allowed,
|
||||
/// Issued by the Domi intermediate, not on the allow list (revoked or never listed).
|
||||
Unlisted,
|
||||
/// Self-signed, with the same subject as the allowed one.
|
||||
SelfSigned,
|
||||
}
|
||||
|
||||
fn device(name: &'static str, host: &'static str, who: Device) -> Case {
|
||||
Case {
|
||||
name,
|
||||
action: Action::HttpsDevice {
|
||||
sni: host,
|
||||
req: Req::get(host, "/"),
|
||||
who,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// One Domi PKI per test process, shared by every [`Env`] (each writes its files).
|
||||
pub struct DevicePki {
|
||||
pub ca_pem: String,
|
||||
pub allow_pem: String,
|
||||
allowed: client::ClientCert,
|
||||
unlisted: client::ClientCert,
|
||||
self_signed: client::ClientCert,
|
||||
}
|
||||
|
||||
impl DevicePki {
|
||||
pub fn cert(&self, who: Device) -> client::ClientCert {
|
||||
match who {
|
||||
Device::Allowed => self.allowed.clone(),
|
||||
Device::Unlisted => self.unlisted.clone(),
|
||||
Device::SelfSigned | Device::None => self.self_signed.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn devices() -> &'static DevicePki {
|
||||
use ianitor_core::pki;
|
||||
static PKI: std::sync::OnceLock<DevicePki> = std::sync::OnceLock::new();
|
||||
PKI.get_or_init(|| {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
let (root, root_key) = pki::create_root(now).unwrap();
|
||||
let k = pki::generate_key().unwrap();
|
||||
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
|
||||
let int_pem = pki::sign_intermediate(&root, &root_key, &csr, now).unwrap();
|
||||
let int = pki::Intermediate::new(&int_pem, k).unwrap();
|
||||
let cc = |i: pki::Issued| client::ClientCert {
|
||||
chain_pem: i.chain_pem,
|
||||
key_pem: i.key_pem,
|
||||
tls12_only: false,
|
||||
};
|
||||
let phone = pki::issue_device(&int, "phone", now).unwrap();
|
||||
let allow_pem = phone.cert_pem.clone();
|
||||
let unlisted = pki::issue_device(&int, "laptop", now).unwrap();
|
||||
let fake_key = rcgen::KeyPair::generate().unwrap();
|
||||
let mut p = rcgen::CertificateParams::default();
|
||||
let mut dn = rcgen::DistinguishedName::new();
|
||||
dn.push(rcgen::DnType::CommonName, "phone");
|
||||
dn.push(rcgen::DnType::OrganizationName, pki::ORG);
|
||||
dn.push(rcgen::DnType::OrganizationalUnitName, "Domi devices");
|
||||
p.distinguished_name = dn;
|
||||
p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth];
|
||||
let fake = p.self_signed(&fake_key).unwrap();
|
||||
DevicePki {
|
||||
ca_pem: int.cert_pem().to_owned(),
|
||||
allow_pem,
|
||||
allowed: cc(phone),
|
||||
unlisted: cc(unlisted),
|
||||
self_signed: client::ClientCert {
|
||||
chain_pem: fake.pem(),
|
||||
key_pem: fake_key.serialize_pem(),
|
||||
tls12_only: false,
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user