The Network Stack Through a Security Lens

"To understand how to break something, you must first understand how it works. To understand how to defend it, you must understand how it breaks." — Bruce Schneier


A Packet's Dangerous Journey

Open your laptop and type a URL into your browser. Before doing anything else in this book, you need to understand the journey that request takes -- and every place along that journey where something can go wrong.

When you navigate to https://api.example.com/users, your data passes through seven conceptual layers, crosses multiple physical networks, gets encapsulated and de-encapsulated, encrypted and decrypted, routed and switched. At every single transition point, an attacker has an opportunity.

graph TD
    subgraph L7["Layer 7: Application"]
        L7A["HTTP, DNS, SMTP, SSH, FTP"]
        L7B["SQL injection, XSS, CSRF,<br/>command injection, API abuse,<br/>path traversal, SSRF"]
    end

    subgraph L6["Layer 6: Presentation"]
        L6A["TLS/SSL, encoding,<br/>serialization, compression"]
        L6B["SSL stripping, downgrade attacks,<br/>deserialization exploits,<br/>padding oracle, CRIME/BREACH"]
    end

    subgraph L5["Layer 5: Session"]
        L5A["Session management,<br/>authentication state"]
        L5B["Session hijacking,<br/>session fixation, replay attacks,<br/>cookie theft"]
    end

    subgraph L4["Layer 4: Transport"]
        L4A["TCP, UDP, QUIC"]
        L4B["SYN floods, TCP reset injection,<br/>sequence prediction,<br/>UDP amplification"]
    end

    subgraph L3["Layer 3: Network"]
        L3A["IP, ICMP, routing protocols"]
        L3B["IP spoofing, BGP hijacking,<br/>ICMP redirect, fragmentation<br/>attacks, route injection"]
    end

    subgraph L2["Layer 2: Data Link"]
        L2A["Ethernet, ARP,<br/>switches, VLANs"]
        L2B["ARP spoofing, MAC flooding,<br/>VLAN hopping, CAM table<br/>overflow, 802.1Q attacks"]
    end

    subgraph L1["Layer 1: Physical"]
        L1A["Cables, radio, fiber,<br/>electrical signals"]
        L1B["Wiretapping, signal jamming,<br/>EM emanation, rogue APs,<br/>physical access"]
    end

    L7 --> L6 --> L5 --> L4 --> L3 --> L2 --> L1

    style L7 fill:#e53e3e,color:#fff
    style L6 fill:#dd6b20,color:#fff
    style L5 fill:#d69e2e,color:#1a202c
    style L4 fill:#38a169,color:#fff
    style L3 fill:#3182ce,color:#fff
    style L2 fill:#805ad5,color:#fff
    style L1 fill:#2d3748,color:#e2e8f0

You might be thinking: the practical model is TCP/IP with four layers, not OSI with seven. That is correct, and in practice you use the TCP/IP model. But the OSI model is useful for security analysis because it gives you finer-grained categories. The key thing is not which model you use -- it is that you understand attacks can happen at every level. Let's walk through each one.


Layer 1: The Physical Layer -- Where It All Begins

The physical layer is the actual medium carrying your data: copper wire, fiber optic cable, radio waves (Wi-Fi, cellular), or even light pulses. Most developers never think about it. Attackers sometimes do.

Wiretapping

Copper Ethernet cables emit electromagnetic radiation. With the right equipment, you can read that radiation without ever touching the cable. It is called Van Eck phreaking, and intelligence agencies have been doing it since the 1960s. The NSA's TEMPEST program has published classification levels for electromagnetic emanation from computing equipment. Shielded cables (STP vs UTP) and Faraday cages exist specifically to counter this threat.

This sounds like spy movie material, and for most threat models, electromagnetic emanation is not a practical concern. But fiber optic cables can be tapped too, and that is very practical. In 2013, documents revealed that intelligence agencies had tapped undersea fiber optic cables carrying internet traffic between continents. The technique involves bending the fiber just enough to leak a small percentage of the light signal to a detector -- a fiber tap splitter. It introduces a barely measurable signal loss that is difficult to detect amid normal fiber attenuation.

For enterprise environments, the physical security lesson is more straightforward but just as critical.

Physical access to network infrastructure means game over. If an attacker can plug into your network switch, attach a rogue device to your network cable, or access your server room, no amount of software security helps. This is why data centers have mantraps, biometric access controls, and 24/7 security cameras. In 2023, a penetration testing firm demonstrated that dropping a $35 Raspberry Pi-based rogue device in a ceiling tile above a conference room could provide persistent network access for weeks before detection. The device used PoE (Power over Ethernet) so it didn't even need its own power supply.

Wi-Fi: The Physical Layer You Can't See

Wi-Fi is a physical layer that radiates in all directions. Your office Wi-Fi signal does not stop at the walls -- it extends into the parking lot, the neighboring building, and the coffee shop downstairs.

# See what Wi-Fi networks are visible (and their signal strength)
# macOS:
$ /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s

# Linux:
$ nmcli device wifi list

# This shows every network your machine can see.
# An attacker in range can see YOUR network too.

# Check your Wi-Fi security type
$ networksetup -getinfo Wi-Fi  # macOS
$ iwconfig wlan0               # Linux

Someone sitting in a car outside your office could potentially capture your Wi-Fi traffic. If your Wi-Fi uses WPA2-Enterprise with certificate-based authentication (802.1X/EAP-TLS), they can capture the encrypted frames but cannot decrypt them without a valid client certificate. If you are using a shared password (WPA2-PSK), and they know the password (which everyone who ever connected knows), they can decrypt all traffic with a captured four-way handshake. And if any employees are connecting to an open Wi-Fi network at a coffee shop for work -- that is exactly why VPNs and TLS exist. They create encrypted tunnels that protect data even when the physical layer is compromised. Defense in depth.

The progression of Wi-Fi security tells an instructive story about protocol evolution:

