repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
gpg.nixNix183 lines8.1 KiBraw download
# modules/home/gpg.nix — the GPG main key and gpg.conf, from the flake.
#
#   public key   modules/home/gpg/daemon-main.pub.asc → imported with ultimate trust (programs.gpg.publicKeys)
#   secret key   sops secret gpg_main_secret (the armored export, still under its own passphrase):
#                imported into the keyring on activation if the keyring lacks it
#   gpg.conf     programs.gpg.settings (the gpg-cheat `setup` defaults)
#
# The agent itself is NixOS's (programs.gnupg.agent, pinentry-gnome3), so
# services.gpg-agent is deliberately not enabled here.
#
# Stale keyring locks: this keyring is in use-keyboxd mode, so public keys live in
# public-keys.d/pubring.db behind the keyboxd daemon. keyboxd has no --supervised
# mode, so it is not a systemd unit like the agent is, and at logout it is
# SIGKILLed along with the user slice (Linger=no, so /run/user/$UID goes away).
# Killed mid-write it leaves a truncated dotlock, and gpg refuses to break a lock
# it cannot parse: every later run then fails with
#   gpg: keydb_search failed: Invalid argument
# which surfaces as "Signing error / GPG failed with exit status: 2" from git and
# jj. Three layers keep that from recurring: gpg-unstick reaps provably unheld
# locks, gnupg-unstick.service sweeps at login and stops keyboxd politely at
# logout, and gpg-guard sweeps inline so a signature cannot hit a stale lock.
# A live lock holder is the other failure: the boot-time activation's keyboxd,
# left on a homedir socket; gpgStopBootDaemons (below) stops it.
# Key: RSA 4096, 2025-12-30, the one on GitLab; fingerprint in modules/hosts/laptop/_identity.nix.
{ ... }:
{
  flake.homeModules.gpg =
  { config, pkgs, lib, identity, ... }:
  let
    fpr = identity.gpgFingerprint;

    # Reaps GnuPG dotlocks that are provably not held -- the holder is dead, or
    # the lock file is unparseable because its writer was killed mid-write. A
    # lock held by a live local process, or claimed by another host, is left
    # alone. Diagnostics go to stderr only, so this is safe to run inline ahead
    # of a gpg whose stdout carries a signature.
    gpg-unstick = pkgs.writeShellScriptBin "gpg-unstick" ''
      set -uo pipefail
      export PATH=${lib.makeBinPath [ pkgs.coreutils ]}

      quiet=0
      [ "''${1-}" = "--quiet" ] || [ "''${1-}" = "-q" ] && quiet=1

      home=''${GNUPGHOME:-$HOME/.gnupg}
      node=$(uname -n)
      removed=0

      say()   { [ "$quiet" -eq 1 ] || printf 'gpg-unstick: %s\n' "$1" >&2; }
      warn()  { printf 'gpg-unstick: %s\n' "$1" >&2; }
      alive() { [ -d "/proc/$1" ]; }

      for dir in "$home" "$home"/public-keys.d "$home"/private-keys-v1.d; do
        [ -d "$dir" ] || continue

        # Named locks: judge by the holder recorded in the backing file.
        for lock in "$dir"/*.lock; do
          [ -e "$lock" ] || continue
          lpid=""; lnode=""
          { read -r lpid || true; read -r lnode || true; } < "$lock"
          lpid=''${lpid//[^0-9]/}

          if [ -n "$lpid" ] && [ "$lnode" = "$node" ] && alive "$lpid"; then
            continue                                   # genuinely held
          fi
          if [ -n "$lpid" ] && [ -n "$lnode" ] && [ "$lnode" != "$node" ]; then
            warn "''${lock#"$home"/} is claimed by another host ($lnode); leaving it"
            continue
          fi
          if rm -f -- "$lock"; then
            removed=$((removed + 1))
            say "removed stale ''${lock#"$home"/} (''${lpid:+holder $lpid is dead}''${lpid:-unparseable lock file})"
          fi
        done

        # Backing files whose hardlink is already gone are orphans of past crashes.
        for lk in "$dir"/.\#lk*; do
          [ -e "$lk" ] || continue
          links=$(stat -c %h -- "$lk" 2>/dev/null) || continue
          [ "$links" -gt 1 ] && continue               # still linked: handled above
          if rm -f -- "$lk"; then
            removed=$((removed + 1))
            say "removed orphaned ''${lk#"$home"/}"
          fi
        done
      done

      [ "$removed" -eq 0 ] && say "no stale locks in $home"
      exit 0
    '';

    # The gpg that git and jj call: sweep first, then hand over to the real gpg
    # with the arguments untouched. Pre-flighting rather than retrying keeps
    # stdin streaming straight through to gpg, so the signing path is unchanged.
    gpg-guard = pkgs.writeShellScriptBin "gpg-guard" ''
      ${gpg-unstick}/bin/gpg-unstick --quiet || true
      exec ${pkgs.gnupg}/bin/gpg "$@"
    '';
  in
  {
    sops.secrets.gpg_main_secret = { };

    home.packages = [ gpg-unstick gpg-guard ];

    # git signs through the guard so a stale lock cannot reach a commit. This has
    # to be signing.signer rather than settings.gpg.program: with format=openpgp
    # git reads gpg.openpgp.program first, and that is the one signer feeds.
    # jj is pointed at the guard by name in ~/.config/jj/config.toml, which is
    # not managed from here.
    programs.git.signing.signer = "${gpg-guard}/bin/gpg-guard";

    # Sweep once at login, and at logout stop keyboxd while systemd can still do
    # it politely -- a SIGTERMed keyboxd releases its lock, a SIGKILLed one does
    # not. RemainAfterExit is what gives the unit a stop phase to hang ExecStop on.
    systemd.user.services.gnupg-unstick = {
      Unit = {
        Description = "Reap stale GnuPG keyring locks";
        Documentation = "man:gpg(1)";
      };
      Service = {
        Type = "oneshot";
        RemainAfterExit = true;
        ExecStart = "${gpg-unstick}/bin/gpg-unstick";
        ExecStop = [
          "-${pkgs.gnupg}/bin/gpgconf --kill keyboxd"
          "${gpg-unstick}/bin/gpg-unstick"
        ];
      };
      Install.WantedBy = [ "default.target" ];
    };

    programs.gpg = {
      enable = true;
      mutableKeys = true; # other people's keys and new subkeys stay editable
      mutableTrust = true;
      publicKeys = [
        { source = ./gpg/daemon-main.pub.asc; trust = 5; }
      ];
      settings = {
        default-key = fpr;
        default-recipient-self = true;
        keyid-format = "0xlong";
        with-fingerprint = true;
        with-subkey-fingerprints = true;
        personal-cipher-preferences = "AES256 AES192 AES";
        personal-digest-preferences = "SHA512 SHA384 SHA256";
        cert-digest-algo = "SHA512";
        no-emit-version = true;
        no-comments = true;
        keyserver = "hkps://keys.openpgp.org";
        auto-key-locate = "local,wkd";
        trust-model = "tofu+pgp";
      };
    };

    # Import the secret key once (idempotent: skipped when the keyring has it).
    # Runs after sops-nix has decrypted the secrets.
    home.activation.gpgMainKey = lib.hm.dag.entryAfter [ "sops-nix" ] ''
      if [ -r "${config.sops.secrets.gpg_main_secret.path}" ] \
         && ! ${pkgs.gnupg}/bin/gpg --batch --list-secret-keys ${fpr} >/dev/null 2>&1; then
        run ${pkgs.gnupg}/bin/gpg --batch --quiet --import "${config.sops.secrets.gpg_main_secret.path}" \
          && echo "gpg: imported the main secret key ${fpr}"
      fi
    '';

    # At boot, home-manager activates before login, so /run/user/$UID does not
    # exist yet and the gpg calls above start keyboxd and gpg-agent with their
    # sockets in the homedir. Those daemons outlive activation, and keyboxd keeps
    # pubring.db locked. After login gpg looks in /run/user/$UID/gnupg, starts a
    # second keyboxd that waits on that lock, and every signature (so every jj
    # command) times out: "database_open … waiting for lock (held by <pid>)".
    # gpg-unstick cannot help, since the holder is alive. Stop them here, only when
    # the socket dir is the homedir, so a switch from a live session (sockets in
    # /run/user) leaves the running agent and its cached passphrase alone.
    home.activation.gpgStopBootDaemons = lib.hm.dag.entryAfter [ "gpgMainKey" "importGpgKeys" ] ''
      gnupghome="${config.programs.gpg.homedir}"
      if [ "$(${pkgs.gnupg}/bin/gpgconf --homedir "$gnupghome" --list-dirs socketdir)" = "$gnupghome" ]; then
        run ${pkgs.gnupg}/bin/gpgconf --homedir "$gnupghome" --kill keyboxd || true
        run ${pkgs.gnupg}/bin/gpgconf --homedir "$gnupghome" --kill gpg-agent || true
      fi
    '';
  }
  ;
}