repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
vpn.nixNix475 lines21.8 KiBraw download
# modules/features/pentest/vpn.nix — the HTB VPN, as a systemd template unit.
#
#   htbvpn list            profiles in daemon.pentest.htb.vpnDir, active marked
#   htbvpn up <profile>    start it (stops whatever was up first)
#   htbvpn down            stop it
#   htbvpn status          unit state and the tunnel address
#   htbip                  just the tunnel address, for pasting into payloads
#
# A template unit rather than a backgrounded `sudo openvpn`: it survives
# closing the terminal, its output goes to the journal (`journalctl -u
# htbvpn@lab_eu_free`), and `htbvpn down` reliably kills it instead of leaving
# an orphan holding tun0.
#
# Profiles are NOT Nix-managed. They are per-account files that rotate every
# time you regenerate them on the HTB website, so the directory is created for
# you and left alone otherwise. Drop the .ovpn in and `htbvpn list` sees it.
{ lib, self, ... }:
{
  flake.nixosModules.pentest-vpn =
    { config, pkgs, lib, user, ... }:
    let
      cfg = config.daemon.pentest;
      on = cfg.enable;
      vpnDir = cfg.htb.vpnDir;
      sudo = "/run/wrappers/bin/sudo";
      # The sudoers rules below name this exact path, and sudo matches on the
      # resolved command. Calling a bare `systemctl` would resolve through PATH
      # to a /nix/store/... path, match no rule, and ask for a password that
      # `sudo -n` cannot supply.
      systemctl = "/run/current-system/sw/bin/systemctl";

      # Shared by htbvpn and htbip: the tunnel is whichever tun* exists, not
      # necessarily tun0 — a second VPN, or a profile with `dev tun1`, moves it.
      tunAddr = pkgs.writeShellScriptBin "htbip" ''
        set -uo pipefail
        for i in $(${pkgs.iproute2}/bin/ip -br link show type tun 2>/dev/null | ${pkgs.gawk}/bin/awk '{print $1}'); do
          a=$(${pkgs.iproute2}/bin/ip -4 -br addr show dev "$i" 2>/dev/null | ${pkgs.gawk}/bin/awk '{print $3}' | ${pkgs.coreutils}/bin/cut -d/ -f1)
          if [ -n "''${a:-}" ]; then printf '%s\n' "$a"; exit 0; fi
        done
        echo "htbip: no tun interface has an address — is the VPN up? (htbvpn status)" >&2
        exit 1
      '';

      # Root side, the fan-ec pattern (modules/hosts/laptop/fan-cli.nix): a
      # fixed store script that validates its own arguments and builds the unit
      # name itself.
      #
      # It replaces two `systemctl start|stop htbvpn@*` sudoers rules, which
      # were a privilege escalation: sudoers matches the argument pattern with
      # fnmatch and no FNM_PATHNAME, so `*` spans spaces and
      # `start htbvpn@x canary.service` matched the rule — systemd then started
      # both units. Any wheel user could start or stop anything, passwordless.
      htbvpn-ctl = pkgs.writeShellScriptBin "htbvpn-ctl" ''
        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.systemd pkgs.coreutils ]}
        [ "$EUID" = 0 ] || { echo "htbvpn-ctl: run as root (htbvpn does that)" >&2; exit 1; }

        # Exactly two arguments, so nothing extra can be appended.
        [ "$#" -eq 2 ] || { echo "usage: htbvpn-ctl start|stop <profile>" >&2; exit 2; }
        action="$1"
        profile="$2"

        case "$action" in
          start | stop) ;;
          *) echo "htbvpn-ctl: action must be start or stop" >&2; exit 2 ;;
        esac
        case "$profile" in
          "" | .* | *[!A-Za-z0-9_.-]*)
            echo "htbvpn-ctl: bad profile name: $profile" >&2; exit 2 ;;
        esac

        exec systemctl "$action" "htbvpn@$profile.service"
      '';

      # Root, before openvpn starts: copy the profile out of the user-owned
      # directory into /run/htbvpn/<profile> (root, 0700), keeping only
      # directives on an allowlist. --script-security 1 is not enough on its
      # own: it does not cover `plugin` (a .so loaded into the root process),
      # `log`/`status`/`writepid` (root writes any path), `management`, or a
      # nested `config`. A symlinked profile or key file is refused, so root
      # cannot be pointed at /etc/shadow either. Key files a profile names
      # (`secret static.key`, `ca ca.crt`) are copied beside it; HTB profiles
      # carry theirs inline, which passes through untouched.
      htbvpn-prepare = pkgs.writeShellScript "htbvpn-prepare" ''
        set -euo pipefail
        PATH=${lib.makeBinPath [ pkgs.coreutils ]}
        profile="$1"
        case "$profile" in
          "" | .* | *[!A-Za-z0-9_.-]*) echo "htbvpn: bad profile name: $profile" >&2; exit 2 ;;
        esac
        src=${lib.escapeShellArg vpnDir}
        out="/run/htbvpn/$profile"     # the unit's RuntimeDirectory, fresh each start

        if [ -L "$src/$profile.ovpn" ] || [ ! -f "$src/$profile.ovpn" ]; then
          echo "htbvpn: $src/$profile.ovpn is missing, a symlink, or not a regular file" >&2; exit 2
        fi

        allowed=" client tls-client pull dev dev-type proto remote remote-random
          resolv-retry nobind float persist-key persist-tun persist-remote-ip
          remote-cert-tls ns-cert-type verify-x509-name comp-lzo compress allow-compression
          verb mute cipher data-ciphers data-ciphers-fallback ncp-ciphers ncp-disable auth
          tls-version-min tls-version-max tls-cipher tls-ciphersuites tls-groups key-direction
          ifconfig ifconfig-ipv6 route route-ipv6 route-nopull route-metric pull-filter
          redirect-gateway block-ipv6 topology tun-mtu tun-mtu-extra link-mtu mssfix fragment
          sndbuf rcvbuf txqueuelen ping ping-restart ping-exit keepalive inactive
          connect-retry connect-retry-max connect-timeout server-poll-timeout
          hand-window tran-window reneg-sec reneg-bytes reneg-pkts explicit-exit-notify
          auth-nocache auth-retry tun-ipv6 setenv-safe ignore-unknown-option "
        allowed=" $(printf '%s ' $allowed)"   # one space-separated line
        files=" ca cert key tls-auth tls-crypt tls-crypt-v2 secret extra-certs pkcs12 "
        blocks=" ca cert key tls-auth tls-crypt tls-crypt-v2 secret extra-certs pkcs12 "

        copy_file() { # a plain file name in the profile directory, nothing else
          local f="$1"
          [ "$f" = "[inline]" ] && return 0
          case "$f" in
            "" | .* | *[!A-Za-z0-9_.-]*) echo "htbvpn: refused file reference: $f" >&2; exit 2 ;;
          esac
          if [ -L "$src/$f" ] || [ ! -f "$src/$f" ]; then
            echo "htbvpn: $src/$f is missing, a symlink, or not a regular file" >&2; exit 2
          fi
          install -m 0600 "$src/$f" "$out/$f"
        }

        block=""
        n=0
        while IFS= read -r line || [ -n "$line" ]; do
          n=$((n + 1))
          line="''${line%$'\r'}"
          if [ -n "$block" ]; then
            printf '%s\n' "$line"
            [ "$line" = "</$block>" ] && block=""
            continue
          fi
          trimmed="''${line#"''${line%%[![:space:]]*}"}"
          case "$trimmed" in "" | "#"* | ";"*) continue ;; esac
          if [[ "$trimmed" =~ ^\<([a-z0-9-]+)\>$ ]] && [[ "$blocks" == *" ''${BASH_REMATCH[1]} "* ]]; then
            block="''${BASH_REMATCH[1]}"
            printf '%s\n' "$trimmed"
            continue
          fi
          read -r word arg _ <<< "$trimmed"
          if [[ "$files" == *" $word "* ]]; then
            copy_file "''${arg:-}"
          elif [[ "$allowed" != *" $word "* ]]; then
            echo "htbvpn: $profile.ovpn line $n: '$word' is not allowed in a profile run as root" >&2
            exit 2
          fi
          printf '%s\n' "$trimmed"
        done < "$src/$profile.ovpn" > "$out/config.ovpn"

        [ -z "$block" ] || { echo "htbvpn: $profile.ovpn: unterminated <$block>" >&2; exit 2; }
        chmod 0600 "$out/config.ovpn"
      '';

      # One command to get on the lab, because `htbvpn up <profile>` is three
      # words too many when there is only ever one profile.
      htbup = pkgs.writeShellScriptBin "htbup" ''
        set -uo pipefail
        PATH=/run/current-system/sw/bin:${lib.makeBinPath [ pkgs.coreutils pkgs.findutils pkgs.gnused ]}:$PATH
        DIR=${lib.escapeShellArg vpnDir}

        p="''${1:-}"
        if [ -z "$p" ]; then
          # No argument: if exactly one profile exists, that is the one meant.
          n=$(find "$DIR" -maxdepth 1 -name '*.ovpn' 2>/dev/null | wc -l)
          if [ "$n" -eq 1 ]; then
            p=$(find "$DIR" -maxdepth 1 -name '*.ovpn' -printf '%f\n' | sed 's/\.ovpn$//')
          elif [ "$n" -eq 0 ]; then
            echo "htbup: no .ovpn profiles in $DIR" >&2
            echo "htbup: download one from HTB (Access -> OpenVPN) and drop it there" >&2
            exit 2
          else
            echo "htbup: several profiles — say which:" >&2
            htbvpn list >&2
            exit 2
          fi
        fi

        htbvpn up "$p" || exit 1
        echo ""
        htbvpn status
        if t=$(htbbox target 2>/dev/null | head -1); then echo "  $t"; fi
        echo "  serve payloads with: payload-serve"
      '';

      htbdown = pkgs.writeShellScriptBin "htbdown" ''
        exec /run/current-system/sw/bin/htbvpn down
      '';

      htbvpn = pkgs.writeShellScriptBin "htbvpn" ''
        set -uo pipefail
        PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnugrep pkgs.gnused pkgs.systemd pkgs.gawk ]}:$PATH
        DIR=${lib.escapeShellArg vpnDir}

        active() { systemctl list-units --type=service --state=active --no-legend 'htbvpn@*' 2>/dev/null \
                     | awk '{print $1}' | sed -n 's/^htbvpn@\(.*\)\.service$/\1/p' | head -1; }

        profiles() { [ -d "$DIR" ] && find "$DIR" -maxdepth 1 -name '*.ovpn' -printf '%f\n' 2>/dev/null | sed 's/\.ovpn$//' | sort; }

        usage() {
          echo "usage: htbvpn list | up <profile> | down | status"
          echo "       profiles live in $DIR (drop your .ovpn there)"
        }

        case "''${1:-status}" in
          list)
            cur=$(active)
            if [ -z "$(profiles)" ]; then
              echo "no .ovpn profiles in $DIR"
              echo "download one from HTB (Access → OpenVPN) and put it there"
              exit 0
            fi
            profiles | while read -r p; do
              if [ "$p" = "$cur" ]; then echo "* $p (up)"; else echo "  $p"; fi
            done ;;

          up)
            p="''${2:-}"
            [ -n "$p" ] || { echo "htbvpn: which profile?" >&2; usage >&2; exit 2; }
            # The instance name becomes part of a path in the unit's ExecStart,
            # so refuse anything that is not a plain file name.
            case "$p" in
              "" | .* | *[!A-Za-z0-9_.-]*)
                echo "htbvpn: bad profile name: $p" >&2
                echo "  profile names are plain file names: letters, digits, _ . -" >&2
                exit 2 ;;
            esac
            if [ ! -f "$DIR/$p.ovpn" ]; then
              echo "htbvpn: no such profile: $DIR/$p.ovpn" >&2
              echo "available:" >&2; profiles | sed 's/^/  /' >&2
              exit 2
            fi
            cur=$(active)
            if [ -n "$cur" ]; then
              echo "stopping htbvpn@$cur first (one tunnel at a time)"
              ${sudo} -n /run/current-system/sw/bin/htbvpn-ctl stop "$cur" || true
            fi
            ${sudo} -n /run/current-system/sw/bin/htbvpn-ctl start "$p" || {
              echo "htbvpn: failed to start; journalctl -u htbvpn@$p" >&2; exit 1; }
            for _ in $(seq 1 30); do
              if a=$(${lib.getExe tunAddr} 2>/dev/null); then echo "htbvpn: $p up, tunnel $a"; exit 0; fi
              sleep 1
            done
            echo "htbvpn: $p started but no tunnel address after 30s; journalctl -u htbvpn@$p" >&2
            exit 1 ;;

          down)
            cur=$(active)
            [ -n "$cur" ] || { echo "htbvpn: nothing is up"; exit 0; }
            ${sudo} -n /run/current-system/sw/bin/htbvpn-ctl stop "$cur"
            echo "htbvpn: $cur down" ;;

          status)
            cur=$(active)
            if [ -z "$cur" ]; then echo "htbvpn: down"; else
              echo "htbvpn: $cur up, tunnel $(${lib.getExe tunAddr} 2>/dev/null || echo '(no address yet)')"
            fi ;;

          -h|--help) usage ;;
          *) usage >&2; exit 2 ;;
        esac
      '';
    in
    {
      config = lib.mkIf on {
        environment.systemPackages = [ htbvpn htbvpn-ctl htbup htbdown tunAddr pkgs.openvpn ];

        # Trust the lab VPN interface so inbound reverse shells and callbacks on
        # tun0 are not dropped by the host firewall. Only traffic arriving on
        # tun0 is affected; every other interface stays firewalled. Without this
        # a reverse shell executes on the target but never connects back, which
        # looks like a payload failure and is miserable to diagnose.
        networking.firewall.trustedInterfaces = [ "tun0" ];

        # Trusting tun0 exposes every listener to the lab network, which is
        # full of boxes other players already own. Ad-hoc listeners there are
        # the point; the system's own must not be among them. LLMNR (5355)
        # answers name queries on every interface — exactly what Responder
        # farms — and mDNS (5353) announces this host. Lookups over mDNS
        # still work; it just no longer responds.
        services.resolved.settings.Resolve = {
          LLMNR = lib.mkDefault false;
          MulticastDNS = lib.mkDefault "resolve";
        };

        # The directory only; the profiles in it are yours. The parents are
        # listed explicitly: a tmpfiles `d` line does not reliably create a
        # missing ~/.config on a fresh account, which is why the VM test's
        # `test -d` failed.
        systemd.tmpfiles.rules = [
          "d /home/${user}/.config 0755 ${user} users - -"
          "d /home/${user}/.config/htb 0700 ${user} users - -"
          "d ${vpnDir} 0700 ${user} users - -"
        ];

        systemd.services."htbvpn@" = {
          description = "HTB OpenVPN profile %i";
          after = [ "network-online.target" ];
          wants = [ "network-online.target" ];
          serviceConfig = {
            Type = "simple";
            # openvpn never reads the user-owned profile: htbvpn-prepare copies
            # an allowlisted version into this root-only runtime directory
            # first (see above), and openvpn runs on that copy.
            RuntimeDirectory = "htbvpn/%i";
            RuntimeDirectoryMode = "0700";
            ExecStartPre = "${htbvpn-prepare} %i";
            # --script-security 1 comes AFTER --config deliberately: openvpn
            # applies options in order, so it overrides anything in the
            # profile. Level 1 still allows openvpn's built-in ifconfig/route.
            ExecStart =
              "${pkgs.openvpn}/bin/openvpn --suppress-timestamps"
              + " --config /run/htbvpn/%i/config.ovpn --script-security 1";
            # Profiles reference key files by relative path; prepare copies them here.
            WorkingDirectory = "/run/htbvpn/%i";
            Restart = "no";

            # Even a fully parsed profile only needs to make a tun device and
            # routes. Home is read-only (prepare reads the profile from it).
            CapabilityBoundingSet = [ "CAP_NET_ADMIN" "CAP_NET_RAW" "CAP_NET_BIND_SERVICE" "CAP_CHOWN" "CAP_FOWNER" "CAP_DAC_OVERRIDE" ];
            NoNewPrivileges = true;
            ProtectSystem = "strict";
            ProtectHome = "read-only";
            PrivateTmp = true;
            ProtectKernelModules = true;
            ProtectKernelTunables = false; # openvpn may set tun sysctls
            ProtectControlGroups = true;
            RestrictSUIDSGID = true;
            LockPersonality = true;
          };
        };

        # One argument-free grant on a fixed script, exactly as fan-cli.nix
        # does. No wildcard, so there is no argument pattern to widen.
        security.sudo.extraRules = [
          {
            groups = [ "wheel" ];
            commands = [
              { command = "${lib.getExe htbvpn-ctl}"; options = [ "NOPASSWD" ]; }
              { command = "/run/current-system/sw/bin/htbvpn-ctl"; options = [ "NOPASSWD" ]; }
            ];
          }
        ];
      };
    };

  perSystem =
    { pkgs, ... }:
    {
      # The deliverable is a running tunnel, so this boots a VM. OpenVPN in
      # static-key point-to-point mode configures its tun device before any
      # peer answers, which is what lets a single node assert a real address.
      checks.pentest-vpn-vm = pkgs.testers.runNixOSTest {
        name = "pentest-vpn";

        nodes.machine = { pkgs, ... }: {
          imports = [
            self.nixosModules.pentest-options
            self.nixosModules.pentest-vpn
          ];
          daemon.pentest.enable = true;
          _module.args.user = "daemonsec";
          users.users.daemonsec = {
            isNormalUser = true;
            extraGroups = [ "wheel" ];
          };

          # A unit the user must NOT be able to start through the VPN grant.
          systemd.services.canary = {
            description = "must not be startable by the htbvpn sudo rule";
            wantedBy = [ ];
            serviceConfig = {
              Type = "oneshot";
              ExecStart = "${pkgs.coreutils}/bin/touch /tmp/canary-fired";
            };
          };
        };

        testScript = ''
          machine.wait_for_unit("multi-user.target")
          d = "/home/daemonsec/.config/htb/vpn"

          machine.succeed(f"test -d {d}")

          # No profiles yet: `list` must say so and not fail.
          machine.succeed("su -l daemonsec -c 'htbvpn list' | grep 'no .ovpn profiles'")

          # A missing profile must exit 2 and start nothing (plan Task 13 #4).
          machine.fail("su -l daemonsec -c 'htbvpn up nosuchprofile'")
          machine.fail("systemctl is-active 'htbvpn@nosuchprofile.service'")

          # Two static-key p2p profiles, each on its own tun device.
          machine.succeed(f"openvpn --genkey secret {d}/static.key")
          for name, dev, local, peer in [
              ("profileA", "tun0", "10.8.0.1", "10.8.0.2"),
              ("profileB", "tun1", "10.9.0.1", "10.9.0.2"),
          ]:
              machine.succeed(
                  f"printf '%s\\n' 'dev {dev}' 'dev-type tun' 'ifconfig {local} {peer}' "
                  f"'secret static.key' 'remote 192.0.2.1' 'proto udp' 'ping 10' "
                  f"'data-ciphers-fallback AES-256-CBC' 'verb 3' > {d}/{name}.ovpn"
              )
          machine.succeed(f"chown -R daemonsec:users {d}")

          # up: unit active and the tunnel really has an address.
          machine.succeed("su -l daemonsec -c 'htbvpn up profileA'")
          machine.wait_for_unit("htbvpn@profileA.service")
          machine.succeed("ip -4 addr show tun0 | grep -q 10.8.0.1")
          machine.succeed("su -l daemonsec -c htbip | grep 10.8.0.1")
          machine.succeed("su -l daemonsec -c 'htbvpn list' | grep '\\* profileA (up)'")

          # Review Focus #5: switching stops the first one. Never two tunnels.
          machine.succeed("su -l daemonsec -c 'htbvpn up profileB'")
          machine.wait_for_unit("htbvpn@profileB.service")
          machine.fail("systemctl is-active 'htbvpn@profileA.service'")
          machine.fail("ip link show tun0")
          machine.succeed("ip -4 addr show tun1 | grep -q 10.9.0.1")

          # The grant must be "start my VPN", not "start anything".
          #
          # sudoers matches the argument pattern with fnmatch and no
          # FNM_PATHNAME, so `*` spans spaces: with a rule of
          # `systemctl start htbvpn@*`, the arguments
          # `start htbvpn@profileA canary.service` MATCH, and systemd starts
          # both units. That turned a VPN grant into "start any unit".
          machine.fail(
              "su -l daemonsec -c 'sudo -n /run/current-system/sw/bin/systemctl "
              "start htbvpn@profileB canary.service'"
          )
          machine.fail("test -e /tmp/canary-fired")
          machine.fail("systemctl is-active canary.service")

          # ...and the plain form must be refused too.
          machine.fail(
              "su -l daemonsec -c 'sudo -n /run/current-system/sw/bin/systemctl "
              "start canary.service'"
          )
          machine.fail("test -e /tmp/canary-fired")

          # A profile is run as root, so it must not be able to load code or
          # point root at other files: these are refused before openvpn starts.
          for name, body in [
              ("evilplugin", "plugin /tmp/evil.so"),
              ("evillog", "log /etc/evil-written-by-openvpn"),
              ("evilconfig", "config /etc/shadow"),
              ("evilkey", "secret ../../../../etc/shadow"),
          ]:
              machine.succeed(f"printf '%s\\n' 'dev tun2' '{body}' > {d}/{name}.ovpn")
          machine.succeed(f"ln -s /etc/shadow {d}/evillink.ovpn")
          machine.succeed(f"chown -R daemonsec:users {d}")
          for name in ["evilplugin", "evillog", "evilconfig", "evilkey", "evillink"]:
              machine.fail(f"su -l daemonsec -c 'htbvpn up {name}'")
              machine.fail(f"systemctl is-active 'htbvpn@{name}.service'")
          machine.fail("test -e /etc/evil-written-by-openvpn")
          machine.succeed("journalctl -u 'htbvpn@evilplugin' | grep \"'plugin' is not allowed\"")

          # The PATH-hijack class: a fake `id` first on the caller's PATH must
          # not run as root through the NOPASSWD grant.
          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 /run/current-system/sw/bin/htbvpn-ctl stop nosuch' || true")
          machine.fail("test -e /tmp/pwned")

          # down: nothing left holding a tunnel.
          machine.succeed("su -l daemonsec -c 'htbvpn down'")
          machine.fail("systemctl is-active 'htbvpn@profileB.service'")
          machine.succeed("su -l daemonsec -c 'htbvpn status' | grep down")
          machine.fail("su -l daemonsec -c htbip")
        '';
      };
    };
}