Capture, decode, and rewrite packets — correctly and lawfully — in Rust. A single PAIML course that takes you from raw bytes on the wire through the IPv4 and UDP headers, the internet checksum, and field mangling, all the way to a contract-governed Rust crate, pktmangle, that parses an IPv4/UDP packet, verifies its checksums, rewrites a field, and serializes a wire-correct packet back.
A packet on the wire is just bytes — and once you can read those bytes, you can change them. This course teaches the load-bearing primitive behind NAT, firewalls, network test harnesses, and authorized security assessment: parse a packet, change a field, fix the checksum, put it back. Almost nobody teaches that primitive from the byte up. We do, and we prove it with a checked Rust artifact.
Read this before you capture or modify a single byte. Everything in this course is taught for defensive, educational, and authorized purposes only.
Packet capture and modification are powerful, and in most jurisdictions they are also regulated. You may capture or mangle traffic only on:
- Your own host or VM — traffic you generate yourself.
- Loopback (
lo) — self-generated traffic that never leaves your machine. This is the default for every lab in the course. - A lab or network you own, or one you have explicit, written authorization to test.
Sniffing or modifying traffic you do not own and are not authorized to inspect is illegal in most jurisdictions and unethical. In the United States this can implicate the Wiretap Act (18 U.S.C. § 2511) and the Computer Fraud and Abuse Act (18 U.S.C. § 1030), with analogues worldwide. This is not a footnote — it is the precondition for doing any of the work below.
Every lab in this course runs against loopback or traffic you generated yourself. The pktmangle crate is exercised entirely on bytes you construct or capture from your own host. The injection mechanisms (raw sockets, Linux NFQUEUE/iptables/netfilter) are taught at the concept level and are explicitly fenced as "do not run against shared or third-party networks." When in doubt, use lo.
- Authorization and Ethics
- What You'll Learn
- Course Outline
- Hands-On: pktmangle
- Repository Layout
- Capstone
- Instructor
- License
The course is a five-module arc that climbs from capturing raw bytes to a contract-governed mangle engine. After completing it you can:
- Capture authorized traffic. Explain how packets are captured — libpcap /
AF_PACKET, promiscuous mode, the kernel hand-off — and capture your own or loopback traffic withtcpdump/tshark, applying a BPF filter to select only the packets of interest. Read and write.pcapfiles for offline analysis. - Decode a packet by hand. Locate and interpret the Ethernet, IPv4, and UDP headers field by field — IHL, TTL, protocol, ports, length — from a hexdump and then programmatically, matching bytes to fields.
- Master the internet checksum. Compute the IPv4 header checksum and the UDP checksum (with the IPv4 pseudo-header) using ones-complement arithmetic, understand why any change to a covered field invalidates the checksum until it is recomputed, and apply incremental update (RFC 1624).
- Mangle packets correctly. Rewrite source/destination IPv4 (NAT-style), change UDP ports, decrement the TTL, and replace the payload — recomputing every affected checksum so the result verifies and length fields stay consistent.
- Build a total, contract-governed codec. Write a parse/serialize codec that round-trips losslessly (
parse(to_bytes(p)) == pfor well-formed packets) and never panics on malformed or truncated input — totality as a checked contract, not a hope. - Reason about injection lawfully. Describe raw sockets and Linux
NFQUEUE/iptables/netfilteras the authorized in-path rewrite mechanism, and recognize exactly where the legal and ethical boundary lies.
Four weeks, four modules of capture/decode/checksum/mangle plus a build-and-ship capstone. Each lesson ships a short concept video, a key-terms reading, and a reflection; each module closes with a role-play practice assignment. The full canonical outline lives in outline.md.
| Week | Module | Lesson | Title |
|---|---|---|---|
| 1 | Capture and Decode | 1.1 | Sniffing and Capture (Authorized Only) |
| 1 | Capture and Decode | 1.2 | Anatomy of a Packet |
| 1 | Capture and Decode | 1.3 | Decoding a Packet by Hand |
| 2 | Checksums and Mangling | 2.1 | The Internet Checksum |
| 2 | Checksums and Mangling | 2.2 | Mangling Fields and Fixing Checksums |
| 2 | Checksums and Mangling | 2.3 | Injection Concepts: Raw Sockets and NFQUEUE |
| 3 | Build the Engine | 3.1 | Parsing IPv4 and UDP from Bytes |
| 3 | Build the Engine | 3.2 | Computing Checksums in Code |
| 3 | Build the Engine | 3.3 | Mangle, Serialize, and Verify |
| 4 | Capstone Project | 4.1 | Capstone: Build pktmangle |
Every command and inspection recipe — runnable on a single host against loopback or self-generated traffic, with the real bytes you should see on the wire — is collected in labs.md. Modules 1–2 are concept plus capture/inspection labs; Modules 3–4 build and exercise the contract-governed Rust crate.
The capstone artifact is pktmangle — a small, dependency-free Rust crate that parses IPv4 + UDP from raw bytes, computes the internet checksum, serializes back, and offers mangle operations that recompute the affected checksums so the result verifies.
Like every PAIML Rust artifact, pktmangle is built contract-first under provable contracts (pv). Its kernel contract, contracts/pktmangle-v1.yaml, specifies the invariants before any code, and contracts/pktmangle-binding.yaml maps each contract equation to the function that satisfies it. The four governing properties are:
- Parse totality —
Ipv4Udp::parsereturnsOkorErrfor any input slice; it never panics, even on truncated, oversized, or garbage bytes. - Checksum correctness — a recomputed IPv4/UDP checksum verifies; a known-good packet verifies as parsed; a corrupted checksum is detected. The RFC 1071 worked example (
00 01 f2 03 f4 f5 f6 f7→0x220d) is a test. - Round-trip —
parse(to_bytes(p)) == pfor every well-formed IPv4/UDP packet, andto_bytes(parse(b)) == b. - Mangle invariants — after any mutation (set src/dst IP, set ports, decrement TTL, replace payload) the affected checksum re-verifies and the length fields (IPv4 total length, UDP length) remain consistent.
The public surface is small and total:
use pktmangle::{Ipv4Udp, PktError, internet_checksum, checksum_valid};
// Parse one captured (own/loopback) IPv4/UDP datagram — never panics on bad bytes.
let mut pkt: Ipv4Udp = Ipv4Udp::parse(&bytes)?;
// Mangle: NAT-style src rewrite, port change, payload swap, TTL decrement.
pkt.set_src_ip([10, 0, 0, 1]);
pkt.set_ports(1234, 5678);
pkt.set_payload(b"a different payload".to_vec());
let forwarded: bool = pkt.decrement_ttl(); // false if TTL was already 0 (drop, don't forward)
// Serialize back — both checksums are recomputed; the result verifies on the wire.
let out: Vec<u8> = pkt.to_bytes();
assert!(checksum_valid(&out[..20])); // IPv4 header checksum
assert_eq!(Ipv4Udp::parse(&out)?, pkt); // round-trip
# Ok::<(), PktError>(())The contract's falsification tests ship as cargo test cases (round-trip, serialized-checksum validity, parse totality over every truncated buffer, and mangle invariants). Run the full Rust gate with:
make rust # cargo fmt --check + clippy -D warnings + cargo test
make lint-contracts # pv validate contracts/*.yaml (skips cleanly if pv is absent)
make check # the whole gate: lint + contracts + comply + rust + structurepacket-sniffing-and-mangling/
├── README.md This file
├── outline.md Canonical module/lesson outline (4 weeks)
├── labs.md Runnable, loopback-only lab recipes for all modules
├── capstone.md The capstone brief — build and ship pktmangle
├── pktmangle/ The contract-governed Rust crate (the artifact)
│ ├── Cargo.toml
│ └── src/lib.rs parse / internet_checksum / to_bytes / mangle ops
├── contracts/ Provable contracts (pv-valid)
│ ├── pktmangle-v1.yaml Kernel contract: invariants, proof obligations, falsification tests
│ └── pktmangle-binding.yaml Maps each contract equation to its Rust function
├── coursera-assets/ Key-terms, reflections, role-plays, course page, banners (SVG/MD)
├── slides/ Title-slide SVG animations (per lesson)
├── assets/hero.svg Course hero banner
├── Makefile lint · lint-contracts · rust · validate · check
├── .github/workflows/ci.yml CI: markdown lint + structure + Rust gate + pv/pmat
└── LICENSE MIT
Check-in policy: source artifacts (SVG, Markdown, Lua) are committed; rendered media (PNG, MP4) is regenerated from source and is never committed.
The capstone is Build pktmangle — sniff, decode, mangle a field, recompute checksums, and verify the result, end to end. You read a .pcap saved from tcpdump on loopback (or self-generated UDP traffic), parse the IPv4/UDP packet, verify both checksums on a known-good packet, rewrite a field and recompute every affected checksum, then serialize a wire-correct packet back and confirm it re-verifies — optionally watching the checksum-OK status flip in tshark/Wireshark.
The same authorization boundary applies throughout: all input is traffic you own or generated yourself, never captured from a network you do not control. The full brief, deliverables, evaluation tiers (Developing / Proficient / Advanced), and the LinkedIn portfolio prompt are in capstone.md.
- Noah Gift — Founder, Pragmatic AI Labs · Duke University faculty
- RFC 791 — Internet Protocol (IPv4): https://www.rfc-editor.org/rfc/rfc791
- RFC 768 — User Datagram Protocol: https://www.rfc-editor.org/rfc/rfc768
- RFC 1071 — Computing the Internet Checksum: https://www.rfc-editor.org/rfc/rfc1071
- RFC 1624 — Incremental Update of the Internet Checksum: https://www.rfc-editor.org/rfc/rfc1624
- tcpdump(1) — packet capture and BPF filters: https://www.tcpdump.org/manpages/tcpdump.1.html
- pcap(3) — the packet capture library: https://www.tcpdump.org/manpages/pcap.3pcap.html
- Rust standard library —
std::result, slices, andVec<u8>: https://doc.rust-lang.org/std/
Course content © Pragmatic AI Labs. Code examples, including the pktmangle crate, are released under the MIT License.