#!/usr/bin/env python3
"""Build office.pcap: five minutes of a synthetic mid-size office network.

The site is "Northstar Logistics", a single-floor 180-seat office with a
Microsoft 365 tenant, an on-premises domain controller and file server, Teams
Phone handsets, AirPrint MFPs, IP cameras and a guest SSID. End hosts are a
deliberate mix of Windows 11, macOS, Ubuntu, Fedora, iOS and Android, so the
capture works for passive OS fingerprinting as well as for protocol work.

Capture model (also documented in README.md -- read that before teaching from
this file). One SPAN session on the core switch, source Po1, both directions:
Po1 is the 802.1Q trunk down to the floor-2 access stack. So the file holds
exactly the frames that cross that trunk:

  * every frame is tagged with the access-side VLAN of the floor-2 device it
    belongs to (10 corp, 30 phones, 40 printers/cameras/BMS, 50 guest; VLAN 99
    management rides untagged as the native VLAN),
  * frames going up carry the sender's own MAC and TTL; frames coming back
    down carry the core's MAC and a TTL one lower, because the core routed
    them -- which is how you tell direction without looking at ports,
  * same-VLAN traffic between the floor-2 stack and another stack is bridged,
    not routed: real MACs on both ends and no TTL decrement,
  * conversations where neither end sits behind Po1 (server-to-server,
    firewall-to-SIEM) are absent, as they would be in the real capture. The
    generator asserts this, so a scene that could not have been captured here
    fails the build instead of quietly lying.

Everything is deterministic: same seed in, byte-identical pcap out.

Usage:
    python3 mkoffice.py                 # -> office.pcap
    python3 mkoffice.py --out /tmp/x.pcap --seed 7
"""

import argparse
import calendar
import random
import zlib

from scapy.all import (
    ARP, Dot1Q, Dot3, Ether, ICMP, IP, IPv6, LLC, NTP, Raw, SNAP, STP, TCP,
    UDP, wrpcap,
)
import scapy.layers.kerberos as KRB
import scapy.layers.netflow as NF
from scapy.asn1.asn1 import (
    ASN1_BIT_STRING, ASN1_GENERAL_STRING, ASN1_GENERALIZED_TIME, ASN1_INTEGER,
    ASN1_NULL, ASN1_OID,
)
from scapy.layers.inet6 import (
    ICMPv6MLDMultAddrRec, ICMPv6MLReport2, ICMPv6ND_NA, ICMPv6ND_NS,
    ICMPv6ND_RA, ICMPv6ND_RS, ICMPv6NDOptDstLLAddr, ICMPv6NDOptPrefixInfo,
    ICMPv6NDOptSrcLLAddr,
)
from scapy.layers.dhcp import BOOTP, DHCP
from scapy.layers.dns import DNS, DNSQR, DNSRR, DNSRROPT, DNSRRSRV
from scapy.layers.dhcp6 import (
    DHCP6_InfoRequest, DHCP6_Reply, DHCP6OptClientId, DHCP6OptDNSDomains,
    DHCP6OptDNSServers, DHCP6OptElapsedTime, DHCP6OptOptReq,
    DHCP6OptServerId, DUID_LL, DUID_LLT,
)
from scapy.layers.netbios import NBNSHeader, NBNSQueryRequest
from scapy.layers.snmp import SNMP, SNMPget, SNMPresponse, SNMPvarbind
from scapy.layers.vrrp import VRRPv3
from scapy.utils import checksum
from scapy.contrib.cdp import (
    CDPMsgCapabilities, CDPMsgDeviceID, CDPMsgPlatform, CDPMsgPortID,
    CDPMsgSoftwareVersion, CDPv2_HDR,
)
from scapy.contrib.lldp import (
    LLDPDU, LLDPDUChassisID, LLDPDUEndOfLLDPDU, LLDPDUPortDescription,
    LLDPDUPortID, LLDPDUSystemDescription, LLDPDUSystemName,
    LLDPDUTimeToLive,
)
from scapy.layers.smb2 import (
    SMB2_Encryption_Capabilities, SMB2_Header, SMB2_Negotiate_Context,
    SMB2_Negotiate_Protocol_Request, SMB2_Negotiate_Protocol_Response,
    SMB2_Preauth_Integrity_Capabilities, SMB2_Transform_Header,
)

# ===========================================================================
#  Clock and randomness
# ===========================================================================
# Tuesday 2026-11-10, 09:14:00 America/Los_Angeles (PST, UTC-8) -- mid-morning,
# so the capture lands on real working traffic rather than the login storm.
T0 = calendar.timegm((2026, 11, 10, 17, 14, 0, 0, 0, 0))
DURATION = 300.0

RNG = random.Random(20261110)


def jit(scale=1.0):
    """Small positive jitter, so nothing lands on a suspiciously round tick."""
    return RNG.random() * scale


