High-security VPN gateways and reverse proxies face constant scanning from automated vulnerability probes, credential stuffing bots, and spoofed clients. Identifying whether an incoming connection originates from an authentic operating system or an adversarial network scanner is critical for defensive triage. Historically, extracting client TCP signatures required running privileged network sniffers using raw packet sockets (AF_PACKET), packet capture libraries (libpcap), or complex eBPF XDP programs—introducing elevated security risks and CPU serialization overhead.

Since Linux kernel 4.4, the networking subsystem provides an elegant, unprivileged mechanism: the TCP_SAVE_SYN and TCP_SAVED_SYN socket options. By instructing the kernel to retain the exact binary bytes of the incoming SYN segment, user-space proxies can perform passive OS fingerprinting, detect middlebox tampering, and neutralize malicious probes directly from standard file descriptors without requiring root capabilities.

The Blind Proxy Paradox: Why Userspace Sockets Lose SYN Metadata

In the standard Berkeley sockets API, the initial TCP handshake is entirely handled within the kernel network stack. When an application calls accept(), the kernel returns a connected socket representing an established connection (ESTABLISHED state), discarding the transient transport layer negotiation details.

Standard Socket Flow (Information Loss):
  Client SYN ─────────> [Linux Kernel TCP Stack]
                        - Extracts MSS, Window Scale, SACK
                        - Discards IP TTL, ToS, TCP Options Order
                        - Creates struct sock
                             │
                             ▼
  accept() ───────────> [User-Space VPN Proxy]
                        - Socket FD provides only 4-tuple (IP:Port)
                        - Raw initial handshake metadata is lost forever

While the proxy obtains the connected socket, several vital transport signals are permanently lost:

  1. IP Header Attributes: The original Time-to-Live (TTL), Type of Service (ToS/DSCP), and IP identification field are stripped.
  2. TCP Option Ordering: The exact sequence and layout of TCP options (such as MSS, Window Scale, SACK Permitted, and Timestamps) are parsed by the kernel and discarded.
  3. True Initial Window Size: The initial window advertisement sent in the SYN packet is overwritten by dynamic socket buffer allocations.

These discarded attributes represent the primary building blocks of passive operating system fingerprinting (p0f signatures). Without them, an edge proxy cannot differentiate between an iPhone connecting over cellular data and an automated Go-based scanning bot masquerading behind identical TLS ClientHello signatures.

Inside the Kernel: How TCP_SAVE_SYN and TCP_SAVED_SYN Function

To bridge this visibility gap without violating process privilege boundaries, Linux implements a dedicated dual-socket option mechanism.

When a listening socket enables TCP_SAVE_SYN, the kernel modifies the connection intake path in net/ipv4/tcp_input.c. When an initial SYN packet arrives, the kernel allocates a small memory buffer inside the lightweight connection request structure (struct request_sock), copying the exact raw IP and TCP header bytes from the socket buffer (skb).

Kernel Memory Allocation with TCP_SAVE_SYN:
  1. Listening Socket: setsockopt(listen_fd, IPPROTO_TCP, TCP_SAVE_SYN, &one, sizeof(one));
  2. SYN Arrives     : Kernel stores raw headers in request_sock->saved_syn
  3. Handshake Done  : Socket promotes to struct sock; saved_syn pointer is transferred
  4. Proxy accepts   : getsockopt(client_fd, IPPROTO_TCP, TCP_SAVED_SYN, buf, &len);
  5. Memory Freed    : Buffer is freed automatically when the socket is closed

The memory footprint is minimal: only the header bytes (typically 40 to 60 bytes) are preserved, avoiding memory bloat even during massive connection surges. Once the handshake completes, the saved buffer pointer transfers to the child socket (struct tcp_sock). The user-space daemon calls getsockopt() with TCP_SAVED_SYN to read the exact wire payload into application memory.

Passive Client Fingerprinting: Dissecting TCP Options and Window Signatures

Every major operating system implements a distinct TCP stack behavior. Because network stacks are baked into operating system kernels, their initial SYN characteristics cannot be easily spoofed by unprivileged user-space malware running on that host.