ProtocolYearStatusKey Weakness
WEP1997BrokenRC4 with 24-bit IV; crackable in minutes with aircrack-ng
WPA2003DeprecatedTKIP temporal fix; vulnerable to chopchop attack
WPA2-PSK2004AcceptableOffline brute-force of pre-shared key via captured handshake (KRACK 2017)
WPA2-Enterprise2004GoodRequires RADIUS server; misconfiguration risks (certificate validation)
WPA3-SAE2018RecommendedSimultaneous Authentication of Equals; resistant to offline dictionary attacks
WPA3-Enterprise2018Best192-bit security suite; mandatory PMF
The KRACK (Key Reinstallation Attack) vulnerability discovered in 2017 affected all WPA2 implementations. The attack forced the client to reinstall an already-in-use encryption key during the four-way handshake, resetting the nonce counter. With a reset nonce, the attacker could decrypt, replay, and forge packets. This was a protocol-level vulnerability, not an implementation bug, meaning every compliant WPA2 device was affected. The fix required firmware updates to every Wi-Fi device in existence. WPA3's SAE (Simultaneous Authentication of Equals) handshake, based on the Dragonfly key exchange, was designed specifically to resist this class of attack.

The data link layer handles communication within a single network segment. Ethernet frames, MAC addresses, ARP, and switches all live here. And this layer has some of the most underappreciated attacks in networking.

ARP Spoofing: Becoming the Man in the Middle

ARP (Address Resolution Protocol) maps IP addresses to MAC addresses on a local network. When your machine wants to send a packet to 192.168.1.1 (the gateway), it broadcasts an ARP request: "Who has 192.168.1.1?" The gateway responds with its MAC address.

The problem: ARP has no authentication. Anyone on the local network can respond to that ARP request.

sequenceDiagram
    participant V as Victim (192.168.1.100)
    participant A as Attacker (192.168.1.200)
    participant G as Gateway (192.168.1.1)

    Note over V,G: Normal ARP Resolution
    V->>G: ARP Request: Who has 192.168.1.1?
    G->>V: ARP Reply: 192.168.1.1 is at MAC:AA:AA:AA

    Note over V,G: ARP Spoofing Attack
    A->>V: Gratuitous ARP: 192.168.1.1 is at MAC:EE:EE:EE (SPOOFED!)
    A->>G: Gratuitous ARP: 192.168.1.100 is at MAC:EE:EE:EE (SPOOFED!)

    Note over V,G: Traffic Now Flows Through Attacker
    V->>A: Traffic intended for gateway
    A->>G: Attacker forwards (and reads) traffic
    G->>A: Response traffic
    A->>V: Attacker forwards (and reads) response

    Note over A: Attacker sees ALL traffic between<br/>victim and gateway in plaintext

The attacker simply lies about their MAC address, and the victim's machine believes it. ARP was designed in 1982 for small, trusted networks. It has zero security. The attacker does not even need to wait for an ARP request. They can send gratuitous ARP replies -- unsolicited ARP responses that update the victim's ARP cache proactively. Once the attacker has positioned themselves as the man in the middle, they can read all unencrypted traffic, modify packets in transit, selectively drop traffic, or inject malicious content into HTTP responses.

This is one of the reasons why TLS is so critical. Even if an attacker positions themselves as a MITM via ARP spoofing, TLS encryption means they see ciphertext, not plaintext. The attacker sees encrypted bytes flowing through their machine but cannot decrypt or modify them without breaking the TLS session.

# Detecting ARP spoofing

# Check ARP table for duplicates — look for two different IPs with same MAC
$ arp -a
? (192.168.1.1) at aa:bb:cc:dd:ee:ff on en0 ifscope [ethernet]
? (192.168.1.200) at aa:bb:cc:dd:ee:ff on en0 ifscope [ethernet]
# WARNING: Two IPs with the same MAC — likely ARP spoofing!

# On Linux, use arpwatch for continuous monitoring
$ sudo apt install arpwatch
$ sudo arpwatch -i eth0
# arpwatch logs MAC/IP pair changes to syslog

# Verify with arping — send ARP requests and watch for multiple responses
$ arping -I eth0 192.168.1.1
# If you see responses from two different MAC addresses, someone is spoofing

# Use tcpdump to watch ARP traffic
$ sudo tcpdump -i en0 arp -n
# Look for frequent ARP replies from the same source to different targets
On a test network (never on production), you can demonstrate ARP spoofing with the tool `arpspoof` (part of the `dsniff` suite). Here's the concept:

```bash
# Enable IP forwarding so traffic still reaches its destination
echo 1 > /proc/sys/net/ipv4/ip_forward

# Tell the victim that you are the gateway
arpspoof -i eth0 -t VICTIM_IP GATEWAY_IP

# Tell the gateway that you are the victim
arpspoof -i eth0 -t GATEWAY_IP VICTIM_IP

# Now use Wireshark to observe traffic flowing through your machine
wireshark -i eth0 -f "host VICTIM_IP"

You'll see all unencrypted traffic from the victim: HTTP requests, DNS queries, any protocol not using TLS. You'll also see that HTTPS traffic appears as encrypted TLS records — proving that TLS protects against this attack.

Modern alternative: use bettercap which combines ARP spoofing, DNS spoofing, and SSL stripping into one tool. It's used extensively in penetration testing.


**Defenses against ARP spoofing:**
- **Dynamic ARP Inspection (DAI)**: Managed switches validate ARP packets against the DHCP snooping binding table. Invalid ARP packets are dropped.
- **Static ARP entries**: For critical infrastructure (gateways, DNS servers), configure static ARP entries that can't be overwritten.
- **802.1X port authentication**: Requires devices to authenticate before gaining network access.
- **VLANs with private VLANs**: Isolate hosts even within the same VLAN so they can't communicate directly.
- **TLS everywhere**: The ultimate defense -- even if ARP spoofing succeeds, the attacker can't read the data.

### MAC Flooding and CAM Table Overflow

Network switches maintain a CAM (Content Addressable Memory) table mapping MAC addresses to physical ports. This table has a limited size -- typically 8,000 to 32,000 entries depending on the switch. If an attacker floods the switch with thousands of fake MAC addresses, the CAM table fills up, and the switch degrades to a hub -- broadcasting all traffic to all ports.

When a switch becomes a hub, the attacker on any port can see all traffic on the network. It is the network equivalent of turning a private conversation into a public broadcast.

```bash
# Simulate MAC flooding with macof (dsniff suite) — TEST NETWORKS ONLY
$ macof -i eth0 -n 50000
# This generates 50,000 random MAC address frames
# The switch's CAM table fills up and it starts broadcasting

