forked from fanf2/regpg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregpg.pl
1963 lines (1545 loc) · 54.1 KB
/
regpg.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
use warnings;
use strict;
use Cwd qw(abs_path);
use File::Basename;
use File::Find;
use File::Path;
use File::Temp qw(mktemp tempfile);
use Getopt::Std;
use MIME::Base64;
use POSIX;
use Term::ANSIColor;
sub usage {
print STDERR <<'EOF';
regpg - safely store server secrets
usage:
regpg help
regpg check [options] <cryptfile.asc>...
keys:
regpg lskeys [options] [cryptfile.asc]
regpg addself [options]
regpg addkey [options] <keyname>...
regpg delkey [options] <keyname>...
regpg exportkey [options] [keyname]...
regpg importkey [options] [keyfile]...
secrets:
regpg encrypt [options] [[clearfile] cryptfile.asc]
regpg decrypt [options] [cryptfile.asc [clearfile]]
regpg recrypt [options] <cryptfile.asc>...
helpers:
regpg depipe [options] <cryptfile.asc> <fifo>
regpg edit [options] <cryptfile.asc>
regpg pbcopy [options] [cryptfile.asc]
regpg pbpaste [options] [cryptfile.asc]
regpg shred [options] <clearfile>...
generators:
regpg dnssec [opts] <action> [flags] <dnskey>
regpg gencrt [opts] <days> [<cakey> <cacrt>] <priv> <cnf> <crt>
regpg gencsrcnf [options] [<certfile>|<hostname> [csr.cnf]]
regpg gencsr [options] <private.asc> <csr.cnf> [csr]
regpg gendnskey [options] <zone>
regpg genkey [options] <algorithm> <private.asc> [ssh.pub]
regpg genpwd [options] [cryptfile.asc]
regpg genspkifp [options] [priv|crt|csr|host]
setup:
regpg init [options] [hook]...
regpg conv <command> [options] <args>...
options:
-k <pubring.gpg> recipient keyring
-n no changes (implies -v)
-q quiet mode
-r recrypt all files after keyring changes
-v verbose mode
Either or both file arguments to `encrypt` and `decrypt`
can be '-' meaning stdin or stdout. Omitted clearfile
arguments are equivalent to '-'.
EOF
exit 1;
}
sub help {
exec "perldoc -M Pod::Text::Overstrike -F $0";
}
my %opt;
my @gpg;
my @gpg_de;
my @gpg_en;
my $keydir;
my $keybase;
sub getargs {
my %arg = @_;
usage unless getopts '-hk:nqrv', \%opt;
help if $opt{h};
$opt{k} //= './pubring.gpg';
$opt{v} = 1 if $opt{n};
usage if @ARGV < $arg{min};
usage if defined $arg{max} and @ARGV > $arg{max};
die "regpg: $opt{k} not found\n"
unless -f $opt{k} or $arg{keymaker};
$opt{k} = "./$opt{k}" unless $opt{k} =~ m{/};
($keybase,$keydir) = fileparse $opt{k};
my $regpghome = $ENV{REGPGHOME} ? $ENV{REGPGHOME} :
$ENV{HOME} ? "$ENV{HOME}/.regpg" :
die "regpg: \$HOME and \$REGPGHOME are unset\n";
# let gpg report any problems
mkdir $regpghome; chmod 0700, $regpghome;
@gpg = (qw(gpg --no-greeting --keyid-format=long --trust-model=always
--homedir), $regpghome,
qw(--no-default-keyring --keyring), $opt{k});
@gpg_de = (qw(gpg --decrypt --quiet --batch --use-agent));
@gpg_en = (@gpg, qw(--armor --force-mdc --encrypt));
return;
}
sub stdio {
my $stdio = (not defined $_[-1] or $_[-1] eq '-');
return !wantarray ? $stdio : $stdio ? () : @_;
}
sub getout {
return @ARGV == 0 ? ()
: @ARGV == 1 ? ('--output', @ARGV)
: die 'Internal error';
}
########################################################################
#
# utilities
#
# save stdout/stderr once
open my $stdout, '>&STDOUT' or die "dup: $!\n";
open my $stderr, '>&STDERR' or die "dup: $!\n";
sub verbose {
print STDERR "@_\n" if $opt{v};
return;
}
sub vsystem {
verbose "running @_";
return 0 if $opt{n};
return 0 if 0 == system @_;
die "failed: @_\n";
}
sub vsystem_warn {
eval { vsystem @_};
return $? >> 8;
}
sub canexec {
return scalar grep { -x "$_/@_" } split /:/, $ENV{PATH};
}
sub firstdir {
return (grep { defined $_ and -d $_ } @_)[0];
}
sub pipeslurp {
verbose "pipe from @_";
return if $opt{n};
open my $pipe, '-|', @_
or die "open pipe from $_[0]: $!\n";
my @out = <$pipe>;
unless (close $pipe) {
die "read pipe from $_[0]: $!\n" if $!;
die "pipe from $_[0] failed\n";
}
return @out if wantarray;
return join '', @out;
}
sub safeslurp {
delete local $opt{n};
return pipeslurp @_;
}
sub pipeslurp_quiet {
return pipeslurp @_ if $opt{v} or $opt{n};
open STDERR, '>', '/dev/null' or die "open /dev/null: $!\n";
my @out = pipeslurp @_;
open STDERR, '>&', $stderr or die "dup: $!\n";
return @out if wantarray;
return join '', @out;
}
sub pipespew {
my $data = shift;
verbose "pipe to @_";
return if $opt{n};
open my $pipe, '|-', @_
or die "open pipe to $_[0]: $!\n";
print $pipe $data;
unless (close $pipe) {
die "write pipe to $_[0]: $!\n" if $!;
die "pipe to $_[0] failed\n";
}
return 0;
}
sub tempclose {
my ($th,$tn,$fn) = @_;
close $th
or die "write $tn: $!\n";
chmod 0666 & ~umask, $tn
or die "chmod $tn: $!\n";
rename $tn => $fn
or die "rename $tn => $fn: $!\n";
return;
}
sub pipespewto {
my $fn = shift;
my $data = shift;
verbose "will pipe out to $fn";
return verbose "pipe to", @_
if $opt{n};
mkpath dirname $fn;
my ($th,$tn) = tempfile "$fn.XXXXXXXX";
open STDOUT, '>&', $th or die "dup: $!\n";
pipespew $data, @_;
open STDOUT, '>&', $stdout or die "dup: $!\n";
return tempclose $th, $tn, $fn;
}
sub spewto {
my $fn = shift;
verbose "write to $fn";
return if $opt{n};
mkpath dirname $fn;
my ($th,$tn) = tempfile "$fn.XXXXXXXX";
print $th @_;
return tempclose $th, $tn, $fn;
}
sub spewtofifo {
my $fifo = shift;
verbose "mkfifo $fifo";
if ($opt{n}) {
verbose "write to $fifo";
verbose "unlink $fifo";
return;
}
unlink $fifo;
mkfifo $fifo, 0600
or die "mkfifo $fifo: $!\n";
my $pid = fork;
die "regpg: fork: $!\n" unless defined $pid;
return $pid if $pid > 0;
open my $fh, '>', $fifo
or die "open $fifo: $!\n";
verbose "write to $fifo";
print $fh @_;
close $fh or die "write $fifo: $!\n";
verbose "unlink $fifo";
unlink $fifo;
verbose "regpg pid $$ done";
exit 0;
}
sub copyfile {
my $srcN = shift;
my $dstN = shift;
verbose "copy $srcN => $dstN";
sysopen my $srcH, $srcN, O_RDONLY
or die "open < $srcN: $!\n";
sysopen my $dstH, $dstN, O_WRONLY|O_CREAT|O_EXCL
or die "open > $dstN: $!\n";
local $/ = undef;
syswrite $dstH, <$srcH>;
close $dstH or die "write $dstN: $!\n";
return;
}
sub peekfile {
my $fn = shift;
return if not -f $fn;
open my $fh, '<', $fn
or die "open $fn: $!\n";
return scalar <$fh>;
}
sub random_bytes {
my $len = shift;
open my $fh, '<', '/dev/urandom'
or die "open /dev/urandom: $!\n";
$len == sysread $fh, my $bytes, $len
or die "read /dev/urandom: $!\n";
return $bytes;
}
sub random_password {
return encode_base64 random_bytes 12;
}
sub random_serial {
return -set_serial => "0x".unpack "H*", random_bytes 16;
}
########################################################################
#
# gpg wrappers
#
# When initializing a public keyring, gpg-2.1 will create a "keybox"
# file which is incompatible with older versions of gpg. However, if
# it is working with an existing old-style keyring it will maintain
# compatibility. So, we use the following key to start the keyring,
# then remove it after adding the keys we wanted. This is a revoked
# expired signing-only key so I can't use it to subvert your secrets.
my $dummy_key = <<'DUMMY';
mQENBDpPyJsBCAC1kKuLLuRySgw2nx9lPPX9lHd2liYpqqxhS5uscubyP7qp11H+gms2Dr2zpcizpVp
vIlF8l44xMwVbO7+rVpG1wnrCf6WklbmLR6vscJOwmSVh2uNA7wiKpU6W9aZAIX9cVF6tMa0KDij8pW
H4GAS5GvZcjaf1qAH1+B4M3iqviX0oyypn/8WU59hnnnMdD9CIUBUOrGqFeN+ZwQUYFs6R9+lkzjDfC
F4xbBSM/+kd4WDfHE+0PXKfXdMh3JTONy9oz5FfIhDTzjFks5SuM/eXZmLbmORwYYN+LIHy3j12ErSO
nnnMtdWPheP1Z8BGuaaeSpEG6wAw8+1v+e/qTxsBABEBAAGJASgEIAECABIFAjpPyMgLHQBkdW1teSB
rZXkACgkQo/luLGExUxvY0wgAqUlFaqmMBXBcSSkEaM5UkcPOjcvy8anAub6Hj5zfzQc6Cfj8e9hR8Y
4S61RQ0GCfgeRJcIFCZpqQpk54J5OldcHMTmAGB9rYMoLxJtBfhUo8IYViRQlJduhz8m7YK7pkp666u
YD45q3NmRazIh30WMewAfw5FaakJXPoXglc8Q23m0YpiBOY4MVMDlqBV8JdjCXKYHWzIX5WXwJtDhiw
uRcOUi6QoCOQC/C2ysdS2MizrYRwY0KPRLtBVH/pm1XfcdW08kX/R0dqHX9rWz7qr6AmWLRbadOUwfV
FxROpMD4qMUXahRlaJdUcjM8IfJO/O84yfA20smkinl+3oWbZfLACAAO0JUR1bW15IEtleSA8ZHVtbX
lAdGhpcy1rZXktaXMuaW52YWxpZD6JAT4EEwECACgFAjpPyJsCGwMFCQABUYAGCwkIBwMCBhUIAgkKC
wQWAgMBAh4BAheAAAoJEKP5bixhMVMbMYgIAJFC/5SDw6l9QTUvHGDhgswq5q+SkjlXrpWJ9kVYQxx7
Bx9QFtCrfGtpHxDND+cJideX8CN4A+EdxYO8R+pQI4Q4nsOIjTBsNYYcmh7YMHTfS3F+/UTpbGWLcIm
SvIhiKHhwVFoFxrgW9IlaiEsW+NngB1dXQeR7xyeUV/MDQrxlBKcNw2hhSf8tPfIn/5djX/Z57cNRDz
Z9qAuajkk7ZZ/gE9ZCrBy0X5T5W0xdV15fGmsvCAWDR1oQyfvZEHIKhIAOHtlCrXAAamm0vyE5cWT8/
W1rVvJ5/AcDJkWHZOw/LaDrT98PXFnyhvY3JPI/XCUWAISA0xB6wjvImRZzOK+wAgAD
DUMMY
sub dummy_init {
return 1 if -f $opt{k} and -s $opt{k};
return spewto $opt{k}, decode_base64 $dummy_key;
}
sub dummy_fini {
return vsystem @gpg, qw(--delete-key --batch --yes 0xA3F96E2C6131531B);
}
sub ring_keys {
my @out = @_ ? (safeslurp @_)
: (safeslurp @gpg, qw(--list-keys --with-colons));
# get the key ID of each encryption-capable key or subkey
return map { m{^(?:[^:]*:){4}([^:]*):} }
grep { m{^(pub|sub|sec|ssb)(:[^:]*){10}:\w*e\w*:} } @out;
}
sub recipients {
return map { ('--recipient' => $_) } ring_keys;
}
sub self_keys {
return ring_keys
qw(gpg --list-secret-keys --with-colons), $ENV{USER};
}
sub clean_ids {
return map { s{^\w+/}{}r } @_;
}
sub add_keys {
# Export from the user's normal gpg setup (except when subverted by
# init_ansible_gpg). We prefer to use gpg2 here, instead of the
# default gpg, so that we can downgrade from keybox files to more
# compatible old-style pubring files. export-minimal removes
# extraneous signatures from the key, which avoids complaints about
# unavailable public keys when it is imported.
my $gpg = (canexec 'gpg2') ? 'gpg2' : 'gpg';
my $keys = pipeslurp $gpg, qw(--export --armor
--export-options export-minimal), @_;
# Import to this local keyring
my $skip = dummy_init;
pipespew $keys, @gpg, '--import';
dummy_fini unless $skip;
return 0;
}
sub fingerprint {
# search in both the regpg keyring and the user's keyring
my @r;
eval { @r = pipeslurp_quiet @gpg, '--fingerprint', @_; };
return @r if @r;
eval { @r = pipeslurp_quiet 'gpg', '--fingerprint', @_; };
return @r if @r;
return "no fingerprint for @_\n", "\n";
}
sub find_all {
my @all;
find { no_chdir => 1, wanted => sub {
push @all, $File::Find::name
if (peekfile($File::Find::name) // '')
=~ m{-----BEGIN PGP MESSAGE-----};
}, }, '.';
return sort @all;
}
sub recrypt_one {
my $fn = shift;
my @recipients = @_;
my $cleartext = pipeslurp @gpg_de, $fn;
return pipespewto $fn, $cleartext, @gpg_en, @recipients;
}
sub recrypt_some {
my @recipients = recipients;
recrypt_one $_, @recipients for @_;
return 0;
}
sub maybe_recrypt_all {
recrypt_some find_all if $opt{r};
return 0;
}
# actually an openssl wrapper
sub certslurp {
my $src = shift;
my ($host,$port) = $src =~ m{^(.*):(\d+)$}
? ($1,$2) : ($src,443);
return safeslurp "openssl s_client ".
"-servername $host -connect $host:$port ".
"</dev/null 2>/dev/null | @_";
}
########################################################################
#
# check
#
sub check_clear {
my ($file,$dir,$ext) = fileparse @_;
return () if @_ > 1 and not $ext;
return grep { -f $_ }
"$dir$file", "$dir$file~", "$dir#$file#", glob "$dir.$file.sw?";
}
sub check_quiet {
my $fn = shift;
my @ring = @_;
my $re = qr{^\S+\s+ENC_TO\s+(\S+)\s+.*\n};
my @file = map { s{$re}{$1}r } grep { m{$re} }
pipeslurp @gpg, qw(--list-only --quiet --status-fd 1), $fn;
# diff key lists
my %ring; @ring{@ring} = (); delete @ring{@file};
my %file; @file{@file} = (); delete @file{@ring};
@ring = keys %ring;
@file = keys %file;
my @clear = check_clear $fn, qw(.asc .gpg);
return ( ring => [ @ring ],
file => [ @file ],
diff => (!!@ring || !!@file),
clear => [ @clear ],
unsafe => (!!@clear) );
}
sub diff_del {
return map { colored("-$_", "red") } @_;
}
sub diff_add {
return map { colored("+$_", "green") } @_;
}
sub holy_crap {
return colored " CLEARTEXT @_", "bright_white on_bright_red";
}
sub check_one {
my $fn = shift;
my %ck = check_quiet $fn, @_;
return 0 if $opt{n};
return 0 if $opt{q} and not ($ck{unsafe} || $ck{diff});
print $fn,
$ck{unsafe} ? "\t" . holy_crap(@{ $ck{clear} }) : "",
$ck{diff} ? "\t" : "",
diff_del(@{ $ck{file} }),
diff_add(@{ $ck{ring} }),
"\n";
return $ck{unsafe} || $ck{diff};
}
sub check_long {
my $fn = shift;
my %ck = check_quiet $fn, @_;
return 0 if $opt{n};
return 0 if $opt{q} and not ($ck{unsafe} || $ck{diff});
print " checking: $fn\n";
printf "%s\n", holy_crap $_ for @{ $ck{clear} };
print diff_del fingerprint $_ for @{ $ck{file} };
print diff_add fingerprint $_ for @{ $ck{ring} };
return $ck{unsafe} || $ck{diff};
}
sub check_some {
my @ring_keys = ring_keys;
return check_long @_, @ring_keys if @_ == 1;
my $r = 0;
$r |= check_one $_, @ring_keys for @_;
return $r;
}
sub shred_files {
if (canexec 'shred') {
vsystem 'shred', '-u', $_ for check_clear @_;
} else {
vsystem 'rm', '-f', check_clear @_;
}
return 0;
}
sub shred_some {
$opt{v} = 1 unless $opt{q};
if (@ARGV) {
shred_files $_ for @ARGV;
} else {
shred_files $_, qw(.asc .gpg) for @_;
}
return 0;
}
########################################################################
#
# dnssec wrappers
#
sub dnssec_key {
return $_[-1] =~ s{(\.[0-9a-z.]*)?\s*$}{}r;
}
sub dnssec_encrypt {
my $key = shift;
my $oldhash = peekfile "$key.private.sha256";
my $newhash = safeslurp qw(openssl dgst -sha256), "$key.private";
$newhash =~ s{^.* }{};
return 0 if $oldhash and $oldhash eq $newhash;
# overwrite without prompting
spewto "$key.private.asc", scalar pipeslurp
@gpg_en, recipients, qw(--output -), "$key.private";
spewto "$key.private.sha256", $newhash;
return 0;
}
sub dnssec_shred {
dnssec_encrypt my $key = shift;
return shred_files "$key.private.asc", '.asc';
}
sub dnssec_keygen {
print my $key = pipeslurp_quiet 'dnssec-keygen', @ARGV;
return dnssec_shred dnssec_key $key;
}
sub dnssec_recrypt {
return dnssec_encrypt dnssec_key @ARGV;
}
sub dnssec_settime {
my $key = dnssec_key @ARGV;
my $inclear = -f "$key.private";
my $umask = umask 0077;
spewto "$key.private", pipeslurp @gpg_de, "$key.private.asc"
unless $inclear;
umask $umask;
my $status = vsystem_warn 'dnssec-settime', @ARGV;
$inclear ? dnssec_encrypt $key : dnssec_shred $key;
return $status;
}
########################################################################
#
# init
#
my $ansible_action = INSERT_HERE 'ansible/action.py';
my $ansible_filter = INSERT_HERE 'ansible/filter.py';
my $gpg_preload = INSERT_HERE 'ansible/gpg-preload.yml';
my $vault_script = INSERT_HERE 'ansible/vault-open.sh';
sub ansible_cfg {
my ($sect,$opt,$val) = @_;
my ($fn,$fh,$c) = ("${keydir}ansible.cfg");
local $/ = undef;
$val = "$1:$val" if open $fh, '<', $fn and
$c = <$fh> and $c =~ m{^\s*$opt\s*=\s*(.*)$}m;
return vsystem qw(ansible localhost -c local -m ini_file -a),
"section=$sect option=$opt value=$val ".
"dest=${keydir}ansible.cfg";
}
sub init_preload {
my $asc = "${keydir}gpg-preload.asc";
my $yml = "${keydir}gpg-preload.yml";
pipespewto $asc, 'True', @gpg_en, recipients
unless -f $asc;
return spewto $yml, $gpg_preload;
}
sub init_plugin {
my ($type,$file) = @_;
spewto "${keydir}plugins/$type/gpg_d.py", $file;
return ansible_cfg 'defaults', "${type}_plugins", "plugins/${type}";
}
sub init_ansible {
init_preload;
# dummy module to make the action plugin work
spewto "${keydir}library/gpg_d.py", '';
init_plugin 'action', $ansible_action;
init_plugin 'filter', $ansible_filter;
return;
}
sub init_ansible_vault {
my $vault_pass = "${keydir}vault.pwd.asc";
my $vault_open = "${keydir}vault.open";
pipespewto $vault_pass, random_password, @gpg_en, recipients
unless -f $vault_pass;
spewto $vault_open, $vault_script;
chmod 0777 & ~umask, $vault_open;
return ansible_cfg qw(defaults vault_password_file vault.open);
}
sub git_diff_attr {
my ($file,$mode) = @_;
my $a = safeslurp qw(git check-attr diff), "$keydir$file";
if ($a eq "$keydir$file: diff: unspecified\n") {
my $gitattr = "$keydir.gitattributes";
verbose "append to $gitattr";
unless ($opt{n}) {
open my $fh, '>>', $gitattr
or die "open $gitattr: $!\n";
print $fh "$file diff=$mode\n";
close $fh
or die "write $gitattr: $!\n";
}
}
return;
}
sub init_git {
git_diff_attr $keybase, 'gpgkeys';
git_diff_attr '*.asc', 'gpgrcpt';
vsystem qw(git config diff.gpgkeys.textconv), 'regpg ls -k';
vsystem qw(git config diff.gpgrcpt.textconv),
sprintf "regpg ls -k %s", abs_path $opt{k};
return;
}
sub init_keys {
return verbose "done init -k $opt{k}" if -f $opt{k};
return add_keys self_keys;
}
########################################################################
#
# conversion
#
sub conv_ansible_gpg {
$opt{v} = 1 unless $opt{q};
getargs keymaker => 1, min => 0, max => 0;
my $old_scripts = "${keydir}ansible-gpg";
return verbose "$old_scripts not found" unless -d $old_scripts;
my $old_dir = "${keydir}.ansible-gpg";
# subvert add_keys to get keys from a file rather than a list of IDs
add_keys qw(--no-default-keyring --keyring), "$old_dir/pubring.gpg";
copyfile "$old_dir/vault_passphrase.gpg" => "${keydir}vault.pwd.asc";
init_ansible_vault;
rmtree $old_scripts, $opt{v}, 1;
rmtree $old_dir, $opt{v}, 1;
return 0;
}
sub conv_ansible_vault {
getargs min => 0, max => 2;
if (@ARGV == 0) {
print "regpg conv ansible-vault candidate files:\n";
print safeslurp q(find . -type f |
xargs grep -l '[$]ANSIBLE_VAULT;' | sort);
return 0;
}
my $version = pipeslurp qw(ansible-vault --version);
my $cleartext;
if ($version =~ m{ansible-vault 2\.4\.0\.}) {
# this is likely to crash due to a bug in ansible 2.4.0
$cleartext = pipeslurp
qw(ansible-vault decrypt --output /dev/stdout), shift @ARGV;
} else {
# `ansible-vault decrypt --output -` is noisy on stderr
$cleartext = pipeslurp_quiet
qw(ansible-vault decrypt --output -), shift @ARGV;
}
return pipespew $cleartext, @gpg_en, recipients, getout;
}
sub conv_stgza {
getargs min => 0, max => 2;
# like @gpg_de but passphrase on stdin instead of via agent
my @gpg_dp = qw(gpg --decrypt --quiet --batch --passphrase-fd 0);
# surprisingly this is better as a long shell pipeline
my $decrypt = "@gpg_de secrets.pwd.asc | @gpg_dp secrets.tar.gz.asc";
if (@ARGV) {
my @tar = (qw(tar Oxzf -), shift @ARGV);
my @encrypt = (@gpg_en, recipients, getout);
return vsystem "$decrypt | @tar | @encrypt";
} else {
my @tar = $opt{v} ? qw(tar tvzf -) : qw(tar tzf -);
return vsystem "$decrypt | @tar | sort";
}
}
########################################################################
#
# subcommands
#
sub addkey {
getargs keymaker => 1, min => 1;
add_keys clean_ids @ARGV;
return maybe_recrypt_all;
}
sub addself {
getargs keymaker => 1, min => 0, max => 0;
return add_keys self_keys;
}
sub delkey {
getargs keymaker => 1, min => 1;
# --expert persuades gpg to delete the key even if the secret
# key is available, when deleting one of the user's own keys
vsystem @gpg, '--expert', '--delete-key', clean_ids @ARGV;
return maybe_recrypt_all;
}
sub exportkey {
getargs min => 0;
return vsystem @gpg, qw(--export --armor), clean_ids @ARGV;
}
sub importkey {
getargs keymaker => 1, min => 0;
my $skip = dummy_init;
my $status = vsystem_warn @gpg, '--import', @ARGV;
dummy_fini unless $skip;
return $status if $status;
return maybe_recrypt_all;
}
sub lskeys {
getargs min => 0, max => 1;
return vsystem @gpg, '--fingerprint'
if @ARGV == 0;
my $out = pipeslurp @gpg,
qw(--quiet --batch --list-packets --list-only), @ARGV;
print fingerprint $_ for $out =~ m{\s+keyid\s+(\S+)\s+}g;
return 0;
}
#----------------------------------------------------------------------#
sub for_files {
my ($zap,$sub) = @_;
getargs min => 0;
if (@ARGV and $opt{r}) {
die "regpg: either -r or arguments, not both\n";
} elsif (@ARGV) {
return $sub->(@ARGV);
} elsif ($opt{r} or $zap eq 'zap') {
return $sub->(find_all);
} else {
die "regpg: use -r to really $zap all files\n";
}
}
sub check {
return for_files zap => \&check_some;
}
sub shred {
return for_files shred => \&shred_some;
}
sub squeegee {
$opt{r} = 1;
return shred;
}
sub recrypt {
return for_files recrypt => \&recrypt_some;
}
sub encrypt {
getargs min => 0, max => 2;
my @in = (@ARGV > 1) ? (shift @ARGV) : ();
return vsystem @gpg_en, recipients, getout, @in;
}
sub decrypt {
getargs min => 0, max => 2;
my @in = (@ARGV > 0) ? (shift @ARGV) : ();
if (stdio @ARGV) {
return vsystem @gpg_de, @in;
} else {
umask 0077;
spewto @ARGV, pipeslurp @gpg_de, @in;
return 0;
}
}
#----------------------------------------------------------------------#
sub depipe {
getargs min => 2, max => 2;
my ($secret,$fifo) = @ARGV;
my $cleartext = pipeslurp @gpg_de, $secret;
my $pid = spewtofifo $fifo, $cleartext;
print "regpg pid $pid waiting on $fifo\n" if $pid;
return 0;
}
my @pbcopy = qw(pbcopy);
my @pbpaste = qw(pbpaste);
sub xclip {
if (canexec 'xclip') {
@pbcopy = qw(xclip -i);
@pbpaste = qw(xclip -o);
}
return getargs min => 0, max => 1;
}
sub pbcopy {
xclip;
my $cleartext = pipeslurp @gpg_de, stdio @ARGV;
pipespew $cleartext, @pbcopy;
unless ($opt{n}) {
print STDERR "Press ^C when you have used the secret...";
do { local $SIG{INT} = sub {}; pause; };
print STDERR "\n";
}
return pipespew '', @pbcopy;
}
sub pbpaste {
xclip;
my $cleartext = pipeslurp @pbpaste;
die 'regpg: clipboard is empty' if $cleartext eq '';
pipespew $cleartext, @gpg_en, recipients, getout;
return pipespew '', @pbcopy;
}
sub edit {
getargs min => 1, max => 1;
my ($template,$dir) = fileparse "@ARGV.XXXXXXXX";
$dir = firstdir "/run/user/$<", "/dev/shm", $ENV{TMPDIR}, $dir, ".";
my $tmp = mktemp "$dir/$template";
vsystem @gpg_de, '--output', $tmp, @ARGV if -f "@ARGV";
my $status = (vsystem_warn $ENV{EDITOR}, $tmp) ||
(vsystem_warn @gpg_en, recipients, '--output', @ARGV, $tmp);
shred_files $tmp;
return $status;
}
#----------------------------------------------------------------------#
sub dnssec {
getargs min => 2;
my $action = shift @ARGV;
my @action = qw(keygen recrypt settime);
if (grep { $action eq $_ } @action) {
return $::{"dnssec_$action"}();
} else {
die "regpg dnssec action must be one of: @action\n";
}
}
sub gendnskey {
getargs min => 1, max => 1;
print my @found = map s{\.key$}{\n}r, glob "K@ARGV.+013+*.key";
return 0 if @found;
unshift @ARGV, qw(-L 86400 -a 13);
my $exit = dnssec_keygen;
unshift @ARGV, qw(-f KSK -Psync now);
return $exit || dnssec_keygen;
}
sub gencsrcnf {
# not really a keymaker - we just don't use the keyring
getargs keymaker => 1, min => 0, max => 2;
my ($src,$cnf,$crt) = @ARGV;
my @openssl_x509 = qw(openssl x509 -noout -text -nameopt multiline);
if (stdio $src or -f $src) {
$crt = safeslurp @openssl_x509, stdio -in => $src;
} else {
$crt = certslurp $src, @openssl_x509;
}
my $dns = qr{DNS:([A-Za-z0-9*.-]+)[,\s]+};
$crt =~ m{\n(\ +)Subject:\n((?:\1\ +.*\n)+)\1[^ ](?:.*\n)+
[ ]+X509v3[ ]Subject[ ]Alternative[ ]Name:\s+($dns+)}x
or die "regpg: could not find certificate subject\n";
my $subject = $2;
my @san = $3 =~ m{$dns}g;
$subject =~ s{^\s+}{}mg;
my $san = join '', map { "DNS.$_ = $san[$_]\n" } keys @san;
my $out = <<"CONF";
[ req ]
prompt = no
distinguished_name = distinguished_name
req_extensions = extensions
x509_extensions = extensions
[ extensions ]
subjectAltName = \@subjectAltName
[ distinguished_name ]
$subject
[ subjectAltName ]
$san
CONF
if (stdio $cnf) {
print $out;
} else {
spewto $cnf, $out;
}
return 0;
}
sub getkey {
my $priv = shift;
if (-f $priv) {
return pipeslurp @gpg_de, $priv;
} else {
my $key = pipeslurp qw(openssl genrsa 2048);
pipespewto $priv, $key, @gpg_en, recipients;
return $key;
}
}
sub gencrt {
getargs min => 4, max => 6;
my ($days,$cakey,$cacrt,$priv,$cnf,$self,$signed);
if (@ARGV == 6) {
($days,$cakey,$cacrt,$priv,$cnf,$signed) = @ARGV;
$self = mktemp "$signed.XXXXXXXX";
$cakey = pipeslurp @gpg_de, $cakey;
$priv = getkey $priv;
} else {
($days,$priv,$cnf,$self) = @ARGV;
$priv = getkey $priv;
}
# Generate a self-signed certificate, then re-sign if necessary.
# If we generate a CSR then `openssl x509 -req` drops the
# extensions when making a signed certificate. `openssl ca`
# requires too much faff with config files for our purposes.
pipespew $priv, qw(openssl req -new -x509 -sha256 -key /dev/stdin),
random_serial, -days => $days, -config => $cnf, -out => $self;
if (@ARGV == 6) {
# The authorityKeyIdentifier will get the wrong value if
# it is added the first time round. See x509v3_config(5ssl)
my $ext = mktemp "$cnf.XXXXXXXX";
spewto $ext,
"subjectKeyIdentifier = hash\n",
"authorityKeyIdentifier = keyid:always, issuer:always\n";
pipespew $cakey, qw(openssl x509 -sha256 -CAkey /dev/stdin),
random_serial, -days => $days, -CA => $cacrt,
-extfile => $ext, -in => $self, -out => $signed;
unlink $self, $ext;
}
vsystem qw(openssl x509 -text -in), $ARGV[-1] if $opt{v};
return 0;
}
sub gencsr {
getargs min => 2, max => 3;
my ($priv,$cnf,$req) = @ARGV;
my $key = getkey $priv;
my @opt = (-config => $cnf);
push @opt, stdio -out => $req;
pipespew $key, qw(openssl req -new -sha256 -key /dev/stdin), @opt;
vsystem qw(openssl req -text -in), $req
if $opt{v} and $opt[-2] eq '-out';
return 0;
}
sub genssh {
my ($pub,$key) = @_;
# Ideally we want to use a pipe, but ssh-keygen does not like
# the loose permission on /dev/stdin on BSDish systems, and
# puttygen seems to stop reading from a pipe before EOF; the
# disadvantage of the fifo is the risk of losing an open race.
my @stat = POSIX::fstat((POSIX::pipe)[0]);
if ($stat[2] & 0077 && $stat[4] == $<) {
my $fifo = mktemp "$pub.XXXXXXXX";
spewtofifo $fifo, $key;
open STDOUT, '>', $pub
or die "regpg: open $pub: $!\n";
exec qw(ssh-keygen -y -f), $fifo;
} else {
pipespewto $pub, $key, qw(ssh-keygen -y -f /dev/stdin);
return 0;
}
}