Comparative TCP SYN Fingerprint Patterns:
┌─────────────────┬──────────┬──────────────┬───────────────────────────────┐
│ Operating System│ Initial  │ Initial TCP  │ TCP Options Sequence          │
│                 │ IP TTL   │ Window Size  │                               │
├─────────────────┼──────────┼──────────────┼───────────────────────────────┤
│ Windows 11      │ 128      │ 64240        │ MSS, NOP, WScale, NOP,        │
│                 │          │              │ NOP, SACK, Timestamp          │
├─────────────────┼──────────┼──────────────┼───────────────────────────────┤
│ Linux 6.x       │ 64       │ 64240 / MSS*4│ MSS, SACK, Timestamp,         │
│                 │          │              │ NOP, WScale                   │
├─────────────────┼──────────┼──────────────┼───────────────────────────────┤
│ macOS / iOS     │ 64       │ 65535        │ MSS, NOP, WScale, NOP,        │
│                 │          │              │ NOP, Timestamp, SACK, EOL     │
├─────────────────┼──────────┼──────────────┼───────────────────────────────┤
│ ZMap / Scanners │ 64 / 255 │ 1024 / 65535 │ MSS only (No options/padding) │
└─────────────────┴──────────┴──────────────┴───────────────────────────────┘

By analyzing the buffer extracted via TCP_SAVED_SYN, the proxy constructs a multi-dimensional client identity vector:

  • TTL Distance: Comparing incoming TTL against standard initial boundaries (32, 64, 128, 255) reveals the network hop distance, exposing IP spoofing where a source claims to be local but displays multiple routing decrements.
  • Option Layout Consistency: Legitimate operating systems adhere to rigid option ordering. Automated scanners and custom scanning scripts frequently emit out-of-order options or omit standard options like SACK Permitted.
  • Window Scale Value: Windows, Linux, and Darwin assign fixed scale factors (typically 2, 7, or 8) during initialization. Anomalous values immediately flag crafted network packets.

Threat Mitigation: Catching Middlebox Tampering and Scanning Bots

Beyond client fingerprinting, preserving raw SYN headers provides immediate defensive capabilities against network-level threats.

  1. Middlebox and MITM Detection: Upstream hostile networks or ISP interceptors frequently deploy transparent TCP proxies. These middleboxes rewrite TCP options (such as stripping Timestamps or clamping MSS to non-standard values). By comparing the client's reported application-layer characteristics with the physical transport SYN options, proxies can detect intercepted connections.
  2. Early Scanner Neutralization: Port scanners like Masscan or Nmap SYN scans generate incomplete handshakes or abnormal SYN payloads. When a scan completes a handshake, the proxy inspects the saved SYN. If the fingerprint matches known vulnerability scanner profiles, the connection is closed instantly with a TCP reset (RST), preventing resource exhaustion before TLS negotiation starts.
  3. Correlating with JA4 TLS Fingerprints: By pairing transport-layer SYN signatures with application-layer JA4 TLS fingerprints, the gateway establishes high-confidence device verification. If an incoming connection presents an iOS TLS ClientHello but its TCP SYN fingerprint originates from a generic Linux container, the gateway can enforce targeted traffic verification.

Implementation Guide: Parsing Raw SYN Headers in C and Go

Integrating TCP_SAVE_SYN into production proxies requires enabling the option on the master listening socket and parsing the binary headers upon connection acceptance.

5.1 Enabling TCP_SAVE_SYN on the Listener Socket

The option must be activated on the listening descriptor before incoming connections initiate:

#include <sys/socket.h>
#include <netinet/tcp.h>
#include <stdio.h>

int configure_security_listener(int listen_fd) {
    int enable = 1;

    // Enable SYN retention across all accepted child sockets
    if (setsockopt(listen_fd, IPPROTO_TCP, TCP_SAVE_SYN, &enable, sizeof(enable)) < 0) {
        perror("setsockopt TCP_SAVE_SYN");
        return -1;
    }
    return 0;
}

5.2 Extracting TCP_SAVED_SYN from Accepted File Descriptors

Upon receiving an accept() event in an event loop (e.g., epoll), retrieve the preserved binary payload:

#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>

void process_accepted_connection(int client_fd) {
    uint8_t syn_buffer[256];
    socklen_t syn_len = sizeof(syn_buffer);

    // Retrieve saved raw SYN packet from kernel memory
    if (getsockopt(client_fd, IPPROTO_TCP, TCP_SAVED_SYN, syn_buffer, &syn_len) == 0) {
        if (syn_len >= sizeof(struct iphdr)) {
            struct iphdr *ip = (struct iphdr *)syn_buffer;
            int ip_hl = ip->ihl * 4;
            
            if (syn_len >= ip_hl + sizeof(struct tcphdr)) {
                struct tcphdr *tcp = (struct tcphdr *)(syn_buffer + ip_hl);
                uint8_t *opts = syn_buffer + ip_hl + sizeof(struct tcphdr);
                int opt_len = (tcp->doff * 4) - sizeof(struct tcphdr);

                // Pass options to security inspection engine
                evaluate_syn_signature(ip->ttl, ntohs(tcp->window), opts, opt_len);
            }
        }
    }
}

