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