repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
_htbbox.pyPython839 lines29.5 KiBraw download
"""htbbox -- one directory and one box.json per HTB machine.

    htbbox new Sauna 10.10.10.175 windows easy      positional, any order
    htbbox new Sauna 10.10.10.175 win easy sauna.htb dc01.sauna.htb
    htbbox new                                      prompt for everything
    htbbox use sauna                                switch box (+ $TARGET, /etc/hosts)
    htbbox target                                   what $TARGET points at
    htbbox clear                                    forget the target; box files stay
    htbcast                                         record a session into $BOXDIR/casts (casts.nix)
    htbbox ls | info | path | json                  look around
    htbbox set ip 10.10.10.176                      change a field
    htbbox host dc01.sauna.htb                      add hostnames (-> /etc/hosts)
    htbbox cred fsmith 'Thestrokes23' kerberoast    record a credential
    htbbox flag user 3f4e...                        record a flag (status -> user/root)
    htbbox note "WinRM open, fsmith in Remote Mgmt" timestamped note
    htbbox ports                                    import open ports from recon/*.xml

Every subcommand that acts on a box takes `-b <box>`; without it, the current
box ($BOX, set by `new`/`use`) is used.

box.json is the single source of truth for a box. Other tools read it with jq
(`htbbox json ip`, `jq .creds "$BOXDIR/box.json"`). writeup.md is rendered once
from the vault's Templater template (or a built-in skeleton) and never
rewritten afterwards -- it is prose you own.

Stdlib only. Nix wraps this with gum on PATH (boxes.nix); without gum the
prompts fall back to input().
"""

import datetime as dt
import ipaddress
import json
import os
import re
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET

SCHEMA = 2
STATE = os.path.join(
    os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "htb"
)
ROOT = os.environ.get("HTB_ROOT") or os.path.expanduser("~/htb")
# The notes vault and its write-up template. Both come from the environment
# (set them in your shell); the defaults are placeholders.
VAULT = os.environ.get("NETRUNNER_VAULT") or os.path.expanduser("~/vault")
TEMPLATE = os.environ.get("HTB_POST_TEMPLATE") or os.path.join(VAULT, "Templates/htb-post.md")
SUBDIRS = ["recon", "enum", "creds", "loot", "exploit", "serve", "casts"]

DIFFICULTIES = ["easy", "medium", "hard", "insane"]
# alias -> canonical display form (the website's frontmatter reads the latter)
OSES = {
    "windows": "Windows", "win": "Windows",
    "linux": "Linux", "lin": "Linux",
    "freebsd": "FreeBSD", "bsd": "FreeBSD",
    "openbsd": "OpenBSD",
    "android": "Android",
    "other": "Other",
}
OS_CHOICES = ["windows", "linux", "freebsd", "openbsd", "android", "other"]
STATUSES = ["active", "user", "root", "retired", "paused"]
SETTABLE = ["name", "ip", "os", "difficulty", "status", "domain", "notes_url"]

USAGE = """\
usage: htbbox <command> [args] [-b box]

  new [name] [ip] [os] [difficulty] [host...]   scaffold a box (any order; prompts for the rest)
      -n name  -i ip  -o os  -d difficulty  -H host   (flags, if you prefer)
  use <box>                     make <box> current: $BOX, $TARGET, /etc/hosts
  target                        what $TARGET points at right now
  clear                         forget the current target (keeps every box's files)
  ls                            all boxes, newest first (* = current)
  info [box]                    the box card: target, flags, creds, ports, notes
  path [box]                    the directory   (or just: cd $BOXDIR)
  json [box] [key]              raw box.json, or one key (dotted: flags.user)
  set <key> <value>             key: name ip os difficulty status domain
  host <name...>                add hostnames; re-points /etc/hosts if current
  cred [user secret [note...]]  add a credential, or list them
  flag <user|root> <value>      record a flag; status follows
  note [text...]                add a timestamped note, or list them
  ports [file.xml]              import open ports from the newest recon/*.xml

  os:          windows linux freebsd openbsd android other   (win, lin ok)
  difficulty:  easy medium hard insane
"""


# ── output ──────────────────────────────────────────────────────────────────

def _color_on(stream):
    return stream.isatty() and "NO_COLOR" not in os.environ


def paint(text, code, stream=sys.stdout):
    return f"\033[{code}m{text}\033[0m" if _color_on(stream) else text


