netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
//! Stateless TCP sequence number encoding.
//!
//! Encodes the full probe identity `(src_ip, dst_ip, dst_port, src_port, phase)`
//! into a 32-bit TCP sequence number using SipHash-2-4. When a SYN-ACK (or
//! data ACK) arrives, the `ack_num - 1` is verified against the hash to confirm
//! the packet belongs to our scan, with zero per-connection state.
//!
//! This is the same fundamental technique as masscan, but upgraded from a
//! weak hash to SipHash for cryptographic resistance against spoofed responses.

use std::hash::{Hash, Hasher};
use std::net::Ipv4Addr;

use siphasher::sip::SipHasher24;

/// Secret key for stateless cookie generation.
///
/// Initialized once per scan session from a CSPRNG. The key MUST be kept
/// secret; if an adversary learns it, they can forge valid SYN-ACK responses.
#[derive(Clone)]
pub struct StatelessCookie {
    key: u64,
}

impl StatelessCookie {
    /// Create a new cookie with a random secret.
    ///
    /// The key is drawn from the OS CSPRNG (`getrandom`). It must be
    /// unpredictable: `fastrand` is a fast non-cryptographic PRNG whose output
    /// an adversary can reconstruct, which would let them forge valid SYN-ACK
    /// cookies and defeat the SipHash anti-spoofing this module exists for.
    ///
    /// # Panics
    ///
    /// Panics only if the OS entropy source is unavailable (a broken system).
    /// Failing closed is correct: a predictable key silently weakens the
    /// anti-spoofing guarantee, which is worse than aborting.
    #[must_use]
    pub fn new() -> Self {
        let mut buf = [0u8; 8];
        getrandom::fill(&mut buf)
            .expect("OS CSPRNG (getrandom) must be available to seed the stateless cookie key");
        Self {
            key: u64::from_ne_bytes(buf),
        }
    }

    /// Create a cookie with a specific secret (for deterministic testing).
    #[must_use]
    pub const fn with_key(key: u64) -> Self {
        Self { key }
    }

    /// Get the secret key (for sharing between TX and RX threads).
    #[must_use]
    pub const fn key(&self) -> u64 {
        self.key
    }
}

impl Default for StatelessCookie {
    fn default() -> Self {
        Self::new()
    }
}

/// Encoder that generates and verifies stateless TCP sequence numbers.
///
/// # Phases
///
/// The `phase` parameter allows extending stateless encoding beyond SYN:
/// - Phase 0: SYN (initial probe)
/// - Phase 1: ACK + data (banner grab)
/// - Phase 2+: Follow-up probes
pub struct SeqEncoder {
    cookie: StatelessCookie,
}

impl SeqEncoder {
    /// Create a new encoder with a random secret.
    #[must_use]
    pub fn new() -> Self {
        Self {
            cookie: StatelessCookie::new(),
        }
    }

    /// Create an encoder with a specific cookie.
    #[must_use]
    pub const fn with_cookie(cookie: StatelessCookie) -> Self {
        Self { cookie }
    }

    /// Encode a probe identity into a TCP sequence number.
    ///
    /// The output is deterministic for the same inputs and secret, but
    /// unpredictable without the secret.
    #[inline]
    pub fn encode(
        &self,
        dst_ip: Ipv4Addr,
        dst_port: u16,
        src_port: u16,
        phase: u8,
    ) -> u32 {
        // Keyed SipHash-2-4: the secret is the PRF KEY (not hashed as input),
        // so this is a proper keyed MAC as the anti-spoofing model requires.
        // The previous std DefaultHasher was SipHash-1-3 (not the documented
        // 2-4), is unspecified/unstable across Rust releases, and its fixed
        // (0,0) key made "hash the secret as a prefix" a weaker construction.
        // The 64-bit secret keys both 128-bit key halves (64-bit effective
        // security = the secret's size; widening needs a wider StatelessCookie).
        let mut hasher = SipHasher24::new_with_keys(self.cookie.key, self.cookie.key);
        dst_ip.hash(&mut hasher);
        dst_port.hash(&mut hasher);
        src_port.hash(&mut hasher);
        phase.hash(&mut hasher);
        (hasher.finish() & 0xFFFF_FFFF) as u32
    }

    /// Verify that an incoming ACK belongs to our scan.
    ///
    /// For a SYN-ACK response: `ack_num` should equal `encode(..., phase=0) + 1`.
    /// Returns `true` if the packet is verified as ours.
    #[inline]
    pub fn verify_synack(
        &self,
        ack_num: u32,
        src_ip: Ipv4Addr,
        src_port: u16,
        our_dst_port: u16,
    ) -> bool {
        let expected = self.encode(src_ip, src_port, our_dst_port, 0);
        ack_num == expected.wrapping_add(1)
    }

