Skip to content

Commit 7be2449

Browse files
scan_sni: decode chunked dns.google responses (#97)
dns.google replies with Transfer-Encoding: chunked; the raw payload was being handed to serde_json with chunk framing still embedded, so every PTR parse failed and scan-sni discovered nothing. Parses the HTTP response (chunked + Content-Length) before JSON decode. Includes 3 new unit tests.
1 parent 685dca0 commit 7be2449

1 file changed

Lines changed: 146 additions & 10 deletions

File tree

‎src/scan_sni.rs‎

Lines changed: 146 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,84 @@ fn truncate_reason(s: &str, max: usize) -> String {
279279
}
280280
}
281281

282+
fn parse_http_response_body(raw: &[u8]) -> Result<Vec<u8>, &'static str> {
283+
let header_end = raw
284+
.windows(4)
285+
.position(|w| w == b"\r\n\r\n")
286+
.ok_or("No HTTP header/body separator found")?;
287+
let header_block = std::str::from_utf8(&raw[..header_end]).map_err(|_| "Bad HTTP headers")?;
288+
let body = &raw[header_end + 4..];
289+
290+
let mut transfer_encoding = None;
291+
let mut content_length = None;
292+
for line in header_block.lines().skip(1) {
293+
let Some((k, v)) = line.split_once(':') else {
294+
continue;
295+
};
296+
if k.eq_ignore_ascii_case("transfer-encoding") {
297+
transfer_encoding = Some(v.trim().to_string());
298+
} else if k.eq_ignore_ascii_case("content-length") {
299+
content_length = v.trim().parse::<usize>().ok();
300+
}
301+
}
302+
303+
if transfer_encoding
304+
.as_deref()
305+
.map(|v| {
306+
v.split(',')
307+
.any(|part| part.trim().eq_ignore_ascii_case("chunked"))
308+
})
309+
.unwrap_or(false)
310+
{
311+
return decode_chunked_http_body(body);
312+
}
313+
314+
if let Some(len) = content_length {
315+
if body.len() < len {
316+
return Err("HTTP body shorter than Content-Length");
317+
}
318+
return Ok(body[..len].to_vec());
319+
}
320+
321+
Ok(body.to_vec())
322+
}
323+
324+
fn decode_chunked_http_body(mut body: &[u8]) -> Result<Vec<u8>, &'static str> {
325+
let mut out = Vec::new();
326+
loop {
327+
let line_end = body
328+
.windows(2)
329+
.position(|w| w == b"\r\n")
330+
.ok_or("truncated chunk size line")?;
331+
let size_line = std::str::from_utf8(&body[..line_end]).map_err(|_| "bad chunk size line")?;
332+
let size = usize::from_str_radix(size_line.trim().split(';').next().unwrap_or(""), 16)
333+
.map_err(|_| "bad chunk size")?;
334+
body = &body[line_end + 2..];
335+
336+
if size == 0 {
337+
loop {
338+
let trailer_end = body
339+
.windows(2)
340+
.position(|w| w == b"\r\n")
341+
.ok_or("truncated chunk trailer")?;
342+
if trailer_end == 0 {
343+
return Ok(out);
344+
}
345+
body = &body[trailer_end + 2..];
346+
}
347+
}
348+
349+
if body.len() < size + 2 {
350+
return Err("truncated chunk body");
351+
}
352+
if &body[size..size + 2] != b"\r\n" {
353+
return Err("chunk missing trailing CRLF");
354+
}
355+
out.extend_from_slice(&body[..size]);
356+
body = &body[size + 2..];
357+
}
358+
}
359+
282360
#[derive(Deserialize)]
283361
struct DnsResponse {
284362
#[serde(rename = "Answer")]
@@ -289,6 +367,21 @@ struct DnsResponse {
289367
struct DnsAnswer {
290368
data: String,
291369
}
370+
371+
fn is_public_google_sni_candidate(domain: &str) -> bool {
372+
let public_suffixes = [
373+
"google.com",
374+
"youtube.com",
375+
"googleapis.com",
376+
"gstatic.com",
377+
"ggpht.com",
378+
"withgoogle.com",
379+
];
380+
public_suffixes.iter().any(|suffix| {
381+
domain == *suffix || domain.strip_suffix(suffix).is_some_and(|prefix| prefix.ends_with('.'))
382+
})
383+
}
384+
292385
pub async fn discover_snis_from_google_ips(config: &Config) -> bool {
293386
let ips = fetch_google_ips(config).await;
294387
println!(
@@ -356,16 +449,28 @@ pub async fn discover_snis_from_google_ips(config: &Config) -> bool {
356449
}
357450
}
358451

359-
let discovered: Vec<String> = all_domains.into_iter().collect();
452+
let mut discovered: Vec<String> = all_domains
453+
.into_iter()
454+
.filter(|d| is_public_google_sni_candidate(d))
455+
.collect();
456+
457+
// PTRs on Google frontend IPs usually resolve to infrastructure names
458+
// like `*.1e100.net`, which are useful as edge hints but not usable as
459+
// fronting SNIs with normal certificate validation. Always validate the
460+
// public Google domain pool too, then add any public PTR-derived names on
461+
// top.
462+
discovered.extend(FAMOUS_GOOGLE_DOMAINS.iter().map(|d| d.to_string()));
463+
discovered.sort();
464+
discovered.dedup();
360465

361466
if discovered.is_empty() {
362-
println!("No SNI domains discovered.");
467+
println!("No public SNI candidates discovered.");
363468
println!();
364469
return false;
365470
}
366471

367472
println!(
368-
"Validating {} SNIs against DPI (IP: {})...",
473+
"Validating {} public SNI candidates against DPI (IP: {})...",
369474
discovered.len(),
370475
config.google_ip
371476
);
@@ -499,13 +604,8 @@ pub async fn fetch_dns_info(url_addr: &str) -> Result<String, Box<dyn std::error
499604
})
500605
.await?;
501606

502-
let response_str = String::from_utf8_lossy(&response);
503-
let body = response_str
504-
.split("\r\n\r\n")
505-
.nth(1)
506-
.ok_or("No HTTP body found")?;
507-
508-
Ok(body.to_string())
607+
let body = parse_http_response_body(&response)?;
608+
Ok(String::from_utf8_lossy(&body).to_string())
509609
}
510610

