# Stateful 4-Tuple TCP Streams, Sequence Anomalies & SCTP

> **FrameAssembly v3.2.2** · Anthology 03 (Layer 4 · 14 Recipes) · MIT License · Canonical URL: https://frameassembly-lang.dev/docs/examples/tcp-handshakes-anomalies

Automatic 4-tuple `seq` and `acknum` progression, RFC 7323 TCP options (`mss`, `wscale`, `sackperm`, `tsval`/`tsecr`), deliberate retransmissions, ZeroWindow stalls, abnormal scan flags, and Castagnoli CRC-32c SCTP.

## Key Wire & Syntax Takeaways

- Set `srcport` and `dstport` once on the opening `tcp syn`; `<-` replies swap ports automatically and payload frames advance `seq` by byte length.
- Explicit `seq <u32>` or `acknum <u32>` overrides re-anchor connection state to reproduce RTO retransmissions, out-of-order segments, or ZeroWindow stalls.
- `sctp` computes hardware-polynomial Castagnoli CRC-32c checksums across 4-way cookie handshakes, DATA chunks, heartbeats, and shutdowns.

## 03.01 · Full TCP Lifecycle: RFC 7323 Window Scale, SACK, Timestamps & 4-Way FIN (`tcp_rfc7323_full_lifecycle.frasm`)

Demonstrates a complete TCP connection from SYN option negotiation (mss, wscale, sackperm, tsval/tsecr) through bidirectional payload transfer and clean 4-way FIN-ACK close.

- **Protocols:** `tcp` (9 Ethernet frames)
- **Wire Behavior:** FrameAssembly advances each direction seq by +1 on syn, +payload_len on data segments, and +1 on fin automatically.
- **Wireshark Filter:** `tcp.port == 8443`
- **CLI Build:** `frameassembly tcp_rfc7323_full_lifecycle.frasm`

```frameassembly
host app_client { ip 10.30.1.15 }
host api_srv    { ip 10.30.2.80 }

compile {
    app_client -> api_srv tcp syn srcport 52843 dstport 8443 win 65535 mss 1460 wscale 7 sackperm tsval 1000 tsecr 0 wait 1ms
    app_client <- api_srv tcp syn ack win 65535 mss 1460 wscale 7 sackperm tsval 4000 tsecr 1000 wait 1ms
    app_client -> api_srv tcp ack tsval 1001 tsecr 4000 wait 2ms
    app_client -> api_srv tcp psh ack tsval 1003 tsecr 4000 payload "PING-API-V1" wait 2ms
    app_client <- api_srv tcp psh ack tsval 4002 tsecr 1003 payload "PONG-API-OK" wait 2ms
    app_client -> api_srv tcp fin ack tsval 1005 tsecr 4002 wait 1ms
    app_client <- api_srv tcp ack tsval 4003 tsecr 1005 wait 1ms
    app_client <- api_srv tcp fin ack tsval 4004 tsecr 1005 wait 1ms
    app_client -> api_srv tcp ack tsval 1006 tsecr 4004
}
```

## 03.02 · Out-of-Order TCP Segment Arrival & Gap Fill for DPI Stream Reassembly (`tcp_out_of_order_reassembly.frasm`)

Deliberately transmits bytes 9..16 (seq 1009) ahead of bytes 1..8 (seq 1001) to verify IDS/IPS TCP stream reassemblers reconstruct split signatures properly.

- **Protocols:** `tcp` (6 Ethernet frames)
- **Wire Behavior:** Explicit seq overrides let you transmit segments out of sequence while keeping checksums valid.
- **Wireshark Filter:** `tcp.analysis.out_of_order || tcp.port == 9090`
- **CLI Build:** `frameassembly tcp_out_of_order_reassembly.frasm`

```frameassembly
host sender { ip 10.40.10.11 }
host sensor { ip 10.40.10.22 }

compile {
    sender -> sensor tcp syn srcport 54090 dstport 9090 seq 1000 win 65535 mss 1460 wait 1ms
    sender <- sensor tcp syn ack seq 5000 acknum 1001 win 65535 mss 1460 wait 1ms
    sender -> sensor tcp ack seq 1001 acknum 5001 wait 1ms
    // Send second 8-byte chunk first (seq 1009), then backfill missing gap (seq 1001)
    sender -> sensor tcp psh ack seq 1009 acknum 5001 payload "CHUNK-02" wait 3ms
    sender -> sensor tcp psh ack seq 1001 acknum 5001 payload "CHUNK-01" wait 2ms
    sender <- sensor tcp ack seq 5001 acknum 1017
}
```