def filler(n):
    """n bytes of deterministic payload stand-in."""
    chunk = bytes((i * 37 + 11) & 0xFF for i in range(251))
    return (chunk * (n // 251 + 1))[:n]


# ===========================================================================
#  OS profiles -- the passive fingerprints students are meant to find
# ===========================================================================
# ttl:  initial TTL / hop limit the stack emits
# win:  advertised window in the SYN (raw value, before scaling)
# ws:   window scale shift
# ts:   does the stack offer RFC 7323 timestamps in its SYN?
# mss:  MSS it announces on a 1500-byte Ethernet link
OS = {
    "win11":   dict(ttl=128, win=64240, ws=8, ts=False, mss=1460),
    "win2022": dict(ttl=128, win=65535, ws=8, ts=False, mss=1460),
    "macos":   dict(ttl=64,  win=65535, ws=6, ts=True,  mss=1460),
    "ios":     dict(ttl=64,  win=65535, ws=6, ts=True,  mss=1460),
    "linux":   dict(ttl=64,  win=64240, ws=7, ts=True,  mss=1460),
    "android": dict(ttl=64,  win=65535, ws=8, ts=True,  mss=1460),
    "embed":   dict(ttl=64,  win=16384, ws=0, ts=False, mss=1460),
    "netgear": dict(ttl=255, win=16384, ws=0, ts=False, mss=1460),
    "ext":     dict(ttl=64,  win=65535, ws=7, ts=True,  mss=1460),
}


class Host:
    """A node that shows up in the capture."""

    def __init__(self, name, ip, mac=None, vlan=None, osname="win11",
                 ip6=None, ttl=None, desc="", mirrored=None):
        self.name = name
        self.ip = ip
        self.mac = mac
        self.vlan = vlan
        self.os = osname
        self.ip6 = ip6
        self.desc = desc
        self.local = mac is not None
        # mirrored = "sits behind Po1, the trunk this SPAN session watches".
        # Servers, the core, the firewall and the floor-1 stack do not.
        self.mirrored = self.local if mirrored is None else mirrored
        self.prof = OS[osname]
        # External peers get an observed (path-worn) TTL instead of an initial
        # one; that is what a capture inside the building actually sees.
        self.ttl = ttl if ttl is not None else self.prof["ttl"]


# ===========================================================================
#  Site topology
# ===========================================================================
#  VLAN 10   10.21.10.0/24    corporate endpoints
#  VLAN 20   10.21.20.0/24    servers
#  VLAN 30   10.21.30.0/24    Teams Phone handsets
#  VLAN 40   10.21.40.0/24    printers, cameras, building controls
#  VLAN 50   10.21.50.0/24    guest SSID (NATed, no route to the inside)
#  VLAN 99   10.21.99.0/24    switch/AP management -- the native, untagged VLAN
#  VLAN 100  10.21.100.0/30   routed link, core <-> edge firewall
CORE_MAC = "00:1e:bd:4a:11:01"     # cs-core-01, Cisco OUI
CORE2_MAC = "00:1e:bd:4a:11:02"    # cs-core-02, VRRP backup
FW_MAC = "00:1b:17:c2:33:40"       # fw-edge-01, Palo Alto OUI
SW2_MAC = "00:23:04:7b:5e:80"      # sw-floor2
AP1_MAC = "88:15:44:29:7a:10"      # ap-f2-01, Cisco Meraki OUI
AP2_MAC = "88:15:44:29:7a:11"      # ap-f2-02
WAN_VLAN = 100
NATIVE_VLAN = 99

H = {}


def host(*a, **kw):
    h = Host(*a, **kw)
    H[h.name] = h
    return h


# --- network infrastructure -------------------------------------------------
core = host("cs-core-01", "10.21.99.2", CORE_MAC, 99, "netgear",
            mirrored=False,
            desc="Catalyst 9300 core, L3 gateway for every VLAN, SPAN source")
core2 = host("cs-core-02", "10.21.99.3", CORE2_MAC, 99, "netgear",
             mirrored=False, desc="VRRP backup")
sw2 = host("sw-floor2", "10.21.99.4", SW2_MAC, 99, "netgear",
           desc="floor-2 access stack, behind Po1; NetFlow exporter")
fw = host("fw-edge-01", "10.21.100.1", FW_MAC, WAN_VLAN, "netgear",
          mirrored=False, desc="edge firewall, NATs everything outbound")
ap1 = host("ap-f2-01", "10.21.99.21", AP1_MAC, 99, "netgear")
ap2 = host("ap-f2-02", "10.21.99.22", AP2_MAC, 99, "netgear")

# --- servers (VLAN 20) ------------------------------------------------------
dc01 = host("dc01", "10.21.20.10", "00:50:56:a1:20:10", 20, "win2022",
            ip6="2001:db8:21:20::10", mirrored=False,
            desc="Windows Server 2025: AD DS, DNS, KDC, NTP")
fs01 = host("fs01", "10.21.20.20", "00:50:56:a1:20:20", 20, "win2022",
            mirrored=False,
            desc="Windows Server 2022, SMB 3.1.1 file server, encryption on")
siem01 = host("siem01", "10.21.20.40", "00:50:56:a1:20:40", 20, "linux",
              mirrored=False,
              desc="Ubuntu 24.04: syslog, NetFlow collector, SNMP poller")
bkp01 = host("bkp01", "10.21.20.50", "00:50:56:a1:20:50", 20, "linux",
             mirrored=False, desc="backup target")
nvr01 = host("nvr01", "10.21.20.55", "00:50:56:a1:20:55", 20, "linux",
             mirrored=False, desc="camera recorder, pulls RTSP from VLAN 40")

# --- corporate endpoints (VLAN 10) -----------------------------------------
wks_fin = host("wks-fin-07", "10.21.10.52", "b0:7b:25:3c:91:04", 10, "win11",
               ip6="2001:db8:21:10::52",
               desc="Dell OptiPlex, Windows 11 24H2, finance")
wks_sales = host("wks-sales-12", "10.21.10.61", "54:e1:ad:0b:72:33", 10,
                 "win11", desc="Lenovo ThinkPad, Windows 11 24H2, sales")
wks_hr = host("wks-hr-03", "10.21.10.64", "b0:7b:25:3c:88:7a", 10, "win11",
              mirrored=False,
              desc="Dell Latitude, Windows 11 24H2, HR -- on the floor-1 "
                   "stack, so it only shows up where it talks to floor 2")
mbp_eng = host("mbp-eng-02", "10.21.10.88", "f0:18:98:5d:2a:61", 10, "macos",
               ip6="2001:db8:21:10::88",
               desc="MacBook Pro, macOS 15, engineering")
mbp_mkt = host("mbp-mkt-05", "10.21.10.91", "3c:07:54:19:cc:08", 10, "macos",
               desc="MacBook Air, macOS 15, marketing")
dev_ubu = host("dev-ws-01", "10.21.10.120", "8c:16:45:2f:10:aa", 10, "linux",
               ip6="2001:db8:21:10::120",
               desc="Ubuntu 24.04 LTS developer workstation")
dev_fed = host("dev-ws-02", "10.21.10.121", "8c:16:45:2f:10:ab", 10, "linux",
               desc="Fedora 42 developer workstation, avahi running")
iphone = host("iphone-jlin", "10.21.10.161", "ac:de:48:11:5e:92", 10, "ios",
              desc="iPhone on corp Wi-Fi")
andro = host("pixel-rsmith", "10.21.10.165", "da:a1:19:7c:04:3b", 10, "android",
             desc="Android handset on corp Wi-Fi")
legacy = host("scan-pc-01", "10.21.10.200", "00:15:5d:aa:19:04", 10, "win11",
              desc="Windows 10 22H2 scanner PC, still speaks LLMNR/NBT-NS")

# --- Teams Phone handsets (VLAN 30) ----------------------------------------
phone1 = host("phone-3012", "10.21.30.61", "80:5e:c0:4a:12:31", 30, "android",
              desc="Teams-certified desk phone")
phone2 = host("phone-3014", "10.21.30.62", "80:5e:c0:4a:12:33", 30, "android")

# --- printers, cameras, building controls (VLAN 40) ------------------------
mfp1 = host("prn-mfp-01", "10.21.40.11", "3c:d9:2b:7e:41:09", 40, "embed",
            desc="HP MFP, IPP Everywhere + Bonjour + SNMP")
mfp2 = host("prn-mfp-02", "10.21.40.12", "3c:d9:2b:7e:41:1a", 40, "embed")
cam1 = host("cam-lobby-01", "10.21.40.21", "00:40:8c:9d:33:70", 40, "embed",
            desc="Axis camera, RTSP")
cam2 = host("cam-dock-02", "10.21.40.22", "00:40:8c:9d:33:71", 40, "embed")
bms = host("bms-gw-01", "10.21.40.30", "00:80:f9:3a:11:62", 40, "embed",
           desc="building management gateway, Modbus/TCP master")
bmsc = host("bms-ctrl-02", "10.21.40.31", "00:80:f9:3a:11:70", 40, "embed",
            mirrored=False,
            desc="rooftop unit controller, Modbus/TCP slave, floor-1 stack "
                 "-- same VLAN as the gateway, so this pair is bridged")

# --- guest SSID (VLAN 50) ---------------------------------------------------
g_iphone = host("guest-ios-a", "10.21.50.113", "ac:de:48:62:7f:20", 50, "ios")
g_laptop = host("guest-win-b", "10.21.50.120", "9c:b6:d0:f1:04:5c", 50, "win11")


# --- external peers ---------------------------------------------------------
# Addresses come out of the ranges those services really publish, so whois and
# BGP lookups line up; the individual host addresses inside them are invented.
def ext(n, ip, ttl, d=""):
    return host(n, ip, None, None, "ext", ttl=ttl, desc=d)


x_teams_media = ext("teams-media", "52.112.17.74", 113,
                    "Teams transport relay, 52.112.0.0/14")
x_teams_sig = ext("teams-signal", "52.122.6.44", 113, "teams.cloud.microsoft")
x_spo = ext("sharepoint", "13.107.138.10", 113,
            "northstarlogistics.sharepoint.com")
x_exo = ext("outlook", "40.100.17.5", 113, "outlook.cloud.microsoft")
x_aad = ext("entra-login", "20.190.160.17", 113, "login.microsoftonline.com")
x_graph = ext("ms-graph", "20.20.35.44", 113, "graph.microsoft.com")
x_do_svc = ext("do-service", "20.42.65.92", 113,
               "kv801.prod.do.dsp.mp.microsoft.com")
x_wu_cdn = ext("wu-cdn", "152.199.19.161", 56,
               "tlu.dl.delivery.mp.microsoft.com")
x_ncsi = ext("msftconnecttest", "20.41.46.254", 113, "www.msftconnecttest.com")
x_mstime = ext("time-windows", "20.101.57.9", 113, "time.windows.com")
x_quad9 = ext("quad9", "9.9.9.9", 55, "dc01's forwarder")
x_cf_doh = ext("cloudflare-doh", "1.1.1.1", 57,
               "cloudflare-dns.com, used by guests")
x_cf_ntp = ext("cloudflare-ntp", "162.159.200.123", 57, "time.cloudflare.com")
x_digicert = ext("ocsp-digicert", "93.184.220.29", 54, "ocsp.digicert.com")
x_apple_apn = ext("apple-apns", "17.57.144.20", 52, "courier.push.apple.com")
x_apple_cap = ext("apple-captive", "17.253.57.201", 52, "captive.apple.com")
x_icloud = ext("icloud", "17.248.188.44", 52, "p54-ckdatabase.icloud.com")
x_brew = ext("brew", "104.18.32.117", 57, "formulae.brew.sh")
x_github = ext("github", "140.82.113.3", 51, "github.com")
x_gh_cdn = ext("github-codeload", "140.82.114.9", 51, "codeload.github.com")
x_ubuntu = ext("archive-ubuntu", "185.125.190.36", 53, "archive.ubuntu.com")
x_ubu_ntp = ext("ntp-ubuntu", "185.125.190.56", 53, "ntp.ubuntu.com")
x_fedora = ext("fedora-mirror", "152.19.134.142", 50, "fedora mirror")
x_docker = ext("docker-registry", "3.219.99.102", 48, "registry-1.docker.io")
x_slack = ext("slack", "3.223.17.44", 48, "slack.com")
x_okta = ext("okta", "99.84.108.73", 55, "northstar.okta.com")
x_zoom = ext("zoom", "170.114.52.2", 52, "zoom.us")
x_edr = ext("edr-cloud", "52.37.124.9", 48, "ts01-b.cloudsink.net")
x_gstatic = ext("gstatic", "142.250.217.78", 54, "connectivitycheck.gstatic.com")
x_youtube = ext("youtube", "172.217.14.238", 54, "QUIC video")
x_hpcloud = ext("hp-cloud", "15.73.40.19", 48, "printer vendor telemetry")

# Multicast / broadcast destinations
MAC_BCAST = "ff:ff:ff:ff:ff:ff"
MAC_MDNS = "01:00:5e:00:00:fb"
MAC_MDNS6 = "33:33:00:00:00:fb"
MAC_LLMNR = "01:00:5e:00:00:fc"
MAC_SSDP = "01:00:5e:7f:ff:fa"
MAC_STP = "01:80:c2:00:00:00"
MAC_LLDP = "01:80:c2:00:00:0e"
MAC_CDP = "01:00:0c:cc:cc:cc"
MAC_VRRP = "01:00:5e:00:00:12"
MAC_ALLNODES6 = "33:33:00:00:00:01"
MAC_ALLROUTERS6 = "33:33:00:00:00:02"
MAC_MLD6 = "33:33:00:00:00:16"

PKTS = []


def emit(t, pkt):
    """Queue one frame at absolute time t (seconds since the epoch)."""
    pkt.time = t
    PKTS.append((t, pkt))
    return pkt


def l2(src_mac, dst_mac, vlan):
    """Ethernet header, 802.1Q-tagged unless the frame rode the native VLAN."""
    e = Ether(src=src_mac, dst=dst_mac)
    if vlan is not None and vlan != NATIVE_VLAN:
        e = e / Dot1Q(vlan=vlan)
    return e


def frame(t, vlan, smac, dmac, upper):
    """Emit a frame whose addressing is spelled out by hand -- used for the
    switch's own control plane, where there is no src/dst Host pair."""
    return emit(t, l2(smac, dmac, vlan) / upper)


def bridged(src, dst):
    """True when the core switches this frame at layer 2 and never routes it."""
    return src.local and dst.local and src.vlan == dst.vlan


def path(src, dst):
    """(vlan, src_mac, dst_mac) for one unicast frame crossing Po1.

    Going up (a floor-2 device is the sender) the frame still carries the
    sender's MAC and is addressed to the core, unless it is same-VLAN traffic
    the core only bridges. Coming down, the core has already rewritten the
    destination MAC, so the source MAC is the core's.
    """
    assert src.mirrored or dst.mirrored, \
        f"{src.name} -> {dst.name} never crosses Po1: it cannot be in this file"
    if src.mirrored:
        return src.vlan, src.mac, (dst.mac if bridged(src, dst) else CORE_MAC)
    return dst.vlan, (src.mac if bridged(src, dst) else CORE_MAC), dst.mac


def ttl_for(src, dst):
    """What the TTL reads at the mirror point.

    Frames on their way up have not been routed yet; frames on their way down
    have lost one hop to the core. External peers are given the TTL they are
    seen with here, so no further adjustment.
    """
    if src.mirrored or bridged(src, dst):
        return src.ttl
    return src.ttl - 1 if src.local else src.ttl


def ipv4(src, dst, *, dscp=0, ttl=None, df=True):
    """IPv4 header carrying the right TTL for the direction and a DSCP mark."""
    return IP(src=src.ip, dst=dst.ip, tos=dscp << 2,
              ttl=ttl if ttl else ttl_for(src, dst), flags="DF" if df else 0,
              id=RNG.randrange(1, 65535))


def u4(t, src, dst, sport, dport, payload, *, dscp=0, ttl=None):
    """One UDP datagram."""
    vlan, sm, dm = path(src, dst)
    p = l2(sm, dm, vlan) / ipv4(src, dst, dscp=dscp, ttl=ttl, df=False) / \
        UDP(sport=sport, dport=dport)
    if payload is not None:
        p = p / payload
    return emit(t, p)


def mcast4(t, src, group, group_mac, sport, dport, payload, *, ttl=255):
    """IPv4 multicast or broadcast; stays inside the sender's VLAN."""
    p = l2(src.mac, group_mac, src.vlan) / \
        IP(src=src.ip, dst=group, ttl=ttl, id=RNG.randrange(1, 65535)) / \
        UDP(sport=sport, dport=dport) / payload
    return emit(t, p)


def mcast6(t, src, group, group_mac, sport, dport, payload, *, hlim=255,
           src6=None):
    p = l2(src.mac, group_mac, src.vlan) / \
        IPv6(src=src6 or src.ip6, dst=group, hlim=hlim) / \
        UDP(sport=sport, dport=dport) / payload
    return emit(t, p)


# ===========================================================================
#  TCP: a small conversation engine
# ===========================================================================
# Each stack gets the SYN option layout it really sends -- that ordering, plus
# the initial TTL and window, is what passive fingerprinting keys on.
SYN_STYLE = {
    "win11": "win", "win2022": "win", "macos": "bsd", "ios": "bsd",
    "linux": "linux", "android": "linux", "embed": "min", "netgear": "min",
    "ext": "linux",
}
STYLE_ORDER = {
    "win":   ["mss", "nop", "ws", "nop", "nop", "sackok"],
    "bsd":   ["mss", "nop", "ws", "nop", "nop", "ts", "sackok", "eol"],
    "linux": ["mss", "sackok", "ts", "nop", "ws"],
    "min":   ["mss", "sackok"],
}


class TcpFlow:
    """One TCP conversation, built packet by packet with a moving clock."""

    def __init__(self, t, c, s, sport, dport, *, dscp=0, rtt=None, bw=None,
                 win_raw=512):
        self.c, self.s = c, s
        self.sport, self.dport = sport, dport
        self.dscp = dscp
        internal = c.local and s.local
        self.rtt = rtt if rtt is not None else (0.0009 if internal else 0.023)
        self.bw = bw if bw is not None else (9.4e8 if internal else 4.5e7)
        self.cp, self.sp = OS[c.os], OS[s.os]
        self.ts = self.cp["ts"] and self.sp["ts"]
        self.mss = min(self.cp["mss"], self.sp["mss"])
        self.seq = {"c": RNG.randrange(10 ** 6, 2 ** 31),
                    "s": RNG.randrange(10 ** 6, 2 ** 31)}
        self.ack = {"c": 0, "s": 0}
        self.tsbase = {"c": RNG.randrange(10 ** 5, 10 ** 8),
                       "s": RNG.randrange(10 ** 5, 10 ** 8)}
        self.tsecr = {"c": 0, "s": 0}
        self.win = {"c": win_raw, "s": win_raw}
        self.t = t
        self.opened = False

    # -- helpers ------------------------------------------------------------
    def _peer(self, who):
        return "s" if who == "c" else "c"

    def _hosts(self, who):
        return (self.c, self.s) if who == "c" else (self.s, self.c)

    def _ports(self, who):
        return (self.sport, self.dport) if who == "c" else (self.dport,
                                                            self.sport)

    def _tsval(self, who):
        return (self.tsbase[who] + int((self.t - T0) * 1000)) & 0xFFFFFFFF

    def _syn_opts(self, who):
        prof = self.cp if who == "c" else self.sp
        order = STYLE_ORDER[SYN_STYLE[(self.c if who == "c" else self.s).os]]
        out = []
        for o in order:
            if o == "mss":
                out.append(("MSS", prof["mss"]))
            elif o == "nop":
                out.append(("NOP", None))
            elif o == "ws" and prof["ws"]:
                out.append(("WScale", prof["ws"]))
            elif o == "sackok":
                out.append(("SAckOK", b""))
            elif o == "ts" and prof["ts"]:
                out.append(("Timestamp", (self._tsval(who), self.tsecr[who])))
            elif o == "eol":
                out.append(("EOL", None))
        return out

    def _data_opts(self, who, extra=None):
        out = []
        if self.ts:
            out += [("NOP", None), ("NOP", None),
                    ("Timestamp", (self._tsval(who), self.tsecr[who]))]
        if extra:
            out += extra
        return out

    def seg(self, who, flags, payload=b"", *, opts=None, syn=False,
            seq=None, win=None, advance=True):
        """Emit one segment from `who` ("c" or "s") at the current clock."""
        src, dst = self._hosts(who)
        sport, dport = self._ports(who)
        vlan, sm, dm = path(src, dst)
        if syn:
            opts = self._syn_opts(who)
            window = (self.cp if who == "c" else self.sp)["win"]
        else:
            opts = self._data_opts(who, opts)
            window = win if win is not None else self.win[who]
        seqno = self.seq[who] if seq is None else seq
        p = l2(sm, dm, vlan) / ipv4(src, dst, dscp=self.dscp) / \
            TCP(sport=sport, dport=dport, flags=flags, seq=seqno,
                ack=self.ack[who], window=window, options=opts)
        if payload:
            p = p / Raw(payload)
        emit(self.t, p)
        if advance:
            self.seq[who] = (self.seq[who] + len(payload) +
                             (1 if ("S" in flags or "F" in flags) else 0))
        self.tsecr[self._peer(who)] = self._tsval(who)
        return p

    # -- phases -------------------------------------------------------------
    def open(self, *, delay=0.0):
        self.t += delay
        self.seg("c", "S", syn=True)
        self.t += self.rtt
        self.ack["s"] = self.seq["c"]
        self.seg("s", "SA", syn=True)
        self.t += self.rtt * 0.45
        self.ack["c"] = self.seq["s"]
        self.seg("c", "A")
        self.opened = True
        return self

    def send(self, who, data, *, think=0.0, ack_every=2, push=True):
        """Send `data` from one side, segmented, with the peer acking."""
        self.t += think
        peer = self._peer(who)
        chunks = [data[i:i + self.mss] for i in range(0, len(data), self.mss)] \
            or [b""]
        unacked = 0
        for i, ch in enumerate(chunks):
            last = i == len(chunks) - 1
            self.ack[who] = self.seq[peer]
            self.seg(who, "PA" if (last and push) else "A", ch)
            self.t += max(len(ch) * 8 / self.bw, 1.2e-5)
            unacked += 1
            if unacked >= ack_every and not last:
                self.t += self.rtt * 0.5
                self.ack[peer] = self.seq[who]
                self.seg(peer, "A")
                unacked = 0
        self.t += self.rtt * 0.5
        self.ack[peer] = self.seq[who]
        self.seg(peer, "A")
        return self

    def retransmit(self, who, data, seq, *, gap=0.28):
        """A lost segment showing up again, after the peer's duplicate ACKs."""
        peer = self._peer(who)
        for _ in range(3):
            self.t += 0.0004
            self.ack[peer] = seq
            self.seg(peer, "A", advance=False,
                     opts=[("SAck", (seq + len(data), seq + 2 * len(data)))])
        self.t += gap
        self.ack[who] = self.seq[peer]
        self.seg(who, "PA", data, seq=seq, advance=False)
        self.t += self.rtt * 0.5
        self.ack[peer] = self.seq[who]
        self.seg(peer, "A")
        return self

    def close(self, who="c", *, think=0.0):
        self.t += think
        peer = self._peer(who)
        self.ack[who] = self.seq[peer]
        self.seg(who, "FA")
        self.t += self.rtt * 0.5
        self.ack[peer] = self.seq[who]
        self.seg(peer, "A")
        self.t += 0.0012
        self.seg(peer, "FA")
        self.t += self.rtt * 0.5
        self.ack[who] = self.seq[peer]
        self.seg(who, "A")
        return self

    def reset(self, who="s"):
        peer = self._peer(who)
        self.ack[who] = self.seq[peer]
        self.seg(who, "RA")
        return self


# ===========================================================================
#  TLS 1.3 records, hand-rolled so the handshake really dissects
# ===========================================================================
def _u8(n):
    return bytes([n])


def _u16(n):
    return n.to_bytes(2, "big")


def _u24(n):
    return n.to_bytes(3, "big")


def _ext(etype, body):
    return _u16(etype) + _u16(len(body)) + body


def _rec(ctype, body, ver=b"\x03\x03"):
    return bytes([ctype]) + ver + _u16(len(body)) + body


def _rand(n):
    """Deterministic pseudo-random bytes: ciphertext, nonces, SRTP payloads."""
    return RNG.randbytes(n)


# Each TLS stack offers its own cipher list, its own extension order and its
# own ALPN, which is what JA3 and JA4 actually measure. Giving every client the
# same Client Hello would make the file useless for fingerprinting work, so
# there is one profile per stack in the building.
TLS_PROFILES = {
    # Schannel, as Outlook/WinHTTP/LDAPS clients on Windows send it.
    "schannel": dict(
        ciphers="1302 1303 1301 c02c c02b c030 c02f 009f 009e c024 c023 c028"
                " c027 c00a c009 c014 c013 009d 009c 003d 003c 0035 002f",
        exts=["server_name", "supported_groups", "ec_point_formats",
              "signature_algorithms", "alpn", "supported_versions",
              "key_share", "psk_modes", "ems", "renego", "session_ticket",
              "status_request"],
        alpn=(b"h2", b"http/1.1")),
    # Chromium-family browsers: GREASE at both ends, short modern cipher list.
    "edge": dict(
        ciphers="1301 1302 1303 c02b c02f c02c c030 cca9 cca8 c013 c014 009c"
                " 009d 002f 0035",
        exts=["grease", "server_name", "ems", "renego", "supported_groups",
              "ec_point_formats", "session_ticket", "alpn", "status_request",
              "signature_algorithms", "supported_versions", "psk_modes",
              "key_share", "compress_cert", "grease2"],
        alpn=(b"h2", b"http/1.1")),
    # Apple Network.framework / Secure Transport.
    "apple": dict(
        ciphers="1301 1302 1303 c02c c02b cca9 c030 c02f cca8 c00a c009 c014"
                " c013 009d 009c 003d 003c 0035 002f",
        exts=["grease", "server_name", "ems", "renego", "supported_groups",
              "ec_point_formats", "alpn", "status_request",
              "signature_algorithms", "supported_versions", "psk_modes",
              "key_share", "session_ticket"],
        alpn=(b"h2", b"http/1.1")),
    # OpenSSL, which is what apt, dnf, curl and docker all end up using.
    "openssl": dict(
        ciphers="1302 1303 1301 c02c c030 009f cca9 cca8 ccaa c02b c02f 009e"
                " c024 c028 006b c023 c027 0067 c00a c014 0039 c009 c013 0033"
                " 009d 009c 003d 003c 0035 002f 00ff",
        exts=["server_name", "ec_point_formats", "supported_groups",
              "session_ticket", "encrypt_then_mac", "ems",
              "signature_algorithms", "supported_versions", "psk_modes",
              "key_share", "post_handshake", "alpn"],
        alpn=(b"h2", b"http/1.1")),
    # The printer's embedded stack: TLS 1.2 only, no ALPN, nothing modern.
    "embedded": dict(
        ciphers="c030 c02f c028 c027 c014 c013 009d 009c 003d 003c 0035 002f",
        exts=["server_name", "ec_point_formats", "supported_groups",
              "signature_algorithms", "renego"],
        alpn=None, tls13=False),
}

OS_TLS = {"win11": "schannel", "win2022": "schannel", "macos": "apple",
          "ios": "apple", "linux": "openssl", "android": "openssl",
          "embed": "embedded", "netgear": "embedded", "ext": "openssl"}


def tls_client_hello(sni, *, profile="schannel"):
    """A ClientHello built to the named stack's shape.

    The SNI and the ALPN list stay in the clear no matter which profile is
    used -- that is the whole reason this capture is useful without keys.
    """
    p = TLS_PROFILES[profile]
    tls13 = p.get("tls13", True)
    sni_b = sni.encode()
    sigalgs = bytes.fromhex("040308040401050308050501080606010201")
    groups = bytes.fromhex("001d00170018") if tls13 else bytes.fromhex("00170018")

    def build(name):
        if name == "grease":
            return _ext(0x0A0A, b"")
        if name == "grease2":
            return _ext(0x1A1A, b"")
        if name == "server_name":
            return _ext(0x0000, _u16(len(sni_b) + 3) + b"\x00" +
                        _u16(len(sni_b)) + sni_b)
        if name == "ems":
            return _ext(0x0017, b"")
        if name == "renego":
            return _ext(0xFF01, b"\x00")
        if name == "supported_groups":
            return _ext(0x000A, _u16(len(groups)) + groups)
        if name == "ec_point_formats":
            return _ext(0x000B, b"\x01\x00")
        if name == "session_ticket":
            return _ext(0x0023, b"")
        if name == "alpn" and p["alpn"]:
            lst = b"".join(_u8(len(a)) + a for a in p["alpn"])
            return _ext(0x0010, _u16(len(lst)) + lst)
        if name == "status_request":
            return _ext(0x0005, b"\x01\x00\x00\x00\x00")
        if name == "signature_algorithms":
            return _ext(0x000D, _u16(len(sigalgs)) + sigalgs)
        if name == "supported_versions" and tls13:
            return _ext(0x002B, b"\x04\x03\x04\x03\x03")
        if name == "psk_modes" and tls13:
            return _ext(0x002D, b"\x01\x01")
        if name == "key_share" and tls13:
            return _ext(0x0033, _u16(36) + _u16(0x001D) + _u16(32) + _rand(32))
        if name == "encrypt_then_mac":
            return _ext(0x0016, b"")
        if name == "post_handshake":
            return _ext(0x0031, b"")
        if name == "compress_cert":
            return _ext(0x001B, b"\x02\x00\x02")
        return b""

    exts = b"".join(build(n) for n in p["exts"])
    ciphers = bytes.fromhex(p["ciphers"].replace(" ", ""))
    sid = _rand(32)
    body = (b"\x03\x03" + _rand(32) + _u8(len(sid)) + sid +
            _u16(len(ciphers)) + ciphers + b"\x01\x00" +
            _u16(len(exts)) + exts)
    return _rec(0x16, b"\x01" + _u24(len(body)) + body, ver=b"\x03\x01")


def tls_server_hello(cipher=0x1302, *, tls13=True):
    if tls13:
        exts = _ext(0x002B, b"\x03\x04") + \
            _ext(0x0033, _u16(0x001D) + _u16(32) + _rand(32))
    else:
        exts = _ext(0xFF01, b"\x00") + _ext(0x000B, b"\x01\x00")
    sid = _rand(32)
    body = (b"\x03\x03" + _rand(32) + _u8(len(sid)) + sid + _u16(cipher) +
            b"\x00" + _u16(len(exts)) + exts)
    return _rec(0x16, b"\x02" + _u24(len(body)) + body)


def tls_ccs():
    return _rec(0x14, b"\x01")


def tls_app(n, chunk=16384):
    """Encrypted records: everything after the handshake looks like this.

    TLS caps a record at 2^14 bytes of plaintext, so anything larger goes out
    as a run of records -- which is exactly how a big upload looks in Wireshark.
    """
    out = b""
    while n > 0:
        k = min(n, chunk)
        out += _rec(0x17, _rand(k))
        n -= k
    return out


def tls_session(t, c, s, sni, *, sport, dport=443, up=1400, down=42000,
                dscp=0, rtt=None, bw=None, close=True, keepalives=0,
                keepalive_gap=20.0, profile=None):
    """TCP + a TLS handshake + application data, the way most of the capture's
    bytes actually move. The Client Hello follows the client's own stack
    unless a profile is named (a browser on Windows is not Schannel)."""
    prof = profile or OS_TLS[c.os]
    tls13 = TLS_PROFILES[prof].get("tls13", True)
    cipher = 0x1302 if tls13 else 0xC030
    f = TcpFlow(t, c, s, sport, dport, dscp=dscp, rtt=rtt, bw=bw)
    f.open()
    f.send("c", tls_client_hello(sni, profile=prof), think=0.0008)
    f.send("s", tls_server_hello(cipher, tls13=tls13) + tls_ccs() +
           tls_app(RNG.randrange(900, 2600)), think=0.004)
    f.send("c", tls_ccs() + tls_app(52) + tls_app(up), think=0.002)
    f.send("s", tls_app(down), think=0.01 + jit(0.02))
    for _ in range(keepalives):
        f.t += keepalive_gap
        f.send("c", tls_app(RNG.randrange(31, 90)))
        f.send("s", tls_app(RNG.randrange(31, 160)), think=0.03)
    if close:
        f.send("c", tls_app(24), think=0.02)      # close_notify, encrypted
        f.close("c")
    return f


# ===========================================================================
#  HTTP, DNS, and the rest of the plaintext protocols
# ===========================================================================
def http_req(method, uri, host, *, ua, extra=(), body=b""):
    head = [f"{method} {uri} HTTP/1.1", f"Host: {host}", f"User-Agent: {ua}"]
    head += list(extra)
    if body:
        head.append(f"Content-Length: {len(body)}")
    head.append("Connection: keep-alive")
    return ("\r\n".join(head) + "\r\n\r\n").encode() + body


def http_resp(status, *, ctype, body=b"", extra=(), server="nginx"):
    head = [f"HTTP/1.1 {status}", f"Server: {server}",
            "Date: Tue, 10 Nov 2026 17:14:30 GMT",
            f"Content-Type: {ctype}", f"Content-Length: {len(body)}"]
    head += list(extra)
    return ("\r\n".join(head) + "\r\n\r\n").encode() + body


UA = {
    "win11": "Microsoft-Delivery-Optimization/10.1",
    "edge": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
             "(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0"),
    "safari": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
               "AppleWebKit/620.1.16 (KHTML, like Gecko) Version/18.2 Safari/620.1.16"),
    "apt": "Debian APT-HTTP/1.3 (2.9.8) non-interactive",
    "curl": "curl/8.11.0",
    "ncsi": "Microsoft NCSI",
    "capnet": "CaptiveNetworkSupport-525.100.11 wispr",
    "android": "Dalvik/2.1.0 (Linux; U; Android 16; Pixel 9 Build/BP31.250610.004)",
}