def die(msg, code=2):
    print(f"htbbox: {msg}", file=sys.stderr)
    sys.exit(code)


def info(msg):
    print(msg, file=sys.stderr)


# ── validation ──────────────────────────────────────────────────────────────

def is_ipv4(s):
    try:
        return isinstance(ipaddress.ip_address(s), ipaddress.IPv4Address)
    except ValueError:
        return False


HOST_RE = re.compile(r"^(?=.{1,253}$)[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$")


def is_hostname(s):
    # fullmatch, not match: `$` also matches before a trailing newline, and a
    # newline in a hostname would become a second /etc/hosts line.
    return bool(HOST_RE.fullmatch(s)) and not is_ipv4(s)


def norm_os(s):
    v = OSES.get(s.lower())
    if not v:
        die(f"os must be one of {', '.join(OS_CHOICES)} (got: {s})")
    return v


def norm_difficulty(s):
    if s.lower() not in DIFFICULTIES:
        die(f"difficulty must be easy, medium, hard or insane (got: {s})")
    return s.lower()


def norm_ip(s):
    if s and not is_ipv4(s):
        die(f"not an IPv4 address: {s}")
    return s


def slugify(s):
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")


def now():
    return dt.datetime.now().replace(microsecond=0).isoformat()


# ── state ───────────────────────────────────────────────────────────────────

def current():
    try:
        with open(os.path.join(STATE, "box")) as fh:
            return fh.read().strip() or None
    except OSError:
        return None


def set_current(box):
    os.makedirs(STATE, exist_ok=True)
    with open(os.path.join(STATE, "box"), "w") as fh:
        fh.write(box + "\n")


def boxdir(box):
    return os.path.join(ROOT, box)


def resolve(box):
    """Box name -> directory name, or die with the command that fixes it."""
    box = box or current()
    if not box:
        die("no box given and none current -- htbbox new, or htbbox use <box>")
    if box.startswith("htb-"):
        box = box[4:]
    if not re.match(r"^[a-z0-9][a-z0-9-]*$", box):
        box = slugify(box)
    if not os.path.isdir(boxdir(box)):
        die(f"no such box: {box} (htbbox ls)")
    return box


def load(box):
    path = os.path.join(boxdir(box), "box.json")
    try:
        with open(path) as fh:
            data = json.load(fh)
    except FileNotFoundError:
        data = {"name": box, "slug": f"htb-{box}"}
    except json.JSONDecodeError as e:
        die(f"{path} is not valid JSON ({e}) -- fix it by hand", 1)
    # Upgrade older manifests in place: missing keys get defaults.
    defaults = {
        "ip": "", "os": "Other", "difficulty": "", "hostnames": [], "domain": "",
        "platform": "HTB-Labs", "status": "active", "created": dt.date.today().isoformat(),
        "updated": now(), "flags": {"user": None, "root": None},
        "creds": [], "ports": [], "notes": [], "tags": [],
    }
    for k, v in defaults.items():
        data.setdefault(k, v)
    data["schema"] = SCHEMA
    return data


def save(box, data):
    data["updated"] = now()
    path = os.path.join(boxdir(box), "box.json")
    tmp = path + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(data, fh, indent=2)
        fh.write("\n")
    os.replace(tmp, path)


def _write_state(name, value):
    os.makedirs(STATE, exist_ok=True)
    path = os.path.join(STATE, name)
    if value:
        with open(path, "w") as fh:
            fh.write(value + "\n")
    else:
        try:
            os.remove(path)
        except FileNotFoundError:
            pass