## 03.03 · Dual-Stack IPv4 + IPv6 Stateful TCP Handshake Template (`tcp_dual_stack_template.frasm`)

Validates load-balancer VIP listener readiness across both IPv4 and IPv6 frontends using one parameterized flow(c, s).

- **Protocols:** `tcp` (6 Ethernet frames)
- **Wire Behavior:** Each 4-tuple maintains an independent TCP sequence state table across IPv4 and IPv6 invocations.
- **Wireshark Filter:** `tcp.port == 443`
- **CLI Build:** `frameassembly tcp_dual_stack_template.frasm`

```frameassembly
host edge_c4 { ip 198.51.100.12 }
host vip_s4  { ip 203.0.113.10 }
host edge_c6 { ip 2001:db8:100::12 }
host vip_s6  { ip 2001:db8:200::10 }

flow lb_health_probe(c, s) {
    c -> s tcp syn srcport 53443 dstport 443 win 65535 mss 1440 sackperm wait 1ms
    c <- s tcp syn ack win 65535 mss 1440 sackperm wait 1ms
    c -> s tcp ack wait 1ms
    c -> s tcp fin ack wait 1ms
    c <- s tcp fin ack wait 1ms
    c -> s tcp ack
}

compile {
    lb_health_probe(edge_c4, vip_s4)
    lb_health_probe(edge_c6, vip_s6)
}
```

## 03.04 · Telecom SCTP 4-Way Cookie Handshake, S1AP Data, Heartbeat & Shutdown (`sctp_telecom_4way_lifecycle.frasm`)

Builds a complete RFC 4960 SCTP association on port 36412 (LTE S1AP) with Castagnoli CRC-32c checksums.

- **Protocols:** `sctp` (10 Ethernet frames)
- **Wire Behavior:** Calculates hardware-polynomial SCTP CRC-32c over every INIT, INIT-ACK, COOKIE-ECHO, DATA, SACK, HEARTBEAT, and SHUTDOWN chunk.
- **Wireshark Filter:** `sctp`
- **CLI Build:** `frameassembly sctp_telecom_4way_lifecycle.frasm`

```frameassembly
host enodeb { ip 10.60.1.10 }
host mme_01 { ip 10.60.2.20 }

compile {
    enodeb -> mme_01 sctp init srcport 36412 dstport 36412 vtag 0 tsn 1000 wait 1ms
    enodeb <- mme_01 sctp initack vtag 0x11223344 tsn 2000 wait 1ms
    enodeb -> mme_01 sctp cookieecho vtag 0x11223344 wait 1ms
    enodeb <- mme_01 sctp cookieack vtag 0x55667788 wait 2ms
    enodeb -> mme_01 sctp data vtag 0x11223344 tsn 1000 stream 0 ssn 0 ppid 18 payload "S1SetupRequest" wait 2ms
    enodeb <- mme_01 sctp sack vtag 0x55667788 tsn 1000 wait 10ms
    enodeb -> mme_01 sctp heartbeat vtag 0x11223344 wait 1ms
    enodeb <- mme_01 sctp heartbeatack vtag 0x55667788 wait 2ms
    enodeb -> mme_01 sctp shutdown vtag 0x11223344 wait 1ms
    enodeb <- mme_01 sctp shutdownack vtag 0x55667788
}
```

## 03.05 · Blocked Management SSH Policy (TCP RST + ICMP Admin Prohibited) (`fw_ssh_deny_policy.frasm`)

Simulates a firewall rejecting unauthorized user-VLAN SSH attempts into the out-of-band switch management subnet using both TCP RST-ACK and ICMP Type 3 Code 13.