def dns_query(qname, qtype="A", *, edns=True, rd=1, tid=None):
    q = DNS(id=tid if tid is not None else RNG.randrange(1, 65535), rd=rd,
            qd=DNSQR(qname=qname, qtype=qtype))
    if edns:
        q.arcount = 1
        q.ar = DNSRROPT(rclass=1232)
    return q


def dns_reply(query, answers=(), *, rcode=0, aa=1, ar_opt=True):
    an = None
    for a in answers:
        an = a if an is None else an / a
    r = DNS(id=query.id, qr=1, aa=aa, rd=1, ra=1, rcode=rcode,
            qd=query.qd, an=an, ancount=len(answers))
    if ar_opt:
        r.arcount = 1
        r.ar = DNSRROPT(rclass=1232)
    return r


def dns_pair(t, client, server, qname, qtype, answers, *, sport=None,
             rcode=0, gap=0.0016):
    """A query and its answer, the single most common exchange in the file."""
    sport = sport or RNG.randrange(49152, 65535)
    q = dns_query(qname, qtype)
    u4(t, client, server, sport, 53, q)
    u4(t + gap + jit(0.002), server, client, 53, sport,
       dns_reply(q, answers, rcode=rcode, aa=0))
    return t + gap


def mdns_query(names):
    qd = None
    for n, qt in names:
        r = DNSQR(qname=n, qtype=qt, qclass=1)
        qd = r if qd is None else qd / r
    return DNS(id=0, rd=0, qd=qd, qdcount=len(names))


def mdns_response(records):
    an = None
    for r in records:
        r.rclass = 0x8001          # cache-flush bit, as Bonjour sets it
        an = r if an is None else an / r
    return DNS(id=0, qr=1, aa=1, rd=0, an=an, ancount=len(records))


def syslog_line(pri, host, text, *, when="Nov 10 09:14:00"):
    return Raw(f"<{pri}>{when} {host} {text}".encode())


def snmp_get(community, oids, rid):
    vb = [SNMPvarbind(oid=ASN1_OID(o), value=ASN1_NULL(0)) for o in oids]
    return SNMP(community=community, PDU=SNMPget(id=rid, varbindlist=vb))


def snmp_resp(community, pairs, rid):
    vb = [SNMPvarbind(oid=ASN1_OID(o), value=v) for o, v in pairs]
    return SNMP(community=community, PDU=SNMPresponse(id=rid, varbindlist=vb))


# ---------------------------------------------------------------------------
#  STUN / TURN, which is how Teams media actually leaves the building
# ---------------------------------------------------------------------------
STUN_MAGIC = b"\x21\x12\xa4\x42"


def _stun_attr(atype, value):
    pad = (-len(value)) % 4
    return _u16(atype) + _u16(len(value)) + value + b"\x00" * pad


def stun_msg(mtype, txid, attrs):
    """A STUN message with MESSAGE-INTEGRITY and a real FINGERPRINT.

    The fingerprint is CRC-32 of the message with the length field already
    counting the fingerprint attribute, XORed with 0x5354554e (RFC 5389
    section 15.5). Get that wrong and Wireshark says so, which is a useful
    thing for students to know.
    """
    body = b"".join(attrs) + _stun_attr(0x0008, _rand(20))
    head = _u16(mtype) + _u16(len(body) + 8) + STUN_MAGIC + txid
    crc = (zlib.crc32(head + body) ^ 0x5354554E) & 0xFFFFFFFF
    body += _stun_attr(0x8028, crc.to_bytes(4, "big"))
    return Raw(_u16(mtype) + _u16(len(body)) + STUN_MAGIC + txid + body)


def stun_binding_request(txid, *, ufrag=b"J2b9:kQ1xPp"):
    """An ICE connectivity check, the way a Teams client opens its media path."""
    return stun_msg(0x0001, txid, [
        _stun_attr(0x0006, ufrag),                       # USERNAME
        _stun_attr(0x8029, _rand(8)),                    # ICE-CONTROLLED
        _stun_attr(0x0024, b"\x6e\x7f\x1e\xff"),         # PRIORITY
    ])


def stun_binding_response(txid, ip, port):
    xport = _u16(port ^ 0x2112)
    xaddr = bytes(a ^ b for a, b in zip(bytes(int(o) for o in ip.split(".")),
                                        STUN_MAGIC))
    return stun_msg(0x0101, txid, [
        _stun_attr(0x0020, b"\x00\x01" + xport + xaddr),  # XOR-MAPPED-ADDRESS
    ])


def turn_channel(chan, data):
    """TURN ChannelData: a 4-byte header, then the SRTP packet."""
    pad = (-len(data)) % 4
    return Raw(_u16(chan) + _u16(len(data)) + data + b"\x00" * pad)


def srtp_like(seq, ts, ssrc, pt, size):
    """An SRTP packet: RTP header in the clear, payload and tag encrypted."""
    hdr = bytes([0x80, pt & 0x7F]) + _u16(seq & 0xFFFF) + \
        ts.to_bytes(4, "big") + ssrc.to_bytes(4, "big")
    return hdr + _rand(size) + _rand(10)


def vrrp_adv(svi, vrid, *, priority=120, adv=100):
    """One VRRPv3 advertisement, checksummed the way current gear does it.

    RFC 5798 described the checksum as covering the message plus "a
    pseudo-header as defined in Section 8.1 of RFC 2460" -- an IPv6 reference
    with no explanation of what to do over IPv4, and implementations split
    over it. RFC 9568 settled it: over IPv4 the checksum covers the VRRP
    message alone; IPv6 still prepends the pseudo-header. Scapy computes the
    pseudo-header variant, which Wireshark now flags as bad, so this fills the
    field in by hand.
    """
    ip = IP(src=svi, dst="224.0.0.18", ttl=255, proto=112)
    args = dict(version=3, type=1, vrid=vrid, priority=priority, ipcount=1,
                adv=adv, addrlist=[f"10.21.{vrid}.1"])
    ck = checksum(bytes((ip / VRRPv3(chksum=0, **args))[VRRPv3]))
    return ip / VRRPv3(chksum=ck, **args)


# ---------------------------------------------------------------------------
#  Just enough DER to make the OCSP exchange genuine ASN.1
# ---------------------------------------------------------------------------
def _der(tag, body):
    if len(body) < 0x80:
        return bytes([tag, len(body)]) + body
    n = (len(body).bit_length() + 7) // 8
    return bytes([tag, 0x80 | n]) + len(body).to_bytes(n, "big") + body


def _der_seq(*parts):
    return _der(0x30, b"".join(parts))


def ocsp_request(serial_hex):
    """OCSPRequest ::= SEQUENCE { tbsRequest SEQUENCE { requestList ... } }"""
    sha1 = _der_seq(_der(0x06, bytes.fromhex("2b0e03021a")), _der(0x05, b""))
    cert_id = _der_seq(sha1,
                       _der(0x04, _rand(20)),            # issuerNameHash
                       _der(0x04, _rand(20)),            # issuerKeyHash
                       _der(0x02, bytes.fromhex(serial_hex)))
    return _der_seq(_der_seq(_der_seq(_der_seq(cert_id))))


def ocsp_try_later():
    """A bare OCSPResponse with responseStatus = tryLater(3) and no bytes."""
    return _der_seq(_der(0x0A, b"\x03"))


# ---------------------------------------------------------------------------
#  IPP, so the AirPrint job is a real print job
# ---------------------------------------------------------------------------
def _ipp_attr(tag, name, value):
    nb = name.encode()
    vb = value if isinstance(value, bytes) else value.encode()
    return bytes([tag]) + _u16(len(nb)) + nb + _u16(len(vb)) + vb


def ipp_print_job(printer_uri, user, job_name, doc):
    a = b"\x01"                                       # operation-attributes
    a += _ipp_attr(0x47, "attributes-charset", "utf-8")
    a += _ipp_attr(0x48, "attributes-natural-language", "en-us")
    a += _ipp_attr(0x45, "printer-uri", printer_uri)
    a += _ipp_attr(0x42, "requesting-user-name", user)
    a += _ipp_attr(0x42, "job-name", job_name)
    a += _ipp_attr(0x49, "document-format", "application/pdf")
    a += b"\x03"                                      # end-of-attributes
    return b"\x02\x00" + _u16(0x0002) + (4).to_bytes(4, "big") + a + doc


def ipp_job_ok(job_id):
    a = b"\x01"
    a += _ipp_attr(0x47, "attributes-charset", "utf-8")
    a += _ipp_attr(0x48, "attributes-natural-language", "en-us")
    a += b"\x02"                                      # job-attributes
    a += _ipp_attr(0x45, "job-uri", f"ipp://10.21.40.11/ipp/print/{job_id}")
    a += bytes([0x21]) + _u16(6) + b"job-id" + _u16(4) + job_id.to_bytes(4, "big")
    a += bytes([0x23]) + _u16(9) + b"job-state" + _u16(4) + (3).to_bytes(4, "big")
    a += _ipp_attr(0x41, "job-state-message", "Job pending.")
    a += b"\x03"
    return b"\x02\x00" + _u16(0x0000) + (4).to_bytes(4, "big") + a