# Detect CAM table overflow from the switch
# On a Cisco switch:
# show mac address-table count
# If the count is near the maximum, suspect flooding

Defense: Port security features on managed switches limit the number of MAC addresses learned per port. Most enterprise switches support port-security commands:

! Cisco IOS port security configuration
interface GigabitEthernet0/1
  switchport mode access
  switchport port-security
  switchport port-security maximum 3
  switchport port-security violation shutdown
  switchport port-security aging time 60

This limits each port to 3 MAC addresses and shuts down the port if more are detected. 802.1X port-based authentication ensures that only authorized devices can connect to switch ports.

VLAN Hopping

VLANs (Virtual LANs) segment a physical network into isolated logical networks. They are a critical security control -- separating guest Wi-Fi from corporate, or PCI cardholder data environments from general-purpose networks. But VLAN isolation can be broken.

The two main VLAN hopping techniques are:

1. **Switch spoofing**: The attacker's machine negotiates a trunk link with the switch (using DTP — Dynamic Trunking Protocol), gaining access to all VLANs. DTP is enabled by default on many Cisco switches. Defense: disable DTP on all access ports with `switchport mode access` and `switchport nonegotiate`. This is one of the most commonly missed hardening steps in network deployments.

2. **Double tagging**: The attacker sends a frame with two 802.1Q VLAN tags. The first switch strips the outer tag (which matches the native VLAN) and forwards the frame to the trunk. The second switch reads the inner tag and delivers the frame to the target VLAN. Defense: ensure the native VLAN is not used for any user traffic, is tagged on trunks, and ideally use a dedicated unused VLAN as the native VLAN.

In PCI DSS environments, VLAN isolation between the cardholder data environment (CDE) and other networks is a requirement. If VLAN hopping is possible, the isolation is illusory, and the entire flat network is considered in scope for PCI compliance — dramatically increasing the audit burden and cost.

Layer 3: The Network Layer -- Routing and IP

The network layer handles addressing (IP) and routing (how packets get from source to destination across multiple networks). Attacks at this layer can redirect traffic, spoof identities, or disrupt routing infrastructure.

IP Spoofing

IP spoofing means crafting packets with a forged source IP address. The packet appears to come from a different machine.

For TCP connections, blind IP spoofing is difficult because the three-way handshake requires bidirectional communication (though not impossible with sequence number prediction). But for UDP, there is no handshake. You send a spoofed UDP packet, and the response goes to the spoofed address. This is the basis of amplification attacks.

sequenceDiagram
    participant ATK as Attacker
    participant DNS as Open DNS Resolver
    participant VIC as Victim Server

    Note over ATK: Attacker spoofs source IP = Victim's IP

    ATK->>DNS: DNS query (60 bytes)<br/>src: VICTIM_IP<br/>"ANY record for large-zone.com"
    Note over DNS: DNS server processes query normally<br/>Sends response to the "source" IP

    DNS->>VIC: DNS response (3,000+ bytes)<br/>50x amplification!

    Note over ATK: Multiply by thousands of<br/>open resolvers simultaneously

    ATK->>DNS: Query (60 bytes, spoofed src)
    ATK->>DNS: Query (60 bytes, spoofed src)
    ATK->>DNS: Query (60 bytes, spoofed src)
    DNS->>VIC: Response (3,000 bytes)
    DNS->>VIC: Response (3,000 bytes)
    DNS->>VIC: Response (3,000 bytes)

    Note over VIC: Victim receives gigabits/s<br/>of unsolicited DNS responses<br/>Network overwhelmed

DNS amplification attacks exploit two things: IP spoofing (to redirect responses to the victim) and the amplification factor (a small query generates a much larger response). A 60-byte DNS query requesting ANY records can generate a 3,000+ byte response -- a 50x amplification. Send spoofed queries to thousands of open DNS resolvers, and you generate terabits of traffic aimed at your victim.

The amplification factor varies dramatically by protocol:

ProtocolAmplification FactorPortWhy It Amplifies
DNS28-54x53ANY queries return all record types
NTP (monlist)556x123monlist returns last 600 clients that queried the server
Memcached10,000-51,000x11211GET command returns cached values much larger than query
SSDP30x1900Service discovery returns detailed device descriptions
CLDAP56-70x389LDAP queries return large directory results
Chargen~359x19Returns continuous stream of characters
SNMP v26x161GetBulk returns large MIB tables

