Craft Anything: understand how any software works, and craft your own.
Rust
Read DNS service records and retain questionless address announcements (R3.12) (#1090)
Afloatd8087e70fc29
diff --git a/crates/formats/src/pcap.rs b/crates/formats/src/pcap.rsindex 53fe2e44..22194726 100644--- a/crates/formats/src/pcap.rs+++ b/crates/formats/src/pcap.rs@@ -768,7 +768,7 @@ fn transport(proto: u8, p: &[u8], d: &mut Decoded) {Some(length) if length < 12 => d.note = Some("DNS over TCP length is smaller than its header".into()),Some(length) => {if let Some(message) = framed.slice(2, usize::from(length)) {- dns(message, d, "dns");+ dns(message, d, "dns", false);} else {d.note = Some("DNS over TCP message cut short".into());}@@ -800,9 +800,9 @@ fn transport(proto: u8, p: &[u8], d: &mut Decoded) {};d.transport = Some(Transport { protocol: "udp", src_port: Some(sp), dst_port: Some(dp), payload_len: payload.len(), ..empty });if sp == 53 || dp == 53 {- dns(payload, d, "dns");+ dns(payload, d, "dns", false);} else if sp == 5353 || dp == 5353 {- dns(payload, d, "mdns");+ dns(payload, d, "mdns", dp == 5353);}}1 | 58 => {@@ -827,6 +827,7 @@ pub fn qtype_name(t: u16) -> String {33 => "SRV".into(),64 => "SVCB".into(),65 => "HTTPS".into(),+ 257 => "CAA".into(),255 => "ANY".into(),n => format!("TYPE{n}"),}@@ -844,7 +845,7 @@ fn dns_sd_service_label(label: &[u8]) -> bool {}/// A DNS name, the offset after it, and whether its wire labels name a DNS-SD instance.-fn dns_name(msg: &[u8], mut off: usize) -> Option<(String, usize, bool)> {+fn dns_name(msg: &[u8], mut off: usize, allow_compression: bool) -> Option<(String, usize, bool)> {let mut out = String::new();// Count the expanded wire name, including label lengths and the terminating root.let mut wire_len = 1usize;@@ -855,7 +856,7 @@ fn dns_name(msg: &[u8], mut off: usize) -> Option<(String, usize, bool)> {let len = *msg.get(off)?;match len {0 => return Some((if out.is_empty() { ".".into() } else { out }, after.unwrap_or(off + 1), labels >= 4 && service_instance)),- l if l & 0xc0 == 0xc0 => {+ l if allow_compression && l & 0xc0 == 0xc0 => {let ptr = usize::from(u16::from_be_bytes([l & 0x3f, *msg.get(off + 1)?]));after.get_or_insert(off + 2);if ptr >= off {@@ -891,9 +892,12 @@ fn dns_name(msg: &[u8], mut off: usize) -> Option<(String, usize, bool)> {/// Decode a bounded set of DNS questions and answer/prerequisite records from one message./// Preserve complete entries before malformed data and mark the message incomplete.-fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {+fn dns(msg: &[u8], d: &mut Decoded, label: &'static str, mdns_wire_format: bool) {let r = Reader::new(msg);let (Some(id), Some(flags), Some(qd), Some(an)) = (r.u16_be(0), r.u16_be(2), r.u16_be(4), r.u16_be(6)) else { return };+ if msg.len() < 12 {+ return;+ }let opcode = (flags >> 11) & 0xf;// Sanity: opcode 0–6 and no absurd counts, so random payload on port 53 isn't misread.if opcode > 6 || qd > 64 || qd == 0 && an == 0 {@@ -903,7 +907,7 @@ fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {let mut out = Dns { id, response: flags & 0x8000 != 0, rcode: (flags & 0xf) as u8, questions: Vec::new(), answers: Vec::new(), incomplete: false };let mut off = 12usize;for _ in 0..qd {- let Some((name, next, _)) = dns_name(msg, off) else {+ let Some((name, next, _)) = dns_name(msg, off, true) else {out.incomplete = true;break;};@@ -917,7 +921,7 @@ fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {}if !out.incomplete {for _ in 0..an.min(64) {- let Some((name, next, service_instance)) = dns_name(msg, off) else {+ let Some((name, next, service_instance)) = dns_name(msg, off, true) else {out.incomplete = true;break;};@@ -930,7 +934,13 @@ fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {out.incomplete = true;break;};+ let end = rd_off + rd.len();+ let within_record = msg.get(..end).unwrap_or(&[]);+ let record_class = if mdns_wire_format { class & 0x7fff } else { class };+ let empty_prerequisite = rd.is_empty() && opcode == 5 && matches!(class, 254 | 255) && ttl == 0;let value = match (rt, rd.len()) {+ (1 | 28 | 6 | 33 | 257, 0) if empty_prerequisite => String::new(),+ (1 | 28, _) if record_class != 1 => format!("<{} bytes>", rd.len()),(1, 4) => Ipv4Addr::new(rd.first().copied().unwrap_or(0),rd.get(1).copied().unwrap_or(0),@@ -939,16 +949,65 @@ fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {).to_string(),(28, 16) => Ipv6Addr::from(<[u8; 16]>::try_from(rd).unwrap_or([0; 16])).to_string(),+ (1 | 28, _) => {+ out.incomplete = true;+ break;+ }+ (33, _) => {+ let fields = Reader::new(rd);+ let Some((target, _, _)) = dns_name(within_record, rd_off + 6, mdns_wire_format).filter(|(_, after, _)| *after == end) else {+ out.incomplete = true;+ break;+ };+ let (Some(priority), Some(weight), Some(port)) = (fields.u16_be(0), fields.u16_be(2), fields.u16_be(4)) else {+ out.incomplete = true;+ break;+ };+ format!("{priority} {weight} {port} {target}")+ }+ (6, _) => {+ let soa = dns_name(within_record, rd_off, true).and_then(|(primary, pos, _)| {+ let (mailbox, pos, _) = dns_name(within_record, pos, true)?;+ let (words, tail) = within_record.get(pos..)?.as_chunks::<4>();+ if !tail.is_empty() {+ return None;+ }+ let words: &[[u8; 4]; 5] = words.try_into().ok()?;+ let [serial, refresh, retry, expire, minimum] = words.map(u32::from_be_bytes);+ Some(format!("{primary} {mailbox} {serial} {refresh} {retry} {expire} {minimum}"))+ });+ let Some(soa) = soa else {+ out.incomplete = true;+ break;+ };+ soa+ }+ (257, _) => {+ let Some((&flags, rest)) = rd.split_first() else {+ out.incomplete = true;+ break;+ };+ let caa = rest.split_first().and_then(|(&n, body)| body.split_at_checked(usize::from(n))).and_then(|(tag, value)| {+ (!tag.is_empty() && tag.iter().all(u8::is_ascii_alphanumeric)).then(|| {+ let value: String = value.iter().flat_map(|&byte| std::ascii::escape_default(byte)).map(char::from).collect();+ format!("{flags} {} {value}", String::from_utf8_lossy(tag))+ })+ });+ let Some(caa) = caa else {+ out.incomplete = true;+ break;+ };+ caa+ }(2 | 5 | 12 | 15, _) => {// RFC 2136 prerequisites can name an RRset without carrying its value.if rd.is_empty() && opcode == 5 && matches!(class, 254 | 255) && ttl == 0 {String::new()} else {- let end = rd_off + rd.len();let start = rd_off + if rt == 15 { 2 } else { 0 };// Keep earlier bytes available to compression pointers, but the encoded// name itself must fit the record and account for all of its RDATA.- let Some((name, _, _)) = dns_name(msg.get(..end).unwrap_or(&[]), start).filter(|(_, after, _)| *after == end) else {+ let Some((name, _, _)) = dns_name(within_record, start, true).filter(|(_, after, _)| *after == end) else {out.incomplete = true;break;};@@ -991,6 +1050,7 @@ fn dns(msg: &[u8], d: &mut Decoded, label: &'static str) {off = rd_off + usize::from(rdlen);}}+ out.incomplete |= flags & 0x0200 != 0;d.dns = Some(out);}@@ -1313,7 +1373,7 @@ pub struct Summary {/// "name TYPE value" from DNS responses.pub dns_answers: Vec<Count>,/// "question A|AAAA address" from DNS responses: each address answered, keyed by the response's first- /// question (so CNAME chains end at the name that was asked), as Wireshark's fields report them.+ /// question (so CNAME chains end at the name that was asked), or the record owner in a questionless reply.pub dns_addresses: Vec<Count>,/// "METHOD host target" from HTTP/1.x requests.pub http_requests: Vec<Count>,@@ -1438,11 +1498,11 @@ pub fn summarize(data: &[u8], cancelled: &dyn Fn() -> bool) -> Result<Summary, Ffor a in &dns.answers {answers.add(format!("{} {} {}", a.name, a.rtype, a.value));}- if dns.response- && let Some(q) = dns.questions.first()- {+ if dns.response {for a in dns.answers.iter().filter(|a| matches!(a.rtype.as_str(), "A" | "AAAA") && a.value.parse::<IpAddr>().is_ok()) {- addresses.add(format!("{} {} {}", q.name, a.rtype, a.value));+ // Questionless replies (including unsolicited mDNS) name the address in the answer.+ let name = dns.questions.first().map_or(&a.name, |q| &q.name);+ addresses.add(format!("{name} {} {}", a.rtype, a.value));}}}@@ -1919,6 +1979,6 @@ mod tests {let _ = summarize(&pcap(&f), &|| false);}// DNS compression loops are refused.- assert!(dns_name(&[0xc0, 0x00], 0).is_none());+ assert!(dns_name(&[0xc0, 0x00], 0, true).is_none());}}diff --git a/crates/formats/tests/dns_rdata_names.rs b/crates/formats/tests/dns_rdata_names.rsindex 88b7315b..7d7d0064 100644--- a/crates/formats/tests/dns_rdata_names.rs+++ b/crates/formats/tests/dns_rdata_names.rs@@ -182,3 +182,88 @@ fn value_dependent_update_name_prerequisites_keep_their_values() {}}}++#[test]+fn an_in_address_requires_the_right_wire_size_but_update_prerequisites_may_be_empty() {+ for (kind, bad) in [(1, &[1, 2, 3][..]), (28, &[0; 15][..])] {+ let mut msg = response(kind, bad, bad.len());+ assert!(decode(1, &packet(&msg)).dns.unwrap().incomplete);+ msg = response(kind, &[], 0);+ msg[2..4].copy_from_slice(&0x2800u16.to_be_bytes());+ let n = msg.len();+ msg[n - 8..n - 6].copy_from_slice(&255u16.to_be_bytes());+ msg[n - 6..n - 2].fill(0);+ let dns = decode(1, &packet(&msg)).dns.unwrap();+ assert!(!dns.incomplete);+ assert_eq!(dns.answers[0].value, "");+ }+}++#[test]+fn questionless_announcements_and_truncated_responses_keep_their_address() {+ let mut message = vec![0, 0, 0x86, 0, 0, 0, 0, 1, 0, 0, 0, 0];+ message.extend(b"\x04node\x05local\x00\x00\x01\x80\x01\x00\x00\x00\x3c\x00\x04\xc0\x00\x02\x04");+ let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [224, 0, 0, 251], &udp(5353, 5353, &message)));+ let dns = decode(1, &frame).dns.unwrap();+ assert!(dns.incomplete);+ assert_eq!(dns.answers.len(), 1);+ assert_eq!(summarize(&pcap(&[frame]), &|| false).unwrap().dns_addresses[0].value, "node.local A 192.0.2.4");+ assert!(decode(1, &packet(&message[..8])).dns.is_none());+}++#[test]+fn service_records_report_their_fields_and_refuse_invalid_framing() {+ let mut soa = vec![0xc0, 12, 0xc0, 12];+ for n in 1u32..=5 {+ soa.extend(n.to_be_bytes());+ }+ for (kind, data, expected) in [+ (33, &b"\x00\x01\x00\x02\x01\xbb\x03srv\x00"[..], "1 2 443 srv"),+ (6, soa.as_slice(), "example.com example.com 1 2 3 4 5"),+ (257, &b"\x80\x05issueca.test"[..], "128 issue ca.test"),+ ] {+ let dns = decode(1, &packet(&response(kind, data, data.len()))).dns.unwrap();+ assert!(!dns.incomplete);+ assert_eq!(dns.answers[0].value, expected);+ }+ for (kind, bad) in [(33, &b"\x00\x01\x00\x02\x01\xbb\xc0\x0c"[..]), (6, &soa[..soa.len() - 1]), (257, &b"\x00\x06issue"[..])] {+ let dns = decode(1, &packet(&response(kind, bad, bad.len()))).dns.unwrap();+ assert!(dns.incomplete);+ assert!(dns.answers.is_empty());+ }+}++#[test]+fn mdns_srv_targets_can_be_compressed_except_in_legacy_replies() {+ let data = [0, 1, 0, 2, 1, 187, 0xc0, 12];+ let msg = response(33, &data, data.len());+ for (port, legacy) in [(5353, false), (51000, true)] {+ let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [192, 0, 2, 1], &udp(5353, port, &msg)));+ let dns = decode(1, &frame).dns.unwrap();+ assert_eq!(dns.incomplete, legacy);+ if !legacy {+ assert_eq!(dns.answers[0].value, "1 2 443 example.com");+ }+ }+}++#[test]+fn caa_binary_values_remain_distinct_in_the_inventory() {+ for (bytes, display) in [(&b"\xff"[..], r"\xff"), (b"\xfe", r"\xfe"), (br"\xff", r"\\xff")] {+ let mut data = b"\x00\x01x".to_vec();+ data.extend(bytes);+ let dns = decode(1, &packet(&response(257, &data, data.len()))).dns.unwrap();+ assert_eq!(dns.answers[0].value, format!("0 x {display}"));+ }+}++#[test]+fn only_mdns_masks_the_cache_flush_bit_in_an_address_class() {+ let mut msg = response(1, &[192, 0, 2, 1], 4);+ let class = msg.len() - 12;+ msg[class..class + 2].copy_from_slice(&0x8001u16.to_be_bytes());+ for (port, expected) in [(53, "<4 bytes>"), (5353, "192.0.2.1")] {+ let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [192, 0, 2, 1], &udp(port, port, &msg)));+ assert_eq!(decode(1, &frame).dns.unwrap().answers[0].value, expected);+ }+}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 801c6271..fd96f1ad 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -1236,6 +1236,8 @@ Owner: open · Status: in progressexchanges, and report malformed records as incomplete instead of inventing answer values,while preserving legal empty DNS UPDATE RRset prerequisites— claimed: Afloat16, branch bugfix/r3.12-dns-rdata-names-review-20261104+- [x] Keep address and service records attached to their owner and validate the record's wire fields.+ — claimed: Afloat16, branch bugfix/r3.12-dns-record-evidence### R3.13 Web inspection correctnessOwner: open · Status: in progressdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex e58eaaf9..be5bbe28 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -14,6 +14,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Runner-owned app windows | Runtime capture tries the launched process and its descendants; the captured window owner's PID is also used for the UI tree. Unrelated processes with matching names are excluded. Process discovery has a deadline, output cap and candidate limit | Hermetic regressions cover runner/child/grandchild ownership, unrelated windows, direct launches, cycles, malformed rows, caps and errors. A macOS process snapshot finds an owned child without opening a window. Windows and real Go GUI capture have not been run || New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change || macOS optional UI tree and screenshots | `runtime_ui_read` with `accessibility: false` skips the tree and its permission check, returns empty nodes without truncation, and records the skipped read (#307). Walkthroughs still require Accessibility. With `screenshot: true`, macOS 14+ returns one owned-by-pid window as PNG/base64, restricted by `window_id` when supplied; without it, the first matching on-screen window. Images are limited to 2048 px per side and 6 MiB PNG. Combined JSON stays within the 16 MiB helper output cap; oversized trees retain a prefix with explicit truncation and partial coverage while preserving the image. Missing Screen Recording permission, a missing window or a capture failure is an explicit screenshot limitation with partial coverage (#248). Denied Accessibility permission returns a tool error before capture when the tree is enabled (the default); set `accessibility: false` to skip the tree. Permission dialogs are never opened | Synthetic Swift serializer regression covers combined tree/image overflow, escaped Unicode values, a single oversized node, an oversized image, and unchanged small/skipped trees. Engine regressions compile/run the real Swift helper: skipped trees at node limits 0/1, screenshot-off control, and impossible-window screenshot errors propagated to evidence. Live helper probe on macOS 27.2 captured only an owned AppKit fixture: valid 320 × 192 PNG (14,400 bytes), matching window id; screenshot-off returned no image/error. No granted-permission tree read, walkthrough, macOS 14 run or MCP transport run |+| DNS service records and address announcements | SRV, SOA and CAA answers expose their wire fields. Internet addresses have checked widths. Truncated replies retain their complete records, and unsolicited address announcements keep their owner. | Synthetic DNS and mDNS captures cover bounded fields, compressed names, empty UPDATE prerequisites and legacy replies. || DNS question boundaries | A question is retained only when its name, type and class are complete. A missing class byte marks the DNS message incomplete; preceding complete questions remain available, and incomplete questions do not enter the query inventory | Four packet regressions cover both truncation lengths, multiple questions, complete class values and the capture summary. No live capture was used || Reject impossible IPv4 header and total lengths | IPv4 decoding rejects impossible header lengths and reports incomplete base headers or options. | Synthetic byte fixtures in `pcap_ipv4_lengths` integration regressions. Cover 10–19 captured header bytes, total lengths below IHL, missing options, complete options, truncated transport headers with readable ports, and a cut UDP payload with both ports and its captured length preserved. || Validate the version in IPv6 frames | IPv6 decoding checks the packet version before reporting IPv6 facts, including captures declaring raw IPv6; explicit raw IPv4 likewise uses IPv4 validation. | Synthetic byte fixtures in `pcap_ipv6_version` integration regressions. Cover incorrect versions behind the IPv6 EtherType, mismatched explicit raw IPv4 and IPv6 link types, matching explicit and generic raw packets, and valid IPv6 traffic-class bits. |