repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
bloodhound.nixNix450 lines20.3 KiBraw download
# modules/features/pentest/bloodhound.nix — both BloodHound viewers, each with
# a single command that brings up everything it needs.
#
#   bloodhound ce        postgres + neo4j + the CE API, then the URL to open
#   bloodhound legacy    neo4j + the archived 4.3.1 GUI
#   bloodhound status    what is up, and where
#   bloodhound down      stop all of it
#   bloodhound creds     the CE admin password (printed on first start)
#
# The two are NOT interchangeable, and this is the thing that wastes an hour:
#
#   bloodhound-ce      reads CE-format JSON. Collect with `rusthound-ce` or
#                      SharpHound CE ($PAYLOADS/windows/amd64/ad).
#   bloodhound-legacy  reads the OLD format, which is what
#                      `bloodhound-python` 1.9 and SharpHound v1 produce. CE
#                      refuses it, which is the only reason this is still here.
#                      nixpkgs dropped it (archived upstream, Electron 11) —
#                      lab data only.
#
# Nothing starts at boot: neo4j is a JVM that wants a gigabyte, and the API
# follows it. `bloodhound ce` is how you pay for it, when you want it.
#
# Every credential is generated on first start and kept in the state
# directory (0750 bloodhound, files 0600): the neo4j password, the postgres
# role password, the JWT key and the CE admin password. Loopback-only is not
# enough on its own: any local process, or a web page doing DNS rebinding
# against 127.0.0.1:7474, could otherwise read or rewrite a client's AD graph.
# `bloodhound creds` prints the ones you type.
{ lib, self, ... }:
{
  imports = [
    ((import ./_sets.nix { inherit lib; }) {
      name = "bloodhound";
      description = "BloodHound CE and Legacy, with neo4j and postgresql";

      packages =
        pkgs:
        let
          extra = import ./_pkgs/default.nix { inherit lib pkgs; };
        in
        [
          pkgs.bloodhound-ce # the CE API + web graph viewer
          pkgs.bloodhound-py # legacy-format collector
          pkgs.rusthound-ce # CE-format collector
          # Neo4j 4.4, NOT nixpkgs' 2026.x: BloodHound CE's migration calls
          # `db.indexes`, removed in Neo4j 5. See _pkgs/default.nix.
          extra.neo4j44 # `neo4j`, `cypher-shell`, `neo4j-admin`
          extra.bloodhoundLegacy
        ];

      expectedBins = [
        "bloodhound-ce"
        "bloodhound-legacy"
        "cypher-shell"
        "neo4j"
        "bloodhound-python"
        "rusthound-ce"
      ];

      extraConfig =
        { pkgs, lib, config, ... }:
        let
          stateDir = "/var/lib/bloodhound";
          configFile = "${stateDir}/bhapi.json";
          port = 8080;
          systemctl = "/run/current-system/sw/bin/systemctl";
          sudo = "/run/wrappers/bin/sudo";
          dbUnits = "neo4j.service postgresql.service";

          extra = import ./_pkgs/default.nix { inherit lib pkgs; };
          neo4j44 = extra.neo4j44;

          # Neo4j's scripts expect a writable NEO4J_HOME. Build one per boot:
          # lib/ and bin/ come from the store, everything it writes is real.
          neo4jSetup = pkgs.writeShellScript "neo4j-setup" ''
            set -euo pipefail
            PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.openssl ]}:$PATH
            H=${stateDir}/neo4j
            mkdir -p $H/{conf,data,logs,run,import,plugins,certificates}
            ln -sfn ${neo4j44}/share/neo4j/lib $H/lib
            ln -sfn ${neo4j44}/share/neo4j/bin $H/bin
            # A generated password, set through neo4j-admin before the server
            # starts. On a graph that already exists, neo4j 4.4 applies it
            # while the built-in user still has the default password.
            [ -s ${stateDir}/neo4j.pw ] || { (umask 077; openssl rand -hex 24 > ${stateDir}/neo4j.pw); }
            if [ ! -e $H/.initial-password-set ]; then
              ${neo4j44}/bin/neo4j-admin set-initial-password "$(cat ${stateDir}/neo4j.pw)" >/dev/null
              touch $H/.initial-password-set
            fi
            cat > $H/conf/neo4j.conf <<'EOF'
            # One lab graph on loopback, password-protected (see the header).
            dbms.security.auth_enabled=true
            dbms.default_listen_address=127.0.0.1
            dbms.connector.bolt.enabled=true
            dbms.connector.bolt.listen_address=127.0.0.1:7687
            dbms.connector.http.enabled=true
            dbms.connector.http.listen_address=127.0.0.1:7474
            dbms.connector.https.enabled=false
            dbms.memory.heap.initial_size=512m
            dbms.memory.heap.max_size=1G
            dbms.memory.pagecache.size=512m
            dbms.jvm.additional=-XX:+UseG1GC
            EOF
            ${pkgs.gnused}/bin/sed -i 's/^            //' $H/conf/neo4j.conf
          '';

          # Root, before the API starts: give the postgres role a generated
          # password (ensureUsers sets none) so pg_hba can require it instead
          # of trusting every local process. SQL goes over stdin, never argv.
          pgPassword = pkgs.writeShellScript "bloodhound-pg-password" ''
            set -euo pipefail
            PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.openssl pkgs.util-linux ]}
            f=${stateDir}/postgres.pw
            if [ ! -s "$f" ]; then
              (umask 077; openssl rand -hex 24 > "$f")
              chown bloodhound:bloodhound "$f"
            fi
            printf "ALTER ROLE bloodhound WITH PASSWORD '%s';\n" "$(cat "$f")" \
              | runuser -u postgres -- ${config.services.postgresql.package}/bin/psql -X -q -v ON_ERROR_STOP=1 -d postgres
          '';

          # The config is written at START, not by Nix: it carries a generated
          # JWT signing key, and a secret in the Nix store is world-readable.
          mkConfig = pkgs.writeShellScript "bloodhound-ce-config" ''
            set -euo pipefail
            PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.openssl pkgs.jq ]}:$PATH
            mkdir -p ${stateDir}/work
            [ -s ${stateDir}/jwt.key ] || { openssl rand -base64 48 > ${stateDir}/jwt.key; chmod 600 ${stateDir}/jwt.key; }
            [ -s ${stateDir}/admin.pw ] || { openssl rand -base64 18 > ${stateDir}/admin.pw; chmod 600 ${stateDir}/admin.pw; }

            # --rawfile, not --arg "$(cat …)": argv is readable by every user in ps.
            jq -n \
              --rawfile jwt ${stateDir}/jwt.key \
              --rawfile pw  ${stateDir}/admin.pw \
              --rawfile neo ${stateDir}/neo4j.pw \
              --rawfile pg  ${stateDir}/postgres.pw \
              '{
                 version: 1,
                 bind_addr: "127.0.0.1:${toString port}",
                 root_url: "http://127.0.0.1:${toString port}/",
                 metrics_port: "127.0.0.1:2112",
                 work_dir: "${stateDir}/work",
                 log_level: "INFO",
                 graph_driver: "neo4j",
                 collectors_base_path: "${pkgs.bloodhound-ce.collectors}",
                 database: {
                   addr: "127.0.0.1:5432",
                   database: "bloodhound",
                   username: "bloodhound",
                   secret: ($pg | rtrimstr("\n"))
                 },
                 neo4j: {
                   addr: "127.0.0.1:7687",
                   database: "neo4j",
                   username: "neo4j",
                   secret: ($neo | rtrimstr("\n"))
                 },
                 crypto: {
                   jwt: { signing_key: ($jwt | rtrimstr("\n")) },
                   argon2: { memory_kibibytes: 1048576, num_iterations: 1, num_threads: 4 }
                 },
                 default_admin: {
                   principal_name: "admin",
                   password: ($pw | rtrimstr("\n")),
                   email_address: "admin@bloodhound.lab",
                   first_name: "Admin",
                   last_name: "User",
                   expire_now: false
                 },
                 enable_startup_wait_period: false,
                 enable_api_logging: true,
                 enable_cypher_mutations: true,
                 disable_cypher_complexity_limit: true
               }' > ${configFile}
            chmod 600 ${configFile}
          '';

          bloodhound = pkgs.writeShellScriptBin "bloodhound" ''
            set -uo pipefail
            PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.curl pkgs.systemd pkgs.gnugrep ]}:$PATH

            wait_for() { # wait_for <url> <seconds> <label>
              local i
              for i in $(seq 1 "$2"); do
                curl -fsS -o /dev/null "$1" 2>/dev/null && return 0
                sleep 1
              done
              echo "bloodhound: $3 did not answer within $2s" >&2
              return 1
            }

            start_dbs() {
              echo "bloodhound: starting ${dbUnits} (neo4j is a JVM — give it ~20s)"
              ${sudo} -n ${systemctl} start ${dbUnits} || return 1
              wait_for http://127.0.0.1:7474 90 "neo4j" || {
                echo "  journalctl -u neo4j" >&2; return 1; }
              echo "bloodhound: neo4j up (browser: http://127.0.0.1:7474)"
            }

            case "''${1:-status}" in
              ce)
                start_dbs || exit 1
                echo "bloodhound: starting the CE API"
                ${sudo} -n ${systemctl} start bloodhound-ce.service || {
                  echo "  journalctl -u bloodhound-ce" >&2; exit 1; }
                if wait_for http://127.0.0.1:${toString port}/ui/login 120 "the CE API"; then
                  echo ""
                  echo "  BloodHound CE:  http://127.0.0.1:${toString port}/"
                  echo "  user:           admin"
                  echo "  password:       run 'bloodhound creds'"
                  echo ""
                  echo "  Upload CE-format zips only (rusthound-ce / SharpHound CE)."
                else
                  echo "  journalctl -u bloodhound-ce" >&2; exit 1
                fi ;;

              legacy)
                # Legacy talks straight to neo4j; it needs no API server.
                start_dbs || exit 1
                echo "bloodhound: launching the archived 4.3.1 GUI"
                echo "  connect to  bolt://127.0.0.1:7687  as neo4j (password: bloodhound creds)"
                echo "  feed it LEGACY-format zips (bloodhound-python / SharpHound v1)"
                exec bloodhound-legacy ;;

              creds)
                # Read through sudo, not with a `[ -r ]` guard first: the file
                # belongs to the bloodhound service user and is mode 600, so
                # it is deliberately unreadable to you directly — the guard
                # was always false and this never printed anything.
                pw=$(${sudo} -n ${pkgs.coreutils}/bin/cat ${stateDir}/admin.pw 2>/dev/null || true)
                if [ -n "''${pw:-}" ]; then
                  echo "user: admin"
                  echo "pass: $pw"
                  neo=$(${sudo} -n ${pkgs.coreutils}/bin/cat ${stateDir}/neo4j.pw 2>/dev/null || true)
                  [ -z "''${neo:-}" ] || printf 'neo4j (legacy GUI, cypher-shell): neo4j / %s\n' "$neo"
                else
                  echo "bloodhound: no credentials yet — run 'bloodhound ce' once" >&2
                  exit 1
                fi ;;

              down)
                ${sudo} -n ${systemctl} stop bloodhound-ce.service 2>/dev/null || true
                ${sudo} -n ${systemctl} stop ${dbUnits} || true
                echo "bloodhound: stopped" ;;

              status)
                for u in neo4j.service postgresql.service bloodhound-ce.service; do
                  printf '  %-24s %s\n' "$u" "$(systemctl is-active "$u" 2>/dev/null || echo inactive)"
                done
                curl -fsS -o /dev/null http://127.0.0.1:${toString port}/ui/login 2>/dev/null \
                  && echo "  CE UI: http://127.0.0.1:${toString port}/" \
                  || echo "  CE UI: not answering" ;;

              -h|--help) echo "usage: bloodhound ce | legacy | creds | status | down" ;;
              *) echo "usage: bloodhound ce | legacy | creds | status | down" >&2; exit 2 ;;
            esac
          '';
        in
        {
          # NOT services.neo4j: that module is pinned to nixpkgs' neo4j
          # 2026.09, which BloodHound CE cannot talk to (it calls `db.indexes`,
          # gone in Neo4j 5). This is the same shape, on 4.4.
          #
          # Neo4j wants a WRITABLE home: the distribution lives in the store,
          # so the pre-start builds one under the state directory with lib/
          # symlinked in and real conf/data/logs/run dirs.
          systemd.services.neo4j = {
            description = "Neo4j 4.4 (for BloodHound)";
            wantedBy = [ ]; # a JVM wanting ~1 GB; started by `bloodhound`
            serviceConfig = {
              Type = "simple";
              User = "bloodhound";
              Group = "bloodhound";
              StateDirectory = "bloodhound";
              StateDirectoryMode = "0750";
              Environment = [
                "NEO4J_HOME=${stateDir}/neo4j"
                "NEO4J_CONF=${stateDir}/neo4j/conf"
              ];
              ExecStartPre = "${neo4jSetup}";
              ExecStart = "${lib.getExe neo4j44} console";
              Restart = "no";
              TimeoutStartSec = "180";
            };
          };

          services.postgresql = {
            enable = true;
            ensureDatabases = [ "bloodhound" ];
            ensureUsers = [
              {
                name = "bloodhound";
                ensureDBOwnership = true;
              }
            ];
            # BloodHound connects over TCP with a password (its DSN is
            # postgresql://user:secret@addr/db). ensureUsers sets none, so
            # bloodhound-ce's pre-start sets a generated one (pgPassword).
            authentication = lib.mkAfter ''
              host bloodhound bloodhound 127.0.0.1/32 scram-sha-256
              host bloodhound bloodhound ::1/128      scram-sha-256
            '';
          };

          systemd.services.bloodhound-ce = {
            description = "BloodHound CE API server";
            wantedBy = [ ]; # started by `bloodhound ce`
            after = [ "neo4j.service" "postgresql.service" ]
              ++ lib.optional (config.systemd.services ? postgresql-setup) "postgresql-setup.service";
            requires = [ "neo4j.service" "postgresql.service" ];
            serviceConfig = {
              Type = "simple";
              ExecStartPre = [ "+${pgPassword}" "${mkConfig}" ];
              ExecStart = "${lib.getExe pkgs.bloodhound-ce} -configfile ${configFile}";
              User = "bloodhound";
              Group = "bloodhound";
              StateDirectory = "bloodhound";
              StateDirectoryMode = "0750";
              WorkingDirectory = stateDir;
              Restart = "no";
              # It only needs loopback and its own state.
              PrivateTmp = true;
              ProtectSystem = "strict";
              ProtectHome = true;
              NoNewPrivileges = true;
              ReadWritePaths = [ stateDir ];
            };
          };

          users.users.bloodhound = {
            isSystemUser = true;
            group = "bloodhound";
            home = stateDir;
            description = "BloodHound CE and its neo4j";
          };
          users.groups.bloodhound = { };

          environment.systemPackages = [ bloodhound ];

          # Scoped as fan-cli.nix does: wheel, no password, these units only.
          security.sudo.extraRules = [
            {
              groups = [ "wheel" ];
              commands = [
                { command = "${systemctl} start ${dbUnits}"; options = [ "NOPASSWD" ]; }
                { command = "${systemctl} stop ${dbUnits}"; options = [ "NOPASSWD" ]; }
                { command = "${systemctl} start bloodhound-ce.service"; options = [ "NOPASSWD" ]; }
                { command = "${systemctl} stop bloodhound-ce.service"; options = [ "NOPASSWD" ]; }
                { command = "${pkgs.coreutils}/bin/cat ${stateDir}/admin.pw"; options = [ "NOPASSWD" ]; }
                { command = "${pkgs.coreutils}/bin/cat ${stateDir}/neo4j.pw"; options = [ "NOPASSWD" ]; }
              ];
            }
          ];
        };
    })

    # The deliverable is "one command brings BloodHound up", so the test boots
    # a VM and drives that command — a binary-resolution check cannot see
    # whether neo4j actually starts or the API actually answers.
    {
      perSystem =
        { pkgs, ... }:
        {
          checks.pentest-bloodhound-vm = pkgs.testers.runNixOSTest {
            name = "pentest-bloodhound";

            nodes.machine = { pkgs, ... }: {
              imports = [
                self.nixosModules.pentest-options
                self.nixosModules.pentest-bloodhound
              ];
              daemon.pentest = {
                enable = true;
                bloodhound.enable = true;
              };
              virtualisation.memorySize = 4096; # neo4j is a JVM
              virtualisation.diskSize = 4096;
              _module.args.user = "daemonsec";
              users.users.daemonsec = {
                isNormalUser = true;
                extraGroups = [ "wheel" ];
              };
            };

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

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

              # neo4j must NOT be running at boot: that is the point of
              # holding its wantedBy empty — it is a JVM wanting a gigabyte.
              machine.fail("systemctl is-active neo4j.service")
              machine.fail("systemctl is-active bloodhound-ce.service")

              # One command brings up both databases and the API, as the user,
              # with no password.
              machine.succeed(as_user("bloodhound ce"), timeout=300)
              machine.wait_for_unit("neo4j.service")
              machine.wait_for_unit("postgresql.service")
              machine.wait_for_unit("bloodhound-ce.service")

              # neo4j answers, and refuses a query without its password.
              machine.wait_for_open_port(7474)
              machine.succeed("curl -fsS http://127.0.0.1:7474 >/dev/null")
              q = """-H 'Content-Type: application/json' -d '{"statements":[{"statement":"RETURN 1"}]}' http://127.0.0.1:7474/db/neo4j/tx/commit"""
              code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' {q}").strip()
              assert code == "401", f"neo4j answered an unauthenticated query: {code}"
              machine.succeed(f"curl -fsS -u neo4j:$(cat /var/lib/bloodhound/neo4j.pw) {q} >/dev/null")

              # postgres no longer trusts any local process as the bloodhound role.
              machine.fail(as_user("psql -w -h 127.0.0.1 -U bloodhound -d bloodhound -c 'select 1'"))

              # Nothing BloodHound runs listens beyond loopback (metrics included).
              machine.fail(r"ss -tlnH | awk '{print $4}' | grep -E '^(0\.0\.0\.0|\*|\[::\]):(2112|7474|7687|8080|5432)$'")

              # The CE API serves its login page — this is what was previously
              # only asserted in a comment.
              machine.wait_for_open_port(8080)
              machine.succeed("curl -fsS http://127.0.0.1:8080/ui/login >/dev/null")

              # The generated config and credentials exist and are not world
              # readable, and `bloodhound creds` can read them back.
              machine.succeed("test -s /var/lib/bloodhound/bhapi.json")
              machine.succeed("test \"$(stat -c %a /var/lib/bloodhound/bhapi.json)\" = 600")
              machine.succeed(as_user("bloodhound creds") + " | grep '^user: admin'")
              machine.succeed(as_user("bloodhound creds") + " | grep -E '^pass: .+'")
              machine.succeed(as_user("bloodhound creds") + " | grep -E '^neo4j .*: neo4j / [0-9a-f]{48}$'")

              # The database BloodHound expects exists and it owns it.
              machine.succeed(
                  "sudo -u postgres psql -tAc "
                  "\"select 1 from pg_database where datname='bloodhound'\" | grep -q 1"
              )

              machine.succeed(as_user("bloodhound status") + " | grep 'CE UI'")

              # Down stops all three.
              machine.succeed(as_user("bloodhound down"))
              machine.fail("systemctl is-active bloodhound-ce.service")
              machine.fail("systemctl is-active neo4j.service")

              # The passwordless grant is scoped to these units only.
              machine.fail(as_user("sudo -n /run/current-system/sw/bin/systemctl start sshd.service"))
            '';
          };
        };
    }
  ];
}