[edge] Listeners: QC's probes kept as regression tests (smuggling and desync with pipelining, a TLS handshake that never starts, an HTTP/2 header block that never ends) with their Python probes in tests/support/probes

This commit is contained in:
2026-11-22 18:50:36 +01:00
parent b492ccf5f9
commit 6ce6bfdb79
3 changed files with 315 additions and 0 deletions
+221
View File
@@ -329,4 +329,225 @@ interval_secs = 1
"{seen:?}"
);
}
// ------------------------------------------------------------------ QC phase 4
// Adopted as regression tests from QC's probes (fix round 1). The two slow-client tests need
// python3 (tests/support/probes/).
async fn qc_raw(edge: &Edge, sni: &str, bytes: &[u8]) -> String {
let tcp = tokio::net::TcpStream::connect(edge.https).await.unwrap();
let mut tls = client::tls_connector(edge.roots())
.connect(ServerName::try_from(sni.to_owned()).unwrap(), tcp)
.await
.unwrap();
tls.write_all(bytes).await.unwrap();
let mut out = Vec::new();
let mut buf = [0u8; 8192];
loop {
match tokio::time::timeout(Duration::from_secs(3), tls.read(&mut buf)).await {
Ok(Ok(n)) if n > 0 => out.extend_from_slice(&buf[..n]),
_ => break,
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// QC p4: desync / smuggling with pipelining on the HTTPS listener. The smuggled request
/// names the forward-auth host and has no session, so if the upstream ever sees
/// /SMUGGLED, it bypassed edge's routing and sign-in.
#[tokio::test(flavor = "multi_thread")]
async fn qc_smuggling_cases_on_the_https_listener() {
let authelia = ianitor_testkit::authelia::MockAuthelia::start().await;
let echo = Echo::start("app").await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![
host_file("app.test", &format!("upstreams = [\"{}\"]\n", echo.url())),
host_file(
"auth.test",
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
echo.url()
),
),
],
..Default::default()
});
let statuses = |t: &str| {
t.match_indices("HTTP/1.1 ")
.map(|(i, _)| t[i + 9..i + 12].to_owned())
.collect::<Vec<_>>()
};
let sm = "GET /SMUGGLED HTTP/1.1\r\nHost: auth.test\r\n\r\n";
let n = sm.len();
let cases: Vec<(&str, &str, String)> = vec![
(
"forward-auth 401 with an unread body",
"auth.test",
format!(
"POST /x HTTP/1.1\r\nHost: auth.test\r\nContent-Length: {n}\r\n\r\n{sm}GET /after HTTP/1.1\r\nHost: app.test\r\n\r\n"
),
),
(
"forward-auth 302 (GET with a body)",
"auth.test",
format!(
"GET /x HTTP/1.1\r\nHost: auth.test\r\nContent-Length: {n}\r\n\r\n{sm}GET /after HTTP/1.1\r\nHost: app.test\r\n\r\n"
),
),
(
"404 host with an unread body",
"app.test",
format!(
"POST /x HTTP/1.1\r\nHost: nobody.test\r\nContent-Length: {n}\r\n\r\n{sm}GET /after HTTP/1.1\r\nHost: app.test\r\n\r\n"
),
),
(
"421 SNI/Host mismatch with a body",
"app.test",
format!("POST /x HTTP/1.1\r\nHost: auth.test\r\nContent-Length: {n}\r\n\r\n{sm}"),
),
(
"Expect: 100-continue, denied",
"auth.test",
format!(
"POST /x HTTP/1.1\r\nHost: auth.test\r\nExpect: 100-continue\r\nContent-Length: {n}\r\n\r\n{sm}"
),
),
(
"CL + TE",
"app.test",
format!(
"POST /clte HTTP/1.1\r\nHost: app.test\r\nContent-Length: {}\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n{sm}",
5 + n
),
),
(
"TE + CL (reversed)",
"app.test",
format!(
"POST /tecl HTTP/1.1\r\nHost: app.test\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n0\r\n\r\n{sm}"
),
),
(
"two different CL",
"app.test",
format!(
"POST /cl2 HTTP/1.1\r\nHost: app.test\r\nContent-Length: 0\r\nContent-Length: {n}\r\n\r\n{sm}"
),
),
(
"TE chunked, identity",
"app.test",
format!(
"POST /teobf HTTP/1.1\r\nHost: app.test\r\nTransfer-Encoding: chunked, identity\r\nContent-Length: {n}\r\n\r\n{sm}"
),
),
(
"TE with a space before the colon",
"app.test",
format!(
"POST /tesp HTTP/1.1\r\nHost: app.test\r\nTransfer-Encoding : chunked\r\nContent-Length: {n}\r\n\r\n{sm}"
),
),
(
"upgrade the upstream refuses, then a request",
"app.test",
format!(
"GET /up HTTP/1.1\r\nHost: app.test\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n{sm}"
),
),
];
let mut bad = Vec::new();
for (name, sni, req) in cases {
echo.clear();
let got = qc_raw(&edge, sni, req.as_bytes()).await;
let reqs = echo.requests();
let paths: Vec<String> = reqs.iter().map(|r| r.path.clone()).collect();
let framing: Vec<String> = reqs
.iter()
.map(|r| {
r.headers
.iter()
.filter(|(h, _)| {
h.eq_ignore_ascii_case("transfer-encoding")
|| h.eq_ignore_ascii_case("content-length")
})
.map(|(h, v)| format!("{h}={}", String::from_utf8_lossy(v)))
.collect::<Vec<_>>()
.join(",")
})
.collect();
eprintln!(
"QC {name}: statuses {:?}; upstream saw {paths:?} {framing:?}",
statuses(&got)
);
if paths.iter().any(|p| p.contains("SMUGGLED")) {
bad.push(name);
}
}
assert!(
bad.is_empty(),
"the smuggled request reached the upstream: {bad:?}"
);
}
/// QC p4: the header deadline wraps only the HTTP app, i.e. after the TLS handshake and,
/// for HTTP/2, after a stream's header block. Probes (Python): a TCP connection that never
/// sends a ClientHello, and an h2 HEADERS block continued one byte every 0.5 s.
#[tokio::test(flavor = "multi_thread")]
async fn qc_slow_tls_handshake_and_h2_header_block() {
let echo = Echo::start("app").await;
let edge = app_edge(&echo, vec![]);
let py = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/support/probes/slow.py"
);
let port = edge.https.port().to_string();
let run = |mode: &str| {
std::process::Command::new("python3")
.args([py, "127.0.0.1", &port, mode, "150", "app.test"])
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap()
};
let a = run("idle");
let b = run("h2");
let out = |c: std::process::Child| {
String::from_utf8_lossy(&c.wait_with_output().unwrap().stdout).into_owned()
};
let (oa, ob) = tokio::task::spawn_blocking(move || (out(a), out(b)))
.await
.unwrap();
eprintln!("QC edge {oa}QC edge {ob}");
assert!(
!oa.contains("STILL OPEN") && !ob.contains("STILL OPEN"),
"{oa}{ob}"
);
}
/// QC p4: an HTTP/2 header block continued one byte per CONTINUATION frame (valid HPACK).
#[tokio::test(flavor = "multi_thread")]
async fn qc_h2_header_block_that_never_ends() {
let echo = Echo::start("app").await;
let edge = app_edge(&echo, vec!["--header-timeout".into(), "5".into()]);
let py = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/support/probes/h2slow.py"
);
let port = edge.https.port().to_string();
let out = tokio::task::spawn_blocking(move || {
std::process::Command::new("python3")
.args([py, "127.0.0.1", &port, "150", "app.test"])
.output()
.unwrap()
})
.await
.unwrap();
let o = String::from_utf8_lossy(&out.stdout).into_owned()
+ &String::from_utf8_lossy(&out.stderr);
eprintln!("QC edge (header timeout 5 s) {o}");
assert!(!o.contains("STILL OPEN"), "{o}");
}
}
+50
View File
@@ -0,0 +1,50 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# QC phase 4: an HTTP/2 header block that never ends: valid HPACK, a literal x-slow header whose 4000-byte
# value arrives one byte per CONTINUATION frame every 0.5 s, after a proper SETTINGS exchange.
# h2slow.py <host> <port> <limit s> [sni] prints "closed after Ns" or "STILL OPEN after Ns"
import socket, ssl, sys, time
host, port, limit = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])
sni = sys.argv[4] if len(sys.argv) > 4 else "app.test"
ctx = ssl.create_default_context(); ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
ctx.set_alpn_protocols(["h2"])
t = ctx.wrap_socket(socket.create_connection((host, port)), server_hostname=sni)
def frame(ty, flags, sid, payload): return len(payload).to_bytes(3, "big") + bytes([ty, flags]) + sid.to_bytes(4, "big") + payload
seen = []
def parse(d):
i = 0
while i + 9 <= len(d):
ln = int.from_bytes(d[i:i+3], "big"); seen.append((d[i+3], d[i+4], d[i+9:i+9+ln][:8].hex())); i += 9 + ln
# 1. preface + SETTINGS; read the server's SETTINGS and ACK it before any header block.
t.sendall(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + frame(4, 0, 0, b""))
t.settimeout(2)
try:
parse(t.recv(65536))
except socket.timeout:
pass
t.sendall(frame(4, 1, 0, b""))
# 2. HEADERS without END_HEADERS: valid HPACK; a literal x-slow header whose 4000-byte value
# then arrives one byte per CONTINUATION frame, every 0.5 s. Nothing else is sent meanwhile.
block = b"\x82\x87\x84" + b"\x41" + bytes([len(sni)]) + sni.encode()
block += b"\x00\x06x-slow" + b"\x7f" + bytes([(3873 % 128) | 0x80, 3873 // 128])
t.sendall(frame(1, 1, 1, block))
start = time.time(); t.settimeout(0.5)
def el(): return f"{time.time()-start:.1f}s"
while time.time() - start < limit:
try:
d = t.recv(65536)
if not d:
print(f"h2 {port}: closed after {el()}; frames from server {seen}"); break
parse(d)
except socket.timeout:
pass
except OSError as e:
print(f"h2 {port}: closed after {el()} ({e}); frames {seen}"); break
try:
t.sendall(frame(9, 0, 1, b"a"))
except OSError as e:
print(f"h2 {port}: closed after {el()} ({e}); frames {seen}"); break
else:
print(f"h2 {port}: STILL OPEN after {limit:.0f}s; frames {seen[:6]}")
+44
View File
@@ -0,0 +1,44 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# QC phase 4: slow-client probes against a TLS listener, by hand-written bytes (no HTTP library).
# slow.py <host> <port> idle <limit s> [sni] a TCP connection that never sends a ClientHello
# slow.py <host> <port> h2 <limit s> [sni] an h2 HEADERS block continued by one CONTINUATION frame every 0.5 s
# Prints "closed after Ns" or "STILL OPEN after Ns". Used by crates/edge/tests/listeners.rs and scripts/conformance.sh.
import socket, ssl, sys, time
host, port, mode, limit = sys.argv[1], int(sys.argv[2]), sys.argv[3], float(sys.argv[4])
sni = sys.argv[5] if len(sys.argv) > 5 else "app.test"
s = socket.create_connection((host, port))
start = time.time()
def el(): return f"{time.time()-start:.1f}s"
if mode == "idle":
# TCP open, no TLS ClientHello ever sent
s.settimeout(limit)
try:
d = s.recv(1)
print(f"idle {port}: closed after {el()} ({d!r})")
except socket.timeout:
print(f"idle {port}: STILL OPEN after {limit:.0f}s")
except OSError as e:
print(f"idle {port}: closed after {el()} ({e})")
elif mode == "h2":
ctx = ssl.create_default_context(); ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
ctx.set_alpn_protocols(["h2"])
t = ctx.wrap_socket(s, server_hostname=sni)
def frame(ty, flags, sid, payload): return len(payload).to_bytes(3, "big") + bytes([ty, flags]) + sid.to_bytes(4, "big") + payload
# preface, SETTINGS, HEADERS (END_STREAM, no END_HEADERS), then a CONTINUATION byte every 0.5 s
t.sendall(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + frame(4, 0, 0, b"") + frame(1, 1, 1, b"\x82"))
start = time.time(); t.settimeout(0.5)
while time.time() - start < limit:
try:
t.sendall(frame(9, 0, 1, b"\x82"))
d = t.recv(4096)
if not d:
print(f"h2 {port} alpn={t.selected_alpn_protocol()}: closed after {el()}"); break
except socket.timeout:
pass
except OSError as e:
print(f"h2 {port} alpn={t.selected_alpn_protocol()}: closed after {el()} ({e})"); break
else:
print(f"h2 {port} alpn={t.selected_alpn_protocol()}: STILL OPEN after {limit:.0f}s")