511611
#[derive(Debug)]
@@ -552,3 +652,39 @@ impl ServerCertVerifier for NoVerify {
552652
]
553653
}
554654
}
655+
656+
#[cfg(test)]
657+
mod tests {
658+
use super::{is_public_google_sni_candidate, parse_http_response_body};
659+
660+
#[test]
661+
fn parses_chunked_http_body_for_dns_json() {
662+
let raw = b"HTTP/1.1 200 OK\r\n\
663+
Transfer-Encoding: chunked\r\n\
664+
Content-Type: application/json\r\n\
665+
\r\n\
666+
5\r\n\
667+
{\"Sta\r\n\
668+
7\r\n\
669+
tus\":0}\r\n\
670+
0\r\n\
671+
\r\n";
672+
let body = parse_http_response_body(raw).unwrap();
673+
assert_eq!(body, br#"{"Status":0}"#);
674+
}
675+
676+
#[test]
677+
fn parses_content_length_http_body() {
678+
let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\n{\"Status\":0}";
679+
let body = parse_http_response_body(raw).unwrap();
680+
assert_eq!(body, br#"{"Status":0}"#);
681+
}
682+
683+
#[test]
684+
fn only_public_google_hostnames_are_scan_sni_candidates() {
685+
assert!(is_public_google_sni_candidate("www.google.com"));
686+
assert!(is_public_google_sni_candidate("fonts.googleapis.com"));
687+
assert!(!is_public_google_sni_candidate("ams15s21-in-f14.1e100.net"));
688+
assert!(!is_public_google_sni_candidate("82.221.107.34.bc.googleusercontent.com"));
689+
}
690+
}

0 commit comments

Comments
 (0)