Part 11 · 1 chapters · ~8 min
Capstone: A TCP Stack over a TUN Device
Building a minimal TCP implementation in user space: creating a TUN device, parsing IPv4 and TCP headers with checksums, the connection state machine, sequence and acknowledgement accounting, retransmission, and testing against real clients with captures.
21
The build
code
# Linux (as root, in a VM or container with NET_ADMIN) ip tuntap add dev tun0 mode tun user $USER ip addr add 10.9.0.1/24 dev tun0 && ip link set tun0 up # your program opens /dev/net/tun with IFF_TUN | IFF_NO_PI, reads packets addressed to 10.9.0.2 milestones 1 parse and print IPv4 + TCP headers for packets arriving on tun0 (ping 10.9.0.2 shows ICMP first) 2 answer SYN with SYN-ACK; nc 10.9.0.2 7 completes the handshake 3 receive data, ACK it, echo it back; nc shows the echo 4 handle FIN in both directions; connection closes cleanly 5 retransmit unacknowledged data after a timeout; test with tc netem loss 10% on the route stretch: window management, SACK, simple congestion control reference: RFC 9293 (TCP), RFC 791 (IPv4); Jon Gjengset's "Implementing TCP in Rust" streams walk through the same build
A TCP STACK OVER A TUN DEVICE
the kernel hands you raw IP packets; you implement TCP
swipe the figure sideways, or tap expand for full screen
1/5
TUN
A TUN device is a virtual network interface: packets the kernel routes to it are handed to your program as raw IP bytes, and bytes you write are injected as packets.
raw IP packets in and out of your programno kernel TCP involved