Search code examples
sshgnupgnixos

How to set up SSH keyphrase caching with GnuPG Agent in NixOS?


I'm using NixOS (unstable channel, at the moment) remotely, via SSH, so no graphical environment. I often push and pull Git repositories, and re-typing the passphrase for SSH keys gets old quick, so I'm trying to set up an agent to cache the passphrase.

With the latest releases, using GnuPG Agent with SSH support seems to be the recommended choice. I enabled the agent by uncommenting the following lines in configuration.nix:

  programs.gnupg.agent = {
    enable = true;
    enableSSHSupport = true;
    pinentryFlavor = "gnome3";
  };

Does the choice of pinentryFlavor matter here? I'm imagining that SSH asks the keys by its own prompt, and caches them using the agent, but a confirmation would be nice. As I said, I'm not using graphical interface.

The main question: it doesn't seem work by just by enabling agent from the configuration.nix. Something else clearly needs to be done, but I'm unable to find any documentation about how to properly enable the agent in NixOS.


Solution

  • The global configuration.nix sets up configuration at /etc/bashrc to call gpg-connect-agent when bash is started and /etc/set-environment to set the SSH_AUTH_SOCK environment variable. It also adds systemwide per-user systemd units at /etc/systemd/user/gpg-agent* that run per-user GnuPG key agents.

    Finally, you must be sure to add the key to the agent using the ssh-add command; it isn't added automatically when SSH prompts the key passphrase.

    This should be enough to make GnuPG agent work with SSH. The choice of pinentryFlavor shouldn't also have effect when used over terminal. Turns out you should set pinentryFlavor to curses when using over terminal. If you don't do that, the agent throws an error when re-authenticating.

    (I'm not sure why I encountered various error conditions when I first enabled GnupPG. It works now with the default settings. It's possible that the systemd service wasn't properly started.)