TExcelTAD

The IPv4 Header Byte by Byte

Firewalls filter on it, intrusion detection systems reassemble by it, and attackers have spent decades bending it: the IPv4 header is twenty bytes that every packet on the Internet carries. Knowing each field lets you answer questions that tools sometimes get wrong: is this source address even possible here? Was this packet fragmented on purpose? Does the TTL fit the host that supposedly sent it? The header is introduced in IPv4 Packets; this lesson parses it from the capture, verifies the checksum, and builds a sanity checker of the kind sensors use.

The layout

08162431 ver IHL DSCP / ECN total length identification flags fragment offset TTL protocol header checksum source address destination address 20 bytes without options (IHL = 5 words)
Field Security relevance
IHL header length in 32-bit words; > 5 means IP options, which are rare today and often dropped
total length must match what was received; mismatches indicate crafted or truncated packets
identification, flags, fragment offset fragmentation; overlapping or tiny fragments have been used to slip past filters
TTL decremented by every router; its value hints at the sender's OS and distance
protocol 1 ICMP, 6 TCP, 17 UDP, 47 GRE, 50 ESP, 51 AH
checksum covers the header only; recomputed at every hop
source address not authenticated; anyone can write any value

Parsing the POST packet

These are the first 20 bytes of the IP packet that carries the login form in $SAMPLES/pcap/http.pcap (from the tcpdump -X dump of that packet).

python · try it yourself
import struct, ipaddress

hdr = bytes.fromhex("450000d51000000040065601" "0a0a0005" "0a0a000a")

def checksum(data):
    s = 0
    for (w,) in struct.iter_unpack("!H", data):
        s += w
    while s >> 16:
        s = (s & 0xFFFF) + (s >> 16)      # fold the carries back in
    return ~s & 0xFFFF

v_ihl, tos, total, ident, flags_frag, ttl, proto, csum, src, dst = struct.unpack("!BBHHHBBH4s4s", hdr)
print("version", v_ihl >> 4, " IHL", v_ihl & 15, "words =", (v_ihl & 15) * 4, "bytes")
print("total length", total, " id", hex(ident), " TTL", ttl, " protocol", proto)
print("flags: reserved", flags_frag >> 15, " DF", (flags_frag >> 14) & 1, " MF", (flags_frag >> 13) & 1,
      " offset", (flags_frag & 0x1FFF) * 8)
print("src", ipaddress.IPv4Address(src), " dst", ipaddress.IPv4Address(dst))
print("checksum in packet", hex(csum), " over the whole header:", hex(checksum(hdr)), "(0 = valid)")
zeroed = hdr[:10] + b"\0\0" + hdr[12:]
print("recomputed with the field zeroed:", hex(checksum(zeroed)))
version 4  IHL 5 words = 20 bytes
total length 213  id 0x1000  TTL 64  protocol 6
flags: reserved 0  DF 0  MF 0  offset 0
src 10.10.0.5  dst 10.10.0.10
checksum in packet 0x5601  over the whole header: 0x0 (0 = valid)
recomputed with the field zeroed: 0x5601

The checksum is the ones' complement of the ones' complement sum of all 16-bit words. Summing a correct header including its checksum gives 0xffff, whose complement is 0: that is how receivers check it in one pass.

A header sanity checker

Sensors and firewalls apply rules like the ones below before anything else. The packets are synthetic variants of the one above: a valid one, a spoofed private source arriving on the Internet side, a tiny first fragment, an overlapping fragment and one with the reserved bit set.

python · try it yourself
import struct, ipaddress

def checksum(data):
    s = sum(w for (w,) in struct.iter_unpack("!H", data))
    while s >> 16:
        s = (s & 0xFFFF) + (s >> 16)
    return ~s & 0xFFFF

