From f50f3ed0d0f6933eb093bfce5d634f4ba8081c50 Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 14:50:27 +0900 Subject: [PATCH 1/6] feat(kernel): harden GRE parsing and wire protocol 47 dispatch Reject GRE headers with reserved or deprecated flag bits, add parser coverage for optional-field offsets and truncation, and route IPv4 protocol 47 through the audited framing gate. The full-suite gate follows after the independent Landlock host-test race is fixed. --- crates/kernel/src/gre.rs | 110 ++++++++++++++++++++++++++++++++ crates/kernel/src/net.rs | 131 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 241 insertions(+) diff --git a/crates/kernel/src/gre.rs b/crates/kernel/src/gre.rs index 340294d6..2a9e5c76 100644 --- a/crates/kernel/src/gre.rs +++ b/crates/kernel/src/gre.rs @@ -268,6 +268,19 @@ pub fn parse_gre(data: &[u8]) -> Result<(GreHeader, usize)> { return Err(Error::InvalidArgument); } + // SECURITY (RFC 2784 §2.3, RFC 2890 §2): only the C/K/S optional-field + // bits (15/13/12) and the 3 version bits (0-2) are meaningful. Every other + // flag bit is Reserved0 or a deprecated RFC 1701 field (Routing Present, + // strict source route) that this parser does not implement. Accepting + // them would leave the payload offset computed only from C/K/S while the + // sender intended extra fields, mis-aligning the payload. Reject any bit + // outside the supported mask rather than parse against a guessed layout. + const GRE_SUPPORTED_BITS: u16 = + GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT | 0x07; + if (flags_version & !GRE_SUPPORTED_BITS) != 0 { + return Err(Error::InvalidArgument); + } + let flags = GreFlags::from_bits(flags_version); let required_len = flags.header_len(); if data.len() < required_len { @@ -793,3 +806,100 @@ impl GreRegistry { count } } + +// ========================================================================= +// Tests +// ========================================================================= + +#[cfg(test)] +mod tests { + use super::*; + + const IPV4_PROTO: u16 = 0x0800; + + /// Build a GRE header+payload with the given raw flags_version word. + fn frame(flags_version: u16, payload: &[u8]) -> ([u8; 64], usize) { + let mut f = [0u8; 64]; + f[0..2].copy_from_slice(&flags_version.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + f[4..4 + payload.len()].copy_from_slice(payload); + (f, 4 + payload.len()) + } + + // A plain base header (no optional fields) must parse and return offset 4. + #[test] + fn parse_base_header_returns_offset_4() { + let (f, n) = frame(0x0000, &[0x45, 0x00]); + let (hdr, off) = parse_gre(&f[..n]).unwrap(); + assert_eq!(off, 4); + assert_eq!(hdr.protocol_type, IPV4_PROTO); + assert!(!hdr.flags().checksum_present()); + } + + // All C/K/S combinations must parse with the correct payload offset. + #[test] + fn parse_all_optional_field_offsets() { + // K only: 4 + 4 = 8 + let (f, n) = frame(GreFlags::KEY_BIT, &[0u8; 4]); + assert_eq!(parse_gre(&f[..n]).unwrap().1, 8); + // K+S: 4 + 4 + 4 = 12 + let (f, n) = frame(GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT, &[0u8; 8]); + assert_eq!(parse_gre(&f[..n]).unwrap().1, 12); + // C+K+S: 4 + 4 + 4 + 4 = 16 + let (f, n) = frame( + GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT, + &[0u8; 12], + ); + assert_eq!(parse_gre(&f[..n]).unwrap().1, 16); + } + + // Truncated optional fields must be rejected before any read. + #[test] + fn parse_rejects_truncated_optional_field() { + // K bit set but only 2 of the 4 key bytes present. + let mut f = [0u8; 6]; + f[0..2].copy_from_slice(&GreFlags::KEY_BIT.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + assert!(parse_gre(&f).is_err()); + } + + // Version != 0 must be rejected. + #[test] + fn parse_rejects_nonzero_version() { + let (f, n) = frame(0x0001, &[0u8; 0]); // version = 1 + assert!(parse_gre(&f[..n]).is_err()); + } + + // SECURITY (RFC 2784 §2.3): reserved/unknown flag bits must be rejected, + // not silently accepted. A bit set in the Reserved0 region (bits 3-11) + // indicates a non-conformant or RFC 1701-era packet this parser does not + // implement; accepting it would mis-align the payload offset. + #[test] + fn parse_rejects_reserved_flag_bits() { + // Bit 11 (a Reserved0 bit, not C/K/S/version) set. + let (f, n) = frame(1 << 11, &[0u8; 0]); + assert!( + parse_gre(&f[..n]).is_err(), + "reserved flag bit must be rejected" + ); + } + + // RFC 1701 Routing Present (bit 14 in this layout) is deprecated and not + // implemented; it must be rejected, not skipped with a guessed length. + #[test] + fn parse_rejects_rfc1701_routing_bit() { + let (f, n) = frame(1 << 14, &[0u8; 0]); + assert!( + parse_gre(&f[..n]).is_err(), + "RFC 1701 routing bit must be rejected" + ); + } + + // A valid header with only C/K/S/version bits must still parse (the + // reserved-bit gate must not over-reject). + #[test] + fn parse_accepts_valid_flag_combination() { + let (f, n) = frame(GreFlags::KEY_BIT, &[0u8; 4]); + assert!(parse_gre(&f[..n]).is_ok(), "valid flags must parse"); + } +} diff --git a/crates/kernel/src/net.rs b/crates/kernel/src/net.rs index 17ee405e..d15492c3 100644 --- a/crates/kernel/src/net.rs +++ b/crates/kernel/src/net.rs @@ -347,6 +347,9 @@ pub const PROTO_TCP: u8 = 6; /// IP protocol number for UDP. pub const PROTO_UDP: u8 = 17; +/// IP protocol number for GRE (RFC 2784). +pub const PROTO_GRE: u8 = 47; + /// Parsed IPv4 header. /// /// Stored in host byte order; the raw on-wire format uses @@ -842,6 +845,7 @@ impl NetworkStack { match ip_hdr.protocol { PROTO_ICMP => self.handle_icmp_packet(eth, &ip_hdr, ip_payload, reply_buf), PROTO_UDP => self.handle_udp_packet(&ip_hdr, ip_payload), + PROTO_GRE => self.handle_gre_packet(&ip_hdr, ip_payload), _ => Err(Error::NotImplemented), } } @@ -901,6 +905,22 @@ impl NetworkStack { /// [`crate::udp::parse_udp_datagram`] for a malformed length field, /// and from [`crate::udp::verify_udp_checksum`] for a datagram whose /// non-zero checksum does not verify. + /// Handle an incoming GRE packet (IP protocol 47, RFC 2784). + /// + /// Framing validation only: parse the GRE header (base + C/K/S optional + /// fields) and drop malformed frames silently via `Ok(0)`. GRE has no + /// length field — the payload extent is the enclosing IPv4 payload, whose + /// bounds `parse_ipv4` already enforced — so `parse_gre` only needs to + /// validate the header shape and optional-field offsets. No tunnel + /// decapsulation or inner-packet dispatch is performed here; that requires + /// a tunnel table and is a separate concern. + fn handle_gre_packet(&self, _ip_hdr: &Ipv4Header, gre_payload: &[u8]) -> Result { + if crate::gre::parse_gre(gre_payload).is_err() { + return Ok(0); + } + Ok(0) + } + fn handle_udp_packet(&self, ip_hdr: &Ipv4Header, udp_payload: &[u8]) -> Result { // The UDP length field is authoritative; `datagram` is trimmed // to exactly that length so the checksum covers no trailing @@ -1499,6 +1519,117 @@ mod tests { udp_off + udp_len } + /// Build an Ethernet+IPv4 frame carrying a raw IP payload of a chosen + /// protocol (no transport header). Used for GRE (protocol 47). + fn build_ip_proto_frame( + src_ip: [u8; 4], + dst_ip: [u8; 4], + protocol: u8, + payload: &[u8], + frame: &mut [u8], + ) -> usize { + 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 + payload.len()) as u16, + id: 0, + flags_frag: 0, + ttl: 64, + protocol, + 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 p_off = ip_off + IPV4_HEADER_MIN_LEN; + frame[p_off..p_off + payload.len()].copy_from_slice(payload); + p_off + payload.len() + } + + /// Build a GRE header (flags word + protocol type) + inner payload. + fn gre_bytes(flags_version: u16, proto: u16, inner: &[u8], out: &mut [u8]) -> usize { + out[0..2].copy_from_slice(&flags_version.to_be_bytes()); + out[2..4].copy_from_slice(&proto.to_be_bytes()); + out[4..4 + inner.len()].copy_from_slice(inner); + 4 + inner.len() + } + + // A structurally valid GRE packet (base header, no optional fields) must + // be admitted (consumed, Ok(0)) — the gate must not reject real GRE. + #[test] + fn gre_valid_base_header_accepted() { + let mut stack = + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); + let mut gre = [0u8; 64]; + let glen = gre_bytes(0x0000, 0x0800, &[0x45, 0x00, 0x00, 0x14], &mut gre); + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame( + [10, 0, 0, 1], + [10, 0, 0, 2], + PROTO_GRE, + &gre[..glen], + &mut frame, + ); + let mut reply = [0u8; 128]; + let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); + assert_eq!(r, 0, "valid GRE must be consumed, not error"); + } + + // A GRE packet with a reserved/deprecated flag bit set must be dropped + // silently by the admission gate, not surfaced as an error. + #[test] + fn gre_reserved_flag_dropped_not_error() { + let mut stack = + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); + let mut gre = [0u8; 64]; + // Bit 11 = a Reserved0 bit, rejected by the supported-bits mask. + let glen = gre_bytes(1 << 11, 0x0800, &[0x45, 0x00, 0x00, 0x14], &mut gre); + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame( + [10, 0, 0, 1], + [10, 0, 0, 2], + PROTO_GRE, + &gre[..glen], + &mut frame, + ); + let mut reply = [0u8; 128]; + let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); + assert_eq!(r, 0, "reserved-flag GRE must be dropped (Ok(0)), not error"); + } + + // A GRE packet with K+S optional fields must parse the correct offset and + // be admitted — optional-field flags are valid framing. + #[test] + fn gre_key_sequence_optional_fields_accepted() { + let mut stack = + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); + // flags_version with K (bit 13) + S (bit 12) set; 4+4 optional bytes. + let mut gre = [0u8; 64]; + let flags: u16 = (1 << 13) | (1 << 12); + gre[0..2].copy_from_slice(&flags.to_be_bytes()); + gre[2..4].copy_from_slice(&0x0800u16.to_be_bytes()); + // key(4) + sequence(4) + a little inner payload. + gre[4..8].copy_from_slice(&0xDEADBEEFu32.to_be_bytes()); + gre[8..12].copy_from_slice(&1u32.to_be_bytes()); + gre[12] = 0x45; + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame( + [10, 0, 0, 1], + [10, 0, 0, 2], + PROTO_GRE, + &gre[..13], + &mut frame, + ); + let mut reply = [0u8; 128]; + let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); + assert_eq!(r, 0, "K+S GRE must be consumed, not error"); + } + // A structurally valid DNS query on port 53 must be admitted (consumed, // Ok(0)) — validation must not reject legitimate DNS traffic. #[test] From d53e5bd7c0f1efd96a19bbab9a39c83571aa7db9 Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 17:17:06 +0900 Subject: [PATCH 2/6] fix(kernel): validate GRE flags and checksums --- crates/kernel/src/gre.rs | 304 ++++++++++++++++++++++++++++++--------- 1 file changed, 236 insertions(+), 68 deletions(-) diff --git a/crates/kernel/src/gre.rs b/crates/kernel/src/gre.rs index 2a9e5c76..ece0201a 100644 --- a/crates/kernel/src/gre.rs +++ b/crates/kernel/src/gre.rs @@ -253,8 +253,9 @@ impl GreHeader { /// /// # Errors /// -/// Returns [`Error::InvalidArgument`] if `data` is too short for -/// the indicated optional fields or if the GRE version is not 0. +/// Returns [`Error::InvalidArgument`] if `data` is too short for the +/// indicated optional fields, if the GRE version is not 0, or if any +/// RFC 2784 §2.3 discard bit (`0x4c00`) is set. pub fn parse_gre(data: &[u8]) -> Result<(GreHeader, usize)> { if data.len() < GRE_HEADER_MIN_LEN { return Err(Error::InvalidArgument); @@ -268,16 +269,16 @@ pub fn parse_gre(data: &[u8]) -> Result<(GreHeader, usize)> { return Err(Error::InvalidArgument); } - // SECURITY (RFC 2784 §2.3, RFC 2890 §2): only the C/K/S optional-field - // bits (15/13/12) and the 3 version bits (0-2) are meaningful. Every other - // flag bit is Reserved0 or a deprecated RFC 1701 field (Routing Present, - // strict source route) that this parser does not implement. Accepting - // them would leave the payload offset computed only from C/K/S while the - // sender intended extra fields, mis-aligning the payload. Reject any bit - // outside the supported mask rather than parse against a guessed layout. - const GRE_SUPPORTED_BITS: u16 = - GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT | 0x07; - if (flags_version & !GRE_SUPPORTED_BITS) != 0 { + // RFC 2784 §2.3: a conformant receiver MUST discard a packet that sets a + // bit whose RFC 1701 meaning implies extra header fields this parser does + // not decode — RFC bit 1 (0x4000, Routing Present), bit 4 (0x0800, strict + // source route), and bit 5 (0x0400, recursion control). Accepting any of + // these would leave the payload offset computed only from C/K/S while the + // sender intended additional fields, mis-aligning the payload. Reserved0 + // bits 6-12 (0x03f8) carry no length implication and MUST be ignored, so + // they are deliberately absent from this discard mask. + const GRE_DISCARD_BITS: u16 = 0x4c00; + if (flags_version & GRE_DISCARD_BITS) != 0 { return Err(Error::InvalidArgument); } @@ -403,6 +404,27 @@ fn verify_gre_checksum(packet: &[u8], payload_offset: usize, wire_checksum: u16) Ok(()) } +/// Shared receive-side GRE gate: [`parse_gre`] plus, when C=1, an RFC 2784 +/// §2.1 checksum over the whole header and payload (checksum field zeroed). +/// +/// Header-only frames are valid; payload-requiring callers check that +/// separately. Nonzero Reserved1 is accepted (RFC 2784 mandates transmit +/// zero, not receiver discard) when the checksum that covers it verifies. +/// +/// Returns the [`GreHeader`] and payload offset from [`parse_gre`]. +/// +/// # Errors +/// +/// [`Error::InvalidArgument`] if the header is malformed (see [`parse_gre`]) +/// or if C=1 and the checksum does not verify. +pub(crate) fn validate_gre_packet(packet: &[u8]) -> Result<(GreHeader, usize)> { + let (header, payload_offset) = parse_gre(packet)?; + if header.flags().checksum_present() { + verify_gre_checksum(packet, payload_offset, header.checksum)?; + } + Ok((header, payload_offset)) +} + /// Serialise a GRE header into `buf`. /// /// Returns the number of bytes written (the header length). @@ -635,17 +657,12 @@ impl GreTunnel { return Err(Error::InvalidArgument); } - let (header, payload_offset) = parse_gre(outer_packet)?; - - // SECURITY: when the Checksum-Present (C) flag is set, verify the - // RFC 1071 one's-complement checksum over the full GRE header + - // payload *before* trusting any of the packet. A forged frame - // with C set and a bogus checksum is dropped here, so its inner - // payload is never returned for re-injection into the stack. - // The C-clear path skips this entirely and is unaffected. - if header.flags().checksum_present() { - verify_gre_checksum(outer_packet, payload_offset, header.checksum)?; - } + // SECURITY: run the shared receive-side validator, which structurally + // parses the header and — when C=1 — verifies the RFC 1071 checksum + // over the full GRE header + payload before any of the packet is + // trusted. A forged frame with C set and a bogus checksum is dropped + // here, so its inner payload is never returned for re-injection. + let (header, payload_offset) = validate_gre_packet(outer_packet)?; // Validate key if configured. if let Some(expected_key) = self.key @@ -836,23 +853,6 @@ mod tests { assert!(!hdr.flags().checksum_present()); } - // All C/K/S combinations must parse with the correct payload offset. - #[test] - fn parse_all_optional_field_offsets() { - // K only: 4 + 4 = 8 - let (f, n) = frame(GreFlags::KEY_BIT, &[0u8; 4]); - assert_eq!(parse_gre(&f[..n]).unwrap().1, 8); - // K+S: 4 + 4 + 4 = 12 - let (f, n) = frame(GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT, &[0u8; 8]); - assert_eq!(parse_gre(&f[..n]).unwrap().1, 12); - // C+K+S: 4 + 4 + 4 + 4 = 16 - let (f, n) = frame( - GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT, - &[0u8; 12], - ); - assert_eq!(parse_gre(&f[..n]).unwrap().1, 16); - } - // Truncated optional fields must be rejected before any read. #[test] fn parse_rejects_truncated_optional_field() { @@ -863,43 +863,211 @@ mod tests { assert!(parse_gre(&f).is_err()); } - // Version != 0 must be rejected. + // RFC 2784 §2.3: Reserved0 bits 6-12 (0x03f8) MUST be ignored on receipt, + // not rejected. Each such bit alone, and all of them together, must parse. + #[test] + fn parse_ignores_reserved0_bits_6_to_12() { + for fv in [0x0200u16, 0x0008u16, 0x03f8u16] { + let (f, n) = frame(fv, &[0x45, 0x00]); + let (hdr, off) = parse_gre(&f[..n]).unwrap(); + assert_eq!(off, 4, "ignored bits must not shift payload offset"); + assert_eq!(hdr.protocol_type, IPV4_PROTO); + } + } + + // RFC 2784 §2.3 receive-discard bits: bit 1 (0x4000), bit 4 (0x0800, + // strict source route), bit 5 (0x0400), and their union (0x4c00) each + // require the packet to be discarded without RFC 1701 support. + #[test] + fn parse_rejects_each_discard_bit() { + for fv in [0x4000u16, 0x0800u16, 0x0400u16, 0x4c00u16] { + let (f, n) = frame(fv, &[0u8; 0]); + assert!(parse_gre(&f[..n]).is_err(), "discard bit must be rejected"); + } + } + + // Every nonzero GRE version (1..=7) must be rejected. + #[test] + fn parse_rejects_all_nonzero_versions() { + for ver in 1u16..=7 { + let (f, n) = frame(ver, &[0u8; 0]); + assert!(parse_gre(&f[..n]).is_err(), "nonzero version must reject"); + } + } + + // All eight C/K/S layouts must parse with the RFC-correct payload offset. + #[test] + fn parse_cks_layouts_have_correct_offsets() { + let c = GreFlags::CHECKSUM_BIT; + let k = GreFlags::KEY_BIT; + let s = GreFlags::SEQUENCE_BIT; + let cases: [(u16, usize); 8] = [ + (0, 4), + (c, 8), + (k, 8), + (s, 8), + (c | k, 12), + (c | s, 12), + (k | s, 12), + (c | k | s, 16), + ]; + for (fv, expected_off) in cases { + let (f, n) = frame(fv, &[0u8; 12]); + let (_hdr, off) = parse_gre(&f[..n]).unwrap(); + assert_eq!(off, expected_off, "offset for flags {fv:#06x}"); + } + } + + /// Compute the RFC 2784 checksum over `packet` with its checksum field + /// (bytes 4-5) treated as zero — an independent reference builder so the + /// checksum tests below are not tautological against the parser's own path. + fn build_gre_cksum(packet: &[u8]) -> u16 { + let mut sum: u32 = 0; + let mut i = 0; + while i + 1 < packet.len() { + let word = if i == 4 { + 0 + } else { + u16::from_be_bytes([packet[i], packet[i + 1]]) + }; + sum = sum.wrapping_add(u32::from(word)); + i += 2; + } + if i < packet.len() { + sum = sum.wrapping_add(u32::from(packet[i]) << 8); + } + while (sum >> 16) != 0 { + sum = (sum & 0xFFFF) + (sum >> 16); + } + !(sum as u16) + } + + /// Build a C-flag GRE packet: flags=0x8000, proto=IPv4, `checksum`, + /// reserved1, then `payload`. Length is header (8) + payload. + fn c_frame(checksum: u16, reserved1: u16, payload: &[u8]) -> ([u8; 64], usize) { + let mut f = [0u8; 64]; + f[0..2].copy_from_slice(&GreFlags::CHECKSUM_BIT.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + f[4..6].copy_from_slice(&checksum.to_be_bytes()); + f[6..8].copy_from_slice(&reserved1.to_be_bytes()); + f[8..8 + payload.len()].copy_from_slice(payload); + (f, 8 + payload.len()) + } + + // The validator must accept all eight C/K/S layouts. C-clear cases skip + // checksum verification; each C-set case gets a real checksum computed + // over its full optional-field layout and written at bytes 4-5, so the + // C path is exercised end-to-end (not merely the C=0 skip). + #[test] + fn validate_accepts_all_cks_layouts() { + let c = GreFlags::CHECKSUM_BIT; + let k = GreFlags::KEY_BIT; + let s = GreFlags::SEQUENCE_BIT; + let cases: [(u16, usize); 8] = [ + (0, 4), + (c, 8), + (k, 8), + (s, 8), + (c | k, 12), + (c | s, 12), + (k | s, 12), + (c | k | s, 16), + ]; + for (fv, expected_off) in cases { + let mut f = [0u8; 64]; + f[0..2].copy_from_slice(&fv.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + let n = expected_off + 2; + f[expected_off..n].copy_from_slice(&[0x45, 0x00]); + if (fv & c) != 0 { + let ck = build_gre_cksum(&f[..n]); + f[4..6].copy_from_slice(&ck.to_be_bytes()); + } + let (_hdr, off) = validate_gre_packet(&f[..n]).unwrap(); + assert_eq!(off, expected_off, "offset for flags {fv:#06x}"); + } + } + + // A C-set packet whose checksum verifies must be accepted; the pinned + // 0x32ff / 0x77ff constants match an independent builder (non-tautological). + #[test] + fn validate_accepts_valid_checksum() { + let (f, n) = c_frame(0x32ff, 0x0000, &[0x45, 0x00]); + assert_eq!(build_gre_cksum(&f[..n]), 0x32ff); + let (hdr, off) = validate_gre_packet(&f[..n]).unwrap(); + assert_eq!(off, 8); + assert_eq!(hdr.checksum, 0x32ff); + + // C-only header-only (no payload) still has a defined checksum 0x77ff. + let (f, n) = c_frame(0x77ff, 0x0000, &[]); + assert_eq!(build_gre_cksum(&f[..n]), 0x77ff); + assert_eq!(validate_gre_packet(&f[..n]).unwrap().1, 8); + } + + // A single-bit checksum corruption (0x32ff -> 0x32fe) must be rejected. + #[test] + fn validate_rejects_corrupt_checksum() { + let (f, n) = c_frame(0x32fe, 0x0000, &[0x45, 0x00]); + assert!(validate_gre_packet(&f[..n]).is_err()); + } + + // An odd-length payload ([0x45]) is right-padded with zero per RFC 1071, + // yielding the same 0x32ff checksum as the even [0x45,0x00] case. + #[test] + fn validate_accepts_odd_length_payload() { + let (f, n) = c_frame(0x32ff, 0x0000, &[0x45]); + assert_eq!(build_gre_cksum(&f[..n]), 0x32ff); + assert_eq!(validate_gre_packet(&f[..n]).unwrap().1, 8); + } + + // A base (C-clear) header-only packet is structurally valid to the generic + // validator: no payload requirement, no checksum to verify. + #[test] + fn validate_accepts_base_header_only() { + let (f, n) = frame(0x0000, &[]); + let (_hdr, off) = validate_gre_packet(&f[..n]).unwrap(); + assert_eq!(off, 4); + } + + // C=0 must skip checksum verification entirely: a garbage checksum-field + // value is irrelevant because the C-clear frame carries no checksum word. #[test] - fn parse_rejects_nonzero_version() { - let (f, n) = frame(0x0001, &[0u8; 0]); // version = 1 - assert!(parse_gre(&f[..n]).is_err()); + fn validate_c_clear_skips_checksum() { + let (f, n) = frame(0x0000, &[0xFF, 0xFF]); + assert!(validate_gre_packet(&f[..n]).is_ok()); } - // SECURITY (RFC 2784 §2.3): reserved/unknown flag bits must be rejected, - // not silently accepted. A bit set in the Reserved0 region (bits 3-11) - // indicates a non-conformant or RFC 1701-era packet this parser does not - // implement; accepting it would mis-align the payload offset. + // Structural errors from parse_gre propagate through the validator: + // truncated optional field and nonzero version. #[test] - fn parse_rejects_reserved_flag_bits() { - // Bit 11 (a Reserved0 bit, not C/K/S/version) set. - let (f, n) = frame(1 << 11, &[0u8; 0]); - assert!( - parse_gre(&f[..n]).is_err(), - "reserved flag bit must be rejected" - ); + fn validate_propagates_structural_errors() { + let mut trunc = [0u8; 6]; + trunc[0..2].copy_from_slice(&GreFlags::KEY_BIT.to_be_bytes()); + trunc[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + assert!(validate_gre_packet(&trunc).is_err()); + + let (f, n) = frame(0x0001, &[0u8; 0]); + assert!(validate_gre_packet(&f[..n]).is_err()); } - // RFC 1701 Routing Present (bit 14 in this layout) is deprecated and not - // implemented; it must be rejected, not skipped with a guessed length. + // RFC 2784 mandates Reserved1 transmit-zero but NOT receiver discard: a + // nonzero Reserved1 must be accepted when it is covered by a valid + // checksum (0x20cb over reserved1=0x1234 + [0x45,0x00]). #[test] - fn parse_rejects_rfc1701_routing_bit() { - let (f, n) = frame(1 << 14, &[0u8; 0]); - assert!( - parse_gre(&f[..n]).is_err(), - "RFC 1701 routing bit must be rejected" - ); + fn validate_accepts_nonzero_reserved1() { + let (f, n) = c_frame(0x20cb, 0x1234, &[0x45, 0x00]); + assert_eq!(build_gre_cksum(&f[..n]), 0x20cb); + assert!(validate_gre_packet(&f[..n]).is_ok()); } - // A valid header with only C/K/S/version bits must still parse (the - // reserved-bit gate must not over-reject). + // decapsulate_depth requires payload even though the generic validator + // accepts header-only framing: a C-clear header-only packet validates + // structurally but is rejected by tunnel decapsulation. #[test] - fn parse_accepts_valid_flag_combination() { - let (f, n) = frame(GreFlags::KEY_BIT, &[0u8; 4]); - assert!(parse_gre(&f[..n]).is_ok(), "valid flags must parse"); + fn decapsulate_rejects_header_only_packet() { + let (f, n) = frame(0x0000, &[]); + assert!(validate_gre_packet(&f[..n]).is_ok()); + let tunnel = GreTunnel::new(1, 0, 0, None); + assert!(tunnel.decapsulate_depth(&f[..n], MAX_ENCAP_LIMIT).is_err()); } } From e25bd10eead54a100252da46235b129bf687505f Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 17:17:14 +0900 Subject: [PATCH 3/6] fix(kernel): harden GRE IPv4 admission --- crates/kernel/src/net.rs | 259 ++++++++++++++++++++++++--------------- 1 file changed, 163 insertions(+), 96 deletions(-) diff --git a/crates/kernel/src/net.rs b/crates/kernel/src/net.rs index d15492c3..48b97a52 100644 --- a/crates/kernel/src/net.rs +++ b/crates/kernel/src/net.rs @@ -405,8 +405,10 @@ impl Ipv4Header { /// # Errors /// /// - [`Error::InvalidArgument`] if `data` is shorter than the -/// minimum IPv4 header (20 bytes), the version is not 4, or the -/// IHL-declared length exceeds the available data. +/// minimum IPv4 header (20 bytes), the version is not 4, the +/// IHL-declared header length exceeds the available data, or the +/// declared `total_len` is below the header length or beyond the +/// available data. pub fn parse_ipv4(data: &[u8]) -> Result<(Ipv4Header, &[u8])> { if data.len() < IPV4_HEADER_MIN_LEN { return Err(Error::InvalidArgument); @@ -437,19 +439,16 @@ pub fn parse_ipv4(data: &[u8]) -> Result<(Ipv4Header, &[u8])> { dst_addr: [data[16], data[17], data[18], data[19]], }; - // Determine actual payload range. A crafted frame can carry a - // `total_len` smaller than the header it declares (large IHL plus a - // tiny non-zero `total_len`); clamping must keep - // `hdr_len <= payload_end <= data.len()` so the slice below never has - // start > end (which would panic). + // SECURITY: `total_len` is attacker-controlled. Reject a datagram that + // declares a length below its own header or beyond the received frame + // rather than clamping, so bytes outside the declared datagram (e.g. + // trailing Ethernet padding) can never reach protocol dispatch. let total = header.total_len as usize; - let payload_end = if total >= hdr_len && total <= data.len() { - total - } else { - data.len() - }; + if total < hdr_len || total > data.len() { + return Err(Error::InvalidArgument); + } - Ok((header, &data[hdr_len..payload_end])) + Ok((header, &data[hdr_len..total])) } /// Compute the RFC 1071 internet checksum over `header` bytes. @@ -808,9 +807,14 @@ impl NetworkStack { /// Handle an incoming IPv4 packet. /// - /// Currently only ICMP echo requests are processed. Returns - /// the total reply frame length (Ethernet + IP + ICMP), or 0 - /// if the packet was consumed silently. + /// Dispatches by IP protocol after verifying the IPv4 header checksum and + /// that the datagram is addressed to us: ICMP echo requests are answered + /// (returning the reply frame length), UDP datagrams pass a checksum and + /// per-port framing admission gate, and GRE (protocol 47) is validated + /// structurally with C-bit checksum verification. Only ICMP produces a + /// reply; UDP and GRE are consumed and return `Ok(0)`, which also covers + /// every silently dropped malformed frame. Any other protocol returns + /// [`Error::NotImplemented`]. fn handle_ipv4( &mut self, eth: &EtherHeader, @@ -845,7 +849,10 @@ impl NetworkStack { match ip_hdr.protocol { PROTO_ICMP => self.handle_icmp_packet(eth, &ip_hdr, ip_payload, reply_buf), PROTO_UDP => self.handle_udp_packet(&ip_hdr, ip_payload), - PROTO_GRE => self.handle_gre_packet(&ip_hdr, ip_payload), + PROTO_GRE => { + let _ = self.handle_gre_packet(ip_payload); + Ok(0) + } _ => Err(Error::NotImplemented), } } @@ -884,6 +891,29 @@ impl NetworkStack { Ok(offset) } + /// Handle an incoming GRE packet (IP protocol 47, RFC 2784). + /// + /// Admission gate only: run the shared [`crate::gre::validate_gre_packet`], + /// which structurally parses the GRE header (base + C/K/S optional fields, + /// version 0, RFC 2784 §2.3 discard mask) and, when the C bit is set, + /// verifies the whole-packet RFC 1071 checksum. A header-only GRE frame is + /// valid framing. No tunnel decapsulation or inner-packet dispatch is + /// performed here — that requires a tunnel table and is a separate concern. + /// + /// Returns `Ok(())` on a validated frame. The caller ([`handle_ipv4`]) + /// maps both this success and any validation error to the `Ok(0)` boundary + /// contract so a malformed frame is dropped silently, never surfaced. + /// + /// # Errors + /// + /// Propagates [`Error::InvalidArgument`] from + /// [`crate::gre::validate_gre_packet`] for a malformed header or a C-bit + /// checksum that does not verify. + fn handle_gre_packet(&self, gre_payload: &[u8]) -> Result<()> { + crate::gre::validate_gre_packet(gre_payload)?; + Ok(()) + } + /// Validate an incoming UDP datagram before delivery. /// /// Re-parses the datagram so the on-wire UDP `length` field — not @@ -905,22 +935,6 @@ impl NetworkStack { /// [`crate::udp::parse_udp_datagram`] for a malformed length field, /// and from [`crate::udp::verify_udp_checksum`] for a datagram whose /// non-zero checksum does not verify. - /// Handle an incoming GRE packet (IP protocol 47, RFC 2784). - /// - /// Framing validation only: parse the GRE header (base + C/K/S optional - /// fields) and drop malformed frames silently via `Ok(0)`. GRE has no - /// length field — the payload extent is the enclosing IPv4 payload, whose - /// bounds `parse_ipv4` already enforced — so `parse_gre` only needs to - /// validate the header shape and optional-field offsets. No tunnel - /// decapsulation or inner-packet dispatch is performed here; that requires - /// a tunnel table and is a separate concern. - fn handle_gre_packet(&self, _ip_hdr: &Ipv4Header, gre_payload: &[u8]) -> Result { - if crate::gre::parse_gre(gre_payload).is_err() { - return Ok(0); - } - Ok(0) - } - fn handle_udp_packet(&self, ip_hdr: &Ipv4Header, udp_payload: &[u8]) -> Result { // The UDP length field is authoritative; `datagram` is trimmed // to exactly that length so the checksum covers no trailing @@ -1208,6 +1222,52 @@ mod tests { assert!(parse_ipv4(&pkt).is_err()); } + #[test] + fn test_parse_ipv4_rejects_total_len_below_header() { + // IHL=5 (hdr_len=20) but total_len=19 (< hdr_len): fail closed. + #[rustfmt::skip] + let pkt: [u8; 20] = [ + 0x45, 0x00, 0x00, 0x13, // ver/ihl, tos, len=19 + 0x00, 0x01, 0x00, 0x00, // id, flags/frag + 0x40, 0x01, 0x00, 0x00, // ttl=64, proto=ICMP + 0x0A, 0x00, 0x00, 0x01, // src 10.0.0.1 + 0x0A, 0x00, 0x00, 0x02, // dst 10.0.0.2 + ]; + assert_eq!(parse_ipv4(&pkt), Err(Error::InvalidArgument)); + } + + #[test] + fn test_parse_ipv4_rejects_total_len_beyond_data() { + // total_len=40 declared but only 24 bytes of frame available. + #[rustfmt::skip] + let pkt: [u8; 24] = [ + 0x45, 0x00, 0x00, 0x28, // ver/ihl, tos, len=40 + 0x00, 0x01, 0x00, 0x00, // id, flags/frag + 0x40, 0x01, 0x00, 0x00, // ttl=64, proto=ICMP + 0x0A, 0x00, 0x00, 0x01, // src 10.0.0.1 + 0x0A, 0x00, 0x00, 0x02, // dst 10.0.0.2 + 0xDE, 0xAD, 0xBE, 0xEF, // payload + ]; + assert_eq!(parse_ipv4(&pkt), Err(Error::InvalidArgument)); + } + + #[test] + fn test_parse_ipv4_slices_payload_to_total_len() { + // total_len=22 (20 hdr + 2 payload); frame has 2 trailing bytes of + // Ethernet padding that must be excluded from the payload slice. + #[rustfmt::skip] + let pkt: [u8; 24] = [ + 0x45, 0x00, 0x00, 0x16, // ver/ihl, tos, len=22 + 0x00, 0x01, 0x00, 0x00, // id, flags/frag + 0x40, 0x01, 0x00, 0x00, // ttl=64, proto=ICMP + 0x0A, 0x00, 0x00, 0x01, // src 10.0.0.1 + 0x0A, 0x00, 0x00, 0x02, // dst 10.0.0.2 + 0xDE, 0xAD, 0x00, 0x00, // 2 payload bytes + 2 padding bytes + ]; + let (_hdr, payload) = parse_ipv4(&pkt).unwrap(); + assert_eq!(payload, &[0xDE, 0xAD]); + } + #[test] fn test_icmp_echo_reply() { let ip_hdr = Ipv4Header { @@ -1551,83 +1611,90 @@ mod tests { p_off + payload.len() } - /// Build a GRE header (flags word + protocol type) + inner payload. - fn gre_bytes(flags_version: u16, proto: u16, inner: &[u8], out: &mut [u8]) -> usize { - out[0..2].copy_from_slice(&flags_version.to_be_bytes()); - out[2..4].copy_from_slice(&proto.to_be_bytes()); - out[4..4 + inner.len()].copy_from_slice(inner); - 4 + inner.len() + /// A network stack instance for direct handler-method tests. + fn gre_stack() -> NetworkStack { + NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]) } - // A structurally valid GRE packet (base header, no optional fields) must - // be admitted (consumed, Ok(0)) — the gate must not reject real GRE. + // Direct handler call: a C-only GRE frame with a valid whole-packet + // checksum (0x32ff over flags=0x8000, proto=IPv4, reserved1=0, payload + // [0x45,0x00]) validates, so the handler returns Ok(()). #[test] - fn gre_valid_base_header_accepted() { - let mut stack = - NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); - let mut gre = [0u8; 64]; - let glen = gre_bytes(0x0000, 0x0800, &[0x45, 0x00, 0x00, 0x14], &mut gre); - let mut frame = [0u8; 128]; - let n = build_ip_proto_frame( - [10, 0, 0, 1], - [10, 0, 0, 2], - PROTO_GRE, - &gre[..glen], - &mut frame, + fn gre_handler_accepts_valid_checksum() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xff, 0x00, 0x00, 0x45, 0x00]; + assert_eq!(gre_stack().handle_gre_packet(&gre), Ok(())); + } + + // Direct handler call: a corrupt checksum (0x32fe) fails validation, so the + // handler propagates Err(InvalidArgument) — proving rejection at the source + // rather than relying on the Ok(0) boundary mapping. + #[test] + fn gre_handler_rejects_corrupt_checksum() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xfe, 0x00, 0x00, 0x45, 0x00]; + assert_eq!( + gre_stack().handle_gre_packet(&gre), + Err(Error::InvalidArgument) ); - let mut reply = [0u8; 128]; - let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); - assert_eq!(r, 0, "valid GRE must be consumed, not error"); } - // A GRE packet with a reserved/deprecated flag bit set must be dropped - // silently by the admission gate, not surfaced as an error. + // Direct handler call: RFC 2784 §2.3 ignored Reserved0 bit 6 (0x0200) is + // admitted by the validator, so the handler returns Ok(()). #[test] - fn gre_reserved_flag_dropped_not_error() { - let mut stack = - NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); - let mut gre = [0u8; 64]; - // Bit 11 = a Reserved0 bit, rejected by the supported-bits mask. - let glen = gre_bytes(1 << 11, 0x0800, &[0x45, 0x00, 0x00, 0x14], &mut gre); - let mut frame = [0u8; 128]; - let n = build_ip_proto_frame( - [10, 0, 0, 1], - [10, 0, 0, 2], - PROTO_GRE, - &gre[..glen], - &mut frame, + fn gre_handler_accepts_ignored_reserved0_bit() { + let gre = [0x02u8, 0x00, 0x08, 0x00, 0x45, 0x00]; + assert_eq!(gre_stack().handle_gre_packet(&gre), Ok(())); + } + + // Direct handler call: RFC 2784 §2.3 discard bit 4 / strict-source-route + // (0x0800) is rejected by the validator, so the handler returns + // Err(InvalidArgument). + #[test] + fn gre_handler_rejects_discard_bit() { + let gre = [0x08u8, 0x00, 0x08, 0x00, 0x45, 0x00]; + assert_eq!( + gre_stack().handle_gre_packet(&gre), + Err(Error::InvalidArgument) ); - let mut reply = [0u8; 128]; - let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); - assert_eq!(r, 0, "reserved-flag GRE must be dropped (Ok(0)), not error"); } - // A GRE packet with K+S optional fields must parse the correct offset and - // be admitted — optional-field flags are valid framing. + // End-to-end dispatch: an unsupported IP protocol (99) returns + // NotImplemented, while a byte-identical payload carried as PROTO_GRE (47) + // is routed to the GRE gate and consumed (Ok(0)). The differing outcomes + // prove protocol 47 reaches handle_gre_packet, not the fallthrough arm. #[test] - fn gre_key_sequence_optional_fields_accepted() { - let mut stack = - NetworkStack::new([0xAA; 6], [10, 0, 0, 2], [10, 0, 0, 1], [255, 255, 255, 0]); - // flags_version with K (bit 13) + S (bit 12) set; 4+4 optional bytes. - let mut gre = [0u8; 64]; - let flags: u16 = (1 << 13) | (1 << 12); - gre[0..2].copy_from_slice(&flags.to_be_bytes()); - gre[2..4].copy_from_slice(&0x0800u16.to_be_bytes()); - // key(4) + sequence(4) + a little inner payload. - gre[4..8].copy_from_slice(&0xDEADBEEFu32.to_be_bytes()); - gre[8..12].copy_from_slice(&1u32.to_be_bytes()); - gre[12] = 0x45; + fn gre_protocol_dispatched_distinctly_from_unsupported() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xff, 0x00, 0x00, 0x45, 0x00]; let mut frame = [0u8; 128]; - let n = build_ip_proto_frame( - [10, 0, 0, 1], - [10, 0, 0, 2], - PROTO_GRE, - &gre[..13], - &mut frame, + let mut reply = [0u8; 128]; + + let mut stack = gre_stack(); + let n = build_ip_proto_frame([10, 0, 0, 1], [10, 0, 0, 2], 99, &gre, &mut frame); + assert_eq!( + stack.process_packet(&frame[..n], &mut reply), + Err(Error::NotImplemented), + "protocol 99 must hit the unsupported arm" + ); + + let mut stack = gre_stack(); + let n = build_ip_proto_frame([10, 0, 0, 1], [10, 0, 0, 2], PROTO_GRE, &gre, &mut frame); + assert_eq!( + stack.process_packet(&frame[..n], &mut reply), + Ok(0), + "PROTO_GRE must be dispatched to the gate and consumed" ); + } + + // End-to-end boundary contract: a malformed GRE frame (corrupt checksum) + // whose handler returns Err is mapped by handle_ipv4 to Ok(0), so the + // public boundary drops it silently and never surfaces the error. + #[test] + fn gre_malformed_frame_dropped_at_boundary() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xfe, 0x00, 0x00, 0x45, 0x00]; + let mut stack = gre_stack(); + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame([10, 0, 0, 1], [10, 0, 0, 2], PROTO_GRE, &gre, &mut frame); let mut reply = [0u8; 128]; - let r = stack.process_packet(&frame[..n], &mut reply).ok().unwrap(); - assert_eq!(r, 0, "K+S GRE must be consumed, not error"); + assert_eq!(stack.process_packet(&frame[..n], &mut reply), Ok(0)); } // A structurally valid DNS query on port 53 must be admitted (consumed, From c9e7766d44be7a50b45925247549a44e546b99ab Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 18:44:20 +0900 Subject: [PATCH 4/6] test(kernel): cover GRE key/sequence checksums --- crates/kernel/src/gre.rs | 69 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/crates/kernel/src/gre.rs b/crates/kernel/src/gre.rs index ece0201a..35b6db41 100644 --- a/crates/kernel/src/gre.rs +++ b/crates/kernel/src/gre.rs @@ -1011,6 +1011,75 @@ mod tests { assert!(validate_gre_packet(&f[..n]).is_err()); } + /// Build a C|K GRE packet: flags=0xA000, proto=IPv4, `checksum`, reserved1, + /// key=0xDEADBEEF, then `payload`. Length is header (12) + payload. + fn ck_frame(checksum: u16, payload: &[u8]) -> ([u8; 64], usize) { + let mut f = [0u8; 64]; + let flags = GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT; + f[0..2].copy_from_slice(&flags.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + f[4..6].copy_from_slice(&checksum.to_be_bytes()); + f[8..12].copy_from_slice(&0xDEAD_BEEFu32.to_be_bytes()); + f[12..12 + payload.len()].copy_from_slice(payload); + (f, 12 + payload.len()) + } + + /// Build a C|K|S GRE packet: flags=0xB000, proto=IPv4, `checksum`, + /// reserved1, key=0xDEADBEEF, sequence=1, then `payload`. Length is header + /// (16) + payload. + fn cks_frame(checksum: u16, payload: &[u8]) -> ([u8; 64], usize) { + let mut f = [0u8; 64]; + let flags = GreFlags::CHECKSUM_BIT | GreFlags::KEY_BIT | GreFlags::SEQUENCE_BIT; + f[0..2].copy_from_slice(&flags.to_be_bytes()); + f[2..4].copy_from_slice(&IPV4_PROTO.to_be_bytes()); + f[4..6].copy_from_slice(&checksum.to_be_bytes()); + f[8..12].copy_from_slice(&0xDEAD_BEEFu32.to_be_bytes()); + f[12..16].copy_from_slice(&1u32.to_be_bytes()); + f[16..16 + payload.len()].copy_from_slice(payload); + (f, 16 + payload.len()) + } + + // A C|K frame with nonzero key 0xDEADBEEF and a checksum covering the key + // must verify. The pinned 0x7561 matches build_gre_cksum (non-tautological), + // and the payload offset is 12 (base 4 + checksum 4 + key 4). + #[test] + fn validate_accepts_ck_valid_checksum() { + let (f, n) = ck_frame(0x7561, &[0x45, 0x00]); + assert_eq!(build_gre_cksum(&f[..n]), 0x7561); + let (hdr, off) = validate_gre_packet(&f[..n]).unwrap(); + assert_eq!(off, 12); + assert_eq!(hdr.key, 0xDEAD_BEEF); + } + + // A single-bit checksum corruption (0x7561 -> 0x7562) on the C|K frame must + // be rejected, proving the checksum covers the key field. + #[test] + fn validate_rejects_ck_corrupt_checksum() { + let (f, n) = ck_frame(0x7562, &[0x45, 0x00]); + assert!(validate_gre_packet(&f[..n]).is_err()); + } + + // A C|K|S frame with nonzero key 0xDEADBEEF and sequence 1 and a checksum + // covering both must verify. The pinned 0x6560 matches build_gre_cksum, and + // the payload offset is 16 (base 4 + checksum 4 + key 4 + sequence 4). + #[test] + fn validate_accepts_cks_valid_checksum() { + let (f, n) = cks_frame(0x6560, &[0x45, 0x00]); + assert_eq!(build_gre_cksum(&f[..n]), 0x6560); + let (hdr, off) = validate_gre_packet(&f[..n]).unwrap(); + assert_eq!(off, 16); + assert_eq!(hdr.key, 0xDEAD_BEEF); + assert_eq!(hdr.sequence_number, 1); + } + + // A single-bit checksum corruption (0x6560 -> 0x6561) on the C|K|S frame + // must be rejected, proving the checksum covers the sequence field. + #[test] + fn validate_rejects_cks_corrupt_checksum() { + let (f, n) = cks_frame(0x6561, &[0x45, 0x00]); + assert!(validate_gre_packet(&f[..n]).is_err()); + } + // An odd-length payload ([0x45]) is right-padded with zero per RFC 1071, // yielding the same 0x32ff checksum as the even [0x45,0x00] case. #[test] From c46dde16a188cb29d003c107e1103fac18fbaa13 Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 18:44:37 +0900 Subject: [PATCH 5/6] fix(kernel): count GRE admission verdicts --- crates/kernel/src/net.rs | 54 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/crates/kernel/src/net.rs b/crates/kernel/src/net.rs index 48b97a52..ba6e7dc1 100644 --- a/crates/kernel/src/net.rs +++ b/crates/kernel/src/net.rs @@ -638,6 +638,10 @@ pub struct NetworkStack { pub arp_table: ArpTable, /// IPv6 stack and NDP neighbor cache. pub ipv6: Ipv6Stack, + /// Count of GRE frames admitted by [`crate::gre::validate_gre_packet`]. + gre_admitted: u64, + /// Count of GRE frames rejected by [`crate::gre::validate_gre_packet`]. + gre_dropped: u64, } impl NetworkStack { @@ -655,9 +659,21 @@ impl NetworkStack { subnet_mask: subnet, arp_table: ArpTable::new(), ipv6: Ipv6Stack::new(Ipv6Addr::link_local_from_mac(&mac), mac), + gre_admitted: 0, + gre_dropped: 0, } } + /// Number of GRE frames admitted by the protocol-47 admission gate. + pub const fn gre_admitted(&self) -> u64 { + self.gre_admitted + } + + /// Number of GRE frames dropped by the protocol-47 admission gate. + pub const fn gre_dropped(&self) -> u64 { + self.gre_dropped + } + /// Process an incoming Ethernet frame. /// /// Parses the Ethernet header and dispatches to the appropriate @@ -850,7 +866,10 @@ impl NetworkStack { PROTO_ICMP => self.handle_icmp_packet(eth, &ip_hdr, ip_payload, reply_buf), PROTO_UDP => self.handle_udp_packet(&ip_hdr, ip_payload), PROTO_GRE => { - let _ = self.handle_gre_packet(ip_payload); + match self.handle_gre_packet(ip_payload) { + Ok(()) => self.gre_admitted = self.gre_admitted.saturating_add(1), + Err(_) => self.gre_dropped = self.gre_dropped.saturating_add(1), + } Ok(0) } _ => Err(Error::NotImplemented), @@ -1697,6 +1716,39 @@ mod tests { assert_eq!(stack.process_packet(&frame[..n], &mut reply), Ok(0)); } + // Given a valid C-only GRE frame dispatched through the public boundary, + // When process_packet consumes it, + // Then only the admitted counter advances and dropped stays zero, proving + // validation has an observable effect on NetworkStack state. + #[test] + fn gre_valid_frame_increments_admitted_only() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xff, 0x00, 0x00, 0x45, 0x00]; + let mut stack = gre_stack(); + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame([10, 0, 0, 1], [10, 0, 0, 2], PROTO_GRE, &gre, &mut frame); + let mut reply = [0u8; 128]; + assert_eq!(stack.process_packet(&frame[..n], &mut reply), Ok(0)); + assert_eq!(stack.gre_admitted(), 1); + assert_eq!(stack.gre_dropped(), 0); + } + + // Given a corrupt-checksum GRE frame dispatched through the public boundary, + // When process_packet drops it, + // Then only the dropped counter advances and admitted stays zero. This + // fails if validate_gre_packet is bypassed, because a bypassed gate would + // admit the corrupt frame and increment admitted instead. + #[test] + fn gre_corrupt_frame_increments_dropped_only() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xfe, 0x00, 0x00, 0x45, 0x00]; + let mut stack = gre_stack(); + let mut frame = [0u8; 128]; + let n = build_ip_proto_frame([10, 0, 0, 1], [10, 0, 0, 2], PROTO_GRE, &gre, &mut frame); + let mut reply = [0u8; 128]; + assert_eq!(stack.process_packet(&frame[..n], &mut reply), Ok(0)); + assert_eq!(stack.gre_dropped(), 1); + assert_eq!(stack.gre_admitted(), 0); + } + // A structurally valid DNS query on port 53 must be admitted (consumed, // Ok(0)) — validation must not reject legitimate DNS traffic. #[test] From f765c58be870fbed4b3877ac83135062dd76cbcf Mon Sep 17 00:00:00 2001 From: kernalix7 Date: Sat, 15 Aug 2026 18:54:49 +0900 Subject: [PATCH 6/6] docs(kernel): correct GRE checksum comment --- crates/kernel/src/gre.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/kernel/src/gre.rs b/crates/kernel/src/gre.rs index 35b6db41..fd36efba 100644 --- a/crates/kernel/src/gre.rs +++ b/crates/kernel/src/gre.rs @@ -1051,8 +1051,8 @@ mod tests { assert_eq!(hdr.key, 0xDEAD_BEEF); } - // A single-bit checksum corruption (0x7561 -> 0x7562) on the C|K frame must - // be rejected, proving the checksum covers the key field. + // A checksum corruption (0x7561 -> 0x7562) on the C|K frame must be rejected, + // proving the checksum covers the key field. #[test] fn validate_rejects_ck_corrupt_checksum() { let (f, n) = ck_frame(0x7562, &[0x45, 0x00]);