- **Protocols:** `tcp`, `icmp` (4 Ethernet frames)
- **Wire Behavior:** Great for verifying SIEM alerts on blocked management-plane access and training helpdesk techs to tell the difference between a firewall Reset and a silent drop.
- **Wireshark Filter:** `tcp.port == 22 || icmp.code == 13`
- **CLI Build:** `frameassembly fw_ssh_deny_policy.frasm`

```frameassembly
// User workstation, internal firewall interface, and protected core switch
host user_laptop { ip 10.10.40.85 }
host mgmt_fw     { ip 10.10.40.1 }
host core_sw     { ip 10.99.0.10 }

compile {
    // Attempt #1: Workstation tries TCP 22 (SSH) -> Rejected inline with TCP RST-ACK
    user_laptop -> core_sw tcp syn srcport 53110 dstport 22 win 65535 mss 1460 wait 1ms
    user_laptop <- core_sw tcp rst ack wait 10ms

    // Attempt #2: Workstation retries TCP 22 -> Firewall returns ICMP Admin Prohibited (Type 3, Code 13)
    user_laptop -> core_sw tcp syn srcport 53111 dstport 22 win 65535 mss 1460 wait 2ms
    mgmt_fw -> user_laptop icmp destunreach type 3 code 13
}
```

## 03.06 · TCP SYN Half-Open Port Scan (Ports 22, 80, 443, 3389) (`scan_tcp_syn_ports.frasm`)

Models an Nmap-style -sS half-open port check across SSH (22), HTTP (80), HTTPS (443), and RDP (3389), contrasting open SYN-ACK ports against closed RST-ACK ports.

- **Protocols:** `tcp` (10 Ethernet frames)
- **Wire Behavior:** In a half-open SYN scan, the scanner immediately sends tcp rst after receiving syn ack instead of completing the 3rd handshake packet.
- **Wireshark Filter:** `tcp.flags.syn == 1 || tcp.flags.reset == 1`
- **CLI Build:** `frameassembly scan_tcp_syn_ports.frasm`

```frameassembly
// Vulnerability scanner checking common TCP ports on a Linux web server
host scanner { ip 10.10.99.10 }
host web_srv { ip 10.10.20.40 }

compile {
    // Port 22 (SSH) -> Open: server sends SYN-ACK, scanner tears down with RST
    scanner -> web_srv tcp syn srcport 55001 dstport 22 win 1024 mss 1460 wait 1ms
    scanner <- web_srv tcp syn ack win 65535 mss 1460 wait 1ms
    scanner -> web_srv tcp rst wait 2ms

    // Port 80 (HTTP) -> Closed: server replies immediately with RST-ACK
    scanner -> web_srv tcp syn srcport 55002 dstport 80 win 1024 mss 1460 wait 1ms
    scanner <- web_srv tcp rst ack wait 2ms

    // Port 443 (HTTPS) -> Open: server sends SYN-ACK, scanner tears down with RST
    scanner -> web_srv tcp syn srcport 55003 dstport 443 win 1024 mss 1460 wait 1ms
    scanner <- web_srv tcp syn ack win 65535 mss 1460 wait 1ms
    scanner -> web_srv tcp rst wait 2ms

    // Port 3389 (RDP) -> Closed: server replies with RST-ACK
    scanner -> web_srv tcp syn srcport 55004 dstport 3389 win 1024 mss 1460 wait 1ms
    scanner <- web_srv tcp rst ack
}
```

## 03.07 · TCP Xmas (FIN+PSH+URG), SYN+FIN & Stealth FIN Scan for IDS Validation (`pentest_ids_xmas_scan.frasm`)

Crafts abnormal TCP flag combinations (Xmas FIN+PSH+URG, illegal SYN+FIN, and unsolicited stealth FIN probe) to verify Suricata, Snort, or Zeek scan-detection rules fire in the lab.

- **Protocols:** `tcp` (5 Ethernet frames)
- **Wire Behavior:** Replay against Suricata (suricata -r pentest_ids_xmas_scan.pcap) during purple-team validation without running live scanner binaries on production segments.
- **Wireshark Filter:** `tcp.flags == 0x029 || tcp.flags == 0x003 || tcp.flags == 0x001`
- **CLI Build:** `frameassembly pentest_ids_xmas_scan.frasm`

