Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 68 additions & 11 deletions crates/kernel/src/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
//! | L2.5 | ARP (IPv4/Ether) | Request + reply |
//! | L3 | IPv4 | Parse + checksum |
//! | L3 | ICMP | Echo reply (ping) |
//! | L4 | TCP | Stateless admit |
//! | L4 | UDP | Rx checksum check |
//!
//! TCP is planned for future implementation.

use crate::ipv6::{Ipv6Addr, Ipv6Stack, MAX_PKT_BUF};
use oncrix_lib::{Error, Result};
Expand Down Expand Up @@ -645,6 +644,10 @@ pub struct NetworkStack {
gre_admitted: u64,
/// Count of GRE frames rejected by [`crate::gre::validate_gre_packet`].
gre_dropped: u64,
/// Count of TCP segments admitted by the protocol-6 gate.
tcp_admitted: u64,
/// Count of TCP segments rejected by the protocol-6 gate.
tcp_dropped: u64,
/// Count of SCTP packets admitted by the protocol-132 gate.
sctp_admitted: u64,
/// Count of SCTP packets rejected by the protocol-132 gate.
Expand All @@ -668,6 +671,8 @@ impl NetworkStack {
ipv6: Ipv6Stack::new(Ipv6Addr::link_local_from_mac(&mac), mac),
gre_admitted: 0,
gre_dropped: 0,
tcp_admitted: 0,
tcp_dropped: 0,
sctp_admitted: 0,
sctp_dropped: 0,
}
Expand All @@ -683,6 +688,16 @@ impl NetworkStack {
self.gre_dropped
}

/// Number of TCP segments admitted by the protocol-6 gate.
pub const fn tcp_admitted(&self) -> u64 {
self.tcp_admitted
}

/// Number of TCP segments dropped by the protocol-6 gate.
pub const fn tcp_dropped(&self) -> u64 {
self.tcp_dropped
}

/// Number of SCTP packets admitted by the protocol-132 gate.
pub const fn sctp_admitted(&self) -> u64 {
self.sctp_admitted
Expand All @@ -696,16 +711,19 @@ impl NetworkStack {
/// Process an incoming Ethernet frame.
///
/// Parses the Ethernet header and dispatches to the appropriate
/// protocol handler (ARP or IPv4/ICMP). If a reply is
/// protocol handler (ARP, IPv4, or IPv6). If a reply is
/// generated it is written into `reply_buf` as a complete
/// Ethernet frame and the total frame length is returned.
///
/// Returns `Ok(0)` when the packet is consumed but no reply is
/// needed (e.g., an ARP reply that merely updates the cache).
/// needed. This includes stateless TCP, GRE, and SCTP admission
/// failures that are intentionally dropped silently.
///
/// # Errors
///
/// Propagates errors from the individual protocol parsers.
/// Returns an error when link or network-layer parsing fails, UDP
/// framing or checksum validation fails, a dispatched protocol is
/// unsupported, or a replying handler cannot encode its response.
pub fn process_packet(&mut self, data: &[u8], reply_buf: &mut [u8]) -> Result<usize> {
let (eth, payload) = parse_ether(data)?;

Expand Down Expand Up @@ -844,12 +862,14 @@ impl NetworkStack {
///
/// 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, GRE (protocol 47) is validated with
/// C-bit checksum verification, and SCTP (protocol 132) passes a stateless
/// CRC32c and chunk-chain gate. Only ICMP produces a reply; UDP, GRE, and
/// SCTP are consumed and return `Ok(0)`, including silently dropped
/// malformed frames. Any other protocol returns [`Error::NotImplemented`].
/// (returning the reply frame length), TCP segments pass a stateless
/// fragment, framing, and checksum admission gate, UDP datagrams pass a
/// checksum and per-port framing admission gate, GRE (protocol 47) is
/// validated with C-bit checksum verification, and SCTP (protocol 132)
/// passes a stateless CRC32c and chunk-chain gate. Only ICMP produces a
/// reply; TCP, UDP, GRE, and SCTP are consumed and return `Ok(0)`, including
/// silently dropped malformed frames. Any other protocol returns
/// [`Error::NotImplemented`].
fn handle_ipv4(
&mut self,
eth: &EtherHeader,
Expand Down Expand Up @@ -883,6 +903,13 @@ impl NetworkStack {

match ip_hdr.protocol {
PROTO_ICMP => self.handle_icmp_packet(eth, &ip_hdr, ip_payload, reply_buf),
PROTO_TCP => {
match self.handle_tcp_packet(&ip_hdr, ip_payload) {
Ok(()) => self.tcp_admitted = self.tcp_admitted.saturating_add(1),
Err(_) => self.tcp_dropped = self.tcp_dropped.saturating_add(1),
}
Ok(0)
}
PROTO_UDP => self.handle_udp_packet(&ip_hdr, ip_payload),
PROTO_GRE => {
match self.handle_gre_packet(ip_payload) {
Expand Down Expand Up @@ -959,6 +986,24 @@ impl NetworkStack {
Ok(())
}

/// Validate a TCP segment before protocol-6 admission.
///
/// This stack has no IPv4 reassembly, so MF or a nonzero fragment offset
/// is rejected locally. DF and the reserved IPv4 flag remain admissible.
///
/// # Errors
///
/// Returns [`Error::InvalidArgument`] for fragments, malformed TCP framing,
/// or an invalid IPv4 TCP checksum.
fn handle_tcp_packet(&self, ip_hdr: &Ipv4Header, segment: &[u8]) -> Result<()> {
if ip_hdr.flags_frag & 0x3FFF != 0 {
return Err(Error::InvalidArgument);
}
crate::tcp::parse_tcp(segment)?;
crate::tcp::verify_tcp_checksum(ip_hdr.src_addr, ip_hdr.dst_addr, segment)?;
Ok(())
}

/// Validate an SCTP packet before protocol-132 admission.
///
/// This stack has no IPv4 reassembly, so MF or a nonzero fragment offset
Expand Down Expand Up @@ -1092,6 +1137,18 @@ impl NetworkStack {
#[path = "net_sctp_tests.rs"]
mod sctp_tests;

#[cfg(test)]
#[path = "net_tcp_test_support.rs"]
mod net_tcp_test_support;

#[cfg(test)]
#[path = "net_tcp_tests.rs"]
mod tcp_tests;

#[cfg(test)]
#[path = "net_tcp_counter_tests.rs"]
mod tcp_counter_tests;

// =========================================================================
// Tests
// =========================================================================
Expand Down
133 changes: 133 additions & 0 deletions crates/kernel/src/net_tcp_counter_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2026 ONCRIX Contributors
// SPDX-License-Identifier: Apache-2.0

use super::net_tcp_test_support::*;
use super::*;

#[test]
fn tcp_valid_segment_increments_admitted_only() {
let segment = valid_tcp_segment();
let (frame, len) = ip_frame(PROTO_TCP, 0, &segment);
let mut stack = tcp_stack();
assert_eq!(stack.process_packet(&frame[..len], &mut [0u8; 128]), Ok(0));
assert_eq!(stack.tcp_admitted(), 1);
assert_eq!(stack.tcp_dropped(), 0);
}

#[test]
fn tcp_corrupt_segment_increments_dropped_only() {
let mut segment = valid_tcp_segment();
segment[4] ^= 1;
let (frame, len) = ip_frame(PROTO_TCP, 0, &segment);
let mut stack = tcp_stack();
assert_eq!(stack.process_packet(&frame[..len], &mut [0u8; 128]), Ok(0));
assert_eq!(stack.tcp_admitted(), 0);
assert_eq!(stack.tcp_dropped(), 1);
}

#[test]
fn tcp_fragment_increments_dropped_only() {
let segment = valid_tcp_segment();
let (frame, len) = ip_frame(PROTO_TCP, 0x2000, &segment);
let mut stack = tcp_stack();
assert_eq!(stack.process_packet(&frame[..len], &mut [0u8; 128]), Ok(0));
assert_eq!(stack.tcp_admitted(), 0);
assert_eq!(stack.tcp_dropped(), 1);
}

#[test]
fn tcp_counters_saturate() {
let valid = valid_tcp_segment();
let mut corrupt = valid;
corrupt[4] ^= 1;
let (valid_frame, valid_len) = ip_frame(PROTO_TCP, 0, &valid);
let (corrupt_frame, corrupt_len) = ip_frame(PROTO_TCP, 0, &corrupt);
let mut stack = tcp_stack();
stack.tcp_admitted = u64::MAX;
stack.tcp_dropped = u64::MAX;
assert_eq!(
stack.process_packet(&valid_frame[..valid_len], &mut [0u8; 128]),
Ok(0)
);
assert_eq!(
stack.process_packet(&corrupt_frame[..corrupt_len], &mut [0u8; 128]),
Ok(0)
);
assert_eq!(stack.tcp_admitted(), u64::MAX);
assert_eq!(stack.tcp_dropped(), u64::MAX);
}

#[test]
fn tcp_bad_ipv4_checksum_does_not_touch_counters() {
let segment = valid_tcp_segment();
let (mut frame, len) = ip_frame(PROTO_TCP, 0, &segment);
frame[ETHER_HEADER_LEN + 8] ^= 1;
let mut stack = tcp_stack();
assert_eq!(stack.process_packet(&frame[..len], &mut [0u8; 128]), Ok(0));
assert_eq!((stack.tcp_admitted(), stack.tcp_dropped()), (0, 0));
}

#[test]
fn tcp_wrong_destination_does_not_touch_counters() {
let segment = valid_tcp_segment();
let (mut frame, len) = ip_frame(PROTO_TCP, 0, &segment);
retarget_ipv4(&mut frame, [10, 0, 0, 9]);
let mut stack = tcp_stack();
assert_eq!(stack.process_packet(&frame[..len], &mut [0u8; 128]), Ok(0));
assert_eq!((stack.tcp_admitted(), stack.tcp_dropped()), (0, 0));
}

#[test]
fn tcp_ethernet_parse_error_does_not_touch_counters() {
let mut stack = tcp_stack();
assert_eq!(
stack.process_packet(&[0u8; 13], &mut [0u8; 128]),
Err(Error::InvalidArgument)
);
assert_eq!((stack.tcp_admitted(), stack.tcp_dropped()), (0, 0));
}

#[test]
fn tcp_ipv4_parse_error_does_not_touch_counters() {
let segment = valid_tcp_segment();
let (mut frame, len) = ip_frame(PROTO_TCP, 0, &segment);
frame[ETHER_HEADER_LEN] = 0x44;
let mut stack = tcp_stack();
assert_eq!(
stack.process_packet(&frame[..len], &mut [0u8; 128]),
Err(Error::InvalidArgument)
);
assert_eq!((stack.tcp_admitted(), stack.tcp_dropped()), (0, 0));
}

#[test]
fn tcp_unsupported_protocol_does_not_touch_counters() {
let segment = valid_tcp_segment();
let (frame, len) = ip_frame(99, 0, &segment);
let mut stack = tcp_stack();
assert_eq!(
stack.process_packet(&frame[..len], &mut [0u8; 128]),
Err(Error::NotImplemented)
);
assert_eq!((stack.tcp_admitted(), stack.tcp_dropped()), (0, 0));
}

#[test]
fn tcp_valid_then_invalid_update_independent_counters() {
let valid = valid_tcp_segment();
let mut corrupt = valid;
corrupt[4] ^= 1;
let (valid_frame, valid_len) = ip_frame(PROTO_TCP, 0, &valid);
let (corrupt_frame, corrupt_len) = ip_frame(PROTO_TCP, 0, &corrupt);
let mut stack = tcp_stack();
assert_eq!(
stack.process_packet(&valid_frame[..valid_len], &mut [0u8; 128]),
Ok(0)
);
assert_eq!(
stack.process_packet(&corrupt_frame[..corrupt_len], &mut [0u8; 128]),
Ok(0)
);
assert_eq!(stack.tcp_admitted(), 1);
assert_eq!(stack.tcp_dropped(), 1);
}
Loading