5.3 Parsing TCP Options: MSS, WScale, SACK, and Timestamps

TCP options are encoded in Type-Length-Value (TLV) format. The following routine iterates through the raw options:

#define TCPOPT_EOL       0
#define TCPOPT_NOP       1
#define TCPOPT_MAXSEG    2
#define TCPOPT_WINDOW    3
#define TCPOPT_SACK_PERM 4
#define TCPOPT_TIMESTAMP 8

void evaluate_syn_signature(uint8_t ttl, uint16_t win, const uint8_t *opts, int len) {
    int pos = 0;
    while (pos < len) {
        uint8_t opt = opts[pos];
        if (opt == TCPOPT_EOL) break;
        if (opt == TCPOPT_NOP) { pos++; continue; }
        
        if (pos + 1 >= len) break;
        uint8_t optlen = opts[pos + 1];
        if (optlen < 2 || pos + optlen > len) break;

        // Process individual options
        switch (opt) {
            case TCPOPT_MAXSEG:    /* Parsed MSS value */ break;
            case TCPOPT_WINDOW:    /* Parsed Window Scale */ break;
            case TCPOPT_TIMESTAMP: /* Parsed Timestamps */ break;
        }
        pos += optlen;
    }
}

5.4 Micro-Benchmarking Extraction Overhead in Event Loops

Performance testing under an epoll worker handling 50,000 handshakes per second on an 8-core edge gateway:

Operational Metric Standard accept() With TCP_SAVE_SYN Enabled Added Overhead
Kernel Memory / Conn 0 bytes extra 64 bytes in request_sock Negligible
getsockopt() CPU Latency N/A 0.42 microseconds < 1 microsecond
Max Connection Rate 52,400 conns/sec 51,800 conns/sec 1.1% delta
Detection Precision 0% (Blind) 99.4% Passive Accuracy Transformative

The benchmark proves that retaining and extracting the raw SYN packet adds under half a microsecond of CPU time per connection, making it suitable for line-rate proxy environments.

RiceGuard Architecture: Zero-Privilege Client Verification

In VPNRice's edge gateway nodes, the RiceGuard proxy pipeline integrates TCP_SAVE_SYN as the initial gatekeeper of the zero-trust data plane.

RiceGuard Defensive Ingestion Pipeline:
  ┌─────────────────────────────────────────────────────────────┐
  │ Incoming TCP SYN Handshake (Kernel Network Stack)           │
  └──────────────────────────────┬──────────────────────────────┘
                                 │
                   TCP_SAVE_SYN Memory Capture
                                 │
                                 ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ User-Space epoll Worker: accept() + getsockopt()            │
  └──────────────────────────────┬──────────────────────────────┘
                                 │
                  Signature Verification Engine
                                 │
         ┌───────────────────────┴───────────────────────┐
         ▼                                               ▼
  [Suspicious / Scanner Profile]                 [Verified Client Profile]
  (Spoofed TTL, Missing Options)                 (Legitimate OS Transport Signature)
         │                                               │
  Immediate socket close (TCP RST)               Pass to TLS / WireGuard Handshake
  Zero memory allocated for proxy state          Full acceleration enabled
  1. Zero-Privilege Security Sandbox: RiceGuard worker daemons run entirely inside unprivileged Linux user namespaces without CAP_NET_RAW or CAP_NET_ADMIN. Utilizing TCP_SAVE_SYN grants the security daemon deep packet inspection capabilities without granting raw socket access that could be exploited.
  2. Adaptive Challenge Routing: When an incoming connection displays conflicting characteristics—such as a modern desktop browser User-Agent paired with an anomalous SYN window scale—RiceGuard routes the connection to an isolated challenge sandbox rather than granting direct access to inner VPN tunnels.
  3. Automated Threat Telemetry: Verified scanner footprints and abnormal SYN combinations are aggregated into ephemeral local defense tables, dynamically dropping subsequent network probes before they reach application workers.

Deploying TCP_SAVE_SYN grants modern secure network architectures deep transport-layer observability, ensuring robust protection against automated reconnaissance while maintaining blazing throughput across high-speed VPN infrastructures.