```frameassembly
// Authorized purple-team host testing IDS/IPS abnormal TCP flag signatures
host red_lab_box { ip 172.18.99.50 }
host dmz_target  { ip 172.18.10.25 }

compile {
    // 1. TCP Xmas Scan: lights up FIN + PSH + URG simultaneously on port 443
    red_lab_box -> dmz_target tcp fin psh urg srcport 56101 dstport 443 win 1024 urgent 0 wait 2ms
    red_lab_box <- dmz_target tcp rst ack wait 4ms

    // 2. Illegal SYN + FIN combination: tests stateless ACL bypass rules on port 80
    red_lab_box -> dmz_target tcp syn fin srcport 56102 dstport 80 win 1024 wait 2ms
    red_lab_box <- dmz_target tcp rst ack wait 4ms

    // 3. TCP FIN Stealth Scan (-sF): unsolicited lone FIN segment with custom seq 5000 on port 22
    red_lab_box -> dmz_target tcp fin srcport 56103 dstport 22 seq 5000 win 1024
}
```

## 03.08 · Application Stall: TCP Zero-Window & Retransmission (`troubleshoot_zero_window.frasm`)

Demonstrates the difference between a network packet drop (manual seq retransmission) and an overloaded server advertising TCP win 0 ("buffer full, pause sending").

- **Protocols:** `tcp`, `http` (7 Ethernet frames)
- **Wire Behavior:** When application teams blame the network for slow transfers, TCP ZeroWindow in Wireshark proves the receiving server paused the sender because its socket buffer filled up.
- **Wireshark Filter:** `tcp.analysis.zero_window || tcp.analysis.retransmission`
- **CLI Build:** `frameassembly troubleshoot_zero_window.frasm`

```frameassembly
// Client uploading report data to a busy backend web server
host client_pc { ip 10.10.15.30 }
host busy_srv  { ip 10.10.80.40 }

compile {
    // 1. Establish TCP connection on port 8080
    client_pc -> busy_srv tcp syn srcport 51800 dstport 8080 win 65535 mss 1460 wait 1ms
    client_pc <- busy_srv tcp syn ack win 65535 mss 1460 wait 1ms
    client_pc -> busy_srv tcp ack wait 1ms

    // 2. Client sends HTTP POST; packet drops on WAN, so client retransmits same seq 1001 after 200ms
    client_pc -> busy_srv http post uri "/ingest" hosthdr "reports.corp.local" body "batch-01-payload" wait 200ms
    client_pc -> busy_srv seq 1001 http post uri "/ingest" hosthdr "reports.corp.local" body "batch-01-payload" wait 2ms

    // 3. Overloaded server ACKs the data with win 0 (TCP ZeroWindow: socket buffer exhausted!)
    client_pc <- busy_srv tcp ack win 0 wait 150ms

    // 4. Server drains buffer and sends Window Update (win 32768) so transfer can resume
    client_pc <- busy_srv tcp ack win 32768
}
```

## 03.09 · Minimal Two-Block TCP & RFC 7323 (`tcp`) Quickstart (`tcp_quickstart.frasm`)

Smallest zero-boilerplate `host` + `compile` capture for Transmission Control Protocol & RFC 7323 Options (IP Proto 6 (Default dstport 80), Dual-Stack IPv4/IPv6).

- **Protocols:** `tcp` (3 Ethernet frames)
- **Wire Behavior:** Tracks 4-tuple `(src_ip, dst_ip, src_port, dst_port)` sequence state starting at `seq 1000`—advancing `seq` by `+1` for `syn`/`fin` and `+payload_len` for data without manual arithmetic.
- **Wireshark Filter:** `tcp`
- **CLI Build:** `frameassembly tcp_quickstart.frasm`

```frameassembly
host client { ip 10.10.1.15 }
host server { ip 10.10.1.80 }

compile {
    client -> server tcp syn srcport 52400 dstport 443 win 65535 mss 1460 wscale 7 sackperm wait 1ms
    client <- server tcp syn ack win 65535 mss 1460 wscale 7 sackperm wait 1ms
    client -> server tcp ack
}
```

## 03.10 · Minimal Two-Block UDP (`udp`) Quickstart (`udp_quickstart.frasm`)

