fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonMerge PR #421575790441

master
10.3 KiB345 linesraw
1{ config, options, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.services.gpg-agent;
8  gpgPkg = config.programs.gpg.package;
9
10  homedir = config.programs.gpg.homedir;
11
12  gpgSshSupportStr = ''
13    ${gpgPkg}/bin/gpg-connect-agent updatestartuptty /bye > /dev/null
14  '';
15
16  gpgInitStr = ''
17    GPG_TTY="$(tty)"
18    export GPG_TTY
19  '' + optionalString cfg.enableSshSupport gpgSshSupportStr;
20
21  gpgFishInitStr = ''
22    set -gx GPG_TTY (tty)
23  '' + optionalString cfg.enableSshSupport gpgSshSupportStr;
24
25  # mimic `gpgconf` output for use in `systemd` unit definitions.
26  # we cannot use `gpgconf` directly because it heavily depends on system
27  # state, but we need the values at build time. original:
28  # https://github.com/gpg/gnupg/blob/c6702d77d936b3e9d91b34d8fdee9599ab94ee1b/common/homedir.c#L672-L681
29  gpgconf = dir:
30    let
31      hash =
32        substring 0 24 (hexStringToBase32 (builtins.hashString "sha1" homedir));
33    in if homedir == options.programs.gpg.homedir.default then
34      "%t/gnupg/${dir}"
35    else
36      "%t/gnupg/d.${hash}/${dir}";
37
38  # Act like `xxd -r -p | base32` but with z-base-32 alphabet and no trailing padding.
39  # Written in Nix for purity.
40  hexStringToBase32 = let
41    mod = a: b: a - a / b * b;
42    pow2 = elemAt [ 1 2 4 8 16 32 64 128 256 ];
43    splitChars = s: init (tail (splitString "" s));
44
45    base32Alphabet = splitChars "ybndrfg8ejkmcpqxot1uwisza345h769";
46    hexToIntTable = listToAttrs (genList (x: {
47      name = toLower (toHexString x);
48      value = x;
49    }) 16);
50
51    initState = {
52      ret = "";
53      buf = 0;
54      bufBits = 0;
55    };
56    go = { ret, buf, bufBits }:
57      hex:
58      let
59        buf' = buf * pow2 4 + hexToIntTable.${hex};
60        bufBits' = bufBits + 4;
61        extraBits = bufBits' - 5;
62      in if bufBits >= 5 then {
63        ret = ret + elemAt base32Alphabet (buf' / pow2 extraBits);
64        buf = mod buf' (pow2 extraBits);
65        bufBits = bufBits' - 5;
66      } else {
67        ret = ret;
68        buf = buf';
69        bufBits = bufBits';
70      };
71  in hexString: (foldl' go initState (splitChars hexString)).ret;
72
73in {
74  meta.maintainers = [ maintainers.rycee ];
75
76  options = {
77    services.gpg-agent = {
78      enable = mkEnableOption "GnuPG private key agent";
79
80      defaultCacheTtl = mkOption {
81        type = types.nullOr types.int;
82        default = null;
83        description = ''
84          Set the time a cache entry is valid to the given number of
85          seconds.
86        '';
87      };
88
89      defaultCacheTtlSsh = mkOption {
90        type = types.nullOr types.int;
91        default = null;
92        description = ''
93          Set the time a cache entry used for SSH keys is valid to the
94          given number of seconds.
95        '';
96      };
97
98      maxCacheTtl = mkOption {
99        type = types.nullOr types.int;
100        default = null;
101        description = ''
102          Set the maximum time a cache entry is valid to n seconds. After this
103          time a cache entry will be expired even if it has been accessed
104          recently or has been set using gpg-preset-passphrase. The default is
105          2 hours (7200 seconds).
106        '';
107      };
108
109      maxCacheTtlSsh = mkOption {
110        type = types.nullOr types.int;
111        default = null;
112        description = ''
113          Set the maximum time a cache entry used for SSH keys is valid to n
114          seconds. After this time a cache entry will be expired even if it has
115          been accessed recently or has been set using gpg-preset-passphrase.
116          The default is 2 hours (7200 seconds).
117        '';
118      };
119
120      enableSshSupport = mkOption {
121        type = types.bool;
122        default = false;
123        description = ''
124          Whether to use the GnuPG key agent for SSH keys.
125        '';
126      };
127
128      sshKeys = mkOption {
129        type = types.nullOr (types.listOf types.str);
130        default = null;
131        description = ''
132          Which GPG keys (by keygrip) to expose as SSH keys.
133        '';
134      };
135
136      enableExtraSocket = mkOption {
137        type = types.bool;
138        default = false;
139        description = ''
140          Whether to enable extra socket of the GnuPG key agent (useful for GPG
141          Agent forwarding).
142        '';
143      };
144
145      verbose = mkOption {
146        type = types.bool;
147        default = false;
148        description = ''
149          Whether to produce verbose output.
150        '';
151      };
152
153      grabKeyboardAndMouse = mkOption {
154        type = types.bool;
155        default = true;
156        description = ''
157          Tell the pinentry to grab the keyboard and mouse. This
158          option should in general be used to avoid X-sniffing
159          attacks. When disabled, this option passes
160          {option}`no-grab` setting to gpg-agent.
161        '';
162      };
163
164      enableScDaemon = mkOption {
165        type = types.bool;
166        default = true;
167        description = ''
168          Make use of the scdaemon tool. This option has the effect of
169          enabling the ability to do smartcard operations. When
170          disabled, this option passes
171          {option}`disable-scdaemon` setting to gpg-agent.
172        '';
173      };
174
175      extraConfig = mkOption {
176        type = types.lines;
177        default = "";
178        example = ''
179          allow-emacs-pinentry
180          allow-loopback-pinentry
181        '';
182        description = ''
183          Extra configuration lines to append to the gpg-agent
184          configuration file.
185        '';
186      };
187
188      pinentryFlavor = mkOption {
189        type = types.nullOr (types.enum pkgs.pinentry.flavors);
190        example = "gnome3";
191        default = "gtk2";
192        description = ''
193          Which pinentry interface to use. If not
194          `null`, it sets
195          {option}`pinentry-program` in
196          {file}`gpg-agent.conf`. Beware that
197          `pinentry-gnome3` may not work on non-Gnome
198          systems. You can fix it by adding the following to your
199          system configuration:
200          ```nix
201          services.dbus.packages = [ pkgs.gcr ];
202          ```
203          For this reason, the default is `gtk2` for
204          now.
205        '';
206      };
207
208      enableBashIntegration = mkEnableOption "Bash integration" // {
209        default = true;
210      };
211
212      enableZshIntegration = mkEnableOption "Zsh integration" // {
213        default = true;
214      };
215
216      enableFishIntegration = mkEnableOption "Fish integration" // {
217        default = true;
218      };
219    };
220  };
221
222  config = mkIf cfg.enable (mkMerge [
223    {
224      home.file."${homedir}/gpg-agent.conf".text = concatStringsSep "\n"
225        (optional (cfg.enableSshSupport) "enable-ssh-support"
226          ++ optional cfg.grabKeyboardAndMouse "grab"
227          ++ optional (!cfg.enableScDaemon) "disable-scdaemon"
228          ++ optional (cfg.defaultCacheTtl != null)
229          "default-cache-ttl ${toString cfg.defaultCacheTtl}"
230          ++ optional (cfg.defaultCacheTtlSsh != null)
231          "default-cache-ttl-ssh ${toString cfg.defaultCacheTtlSsh}"
232          ++ optional (cfg.maxCacheTtl != null)
233          "max-cache-ttl ${toString cfg.maxCacheTtl}"
234          ++ optional (cfg.maxCacheTtlSsh != null)
235          "max-cache-ttl-ssh ${toString cfg.maxCacheTtlSsh}"
236          ++ optional (cfg.pinentryFlavor != null)
237          "pinentry-program ${pkgs.pinentry.${cfg.pinentryFlavor}}/bin/pinentry"
238          ++ [ cfg.extraConfig ]);
239
240      home.sessionVariablesExtra = optionalString cfg.enableSshSupport ''
241        if [[ -z "$SSH_AUTH_SOCK" ]]; then
242          export SSH_AUTH_SOCK="$(${gpgPkg}/bin/gpgconf --list-dirs agent-ssh-socket)"
243        fi
244      '';
245
246      programs.bash.initExtra = mkIf cfg.enableBashIntegration gpgInitStr;
247      programs.zsh.initExtra = mkIf cfg.enableZshIntegration gpgInitStr;
248      programs.fish.interactiveShellInit =
249        mkIf cfg.enableFishIntegration gpgFishInitStr;
250    }
251
252    (mkIf (cfg.sshKeys != null) {
253      # Trailing newlines are important
254      home.file."${homedir}/sshcontrol".text = concatMapStrings (s: ''
255        ${s}
256      '') cfg.sshKeys;
257    })
258
259    # The systemd units below are direct translations of the
260    # descriptions in the
261    #
262    #   ${gpgPkg}/share/doc/gnupg/examples/systemd-user
263    #
264    # directory.
265    {
266      assertions = [
267        (hm.assertions.assertPlatform "services.gpg-agent" pkgs platforms.linux)
268      ];
269
270      systemd.user.services.gpg-agent = {
271        Unit = {
272          Description = "GnuPG cryptographic agent and passphrase cache";
273          Documentation = "man:gpg-agent(1)";
274          Requires = "gpg-agent.socket";
275          After = "gpg-agent.socket";
276          # This is a socket-activated service:
277          RefuseManualStart = true;
278        };
279
280        Service = {
281          ExecStart = "${gpgPkg}/bin/gpg-agent --supervised"
282            + optionalString cfg.verbose " --verbose";
283          ExecReload = "${gpgPkg}/bin/gpgconf --reload gpg-agent";
284          Environment = [ "GNUPGHOME=${homedir}" ];
285        };
286      };
287
288      systemd.user.sockets.gpg-agent = {
289        Unit = {
290          Description = "GnuPG cryptographic agent and passphrase cache";
291          Documentation = "man:gpg-agent(1)";
292        };
293
294        Socket = {
295          ListenStream = gpgconf "S.gpg-agent";
296          FileDescriptorName = "std";
297          SocketMode = "0600";
298          DirectoryMode = "0700";
299        };
300
301        Install = { WantedBy = [ "sockets.target" ]; };
302      };
303    }
304
305    (mkIf cfg.enableSshSupport {
306      systemd.user.sockets.gpg-agent-ssh = {
307        Unit = {
308          Description = "GnuPG cryptographic agent (ssh-agent emulation)";
309          Documentation =
310            "man:gpg-agent(1) man:ssh-add(1) man:ssh-agent(1) man:ssh(1)";
311        };
312
313        Socket = {
314          ListenStream = gpgconf "S.gpg-agent.ssh";
315          FileDescriptorName = "ssh";
316          Service = "gpg-agent.service";
317          SocketMode = "0600";
318          DirectoryMode = "0700";
319        };
320
321        Install = { WantedBy = [ "sockets.target" ]; };
322      };
323    })
324
325    (mkIf cfg.enableExtraSocket {
326      systemd.user.sockets.gpg-agent-extra = {
327        Unit = {
328          Description =
329            "GnuPG cryptographic agent and passphrase cache (restricted)";
330          Documentation = "man:gpg-agent(1) man:ssh(1)";
331        };
332
333        Socket = {
334          ListenStream = gpgconf "S.gpg-agent.extra";
335          FileDescriptorName = "extra";
336          Service = "gpg-agent.service";
337          SocketMode = "0600";
338          DirectoryMode = "0700";
339        };
340
341        Install = { WantedBy = [ "sockets.target" ]; };
342      };
343    })
344  ]);
345}