# ---------------------------------------------------------------------------
#  SSH: a real binary-packet key exchange, then opaque records
# ---------------------------------------------------------------------------
# Everything up to NEWKEYS is in the clear on the wire, which is why an
# analyst can tell OpenSSH from a Cisco stack without decrypting anything.
# Random bytes with no length framing make Zeek log SSH weirds, so the
# handshake here is built properly and only the post-NEWKEYS traffic is noise.
OPENSSH_KEX = ("sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com,"
               "mlkem768x25519-sha256,curve25519-sha256,"
               "curve25519-sha256@libssh.org,ecdh-sha2-nistp256,"
               "ecdh-sha2-nistp384,ecdh-sha2-nistp521,"
               "diffie-hellman-group-exchange-sha256,"
               "diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,"
               "diffie-hellman-group14-sha256,ext-info-c,"
               "kex-strict-c-v00@openssh.com")
OPENSSH_CIPHERS = ("chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,"
                   "aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com")
OPENSSH_MACS = ("umac-64-etm@openssh.com,umac-128-etm@openssh.com,"
                "hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,"
                "hmac-sha1-etm@openssh.com,umac-64@openssh.com,"
                "umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1")
OPENSSH_HOSTKEYS = ("ssh-ed25519-cert-v01@openssh.com,"
                    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
                    "rsa-sha2-512-cert-v01@openssh.com,ssh-ed25519,"
                    "ecdsa-sha2-nistp256,rsa-sha2-512,rsa-sha2-256")


def _ssh_str(s):
    b = s.encode() if isinstance(s, str) else s
    return len(b).to_bytes(4, "big") + b


def ssh_packet(payload, *, block=8):
    """RFC 4253 binary packet: length, padding length, payload, padding."""
    pad = block - ((5 + len(payload)) % block)
    if pad < 4:
        pad += block
    return ((1 + len(payload) + pad).to_bytes(4, "big") + bytes([pad]) +
            payload + _rand(pad))


def ssh_kexinit(kex, hostkeys, ciphers, macs, comp="none,zlib@openssh.com"):
    p = bytes([20]) + _rand(16)
    for nl in (kex, hostkeys, ciphers, ciphers, macs, macs, comp, comp, "", ""):
        p += _ssh_str(nl)
    return ssh_packet(p + b"\x00" + (0).to_bytes(4, "big"))


def ssh_ecdh_init():
    return ssh_packet(bytes([30]) + _ssh_str(_rand(32)))


def ssh_ecdh_reply(keytype="ssh-ed25519"):
    hostkey = _ssh_str(keytype) + _ssh_str(_rand(32))
    sig = _ssh_str(keytype) + _ssh_str(_rand(64))
    return ssh_packet(bytes([31]) + _ssh_str(hostkey) + _ssh_str(_rand(32)) +
                      _ssh_str(sig))


def ssh_newkeys():
    return ssh_packet(bytes([21]))


# ---------------------------------------------------------------------------
#  Modbus/TCP, the building-management chatter
# ---------------------------------------------------------------------------
def modbus_read(tid, unit, start, qty):
    pdu = b"\x03" + _u16(start) + _u16(qty)
    return Raw(_u16(tid) + _u16(0) + _u16(len(pdu) + 1) + bytes([unit]) + pdu)


def modbus_values(tid, unit, values):
    data = b"".join(_u16(v) for v in values)
    pdu = b"\x03" + bytes([len(data)]) + data
    return Raw(_u16(tid) + _u16(0) + _u16(len(pdu) + 1) + bytes([unit]) + pdu)


# ---------------------------------------------------------------------------
#  SMB 3.1.1
# ---------------------------------------------------------------------------
def nbss(body):
    return b"\x00" + len(body).to_bytes(3, "big") + body


def smb2_negotiate_req():
    ctx = [
        SMB2_Negotiate_Context(ContextType=0x0001) /
        SMB2_Preauth_Integrity_Capabilities(HashAlgorithms=[0x0001],
                                            Salt=filler(32)),
        SMB2_Negotiate_Context(ContextType=0x0002) /
        SMB2_Encryption_Capabilities(Ciphers=[0x0002, 0x0001]),
    ]
    body = SMB2_Negotiate_Protocol_Request(
        Dialects=[0x0202, 0x0210, 0x0300, 0x0302, 0x0311],
        SecurityMode=3, Capabilities=0x7F,
        ClientGUID=filler(16), NegotiateContexts=ctx)
    return nbss(bytes(SMB2_Header(Command="SMB2_NEGOTIATE", MID=0,
                                  CreditRequest=31) / body))


def smb2_negotiate_resp():
    ctx = [
        SMB2_Negotiate_Context(ContextType=0x0001) /
        SMB2_Preauth_Integrity_Capabilities(HashAlgorithms=[0x0001],
                                            Salt=filler(32)),
        SMB2_Negotiate_Context(ContextType=0x0002) /
        SMB2_Encryption_Capabilities(Ciphers=[0x0002]),
    ]
    body = SMB2_Negotiate_Protocol_Response(
        DialectRevision=0x0311, SecurityMode=3, Capabilities=0x7F,
        ServerGUID=filler(16), MaxTransactionSize=8388608,
        MaxReadSize=8388608, MaxWriteSize=8388608,
        # Both of these default to "now", which would make the pcap differ on
        # every build. Pin them: the server booted nine days before capture.
        ServerTime=T0 + 31.0, ServerStartTime=T0 - 9 * 86400,
        NegotiateContexts=ctx, SecurityBlob=b"")
    return nbss(bytes(SMB2_Header(Command="SMB2_NEGOTIATE", Flags="SMB2_FLAGS_SERVER_TO_REDIR",
                                  MID=0, CreditRequest=1) / body))


def smb3_encrypted(session, size, msgid):
    """A TRANSFER of encrypted SMB3 -- what an audited file server looks
    like on the wire once SMB encryption is turned on."""
    tr = SMB2_Transform_Header(SessionId=session, OriginalMessageSize=size,
                               Nonce=_rand(11) + b"\x00" * 5, Flags=0x0001)
    return nbss(bytes(tr) + filler(size))


