From 9fe5408160afef328bea30432179d1ad931b7f8e Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Thu, 13 Aug 2026 13:50:02 +0900 Subject: [PATCH] feat(kernel): validate DNS messages arriving on the DNS port MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wire the now-hardened DNS parser into the UDP receive path as a structural admission check, mirroring how `handle_udp_packet` already delegates to `crate::udp` and re-checks bounds at the call site. `dns.rs` gains `validate_message`, a framing-only validator that walks the header and every declared section (questions, then answer/authority/additional records) using the pointer-hardened `decode_domain_name`, bounds-checks the fixed fields and each `RDLENGTH`, treats RDATA as opaque, and requires the message to end exactly at the last record. Unlike `parse_response` it accepts both queries and responses, imposes no answer cap, and covers the authority/additional sections, so it is a sound gate regardless of the QR bit or response code. It deliberately reuses `decode_domain_name`, not `skip_name`, so the forward/self-pointer rejection applies to every name. `handle_udp_packet` now keeps the parsed UDP header and, for datagrams whose source or destination port is 53, validates the payload after the checksum is verified. Malformed DNS is dropped silently via the existing `Ok(0)` convention rather than surfaced as an error; no resolver state, cache, or query transmission is introduced — that plumbing is a separate concern. Tests: `validate_message` accepts a `build_query` output and rejects a forward-pointer question, an RDLENGTH overrun, and trailing bytes; at the net layer a valid DNS query on port 53 is consumed (`Ok(0)`) and a valid-checksum-but-malformed datagram is dropped rather than erroring. Suite: 4607 passed, 0 skipped. QEMU boot passes on all three architectures. --- crates/kernel/src/dns.rs | 116 +++++++++++++++++++++++++++++++++++++ crates/kernel/src/net.rs | 121 ++++++++++++++++++++++++++++++++++++++- crates/kernel/src/udp.rs | 2 +- 3 files changed, 237 insertions(+), 2 deletions(-) diff --git a/crates/kernel/src/dns.rs b/crates/kernel/src/dns.rs index f55d7615..0f8a624d 100644 --- a/crates/kernel/src/dns.rs +++ b/crates/kernel/src/dns.rs @@ -624,6 +624,69 @@ pub fn parse_response(data: &[u8]) -> Result { Ok(response) } +/// Structurally validate a DNS message (query or response) without +/// interpreting it. +/// +/// Walks the header and every declared section — `qd_count` questions, then +/// `an_count` + `ns_count` + `ar_count` resource records — checking that each +/// name parses within bounds (via the pointer-hardened +/// [`decode_domain_name`]) and that fixed fields and `RDLENGTH` stay inside +/// the message. `RDATA` is treated as opaque bytes: record-type-specific names +/// inside `CNAME`/`MX`/`SOA` and similar are *not* followed, since that is +/// semantic parsing beyond framing. +/// +/// Unlike [`parse_response`], this accepts both queries and responses, imposes +/// no answer-count cap, and validates the authority and additional sections, +/// so it is a sound admission gate for any DNS datagram regardless of the QR +/// bit or response code. +/// +/// # Errors +/// +/// Returns [`Error::InvalidArgument`] if the message is truncated, a name or +/// record field runs past the end, a compression pointer is malformed, or +/// bytes remain after the last declared record (`pos != data.len()`). +pub fn validate_message(data: &[u8]) -> Result<()> { + let header = parse_header(data)?; + let mut pos = DNS_HEADER_LEN; + // Scratch for decoded names; only the consumed length matters here. + let mut name_buf = [0u8; 256]; + + for _ in 0..header.qd_count { + let (consumed, _) = decode_domain_name(data, pos, &mut name_buf)?; + pos = pos.saturating_add(consumed); + // QTYPE + QCLASS. + pos = pos.saturating_add(4); + if pos > data.len() { + return Err(Error::InvalidArgument); + } + } + + let rr_total = (header.an_count as usize) + .saturating_add(header.ns_count as usize) + .saturating_add(header.ar_count as usize); + for _ in 0..rr_total { + let (consumed, _) = decode_domain_name(data, pos, &mut name_buf)?; + pos = pos.saturating_add(consumed); + // TYPE(2) + CLASS(2) + TTL(4) + RDLENGTH(2). + if pos.saturating_add(10) > data.len() { + return Err(Error::InvalidArgument); + } + let rdlength = u16::from_be_bytes([data[pos + 8], data[pos + 9]]) as usize; + pos = pos.saturating_add(10); + if pos.saturating_add(rdlength) > data.len() { + return Err(Error::InvalidArgument); + } + pos = pos.saturating_add(rdlength); + } + + // Reject trailing bytes: a well-formed message ends exactly at the last + // declared record, so anything left over is padding or a smuggled tail. + if pos != data.len() { + return Err(Error::InvalidArgument); + } + Ok(()) +} + // ========================================================================= // DnsCache // ========================================================================= @@ -1053,6 +1116,59 @@ mod tests { ); } + // ---- validate_message ------------------------------------------------- + + // A real query built by build_query must validate. + #[test] + fn test_validate_message_accepts_built_query() { + let mut buf = [0u8; 512]; + let len = build_query(0x1234, b"example.com", TYPE_A, &mut buf).unwrap(); + validate_message(&buf[..len]).unwrap(); + } + + // A query whose question name uses a forward pointer must be rejected even + // though the rest of the framing is well-formed. + #[test] + fn test_validate_message_rejects_forward_pointer_in_question() { + let mut data = [0u8; 32]; + // Header: qd_count = 1. + data[5] = 1; + // Question name at offset 12 is a forward pointer to offset 20. + data[12] = 0xC0; + data[13] = 0x14; + // QTYPE + QCLASS at 14..18. + data[18] = 0; + // A label at offset 20 that the forward pointer would wrongly reach. + data[20] = 1; + data[21] = b'x'; + data[22] = 0; + assert!(validate_message(&data).is_err()); + } + + // A declared answer whose RDLENGTH overruns the message must be rejected. + #[test] + fn test_validate_message_rejects_rdlength_overrun() { + let mut data = [0u8; 64]; + // Header: qd_count = 0, an_count = 1. + data[7] = 1; + // Owner name at 12: a single root label (1 byte). + data[12] = 0; + // TYPE(2)+CLASS(2)+TTL(4) at 13..23, RDLENGTH at 23..25. + data[23] = 0; + data[24] = 200; // RDLENGTH = 200, but only ~39 bytes remain. + assert!(validate_message(&data).is_err()); + } + + // Trailing bytes after the last declared record must be rejected. + #[test] + fn test_validate_message_rejects_trailing_bytes() { + let mut buf = [0u8; 512]; + let len = build_query(0x1234, b"example.com", TYPE_A, &mut buf).unwrap(); + // Append a stray byte beyond the well-formed query. + buf[len] = 0xAA; + assert!(validate_message(&buf[..len + 1]).is_err()); + } + #[test] fn test_build_query() { let mut buf = [0u8; 512]; diff --git a/crates/kernel/src/net.rs b/crates/kernel/src/net.rs index d9bde7bb..fec4fa46 100644 --- a/crates/kernel/src/net.rs +++ b/crates/kernel/src/net.rs @@ -905,12 +905,27 @@ impl NetworkStack { // The UDP length field is authoritative; `datagram` is trimmed // to exactly that length so the checksum covers no trailing // bytes from the IP payload. - let (_hdr, datagram) = crate::udp::parse_udp_datagram(udp_payload)?; + let (hdr, datagram) = crate::udp::parse_udp_datagram(udp_payload)?; // Verify against the real IPs from the IP header; drop on a // checksum mismatch. crate::udp::verify_udp_checksum(&ip_hdr.src_addr, &ip_hdr.dst_addr, datagram)?; + // DNS admission check: a datagram on the DNS port (query to us, or a + // response from a server) must be a structurally well-formed DNS + // message. This mirrors the file's parse-and-validate convention and + // drops malformed frames silently (`Ok(0)`) rather than surfacing them + // as errors. It is framing validation only — RDATA is not interpreted + // and no resolver state is touched here. + if hdr.src_port == crate::dns::DNS_PORT || hdr.dst_port == crate::dns::DNS_PORT { + let Some(dns_payload) = datagram.get(crate::udp::UDP_HEADER_LEN..) else { + return Ok(0); + }; + if crate::dns::validate_message(dns_payload).is_err() { + return Ok(0); + } + } + Ok(0) } @@ -1416,4 +1431,108 @@ mod tests { let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); assert_eq!(r, 0); } + + /// Build an Ethernet+IPv4+UDP frame for a specific destination port. + /// + /// Same construction as [`build_udp_frame`] but with caller-chosen ports, + /// so DNS (port 53) traffic can be exercised. + #[allow(clippy::too_many_arguments)] + fn build_udp_frame_to_port( + src_ip: [u8; 4], + dst_ip: [u8; 4], + src_port: u16, + dst_port: u16, + payload: &[u8], + good_checksum: bool, + frame: &mut [u8], + ) -> usize { + let mut udp = [0u8; 256]; + let udp_len = crate::udp::write_udp(src_port, dst_port, payload, &mut udp) + .ok() + .unwrap(); + let cksum = crate::udp::udp_checksum(&src_ip, &dst_ip, &udp[..udp_len]); + let ck = if good_checksum { + cksum.to_be_bytes() + } else { + (cksum ^ 0x0100).to_be_bytes() + }; + udp[6] = ck[0]; + udp[7] = ck[1]; + + frame[..6].copy_from_slice(&[0xAA; 6]); + frame[6..12].copy_from_slice(&[0xBB; 6]); + frame[12] = 0x08; + frame[13] = 0x00; + let ip = Ipv4Header { + version_ihl: 0x45, + tos: 0, + total_len: (IPV4_HEADER_MIN_LEN + udp_len) as u16, + id: 0, + flags_frag: 0, + ttl: 64, + protocol: PROTO_UDP, + checksum: 0, + src_addr: src_ip, + dst_addr: dst_ip, + }; + let ip_off = ETHER_HEADER_LEN; + write_ipv4(&mut frame[ip_off..], &ip).ok().unwrap(); + let udp_off = ip_off + IPV4_HEADER_MIN_LEN; + frame[udp_off..udp_off + udp_len].copy_from_slice(&udp[..udp_len]); + udp_off + udp_len + } + + // A structurally valid DNS query on port 53 must be admitted (consumed, + // Ok(0)) — validation must not reject legitimate DNS traffic. + #[test] + fn dns_valid_query_on_port53_accepted() { + let mut stack = + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); + let mut qbuf = [0u8; 128]; + let qlen = crate::dns::build_query(0x1234, b"example.com", crate::dns::TYPE_A, &mut qbuf) + .ok() + .unwrap(); + let mut frame = [0u8; 256]; + let n = build_udp_frame_to_port( + [10, 0, 0, 1], + [10, 0, 0, 2], + 12345, + crate::dns::DNS_PORT, + &qbuf[..qlen], + true, + &mut frame, + ); + let mut reply = [0u8; 256]; + let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); + assert_eq!(r, 0, "valid DNS query must be consumed, not error"); + } + + // A DNS datagram with a valid UDP checksum but a malformed (forward-pointer) + // message must be dropped silently by the admission gate, not error. + #[test] + fn dns_forward_pointer_on_port53_dropped_not_error() { + let mut stack = + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); + // Hand-build a DNS message whose question name is a forward pointer. + let mut msg = [0u8; 32]; + msg[5] = 1; // qd_count = 1 + msg[12] = 0xC0; + msg[13] = 0x14; // forward pointer to offset 20 + msg[20] = 1; + msg[21] = b'x'; + msg[22] = 0; + let mut frame = [0u8; 256]; + let n = build_udp_frame_to_port( + [10, 0, 0, 1], + [10, 0, 0, 2], + 12345, + crate::dns::DNS_PORT, + &msg, + true, + &mut frame, + ); + let mut reply = [0u8; 256]; + let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); + assert_eq!(r, 0, "malformed DNS must be dropped (Ok(0)), not an error"); + } } diff --git a/crates/kernel/src/udp.rs b/crates/kernel/src/udp.rs index bea3980b..5ddbf89f 100644 --- a/crates/kernel/src/udp.rs +++ b/crates/kernel/src/udp.rs @@ -17,7 +17,7 @@ use oncrix_lib::{Error, Result}; // ========================================================================= /// UDP header size in bytes (src_port + dst_port + length + checksum). -const UDP_HEADER_LEN: usize = 8; +pub(crate) const UDP_HEADER_LEN: usize = 8; /// Maximum number of UDP sockets in the socket table. const UDP_TABLE_SIZE: usize = 32;