Mitigating SYN Flood Attacks Using SYNPROXY with nftables on Linux

Networking tutorial - IT technology blog
Networking tutorial - IT technology blog

The Real-World Problem: Midnight Connection Starvation

Your phone buzzes at 2:00 AM with PagerDuty alerts across the fleet. NGINX is throwing 504 Gateway Timeouts, yet top shows system load under 0.40, CPU usage idling below 15%, and plenty of free memory. When you jump into the console and inspect dmesg, the real culprit surfaces:

TCP: request_sock_TCP: Possible SYN flooding on port 443. Dropping request.
nf_conntrack: table full, dropping packet.

Legitimate users cannot finish a single TLS handshake. The server is weathering a volumetric TCP SYN flood, absorbing 300,000 forged packets every second. Primitive firewall rate limits drop legitimate customer traffic right alongside the attack. Even worse, Netfilter connection tracking chokes long before incoming packets can reach your application sockets in user space.

Root Cause Analysis: Why Standard TCP Handshakes Crumble

Every standard TCP connection begins with a three-way handshake:

  1. The client sends a SYN packet.
  2. The server allocates an entry in its listen backlog (the half-open connection queue), returns a SYN-ACK, and arms a retransmission timer.
  3. The client acknowledges with an ACK, moving the socket into the established pool.

During an attack, forged clients spray random source IPs and discard the server’s SYN-ACK. Half-open sockets linger until they hit kernel timeouts. Linux provides TCP SYN Cookies (net.ipv4.tcp_syncookies) to compute sequence numbers cryptographically rather than reserving queue memory. That protects the socket queue. But on production edge servers, another bottleneck fails first: Netfilter Connection Tracking (conntrack).

Netfilter evaluates stateful firewall rules by allocating a struct nf_conn record on the very first incoming SYN. Each entry consumes roughly 320 bytes of non-swappable kernel slab memory. On an Ubuntu host with 16 GB of RAM, nf_conntrack_max commonly defaults to 262,144 entries. A 300 kpps flood saturates that table in less than one second. The moment it fills, the kernel drops all subsequent incoming packets at the interface level, rendering host-level SYN cookies useless.

Evaluating Defenses: Rate Limiting vs. SYN Cookies vs. SYNPROXY

Engineers usually cycle through three distinct layers of defense when addressing this vulnerability:

  • Per-IP Rate Limiting: Enforcing packet quotas with hash limits fails against distributed botnets using thousands of IP addresses. It also blocks corporate offices and mobile gateways where hundreds of legitimate users share one NAT IP.
  • Standard TCP SYN Cookies: This sysctl flag saves the TCP listen backlog (tcp_max_syn_backlog). However, it offers zero protection against nf_conntrack exhaustion because packet filtering hooks fire ahead of the TCP layer.
  • Kernel SYNPROXY: The netfilter synproxy target intercepts incoming SYN packets inside the PREROUTING chain before conntrack can allocate state. It marks the traffic as notrack and responds with a hardware-speed synthetic SYN-ACK. Only after the remote client returns a valid cryptographic ACK does SYNPROXY allocate a conntrack entry and build a clean backend connection.

SYNPROXY offloads authentication to the kernel’s early packet path. Spoofed packets are answered and forgotten without consuming persistent table memory.

Implementing SYNPROXY with nftables

Modern Linux distributions use nftables to replace legacy iptables and xtables. With nftables, SYNPROXY configuration is self-contained and avoids brittle multi-table raw rules.

Step 1: Tune Kernel Parameters

SYNPROXY requires identical TCP options between the client, proxy, and backend daemon. Add these optimized values to /etc/sysctl.d/99-synproxy.conf:

# Enable TCP SYN Cookies
net.ipv4.tcp_syncookies = 1

# Enable TCP Timestamps (mandatory for SYNPROXY sequence validation)
net.ipv4.tcp_timestamps = 1

# Enable Window Scaling and Selective ACK (SACK)
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1

# Expand conntrack capacity (2M entries ~= 640MB kernel memory)
net.netfilter.nf_conntrack_max = 2097152

Reload sysctl settings immediately:

sudo sysctl --system

Step 2: Construct the nftables Ruleset

Create a robust ruleset in /etc/nftables.conf to guard web services on ports 80 and 443:

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    # Configure the synproxy profile with TCP window scaling and MSS
    synproxy synproxy_web {
        mss 1460
        wscale 7
        timestamp
        sack-perm
    }

    chain raw_prerouting {
        type filter hook prerouting priority raw; policy accept;

        # 1. Bypass conntrack allocation for incoming SYN packets on protected ports
        tcp dport { 80, 443 } tcp flags syn notrack
    }

    chain filter_input {
        type filter hook input priority filter; policy drop;

        # Accept localhost traffic and existing tracked connections
        iif "lo" accept
        ct state established,related accept
        ct state invalid drop

        # Leave administrative ports untouched by synproxy
        tcp dport 22 ct state new accept

        # 2. Hand untracked SYN and handshake ACK packets to SYNPROXY
        tcp dport { 80, 443 } ct state untracked,invalid synproxy name "synproxy_web"

        # 3. Allow completed handshakes to instantiate new tracked sessions
        tcp dport { 80, 443 } ct state new accept
    }
}

Commit the ruleset to the running kernel:

sudo nft -f /etc/nftables.conf

Step 3: Verify SYNPROXY Under Load

Confirm that your proxy definition and prerouting rules loaded properly:

sudo nft list table inet filter

During a flood, monitor active table consumption and SYNPROXY counter metrics:

# Check active conntrack allocations against your 2M limit
sudo conntrack -C

# Inspect live SYNPROXY handshake transitions
sudo nstat -az "*TcpExtSyncookies*" "*Synproxy*"

When operating correctly, conntrack -C will remain steady near your baseline connection count, even while handling millions of inbound spoofed packets.

Production Guardrails and Gotchas

  • Align MSS and Window Scale: If your backend NGINX or Envoy host advertises wscale 7 but your SYNPROXY profile specifies wscale 9, TCP window calculations desynchronize. Large file downloads will suffer severe bandwidth degradation.
  • Isolate Management Ports: Never place SSH or internal database interfaces behind SYNPROXY. Protect management services with WireGuard tunnels or tight IP allowlists instead.
  • Guarantee Symmetric Routing: SYNPROXY must observe the complete bidirectional packet flow. If outgoing server packets exit via an alternative gateway or direct server return (DSR) path, the proxy state engine will desynchronize and drop valid sessions.
Share: