TExcelTAD

The TCP Header and Its Flags

Six bits in the TCP header decide most of what a firewall does with a packet. A packet with only SYN set opens a connection; one with SYN and FIN set at once is nonsense that no normal stack sends, and therefore a fingerprint of a scanner or an evasion attempt. Ports, sequence numbers, window and options carry more clues. This lesson parses a real TCP header from the sample capture, verifies its checksum the way the receiver does, and then classifies flag combinations as a sensor would. TCP's fields are introduced in TCP Segments.

The layout

Offset Size Field In the login packet
0 2 source port 50414
2 2 destination port 80
4 4 sequence number 2000001
8 4 acknowledgement number 4000001
12 4 bits data offset (header length in 32-bit words) 5 = 20 bytes
13 8 bits flags: CWR ECE URG ACK PSH RST SYN FIN 0x18 = ACK + PSH
14 2 window 502
16 2 checksum (pseudo-header + header + data) 0x93d8
18 2 urgent pointer 0
20 0–40 options (MSS, window scale, SACK, timestamps) none

Parsing two segments

The SYN that opened the login connection carries one option (MSS); the login request itself carries 173 bytes of HTTP. The payload is rebuilt from its text, so you can read it; the header bytes are copied from $SAMPLES/pcap/http.pcap. TCP's checksum also covers a pseudo-header (source and destination IP, protocol 6, TCP length) so that a segment delivered to the wrong address fails the check.

python · try it yourself
import struct, ipaddress

FLAGS = "FIN SYN RST PSH ACK URG ECE CWR".split()

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

def parse(seg):
    sport, dport, seq, ack, off_flags, win, csum, urg = struct.unpack("!HHIIHHHH", seg[:20])
    hlen = (off_flags >> 12) * 4
    flags = [n for i, n in enumerate(FLAGS) if off_flags & (1 << i)]
    opts, i = [], 20
    while i < hlen:
        kind = seg[i]
        if kind == 0: break
        if kind == 1: i += 1; continue
        length = seg[i + 1]
        if kind == 2: opts.append(("MSS", struct.unpack("!H", seg[i + 2:i + 4])[0]))
        else: opts.append((kind, seg[i + 2:i + length].hex()))
        i += length
    return dict(sport=sport, dport=dport, seq=seq, ack=ack, hlen=hlen, flags="+".join(flags),
                win=win, csum=hex(csum), opts=opts, data=len(seg) - hlen)

def tcp_ok(src, dst, seg):
    pseudo = ipaddress.IPv4Address(src).packed + ipaddress.IPv4Address(dst).packed + struct.pack("!BBH", 0, 6, len(seg))
    return checksum(pseudo + seg) == 0

syn = bytes.fromhex("c4ee0050001e8480000000006002faf03f360000020405b4")
body = (b"POST /login HTTP/1.1\r\nHost: www.lab.test\r\nUser-Agent: lab-client/1.0\r\n"
        b"Content-Type: application/x-www-form-urlencoded\r\nContent-Length: 32\r\n\r\n"
        b"user=alice&password=lab-only-123")
post = bytes.fromhex("c4ee0050001e8481003d0901501801f693d80000") + body

for name, seg in [("SYN", syn), ("POST", post)]:
    print(name, parse(seg))
    print("   checksum valid:", tcp_ok("10.10.0.5", "10.10.0.10", seg),
          "| delivered to 10.10.0.11 instead:", tcp_ok("10.10.0.5", "10.10.0.11", seg))
SYN {'sport': 50414, 'dport': 80, 'seq': 2000000, 'ack': 0, 'hlen': 24, 'flags': 'SYN', 'win': 64240, 'csum': '0x3f36', 'opts': [('MSS', 1460)], 'data': 0}
   checksum valid: True | delivered to 10.10.0.11 instead: False
POST {'sport': 50414, 'dport': 80, 'seq': 2000001, 'ack': 4000001, 'hlen': 20, 'flags': 'PSH+ACK', 'win': 502, 'csum': '0x93d8', 'opts': [], 'data': 173}
   checksum valid: True | delivered to 10.10.0.11 instead: False

The SYN's header is 24 bytes (data offset 6) because of the 4-byte MSS option; its sequence number 2000000 is the client's initial sequence number (ISN), and the POST starts one higher because the SYN itself consumes one number. Changing the destination address in the pseudo-header breaks the checksum, as intended.

Flags as a fingerprint

Normal TCP uses a handful of combinations: SYN, SYN+ACK, ACK, PSH+ACK, FIN+ACK, RST, RST+ACK. Anything else is either a scanner probing how a host reacts (Nmap's NULL, FIN and Xmas scans rely on RFC 793 behaviour of closed ports answering with RST) or an attempt to confuse a filter. The classifier below labels combinations the way IDS rules do.

python · try it yourself
F = dict(FIN=1, SYN=2, RST=4, PSH=8, ACK=16, URG=32)

def label(flags):
    names = [n for n, b in F.items() if flags & b]
    combo = "+".join(names) or "none"
    if flags == 0:                          return combo, "NULL scan probe"
    if flags == F["FIN"]:                   return combo, "FIN scan probe (FIN without ACK)"
    if flags == F["FIN"] | F["PSH"] | F["URG"]: return combo, "Xmas scan probe"
    if flags & F["SYN"] and flags & F["FIN"]: return combo, "invalid: SYN and FIN together"
    if flags & F["SYN"] and flags & F["RST"]: return combo, "invalid: SYN and RST together"
    if flags in (F["SYN"], F["SYN"] | F["ACK"], F["ACK"], F["PSH"] | F["ACK"],
                 F["FIN"] | F["ACK"], F["RST"], F["RST"] | F["ACK"]):
        return combo, "normal"
    return combo, "unusual"

for f in [0x02, 0x12, 0x18, 0x11, 0x00, 0x01, 0x29, 0x03, 0x06, 0x20]:
    combo, verdict = label(f)
    print(f"0x{f:02x}  {combo:<16} {verdict}")
0x02  SYN              normal
0x12  SYN+ACK          normal
0x18  PSH+ACK          normal
0x11  FIN+ACK          normal
0x00  none             NULL scan probe
0x01  FIN              FIN scan probe (FIN without ACK)
0x29  FIN+PSH+URG      Xmas scan probe
0x03  FIN+SYN          invalid: SYN and FIN together
0x06  SYN+RST          invalid: SYN and RST together
0x20  URG              unusual

Filtering by flags in a capture

BPF can test the flag byte directly: tcp[tcpflags] is byte 13 of the TCP header, and named masks such as tcp-syn and tcp-ack make filters readable. These lines count connection attempts (SYN without ACK), list the connection teardowns (-S prints absolute sequence numbers) and check for an impossible combination in the sample capture:

bash · try it yourself
cd $SAMPLES/pcap
echo -n "SYN without ACK: "
tcpdump -nn -r http.pcap 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn' 2>/dev/null | wc -l
echo "FIN segments:"
tcpdump -nn -S -r http.pcap 'tcp[tcpflags] & tcp-fin != 0' 2>/dev/null
echo -n "SYN+FIN (should be 0): "
tcpdump -nn -r http.pcap 'tcp[tcpflags] & (tcp-syn|tcp-fin) == (tcp-syn|tcp-fin)' 2>/dev/null | wc -l
SYN without ACK: 2
FIN segments:
10:00:00.001750 IP 10.10.0.5.50412 > 10.10.0.10.80: Flags [F.], seq 1000080, ack 3000134, win 501, length 0
10:00:00.002000 IP 10.10.0.10.80 > 10.10.0.5.50412: Flags [F.], seq 3000134, ack 1000081, win 509, length 0
10:00:01.001750 IP 10.10.0.5.50414 > 10.10.0.10.80: Flags [F.], seq 2000174, ack 4000115, win 501, length 0
10:00:01.002000 IP 10.10.0.10.80 > 10.10.0.5.50414: Flags [F.], seq 4000115, ack 2000175, win 509, length 0
SYN+FIN (should be 0): 0

How it is detected

  • Invalid or scanner flag combinations (NULL, FIN-only, Xmas, SYN+FIN): signature rules in Snort and Suricata, and Zeek's weird.log.
  • Many SYNs, few completed handshakes: scans and SYN floods (next lessons).
  • RST storms: a host answering many probes to closed ports, or someone injecting resets into other people's connections (RST injection needs a sequence number inside the receive window, which RFC 5961 made much harder to guess).
  • Options fingerprints: the order of options, window size and TTL identify operating systems (passive fingerprinting with tools like p0f); a mismatch with the claimed OS is a clue.

How it is prevented

  • Stateful filtering: a firewall that tracks connections drops packets that don't fit any state. In nftables, ct state invalid drop handles invalid combinations, and only SYN may create a new connection (tcp flags & (fin|syn|rst|ack) != syn ct state new drop).
  • Normalisation at the edge (scrubbing): reject reserved bits, impossible flag sets and overlapping segments so that the IDS and the end host see the same thing.
  • Random initial sequence numbers (RFC 6528) and RFC 5961's challenge ACKs, both default in modern stacks, defeat blind injection.

Pitfalls

  • Reading tcp[13] without masking. tcp[13] == 2 misses SYNs with the ECN bits set (0xc2); use tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn.
  • Forgetting the data offset when locating the payload: options make the header longer than 20 bytes.
  • Validating TCP checksums of traffic captured on the sending host, where checksum offload leaves them unfilled.

Practice

1. The flag byte is 0x14. What is it, and when is it sent?

0x14 = ACK (0x10) + RST (0x04). A host sends RST+ACK when a SYN arrives for a closed port, among other cases. It is what a connect scan records as "closed".

2. Why does the POST's sequence number start at 2000001 when the SYN had 2000000?

The SYN flag consumes one sequence number. The first data byte is therefore ISN + 1, and the POST's 173 bytes occupy 2000001 to 2000173.

3. Write a tcpdump filter for SYN-ACKs only.

'tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)'. In the sample capture it matches the two server answers.

Test yourself

What does the flag byte 0x12 mean?

  1. SYN
  2. SYN+ACK
  3. PSH+ACK
  4. FIN+ACK

Why does the TCP checksum include a pseudo-header with the IP addresses?

  1. To encrypt the addresses
  2. So a segment delivered to the wrong host or protocol fails the check
  3. Because TCP has no ports
  4. To compress the header

Which flag combination is never sent by a normal TCP stack?

  1. FIN+ACK
  2. RST
  3. SYN+FIN
  4. PSH+ACK

Why is tcp[13] == 2 a poor filter for SYN packets?

  1. Byte 13 is the window
  2. It misses SYNs that also have ECN bits set
  3. It matches all ACKs
  4. tcpdump can't index TCP bytes