In February 2018, GitHub was hit by a 1.35 Tbps DDoS attack using Memcached amplification. The attackers sent small GET requests to publicly accessible Memcached servers with a spoofed source IP (GitHub's). Memcached responded with cached values up to 51,000 times larger than the request. GitHub's DDoS mitigation provider (Akamai Prolexic) absorbed the attack within 10 minutes, but it was the largest DDoS recorded at that time. The fix was simple in retrospect: Memcached should never be exposed to the internet. But thousands of Memcached servers were publicly accessible because they bound to 0.0.0.0 by default.

Defense against IP spoofing: BCP38/RFC 2827 -- ingress filtering. ISPs should drop packets with source IPs that could not have originated from their network. Many do, but not all. You can check your own network's compliance at https://www.caida.org/projects/spoofer/.

BGP Hijacking: Stealing the Internet's Routing

BGP (Border Gateway Protocol) is how the internet's autonomous systems (AS) -- the large networks operated by ISPs, cloud providers, and content companies -- tell each other about reachable IP address ranges. BGP is the routing protocol that glues the entire internet together.

BGP has no built-in authentication. Any AS can announce that it owns any IP prefix. The rest of the internet trusts those announcements and routes traffic accordingly.

flowchart TD
    subgraph NORMAL["Normal Routing"]
        U1["User"] -->|"Route: AS64500→AS13335"| ISP1["ISP<br/>AS64500"]
        ISP1 -->|"Route: AS13335"| CF1["Cloudflare<br/>AS13335<br/>1.1.1.0/24"]
    end

    subgraph HIJACK["BGP Hijack"]
        U2["User"] -->|"Route: AS64500→AS99999"| ISP2["ISP<br/>AS64500"]
        ISP2 -->|"More specific route wins!"| ATK["Attacker<br/>AS99999<br/>announces 1.1.1.0/25"]
        ISP2 -.->|"Original route<br/>loses to more<br/>specific prefix"| CF2["Cloudflare<br/>AS13335<br/>1.1.1.0/24"]
    end

    style ATK fill:#e53e3e,color:#fff
    style CF1 fill:#38a169,color:#fff
    style CF2 fill:#718096,color:#fff
In April 2018, attackers hijacked Amazon's Route 53 DNS IP address space by announcing more-specific BGP routes through a small ISP in Ohio. For about two hours, DNS queries intended for Amazon's DNS servers were redirected to attacker-controlled servers. The attackers used this to serve fake DNS responses for MyEtherWallet.com, redirecting users to a phishing site that stole cryptocurrency. They made off with approximately $150,000 in Ethereum.

But here's the scarier version of this attack: in 2022, Russian-linked attackers briefly hijacked IP prefixes belonging to Twitter, Amazon, and multiple other major services. The hijacks lasted only minutes — long enough to intercept traffic but short enough to avoid automated detection. This pattern of short-duration hijacks is increasingly common because it evades monitoring that only alerts on sustained anomalies.

The fundamental problem is that BGP was designed in 1989 for a much smaller, more trusted internet. RPKI (Resource Public Key Infrastructure) is being deployed to add cryptographic verification to BGP announcements, but adoption is slow. As of 2025, only about 40% of routes are covered by RPKI ROAs (Route Origin Authorizations). Until adoption reaches near-universal levels, BGP hijacking remains a viable attack vector.

The routing infrastructure of the entire internet is essentially based on trust. It is one of the internet's most fundamental vulnerabilities. The good news is that RPKI adoption is accelerating -- Cloudflare, Google, Amazon, and most major ISPs now validate RPKI. The bad news is that the long tail of smaller ISPs is slow to adopt, and an attacker only needs one non-validating ISP to propagate a hijack.

ICMP Attacks and Reconnaissance

ICMP (Internet Control Message Protocol) is used for diagnostic and error-reporting purposes -- ping, traceroute, "destination unreachable" messages. But ICMP can be abused in several ways:

# ICMP redirect attack: Tell a victim to route traffic through you
# Detect ICMP redirects with tcpdump:
$ sudo tcpdump -i eth0 'icmp[icmptype] == 5'

# Disable ICMP redirect acceptance (Linux):
$ sudo sysctl -w net.ipv4.conf.all.accept_redirects=0
$ sudo sysctl -w net.ipv6.conf.all.accept_redirects=0
$ sudo sysctl -w net.ipv4.conf.all.send_redirects=0

# Use traceroute to map network topology (attacker reconnaissance):
$ traceroute -n api.ourcompany.com
 1  10.0.0.1      1.234 ms   # Local gateway
 2  172.16.0.1    5.678 ms   # ISP router
 3  209.85.243.1  12.345 ms  # Transit router
 4  93.184.216.34 20.567 ms  # Destination

# Each hop reveals an internal IP address
# This is why many firewalls block outbound ICMP TTL exceeded

# Detect ICMP-based covert channels (data exfiltration via ping)
$ sudo tcpdump -i eth0 'icmp[icmptype] == 8' -X | head -40
# Large or unusual ICMP payloads may indicate data exfiltration

Layer 4: The Transport Layer -- TCP and UDP

The transport layer provides end-to-end communication between processes. TCP provides reliable, ordered delivery with connection management. UDP provides fast, connectionless delivery. Both have vulnerabilities.

The TCP Three-Way Handshake and SYN Floods

sequenceDiagram
    participant C as Client
    participant S as Server

    Note over C,S: TCP Three-Way Handshake
    C->>S: SYN (seq=100)<br/>"I want to connect"
    Note over S: Server allocates TCB<br/>(~280 bytes) for half-open connection
    S->>C: SYN-ACK (seq=300, ack=101)<br/>"OK, I'm listening"
    C->>S: ACK (seq=101, ack=301)<br/>"Connected!"
    Note over C,S: CONNECTION ESTABLISHED

    Note over C,S: SYN Flood Attack
    C->>S: SYN (seq=200, src=spoofed_IP_1)
    Note over S: Allocates TCB #1
    C->>S: SYN (seq=201, src=spoofed_IP_2)
    Note over S: Allocates TCB #2
    C->>S: SYN (seq=202, src=spoofed_IP_3)
    Note over S: Allocates TCB #3
    Note over C: Never sends ACK<br/>(spoofed IPs don't know about the connection)
    Note over S: Millions of half-open connections<br/>TCB table exhausted<br/>Legitimate connections REFUSED

A SYN flood exploits the handshake by sending thousands of SYN packets from spoofed source IPs and never completing the handshake. The server allocates resources for each half-open connection, eventually exhausting its connection table.

The server has to remember every SYN it receives -- it allocates a Transmission Control Block (TCB) for each one, typically 280 bytes. The kernel's SYN backlog queue has a fixed size (typically 128-1024 entries). An attacker sending millions of SYN packets per second with random source IPs fills up the SYN backlog, and legitimate connections cannot be established. The SYN-ACK responses go to the spoofed IPs, which either do not exist or ignore the unexpected packet. The server waits for the final ACK (typically 75 seconds with retries), tying up resources the entire time.

# Detecting a SYN flood
$ ss -s
Total: 45032
TCP:   44200 (estab 200, closed 100, orphaned 50, synrecv 43850)
# synrecv count of 43850 = under SYN flood attack

# Or with netstat
$ netstat -an | grep SYN_RECV | wc -l
43850

# Monitor SYN packets in real time
$ sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) == 0' -c 1000
# If you see thousands of SYNs from different source IPs per second
# with no corresponding ACKs, it's a SYN flood

# Check current SYN backlog size
$ sysctl net.ipv4.tcp_max_syn_backlog
net.ipv4.tcp_max_syn_backlog = 1024

Defense: SYN Cookies

This is an elegant solution. SYN cookies (invented by Daniel J. Bernstein in 1996) eliminate the need to allocate memory for each SYN. Instead, the server encodes the connection state into the initial sequence number of the SYN-ACK response. The sequence number is computed as a cryptographic hash of the source/destination IP, source/destination port, and a server secret, plus the timestamp and MSS value. When the final ACK arrives, the server reconstructs the connection state from the acknowledged sequence number. Zero memory allocated until the handshake completes.

# Enable SYN cookies on Linux
$ sudo sysctl -w net.ipv4.tcp_syncookies=1

# Make it permanent
$ echo "net.ipv4.tcp_syncookies = 1" | sudo tee -a /etc/sysctl.conf

# Additional SYN flood mitigation
$ sudo sysctl -w net.ipv4.tcp_max_syn_backlog=4096
$ sudo sysctl -w net.ipv4.tcp_synack_retries=2
$ sudo sysctl -w net.core.somaxconn=4096

The trade-off: SYN cookies lose some TCP options (window scaling, selective acknowledgment) because there is nowhere to store them. This slightly reduces performance for connections established via SYN cookies. In practice, the trade-off is overwhelmingly worth it.

TCP Session Hijacking and Reset Attacks

If an attacker can predict or observe TCP sequence numbers, they can inject packets into an existing connection.

In early TCP implementations, initial sequence numbers were predictable -- they incremented by a fixed amount for each new connection. Kevin Mitnick's famous 1994 attack on Tsutomu Shimomura used TCP sequence number prediction to hijack a trusted session. Modern operating systems use cryptographically random initial sequence numbers (RFC 6528), making blind injection extremely difficult. But if the attacker can sniff traffic (via ARP spoofing, for example), they can see the sequence numbers and inject packets anyway.

A TCP RST (reset) injection attack terminates a connection immediately. If an attacker can guess the correct sequence number window for an active connection, they can inject a RST packet and kill the connection.

The Great Firewall of China (GFW) uses TCP reset injection as its primary censorship mechanism. When the GFW's deep packet inspection detects a connection carrying prohibited content (identified by keyword matching in HTTP, SNI inspection in TLS, or protocol fingerprinting), it injects forged RST packets to both endpoints, terminating the connection. Both sides think the other closed the connection. This is why connections to blocked sites in China produce "connection reset" errors rather than timeouts or clean blocks — you're seeing the injected RST.

The GFW can inject RST packets because it sits on the backbone links between Chinese ISPs and the global internet. It doesn't need to be a man-in-the-middle; it only needs to be able to read packets on the wire (passive tap) and inject packets (active injection). This is technically a "man-on-the-side" attack rather than a man-in-the-middle attack. The injected RST arrives before the legitimate response because the GFW hardware is physically closer to the Chinese endpoint.

Circumvention techniques include: ignoring RST packets from unexpected sources (requires kernel modification), using protocols that don't use TCP (QUIC over UDP), or tunneling traffic through protocols the GFW doesn't inspect (encrypted DNS, Tor with pluggable transports).

UDP Amplification: The Modern DDoS Weapon

UDP has no handshake, no connection state, and no built-in mechanism to verify the source of a packet. Combined with IP spoofing, this makes UDP the protocol of choice for DDoS amplification attacks.

# Check for publicly accessible services that could be used for amplification
# These should NEVER be exposed to the internet:

# Memcached (port 11211) — up to 51,000x amplification
$ nmap -sU -p 11211 --script memcached-info target
# If accessible, your server could be used as a DDoS amplifier

# NTP monlist (port 123) — up to 556x amplification
$ ntpdc -c monlist target_ntp_server
# If this returns data, the NTP server can be abused

# Open DNS resolver (port 53)
$ dig @target_dns_server google.com ANY +short
# If this responds, it's an open resolver that can be abused

# SSDP (port 1900) — common on home routers
$ nmap -sU -p 1900 --script upnp-info target

Layer 5-6: Session and Presentation

In the TCP/IP model, these layers are absorbed into the application layer. But it is useful to think about session and presentation concerns separately for security analysis.

Session Layer Attacks

Sessions represent ongoing interactions between a client and server. Web sessions are typically managed through cookies, tokens, or server-side session storage.

Session hijacking happens when an attacker obtains a valid session token:

# If you can sniff unencrypted HTTP traffic, session cookies are visible:
$ sudo tcpdump -i eth0 -A -s 0 'tcp port 80' | grep -i 'cookie:'
Cookie: session_id=abc123def456; user=admin; role=superuser

# This is why every site MUST use HTTPS.
# Session cookies sent over HTTP are visible to any network observer.

# Even with HTTPS, cookies can leak if the Secure flag isn't set:
# Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
#                                  ^^^^^^
#                                  Without this, cookie sent over HTTP too

Session fixation is a subtler attack where the attacker sets the session ID before the victim authenticates:

sequenceDiagram
    participant A as Attacker
    participant S as Server
    participant V as Victim

    A->>S: GET /login
    S->>A: Set-Cookie: session=ABC123

    Note over A: Attacker now knows session ID ABC123

    A->>V: Send link: https://bank.com/login?session=ABC123<br/>(via email, chat, etc.)

    V->>S: GET /login?session=ABC123
    Note over S: Server accepts the session ID
    V->>S: POST /login (username, password)
    Note over S: Server authenticates user<br/>Session ABC123 now authenticated

    A->>S: GET /account (Cookie: session=ABC123)
    Note over S: Session ABC123 is authenticated<br/>Attacker has access to victim's account!

    Note over S: DEFENSE: Regenerate session ID<br/>after successful authentication

The defense is simple but often overlooked: regenerate the session ID after successful authentication. The pre-authentication session ID is invalidated, and a new one is issued. The attacker's known session ID becomes useless. In PHP, this is session_regenerate_id(true). In Java Spring Security, it happens automatically. In Express.js, you need to call req.session.regenerate(). Check your framework's documentation.

Presentation Layer: SSL Stripping

The presentation layer handles data formatting, encryption, and compression. TLS operates here, and attacks against TLS have been some of the most impactful in security history.

SSL stripping (Moxie Marlinspike, Black Hat 2009): The attacker intercepts HTTP traffic and prevents the upgrade to HTTPS. The victim's browser communicates with the attacker over HTTP, while the attacker communicates with the real server over HTTPS.

sequenceDiagram
    participant V as Victim Browser
    participant A as Attacker (MITM)
    participant S as Real Server

    V->>A: HTTP GET http://bank.com
    Note over A: Attacker intercepts,<br/>does NOT redirect to HTTPS

    A->>S: HTTPS GET https://bank.com
    S->>A: HTTPS 200 OK (login page)

    A->>V: HTTP 200 OK (login page)<br/>Links rewritten: https→http<br/>No lock icon in browser

    V->>A: HTTP POST /login<br/>username=alice&password=secret123
    Note over A: Attacker reads credentials<br/>in plaintext!

    A->>S: HTTPS POST /login<br/>username=alice&password=secret123
    S->>A: HTTPS 200 OK (logged in)
    A->>V: HTTP 200 OK (logged in)

Defense: HSTS (HTTP Strict Transport Security) headers tell the browser to always use HTTPS, even if the user types http://. HSTS preloading goes further -- browsers ship with a list of domains that must always use HTTPS, defeating SSL stripping even on the first visit.

# Check if a site has HSTS:
$ curl -sI https://google.com | grep -i strict
strict-transport-security: max-age=31536000; includeSubDomains; preload

# max-age=31536000 means the browser will remember to use HTTPS
# for this domain for one year
# includeSubDomains applies to all subdomains
# preload means the domain is in the browser's built-in HSTS list

# Check if a domain is HSTS preloaded:
# Visit https://hstspreload.org/
HSTS only protects after the browser has seen the header at least once (or if the domain is preloaded). On the very first visit, if the user types `http://bank.com`, they're still vulnerable to SSL stripping until the HSTS header is received over the HTTPS connection. This is why HSTS preloading exists — it protects even the first visit. Submit your domain at https://hstspreload.org/ to be included in browser preload lists. Requirements: valid HTTPS on all subdomains, HSTS header with includeSubDomains and preload directives, max-age of at least 1 year.

Layer 7: The Application Layer -- Where Most Breaches Happen

Here is the uncomfortable truth: the majority of breaches happen at the application layer. Not because it is the weakest layer architecturally, but because it is the most complex and the most exposed. The OWASP Top 10 is essentially a layer 7 vulnerability list.

DNS Attacks

DNS is the internet's naming system, and it is a critical attack vector because almost every network communication begins with a DNS lookup.

DNS spoofing/cache poisoning: An attacker provides false DNS responses, redirecting users to malicious servers.

# Query DNS and examine the response
$ dig @8.8.8.8 example.com A +short
93.184.216.34

# Check if DNSSEC is enabled for a domain
$ dig @8.8.8.8 example.com A +dnssec +short
93.184.216.34
A 13 2 86400 20240301000000 20240215000000 12345 example.com. BASE64SIG...
# If you see an RRSIG record, DNSSEC is configured

# Check the full DNSSEC chain of trust
$ dig @8.8.8.8 example.com A +dnssec +multiline +trace

# Monitor DNS queries in real time
$ sudo tcpdump -i en0 'udp port 53' -l | tee /tmp/dns_queries.txt
# Watch for unusual domains, high query rates, or DNS tunneling patterns

# Test for DNS-over-HTTPS support
$ curl -s -H 'accept: application/dns-json' \
    'https://cloudflare-dns.com/dns-query?name=example.com&type=A' | \
    python3 -m json.tool
The Kaminsky attack (2008) was a devastating DNS cache poisoning technique discovered by Dan Kaminsky. Traditional cache poisoning required guessing the 16-bit transaction ID (65,536 possibilities) and waiting for a cache entry to expire (potentially hours or days). Kaminsky's technique was far more powerful:

1. Query the recursive resolver for a random, non-existent subdomain: `random123.example.com`
2. Since this subdomain doesn't exist in the cache, the resolver must query the authoritative server
3. While the resolver waits for the real answer, flood it with forged responses claiming to be from the authoritative server
4. Include a poisoned authority section in the forged response: "The nameserver for example.com is now evil-ns.attacker.com"
5. If any forged response matches the transaction ID, the entire domain is hijacked

The brilliance was using random subdomains to bypass cache TTL — you can make the resolver issue queries on demand, giving you unlimited attempts. The fix was source port randomization (adding ~16 bits of entropy, making the total ~32 bits), but the fundamental lack of authentication in DNS wasn't addressed until DNSSEC. DNSSEC adds cryptographic signatures to DNS records, allowing resolvers to verify that responses haven't been forged. However, DNSSEC adoption remains incomplete — as of 2025, roughly 30% of domains have DNSSEC enabled.

HTTP-Based Attacks

HTTP is the application protocol for the web, and it is the vector for the most common web vulnerabilities. Rather than listing them all, here is the attack flow that an actual attacker follows:

flowchart TD
    RECON["Reconnaissance<br/>nmap, subfinder, nuclei"] --> ENUM["Enumerate endpoints<br/>gobuster, ffuf, API fuzzing"]
    ENUM --> VULN{"Vulnerability<br/>found?"}
    VULN -->|"SQL Injection"| SQLI["Extract database<br/>via UNION or blind injection"]
    VULN -->|"XSS"| XSS["Steal session tokens<br/>via JavaScript injection"]
    VULN -->|"SSRF"| SSRF["Access internal services<br/>via server-side requests"]
    VULN -->|"Auth Bypass"| AUTH["Access admin panels<br/>or other users' data"]
    VULN -->|"File Upload"| UPLOAD["Upload web shell<br/>gain command execution"]

    SQLI --> LATERAL["Lateral movement<br/>Credentials in DB, pivot to internal"]
    XSS --> LATERAL
    SSRF --> LATERAL
    AUTH --> LATERAL
    UPLOAD --> LATERAL

    LATERAL --> PERSIST["Persistence<br/>Backdoor, cron job, SSH key"]
    PERSIST --> EXFIL["Data exfiltration<br/>DNS tunneling, HTTPS to C2"]

    style RECON fill:#3182ce,color:#fff
    style EXFIL fill:#e53e3e,color:#fff

Using parameterized queries everywhere is a good start for SQL injection prevention. But do you also use parameterized queries in your admin scripts? Your data migration tools? Your one-off debugging queries? SQL injection does not just happen in web endpoints. And it is not the only application-layer threat. SSRF (Server-Side Request Forgery) has become the new SQL injection in cloud environments. The 2019 Capital One breach used SSRF to access AWS metadata endpoints and exfiltrate 100 million customer records.

Practical Network Reconnaissance

Here is how an attacker maps your network attack surface. These are the same tools that security professionals use for legitimate assessment.

# TCP SYN scan of a target (most common port scan type)
# -sS: SYN scan (stealthy, doesn't complete handshake)
# -sV: Version detection
# -O: OS detection
# -p-: All 65535 ports
$ sudo nmap -sS -sV -O -p- target.example.com

# Quick scan of common ports with script scanning
$ nmap -F -sC target.example.com

# UDP scan (slower, but finds services like DNS, SNMP, NTP)
$ sudo nmap -sU --top-ports 100 target.example.com

# Scan a network range for live hosts (ping sweep)
$ nmap -sn 192.168.1.0/24

# Service enumeration with version detection and default scripts
$ nmap -sV -sC -p 22,80,443,3306,5432,6379,8080,8443,9200 target.example.com

# Vulnerability scanning with NSE scripts
$ nmap --script vuln -p 443 target.example.com

# SSL/TLS configuration check
$ nmap --script ssl-enum-ciphers -p 443 target.example.com

You should absolutely run nmap against your own infrastructure. If you do not know your own attack surface, you cannot defend it. Run regular port scans against your public-facing infrastructure. Compare the results to what you expect. Any unexpected open ports are either misconfigurations or compromises. At a minimum, do this monthly. Better yet, automate it: run nmap from an external vantage point in CI/CD and alert on changes.

Never run nmap against systems you don't own or have explicit authorization to test. Port scanning without permission can violate computer fraud laws (CFAA in the US, Computer Misuse Act in the UK). Always get written authorization before performing security assessments, even against your own company's systems — legal and compliance teams need to be in the loop. This written authorization is called a "rules of engagement" document and should specify: target IP ranges, allowed scan types, time windows, and escalation procedures.

Packet Encapsulation: How Data Wraps at Each Layer

Understanding encapsulation is essential for analyzing captures and understanding where security controls operate.

graph LR
    subgraph APP["Application Layer"]
        HTTP["HTTP Request<br/>GET /users HTTP/1.1<br/>Host: api.example.com"]
    end

    subgraph TLS["TLS Layer"]
        TLSR["TLS Record<br/>Content Type | Version | Length<br/>| Encrypted Payload | Auth Tag |"]
    end

    subgraph TCP["Transport Layer"]
        TCPS["TCP Segment<br/>Src Port | Dst Port | Seq# | Ack#<br/>| Flags | Window | Checksum |<br/>| TLS Record |"]
    end

    subgraph IP["Network Layer"]
        IPS["IP Packet<br/>Version | IHL | DSCP | Total Length<br/>| TTL | Protocol | Checksum<br/>| Src IP | Dst IP |<br/>| TCP Segment |"]
    end

    subgraph ETH["Data Link Layer"]
        ETHS["Ethernet Frame<br/>Dst MAC | Src MAC | EtherType<br/>| IP Packet |<br/>| FCS |"]
    end

    HTTP --> TLS --> TCP --> IP --> ETH

    style APP fill:#e53e3e,color:#fff
    style TLS fill:#dd6b20,color:#fff
    style TCP fill:#38a169,color:#fff
    style IP fill:#3182ce,color:#fff
    style ETH fill:#805ad5,color:#fff

Each layer adds its own header (and sometimes trailer). When a network capture tool like tcpdump or Wireshark captures a packet, it captures the entire frame -- all layers. The tool then dissects each layer's header to display the information.

Key security implications of encapsulation:

  • A firewall operating at Layer 3-4 sees IP addresses and port numbers but cannot inspect the application payload (if encrypted)
  • A WAF operating at Layer 7 can inspect HTTP content but requires TLS termination to see encrypted payloads
  • TLS encrypts from Layer 6 upward -- everything below (TCP headers, IP headers, Ethernet headers) remains visible to network observers
  • This is why metadata analysis works -- even with TLS, an observer can see source/destination IPs, packet sizes, timing patterns, and SNI hostname

Packet Capture: Seeing the Traffic

The single most valuable skill in network security is being able to capture and analyze network traffic.

# Capture all traffic on an interface
$ sudo tcpdump -i en0

# Capture only TCP traffic on port 443 (HTTPS)
$ sudo tcpdump -i en0 'tcp port 443'

# Capture DNS queries and responses
$ sudo tcpdump -i en0 'udp port 53' -vv
# -vv shows decoded DNS query names and response records

# Capture and save to a file (for later analysis in Wireshark)
$ sudo tcpdump -i en0 -w capture.pcap

# Show packet contents in ASCII (useful for unencrypted HTTP)
$ sudo tcpdump -i en0 -A 'tcp port 80'

# Show packet contents in hex and ASCII
$ sudo tcpdump -i en0 -XX 'tcp port 80'

# Capture only packets from a specific host
$ sudo tcpdump -i en0 host 192.168.1.100

# Capture SYN packets only (detect port scans)
$ sudo tcpdump -i en0 'tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) == 0'

# Capture packets with specific TCP flags (RST — detect injection)
$ sudo tcpdump -i en0 'tcp[tcpflags] & (tcp-rst) != 0'

# Capture ICMP (ping, traceroute, redirects)
$ sudo tcpdump -i en0 icmp

# Capture the first 200 bytes of each packet (headers only)
$ sudo tcpdump -i en0 -s 200 -c 100 -w sample.pcap

What is the difference between tcpdump and Wireshark? tcpdump is command-line, lightweight, and available on virtually every Unix system. It is what you use on servers, in scripts, and for quick captures. Wireshark is a GUI tool with powerful protocol dissection, filtering, and visualization. You typically capture with tcpdump and analyze with Wireshark. They use the same pcap file format. There is also tshark, which is Wireshark's command-line version with Wireshark's protocol dissectors but no GUI -- useful for automated analysis.

Capture a TLS handshake and see what's visible to a network observer:

```bash
# Terminal 1: Start capture
sudo tcpdump -i en0 -w /tmp/tls_test.pcap 'host example.com'

# Terminal 2: Generate some traffic
curl -v https://example.com

# Terminal 1: Stop capture with Ctrl-C

# Open in Wireshark
wireshark /tmp/tls_test.pcap

In Wireshark, apply these filters and observe what's visible:

  • dns — The DNS query for example.com is in plaintext (the observer knows which site you're visiting)
  • tcp.flags.syn == 1 — The TCP SYN reveals the destination IP and port
  • tls.handshake.type == 1 — The ClientHello reveals the SNI hostname (in plaintext!)
  • tls.handshake.type == 2 — The ServerHello reveals the selected cipher suite
  • tls.record.content_type == 23 — Application data records are encrypted (observer sees only ciphertext)

Key insight: TLS protects the content of your communication, but metadata (who you're talking to, when, how much data) remains visible. This is why encrypted DNS (DoH/DoT) and Encrypted Client Hello (ECH) are being developed.


---

## Putting It All Together: A Packet's Full Journey

Let's trace an HTTPS request to `api.example.com` through every layer, noting the security-relevant events at each step.

```mermaid
flowchart TD
    subgraph L7_APP["Layer 7: Application"]
        A1["Browser constructs HTTP request<br/>GET /users HTTP/1.1<br/>Host: api.ourcompany.com<br/>Cookie: session=eyJ..."]
        A1R["RISKS: Cookie theft, injection,<br/>API abuse, SSRF"]
    end

    subgraph DNS_RES["DNS Resolution"]
        D1["Browser queries DNS<br/>for api.ourcompany.com"]
        D1R["RISKS: DNS query unencrypted,<br/>response can be spoofed,<br/>ISP can log/redirect"]
    end

    subgraph L6_TLS["Layer 6: TLS Handshake"]
        T1["ClientHello → ServerHello →<br/>Certificate → KeyExchange →<br/>Finished → Encrypted channel"]
        T1R["RISKS: Downgrade attack,<br/>cert validation bypass,<br/>SSL stripping"]
    end

    subgraph L4_TCP["Layer 4: TCP"]
        TC1["SYN → SYN-ACK → ACK<br/>Three-way handshake"]
        TC1R["RISKS: SYN flood,<br/>RST injection,<br/>session hijacking"]
    end

    subgraph L3_IP["Layer 3: IP Routing"]
        I1["IP packet routed through<br/>multiple hops via BGP"]
        I1R["RISKS: BGP hijack,<br/>IP spoofing,<br/>ICMP redirect"]
    end

    subgraph L2_ETH["Layer 2: Ethernet"]
        E1["ARP resolves gateway MAC<br/>Ethernet frame constructed"]
        E1R["RISKS: ARP spoofing,<br/>VLAN hopping,<br/>MAC flooding"]
    end

    subgraph L1_PHY["Layer 1: Physical"]
        P1["Electrical/optical/radio<br/>signals on the wire"]
        P1R["RISKS: Wiretapping,<br/>Wi-Fi sniffing,<br/>rogue AP"]
    end

    L7_APP --> DNS_RES --> L6_TLS --> L4_TCP --> L3_IP --> L2_ETH --> L1_PHY

That is a lot of risk for a single HTTP request. And that is exactly why defense in depth exists. No single layer is responsible for security. TLS handles confidentiality and integrity at the presentation/transport level. DNSSEC handles DNS integrity. Network segmentation and access controls handle layer 2-3 security. Application-level controls handle layer 7. Each layer compensates for the weaknesses of the others.

The critical takeaway: if you only secure one layer, secure the application layer (layer 7) because that is where most breaches occur. But if you can secure two, add TLS (layer 6). Three? Add network segmentation (layer 2-3). Real security comes from layering all of them.


What You've Learned

This chapter walked through every layer of the network stack with a security lens:

  • Physical layer attacks include wiretapping, signal jamming, and rogue device insertion. Wi-Fi security has evolved from WEP (broken) through WPA2 (KRACK vulnerability) to WPA3 (current recommendation). Defense relies on physical security and encrypted upper layers.
  • Data link layer attacks include ARP spoofing (becoming a man-in-the-middle on the local network), MAC flooding (turning a switch into a hub), and VLAN hopping (escaping network segmentation). Defenses include DAI, port security, 802.1X, and disabling DTP.
  • Network layer attacks include IP spoofing (used in amplification DDoS), BGP hijacking (redirecting internet routing), and ICMP abuse. Defenses include ingress filtering (BCP38), RPKI, and ICMP hardening.
  • Transport layer attacks include SYN floods (exhausting server connection tables), TCP reset injection (the Great Firewall uses this), and UDP amplification (Memcached, NTP, DNS). Defenses include SYN cookies, randomized sequence numbers, and blocking amplification-capable services from the internet.
  • Session/presentation layer attacks include session hijacking, session fixation, SSL stripping, and TLS downgrade attacks. Defenses include HSTS (with preloading), secure cookie flags, and session regeneration after authentication.
  • Application layer attacks include SQL injection, XSS, SSRF, and DNS spoofing. This is where the majority of breaches occur. Defenses include input validation, parameterized queries, CSP headers, and DNSSEC.
  • Packet encapsulation means that each layer adds headers visible to observers. TLS encrypts application data but leaves network metadata visible.
  • tcpdump and nmap are essential tools for understanding your network's behavior and attack surface. Regular self-assessment is a security practice, not a one-time event.

Now that you understand where attacks happen, the next few chapters teach you the cryptographic tools that defend against them. The most fundamental question: how do you keep a secret when you have to send it across an untrusted network? The answer is encryption -- but it is more nuanced than you might think.