Smallest zero-boilerplate `host` + `compile` capture for User Datagram Protocol (IP Proto 17 (Default dstport 80), Dual-Stack IPv4/IPv6).

- **Protocols:** `udp` (2 Ethernet frames)
- **Wire Behavior:** Computes the 16-bit UDP Length (`8 + payload bytes`) and outer IPv4 Total Length / IPv6 Payload Length automatically.
- **Wireshark Filter:** `udp`
- **CLI Build:** `frameassembly udp_quickstart.frasm`

```frameassembly
host sensor  { ip 10.20.0.15 }
host gateway { ip 10.20.0.1 }

compile {
    sensor -> gateway udp srcport 53100 dstport 9000 payload "ping:seq=1" wait 2ms
    sensor <- gateway udp payload "pong:seq=1"
}
```

## 03.11 · Minimal Two-Block SCTP (CRC-32c) (`sctp`) Quickstart (`sctp_quickstart.frasm`)

Smallest zero-boilerplate `host` + `compile` capture for Stream Control Transmission Protocol (IP Proto 132 (38412 NGAP / 36412 S1AP), Dual-Stack IPv4/IPv6).

- **Protocols:** `sctp` (3 Ethernet frames)
- **Wire Behavior:** Computes the 32-bit reflected Castagnoli CRC-32c checksum across the 12-byte SCTP Common Header and all padded chunk bytes.
- **Wireshark Filter:** `sctp`
- **CLI Build:** `frameassembly sctp_quickstart.frasm`

```frameassembly
host gnb_01 { ip 10.50.1.10 }
host amf_01 { ip 10.50.1.20 }

compile {
    gnb_01 -> amf_01 sctp init srcport 38412 dstport 38412 vtag 0 tsn 1000 wait 1ms
    gnb_01 <- amf_01 sctp initack vtag 0x11223344 tsn 2000 wait 1ms
    gnb_01 -> amf_01 sctp data vtag 0x22334455 tsn 1001 stream 0 ssn 0 ppid 60 hexpayload "0015000900000100"
}
```

## 03.12 · TCP & RFC 7323 (`tcp`): Full Lifecycle: RFC 7323 Handshake, ECN-Capable Data Exchange & Graceful FIN Close (`tcp_rfc7323_lifecycle.frasm`)

Captures a complete 7-packet TCP lifecycle with RFC 7323 timestamps (`tsval`/`tsecr`), selective ACK permission (`sackperm`), payload push (`psh ack`), and 4-way `fin ack` teardown.

- **Protocols:** `tcp` (8 Ethernet frames)
- **Wire Behavior:** Tracks 4-tuple `(src_ip, dst_ip, src_port, dst_port)` sequence state starting at `seq 1000`—advancing `seq` by `+1` for `syn`/`fin` and `+payload_len` for data without manual arithmetic. Remembers `srcport 52400` and `dstport 443` from the opening `syn` so `<-` and `->` follow-up frames swap `443 <-> 52400` automatically.
- **Wireshark Filter:** `tcp`
- **CLI Build:** `frameassembly show tcp_rfc7323_lifecycle.frasm`

```frameassembly
host app_client { ip 172.16.20.10 }
host api_origin { ip 172.16.20.90 }

compile {
    // 1. 3-way handshake negotiating MSS 1460, Window Scale 7, SACK, and Timestamps
    app_client -> api_origin tcp syn srcport 54110 dstport 8443 win 65535 mss 1460 wscale 7 sackperm tsval 1000 tsecr 0 wait 1ms
    app_client <- api_origin tcp syn ack win 65535 mss 1460 wscale 7 sackperm tsval 5000 tsecr 1000 wait 1ms
    app_client -> api_origin tcp ack tsval 1001 tsecr 5000 wait 2ms
    // 2. Bidirectional application payload (seq/acknum advance automatically by byte length)
    app_client -> api_origin tcp psh ack tsval 1003 tsecr 5000 payload "PING /healthz
" wait 2ms
    app_client <- api_origin tcp psh ack tsval 5002 tsecr 1003 payload "200 OK
" wait 3ms
    // 3. Clean 3-packet FIN/ACK session close
    app_client -> api_origin tcp fin ack tsval 1006 tsecr 5002 wait 1ms
    app_client <- api_origin tcp fin ack tsval 5003 tsecr 1007 wait 1ms
    app_client -> api_origin tcp ack tsval 1007 tsecr 5004
}
```

