]> Git — Sourcephile - sourcephile-nix.git/blob - shell/modules/tools/security/gnupg.nix
nix: fix nixpkgs-channel and gpg-agent
[sourcephile-nix.git] / shell / modules / tools / security / gnupg.nix
1 { pkgs, lib, config, ... }:
2 let
3 inherit (lib) types;
4 inherit (config) gnupg;
5 unlines = builtins.concatStringsSep "\n";
6 unwords = builtins.concatStringsSep " ";
7
8 generateKeys = keys: unlines (lib.mapAttrsToList generateKey keys);
9 generateKey =
10 uid:
11 { uid ? uid
12 , algo ? "future-default"
13 , usage ? ["default"]
14 , expire ? "-"
15 , passPath
16 , subKeys ? {}
17 , ...
18 }@primary:
19 ''
20 info "generateKey uid=\"${uid}\""
21 if ! ${gpg-with-home}/bin/gpg-with-home --list-secret-keys -- "=${uid}" >/dev/null 2>/dev/null
22 then
23 ${pkgs.pass}/bin/pass "${passPath}" |
24 ${gpg-with-home}/bin/gpg-with-home \
25 --batch --pinentry-mode loopback --passphrase-fd 0 \
26 --quick-generate-key "${uid}" "${algo}" "${unwords usage}" "${expire}"
27 fi
28 ${head1}
29 fpr=$(${gpg-fingerprint}/bin/gpg-fingerprint -- "=${uid}" | head1)
30 caps=$(${gpg-with-home}/bin/gpg-with-home \
31 --with-colons --fixed-list-mode --with-fingerprint \
32 --list-secret-keys -- "=${uid}" |
33 ${pkgs.gnugrep}/bin/grep '^ssb:' |
34 ${pkgs.coreutils}/bin/cut -d : -f 12 || true)
35 ''
36 + unlines (map (generateSubKey primary) subKeys)
37 + generateBackupKey "$fpr" primary
38 ;
39 generateSubKey =
40 primary:
41 { expire ? primary.expire
42 , algo ? primary.algo
43 , usage
44 , ...
45 }:
46 ''
47 info " generateSubKey usage=[${unwords usage}]"
48 if ! printf '%s\n' "$caps" | ${pkgs.gnugrep}/bin/grep -Fqx "${lettersKeyUsage usage}"
49 then
50 ${pkgs.pass}/bin/pass "${primary.passPath}" |
51 ${gpg-with-home}/bin/gpg-with-home \
52 --batch --pinentry-mode loopback --passphrase-fd 0 \
53 --quick-add-key "$fpr" "${algo}" "${unwords usage}" "${expire}"
54 fi
55 '';
56 generateBackupKey =
57 fpr:
58 { passPath
59 , backupRecipients ? []
60 , uid
61 , ...
62 }:
63 lib.optionalString (backupRecipients != [])
64 ''
65 info " generateBackupKey backupRecipients=[${unwords (map (s: "\\\"${s}\\\"") backupRecipients)}]"
66 mkdir -p "${gnupg.gnupgHome}/backup/${uid}/"
67 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.pubkey.asc"
68 then
69 ${gpg-with-home}/bin/gpg-with-home \
70 --batch \
71 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.pubkey.asc" \
72 --export-options export-backup \
73 --export "${fpr}"
74 fi
75 '' + (if backupRecipients == [""] then
76 ''
77 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.revoke.asc"
78 then
79 ${pkgs.pass}/bin/pass "${passPath}" |
80 ${gpg-with-home}/bin/gpg-with-home \
81 --pinentry-mode loopback --passphrase-fd 0 \
82 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.revoke.asc" \
83 --gen-revoke "${fpr}"
84 fi
85 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.privkey.sec"
86 then
87 ${pkgs.pass}/bin/pass "${passPath}" |
88 ${gpg-with-home}/bin/gpg-with-home \
89 --batch --pinentry-mode loopback --passphrase-fd 0 \
90 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.privkey.sec" \
91 --export-options export-backup \
92 --export-secret-key "${fpr}"
93 fi
94 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.subkeys.sec"
95 then
96 ${pkgs.pass}/bin/pass "${passPath}" |
97 ${gpg-with-home}/bin/gpg-with-home \
98 --batch --pinentry-mode loopback --passphrase-fd 0 \
99 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.subkeys.sec" \
100 --export-options export-backup \
101 --export-secret-subkeys "${fpr}"
102 fi
103 '' else ''
104 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.revoke.asc.gpg"
105 then
106 ${pkgs.pass}/bin/pass "${passPath}" |
107 ${gpg-with-home}/bin/gpg-with-home \
108 --pinentry-mode loopback --passphrase-fd 0 \
109 --armor --gen-revoke "${fpr}" |
110 gpg --encrypt ${recipients backupRecipients} \
111 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.revoke.asc.gpg"
112 fi
113 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.privkey.sec.gpg"
114 then
115 ${pkgs.pass}/bin/pass "${passPath}" |
116 ${gpg-with-home}/bin/gpg-with-home \
117 --batch --pinentry-mode loopback --passphrase-fd 0 \
118 --armor --export-options export-backup \
119 --export-secret-key "${fpr}" |
120 gpg --encrypt ${recipients backupRecipients} \
121 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.privkey.sec.gpg"
122 fi
123 if ! test -s "${gnupg.gnupgHome}/backup/${uid}/${fpr}.subkeys.sec.gpg"
124 then
125 ${pkgs.pass}/bin/pass "${passPath}" |
126 ${gpg-with-home}/bin/gpg-with-home \
127 --batch --pinentry-mode loopback --passphrase-fd 0 \
128 --armor --export-options export-backup \
129 --export-secret-subkeys "${fpr}" |
130 gpg --encrypt ${recipients backupRecipients} \
131 --armor --yes --output "${gnupg.gnupgHome}/backup/${uid}/${fpr}.subkeys.sec.gpg"
132 fi
133 '');
134 recipients = rs: unwords (map (r: ''--recipient "${refKey r}"'') rs);
135 refKey = key: if builtins.typeOf key == "string" then key else "=${key.uid}";
136 signer = s: if s == null
137 then ""
138 else ''--sign --default-key "${refKey s}"'';
139 lettersKeyUsage = usage:
140 (if builtins.elem "encrypt" usage then "e" else "") +
141 (if builtins.elem "sign" usage then "s" else "") +
142 (if builtins.elem "cert" usage then "c" else "") +
143 (if builtins.elem "auth" usage then "a" else "");
144
145 passOfFingerprint = key:
146 # Return shell code
147 # which fills a map from the fingerprints of the given key
148 # to its password file.
149 ''
150 # shell.gnupg.pass.passOfFingerprint
151 for fpr in $(${gpg-fingerprint}/bin/gpg-fingerprint -- "=${key.uid}")
152 do eval "pass_$fpr=\"${key.passPath}\""
153 done
154 '';
155 forgetPass =
156 # Return shell code
157 # which installs an exit and keyboard interruption (^C) trap
158 # removing any pass from gpg-agent
159 # whose keygrip is registered in $keygrips.
160 ''
161 # forgetPass
162 keygrips=
163 forgetPass () {
164 for keygrip in $keygrips
165 do
166 echo >&2 "gpg: forget: keygrip=$keygrip"
167 GNUPGHOME=${gnupg.gnupgHome} \
168 ${pkgs.gnupg}/bin/gpg-connect-agent </dev/null >&2 "CLEAR_PASSPHRASE $keygrip" ||
169 true
170 done
171 keygrips=
172 }
173 trap 'forgetPass' EXIT INT
174 '';
175 presetPass = keys: uid:
176 # Return shell code
177 # which preset the pass of given uid into gpg-agent,
178 # using keys to find where the pass is stored.
179 ''
180 ${unlines (map passOfFingerprint keys)}
181 # presetPass
182 GNUPGHOME=${gnupg.gnupgHome} \
183 ${pkgs.gnupg}/bin/gpgconf --launch gpg-agent
184 ${head1}
185 fpr="$(${gpg-fingerprint}/bin/fingerprint -- "${uid}" | head1)"
186 eval pass="\''${pass_$fpr}"
187 if test -n "$pass"
188 then
189 for keygrip in $(${gnupg.gpg-keygrip}/bin/gpg-keygrip -- "$fpr")
190 do
191 keygrips="$keygrips $keygrip"
192 echo >&2 "gpg: preset: keygrip=$keygrip pass=$pass"
193 ${pkgs.pass}/bin/pass "$pass" |
194 GNUPGHOME=${gnupg.gnupgHome} \
195 ${pkgs.gnupg}/libexec/gpg-preset-passphrase --preset ''${XTRACE:+--verbose} $keygrip
196 done
197 fi
198 '';
199
200 # Initialize the keyring according to gnupg.keys.
201 gpg-init = pkgs.writeShellScriptBin "gpg-init" (''
202 set -eu
203 set -o pipefail
204 ${info}
205 ${pkgs.coreutils}/bin/install -dm0700 -D ${gnupg.gnupgHome}
206 ${pkgs.coreutils}/bin/ln -snf ${gnupg.gpgConf} ${gnupg.gnupgHome}/gpg.conf
207 ${pkgs.coreutils}/bin/ln -snf ${gnupg.gpgAgentConf} ${gnupg.gnupgHome}/gpg-agent.conf
208 ${pkgs.coreutils}/bin/ln -snf ${gnupg.dirmngrConf} ${gnupg.gnupgHome}/dirmngr.conf
209 '' +
210 generateKeys gnupg.keys
211 );
212
213 # A wrapper around gpg to set GNUPGHOME.
214 gpg-with-home = pkgs.writeScriptBin "gpg-with-home" ''
215 GNUPGHOME=${gnupg.gnupgHome} \
216 exec ${pkgs.gnupg}/bin/gpg "$@"
217 '';
218
219 # A wrapper around gpg to get fingerprints.
220 gpg-fingerprint = pkgs.writeScriptBin "gpg-fingerprint" ''
221 set -eu
222 ${gpg-with-home}/bin/gpg-with-home \
223 --with-colons --fixed-list-mode --with-fingerprint --with-subkey-fingerprint \
224 --list-public-keys "$@" |
225 while IFS=: read -r t x x x key x x x x uid x
226 do case $t in
227 (pub|sub|sec|ssb)
228 while IFS=: read -r t x x x x x x x x fpr x
229 do case $t in (fpr) printf '%s\n' "$fpr"; break;;
230 esac done
231 ;;
232 esac done
233 '';
234
235 # A wrapper around gpg to get keygrips.
236 gpg-keygrip = pkgs.writeScriptBin "gpg-keygrip" ''
237 set -eu
238 ${gpg-with-home}/bin/gpg-with-home \
239 --with-colons --fixed-list-mode --with-keygrip \
240 --list-public-keys "$@" |
241 while IFS=: read -r t x x x key x x x x uid x
242 do case $t in
243 (pub|sub|sec|ssb)
244 while IFS=: read -r t x x x x x x x x grp x
245 do case $t in (grp) printf '%s\n' "$grp"; break;;
246 esac done
247 ;;
248 esac done
249 '';
250
251 # A wrapper around gpg to get uids.
252 gpg-uid = pkgs.writeScriptBin "gpg-uid" ''
253 set -eu
254 ${gpg-with-home}/bin/gpg-with-home \
255 --with-colons --fixed-list-mode \
256 --list-public-keys "$@" |
257 while IFS=: read -r t st x x x x x id x uid x
258 do case $t in
259 (uid)
260 case $st in
261 (u) printf '%s\n' "$uid";;
262 esac
263 ;;
264 esac done
265 '';
266
267 head1 = ''
268 head1(){
269 IFS= read -r line
270 cat >/dev/null # NOTE: consuming all the input avoids useless triggering of pipefail
271 printf %s "$line"
272 }
273 '';
274 info = ''
275 info(){
276 echo >&2 "gpg-init: $*"
277 }
278 '';
279 in
280 {
281 options.gnupg = {
282 enable = lib.mkEnableOption "GnuPG shell utilities";
283 gnupgHome = lib.mkOption {
284 type = types.path;
285 default = "sec/gnupg";
286 description = ''
287 '';
288 };
289 keys = lib.mkOption {
290 default = {};
291 example =
292 { "John Doe. <contact@example.coop>" = {
293 algo = "rsa4096";
294 expire = "1y";
295 usage = ["cert" "sign"];
296 passPath = "example.coop/gpg/contact";
297 subKeys = [
298 { algo = "rsa4096"; expire = "1y"; usage = ["sign"];}
299 { algo = "rsa4096"; expire = "1y"; usage = ["encrypt"];}
300 { algo = "rsa4096"; expire = "1y"; usage = ["auth"];}
301 ];
302 backupRecipients = ["@john@doe.pro"];
303 };
304 };
305 type = types.attrsOf (types.submodule ({uid, ...}: {
306 #config.uid = lib.mkDefault uid;
307 options = {
308 uid = lib.mkOption {
309 type = types.str;
310 example = "John Doe <john.doe@example.coop>";
311 default = uid;
312 description = ''
313 User ID.
314 '';
315 };
316 algo = lib.mkOption {
317 type = types.enum [ "rsa4096" ];
318 default = "future-default";
319 example = "rsa4096";
320 description = ''
321 Cryptographic algorithm.
322 '';
323 };
324 expire = lib.mkOption {
325 type = types.str;
326 default = "1y";
327 example = "1y";
328 description = ''
329 Expiration timeout.
330 '';
331 };
332 usage = lib.mkOption {
333 type = with types; listOf (enum [ "cert" "sign" "encrypt" "auth" "default" ]);
334 default = ["default"];
335 example = ["cert" "sign" "encrypt" "auth"];
336 description = ''
337 Cryptographic usage.
338 '';
339 };
340 passPath = lib.mkOption {
341 type = types.str;
342 example = "gnupg/coop/example/contact@";
343 description = ''
344 Password path.
345 '';
346 };
347 subKeys = lib.mkOption {
348 type = types.listOf (types.submodule {
349 options = {
350 algo = lib.mkOption {
351 type = types.enum [ "rsa4096" ];
352 default = "default";
353 example = "rsa4096";
354 description = ''
355 Cryptographic algorithm.
356 '';
357 };
358 expire = lib.mkOption {
359 type = types.str;
360 default = "1y";
361 example = "1y";
362 description = ''
363 Expiration timeout.
364 '';
365 };
366 usage = lib.mkOption {
367 type = with types; listOf (enum [ "sign" "encrypt" "auth" "default" ]);
368 default = ["default"];
369 example = ["sign" "encrypt" "auth"];
370 description = ''
371 Cryptographic usage.
372 '';
373 };
374 };
375 });
376 };
377 backupRecipients = lib.mkOption {
378 type = with types; listOf str;
379 default = [];
380 example = ["@john@doe.pro"];
381 description = ''
382 Backup keys used to encrypt the a backup copy of the secret keys.
383 '';
384 };
385 };
386 }));
387 };
388 dirmngrConf = lib.mkOption {
389 type = types.lines;
390 apply = s: pkgs.writeText "dirmngr.conf" s;
391 default = ''
392 allow-ocsp
393 hkp-cacert ${gnupg.keyserverPEM}
394 keyserver hkps://keys.mayfirst.org
395 use-tor
396 #log-file ${gnupg.gnupgHome}/dirmngr.log
397 #standard-resolver
398 '';
399 description = ''
400 GnuPG's dirmngr.conf content.
401 '';
402 };
403 keyserverPEM = lib.mkOption {
404 type = types.lines;
405 apply = s: pkgs.writeText "keyserver.pem" s;
406 default = builtins.readFile gnupg/keyserver.pem;
407 description = ''
408 dirmngr's hkp-cacert content.
409 '';
410 };
411 gpgAgentConf = lib.mkOption {
412 type = types.lines;
413 apply = s: pkgs.writeText "gpg-agent.conf" s;
414 default = ''
415 allow-preset-passphrase
416 default-cache-ttl 17200
417 default-cache-ttl-ssh 17200
418 enable-ssh-support
419 max-cache-ttl 17200
420 max-cache-ttl-ssh 17200
421 pinentry-program ${pkgs.pinentry}/bin/pinentry
422 '';
423 description = ''
424 GnuPG's gpg-agent.conf content.
425 '';
426 };
427 gpgConf = lib.mkOption {
428 type = types.lines;
429 apply = s: pkgs.writeText "gpg.conf" s;
430 default = ''
431 auto-key-locate keyserver
432 cert-digest-algo SHA512
433 charset utf-8
434 default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 TWOFISH BZIP2 ZLIB ZIP Uncompressed
435 fixed-list-mode
436 keyid-format 0xlong
437 keyserver-options no-honor-keyserver-url
438 no-auto-key-locate
439 no-default-keyring
440 no-emit-version
441 personal-cipher-preferences AES256 AES CAST5
442 personal-digest-preferences SHA512
443 quiet
444 s2k-cipher-algo AES256
445 s2k-count 65536
446 s2k-digest-algo SHA512
447 s2k-mode 3
448 tofu-default-policy unknown
449 trust-model tofu+pgp
450 use-agent
451 utf8-strings
452 '';
453 description = ''
454 GnuPG's gpg.conf content.
455 '';
456 };
457 };
458 config = lib.mkIf gnupg.enable {
459 nix-shell.buildInputs = [
460 gpg-with-home
461 gpg-fingerprint
462 gpg-keygrip
463 gpg-uid
464 gpg-init
465 ];
466 nix-shell.shellHook = ''
467 # gnupg
468 export GNUPGHOME=${gnupg.gnupgHome}
469 install -dm700 "$GNUPGHOME"
470 export GPG_TTY=$(${pkgs.coreutils}/bin/tty)
471 ${pkgs.gnupg}/bin/gpgconf --launch gpg-agent
472 export SSH_AUTH_SOCK=$(${pkgs.gnupg}/bin/gpgconf --list-dirs agent-ssh-socket)
473 '';
474 };
475 }