def hosts_helper(*args):
    """Run the root /etc/hosts helper (htb.nix) through its NOPASSWD sudo rule.
    It re-validates every argument itself; this only reports failure."""
    exe = "/run/current-system/sw/bin/htb-hosts"
    if not os.access(exe, os.X_OK):
        exe = shutil.which("htb-hosts")
    if not exe:
        info("htbbox: htb-hosts not found -- /etc/hosts not updated")
        return False
    r = subprocess.run(["/run/wrappers/bin/sudo", "-n", exe, *args],
                       stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
    if r.returncode != 0:
        info(r.stderr.rstrip() or "htbbox: htb-hosts failed")
        info("htbbox: /etc/hosts was NOT updated -- check it by hand")
        return False
    return True


def point_target(data):
    """Point $TARGET (and /etc/hosts, when there are names) at this box.
    $STATE/target and $STATE/host are what the zsh loader (htb.nix) exports
    as $TARGET/$RHOST/$IP in every terminal at its next prompt."""
    if not data.get("ip"):
        return
    hosts = data.get("hostnames", [])
    _write_state("target", data["ip"])
    _write_state("host", " ".join(hosts))
    if hosts:
        hosts_helper("set", data["ip"], *hosts)
    else:
        hosts_helper("clear")  # drop the previous box's names


# ── prompts ─────────────────────────────────────────────────────────────────

def interactive():
    return sys.stdin.isatty() and sys.stderr.isatty()


def ask(prompt, placeholder=""):
    if shutil.which("gum"):
        r = subprocess.run(["gum", "input", "--prompt", f"{prompt} > ", "--placeholder", placeholder],
                           stdout=subprocess.PIPE, text=True)
        if r.returncode != 0:
            sys.exit(1)
        return r.stdout.strip()
    return input(f"{prompt} [{placeholder}]: ").strip()


def choose(header, options):
    if shutil.which("gum"):
        r = subprocess.run(["gum", "choose", "--header", header, *options],
                           stdout=subprocess.PIPE, text=True)
        if r.returncode != 0:
            sys.exit(1)
        return r.stdout.strip()
    while True:
        v = input(f"{header} ({'/'.join(options)}): ").strip().lower()
        if v in options or v in OSES:
            return v


# ── argument helpers ────────────────────────────────────────────────────────

def pop_box(args):
    """Remove `-b X` / `--box X` from anywhere in args; return (box, rest)."""
    box, rest, it = None, [], iter(args)
    for a in it:
        if a in ("-b", "--box"):
            box = next(it, None) or die("-b needs a box name")
        elif a.startswith("--box="):
            box = a.split("=", 1)[1]
        else:
            rest.append(a)
    return box, rest


# ── commands ────────────────────────────────────────────────────────────────

def cmd_new(args):
    name = ip = os_ = diff = None
    hosts, tags = [], []
    it = iter(args)
    for a in it:
        flagval = lambda: next(it, None) or die(f"{a} needs a value")  # noqa: E731
        if a in ("-n", "--name"):
            name = flagval()
        elif a in ("-i", "--ip"):
            ip = flagval()
        elif a in ("-o", "--os"):
            os_ = flagval()
        elif a in ("-d", "--difficulty"):
            diff = flagval()
        elif a in ("-H", "--host"):
            hosts.append(flagval())
        elif a in ("-t", "--tag"):
            tags.append(flagval())
        elif a in ("-h", "--help"):
            print(USAGE, end="")
            return
        elif a.startswith("-"):
            die(f"unknown option: {a}")
        # Positional: classify by shape, so the order does not matter.
        elif is_ipv4(a) and not ip:
            ip = a
        elif a.lower() in DIFFICULTIES and not diff:
            diff = a
        elif a.lower() in OSES and not os_:
            os_ = a
        elif is_hostname(a):
            hosts.append(a)
        elif not name:
            name = a
        else:
            die(f"don't know what '{a}' is (name already '{name}'). Use -n/-i/-o/-d to be explicit.")

    # Ask for what is missing -- only on a terminal, so scripts fail fast.
    tty = interactive()
    if not name:
        name = ask("machine name", "Sauna") if tty else None
    if not name:
        die("a machine name is required\n" + USAGE)
    if ip is None and tty:
        ip = ask("target ip", "10.10.10.175 (blank: later)")
    if not diff:
        diff = choose("difficulty", DIFFICULTIES) if tty else die("difficulty is required (easy|medium|hard|insane)")
    if not os_:
        os_ = choose("operating system", OS_CHOICES) if tty else die("os is required (windows|linux|...)")

    ip = norm_ip(ip or "")
    diff = norm_difficulty(diff)
    os_ = norm_os(os_)
    for h in hosts:
        if not is_hostname(h):
            die(f"not a hostname: {h}")
    box = slugify(name)
    if not box:
        die(f"name has no usable characters: {name}")

    d = boxdir(box)
    existed = os.path.exists(os.path.join(d, "box.json"))
    for sub in SUBDIRS:
        os.makedirs(os.path.join(d, sub), exist_ok=True)

    # Re-running `new` on a box updates the fields given and keeps everything
    # else (creds, flags, notes) -- it never starts the manifest over.
    data = load(box)
    data.update({"name": name, "slug": f"htb-{box}", "os": os_, "difficulty": diff})
    if ip:
        data["ip"] = ip
    data["hostnames"] = sorted(set(data["hostnames"]) | set(hosts), key=len, reverse=True)
    if hosts and not data["domain"]:
        data["domain"] = guess_domain(data["hostnames"])
    data["tags"] = sorted(set(data["tags"]) | set(tags))
    save(box, data)
    render_writeup(d, data)

    set_current(box)
    point_target(data)
    info(paint(f"{'updated' if existed else 'new box'} {name}", "1;35", sys.stderr)
         + f"  {data['ip'] or '(no ip)'}  {os_}  {diff}"
         + (f"  {' '.join(data['hostnames'])}" if data["hostnames"] else ""))
    info(paint("  cd $BOXDIR  ·  htbbox info  ·  htbpaths", "2", sys.stderr))
    print(d)


def guess_domain(hosts):
    # Shortest name with exactly one dot is usually the AD domain (sequel.htb).
    two = [h for h in hosts if h.count(".") == 1]
    return min(two, key=len) if two else ""


def cmd_use(args):
    box, rest = pop_box(args)
    box = resolve(box or (rest[0] if rest else None))
    data = load(box)
    set_current(box)
    point_target(data)
    info(f"current box: {data['name']}  {data['ip'] or '(no ip)'}")
    print(boxdir(box))


def cmd_target(_args):
    """One line: what $TARGET points at right now."""
    def read(name):
        try:
            with open(os.path.join(STATE, name)) as fh:
                return fh.read().strip()
        except OSError:
            return ""
    ip, host, box = read("target"), read("host"), read("box")
    if not ip and not box:
        print("no target -- htbbox new, or htbbox use <box>")
        return
    print(f"target {ip or '(no ip)'}" + (f"  ({host})" if host else "")
          + (f"  box {box}" if box else ""))


def cmd_clear(args):
    """Forget the current target everywhere -- $TARGET/$BOX in every terminal,
    the /etc/hosts block, the prompt banner. Never touches ~/htb: every box
    directory, box.json, writeup and cast stays exactly where it is."""
    if args and args[0] in ("-h", "--help"):
        print("usage: htbbox clear   (forget the current target; keeps all box files)")
        return
    for name in ("target", "host", "box"):
        _write_state(name, "")
    ok = hosts_helper("clear")
    info("htbbox: target cleared" + ("" if ok else " (but see /etc/hosts above)")
         + " -- box directories untouched")
    if not ok:
        sys.exit(1)


def cmd_ls(_args):
    if not os.path.isdir(ROOT):
        print("no boxes yet -- htbbox new")
        return
    cur = current()
    entries = []
    for b in os.listdir(ROOT):
        d = boxdir(b)
        # _termsessions (htbcast with no box) and dotdirs are not boxes.
        if not os.path.isdir(d) or b.startswith(("_", ".")):
            continue
        j = os.path.join(d, "box.json")
        entries.append((os.path.getmtime(j if os.path.exists(j) else d), b))
    if not entries:
        print("no boxes yet -- htbbox new")
        return
    rows = []
    for _, b in sorted(entries, reverse=True):
        if os.path.exists(os.path.join(boxdir(b), "box.json")):
            x = load(b)
            rows.append(("*" if b == cur else " ", b, x["ip"] or "-", x["os"], x["difficulty"] or "-",
                         x["status"], x["created"]))
        else:
            rows.append(("*" if b == cur else " ", b, "(no manifest)", "", "", "", ""))
    head = ("", "BOX", "IP", "OS", "DIFF", "STATUS", "CREATED")
    widths = [max(len(r[i]) for r in rows + [head]) for i in range(len(head))]
    fmt = lambda r: "  ".join(c.ljust(w) for c, w in zip(r, widths)).rstrip()  # noqa: E731
    out = [paint(fmt(head), "2")]
    for r in rows:
        line = fmt(r)
        out.append(paint(line, "1;35") if r[0] == "*" else line)
    print("\n".join(out))


def cmd_info(args):
    box, rest = pop_box(args)
    box = resolve(box or (rest[0] if rest else None))
    x = load(box)
    d = boxdir(box)
    k = lambda s: paint(f"{s:<11}", "2")  # noqa: E731
    flag = lambda f: paint("✓ " + (f.get("at", "")[:16]), "32") if f else paint("·", "2")  # noqa: E731
    lines = [
        paint(f"{x['name']}", "1;35") + paint(f"  {x['slug']}" + ("  (current)" if box == current() else ""), "2"),
        f"{k('ip')}{x['ip'] or '-'}",
        f"{k('os')}{x['os']}",
        f"{k('difficulty')}{x['difficulty'] or '-'}",
        f"{k('status')}{x['status']}",
    ]
    if x["domain"]:
        lines.append(f"{k('domain')}{x['domain']}")
    if x["hostnames"]:
        lines.append(f"{k('hostnames')}{' '.join(x['hostnames'])}")
    lines.append(f"{k('flags')}user {flag(x['flags'].get('user'))}   root {flag(x['flags'].get('root'))}")
    lines.append(f"{k('created')}{x['created']}   updated {x['updated'][:16]}")
    lines.append(f"{k('path')}{d}")
    if x["ports"]:
        lines.append("")
        lines.append(paint("ports", "1"))
        for p in x["ports"]:
            svc = " ".join(s for s in (p.get("service"), p.get("product"), p.get("version")) if s)
            lines.append(f"  {str(p['port']) + '/' + p.get('proto', 'tcp'):<10} {svc}")
    if x["creds"]:
        lines.append("")
        lines.append(paint("creds", "1"))
        for c in x["creds"]:
            lines.append(f"  {c['user']:<20} {c['secret']:<28} {paint(c.get('note', ''), '2')}")
    if x["notes"]:
        lines.append("")
        lines.append(paint("notes", "1"))
        for n in x["notes"][-8:]:
            lines.append(f"  {paint(n['at'][5:16], '2')}  {n['text']}")
        if len(x["notes"]) > 8:
            lines.append(paint(f"  … {len(x['notes']) - 8} older (htbbox note)", "2"))
    lines.append("")
    counts = "  ".join(f"{s} {len(os.listdir(os.path.join(d, s))) if os.path.isdir(os.path.join(d, s)) else 0}"
                       for s in SUBDIRS)
    lines.append(paint(counts, "2"))
    print("\n".join(lines))


def cmd_path(args):
    box, rest = pop_box(args)
    print(boxdir(resolve(box or (rest[0] if rest else None))))


def cmd_json(args):
    box, rest = pop_box(args)
    # `htbbox json ip` (key on the current box) vs `htbbox json sauna`.
    key = None
    if rest and not box and os.path.isdir(boxdir(slugify(rest[0]))) and rest[0] not in load_keys():
        box, rest = rest[0], rest[1:]
    if rest:
        key = rest[0]
    x = load(resolve(box))
    if key:
        for part in key.split("."):
            x = x.get(part) if isinstance(x, dict) else None
        if isinstance(x, (dict, list)):
            print(json.dumps(x, indent=2))
        elif x is not None:
            print(x)
        return
    print(json.dumps(x, indent=2))


def load_keys():
    return {"name", "slug", "ip", "os", "difficulty", "hostnames", "domain", "platform", "status",
            "created", "updated", "flags", "creds", "ports", "notes", "tags", "schema"}


def cmd_set(args):
    box, rest = pop_box(args)
    if len(rest) < 2:
        die(f"usage: htbbox set <key> <value>   keys: {' '.join(SETTABLE)}")
    key, value = rest[0], " ".join(rest[1:])
    box = resolve(box)
    x = load(box)
    if key == "ip":
        value = norm_ip(value)
    elif key == "os":
        value = norm_os(value)
    elif key == "difficulty":
        value = norm_difficulty(value)
    elif key == "status" and value not in STATUSES:
        die(f"status must be one of {', '.join(STATUSES)}")
    elif key not in SETTABLE:
        die(f"can't set '{key}' -- settable: {' '.join(SETTABLE)} (or edit box.json)")
    x[key] = value
    save(box, x)
    if key == "ip" and box == current():
        point_target(x)
    info(f"{x['name']}: {key} = {value}")


def cmd_host(args):
    box, rest = pop_box(args)
    if not rest:
        die("usage: htbbox host <name...>")
    for h in rest:
        if not is_hostname(h):
            die(f"not a hostname: {h}")
    box = resolve(box)
    x = load(box)
    x["hostnames"] = sorted(set(x["hostnames"]) | set(rest), key=len, reverse=True)
    if not x["domain"]:
        x["domain"] = guess_domain(x["hostnames"])
    save(box, x)
    if box == current():
        point_target(x)
    info(f"{x['name']}: hostnames {' '.join(x['hostnames'])}")


def cmd_cred(args):
    box, rest = pop_box(args)
    box = resolve(box)
    x = load(box)
    if not rest:
        if not x["creds"]:
            print("no creds yet -- htbbox cred <user> <secret> [note]")
        for c in x["creds"]:
            print(f"{c['user']}\t{c['secret']}\t{c.get('note', '')}")
        return
    if len(rest) < 2:
        die("usage: htbbox cred <user> <secret> [note...]")
    user, secret, note = rest[0], rest[1], " ".join(rest[2:])
    kind = "hash" if re.fullmatch(r"[0-9a-fA-F]{32}(:[0-9a-fA-F]{32})?", secret) else "password"
    x["creds"].append({"user": user, "secret": secret, "type": kind, "note": note, "at": now()})
    save(box, x)
    # Keep a plain user/pass list beside it, for nxc/hydra -U/-P style use.
    with open(os.path.join(boxdir(box), "creds", "creds.txt"), "a") as fh:
        fh.write(f"{user}:{secret}\n")
    info(f"{x['name']}: cred {user} ({kind}) -- {len(x['creds'])} total")


def cmd_flag(args):
    box, rest = pop_box(args)
    if len(rest) != 2 or rest[0] not in ("user", "root"):
        die("usage: htbbox flag <user|root> <value>")
    which, value = rest
    if not re.fullmatch(r"[0-9a-fA-F]{32}", value):
        info("htbbox: note -- that is not a 32-char hex flag; saved anyway")
    box = resolve(box)
    x = load(box)
    x["flags"][which] = {"value": value, "at": now()}
    if which == "root" or x["status"] == "active":
        x["status"] = which
    save(box, x)
    info(paint(f"{x['name']}: {which} flag recorded", "1;32", sys.stderr))


def cmd_note(args):
    box, rest = pop_box(args)
    box = resolve(box)
    x = load(box)
    if not rest:
        for n in x["notes"]:
            print(f"{n['at'][:16]}  {n['text']}")
        if not x["notes"]:
            print("no notes yet -- htbbox note <text>")
        return
    x["notes"].append({"at": now(), "text": " ".join(rest)})
    save(box, x)
    info(f"{x['name']}: note added ({len(x['notes'])})")


def cmd_ports(args):
    box, rest = pop_box(args)
    box = resolve(box)
    d = boxdir(box)
    if rest:
        xml = rest[0]
    else:
        found = []
        for root, _, files in os.walk(os.path.join(d, "recon")):
            found += [os.path.join(root, f) for f in files if f.endswith(".xml")]
        if not found:
            die("no nmap XML in recon/ -- scan with -oA recon/<name> (or -oX), then rerun")
        xml = max(found, key=os.path.getmtime)
    try:
        tree = ET.parse(xml)
    except (ET.ParseError, OSError) as e:
        die(f"can't read {xml}: {e}", 1)
    ports = {}
    x = load(box)
    for p in x["ports"]:
        ports[(p["port"], p.get("proto", "tcp"))] = p
    for port in tree.iter("port"):
        st = port.find("state")
        if st is None or st.get("state") != "open":
            continue
        svc = port.find("service")
        entry = {"port": int(port.get("portid")), "proto": port.get("protocol", "tcp")}
        if svc is not None:
            for a in ("name", "product", "version"):
                if svc.get(a):
                    entry["service" if a == "name" else a] = svc.get(a)
        ports[(entry["port"], entry["proto"])] = entry
    x["ports"] = sorted(ports.values(), key=lambda p: (p["proto"], p["port"]))
    save(box, x)
    info(f"{x['name']}: {len(x['ports'])} open ports (from {os.path.relpath(xml, d)})")
    for p in x["ports"]:
        print(f"{p['port']}/{p['proto']}\t{p.get('service', '')}\t{p.get('product', '')} {p.get('version', '')}".rstrip())


# ── writeup ─────────────────────────────────────────────────────────────────

def render_writeup(outdir, x):
    """Render writeup.md once. Never overwrites: it is your prose after this."""
    writeup = os.path.join(outdir, "writeup.md")
    if os.path.exists(writeup):
        return
    today = dt.date.today().isoformat()
    body = None
    if os.path.exists(TEMPLATE):
        with open(TEMPLATE) as fh:
            body = fh.read()
        # Drop the Templater header: <%* ... -%> (the JS that prompts in Obsidian).
        body = re.sub(r"^<%\*.*?-%>\n", "", body, count=1, flags=re.S)
        subs = {
            "<% yaml(machine) %>": json.dumps(x["name"]),
            "<% yaml(slug) %>": json.dumps(x["slug"]),
            "<% yaml(targetOS) %>": json.dumps(x["os"]),
            "<% yaml(difficulty) %>": json.dumps(x["difficulty"]),
            '<% tp.date.now("YYYY-MM-DD") %>': today,
            "<% targetOS %>": x["os"],
            "<% difficulty %>": x["difficulty"],
            "<% tp.file.cursor() %>": "",
        }
        for token, value in subs.items():
            body = body.replace(token, value)
        body = body.replace('ip: ""', f"ip: {json.dumps(x['ip'])}")
        # A leftover <% ... %> means the vault template grew a token this
        # renderer does not know. Fail loudly rather than publish Templater source.
        leftover = re.findall(r"<%.*?%>", body, flags=re.S)
        if leftover:
            die(f"template has tokens this renderer does not handle: {leftover[:3]} -- update _htbbox.py", 1)
    if body is None:
        body = SKELETON.format(
            name=json.dumps(x["name"]), slug=json.dumps(x["slug"]), os=json.dumps(x["os"]),
            difficulty=json.dumps(x["difficulty"]), today=today, ip=json.dumps(x["ip"]),
            ip_raw=x["ip"], os_raw=x["os"], difficulty_raw=x["difficulty"],
            hosts=" ".join(x["hostnames"]) or "-",
        )
        info("htbbox: vault template not found, used the built-in skeleton")
    with open(writeup, "w") as fh:
        fh.write(body)


SKELETON = """\
---
title: {name}
slug: {slug}
type: writeup
site: daemon-sec
category: ctf
platform: HTB-Labs
machine: {name}
target_os: {os}
difficulty: {difficulty}
author: DAEMON
excerpt: ""
status: active
publish_status: draft
creation_date: {today}
published_at: ""
updated_at: ""
ip: {ip}
tools_used: []
techniques: []
bannerImage: ""
tags:
  - HTB
  - HTB/Labs
cssclasses:
  - editorial
  - note-banner
---

```dataviewjs
await dv.view("00Meta/Views/NoteBanner");
```

## Explain like I'm new

## Attack path

## Target details

| Field | Value |
| --- | --- |
| IP Address | {ip_raw} |
| Hostnames | {hosts} |
| Operating system | {os_raw} |
| Difficulty | {difficulty_raw} |

## Reconnaissance

## Enumeration

## Initial access

## Privilege escalation

## Credentials and flags

## Operator notes

## Lessons learned

## References
"""


# ── main ────────────────────────────────────────────────────────────────────

COMMANDS = {
    "new": cmd_new, "use": cmd_use, "switch": cmd_use,
    "ls": cmd_ls, "list": cmd_ls,
    "info": cmd_info, "show": cmd_info,
    "path": cmd_path, "json": cmd_json, "set": cmd_set,
    "host": cmd_host, "hosts": cmd_host,
    "cred": cmd_cred, "creds": cmd_cred,
    "flag": cmd_flag, "note": cmd_note, "notes": cmd_note,
    "ports": cmd_ports,
    "target": cmd_target, "clear": cmd_clear,
}


def main(argv):
    if not argv:
        argv = ["info"] if current() and os.path.isdir(boxdir(current())) else ["ls"]
    cmd, args = argv[0], argv[1:]
    if cmd in ("-h", "--help", "help"):
        print(USAGE, end="")
        return
    fn = COMMANDS.get(cmd)
    if not fn:
        print(USAGE, end="", file=sys.stderr)
        die(f"unknown command: {cmd}")
    fn(args)


if __name__ == "__main__":
    try:
        main(sys.argv[1:])
        sys.stdout.flush()
    except BrokenPipeError:
        # `htbbox ls | grep -q x` closes the pipe early; that is success, not
        # an error. Point stdout at devnull so the interpreter's own flush at
        # exit does not raise a second time.
        os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        sys.exit(0)
    except KeyboardInterrupt:
        sys.exit(130)