## 03.13 · UDP (`udp`): Dual-Stack Custom Binary Telemetry Feed with QoS Marking (`udp_dualstack_binary.frasm`)

Uses a reusable `flow(tx, rx)` template to emit identical hex-encoded binary UDP frames marked `dscp 46` (EF) over both IPv4 and IPv6 endpoints.

- **Protocols:** `udp` (3 Ethernet frames)
- **Wire Behavior:** Computes the 16-bit UDP Length (`8 + payload bytes`) and outer IPv4 Total Length / IPv6 Payload Length automatically. Calculates the ones'-complement pseudo-header checksum over IPv4 or IPv6 addresses, converting `0x0000` to `0xffff` per RFC 768 / RFC 8200.
- **Wireshark Filter:** `udp`
- **CLI Build:** `frameassembly show udp_dualstack_binary.frasm`

```frameassembly
host feed_v4 { ip 192.0.2.10 }
host recv_v4 { ip 192.0.2.20 }
host feed_v6 { ip 2001:db8:feed::10 }
host recv_v6 { ip 2001:db8:feed::20 }

flow telemetry_burst(tx, rx) {
    tx -> rx udp srcport 55100 dstport 19500 dscp 46 hexpayload "cafebabe00010008deadbeef" wait 500us
    tx -> rx udp dscp 46 hexpayload "cafebabe0002000801020304" wait 1ms
    tx <- rx udp dscp 46 payload "ACK:2"
}

compile {
    telemetry_burst(feed_v4, recv_v4)
    telemetry_burst(feed_v6, recv_v6)
}
```

## 03.14 · SCTP (CRC-32c) (`sctp`): Complete 5G N2 NGAP SCTP 4-Way Handshake, Data Transfer & Heartbeat (`sctp_5g_ngap_association.frasm`)

Models a 5G gNodeB establishing a full 4-way cookie handshake with an AMF on port 38412, transmitting an NGAP Setup Request (`ppid 60`), receiving `sack`, and exchanging `heartbeat` / `heartbeatack`.

- **Protocols:** `sctp` (8 Ethernet frames)
- **Wire Behavior:** Computes the 32-bit reflected Castagnoli CRC-32c checksum across the 12-byte SCTP Common Header and all padded chunk bytes. Pads chunk payloads to 4-byte alignment per RFC 9260 while recording the exact unpadded length inside the Chunk Length field.
- **Wireshark Filter:** `sctp`
- **CLI Build:** `frameassembly show sctp_5g_ngap_association.frasm`

```frameassembly
host gnb_du { ip 172.20.10.11 }
host core_amf { ip 172.20.10.50 }

compile {
    // 1. RFC 9260 4-way association handshake (INIT must carry vtag 0)
    gnb_du -> core_amf sctp init srcport 38412 dstport 38412 vtag 0 tsn 1000 dscp 46 wait 1ms
    gnb_du <- core_amf sctp initack vtag 0xa1b2c3d4 tsn 5000 dscp 46 wait 1ms
    gnb_du -> core_amf sctp cookieecho vtag 0x55667788 dscp 46 wait 1ms
    gnb_du <- core_amf sctp cookieack vtag 0xa1b2c3d4 dscp 46 wait 2ms
    // 2. NGAP payload over Stream 0 (PPID 60 = 3GPP NGAP) + SACK acknowledgment
    gnb_du -> core_amf sctp data vtag 0x55667788 tsn 1000 stream 0 ssn 0 ppid 60 dscp 46 hexpayload "00150014000002001b00080000f110000001" wait 1ms
    gnb_du <- core_amf sctp sack vtag 0xa1b2c3d4 tsn 1000 dscp 46 wait 5ms
    // 3. Path liveness probe
    gnb_du -> core_amf sctp heartbeat vtag 0x55667788 wait 1ms
    gnb_du <- core_amf sctp heartbeatack vtag 0xa1b2c3d4
}
```