def build(src, dst, total=40, ident=0x1000, flags=0, offset=0, ttl=64, proto=6):
    h = struct.pack("!BBHHHBBH4s4s", 0x45, 0, total, ident, (flags << 13) | (offset // 8),
                    ttl, proto, 0, ipaddress.IPv4Address(src).packed, ipaddress.IPv4Address(dst).packed)
    return h[:10] + struct.pack("!H", checksum(h)) + h[12:]

BOGONS = [ipaddress.ip_network(n) for n in ("0.0.0.0/8", "10.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16",
                                             "172.16.0.0/12", "192.168.0.0/16", "224.0.0.0/4", "240.0.0.0/4")]

def check(h, outside):
    v_ihl, _, total, ident, ff, ttl, proto, _, src, dst = struct.unpack("!BBHHHBBH4s4s", h[:20])
    src = ipaddress.IPv4Address(src)
    problems = []
    if checksum(h[:20]) != 0:                   problems.append("bad checksum")
    if ff >> 15:                                problems.append("reserved bit set")
    mf, off = (ff >> 13) & 1, (ff & 0x1FFF) * 8
    if mf and total - 20 < 16 and off == 0:     problems.append("tiny first fragment")
    if off and off < 16:                        problems.append("fragment overlaps the TCP header")
    if outside and any(src in n for n in BOGONS): problems.append(f"bogon source {src} on the outside interface")
    return problems or ["ok"]

samples = [
    ("normal",            build("203.0.113.40", "198.51.100.10"), True),
    ("spoofed private",   build("10.10.0.5", "198.51.100.10"), True),
    ("tiny fragment",     build("203.0.113.40", "198.51.100.10", total=28, flags=1), True),
    ("overlap fragment",  build("203.0.113.40", "198.51.100.10", offset=8), True),
    ("reserved bit",      build("203.0.113.40", "198.51.100.10", flags=4), True),
]
bad = bytearray(samples[0][1]); bad[8] = 1        # change TTL without fixing the checksum
samples.append(("corrupted", bytes(bad), True))
for name, pkt, outside in samples:
    print(f"{name:<17}", ", ".join(check(pkt, outside)))
normal            ok
spoofed private   bogon source 10.10.0.5 on the outside interface
tiny fragment     tiny first fragment
overlap fragment  fragment overlaps the TCP header
reserved bit      reserved bit set
corrupted         bad checksum

Attacks on the header and their detection

  • Source spoofing. Nothing checks the source field, so floods and reflection attacks forge it (see Routing and Spoofed Sources). Detection: bogon sources on Internet-facing interfaces, sources that can't arrive on that interface, TTLs inconsistent with the claimed sender. Fix: ingress filtering (BCP 38) and unicast reverse-path forwarding.
  • Fragmentation tricks. A filter that checks TCP ports only in the first fragment can be bypassed if the TCP header is split across fragments (tiny fragments) or rewritten by a later overlapping fragment (RFC 1858, RFC 3128). Different operating systems also reassemble overlaps differently, so an IDS may see other bytes than the target. Detection: IDS fragment rules and reassembly normalisation (Suricata, Zeek both flag overlaps). Fix: drop fragments with offset 1 (the overlap case) and first fragments too short to hold the transport header, as RFC 1858 recommends, and normalise at the edge.
  • TTL-based evasion. Packets with a TTL that expires between the IDS and the target are seen by the IDS but never arrive. Normalisers raise low TTLs; analysts compare TTL distributions per source.

TTL as a fingerprint

Common initial TTLs are 64 (Linux, macOS, Android), 128 (Windows) and 255 (many network devices). A packet that arrives with TTL 119 most likely started at 128 and crossed 9 routers. In a capture, the TTL of each source is a quick consistency check:

bash · try it yourself
tshark -r $SAMPLES/pcap/http.pcap -T fields -e ip.src -e ip.ttl -e ip.flags.df | sort | uniq -c
      8 10.10.0.10	64	False
     12 10.10.0.5	64	False

All packets in the lab capture start at 64 on the same subnet (no router between), so neither side has decremented anything. A "Windows" host that suddenly sends with TTL 64, or a single source whose TTL jumps, is worth a second look.

Pitfalls

  • Trusting the source address as identity. It is only as trustworthy as the filtering upstream.
  • Forgetting the IHL: options shift the transport header. Always slice at IHL * 4, not at 20.
  • Validating checksums on outgoing traffic captured on the sending host: with checksum offloading, the NIC fills them in later and the capture shows them as wrong.

Practice

1. A header starts 46 00 …. Where does the TCP header begin?

IHL = 6 words = 24 bytes: there are 4 bytes of IP options, so the TCP header starts at offset 24.

2. Why must every router recompute the header checksum?

It decrements the TTL, which changes the header. (IPv6 removed the header checksum for exactly this reason, relying on link-layer and transport checksums.)

3. A packet arrives on your Internet link with source 192.168.1.20 and TTL 52. What can you conclude?

The source is private (RFC 1918) and can't legitimately arrive from the Internet, so it is spoofed or leaked by a misconfigured network. Drop it at the edge (ingress filtering) and, if they are many, investigate a reflection or flood.

Test yourself

In the POST packet, what does the first byte 0x45 mean?

  1. Version 4, header length 5 words (20 bytes)
  2. TTL 69
  3. Protocol 0x45
  4. Version 5, length 4

What does the IPv4 header checksum protect?

  1. The whole packet
  2. Only the header
  3. Only the payload
  4. The Ethernet frame

Why do filters drop fragments with fragment offset 1 (8 bytes)?

  1. They are always corrupted
  2. They can overwrite the TCP header of the first fragment, bypassing port checks
  3. They carry IPv6
  4. They have no checksum

A packet arrives with TTL 120. What was the most likely initial TTL?

  1. 64
  2. 128
  3. 255
  4. 32