diff --git a/crates/kernel/src/gre.rs b/crates/kernel/src/gre.rs index 340294d..fd36efb 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,6 +269,19 @@ pub fn parse_gre(data: &[u8]) -> Result<(GreHeader, usize)> { return Err(Error::InvalidArgument); } + // 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); + } + let flags = GreFlags::from_bits(flags_version); let required_len = flags.header_len(); if data.len() < required_len { @@ -390,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). @@ -622,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 @@ -793,3 +823,320 @@ 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()); + } + + // 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()); + } + + // 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()); + } + + /// 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 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] + 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 validate_c_clear_skips_checksum() { + let (f, n) = frame(0x0000, &[0xFF, 0xFF]); + assert!(validate_gre_packet(&f[..n]).is_ok()); + } + + // Structural errors from parse_gre propagate through the validator: + // truncated optional field and nonzero version. + #[test] + 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 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 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()); + } + + // 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 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()); + } +} diff --git a/crates/kernel/src/net.rs b/crates/kernel/src/net.rs index 17ee405..ba6e7dc 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 @@ -402,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); @@ -434,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. @@ -636,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 { @@ -653,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 @@ -805,9 +823,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, @@ -842,6 +865,13 @@ 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 => { + 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), } } @@ -880,6 +910,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 @@ -1188,6 +1241,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 { @@ -1499,6 +1598,157 @@ 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() + } + + /// 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]) + } + + // 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_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) + ); + } + + // 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_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) + ); + } + + // 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_protocol_dispatched_distinctly_from_unsupported() { + let gre = [0x80u8, 0x00, 0x08, 0x00, 0x32, 0xff, 0x00, 0x00, 0x45, 0x00]; + let mut frame = [0u8; 128]; + 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]; + 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]