# ===========================================================================
#  Scene 1 -- the layer-2 control plane nobody notices until it breaks
# ===========================================================================
def scene_control_plane():
    # RSTP from the core, which is root for every VLAN. Untagged: it rides the
    # native VLAN, which is why these frames have no 802.1Q header at all.
    for i in range(int(DURATION // 2)):
        emit(T0 + 0.37 + i * 2.0,
             Dot3(src=CORE_MAC, dst=MAC_STP) /
             LLC(dsap=0x42, ssap=0x42, ctrl=3) /
             STP(proto=0, version=2, bpdutype=2, bpduflags=0x3C,
                 rootid=32768, rootmac=CORE_MAC, pathcost=0,
                 bridgeid=32768, bridgemac=CORE_MAC, portid=0x8019,
                 age=0, maxage=20, hellotime=2, fwddelay=15) /
             # RSTP adds a Version 1 Length field that scapy's STP layer does
             # not carry; without it the BPDU is one byte short and every
             # dissector calls it malformed.
             Raw(b"\x00"))

    # LLDP, every 30 s, from the devices on the far side of Po1.
    lldp_src = [
        (sw2, "TenGigabitEthernet1/1/1", "sw-floor2.corp.northstar.example",
         "Cisco IOS XE Software, Version 17.15.03, C9300-48P"),
        (ap1, "wired0", "ap-f2-01", "Meraki MR46 firmware 31.1.4"),
        (ap2, "wired0", "ap-f2-02", "Meraki MR46 firmware 31.1.4"),
        (mfp1, "1", "prn-mfp-01", "HP LaserJet Enterprise MFP M634, FutureSmart 5"),
    ]
    for n, (h, port, sysname, sysdesc) in enumerate(lldp_src):
        for i in range(int(DURATION // 30) + 1):
            t = T0 + 1.2 + n * 1.7 + i * 30.0
            if t > T0 + DURATION:
                break
            emit(t, Ether(src=h.mac, dst=MAC_LLDP, type=0x88CC) /
                 LLDPDU() /
                 LLDPDUChassisID(subtype=0x04, id=h.mac) /
                 LLDPDUPortID(subtype=0x05, id=port) /
                 LLDPDUTimeToLive(ttl=120) /
                 LLDPDUPortDescription(description=port) /
                 LLDPDUSystemName(system_name=sysname) /
                 LLDPDUSystemDescription(description=sysdesc) /
                 LLDPDUEndOfLLDPDU())

    # CDP from the core, 60 s, because the Cisco gear on both ends still runs it.
    for i in range(int(DURATION // 60) + 1):
        emit(T0 + 4.1 + i * 60.0,
             Dot3(src=CORE_MAC, dst=MAC_CDP) /
             LLC(dsap=0xAA, ssap=0xAA, ctrl=3) /
             SNAP(OUI=0x00000C, code=0x2000) /
             CDPv2_HDR(vers=2, ttl=180, msg=[
                 CDPMsgDeviceID(val=b"cs-core-01.corp.northstar.example"),
                 CDPMsgPortID(iface=b"Port-channel1"),
                 CDPMsgCapabilities(cap="Router+Switch+IGMPCapable"),
                 CDPMsgSoftwareVersion(val=b"Cisco IOS XE Software, Version 17.15.03"),
                 CDPMsgPlatform(val=b"cisco C9300-48P"),
             ]))

    # VRRPv3, one group per client VLAN, default one-second advertisement.
    # ~1200 frames of it: the single largest talker in the file, and the first
    # thing a student learns to filter out.
    for vlan, svi in ((10, "10.21.10.2"), (30, "10.21.30.2"),
                      (40, "10.21.40.2"), (50, "10.21.50.2")):
        for i in range(int(DURATION)):
            frame(T0 + 0.91 + i * 1.0 + (vlan / 1000.0), vlan, CORE_MAC,
                  MAC_VRRP, vrrp_adv(svi, vlan))

    # IPv6 on the corporate VLAN: router advertisements from both cores, then a
    # client solicitation, neighbour discovery and an MLDv2 report.
    for i in range(int(DURATION // 30) + 1):
        t = T0 + 6.4 + i * 30.0
        if t > T0 + DURATION:
            break
        for mac, ll, pref in ((CORE_MAC, "fe80::21:1", 120),
                              (CORE2_MAC, "fe80::21:2", 60)):
            frame(t + (0.4 if mac == CORE2_MAC else 0.0), 10, mac,
                  MAC_ALLNODES6,
                  IPv6(src=ll, dst="ff02::1", hlim=255) /
                  ICMPv6ND_RA(chlim=64, M=0, O=1, routerlifetime=1800,
                              prf=0 if pref == 120 else 1) /
                  ICMPv6NDOptSrcLLAddr(lladdr=mac) /
                  ICMPv6NDOptPrefixInfo(prefix="2001:db8:21:10::", prefixlen=64,
                                        validlifetime=2592000,
                                        preferredlifetime=604800))

    frame(T0 + 48.2, 10, mbp_eng.mac, MAC_ALLROUTERS6,
          IPv6(src="fe80::f218:98ff:fe5d:2a61", dst="ff02::2", hlim=255) /
          ICMPv6ND_RS() / ICMPv6NDOptSrcLLAddr(lladdr=mbp_eng.mac))
    frame(T0 + 48.9, 10, CORE_MAC, MAC_ALLNODES6,
          IPv6(src="fe80::21:1", dst="ff02::1", hlim=255) /
          ICMPv6ND_RA(chlim=64, M=0, O=1, routerlifetime=1800) /
          ICMPv6NDOptSrcLLAddr(lladdr=CORE_MAC) /
          ICMPv6NDOptPrefixInfo(prefix="2001:db8:21:10::", prefixlen=64,
                                validlifetime=2592000,
                                preferredlifetime=604800))
    # Duplicate address detection: source is the unspecified address.
    frame(T0 + 61.5, 10, andro.mac, "33:33:ff:7c:04:3b",
          IPv6(src="::", dst="ff02::1:ff7c:043b", hlim=255) /
          ICMPv6ND_NS(tgt="2001:db8:21:10:d8a1:19ff:fe7c:43b") /
          ICMPv6NDOptSrcLLAddr(lladdr=andro.mac))
    frame(T0 + 62.1, 10, dev_ubu.mac, "33:33:ff:00:00:01",
          IPv6(src=dev_ubu.ip6, dst="ff02::1:ff00:1", hlim=255) /
          ICMPv6ND_NS(tgt="2001:db8:21:10::1") /
          ICMPv6NDOptSrcLLAddr(lladdr=dev_ubu.mac))
    frame(T0 + 62.2, 10, CORE_MAC, dev_ubu.mac,
          IPv6(src="2001:db8:21:10::1", dst=dev_ubu.ip6, hlim=255) /
          ICMPv6ND_NA(tgt="2001:db8:21:10::1", R=1, S=1, O=1) /
          ICMPv6NDOptDstLLAddr(lladdr=CORE_MAC))
    for h, grp in ((mbp_eng, "ff02::fb"), (dev_ubu, "ff02::fb"),
                   (wks_fin, "ff02::1:3")):
        frame(T0 + 70.0 + jit(4), 10, h.mac, MAC_MLD6,
              IPv6(src=h.ip6 or "fe80::1:2:3:4", dst="ff02::16", hlim=1) /
              ICMPv6MLReport2(records=[
                  ICMPv6MLDMultAddrRec(dst=grp, rtype=4)]))


# ===========================================================================
#  Scene 2 -- ARP, DHCP, and the chatter of hosts finding each other
# ===========================================================================
def scene_arp_dhcp():
    # Clients ARPing for their default gateway, and the core ARPing back down.
    for n, h in enumerate((wks_fin, mbp_eng, dev_fed, iphone, mbp_mkt)):
        t = T0 + 2.0 + n * 11.3 + jit(0.8)
        frame(t, h.vlan, h.mac, MAC_BCAST,
              ARP(op=1, hwsrc=h.mac, psrc=h.ip, hwdst="00:00:00:00:00:00",
                  pdst=f"10.21.{h.vlan}.1"))
        frame(t + 0.0004, h.vlan, CORE_MAC, h.mac,
              ARP(op=2, hwsrc=CORE_MAC, psrc=f"10.21.{h.vlan}.1",
                  hwdst=h.mac, pdst=h.ip))
    # The core resolving a client it has not spoken to in a while.
    for n, h in enumerate((phone2, cam2, mfp1)):
        t = T0 + 24.0 + n * 37.0
        frame(t, h.vlan, CORE_MAC, MAC_BCAST,
              ARP(op=1, hwsrc=CORE_MAC, psrc=f"10.21.{h.vlan}.1",
                  hwdst="00:00:00:00:00:00", pdst=h.ip))
        frame(t + 0.0006, h.vlan, h.mac, CORE_MAC,
              ARP(op=2, hwsrc=h.mac, psrc=h.ip, hwdst=CORE_MAC,
                  pdst=f"10.21.{h.vlan}.1"))
    # Gratuitous ARP: a desk phone that just finished booting.
    for i in range(3):
        frame(T0 + 89.0 + i * 0.9, phone1.vlan, phone1.mac, MAC_BCAST,
              ARP(op=2, hwsrc=phone1.mac, psrc=phone1.ip,
                  hwdst="ff:ff:ff:ff:ff:ff", pdst=phone1.ip))
    # An address conflict: the scanner PC was given a static address that the
    # DHCP pool also handed to a phone. Both announce it; both are wrong.
    for i, h in enumerate((legacy, iphone)):
        frame(T0 + 142.0 + i * 0.35, 10, h.mac, MAC_BCAST,
              ARP(op=2, hwsrc=h.mac, psrc=iphone.ip, hwdst=MAC_BCAST,
                  pdst=iphone.ip))

    # A full DHCP handshake: the Android handset coming back from sleep. The
    # core is the relay agent, so the replies arrive with its MAC and giaddr.
    xid = 0x7A3C9E21
    disc_opts = [("message-type", "discover"),
                 ("client_id", b"\x01" + bytes.fromhex(andro.mac.replace(":", ""))),
                 ("hostname", b"pixel-rsmith"),
                 ("vendor_class_id", b"android-dhcp-16"),
                 ("param_req_list", [1, 3, 6, 15, 26, 28, 51, 58, 59, 43]),
                 ("max_dhcp_size", 1500), "end"]
    frame(T0 + 31.1, 10, andro.mac, MAC_BCAST,
          IP(src="0.0.0.0", dst="255.255.255.255", ttl=64) /
          UDP(sport=68, dport=67) /
          BOOTP(op=1, xid=xid, flags=0,
                chaddr=bytes.fromhex(andro.mac.replace(":", ""))) /
          DHCP(options=disc_opts))
    srv_opts = lambda kind: [("message-type", kind), ("server_id", dc01.ip),
                             ("lease_time", 28800), ("renewal_time", 14400),
                             ("rebinding_time", 25200),
                             ("subnet_mask", "255.255.255.0"),
                             ("router", "10.21.10.1"),
                             ("name_server", dc01.ip),
                             ("domain", b"corp.northstar.example"), "end"]
    frame(T0 + 31.14, 10, CORE_MAC, andro.mac,
          IP(src=dc01.ip, dst=andro.ip, ttl=127) / UDP(sport=67, dport=68) /
          BOOTP(op=2, xid=xid, yiaddr=andro.ip, siaddr=dc01.ip,
                giaddr="10.21.10.1",
                chaddr=bytes.fromhex(andro.mac.replace(":", ""))) /
          DHCP(options=srv_opts("offer")))
    frame(T0 + 31.16, 10, andro.mac, MAC_BCAST,
          IP(src="0.0.0.0", dst="255.255.255.255", ttl=64) /
          UDP(sport=68, dport=67) /
          BOOTP(op=1, xid=xid,
                chaddr=bytes.fromhex(andro.mac.replace(":", ""))) /
          DHCP(options=[("message-type", "request"),
                        ("client_id", b"\x01" + bytes.fromhex(andro.mac.replace(":", ""))),
                        ("requested_addr", andro.ip),
                        ("server_id", dc01.ip),
                        ("hostname", b"pixel-rsmith"),
                        ("param_req_list", [1, 3, 6, 15, 26, 28, 51, 58, 59, 43]),
                        "end"]))
    frame(T0 + 31.19, 10, CORE_MAC, andro.mac,
          IP(src=dc01.ip, dst=andro.ip, ttl=127) / UDP(sport=67, dport=68) /
          BOOTP(op=2, xid=xid, yiaddr=andro.ip, siaddr=dc01.ip,
                giaddr="10.21.10.1",
                chaddr=bytes.fromhex(andro.mac.replace(":", ""))) /
          DHCP(options=srv_opts("ack")))

    # Mid-lease renewals are unicast, so they are routed like any other packet.
    for n, h in enumerate((wks_fin, mfp1)):
        t = T0 + 118.0 + n * 63.0
        rxid = RNG.randrange(1, 2 ** 32 - 1)
        chaddr = bytes.fromhex(h.mac.replace(":", ""))
        u4(t, h, dc01, 68, 67,
           BOOTP(op=1, xid=rxid, ciaddr=h.ip, chaddr=chaddr) /
           DHCP(options=[("message-type", "request"),
                         ("client_id", b"\x01" + chaddr),
                         ("param_req_list", [1, 3, 6, 15, 31, 33, 43, 44, 46, 47]),
                         "end"]))
        u4(t + 0.0031, dc01, h, 67, 68,
           BOOTP(op=2, xid=rxid, yiaddr=h.ip, ciaddr=h.ip, siaddr=dc01.ip,
                 chaddr=chaddr) /
           DHCP(options=srv_opts("ack")))

    # DHCPv6 information-request: the RA set the Other-config flag, so the
    # Linux box asks for DNS servers and nothing else.
    duid = DUID_LLT(lladdr=dev_ubu.mac, timeval=0x2E4A1B70)
    frame(T0 + 96.3, 10, dev_ubu.mac, "33:33:00:01:00:02",
          IPv6(src="fe80::8e16:45ff:fe2f:10aa", dst="ff02::1:2", hlim=1) /
          UDP(sport=546, dport=547) /
          DHCP6_InfoRequest(trid=0x9C21A4) /
          DHCP6OptClientId(duid=duid) /
          DHCP6OptElapsedTime(elapsedtime=0) /
          DHCP6OptOptReq(reqopts=[23, 24, 56]))
    frame(T0 + 96.31, 10, CORE_MAC, dev_ubu.mac,
          IPv6(src="fe80::21:1", dst="fe80::8e16:45ff:fe2f:10aa", hlim=64) /
          UDP(sport=547, dport=546) /
          DHCP6_Reply(trid=0x9C21A4) /
          DHCP6OptClientId(duid=duid) /
          DHCP6OptServerId(duid=DUID_LL(lladdr=CORE_MAC)) /
          DHCP6OptDNSServers(dnsservers=["2001:db8:21:20::10"]) /
          DHCP6OptDNSDomains(dnsdomains=["corp.northstar.example"]))


# ===========================================================================
#  Scene 3 -- name resolution: unicast DNS, mDNS, and the legacy leftovers
# ===========================================================================
A_REC = {
    "outlook.cloud.microsoft": x_exo.ip,
    "teams.cloud.microsoft": x_teams_sig.ip,
    "northstarlogistics.sharepoint.com": x_spo.ip,
    "login.microsoftonline.com": x_aad.ip,
    "graph.microsoft.com": x_graph.ip,
    "www.msftconnecttest.com": x_ncsi.ip,
    "tlu.dl.delivery.mp.microsoft.com": x_wu_cdn.ip,
    "kv801.prod.do.dsp.mp.microsoft.com": x_do_svc.ip,
    "ts01-b.cloudsink.net": x_edr.ip,
    "time.windows.com": x_mstime.ip,
    "captive.apple.com": x_apple_cap.ip,
    "17-courier.push.apple.com": x_apple_apn.ip,
    "p54-ckdatabase.icloud.com": x_icloud.ip,
    "formulae.brew.sh": x_brew.ip,
    "ocsp.digicert.com": x_digicert.ip,
    "github.com": x_github.ip,
    "codeload.github.com": x_gh_cdn.ip,
    "archive.ubuntu.com": x_ubuntu.ip,
    "ntp.ubuntu.com": x_ubu_ntp.ip,
    "dl.fedoraproject.org": x_fedora.ip,
    "registry-1.docker.io": x_docker.ip,
    "slack.com": x_slack.ip,
    "northstar.okta.com": x_okta.ip,
    "zoom.us": x_zoom.ip,
    "connectivitycheck.gstatic.com": x_gstatic.ip,
    "fs01.corp.northstar.example": fs01.ip,
    "dc01.corp.northstar.example": dc01.ip,
    "prn-mfp-01.corp.northstar.example": mfp1.ip,
}
AAAA_REC = {
    "outlook.cloud.microsoft": "2603:1016:2400:21::5",
    "northstarlogistics.sharepoint.com": "2620:1ec:8f8:1::10",
    "login.microsoftonline.com": "2603:1006:2000:20::17",
    "github.com": "2606:50c0:8000::153",
    "connectivitycheck.gstatic.com": "2607:f8b0:400a:803::2003",
    "dc01.corp.northstar.example": dc01.ip6,
}


def dns_scene_pair(t, client, qname, qtype="A", rcode=0, ttl=300):
    """Query plus answer, filled in from the zone tables above."""
    answers = []
    if rcode == 0:
        if qtype == "A" and qname in A_REC:
            answers = [DNSRR(rrname=qname, type="A", ttl=ttl, rdata=A_REC[qname])]
        elif qtype == "AAAA" and qname in AAAA_REC:
            answers = [DNSRR(rrname=qname, type="AAAA", ttl=ttl,
                             rdata=AAAA_REC[qname])]
    return dns_pair(t, client, dc01, qname, qtype, answers, rcode=rcode)


def scene_dns():
    plan = [
        (wks_fin, 3.2, "outlook.cloud.microsoft", "A"),
        (wks_fin, 3.21, "outlook.cloud.microsoft", "AAAA"),
        (wks_fin, 7.4, "teams.cloud.microsoft", "A"),
        (wks_fin, 7.42, "teams.cloud.microsoft", "AAAA"),
        (wks_fin, 12.9, "northstarlogistics.sharepoint.com", "A"),
        (wks_fin, 13.0, "fs01.corp.northstar.example", "A"),
        (wks_fin, 44.6, "login.microsoftonline.com", "A"),
        (wks_sales, 5.8, "outlook.cloud.microsoft", "A"),
        (wks_sales, 18.2, "teams.cloud.microsoft", "A"),
        (wks_sales, 23.5, "kv801.prod.do.dsp.mp.microsoft.com", "A"),
        (wks_sales, 24.1, "tlu.dl.delivery.mp.microsoft.com", "A"),
        (wks_sales, 96.2, "graph.microsoft.com", "A"),
        (legacy, 57.3, "ts01-b.cloudsink.net", "A"),
        (legacy, 148.9, "www.msftconnecttest.com", "A"),
        (mbp_eng, 9.1, "captive.apple.com", "A"),
        (mbp_eng, 15.6, "17-courier.push.apple.com", "A"),
        (mbp_eng, 21.8, "p54-ckdatabase.icloud.com", "A"),
        (mbp_eng, 73.4, "formulae.brew.sh", "A"),
        (mbp_eng, 112.7, "ocsp.digicert.com", "A"),
        (mbp_mkt, 29.3, "slack.com", "A"),
        (mbp_mkt, 35.1, "zoom.us", "A"),
        (mbp_mkt, 61.2, "northstar.okta.com", "A"),
        (dev_ubu, 11.4, "archive.ubuntu.com", "A"),
        (dev_ubu, 11.45, "archive.ubuntu.com", "AAAA"),
        (dev_ubu, 40.7, "github.com", "A"),
        (dev_ubu, 40.75, "github.com", "AAAA"),
        (dev_ubu, 86.1, "registry-1.docker.io", "A"),
        (dev_ubu, 171.3, "ntp.ubuntu.com", "A"),
        (dev_fed, 52.8, "dl.fedoraproject.org", "A"),
        (dev_fed, 131.6, "codeload.github.com", "A"),
        (andro, 19.7, "connectivitycheck.gstatic.com", "A"),
        (andro, 19.74, "connectivitycheck.gstatic.com", "AAAA"),
        (iphone, 67.5, "17-courier.push.apple.com", "A"),
        (mbp_eng, 183.2, "prn-mfp-01.corp.northstar.example", "A"),
        (dev_ubu, 202.4, "dc01.corp.northstar.example", "AAAA"),
    ]
    for h, off, name, qt in plan:
        dns_scene_pair(T0 + off, h, name, qt)

    # An SRV lookup: this is a domain-joined machine locating a domain
    # controller before it authenticates.
    q = dns_query("_ldap._tcp.dc._msdcs.corp.northstar.example", "SRV")
    sport = 51234
    u4(T0 + 27.0, wks_fin, dc01, sport, 53, q)
    u4(T0 + 27.0022, dc01, wks_fin, 53, sport,
       dns_reply(q, [DNSRRSRV(rrname="_ldap._tcp.dc._msdcs.corp.northstar.example",
                              ttl=600, priority=0, weight=100, port=389,
                              target="dc01.corp.northstar.example")]))

    # A reverse lookup, the way a help-desk script does it.
    q = dns_query("11.40.21.10.in-addr.arpa", "PTR")
    u4(T0 + 155.4, dev_ubu, dc01, 44301, 53, q)
    u4(T0 + 155.4019, dc01, dev_ubu, 53, 44301,
       dns_reply(q, [DNSRR(rrname="11.40.21.10.in-addr.arpa", type="PTR",
                           ttl=1200,
                           rdata="prn-mfp-01.corp.northstar.example")]))

    # WPAD: the name does not exist, and Windows asks anyway. Classic finding.
    for off, h in ((38.4, wks_sales), (38.9, legacy), (206.7, wks_fin)):
        dns_scene_pair(T0 + off, h, "wpad.corp.northstar.example", "A", rcode=3)
    # A fat-fingered hostname, and a zone whose DNSSEC is broken this morning.
    dns_scene_pair(T0 + 99.8, wks_fin, "sharepoiint.com", "A", rcode=3)
    dns_scene_pair(T0 + 128.3, mbp_mkt, "metrics.badzone.example", "A", rcode=2)

    # mDNS. Apple gear drives most of it; the Fedora box runs avahi; the
    # printers answer. Note the cache-flush bit on the responses.
    mdns_plan = [
        (mbp_eng, 8.3, [("_ipp._tcp.local", "PTR"), ("_ipps._tcp.local", "PTR")]),
        (mbp_eng, 8.9, [("_airplay._tcp.local", "PTR")]),
        (iphone, 26.4, [("_companion-link._tcp.local", "PTR")]),
        (mbp_mkt, 55.2, [("_ipp._tcp.local", "PTR")]),
        (dev_fed, 79.6, [("_workstation._tcp.local", "PTR")]),
        (mbp_eng, 134.8, [("prn-mfp-01.local", "A")]),
        (iphone, 177.1, [("_raop._tcp.local", "PTR")]),
        (andro, 213.5, [("_googlecast._tcp.local", "PTR")]),
    ]
    for h, off, names in mdns_plan:
        mcast4(T0 + off, h, "224.0.0.251", MAC_MDNS, 5353, 5353,
               mdns_query(names), ttl=255)
        if h.ip6:
            mcast6(T0 + off + 0.0008, h, "ff02::fb", MAC_MDNS6, 5353, 5353,
                   mdns_query(names), hlim=255,
                   src6=h.ip6)
    # The MFP answering the printer discovery, and announcing itself.
    for off in (8.42, 55.31, 134.83):
        mcast4(T0 + off, mfp1, "224.0.0.251", MAC_MDNS, 5353, 5353,
               mdns_response([
                   DNSRR(rrname="_ipp._tcp.local", type="PTR", ttl=4500,
                         rdata="HP LaserJet MFP M634 [7E4109]._ipp._tcp.local"),
                   DNSRR(rrname="prn-mfp-01.local", type="A", ttl=120,
                         rdata=mfp1.ip),
               ]), ttl=255)
    for off in (101.2, 251.7):
        mcast4(T0 + off, mfp2, "224.0.0.251", MAC_MDNS, 5353, 5353,
               mdns_response([
                   DNSRR(rrname="prn-mfp-02.local", type="A", ttl=120,
                         rdata=mfp2.ip)]), ttl=255)

    # LLMNR and NBT-NS, still alive on the scanner PC. Nothing answers.
    for off, name in ((45.1, "fileserver"), (45.6, "fileserver"),
                      (164.2, "wpad"), (164.8, "wpad")):
        mcast4(T0 + off, legacy, "224.0.0.252", MAC_LLMNR, 55213, 5355,
               DNS(id=RNG.randrange(1, 65535), rd=0,
                   qd=DNSQR(qname=name, qtype="A", qclass=1)), ttl=1)
    for off, name in ((46.2, "FILESERVER"), (165.4, "WPAD")):
        mcast4(T0 + off, legacy, "10.21.10.255", MAC_BCAST, 137, 137,
               NBNSHeader(NAME_TRN_ID=RNG.randrange(1, 65535), NM_FLAGS=0x11) /
               NBNSQueryRequest(QUESTION_NAME=name), ttl=128)

    # SSDP: a Windows box looking for anything castable in the conference room.
    for off in (33.7, 113.4, 193.1):
        msearch = ("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\n"
                   'MAN: "ssdp:discover"\r\nMX: 1\r\n'
                   "ST: urn:dial-multiscreen-org:service:dial:1\r\n"
                   "USER-AGENT: Microsoft Edge/141.0.0.0 Windows\r\n\r\n")
        mcast4(T0 + off, wks_sales, "239.255.255.250", MAC_SSDP, 56121, 1900,
               Raw(msearch.encode()), ttl=1)
    for off in (34.2, 114.0):
        notify = ("NOTIFY * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\n"
                  "CACHE-CONTROL: max-age=1800\r\n"
                  "LOCATION: http://10.21.40.11:8060/dial/dd.xml\r\n"
                  "NT: urn:dial-multiscreen-org:service:dial:1\r\n"
                  "NTS: ssdp:alive\r\nSERVER: HP/1.0 UPnP/1.0\r\n"
                  "USN: uuid:7e410903-1b2c-4d5e::urn:dial-multiscreen-org:"
                  "service:dial:1\r\n\r\n")
        mcast4(T0 + off, mfp1, "239.255.255.250", MAC_SSDP, 1900, 1900,
               Raw(notify.encode()), ttl=4)


# ===========================================================================
#  Scene 4 -- Active Directory: Kerberos, LDAPS, SMB 3.1.1
# ===========================================================================
REALM = b"CORP.NORTHSTAR.EXAMPLE"
G = ASN1_GENERAL_STRING


def principal(ntype, parts):
    return KRB.PrincipalName(nameType=ntype, nameString=[G(p) for p in parts])


def krb_tcp(msg):
    return bytes(KRB.KerberosTCPHeader() / msg)


def scene_kerberos():
    """A real Kerberos morning: pre-auth required, pre-auth supplied, then a
    service ticket for the file server."""
    till = ASN1_GENERALIZED_TIME(b"20261111031400Z")
    cname = principal(1, [b"jlin"])
    krbtgt = principal(2, [b"krbtgt", REALM])

    def req_body(sname, nonce, etypes=(18, 17, 23)):
        return KRB.KRB_KDC_REQ_BODY(
            # KDCOptions is a 32-bit BIT STRING (RFC 4120 sect 5.4.1), and
            # scapy's default encodes a single byte -- which parsers that
            # read all four, Zeek among them, run straight off the end of.
            # These are the bits a domain-joined Windows client sets.
            kdcOptions="forwardable+renewable+canonicalize+renewable-ok",
            cname=cname, realm=G(REALM), sname=sname, till=till, rtime=till,
            nonce=nonce, etype=list(etypes))

    f = TcpFlow(T0 + 27.05, wks_fin, dc01, 50112, 88)
    f.open()
    f.send("c", krb_tcp(KRB.KRB_AS_REQ(
        padata=[KRB.PADATA(padataType=128,
                           padataValue=KRB.PA_PAC_REQUEST(includePac=True))],
        reqBody=req_body(krbtgt, 0x5F3A21CC))), think=0.0012)
    f.send("s", krb_tcp(KRB.KRB_ERROR(
        errorCode=25, realm=G(REALM), sname=krbtgt,
        stime=ASN1_GENERALIZED_TIME(b"20261110171427Z"), susec=491822,
        eText=G(b"NEEDED_PREAUTH"))), think=0.0023)
    f.close("c", think=0.002)

    f = TcpFlow(T0 + 27.12, wks_fin, dc01, 50113, 88)
    f.open()
    f.send("c", krb_tcp(KRB.KRB_AS_REQ(
        padata=[KRB.PADATA(padataType=2,
                           padataValue=KRB.EncryptedData(etype=18,
                                                         cipher=_rand(56))),
                KRB.PADATA(padataType=128,
                           padataValue=KRB.PA_PAC_REQUEST(includePac=True))],
        reqBody=req_body(krbtgt, 0x5F3A21CD, (18,)))), think=0.0014)
    tgt = KRB.KRB_Ticket(tktVno=5, realm=G(REALM), sname=krbtgt,
                         encPart=KRB.EncryptedData(etype=18, kvno=2,
                                                   cipher=_rand(1024)))
    f.send("s", krb_tcp(KRB.KRB_AS_REP(
        crealm=G(REALM), cname=cname, ticket=tgt,
        encPart=KRB.EncryptedData(etype=18, kvno=9, cipher=_rand(368)))),
        think=0.0071)
    f.close("c", think=0.003)

    # Service ticket for CIFS on the file server, right before the SMB session.
    f = TcpFlow(T0 + 29.4, wks_fin, dc01, 50119, 88)
    f.open()
    apreq = KRB.KRB_AP_REQ(
        # APOptions is 32 bits wide too, for the same reason as KDCOptions
        # above; this is mutual-required, the bit a Windows client sets.
        apOptions=ASN1_BIT_STRING("00100000" + "0" * 24),
        ticket=tgt,
        authenticator=KRB.EncryptedData(etype=18, kvno=9,
                                        cipher=_rand(176)))
    cifs = principal(2, [b"cifs", b"fs01.corp.northstar.example"])
    f.send("c", krb_tcp(KRB.KRB_TGS_REQ(
        padata=[KRB.PADATA(padataType=1, padataValue=apreq)],
        # rtime defaults to "now" in scapy, which would break reproducibility.
        reqBody=KRB.KRB_KDC_REQ_BODY(
            kdcOptions="forwardable+renewable+canonicalize",
            realm=G(REALM), sname=cifs, till=till, rtime=till,
            nonce=0x11A2B3C4, etype=[18]))),
        think=0.0016)
    f.send("s", krb_tcp(KRB.KRB_TGS_REP(
        # scapy's KDC-REP leaves msg-type at 11 (AS-REP) for a TGS-REP too.
        msgType=13, crealm=G(REALM), cname=cname,
        ticket=KRB.KRB_Ticket(tktVno=5, realm=G(REALM), sname=cifs,
                              encPart=KRB.EncryptedData(etype=18, kvno=4,
                                                        cipher=_rand(1456))),
        encPart=KRB.EncryptedData(etype=18, kvno=9, cipher=_rand(304)))),
        think=0.0049)
    f.close("c", think=0.0025)


def scene_ldaps_smb():
    # Group Policy refresh over LDAPS -- the client's own certificate check
    # happens inside TLS, so all you see from outside is the SNI.
    tls_session(T0 + 36.2, wks_fin, dc01, "dc01.corp.northstar.example",
                sport=50201, dport=636, up=820, down=9400)
    tls_session(T0 + 121.5, legacy, dc01, "dc01.corp.northstar.example",
                sport=50288, dport=636, up=640, down=7100)

    # SMB 3.1.1 to the file server. Negotiate is in the clear; everything
    # after session setup is wrapped in SMB3 transform headers, because the
    # share requires encryption.
    f = TcpFlow(T0 + 29.9, wks_fin, fs01, 50224, 445, win_raw=1024)
    f.open()
    f.send("c", smb2_negotiate_req(), think=0.0011)
    f.send("s", smb2_negotiate_resp(), think=0.0019)
    sid = 0x0000A10000000085
    # Session setup, tree connect, create -- all encrypted at this point.
    for mid, size in ((2, 448), (3, 288), (4, 376), (5, 232)):
        f.send("c", smb3_encrypted(sid, size, mid), think=0.0014)
        f.send("s", smb3_encrypted(sid, size + 96, mid), think=0.0021)
    # Reading a 1.2 MB workbook in 64 KB chunks.
    for n in range(18):
        f.send("c", smb3_encrypted(sid, 180, 10 + n), think=0.0013)
        if n == 7:
            # One chunk goes missing on the way down: three duplicate ACKs
            # with a SACK block, then the retransmission.
            lost = smb3_encrypted(sid, 1400, 10 + n)   # one full-size segment
            seq = f.seq["s"]
            f.seg("s", "PA", lost, advance=True)
            f.retransmit("s", lost, seq)
        f.send("s", smb3_encrypted(sid, 65536, 10 + n), think=0.0024,
               ack_every=4)
    f.send("c", smb3_encrypted(sid, 204, 90), think=0.004)   # close + logoff
    f.send("s", smb3_encrypted(sid, 148, 90), think=0.0017)
    f.close("c", think=0.03)


# ===========================================================================
#  Scene 5 -- Microsoft 365, SaaS, and the TLS/QUIC mix of a modern desk
# ===========================================================================
def quic_short(dcid, pn, size):
    """A 1-RTT QUIC packet: short header, then nothing you can read."""
    return Raw(bytes([0x41]) + dcid + pn.to_bytes(2, "big") + _rand(size))


def quic_initial(dcid, scid, pn, size):
    """A QUIC v1 Initial. Long header, so the version and both connection IDs
    are in the clear -- which is what lets a dissector follow the rest of the
    flow once it has seen one."""
    body = pn.to_bytes(4, "big") + _rand(size)
    return Raw(bytes([0xC3]) + b"\x00\x00\x00\x01" +
               bytes([len(dcid)]) + dcid + bytes([len(scid)]) + scid +
               b"\x00" + _u16(0x4000 | len(body)) + body)


def quic_flow(t, c, s, sport, *, up_pkts, down_pkts, up_size=320,
              down_size=1250, pps=240, dscp=0):
    """A QUIC exchange on UDP/443: Wireshark shows the protected payloads."""
    dcid_s = _rand(8)
    dcid_c = _rand(8)
    # The handshake first, padded out the way a real client pads an Initial.
    u4(t, c, s, sport, 443, quic_initial(dcid_s, dcid_c, 1, 1182), dscp=dscp)
    u4(t + 0.019, s, c, 443, sport, quic_initial(dcid_c, dcid_s, 1, 1182),
       dscp=dscp)
    t += 0.028
    pn = 1
    gap = 1.0 / pps
    sent = recvd = 0
    while sent < up_pkts or recvd < down_pkts:
        if sent < up_pkts:
            u4(t, c, s, sport, 443, quic_short(dcid_s, pn, up_size), dscp=dscp)
            sent += 1
        for _ in range(max(1, down_pkts // max(up_pkts, 1))):
            if recvd < down_pkts:
                t += gap * 0.25
                u4(t + 0.012, s, c, 443, sport,
                   quic_short(dcid_c, pn, down_size), dscp=dscp)
                recvd += 1
        pn += 1
        t += gap
    return t


def scene_m365():
    # Outlook: one long-lived connection with keepalives, which is what makes
    # Exchange Online flows look so different from web browsing.
    tls_session(T0 + 3.4, wks_fin, x_exo, "outlook.cloud.microsoft",
                sport=50302, up=1850, down=38000, keepalives=9,
                keepalive_gap=28.0, close=False)
    tls_session(T0 + 6.0, wks_sales, x_exo, "outlook.cloud.microsoft",
                sport=50341, up=1640, down=24500, keepalives=7,
                keepalive_gap=33.0, close=False)
    # Teams signalling: TLS to the service, then media leaves over UDP.
    tls_session(T0 + 7.6, wks_fin, x_teams_sig, "teams.cloud.microsoft",
                sport=50355, up=2100, down=15400, keepalives=11,
                keepalive_gap=22.0, close=False)
    tls_session(T0 + 18.4, wks_sales, x_teams_sig, "teams.cloud.microsoft",
                sport=50361, up=1960, down=12800, keepalives=8,
                keepalive_gap=30.0, close=False)
    # Entra ID sign-in, then Graph, then SharePoint.
    # This one is the browser, not Schannel, so its Client Hello differs from
    # the Outlook session on the same machine.
    tls_session(T0 + 44.8, wks_fin, x_aad, "login.microsoftonline.com",
                sport=50402, up=2600, down=11200, profile="edge")
    tls_session(T0 + 96.4, wks_sales, x_graph, "graph.microsoft.com",
                sport=50431, up=1180, down=6400)
    # A deck going up to SharePoint over TLS, and the same site's static
    # content coming back over QUIC -- both are normal for M365 now.
    tls_session(T0 + 13.1, wks_fin, x_spo, "northstarlogistics.sharepoint.com",
                sport=50377, up=920000, down=4200, bw=3.2e7)
    quic_flow(T0 + 58.2, wks_sales, x_spo, 54211, up_pkts=42, down_pkts=260)
    quic_flow(T0 + 152.6, wks_fin, x_exo, 54288, up_pkts=26, down_pkts=120)
    # Endpoint protection telemetry: small, constant, and always encrypted.
    tls_session(T0 + 57.5, legacy, x_edr, "ts01-b.cloudsink.net",
                sport=50455, up=740, down=1100, keepalives=6,
                keepalive_gap=40.0, close=False)
    # Okta, Slack and Zoom, from the Macs.
    tls_session(T0 + 61.4, mbp_mkt, x_okta, "northstar.okta.com",
                sport=50611, up=1420, down=9300)
    tls_session(T0 + 29.6, mbp_mkt, x_slack, "slack.com", sport=50622,
                up=2200, down=48000, keepalives=9, keepalive_gap=26.0,
                close=False)
    tls_session(T0 + 35.4, mbp_mkt, x_zoom, "zoom.us", sport=50633,
                up=1600, down=14200, keepalives=4, keepalive_gap=35.0,
                close=False)


def scene_windows_update():
    # The Delivery Optimization client checks in with the cloud service...
    tls_session(T0 + 23.8, wks_sales, x_do_svc,
                "kv801.prod.do.dsp.mp.microsoft.com", sport=50701,
                up=1240, down=3800)
    # ...then pulls content over plain HTTP, which is still how Windows
    # Update ships its payloads. Watch the Range headers.
    f = TcpFlow(T0 + 24.4, wks_sales, x_wu_cdn, 50712, 80, bw=6.4e7)
    f.open()
    for i in range(4):
        lo = i * 65536
        req = http_req("GET",
                       "/c/msdownload/update/software/updt/2026/11/"
                       "windows11.0-kb5079271-x64_8f2a1c9e4b.cab",
                       "tlu.dl.delivery.mp.microsoft.com", ua=UA["win11"],
                       extra=[f"Range: bytes={lo}-{lo + 65535}",
                              "Accept-Encoding: identity",
                              "X-DO-Caller: do-client"])
        f.send("c", req, think=0.004 if i else 0.0)
        body = filler(65536)
        f.send("s", http_resp("206 Partial Content",
                              ctype="application/octet-stream", body=body,
                              server="ECAcc (dcd/7D2A)",
                              extra=[f"Content-Range: bytes {lo}-{lo + 65535}/2097152",
                                     "X-Cache: TCP_HIT"]),
               think=0.021, ack_every=5)
    f.close("c", think=0.05)

    # Peer-to-peer Delivery Optimization on TCP 7680, to a machine on the
    # floor-1 stack. Same VLAN, so the core only bridges it: real MACs on both
    # ends and no TTL decrement. That is the giveaway that it never left.
    f = TcpFlow(T0 + 88.6, wks_sales, wks_hr, 50733, 7680)
    f.open()
    for i in range(3):
        f.send("c", http_req("GET", f"/content/piece/{i}", wks_hr.ip,
                             ua=UA["win11"],
                             extra=["X-DO-ContentId: 8f2a1c9e-4b11-4d7e",
                                    f"Range: bytes={i * 131072}-{(i + 1) * 131072 - 1}"]),
               think=0.003 if i else 0.0)
        f.send("s", http_resp("206 Partial Content",
                              ctype="application/octet-stream",
                              body=filler(131072), server="Microsoft-DO/10.1",
                              extra=["X-DO-BlockCount: 16"]),
               think=0.0035, ack_every=6)
    f.close("c", think=0.02)

    # NCSI: how Windows decides it has Internet. DNS first, then a 14-byte GET.
    for off, h in ((148.95, legacy), (238.4, wks_sales)):
        f = TcpFlow(T0 + off, h, x_ncsi, RNG.randrange(50000, 50999), 80)
        f.open()
        f.send("c", http_req("GET", "/connecttest.txt",
                             "www.msftconnecttest.com", ua=UA["ncsi"],
                             extra=["Cache-Control: no-cache"]), think=0.0009)
        f.send("s", http_resp("200 OK", ctype="text/plain",
                              body=b"Microsoft Connect Test",
                              server="Microsoft-IIS/10.0"), think=0.019)
        f.close("c", think=0.004)

    # WPAD over HTTP, after DNS said no: the client tries the proxy name
    # anyway and gets a 404 from the internal web server.
    f = TcpFlow(T0 + 207.1, wks_fin, fs01, 50801, 80)
    f.open()
    f.send("c", http_req("GET", "/wpad.dat", "wpad.corp.northstar.example",
                         ua="WinHttp-Autoproxy-Service/5.1"), think=0.001)
    f.send("s", http_resp("404 Not Found", ctype="text/html",
                          body=b"<html><head><title>404 - File or directory "
                               b"not found.</title></head></html>",
                          server="Microsoft-IIS/10.0"), think=0.0024)
    f.close("s", think=0.002)


# ===========================================================================
#  Scene 6 -- the Apple corner: Bonjour, APNs, OCSP, AirPrint
# ===========================================================================
def scene_apple():
    # The push connection: TLS on 5223, then almost nothing for minutes.
    tls_session(T0 + 15.9, mbp_eng, x_apple_apn, "17-courier.push.apple.com",
                sport=50901, dport=5223, up=420, down=680, keepalives=8,
                keepalive_gap=31.0, close=False)
    tls_session(T0 + 67.9, iphone, x_apple_apn, "17-courier.push.apple.com",
                sport=50911, dport=5223, up=380, down=520, keepalives=5,
                keepalive_gap=38.0, close=False)
    tls_session(T0 + 22.1, mbp_eng, x_icloud, "p54-ckdatabase.icloud.com",
                sport=50922, up=4200, down=31000, keepalives=3,
                keepalive_gap=44.0)
    tls_session(T0 + 73.8, mbp_eng, x_brew, "formulae.brew.sh", sport=50933,
                up=980, down=184000)

    # The captive-portal probe every Mac and iPhone makes, in the clear.
    for off, h in ((9.4, mbp_eng), (121.2, iphone)):
        f = TcpFlow(T0 + off, h, x_apple_cap, RNG.randrange(51000, 51999), 80)
        f.open()
        f.send("c", http_req("GET", "/hotspot-detect.html",
                             "captive.apple.com", ua=UA["capnet"]),
               think=0.0008)
        f.send("s", http_resp("200 OK", ctype="text/html",
                              body=b"<HTML><HEAD><TITLE>Success</TITLE></HEAD>"
                                   b"<BODY>Success</BODY></HTML>",
                              server="AppleHttpServer/5bfb6b4fd1"),
               think=0.018)
        f.close("c", think=0.003)

    # Certificate status over HTTP: OCSP POST, then a CRL fetch. Both plain.
    f = TcpFlow(T0 + 113.0, mbp_eng, x_digicert, 51210, 80)
    f.open()
    f.send("c", http_req("POST", "/", "ocsp.digicert.com", ua=UA["safari"],
                         extra=["Content-Type: application/ocsp-request"],
                         body=ocsp_request("039ac4fa1d2b7e0c91")), think=0.001)
    # The responder is having a morning: tryLater, so the client soft-fails
    # and falls back to the CRL it already has cached.
    f.send("s", http_resp("200 OK", ctype="application/ocsp-response",
                          body=ocsp_try_later(), server="nginx/1.26.2",
                          extra=["Cache-Control: max-age=60"]),
           think=0.026)
    f.send("c", http_req("GET", "/DigiCertGlobalG3TLSECC2021.crl",
                         "crl3.digicert.com", ua=UA["safari"],
                         extra=["If-Modified-Since: Sun, 08 Nov 2026 "
                                "11:03:41 GMT"]), think=0.03)
    f.send("s", http_resp("304 Not Modified", ctype="application/pkix-crl",
                          server="nginx/1.26.2",
                          extra=["Last-Modified: Sun, 08 Nov 2026 11:03:41 GMT"]),
           think=0.024)
    f.close("c", think=0.04)

    # AirPrint: a real IPP Print-Job operation with a PDF behind it.
    f = TcpFlow(T0 + 184.0, mbp_eng, mfp1, 51301, 631)
    f.open()
    doc = filler(176000)
    job = ipp_print_job("ipp://prn-mfp-01.local:631/ipp/print", "kmcgrath",
                        "Q4-forecast.pdf", doc)
    f.send("c", http_req("POST", "/ipp/print", "prn-mfp-01.local:631",
                         ua="CUPS/2.4.11 (Darwin 24.2.0; x86_64) IPP/2.0",
                         extra=["Content-Type: application/ipp",
                                "Expect: 100-continue"],
                         body=job), think=0.0012, ack_every=5)
    f.send("s", http_resp("200 OK", ctype="application/ipp",
                          body=ipp_job_ok(412), server="HP HTTP Server; "
                          "HP LaserJet MFP M634"), think=0.14)
    f.close("c", think=0.01)

    # And the printer phoning home to its vendor.
    tls_session(T0 + 231.4, mfp1, x_hpcloud, "h30495.www3.hp.com",
                sport=51344, up=680, down=1420)


# ===========================================================================
#  Scene 7 -- the Linux desks: apt, dnf, SSH, docker, NTP
# ===========================================================================
def scene_linux():
    # apt over HTTP. The InRelease file is signed, so plaintext is fine by
    # design -- and it means you can see exactly which packages were pulled.
    f = TcpFlow(T0 + 11.6, dev_ubu, x_ubuntu, 51401, 80, bw=5.6e7)
    f.open()
    f.send("c", http_req("GET", "/ubuntu/dists/noble/InRelease",
                         "archive.ubuntu.com", ua=UA["apt"],
                         extra=["Accept: text/*"]), think=0.0011)
    f.send("s", http_resp("200 OK", ctype="text/plain", body=filler(287431),
                          server="Apache/2.4.59 (Ubuntu)",
                          extra=["Last-Modified: Mon, 09 Nov 2026 22:11:04 GMT"]),
           think=0.027, ack_every=6)
    f.send("c", http_req("GET", "/ubuntu/dists/noble-security/InRelease",
                         "archive.ubuntu.com", ua=UA["apt"],
                         extra=["If-Modified-Since: Mon, 09 Nov 2026 06:02:11 GMT"]),
           think=0.05)
    f.send("s", http_resp("304 Not Modified", ctype="text/plain",
                          server="Apache/2.4.59 (Ubuntu)"), think=0.022)
    f.send("c", http_req("GET", "/ubuntu/pool/main/o/openssl/"
                         "openssl_3.0.13-0ubuntu3.6_amd64.deb",
                         "archive.ubuntu.com", ua=UA["apt"]), think=0.04)
    f.send("s", http_resp("200 OK", ctype="application/x-debian-package",
                          body=filler(428032), server="Apache/2.4.59 (Ubuntu)"),
           think=0.03, ack_every=8)
    f.close("c", think=0.06)

    # dnf, which does the same job over TLS.
    tls_session(T0 + 53.0, dev_fed, x_fedora, "dl.fedoraproject.org",
                sport=51422, up=1340, down=263000, bw=5.2e7)

    # SSH to GitHub. The version banners are the last readable thing.
    f = TcpFlow(T0 + 41.0, dev_ubu, x_github, 51433, 22)
    f.open()
    f.send("c", b"SSH-2.0-OpenSSH_9.9p1 Ubuntu-3ubuntu3\r\n", think=0.0009)
    f.send("s", b"SSH-2.0-babeld-2a1b2c3d\r\n", think=0.028)
    f.send("c", ssh_kexinit(OPENSSH_KEX, OPENSSH_HOSTKEYS, OPENSSH_CIPHERS,
                            OPENSSH_MACS), think=0.002)
    f.send("s", ssh_kexinit("curve25519-sha256,ecdh-sha2-nistp256,"
                            "kex-strict-s-v00@openssh.com",
                            "ssh-ed25519,ecdsa-sha2-nistp256,rsa-sha2-512,"
                            "rsa-sha2-256",
                            "chacha20-poly1305@openssh.com,aes256-ctr",
                            "hmac-sha2-512-etm@openssh.com,hmac-sha2-256",
                            comp="none"), think=0.031)
    f.send("c", ssh_ecdh_init(), think=0.004)
    f.send("s", ssh_ecdh_reply() + ssh_newkeys(), think=0.026)
    f.send("c", ssh_newkeys(), think=0.002)
    for i in range(6):                           # the git pack, encrypted
        f.send("c", _rand(96), think=0.05)
        f.send("s", _rand(14600), think=0.03, ack_every=4)
    f.close("c", think=0.08)

    # A container image pull: TLS, big, bursty.
    tls_session(T0 + 86.5, dev_ubu, x_docker, "registry-1.docker.io",
                sport=51444, up=2400, down=1140000, bw=4.1e7)
    tls_session(T0 + 132.0, dev_fed, x_gh_cdn, "codeload.github.com",
                sport=51455, up=1180, down=214000)

    # NTP. The Windows hosts and the switch use the DC; the Linux boxes use
    # the distro pool, which is a finding in itself if policy says otherwise.
    for n, h in enumerate((wks_fin, wks_sales, legacy, mbp_eng, phone1, sw2)):
        t = T0 + 17.0 + n * 41.0
        if t > T0 + DURATION - 1:
            break
        sport = RNG.randrange(49152, 65535) if h.os != "netgear" else 123
        u4(t, h, dc01, sport, 123,
           NTP(mode=3, version=4, stratum=0, poll=10, precision=-23,
               orig=t, sent=t))
        u4(t + 0.0014, dc01, h, 123, sport,
           NTP(mode=4, version=4, stratum=3, poll=10, precision=-23,
               id="10.21.20.10", ref=t - 212.0, orig=t, recv=t + 0.0012,
               sent=t + 0.0013))
    for n, (h, srv) in enumerate(((dev_ubu, x_ubu_ntp), (dev_fed, x_ubu_ntp))):
        t = T0 + 171.4 + n * 29.0
        sport = RNG.randrange(49152, 65535)
        u4(t, h, srv, sport, 123,
           NTP(mode=3, version=4, stratum=0, poll=10, precision=-24,
               orig=t, sent=t))
        u4(t + 0.0241, srv, h, 123, sport,
           NTP(mode=4, version=4, stratum=2, poll=10, precision=-24,
               id="185.125.190.56", ref=t - 601.0, orig=t, recv=t + 0.0119,
               sent=t + 0.012))


# ===========================================================================
#  Scene 8 -- real-time media: Teams, a desk phone, and a Zoom call
# ===========================================================================
# DSCP values are the ones Microsoft publishes for Teams QoS: EF (46) for
# audio, AF41 (34) for video, AF21 (18) for sharing. They are why these flows
# look different from everything else in the file at the IP layer.
DSCP_EF, DSCP_AF41, DSCP_AF21 = 46, 34, 18


def teams_media(t, client, sport, *, secs, pt, size, pps, dscp, chan,
                ssrc, relay=x_teams_media, two_way=True):
    """STUN binding, then TURN ChannelData carrying SRTP in both directions."""
    txid = _rand(12)
    u4(t, client, relay, sport, 3478, stun_binding_request(txid), dscp=dscp)
    u4(t + 0.0184, relay, client, 3478, sport,
       stun_binding_response(txid, "198.51.100.77", 34211), dscp=dscp)
    gap = 1.0 / pps
    seq = RNG.randrange(1000, 40000)
    ts = RNG.randrange(10 ** 6, 10 ** 8)
    n = int(secs * pps)
    for i in range(n):
        tt = t + 0.05 + i * gap
        u4(tt, client, relay, sport, 3478,
           turn_channel(chan, srtp_like(seq + i, ts + i * 960, ssrc, pt, size)),
           dscp=dscp)
        if two_way:
            u4(tt + 0.0092 + jit(0.0022), relay, client, 3478, sport,
               turn_channel(chan, srtp_like(seq + i, ts + i * 960,
                                            ssrc ^ 0x5A5A5A, pt, size)),
               dscp=dscp)
    return t + 0.05 + n * gap


def scene_media():
    # A 35-second Teams audio call from the finance desk: 50 packets a second
    # each way, DSCP EF, source port inside the audio range Microsoft asks you
    # to mark.
    teams_media(T0 + 20.5, wks_fin, 50004, secs=35, pt=111, size=62, pps=50,
                dscp=DSCP_EF, chan=0x4001, ssrc=0x2B7A91C4)
    # A meeting from the sales desk: audio plus 15 seconds of video, which is
    # where the bytes are.
    teams_media(T0 + 104.0, wks_sales, 50011, secs=15, pt=111, size=62, pps=50,
                dscp=DSCP_EF, chan=0x4002, ssrc=0x71C3A0E2)
    teams_media(T0 + 104.2, wks_sales, 50026, secs=15, pt=100, size=1080,
                pps=45, dscp=DSCP_AF41, chan=0x4003, ssrc=0x71C3A0E3)
    # Someone sharing a window: AF21, bursty, lower rate.
    teams_media(T0 + 112.0, wks_sales, 50044, secs=8, pt=122, size=940,
                pps=18, dscp=DSCP_AF21, chan=0x4004, ssrc=0x71C3A0E4)
    # The desk phone, 20 seconds, same relay.
    teams_media(T0 + 161.0, phone1, 50008, secs=20, pt=111, size=62, pps=50,
                dscp=DSCP_EF, chan=0x4005, ssrc=0x3F8102DD)
    # And a Zoom call from a Mac, which uses its own UDP port and marks
    # nothing -- a useful contrast when you filter on DSCP.
    sport = 54902
    for i in range(20 * 50):
        tt = T0 + 36.0 + i * 0.02
        u4(tt, mbp_mkt, x_zoom, sport, 8801,
           Raw(_u16(0x0501) + _u16(i & 0xFFFF) + _rand(118)))
        u4(tt + 0.0121, x_zoom, mbp_mkt, 8801, sport,
           Raw(_u16(0x0501) + _u16(i & 0xFFFF) + _rand(118)))


# ===========================================================================
#  Scene 9 -- cameras: RTSP with an SDP body, so the RTP really decodes
# ===========================================================================
def scene_cameras():
    def rtsp_pull(t, cam, cport, ssrc, secs, fps=15):
        f = TcpFlow(t, nvr01, cam, 45000 + cport % 1000, 554)
        f.open()
        base = f"rtsp://{cam.ip}/axis-media/media.amp"
        f.send("c", (f"OPTIONS {base} RTSP/1.0\r\nCSeq: 1\r\n"
                     "User-Agent: nvr01-recorder/4.2\r\n\r\n").encode(),
               think=0.0009)
        f.send("s", (b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nPublic: OPTIONS, DESCRIBE,"
                     b" SETUP, TEARDOWN, PLAY, PAUSE\r\n\r\n"), think=0.0042)
        sdp = (f"v=0\r\no=- 1762810440 1 IN IP4 {cam.ip}\r\ns=Media Presentation"
               f"\r\nc=IN IP4 0.0.0.0\r\nt=0 0\r\n"
               f"m=video 0 RTP/AVP 96\r\na=rtpmap:96 H264/90000\r\n"
               "a=fmtp:96 packetization-mode=1;profile-level-id=4d0029\r\n"
               "a=control:trackID=1\r\n").encode()
        f.send("c", (f"DESCRIBE {base} RTSP/1.0\r\nCSeq: 2\r\n"
                     "Accept: application/sdp\r\n"
                     "User-Agent: nvr01-recorder/4.2\r\n\r\n").encode(),
               think=0.003)
        f.send("s", (b"RTSP/1.0 200 OK\r\nCSeq: 2\r\nContent-Type: "
                     b"application/sdp\r\nContent-Length: " +
                     str(len(sdp)).encode() + b"\r\n\r\n" + sdp), think=0.0051)
        f.send("c", (f"SETUP {base}/trackID=1 RTSP/1.0\r\nCSeq: 3\r\n"
                     f"Transport: RTP/AVP;unicast;client_port={cport}-{cport + 1}"
                     "\r\nUser-Agent: nvr01-recorder/4.2\r\n\r\n").encode(),
               think=0.004)
        f.send("s", (f"RTSP/1.0 200 OK\r\nCSeq: 3\r\nSession: 1A9C32E7;"
                     f"timeout=60\r\nTransport: RTP/AVP;unicast;"
                     f"client_port={cport}-{cport + 1};"
                     f"server_port=50000-50001;ssrc={ssrc:08X}\r\n\r\n").encode(),
               think=0.0061)
        f.send("c", (f"PLAY {base} RTSP/1.0\r\nCSeq: 4\r\nSession: 1A9C32E7\r\n"
                     "Range: npt=0.000-\r\n\r\n").encode(), think=0.003)
        f.send("s", (b"RTSP/1.0 200 OK\r\nCSeq: 4\r\nSession: 1A9C32E7\r\n"
                     b"RTP-Info: url=" + base.encode() +
                     b"/trackID=1;seq=19231;rtptime=3221171185\r\n\r\n"),
               think=0.0049)
        # The stream itself: RTP on the port SETUP negotiated, plus RTCP.
        t1 = f.t + 0.02
        seq = 19231
        rtpts = 3221171185
        for i in range(int(secs * fps)):
            tt = t1 + i / fps
            u4(tt, cam, nvr01, 50000, cport,
               Raw(bytes([0x80, 96 if i % 12 else 0xE0]) + _u16((seq + i) & 0xFFFF) +
                   ((rtpts + i * 6000) & 0xFFFFFFFF).to_bytes(4, "big") +
                   ssrc.to_bytes(4, "big") + _rand(760)))
            if i % 30 == 29:
                u4(tt + 0.004, nvr01, cam, cport + 1, 50001,
                   Raw(b"\x81\xc9\x00\x07" + ssrc.to_bytes(4, "big") +
                       _rand(24)))
        return f

    rtsp_pull(T0 + 12.4, cam1, 40100, 0x4B19A2C7, secs=240, fps=6)
    rtsp_pull(T0 + 95.2, cam2, 40200, 0x4B19A2D1, secs=60, fps=6)


# ===========================================================================
#  Scene 10 -- building controls, printers, switch management, flow export
# ===========================================================================
def scene_facilities():
    # Modbus/TCP: the gateway polls the rooftop unit every 10 s. Same VLAN,
    # different stack, so these frames are bridged across Po1.
    f = TcpFlow(T0 + 5.1, bms, bmsc, 49300, 502, win_raw=256)
    f.open()
    for i in range(29):
        tid = 0x1000 + i
        f.send("c", bytes(modbus_read(tid, 1, 0x0064, 8)), think=10.0 if i else 0.0)
        f.send("s", bytes(modbus_values(tid, 1, [
            680 + i % 7, 721, 14, 1, 0, 2250 + i, 48, 1])), think=0.0038)
    f.close("c", think=0.5)

    # SNMP polling from the SIEM: interface counters off the switch, supply
    # levels off the printer. SNMPv2c, community in the clear.
    oids_if = ["1.3.6.1.2.1.1.3.0", "1.3.6.1.2.1.31.1.1.1.6.1",
               "1.3.6.1.2.1.31.1.1.1.10.1", "1.3.6.1.2.1.2.2.1.8.1"]
    oids_prn = ["1.3.6.1.2.1.43.11.1.1.9.1.1", "1.3.6.1.2.1.43.10.2.1.4.1.1",
                "1.3.6.1.2.1.25.3.5.1.1.1"]
    for i in range(5):
        t = T0 + 10.0 + i * 60.0
        if t > T0 + DURATION - 1:
            break
        for tgt, oids, comm in ((sw2, oids_if, "n0rthst4r-ro"),
                                (mfp1, oids_prn, "n0rthst4r-ro")):
            rid = 0x5A00 + i * 16 + (0 if tgt is sw2 else 1)
            sport = 42000 + i * 2 + (0 if tgt is sw2 else 1)
            u4(t, siem01, tgt, sport, 161, snmp_get(comm, oids, rid))
            vals = [(o, ASN1_INTEGER(RNG.randrange(1000, 90000000)))
                    for o in oids]
            u4(t + 0.0026, tgt, siem01, 161, sport,
               snmp_resp(comm, vals, rid))

    # Syslog from the access switch and the APs, UDP 514, plaintext.
    msgs = [
        (sw2, 189, "%LINK-3-UPDOWN: Interface GigabitEthernet1/0/24, "
                   "changed state to down"),
        (sw2, 189, "%LINK-3-UPDOWN: Interface GigabitEthernet1/0/24, "
                   "changed state to up"),
        (sw2, 188, "%SW_MATM-4-MACFLAP_NOTIF: Host 0015.5daa.1904 in vlan 10 "
                   "is flapping between port Gi1/0/19 and port Gi1/0/31"),
        (ap1, 190, "wireless: client ac:de:48:11:5e:92 associated to ssid "
                   "NSL-Corp band 5GHz rssi -54"),
        (ap2, 190, "wireless: client da:a1:19:7c:04:3b roamed from ap-f2-01 "
                   "to ap-f2-02 ssid NSL-Corp"),
        (sw2, 190, "%DOT1X-5-SUCCESS: Authentication successful for client "
                   "(b07b.253c.9104) on Interface Gi1/0/12 AuditSessionID "
                   "0A1563020000001A2B3C4D5E"),
        (ap1, 187, "wireless: client 9c:b6:d0:f1:04:5c failed to associate "
                   "ssid NSL-Guest reason 23 (802.1X auth timeout)"),
        (sw2, 190, "%PLATFORM_THERMAL-6-FRU_FAN_OK: Fan 2 is operating "
                   "normally"),
    ]
    for i in range(24):
        src, pri, text = msgs[i % len(msgs)]
        t = T0 + 14.0 + i * 11.7
        if t > T0 + DURATION - 1:
            break
        secs = int(t - T0) + 14 * 60
        when = "Nov 10 09:%02d:%02d" % (14 + secs // 60, secs % 60)
        u4(t, src, siem01, 514, 514, syslog_line(pri, src.name, text, when=when))

    # NetFlow v9 off the access stack: one template, then data flowsets.
    tmpl_fields = [(8, 4), (12, 4), (7, 2), (11, 2), (4, 1), (1, 4), (2, 4),
                   (21, 4), (22, 4), (10, 4), (61, 1)]
    tmpl = NF.NetflowFlowsetV9(templates=[NF.NetflowTemplateV9(
        templateID=256, fieldCount=len(tmpl_fields),
        template_fields=[NF.NetflowTemplateFieldV9(fieldType=ft, fieldLength=fl)
                         for ft, fl in tmpl_fields])])
    seq = 771

    def nf_hdr(count, t, seqnum):
        return NF.NetflowHeader() / NF.NetflowHeaderV9(
            count=count, sysUptime=int((t - T0) * 1000) + 4120300,
            unixSecs=int(t), packageSequence=seqnum, SourceID=256)

    u4(T0 + 8.0, sw2, siem01, 51022, 2055, nf_hdr(1, T0 + 8.0, seq) / tmpl)
    seq += 1
    flows = [
        (wks_fin.ip, x_exo.ip, 50302, 443, 6, 1, 1, 212, 184320, 41000),
        (wks_sales.ip, x_wu_cdn.ip, 50712, 80, 6, 1, 1, 903, 794624, 68000),
        (wks_fin.ip, x_teams_media.ip, 50004, 3478, 17, 1, 1, 1750, 199500, 35000),
        (mbp_eng.ip, x_icloud.ip, 50922, 443, 6, 1, 1, 141, 52400, 22000),
        (dev_ubu.ip, x_ubuntu.ip, 51401, 80, 6, 1, 1, 1104, 1472000, 51000),
        (nvr01.ip, cam1.ip, 40100, 554, 6, 1, 1, 64, 9800, 240000),
    ]
    for i in range(6):
        t = T0 + 38.0 + i * 45.0
        if t > T0 + DURATION - 1:
            break
        recs = []
        for (s_ip, d_ip, sp, dp, proto, inif, outif, pkts, octets, dur) in flows:
            val = (bytes(int(o) for o in s_ip.split(".")) +
                   bytes(int(o) for o in d_ip.split(".")) +
                   _u16(sp) + _u16(dp) + bytes([proto]) +
                   inif.to_bytes(4, "big") + outif.to_bytes(4, "big") +
                   (int((t - T0) * 1000) + 4120300).to_bytes(4, "big") +
                   (int((t - T0) * 1000) + 4120300 - dur).to_bytes(4, "big") +
                   pkts.to_bytes(4, "big") + bytes([0x1B]))
            recs.append(NF.NetflowRecordV9(fieldValue=val))
        u4(t, sw2, siem01, 51022, 2055,
           nf_hdr(len(recs), t, seq) /
           NF.NetflowDataflowsetV9(templateID=256, records=recs))
        seq += 1
        if i % 3 == 2:          # exporters resend the template periodically
            u4(t + 0.001, sw2, siem01, 51022, 2055,
               nf_hdr(1, t, seq) / tmpl)
            seq += 1

    # An admin on SSH to the switch: banner in the clear, everything else not.
    f = TcpFlow(T0 + 225.0, dev_ubu, sw2, 51501, 22)
    f.open()
    f.send("c", b"SSH-2.0-OpenSSH_9.9p1 Ubuntu-3ubuntu3\r\n", think=0.0008)
    f.send("s", b"SSH-2.0-Cisco-2.0\r\n", think=0.0036)
    f.send("c", ssh_kexinit(OPENSSH_KEX, OPENSSH_HOSTKEYS, OPENSSH_CIPHERS,
                            OPENSSH_MACS), think=0.002)
    # The switch offers a much shorter, much older list than the client.
    f.send("s", ssh_kexinit("ecdh-sha2-nistp256,diffie-hellman-group14-sha1",
                            "rsa-sha2-256,ssh-rsa",
                            "aes128-ctr,aes192-ctr,aes256-ctr",
                            "hmac-sha2-256,hmac-sha1", comp="none"),
           think=0.0041)
    f.send("c", ssh_ecdh_init(), think=0.002)
    f.send("s", ssh_ecdh_reply("rsa-sha2-256") + ssh_newkeys(), think=0.0056)
    f.send("c", ssh_newkeys(), think=0.0015)
    for i in range(7):
        f.send("c", _rand(64), think=0.4 + jit(0.6))
        f.send("s", _rand(RNG.randrange(180, 2400)), think=0.006)
    # Left open at the end of the capture, as idle sessions usually are.

    # The monitoring host pinging the printer and the camera.
    for n, tgt in enumerate((mfp1, cam1, phone1)):
        for i in range(4):
            t = T0 + 21.0 + n * 7.0 + i * 60.0
            if t > T0 + DURATION - 1:
                break
            ident = 0x4A00 + n * 16 + i
            u4_icmp = l2(CORE_MAC, tgt.mac, tgt.vlan) / \
                IP(src=siem01.ip, dst=tgt.ip, ttl=siem01.ttl - 1) / \
                ICMP(type=8, id=ident, seq=i + 1) / Raw(filler(56))
            emit(t, u4_icmp)
            reply = l2(tgt.mac, CORE_MAC, tgt.vlan) / \
                IP(src=tgt.ip, dst=siem01.ip, ttl=tgt.ttl) / \
                ICMP(type=0, id=ident, seq=i + 1) / Raw(filler(56))
            emit(t + 0.0019 + jit(0.002), reply)


# ===========================================================================
#  Scene 11 -- the guest SSID: captive portal, DoH, and QUIC video
# ===========================================================================
def scene_guest():
    # The portal intercept: a plain HTTP request gets a 302 to the portal.
    f = TcpFlow(T0 + 49.0, g_laptop, x_ncsi, 51601, 80)
    f.open()
    f.send("c", http_req("GET", "/connecttest.txt", "www.msftconnecttest.com",
                         ua=UA["ncsi"]), think=0.001)
    f.send("s", http_resp("302 Found", ctype="text/html",
                          body=b"<html><body>Redirecting</body></html>",
                          server="nginx",
                          extra=["Location: https://portal.northstar.example/"
                                 "guest?mac=9cb6d0f1045c&url=http%3A%2F%2F"
                                 "www.msftconnecttest.com%2Fconnecttest.txt"]),
           think=0.009)
    f.close("s", think=0.004)
    # Then the portal itself, over TLS to the firewall's captive-portal page.
    tls_session(T0 + 49.6, g_laptop, fw, "portal.northstar.example",
                sport=51611, up=1840, down=36400, profile="edge")
    # Guests resolve names over DoH, so the queries are invisible to dc01.
    tls_session(T0 + 51.2, g_laptop, x_cf_doh, "cloudflare-dns.com",
                sport=51622, up=620, down=1480, keepalives=7,
                keepalive_gap=18.0, close=False)
    tls_session(T0 + 77.4, g_iphone, x_cf_doh, "cloudflare-dns.com",
                sport=51633, up=540, down=1240, keepalives=5,
                keepalive_gap=24.0, close=False)
    # An iPhone on guest Wi-Fi doing its captive check, then streaming.
    f = TcpFlow(T0 + 76.1, g_iphone, x_apple_cap, 51644, 80)
    f.open()
    f.send("c", http_req("GET", "/hotspot-detect.html", "captive.apple.com",
                         ua=UA["capnet"]), think=0.0011)
    f.send("s", http_resp("200 OK", ctype="text/html",
                          body=b"<HTML><HEAD><TITLE>Success</TITLE></HEAD>"
                               b"<BODY>Success</BODY></HTML>",
                          server="AppleHttpServer/5bfb6b4fd1"), think=0.027)
    f.close("c", think=0.004)
    quic_flow(T0 + 84.0, g_iphone, x_youtube, 55101, up_pkts=70,
              down_pkts=520, down_size=1252)
    # And the Android handset on the corporate SSID doing its own check.
    f = TcpFlow(T0 + 20.0, andro, x_gstatic, 51655, 80)
    f.open()
    f.send("c", http_req("GET", "/generate_204",
                         "connectivitycheck.gstatic.com", ua=UA["android"]),
           think=0.0012)
    f.send("s", http_resp("204 No Content", ctype="text/html",
                          server="gws"), think=0.024)
    f.close("c", think=0.005)
    quic_flow(T0 + 243.0, andro, x_youtube, 55202, up_pkts=34, down_pkts=190,
              down_size=1252)


# ===========================================================================
#  Scene 12 -- the small failures every real capture contains
# ===========================================================================
def scene_rough_edges():
    # RDP to a file server that does not offer it: SYN, then RST/ACK.
    f = TcpFlow(T0 + 138.0, dev_ubu, fs01, 51701, 3389)
    f.seg("c", "S", syn=True)
    f.t += 0.0011
    f.ack["s"] = f.seq["c"]
    f.seg("s", "RA")

    # A SYN to a port the firewall silently drops: three retries, 1s, 2s, 4s.
    f = TcpFlow(T0 + 174.0, dev_fed, x_slack, 51711, 8443)
    seq0 = f.seq["c"]
    for delay in (0.0, 1.0, 3.0):
        f.t = T0 + 174.0 + delay
        f.seg("c", "S", syn=True, seq=seq0, advance=False)

    # A UDP probe to a closed port on the printer, and the ICMP that comes back.
    probe = l2(mbp_mkt.mac, CORE_MAC, 10) / \
        IP(src=mbp_mkt.ip, dst=mfp1.ip, ttl=mbp_mkt.ttl) / \
        UDP(sport=51721, dport=9100) / Raw(b"\x1b%-12345X@PJL INFO STATUS\r\n")
    emit(T0 + 198.0, probe)
    emit(T0 + 198.0021,
         l2(CORE_MAC, mbp_mkt.mac, 10) /
         IP(src=mfp1.ip, dst=mbp_mkt.ip, ttl=mfp1.ttl - 1) /
         ICMP(type=3, code=3) / probe[IP])

    # An expired session: the server gives up on an idle TLS connection.
    f = TcpFlow(T0 + 210.0, mbp_mkt, x_slack, 51731, 443)
    f.open()
    f.send("c", tls_client_hello("slack.com", profile="apple"), think=0.001)
    f.send("s", tls_server_hello() + tls_ccs() + tls_app(1240), think=0.026)
    f.send("c", tls_ccs() + tls_app(52) + tls_app(640), think=0.002)
    f.send("s", tls_app(2100), think=0.03)
    f.t += 41.0
    f.send("s", tls_app(24))            # close_notify from the server side
    f.close("s", think=0.001)


# ===========================================================================
#  Assemble
# ===========================================================================
SCENES = (
    scene_control_plane,
    scene_arp_dhcp,
    scene_dns,
    scene_kerberos,
    scene_ldaps_smb,
    scene_m365,
    scene_windows_update,
    scene_apple,
    scene_linux,
    scene_media,
    scene_cameras,
    scene_facilities,
    scene_guest,
    scene_rough_edges,
)


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--out", default="office.pcap", help="output pcap path")
    ap.add_argument("--seed", type=int, default=20261110,
                    help="PRNG seed; the same seed always rebuilds the same file")
    args = ap.parse_args()

    global RNG
    RNG = random.Random(args.seed)

    for scene in SCENES:
        scene()

    PKTS.sort(key=lambda tp: tp[0])
    pkts = [p for _, p in PKTS]
    wrpcap(args.out, pkts)

    span = PKTS[-1][0] - PKTS[0][0]
    print(f"{args.out}: {len(pkts)} frames, {span:.1f} s "
          f"({len(PKTS) / span:.0f} pkt/s average)")


if __name__ == "__main__":
    main()
