repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
htb.nixNix369 lines18.5 KiBraw download
# modules/features/pentest/htb.nix — the box you are currently on, shared by
# every terminal.
#
#   htbtime [host]                          clock-skew helper (defaults to $TARGET)
#   htb-hosts set <ip> <name>… | clear      root half of /etc/hosts (via sudo)
#
# Setting and clearing the target is htbbox's job (boxes.nix, _htbbox.py):
# `htbbox new|use` write $STATE/target, $STATE/host and $STATE/box and call
# htb-hosts; `htbbox clear` removes all three and the /etc/hosts block. There
# used to be a separate `htbtarget` command and the dotfiles' sqlite
# `htb-newbox` as well — three ways to set one target, and the dotfiles' one
# printed a banner nothing could clear. One command now owns it. The loader
# below turns the state files into $TARGET/$RHOST/$IP and $BOX/$BOXDIR.
#
# Why a file and a shell hook rather than an exported variable: a variable set
# in one terminal cannot reach a shell that is already running. The target
# lives in $XDG_STATE_HOME/htb/, and modules/home/htb-shell.nix re-reads it in
# zsh's precmd, so every terminal picks up a change at its next prompt. A shell
# sitting mid-command keeps the old value until it returns — that is inherent,
# and the cheat card says so.
#
# /etc/hosts needs care on NixOS: it is normally a symlink into the store, so
# it cannot be edited at all. environment.etc.hosts.mode below makes NixOS copy
# it instead, which is what makes `htbbox new … <fqdn>` possible. A rebuild
# regenerates the file and drops the block, which is fine: it is as ephemeral
# as the target itself. Kerberos needs the name to resolve, so this matters on
# every AD box.
{ lib, self, ... }:
{
  flake.nixosModules.pentest-htb =
    { config, pkgs, lib, user, ... }:
    let
      on = config.daemon.pentest.enable;
      sudo = "/run/wrappers/bin/sudo";
      beginMark = "# BEGIN htb (managed by htbbox — edits here are overwritten)";
      # The marker before htbtarget was folded into htbbox; still stripped, so a
      # block written by the old command does not survive as a stale mapping.
      legacyBeginMark = "# BEGIN htb (managed by htbtarget — edits here are overwritten)";
      endMark = "# END htb";

      # Root half: rewrites only the marked region of /etc/hosts. Validates its
      # own arguments rather than trusting the caller, because it runs as root.
      htb-hosts = pkgs.writeShellScriptBin "htb-hosts" ''
        set -uo pipefail
        # PATH first and with nothing appended: sudo keeps the caller's PATH (no
        # secure_path), so a bare `id` or an inherited `:$PATH` would let any
        # process running as the user put its own `id` first and get root.
        PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnused pkgs.gnugrep ]}
        [ "$EUID" = 0 ] || { echo "htb-hosts: run as root (htbbox does that through sudo)" >&2; exit 1; }

        F=/etc/hosts
        BEGIN=${lib.escapeShellArg beginMark}
        OLDBEGIN=${lib.escapeShellArg legacyBeginMark}
        END=${lib.escapeShellArg endMark}

        if [ -L "$F" ]; then
          echo "htb-hosts: $F is a symlink into the Nix store and cannot be edited." >&2
          echo "htb-hosts: environment.etc.hosts.mode should have made it a real file;" >&2
          echo "htb-hosts: rebuild the system (nh os switch) and try again." >&2
          exit 1
        fi

        strip_block() { sed -e "/^$BEGIN\$/,/^$END\$/d" -e "/^$OLDBEGIN\$/,/^$END\$/d" "$F"; }

        case "''${1:-}" in
          clear)
            tmp=$(mktemp); strip_block > "$tmp"
            cat "$tmp" > "$F"; rm -f "$tmp"
            echo "htb-hosts: cleared" ;;
          set)
            ip="''${2:-}"; shift 2 || true
            [ -n "$ip" ] && [ "$#" -gt 0 ] || { echo "usage: htb-hosts set <ip> <name>…" >&2; exit 2; }

            # Re-validate as root: this helper is reachable DIRECTLY through a
            # NOPASSWD sudo rule, so its own checks are the real boundary, not
            # htbbox's.
            #
            # Each argument is validated as ONE token — `for n in "$@"`, quoted.
            # An earlier version did `names="$*"` then `for n in $names`, which
            # word-split on whitespace: every token passed the DNS-label test
            # while the embedded newline survived into the printf, writing an
            # arbitrary extra line into /etc/hosts as root. The deny pattern
            # below rejects a newline only because the argument is not split.
            # Lab targets only: an IPv4 address in 10/8, 172.16/12 or
            # 192.168/16. Anything else would let a process running as the user
            # point a public name (github.com, cache.nixos.org) wherever it
            # likes, without a password.
            if ! [[ "$ip" =~ ^(10\.[0-9]{1,3}|172\.(1[6-9]|2[0-9]|3[01])|192\.168)\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
              echo "htb-hosts: bad address: $ip (lab IPv4 in 10/8, 172.16/12 or 192.168/16 only)" >&2; exit 2
            fi
            IFS=. read -r o1 o2 o3 o4 <<< "$ip"
            for o in "$o1" "$o2" "$o3" "$o4"; do
              [ "$((10#$o))" -le 255 ] || { echo "htb-hosts: bad address: $ip" >&2; exit 2; }
            done
            names=""
            for n in "$@"; do
              case "$n" in
                *[!A-Za-z0-9.-]*|-*|.*|"")
                  echo "htb-hosts: bad hostname: $n" >&2; exit 2 ;;
              esac
              names="''${names:+$names }$n"
            done

            tmp=$(mktemp)
            strip_block > "$tmp"
            printf '%s\n%s %s\n%s\n' "$BEGIN" "$ip" "$names" "$END" >> "$tmp"
            cat "$tmp" > "$F"; rm -f "$tmp"
            echo "htb-hosts: $ip $names" ;;
          *) echo "usage: htb-hosts set <ip> <name>… | clear" >&2; exit 2 ;;
        esac
      '';

      stateSh = ''
        STATE="''${XDG_STATE_HOME:-$HOME/.local/state}/htb"
        mkdir -p "$STATE"
      '';

      htbtime = pkgs.writeShellScriptBin "htbtime" ''
        set -uo pipefail
        ${stateSh}
        case "''${1:-}" in
          off|status) exec ${sudo} -n /run/current-system/sw/bin/htb-time "$1" ;;
        esac
        host="''${1:-}"
        if [ -z "$host" ]; then
          if [ -s "$STATE/target" ]; then host=$(cat "$STATE/target"); else
            echo "htbtime: no target set — run 'htbbox new' or 'htbbox use <box>' first, or 'htbtime <host>'" >&2
            exit 2
          fi
        fi
        exec ${sudo} -n /run/current-system/sw/bin/htb-time "$host"
      '';

    in
    {
      config = lib.mkIf on {
        environment.systemPackages = [ htbtime htb-hosts ];

        # $TARGET in every terminal.
        #
        # This has to be the NixOS option, not home-manager's
        # programs.zsh.initContent: zsh's real configuration here is the
        # dotfiles' ZDOTDIR tree (modules/home/shell.nix points ZDOTDIR at
        # ~/.dotfiles), home-manager's zsh module is not even enabled, and so
        # it generates no ~/.zshrc at all. An earlier version of this lived
        # there and was dead code — the state file was written and no shell
        # ever read it.
        #
        # /etc/zshrc is sourced for every interactive zsh BEFORE
        # $ZDOTDIR/.zshrc, so this coexists with the dotfiles rather than
        # competing with them, and `add-zsh-hook` appends, so their own precmd
        # hooks still run.
        programs.zsh.interactiveShellInit = lib.mkAfter ''
          # --- htb target, shared across terminals ---------------------------
          # Re-read before each prompt, so a target set in another terminal
          # shows up here. Three small reads of files under $XDG_STATE_HOME.
          _htb_state="''${XDG_STATE_HOME:-$HOME/.local/state}/htb"
          _htb_load() {
            if [[ -s "$_htb_state/target" ]]; then
              local t
              t="$(<"$_htb_state/target")"
              export TARGET="''${t%%$'\n'*}"
              export RHOST="$TARGET" IP="$TARGET"
            else
              unset TARGET RHOST IP
            fi
            if [[ -s "$_htb_state/box" ]]; then
              local b
              b="$(<"$_htb_state/box")"
              export BOX="''${b%%$'\n'*}"
              export BOXDIR="''${HTB_ROOT:-$HOME/htb}/$BOX"
            else
              unset BOX BOXDIR
            fi
          }
          autoload -Uz add-zsh-hook
          add-zsh-hook precmd _htb_load
          _htb_load
        '';

        # Makes /etc/hosts a real, writable file instead of a store symlink.
        # Without this htb-hosts cannot work at all (and says so).
        environment.etc.hosts.mode = "0644";

        security.sudo.extraRules = [
          {
            groups = [ "wheel" ];
            commands = [
              { command = "${lib.getExe htb-hosts}"; options = [ "NOPASSWD" ]; }
              { command = "/run/current-system/sw/bin/htb-hosts"; options = [ "NOPASSWD" ]; }
            ];
          }
        ];
      };
    };

  perSystem =
    { pkgs, ... }:
    {
      checks.pentest-htb-vm = pkgs.testers.runNixOSTest {
        name = "pentest-htb";

        nodes.machine = { pkgs, ... }: {
          imports = [
            self.nixosModules.pentest-options
            self.nixosModules.pentest-htb
            self.nixosModules.pentest-boxes # htbbox, asserted below
          ];
          daemon.pentest.enable = true;
          # The real host has zsh as the login shell; /etc/zshrc (where the
          # $TARGET loader goes) only exists when this is on.
          programs.zsh.enable = true;
          _module.args.user = "daemonsec";
          users.users.daemonsec = {
            isNormalUser = true;
            extraGroups = [ "wheel" ];
            shell = pkgs.zsh;
          };
        };

        testScript = ''
          machine.wait_for_unit("multi-user.target")

          def as_user(cmd):
              return f"su -l daemonsec -c {cmd!r}"

          # The NixOS-specific precondition: /etc/hosts must be a real file.
          machine.succeed("test -f /etc/hosts && test ! -L /etc/hosts")

          machine.succeed(as_user("htbbox target") + " | grep -q 'no target'")

          # Review Focus #4: malformed input is refused BEFORE /etc/hosts is
          # touched, and before a box directory is made.
          hosts_before = machine.succeed("cat /etc/hosts")
          machine.fail(as_user("htbbox new -n Bad1 -d easy -o linux -i 'not an ip'"))
          machine.fail(as_user("htbbox new -n Bad2 -d easy -o linux -i 10.10.11.999"))
          machine.fail(as_user("htbbox new -n Bad3 -d easy -o linux -i 10.10.11.5 -H 'bad name'"))
          # An embedded newline must not smuggle a second /etc/hosts entry.
          machine.fail(as_user("htbbox new -n Bad4 -d easy -o linux -i 10.10.11.5 -H $'x.htb\\n1.2.3.4 evil.htb'"))
          machine.fail(as_user("htbbox new -n Bad5 -d easy -o linux -i 10.10.11.5 -H $'x.htb\\n'"))
          assert machine.succeed("cat /etc/hosts") == hosts_before, "/etc/hosts changed on a rejected input"
          machine.fail("grep -q evil /etc/hosts")

          # A hostname writes exactly one marked block, and is idempotent.
          machine.succeed(as_user("htbbox new -n Vin -d easy -o windows -i 10.10.11.5 -H dc01.vintage.htb -H vintage.htb"))
          machine.succeed("grep -q '10.10.11.5 dc01.vintage.htb vintage.htb' /etc/hosts")
          assert machine.succeed("grep -c 'BEGIN htb' /etc/hosts").strip() == "1"
          machine.succeed(as_user("htbbox set ip 10.10.11.6"))
          assert machine.succeed("grep -c 'BEGIN htb' /etc/hosts").strip() == "1", "block duplicated"
          machine.succeed("grep -q '10.10.11.6 dc01.vintage.htb' /etc/hosts")
          machine.fail("grep -q 10.10.11.5 /etc/hosts")
          machine.succeed(as_user("htbbox target") + " | grep -q 10.10.11.6")

          # localhost must survive all of this.
          machine.succeed("grep -q '127.0.0.1 localhost' /etc/hosts")

          # The ROOT helper must refuse the same input, not just htbbox:
          # it is reachable directly through a NOPASSWD sudo rule, so its own
          # validation is the real boundary. `names="$*"` + unquoted `for n in
          # $names` word-split each token while leaving the newline intact,
          # which wrote an arbitrary second line into /etc/hosts as root.
          machine.fail("htb-hosts set 10.10.11.7 $'dc01.htb\n6.6.6.6 attacker.evil'")
          machine.fail("grep -q attacker.evil /etc/hosts")
          machine.fail("su -l daemonsec -c \"sudo -n htb-hosts set 10.10.11.7 $'a\n9.9.9.9 evil2'\"")
          machine.fail("grep -q evil2 /etc/hosts")

          # Lab addresses only: a passwordless grant must not repoint public names.
          machine.fail("su -l daemonsec -c 'sudo -n htb-hosts set 140.82.112.3 github.com'")
          machine.fail("su -l daemonsec -c 'sudo -n htb-hosts set 10.10.300.1 x.htb'")
          machine.fail("grep -q github.com /etc/hosts")

          # A fake `id` first on the caller's PATH must not run as root.
          machine.succeed("mkdir -p /tmp/fake && printf '#!/bin/sh\\ntouch /tmp/pwned; echo 0\\n' > /tmp/fake/id && chmod 755 /tmp/fake/id")
          machine.succeed("su -l daemonsec -c 'PATH=/tmp/fake:$PATH sudo -n htb-hosts clear' || true")
          machine.fail("test -e /tmp/pwned")
          machine.succeed("grep -q '127.0.0.1 localhost' /etc/hosts")

          # C1, the whole point of the feature: an interactive shell must
          # actually export $TARGET. The state file existing is not enough —
          # the first implementation wrote the file and no shell ever read it.
          # NB the escaped dollars: `su -l … -c "…"` runs a NON-interactive
          # login shell, which would expand $TARGET to empty itself before the
          # inner interactive zsh (the one that sources /etc/zshrc) ever sees
          # it. That made this assertion fail against working code once.
          out = machine.succeed(
              "su -l daemonsec -c 'zsh -ic \"echo T=\\$TARGET R=\\$RHOST I=\\$IP B=\\$BOX\"'"
          )
          for want in ["T=10.10.11.6", "R=10.10.11.6", "I=10.10.11.6", "B=vin"]:
              assert want in out, f"expected {want} in a fresh shell, got: {out!r}"

          # clear forgets the target everywhere but deletes nothing on disk.
          machine.succeed(as_user("htbbox clear"))
          machine.fail("grep -q 'BEGIN htb' /etc/hosts")
          machine.succeed(as_user("htbbox target") + " | grep -q 'no target'")
          machine.succeed("test -s /home/daemonsec/htb/vin/box.json")
          machine.succeed("test -d /home/daemonsec/htb/vin/casts")
          # No brackets: zsh globs "[]" and fails on no-match. No braced
          # parameter expansion either, because Nix interpolates that out of
          # this testScript string. A trailing dot shows an empty expansion.
          out = machine.succeed(
              "su -l daemonsec -c 'zsh -ic \"print -r -- t=\\$TARGET. b=\\$BOX.\"'"
          )
          assert "t=." in out and "b=." in out, f"expected $TARGET/$BOX unset after clear, got: {out!r}"

          # htbtime with no target must name the command that sets one.
          # Captured, not piped: the driver runs with pipefail, so htbtime's
          # intended exit 2 would fail a pipeline even when grep matches.
          out = machine.fail(as_user("htbtime") + " 2>&1")
          assert "htbbox new" in out, f"htbtime should point at htbbox new, got: {out!r}"

          # Engagement scaffolding (boxes.nix). Every field is passed, so gum
          # never prompts -- a prompt in a VM test would hang until timeout.
          out = machine.succeed(as_user(
              "htbbox new -n EscapeTwo -i 10.10.11.202 -d medium -o windows"
          )).strip()
          assert out.endswith("/htb/escapetwo"), out
          for sub in ["recon", "enum", "creds", "loot", "exploit", "serve", "casts"]:
              machine.succeed(f"test -d /home/daemonsec/htb/escapetwo/{sub}")

          # The manifest every other tool reads, and the slug the website uses.
          machine.succeed(
              "grep -q '\"slug\": \"htb-escapetwo\"' /home/daemonsec/htb/escapetwo/box.json"
          )
          machine.succeed(
              "grep -q '\"difficulty\": \"medium\"' /home/daemonsec/htb/escapetwo/box.json"
          )
          # Frontmatter the importer needs, from the built-in skeleton (no
          # vault in the VM), and no un-substituted Templater tokens anywhere.
          machine.succeed("grep -q '^target_os: \"Windows\"' /home/daemonsec/htb/escapetwo/writeup.md")
          machine.succeed("grep -q '^ip: \"10.10.11.202\"' /home/daemonsec/htb/escapetwo/writeup.md")
          machine.fail("grep -q '<%' /home/daemonsec/htb/escapetwo/writeup.md")

          # Scaffolding a box points the whole toolkit at it.
          machine.succeed(as_user("htbbox target") + " | grep -q 10.10.11.202")
          machine.succeed(as_user("htbbox ls") + " | grep -q escapetwo")
          machine.succeed(as_user("htbbox path") + " | grep -q /htb/escapetwo")
          machine.succeed(as_user("htbbox info") + " | grep -q EscapeTwo")

          # Positional form, any order, with hostnames: the shape of each
          # argument says what it is.
          machine.succeed(as_user("htbbox new 10.10.11.9 hard Vintage linux dc01.vintage.htb vintage.htb"))
          machine.succeed("grep -q '\"os\": \"Linux\"' /home/daemonsec/htb/vintage/box.json")
          machine.succeed("grep -q '\"domain\": \"vintage.htb\"' /home/daemonsec/htb/vintage/box.json")
          machine.succeed("grep -q '10.10.11.9 dc01.vintage.htb vintage.htb' /etc/hosts")
          machine.succeed(as_user("htbbox cred svc_sql 'Passw0rd!' mssql"))
          machine.succeed(as_user("htbbox json creds") + " | grep -q svc_sql")
          machine.succeed(as_user("htbbox flag user 0123456789abcdef0123456789abcdef"))
          assert machine.succeed(as_user("htbbox json status")).strip() == "user"
          machine.succeed(as_user("htbbox use escapetwo"))
          machine.succeed(as_user("htbbox target") + " | grep -q 10.10.11.202")
          out = machine.succeed("su -l daemonsec -c 'zsh -ic \"echo D=\\$BOXDIR\"'")
          assert "D=/home/daemonsec/htb/escapetwo" in out, out

          # Bad input is refused rather than written into the manifest.
          machine.fail(as_user("htbbox new -n Nope -d impossible -o linux -i 10.0.0.1"))
          machine.fail(as_user("htbbox new -n Nope -d easy -o plan9 -i 10.0.0.1"))
          machine.fail(as_user("htbbox new -n Nope -d easy -o linux -i notanip"))
          machine.fail("test -d /home/daemonsec/htb/nope")

          # Rerunning must not clobber a writeup already being written.
          machine.succeed("echo 'MY PROSE' >> /home/daemonsec/htb/escapetwo/writeup.md")
          machine.succeed(as_user(
              "htbbox new -n EscapeTwo -i 10.10.11.202 -d medium -o windows"
          ))
          machine.succeed("grep -q 'MY PROSE' /home/daemonsec/htb/escapetwo/writeup.md")
        '';
      };
    };
}