repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
time.nixNix300 lines12.5 KiBraw download
# modules/features/pentest/time.nix — clock skew, on purpose and reversibly.
#
# Kerberos rejects a ticket request when the clock is more than five minutes
# off the KDC, so against an AD box the first fix is usually to match the DC's
# clock. On NixOS that fights the system: systemd-timesyncd is enabled by
# default and will quietly put the clock back.
#
# `htb-time` is the root half (this file); `htbtime` is the user-facing half in
# modules/home/htb.nix, exactly as fan-ec/fan are split in
# modules/hosts/laptop/fan-cli.nix and modules/home/fan.nix.
#
#   htb-time <host>   record what time sync looks like now, turn it off, and
#                     step the clock to <host>
#   htb-time off      put back precisely what was recorded, then resync
#   htb-time status   current offset and whether we are holding a skew
#
# Two things it refuses to do quietly:
#  * leave you wondering why TLS broke. A large skew makes certificates look
#    not-yet-valid or expired, so `nix`, `git` and anything HTTPS start failing.
#    It says so, every time.
#  * leave the clock unmanaged. If the state file is missing or unreadable when
#    `off` runs, it restores the NixOS default (NTP on) rather than doing
#    nothing — and a reboot would do that anyway, so a forgotten `off` cannot
#    strand the machine.
{ lib, self, ... }:
{
  flake.nixosModules.pentest-time =
    { config, pkgs, lib, ... }:
    let
      on = config.daemon.pentest.enable;

      htb-time = pkgs.writeShellScriptBin "htb-time" ''
        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.systemd pkgs.gnugrep pkgs.gawk pkgs.gnused ]}
        [ "$EUID" = 0 ] || { echo "htb-time: run as root (htbtime does that for you)" >&2; exit 1; }

        NTPDATE=${pkgs.ntp}/bin/ntpdate
        SNTP=${pkgs.ntp}/bin/sntp
        CHRONYD=${pkgs.chrony}/bin/chronyd
        DIR=/var/lib/htb-time
        STATE=$DIR/state

        # Units that would fight a manual clock. Only ones that exist are touched.
        UNITS="systemd-timesyncd.service chronyd.service chrony.service ntpd.service"

        unit_exists() { systemctl cat "$1" >/dev/null 2>&1; }
        ntp_enabled() { timedatectl show -p NTP --value 2>/dev/null || echo unknown; }

        save_state() {
          mkdir -p "$DIR"
          {
            echo "ntp=$(ntp_enabled)"
            for u in $UNITS; do
              if unit_exists "$u"; then
                echo "unit=$u:$(systemctl is-active "$u" 2>/dev/null || echo inactive)"
              fi
            done
          } > "$STATE"
        }

        stop_competitors() {
          for u in $UNITS; do
            if unit_exists "$u" && systemctl is-active --quiet "$u" 2>/dev/null; then
              echo "  stopping $u"
              systemctl stop "$u" || true
            fi
          done
          timedatectl set-ntp false 2>/dev/null || true
        }

        warn_tls() {
          cat >&2 <<'EOF'

        htb-time: the clock is now deliberately wrong for this machine.
          TLS certificate validation compares against it, so `nix`, `git`, curl
          and anything else over HTTPS may start failing while this is held.
          Put it back with:  htbtime off
        EOF
        }

        offset_against() { # best-effort, read-only
          $SNTP "$1" 2>/dev/null | ${pkgs.gnugrep}/bin/grep -oE '^[+-][0-9]+\.[0-9]+' | head -1
        }

        case "''${1:-status}" in
          off)
            if [ ! -r "$STATE" ]; then
              # Review Focus #3: never leave the clock unmanaged.
              echo "htb-time: no saved state at $STATE (nothing to restore, or it was lost)." >&2
              echo "htb-time: restoring the NixOS default instead: NTP on." >&2
              timedatectl set-ntp true 2>/dev/null || true
              unit_exists systemd-timesyncd.service && systemctl start systemd-timesyncd.service || true
              echo "htb-time: NTP enabled, clock is managed again."
              exit 0
            fi

            want_ntp=$(${pkgs.gnugrep}/bin/grep -m1 '^ntp=' "$STATE" | cut -d= -f2)
            if [ "$want_ntp" = "yes" ] || [ -z "''${want_ntp:-}" ] || [ "$want_ntp" = "unknown" ]; then
              timedatectl set-ntp true 2>/dev/null || true
            else
              timedatectl set-ntp false 2>/dev/null || true
            fi

            ${pkgs.gnugrep}/bin/grep '^unit=' "$STATE" 2>/dev/null | sed 's/^unit=//' | while IFS=: read -r u st; do
              if [ "$st" = "active" ]; then
                unit_exists "$u" && systemctl start "$u" 2>/dev/null || true
              fi
            done

            rm -f "$STATE"
            echo "htb-time: restored (NTP=$(ntp_enabled)); the clock is managed again."
            exit 0
            ;;

          status)
            if [ -r "$STATE" ]; then
              echo "htb-time: HOLDING a manual skew (state $STATE)"
              sed 's/^/  /' "$STATE"
              echo "  release with: htbtime off"
            else
              echo "htb-time: not holding a skew"
            fi
            echo "  NTP=$(ntp_enabled)  now=$(date -Is)"
            # Explicit: a consumer like `htb-time status | grep -q x` exits as
            # soon as it matches, so the last echo takes EPIPE and would
            # otherwise become this script's exit status.
            exit 0
            ;;

          -h|--help)
            echo "usage: htb-time <host> | off | status"
            ;;

          *)
            target="$1"
            # Root ntpdate takes options (`-k <file>`), and chronyd -q parses
            # the target into a directive, so only a plain host name, IPv4 or
            # IPv6 address gets through: no leading '-', no spaces.
            if ! [[ "$target" =~ ^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$ ]]; then
              echo "htb-time: bad host: $target (a host name or IP address)" >&2
              exit 2
            fi
            echo "htb-time: syncing this machine's clock to $target"
            [ -r "$STATE" ] || save_state
            stop_competitors

            if $NTPDATE -u "$target" 2>&1 | sed 's/^/  ntpdate: /'; then
              echo "htb-time: clock stepped to $target (now $(date -Is))"
              warn_tls
              exit 0
            fi

            echo "  ntpdate failed; trying chronyd -q" >&2
            if $CHRONYD -q "server $target iburst maxdelay 10" 2>&1 | sed 's/^/  chronyd: /'; then
              echo "htb-time: clock stepped to $target (now $(date -Is))"
              warn_tls
              exit 0
            fi

            # Deliberately leaves NTP off (spec C6: do not silently half-apply),
            # but says so loudly and names the way back.
            echo "htb-time: could not get the time from $target." >&2
            echo "htb-time: NTP is still DISABLED and the state is saved." >&2
            echo "htb-time: either retry, or run 'htbtime off' to put sync back." >&2
            exit 1
            ;;
        esac
      '';
    in
    {
      config = lib.mkIf on {
        environment.systemPackages = [ htb-time pkgs.ntp pkgs.chrony ];
        systemd.tmpfiles.rules = [ "d /var/lib/htb-time 0755 root root - -" ];

        # Same shape as fan-cli.nix: one fixed store script, wheel only.
        security.sudo.extraRules = [
          {
            groups = [ "wheel" ];
            commands = [
              { command = "/run/current-system/sw/bin/htb-time"; options = [ "NOPASSWD" ]; }
            ];
          }
        ];
      };
    };

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

        nodes = {
          # Stands in for the DC whose clock we chase. chrony rather than
          # ntpd: ntpd with a local-clock fudge needs minutes before it will
          # answer as authoritative, so ntpdate finds "no server suitable" and
          # the test hangs. chrony's `local stratum 10` serves immediately.
          dc = {
            services.chrony = {
              enable = true;
              extraConfig = ''
                # `local stratum 10` makes chronyd answer as synchronised even
                # though this node has no upstream source, which is the whole
                # point of a stand-in DC. Without it ntpdate reports "no server
                # suitable for synchronization". NOT `orphan`: that only
                # activates once every other source is unreachable, which left
                # the server silent.
                local stratum 10
                allow all
              '';
            };
            networking.firewall.allowedUDPPorts = [ 123 ];
          };

          machine = { lib, ... }: {
            imports = [
              self.nixosModules.pentest-options
              self.nixosModules.pentest-time
            ];
            daemon.pentest.enable = true;
            # The test driver leaves time sync off, which would make the
            # baseline NTP=no and the round-trip assertion vacuous. The real
            # machine has timesyncd on, so say so explicitly: that is the
            # state htb-time has to record and put back.
            # mkForce: the NixOS test driver switches time sync OFF for its
            # nodes, which is exactly the state this test must not start from.
            services.timesyncd.enable = lib.mkForce true;
            _module.args.user = "daemonsec";
            users.users.daemonsec = {
              isNormalUser = true;
              extraGroups = [ "wheel" ];
            };
          };
        };

        testScript = ''
          start_all()
          dc.wait_for_unit("chronyd.service")
          machine.wait_for_unit("multi-user.target")

          # Do not proceed until the DC will actually answer, otherwise a
          # failure here is indistinguishable from a bug in htb-time.
          machine.wait_until_succeeds(
              "${pkgs.ntp}/bin/sntp -t 2 dc >/dev/null 2>&1 "
              "|| ${pkgs.ntp}/bin/ntpdate -q -t 2 dc >/dev/null 2>&1",
              timeout=120,
          )

          # Baseline: NixOS manages the clock.
          machine.wait_for_unit("systemd-timesyncd.service")
          before = machine.succeed("timedatectl show -p NTP --value").strip()
          assert before == "yes", f"expected NTP managed at boot, got {before!r}"
          machine.succeed("htb-time status | grep -q 'not holding a skew'")

          # Hold a skew against the DC.
          machine.succeed("htb-time dc")
          machine.succeed("test -r /var/lib/htb-time/state")
          held = machine.succeed("timedatectl show -p NTP --value").strip()
          assert held == "no", f"NTP should be off while holding a skew, got {held!r}"
          machine.fail("systemctl is-active systemd-timesyncd.service")
          machine.succeed("htb-time status | grep -q HOLDING")

          # Release: must match the baseline exactly, and clear the state.
          machine.succeed("htb-time off")
          after = machine.succeed("timedatectl show -p NTP --value").strip()
          assert after == before, f"off must restore NTP={before!r}, got {after!r}"
          machine.fail("test -e /var/lib/htb-time/state")

          # Review Focus #3: `off` with the state file gone must still leave the
          # clock managed, and must not fail.
          machine.succeed("htb-time dc")
          machine.succeed("rm -f /var/lib/htb-time/state")
          out = machine.succeed("htb-time off 2>&1")
          assert "NTP on" in out or "managed again" in out, out
          recovered = machine.succeed("timedatectl show -p NTP --value").strip()
          assert recovered == "yes", f"expected NTP restored to yes, got {recovered!r}"

          # An unreachable host fails loudly, keeps the state, and names the way back.
          machine.succeed("htb-time off || true")
          err = machine.fail("htb-time 192.0.2.123 2>&1")
          assert "htbtime off" in err, err
          machine.succeed("test -r /var/lib/htb-time/state")
          machine.succeed("htb-time off")

          # The user half needs no password.
          machine.succeed("su -l daemonsec -c 'sudo -n htb-time status'")

          # ...but the target must be a host, not options for root ntpdate or
          # a chronyd directive, and must not save state or stop NTP.
          for bad in ["-k/etc/shadow", "'dc maxdelay 1'", "'dc;id'"]:
              err = machine.fail(f"su -l daemonsec -c \"sudo -n htb-time {bad}\" 2>&1")
              assert "bad host" in err, err
          machine.fail("test -e /var/lib/htb-time/state")
        '';
      };
    };
}