    /// Verify a data ACK from a stateless banner grab.
    ///
    /// For phase 1 (banner grab): `ack_num` should equal
    /// `encode(..., phase=1) + payload_len`.
    #[inline]
    pub fn verify_data_ack(
        &self,
        ack_num: u32,
        src_ip: Ipv4Addr,
        src_port: u16,
        our_dst_port: u16,
        payload_len: u32,
    ) -> bool {
        let expected = self.encode(src_ip, src_port, our_dst_port, 1);
        ack_num == expected.wrapping_add(payload_len)
    }

    /// Get the underlying cookie (for sharing with RX thread).
    #[must_use]
    pub const fn cookie(&self) -> &StatelessCookie {
        &self.cookie
    }
}

impl Default for SeqEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encode_is_deterministic() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        let s1 = enc.encode(ip, 80, 49152, 0);
        let s2 = enc.encode(ip, 80, 49152, 0);
        assert_eq!(s1, s2);
    }

    #[test]
    fn fresh_cookie_keys_are_random_not_constant() {
        // Regression guard: the secret key must come from the OS CSPRNG, so
        // independent cookies must not collide. A constant/degenerate source
        // (or reverting to a predictable seed) would produce repeats.
        const N: usize = 256;
        let keys: std::collections::HashSet<u64> =
            (0..N).map(|_| StatelessCookie::new().key()).collect();
        assert_eq!(
            keys.len(),
            N,
            "all {N} fresh cookie keys must be distinct; a collision means the key source is not random"
        );
        // No fresh key should equal the all-zero degenerate value in practice.
        assert!(!keys.contains(&0), "a fresh key of 0 indicates a broken RNG source");
    }

    #[test]
    fn encode_differs_by_target() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip_a = Ipv4Addr::new(1, 2, 3, 4);
        let ip_b = Ipv4Addr::new(5, 6, 7, 8);
        assert_ne!(
            enc.encode(ip_a, 80, 49152, 0),
            enc.encode(ip_b, 80, 49152, 0),
        );
    }

    #[test]
    fn encode_differs_by_port() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        assert_ne!(
            enc.encode(ip, 80, 49152, 0),
            enc.encode(ip, 443, 49152, 0),
        );
    }

    #[test]
    fn encode_differs_by_phase() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        assert_ne!(
            enc.encode(ip, 80, 49152, 0),
            enc.encode(ip, 80, 49152, 1),
        );
    }

    #[test]
    fn encode_differs_by_key() {
        let enc_a = SeqEncoder::with_cookie(StatelessCookie::with_key(1));
        let enc_b = SeqEncoder::with_cookie(StatelessCookie::with_key(2));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        assert_ne!(
            enc_a.encode(ip, 80, 49152, 0),
            enc_b.encode(ip, 80, 49152, 0),
        );
    }

    #[test]
    fn verify_synack_accepts_valid() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        let seq = enc.encode(ip, 80, 49152, 0);
        let ack = seq.wrapping_add(1);
        assert!(enc.verify_synack(ack, ip, 80, 49152));
    }

    #[test]
    fn verify_synack_rejects_invalid() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        // Random ack number  -  not from our scan
        assert!(!enc.verify_synack(0xDEADBEEF, ip, 80, 49152));
    }

    #[test]
    fn verify_synack_rejects_wrong_target() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip_a = Ipv4Addr::new(1, 2, 3, 4);
        let ip_b = Ipv4Addr::new(5, 6, 7, 8);
        let seq = enc.encode(ip_a, 80, 49152, 0);
        let ack = seq.wrapping_add(1);
        // Valid ack for ip_a, but claiming to be from ip_b
        assert!(!enc.verify_synack(ack, ip_b, 80, 49152));
    }

    #[test]
    fn verify_data_ack_works() {
        let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(42));
        let ip = Ipv4Addr::new(1, 2, 3, 4);
        let seq = enc.encode(ip, 80, 49152, 1);
        let payload_len = 100u32;
        let ack = seq.wrapping_add(payload_len);
        assert!(enc.verify_data_ack(ack, ip, 80, 49152, payload_len));
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn encode_roundtrips(
            a in any::<u8>(), b in any::<u8>(), c in any::<u8>(), d in any::<u8>(),
            port in any::<u16>(),
            src_port in any::<u16>(),
            phase in 0u8..4,
            key in any::<u64>(),
        ) {
            let enc = SeqEncoder::with_cookie(StatelessCookie::with_key(key));
            let ip = Ipv4Addr::new(a, b, c, d);
            let seq = enc.encode(ip, port, src_port, phase);

            // Deterministic
            prop_assert_eq!(seq, enc.encode(ip, port, src_port, phase));

            // SYN-ACK verify roundtrip (phase 0 only)
            if phase == 0 {
                prop_assert!(enc.verify_synack(seq.wrapping_add(1), ip, port, src_port));
                // Wrong ack rejected
                prop_assert!(!enc.verify_synack(seq.wrapping_add(2), ip, port, src_port));
            }
        }
    }
}