-
Notifications
You must be signed in to change notification settings - Fork 19
/
signd
executable file
·2437 lines (2241 loc) · 83.8 KB
/
signd
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
#
# Copyright (c) 2022 SUSE LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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 (see the file COPYING); if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
################################################################
use Socket;
use POSIX;
use Fcntl qw(:DEFAULT :flock);
use Math::BigInt;
use MIME::Base64;
use Encode;
use bytes;
use File::Temp qw/tempdir/;
use File::Path qw/remove_tree/;
use Digest::SHA;
use strict;
use warnings;
my $have_gcrypt;
eval {
require Crypt::GCrypt::Sexp;
require Crypt::GCrypt::MPI;
require Crypt::GCrypt;
die unless defined &Crypt::GCrypt::pk_sign;
Crypt::GCrypt::gcrypt_version(); # initialize lib
$have_gcrypt = 1;
};
my @allows;
my @allow_subject;
my %map;
my $signhost = '127.0.0.1';
my $port = 5167;
my $sockproto = '';
my $signuser = '';
my $gpg = '/usr/bin/gpg';
my $phrases = '';
my $aliases = '';
my $encryptionkeys = '';
my $tmpdir = '/run/signd';
my $patchclasstime;
my $conf = '/etc/sign.conf';
my $allow_unprivileged_ports = 0;
my $use_unprivileged_ports = 0;
my $logfile;
my $pidfile = '/run/signd.pid';
my $use_agent;
my $agentsocket = [];
my @pinentrymode;
my $keycache = '';
my $use_gcrypt_sign;
my $use_gcrypt_privsign;
my $use_gcrypt_decrypt;
my $ssl_certfile;
my $ssl_keyfile;
my $ssl_verifyfile;
my $ssl_verifydir;
my $proxyport;
my $proxysockproto;
my $proxyssl_certfile;
my $proxyssl_keyfile;
my $proxyssl_verifyfile;
my $proxyssl_verifydir;
my $restricted_gnupghome = '';
my $restricted_phrases = '';
my $restricted_aliases = '';
my $privileged_gnupghome = '';
my $privileged_logfile;
my $system_gnupghome = '';
my $extranonce = '';
my $backup_user = '';
my @backup_locations;
my $signaddr;
# request data
my $oldproto = 0;
my $peer = 'unknown';
##
## helper functions
##
sub ls {
my ($dir) = @_;
my $d;
return () unless defined($dir) && opendir($d, $dir);
my @d = grep {!/^\./} readdir($d);
closedir($d);
return sort(@d);
}
sub spew {
my ($fn, $data) = @_;
local *F;
open(F, '>', $fn) || die("$fn: $!\n");
(syswrite(F, $data) || 0) == length($data) || die("write error: $!\n");
close(F) || die("close: $!\n");
}
sub slurp_first_line {
my ($fn) = @_;
my $fd;
open($fd, '<', $fn) || die("$fn: $!\n");
my $data = <$fd>;
die("$fn: $!\n") unless defined $data;
close $fd;
chomp $data;
return $data;
}
sub printlog {
my ($msg) = @_;
my @lt = localtime(time);
my $year = $lt[5] + 1900;
my $month = $lt[4] + 1;
printf "%04d-%02d-%02d %02d:%02d:%02d: %s\n", $year, $month, @lt[3,2,1,0], $msg;
}
sub create_tmpdir {
my $tdir = tempdir('XXXXXXXX', DIR => $tmpdir, CLEANUP => 1);
chmod 0700, $tdir;
return $tdir;
}
# convert CIDR prefix to netmask array
sub calc_netmask {
my $prefix = @_;
my $mask = (2 ** $prefix - 1) << (32 - $prefix);
my @netmask = unpack( "C4", pack( "N", $mask ) );
return @netmask;
}
# Check if an ip falls within a CIDR-style subnet
sub ip_in_network {
my ($ip, $network) = @_;
return 0 unless $network =~ /^([0-9\.]+)\/([0-9]+)$/;
my @ip_a = split '\.', $ip;
my @network_a = split '\.', "$1.0.0.0.0";
my @netmask_a = unpack('C4', pack('N', 0xffffffff >> $2));
for (my $i = 0; $i < 4; $i++) {
return 0 if ($ip_a[$i] | $netmask_a[$i]) != ($network_a[$i] | $netmask_a[$i]);
}
return 1;
}
sub swrite {
my ($sock, $data) = @_;
local *S = $sock;
while (length($data)) {
my $l = syswrite(S, $data, length($data));
die("write: $!\n") unless $l;
$data = substr($data, $l);
}
}
sub checkbadchar {
my ($str, $what) = @_;
die("bad character in $what\n") if $str =~ /[\000-\037]/;
eval {
Encode::_utf8_on($str);
encode('UTF-8', $str, Encode::FB_CROAK);
};
die("$what is not utf-8\n") if $@;
}
##
## PGP functions (RFC 4880)
##
my $pgp_curve_nistp256 = "\x2a\x86\x48\xce\x3d\x03\x01\x07";
my $pgp_curve_nistp384 = "\x2b\x81\x04\x00\x22";
my $pgp_curve_ed25519 = "\x2b\x06\x01\x04\x01\xda\x47\x0f\x01";
my $pgp_curve_cv25519 = "\x2b\x06\x01\x04\x01\x97\x55\x01\x05\x01";
sub get_pgphashalgo {
my ($hashalgo) = @_;
$hashalgo = lc($hashalgo);
return 2 if $hashalgo eq 'sha1';
return 8 if $hashalgo eq 'sha256';
return 10 if $hashalgo eq 'sha512';
return undef;
}
sub decodetaglenoff {
my ($pkg) = @_;
my $tag = unpack('C', $pkg);
die("not a pgp packet\n") unless $tag & 128;
my ($len, $off);
if ($tag & 64) {
# new packet format
$tag &= 63;
$len = unpack('@1C', $pkg);
if ($len < 192) {
$off = 2;
} elsif ($len >= 192 && $len < 224) {
$len = unpack('@1n', $pkg) - 48960;
$off = 3;
} elsif ($len == 255) {
$len = unpack('@2N', $pkg);
$off = 6;
}
} else {
# old packet format
if (($tag & 3) == 0) {
$len = unpack('C', substr($pkg, 1));
$off = 2;
} elsif (($tag & 3) == 1) {
$len = unpack('n', substr($pkg, 1));
$off = 3;
} elsif (($tag & 3) == 2) {
$len = unpack('N', substr($pkg, 1));
$off = 5;
}
$tag = ($tag & 60) >> 2;
}
die("unsupported pgp packet length\n") unless defined $off;
return ($tag, $len, $off);
}
sub decodepkg {
my ($pkg) = @_;
my $partial = '';
if ((unpack('C', $pkg) & 0xc3) == 0x83) {
return ((unpack('C', $pkg) & 60) >> 2, substr($pkg, 1), '');
}
while ((unpack('C', $pkg) & 0xc0) == 0xc0) {
my $len = unpack('@1C', $pkg);
last if $len < 224 || $len == 255;
$len = 1 << ($len & 0x1f);
die("truncated pgp packet\n") if length($pkg) < $len + 2;
$partial .= substr($pkg, 2, $len);
substr($pkg, 1, $len + 1, '');
}
my ($tag, $len, $off) = decodetaglenoff($pkg);
return ($tag, $partial.substr($pkg, $off, $len), substr($pkg, $off + $len));
}
sub striptofirst {
my ($pkg) = @_;
my ($tag, $len, $off) = decodetaglenoff($pkg);
return substr($pkg, 0, $off + $len);
}
sub encodetag {
my ($tag, $pack) = @_;
my $l = length($pack);
return pack("CC", $tag + 192, $l).$pack if $l < 192;
return pack("Cn", $tag + 192, $l + 48960).$pack if $l < 8384;
return pack("CCN", $tag + 192, 255, $l).$pack;
}
sub encodetag_oldformat {
my ($tag, $pack) = @_;
my $l = length($pack);
return pack("CC", $tag * 4 + 128, $l).$pack if $l < 256;
return pack("Cn", $tag * 4 + 129, $l).$pack if $l < 65536;
return pack("CN", $tag * 4 + 130, $l).$pack;
}
sub encodesubpackets {
my $su = '';
for (@_) {
die("unsupported subpackage length\n") if length($_) >= 16320;
$su .= pack('C', length($_)).$_ if length($_) < 192;
$su .= pack('n', length($_) + 48960).$_ if length($_) >= 192;
}
return $su;
}
sub encodempi {
my ($mpi) = @_;
$mpi = substr($mpi, 1) while substr($mpi, 0, 1) eq "\0";
my $first = unpack('C', $mpi);
my $bits = 0;
while ($first && ($first & 0x80) == 0) {
$bits++;
$first *= 2;
}
return pack('n', 8 * length($mpi) - $bits).$mpi;
}
sub priv2pub {
my ($privkey, $info) = @_;
my $pubkey = '';
my ($tag, $len, $off) = decodetaglenoff($privkey);
die("not a secret key packet\n") unless $tag == 5;
my $pack = substr($privkey, $off, $len);
my $pkver = unpack('C', $pack);
my ($mpioff, $pkalgo);
if ($pkver == 3) {
(undef, undef, undef, $pkalgo) = unpack('CNnC', $pack);
$mpioff = 8;
} elsif ($pkver == 4) {
(undef, undef, $pkalgo) = unpack('CNC', $pack);
$mpioff = 6;
}
die("unknown public key version $pkver\n") unless $mpioff;
$info->{'version'} = $pkver if $info;
$info->{'algo'} = $pkalgo if $info;
if ($pkalgo == 19 || $pkalgo == 22) { # ECDSA + EdDSA have a curve
my $oidlen = unpack('C', substr($pack, $mpioff));
die("bad curve len") if $oidlen == 0 || $oidlen == 255;
$info->{'curve'} = substr($pack, $mpioff + 1, $oidlen) if $info;
$mpioff += $oidlen + 1;
}
my ($mpinum, $smpinum);
($mpinum, $smpinum) = (2, 4) if $pkalgo == 1; # RSA
($mpinum, $smpinum) = (4, 1) if $pkalgo == 17; # DSA
($mpinum, $smpinum) = (3, 1) if $pkalgo == 16 || $pkalgo == 20; # Elgamal
($mpinum, $smpinum) = (1, 1) if $pkalgo == 19 || $pkalgo == 22; # ECDSA + EdDSA
die("unsupported public key algorithm $pkalgo\n") unless defined $mpinum;
while ($mpinum > 0) {
my $ml = unpack('n', substr($pack, $mpioff, 2));
$ml = (($ml + 7) >> 3) + 2;
push @{$info->{'mpis'}}, substr($pack, $mpioff + 2, $ml - 2) if $info;
$mpioff += $ml;
$mpinum--;
}
if ($info) {
my $s2k = unpack('C', substr($pack, $mpioff, 1));
if ($s2k == 0) {
my $smpioff = $mpioff + 1;
while ($smpinum > 0) {
my $ml = unpack('n', substr($pack, $smpioff, 2));
$ml = (($ml + 7) >> 3) + 2;
push @{$info->{'smpis'}}, substr($pack, $smpioff + 2, $ml - 2);
$smpioff += $ml;
$smpinum--;
}
}
$info->{'fingerprint'} = Digest::SHA::sha1_hex(pack('Cn', 0x99, $mpioff).substr($pack, 0, $mpioff)) if $pkver == 4;
}
return encodetag(6, substr($pack, 0, $mpioff));
}
sub patchclasstime {
my ($sig, $t) = @_;
die("classtime is not 10 hex nibbles\n") unless $t =~ /^[0-9a-fA-F]{10}$/s;
my ($tag, $len, $off) = decodetaglenoff($sig);
die("not a v3 signature\n") unless $tag == 2 && ord(substr($sig, $off, 1)) == 3;
substr($sig, $off + 2, 5, pack('H*', $t));
return $sig;
}
sub wrap_into_pgpsig_v3 {
my ($extra, $fingerprint, $pgppubalgo, $pgphashalgo, $hash, $sigdata) = @_;
my $v3sig = pack('CCH10H16CCH4', 3, 5, $extra, substr($fingerprint, -16), $pgppubalgo, $pgphashalgo, substr($hash, 0, 4)).$sigdata;
return encodetag_oldformat(2, $v3sig);
}
sub wrap_into_pgpsig_v4 {
my ($extra, $fingerprint, $pgppubalgo, $pgphashalgo, $hash, $sigdata) = @_;
die("wrap_into_pgpsig_v4: bad fingerprint length\n") unless length($fingerprint) == 40;
my $pubkeyversion = 4;
my $hashedsub = encodesubpackets(pack('CCH*', 33, $pubkeyversion, $fingerprint), pack('CH*', 2, substr($extra, 2, 8)));
my $unhashedsub = encodesubpackets(pack('CH*', 16, substr($fingerprint, -16)));
my $v4sig = pack('CH2CC', 4, substr($extra, 0, 2), $pgppubalgo, $pgphashalgo);
$v4sig .= pack('n', length($hashedsub)).$hashedsub;
$v4sig .= pack('n', length($unhashedsub)).$unhashedsub;
$v4sig .= pack('H4', substr($hash, 0, 4)).$sigdata;
return encodetag_oldformat(2, $v4sig);
}
sub parse_encryted_data {
my ($encodeddata) = @_;
my ($tag, $len, $off) = decodetaglenoff($encodeddata);
die("encrypted data does not start with a session packet\n") if $tag != 1;
my $pkg = substr($encodeddata, $off, $len);
my ($version, $keyid, $algo) = unpack('CH16C', $pkg);
die("unsupported session packet version\n") unless $version == 3;
my @mpis;
my $mpinum;
$mpinum = 1 if $algo == 1;
$mpinum = 2 if $algo == 16;
$mpinum = 1 if $algo == 18;
die("unsupported encryption algorithm $algo\n") unless $mpinum;
my $einfo = { 'algo' => $algo, 'keyid' => $keyid };
my $mpioff = 10;
while ($mpinum > 0) {
my $ml = unpack('n', substr($pkg, $mpioff, 2));
$ml = (($ml + 7) >> 3) + 2;
push @{$einfo->{'mpis'}}, substr($pkg, $mpioff + 2, $ml - 2);
$mpioff += $ml;
$mpinum--;
}
if ($algo == 18) {
my $ml = unpack('C', substr($pkg, $mpioff, 1));
die("bad ecdh encoded key size\n") if $ml < 2 || $ml == 255;
push @{$einfo->{'mpis'}}, substr($pkg, $mpioff, $ml + 1);
$mpioff += $ml + 1;
}
die("truncated mpis\n") if length($pkg) < $mpioff;
($tag, $pkg) = decodepkg(substr($encodeddata, $off + $len));
die("unsupported protected data tag $tag\n") unless $tag == 18;
die("unsupported integrity protected data packet version\n") if unpack('C', substr($pkg, 0, 1, '')) != 1;
return ($einfo, $pkg, 1);
}
sub parse_sym_encryted_data {
my ($encodeddata) = @_;
my ($tag, $len, $off) = decodetaglenoff($encodeddata);
die("encrypted data does not start with a symmetric session packet\n") if $tag != 3;
my $pkg = substr($encodeddata, $off, $len);
my ($version, $cipheralgo, $s2kmode) = unpack('CCC', $pkg);
die("unsupported session packet version\n") unless $version == 4;
die("unsupported s2k mode\n") unless $s2kmode== 3;
die("symmetric session packet with session key\n") if $len > 2 + 11;
my ($s2kalgo, $s2ksalt, $s2kcnt) = unpack('@3Ca8C', $pkg);
my $einfo = { 'cipheralgo' => $cipheralgo, 's2kalgo' => $s2kalgo, 's2kcnt' => $s2kcnt, 's2ksalt' => $s2ksalt };
($tag, $pkg) = decodepkg(substr($encodeddata, $off + $len));
die("unsupported protected data tag $tag\n") unless $tag == 18;
die("unsupported integrity protected data packet version\n") if unpack('C', substr($pkg, 0, 1, '')) != 1;
return ($einfo, $pkg, 1);
}
sub decode_decrypted_data {
my ($decrypted) = @_;
my ($tag, $pkg);
($tag, $pkg, $decrypted) = decodepkg($decrypted);
if ($tag == 8) {
my $compalgo = unpack('C', $pkg);
die("unsupported compression algo $compalgo\n") unless $compalgo == 1 || $compalgo == 2;
my ($compressed, $decompressed) = (substr($pkg, 1), '');
my ($zlib, $status) = Compress::Raw::Zlib::Inflate->new(-WindowBits => $compalgo == 2 ? Compress::Raw::Zlib::MAX_WBITS() : -15, -Bufsize => 65536, -LimitOutput => 1);
die("could not create zlib decompressor\n") unless $status == Compress::Raw::Zlib::Z_OK();
die("decompression error\n") unless $zlib->inflate($compressed, $decompressed, 1) == Compress::Raw::Zlib::Z_STREAM_END();
($tag, $pkg, $decrypted) = decodepkg($decompressed.$decrypted);
}
die("not a single data packet\n") if $decrypted ne '';
die("not a literal data packet\n") if $tag != 11;
my ($fmt, $fnl) = unpack('CC', $pkg);
die("not binary data\n") unless $fmt == 0x62;
die("literal data packet is too small\n") unless length($pkg) >= 2 + $fnl + 4;
return substr($pkg, 2 + $fnl + 4);
}
##
## libgcrypt support
##
sub sign_with_gcrypt {
my ($info, $hash, $hashalgo, $replyv4) = @_;
die("sign_with_gcrypt: missing fingerprint\n") unless $info->{'fingerprint'};
my $issuer = substr($info->{'fingerprint'}, -16);
die("bad hash $hash\n") unless $hash =~ /^((?:[0-9a-fA-F][0-9a-fA-F])+)\@(0[01][0-9a-fA-F]{8})$/;
my $extra = $2;
$hash = $1;
$hashalgo = lc($hashalgo);
my $pgphashalgo = get_pgphashalgo($hashalgo);
die("sign_with_gcrypt: bad hashalgo $hashalgo\n") unless $pgphashalgo;
my $sigdata;
if ($info->{'algo'} == 1) {
die("sign_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 2 && @{$info->{'smpis'} || []} == 4;
my ($n, $e, $d, $p, $q, $u) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'mpis'}}, @{$info->{'smpis'}};
my $data = Crypt::GCrypt::Sexp->build("(data (flags pkcs1) (hash $hashalgo %b))", pack('H*', $hash));
my $skey = Crypt::GCrypt::Sexp->build("(private-key (rsa (n %M) (e %M) (d %M) (p %M) (q %M) (u %M)))", $n, $e, $d, $p, $q, $u);
my $res = Crypt::GCrypt::pk_sign($data, $skey);
my $sv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 's');
die("could not extract sign result\n") unless $sv;
$sigdata = $sv->print(Crypt::GCrypt::MPI::FMT_PGP());
} elsif ($info->{'algo'} == 17) {
die("sign_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 4 && @{$info->{'smpis'} || []} == 1;
my $qlen = length($info->{'mpis'}->[1]);
my $hashraw = substr(pack('H*', $hash), 0, $qlen < 20 ? 20 : $qlen);
my ($p, $q, $g, $y, $x) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'mpis'}}, @{$info->{'smpis'}};
my $data = Crypt::GCrypt::Sexp->build("(data (flags raw) (value %b))", $hashraw);
my $skey = Crypt::GCrypt::Sexp->build("(private-key (dsa (p %M) (q %M) (g %M) (y %M) (x %M)))", $p, $q, $g, $y, $x);
my $res = Crypt::GCrypt::pk_sign($data, $skey);
my $rv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 'r');
my $sv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 's');
$sigdata = $rv->print(Crypt::GCrypt::MPI::FMT_PGP()).$sv->print(Crypt::GCrypt::MPI::FMT_PGP());
} elsif ($info->{'algo'} == 19) {
die("sign_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 1 && @{$info->{'smpis'} || []} == 1;
my $curve;
$curve = 'NIST P-256' if $info->{'curve'} eq $pgp_curve_nistp256;
$curve = 'NIST P-384' if $info->{'curve'} eq $pgp_curve_nistp384;
die("sign_with_gcrypt: unsupported ECDSA curve\n") unless $curve;
my $hashraw = pack('H*', $hash);
$hashraw = substr($hashraw, 0, 32) if $curve eq 'NIST P-256';
$hashraw = substr($hashraw, 0, 48) if $curve eq 'NIST P-384';
my ($q, $d) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'mpis'}}, @{$info->{'smpis'}};
my $data = Crypt::GCrypt::Sexp->build("(data (flags raw) (value %b))", $hashraw);
my $skey = Crypt::GCrypt::Sexp->build("(private-key (ecc (curve \"$curve\") (q %M) (d %M)))", $q, $d);
my $res = Crypt::GCrypt::pk_sign($data, $skey);
my $rv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 'r');
my $sv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 's');
$sigdata = $rv->print(Crypt::GCrypt::MPI::FMT_PGP()).$sv->print(Crypt::GCrypt::MPI::FMT_PGP());
} elsif ($info->{'algo'} == 22) {
my $curve;
$curve = 'Ed25519' if $info->{'curve'} eq $pgp_curve_ed25519;
die("sign_with_gcrypt: unsupported EdDSA curve\n") unless $curve;
die("sign_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 1 && @{$info->{'smpis'} || []} == 1;
my ($d) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'smpis'}};
my $data = Crypt::GCrypt::Sexp->build("(data (flags eddsa) (hash-algo sha512) (value %b))", pack('H*', $hash));
my $skey = Crypt::GCrypt::Sexp->build("(private-key (ecc (curve \"$curve\") (d %M)))", $d);
my $res = Crypt::GCrypt::pk_sign($data, $skey);
my $rv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 'r');
my $sv = $res->nth_mpi(1, Crypt::GCrypt::MPI::FMT_USG(), 's');
$sigdata = $rv->print(Crypt::GCrypt::MPI::FMT_PGP()).$sv->print(Crypt::GCrypt::MPI::FMT_PGP());
} else {
die("sign_with_gcrypt: unsupported pubkey algorithm $info->{'algo'}\n");
}
return wrap_into_pgpsig_v4($extra, $info->{'fingerprint'}, $info->{'algo'}, $pgphashalgo, $hash, $sigdata) if $replyv4;
return wrap_into_pgpsig_v3($extra, $info->{'fingerprint'}, $info->{'algo'}, $pgphashalgo, $hash, $sigdata);
}
sub can_sign_with_gcrypt {
my ($info) = @_;
return 0 unless $have_gcrypt && $info && $info->{'algo'};
return 0 unless $info->{'smpis'};
return 1 if $info->{'algo'} == 1;
return 1 if $info->{'algo'} == 17;
return 1 if $info->{'algo'} == 22 && $info->{'curve'} eq $pgp_curve_ed25519;
return 1 if $info->{'algo'} == 19 && $info->{'curve'} eq $pgp_curve_nistp256;
return 1 if $info->{'algo'} == 19 && $info->{'curve'} eq $pgp_curve_nistp384;
return 0;
}
sub decrypt_cipher_with_gcrypt {
my ($cipheralgo, $key, $encrypted, $encrypted_mdc) = @_;
my ($cipher, $blklen);
if ($cipheralgo == 7) { # AES128
die("bad cipher key length\n") unless length($key) == 16;
$blklen = 16;
$cipher = Crypt::GCrypt->new('type' => 'cipher', 'algorithm' => 'aes128', 'mode' => 'cfb', 'padding' => 'none');
} elsif ($cipheralgo == 9) { # AES256
die("bad cipher key length\n") unless length($key) == 32;
$blklen = 16;
$cipher = Crypt::GCrypt->new('type' => 'cipher', 'algorithm' => 'aes256', 'mode' => 'cfb', 'padding' => 'none');
}
die("decrypt_with_gcrypt: unsupported cipher algorithm $cipheralgo\n") unless $cipher && $blklen;
$cipher->start('decrypting');
$cipher->setkey($key);
my $padlen = length($encrypted) % $blklen;
my $pad = $padlen ? ("\0" x ($blklen - $padlen)) : '';
my $plain = $cipher->decrypt("$encrypted$pad");
$plain .= $cipher->finish();
$plain = substr($plain, 0, length($encrypted)) if $padlen;
die("bad DEK data\n") if length($plain) < $blklen + 2;
my @chk = unpack('nn', substr($plain, $blklen - 2, 4));
die("DEK mismatch\n") if $chk[0] != $chk[1];
if ($encrypted_mdc) {
die("MDC mismatch\n") if length($plain) < $blklen + 2 + 22 || unpack('n', substr($plain, -22, 2)) != 0xd314;
die("MDC mismatch\n") if substr($plain, -20) ne Digest::SHA::sha1(substr($plain, 0, -20));
substr($plain, -22, 22, '');
}
return substr($plain, $blklen + 2);
}
sub decrypt_with_gcrypt {
my ($info, $einfo, $encrypted, $encrypted_mdc) = @_;
die("decrypt_with_gcrypt: encryption algo mismatch\n") if $info->{'algo'} != $einfo->{'algo'};
my $value;
if ($info->{'algo'} == 1) {
die("decrypt_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 2 && @{$info->{'smpis'} || []} == 4 && @{$einfo->{'mpis'} || []} == 1;
my ($av) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$einfo->{'mpis'}};
my ($n, $e, $d, $p, $q, $u) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'mpis'}}, @{$info->{'smpis'}};
my $encval = Crypt::GCrypt::Sexp->build("(enc-val (flags) (rsa (a %M)))", $av);
my $skey = Crypt::GCrypt::Sexp->build("(private-key (rsa (n %M) (e %M) (d %M) (p %M) (q %M) (u %M)))", $n, $e, $d, $p, $q, $u);
my $res = Crypt::GCrypt::pk_decrypt($encval, $skey);
$value = $res->nth_data(1, 'value');
} elsif ($info->{'algo'} == 16) {
die("decrypt_with_gcrypt: missing MPIs\n") unless @{$info->{'mpis'} || []} == 3 && @{$info->{'smpis'} || []} == 1 && @{$einfo->{'mpis'} || []} == 2;
my ($av, $bv) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$einfo->{'mpis'}};
my ($p, $g, $y, $x) = map {Crypt::GCrypt::MPI->new('format' => Crypt::GCrypt::MPI::FMT_USG(), 'value' => $_)} @{$info->{'mpis'}}, @{$info->{'smpis'}};
my $encval = Crypt::GCrypt::Sexp->build("(enc-val (flags) (elg (a %M) (b %M)))", $av, $bv);
my $skey = Crypt::GCrypt::Sexp->build("(private-key (elg (p %M) (g %M) (y %M) (x %M)))", $p, $g, $y, $x);
my $res = Crypt::GCrypt::pk_decrypt($encval, $skey);
$value = $res->nth_data(1, 'value');
} else {
die("decrypt_with_gcrypt: unsupported encryption algorithm $info->{'algo'}\n");
}
$value = substr($value, 1) if unpack('C', $value) == 0;
die("decryption error\n") unless unpack('C', $value) == 2;
my $idx = index($value, "\0");
die("decryption error\n") unless $idx >= 0;
$value = substr($value, $idx + 1);
my $cipheralgo = unpack('C', substr($value, 0, 1, ''));
my $csum = unpack('n', substr($value, -2, 2, ''));
my $csum2 = 0;
$csum2 += $_ for unpack('C*', $value);
die("decryption error\n") unless $csum == ($csum2 % 65536);
return decrypt_cipher_with_gcrypt($cipheralgo, $value, $encrypted, $encrypted_mdc);
}
sub can_decrypt_with_gcrypt {
my ($einfo) = @_;
return 0 unless $have_gcrypt && $einfo && $einfo->{'algo'};
return 1 if $einfo->{'algo'} == 1;
return 1 if $einfo->{'algo'} == 16;
return 0;
}
sub pgp_s2k_is {
my ($hashalgo, $salt, $passphrase, $count, $outsize) = @_;
die("unsupported s2k_is params\n") if $hashalgo != 10 || length($salt) != 8 || $count < 1024 || $outsize > 32 || $count > 131072;
my $l = length($salt) + length($passphrase);
$count = $l if $count < $l;
my $blob = "$salt$passphrase" x (1 + int($count / $l));
substr($blob, $count, length($blob), '');
return substr(Digest::SHA::sha512($blob), 0, $outsize);
}
sub decrypt_sym_with_gcrypt {
my ($info, $salt, $encrypted, $encrypted_mdc) = @_;
my $keylen;
$keylen = 32 if $info->{'cipheralgo'} == 9;
die("decrypt_sym_with_gcrypt: unsupported cipher algorithm $info->{'cipheralgo'}\n") unless $keylen;
my $s2kcnt = (16 + ($info->{'s2kcnt'} & 0x0f)) << (6 + (($info->{'s2kcnt'} >> 4) & 0x0f));
my $secret = pgp_s2k_is($info->{'s2kalgo'}, $salt, $info->{'secret'}, $s2kcnt, $keylen);
my $decrypted = decrypt_cipher_with_gcrypt($info->{'cipheralgo'}, $secret, $encrypted, $encrypted_mdc);
return decode_decrypted_data($decrypted);
}
sub can_decrypt_sym_with_gcrypt {
my ($info) = @_;
return 0 unless $have_gcrypt && $info && defined($info->{'secret'});
return 0 if ($info->{'s2kalgo'} || 0) != 10;
return 0 if ($info->{'cipheralgo'} || 0) != 9;
return 0 if ($info->{'s2kcnt'} || 0) > 0x70;
return 1;
}
##
## gnupg agent functions
##
my $agent_sock;
sub find_agentsocket_with_gpgconf {
$agentsocket = [];
for (split("\n", `gpgconf --list-dirs`)) {
$agentsocket = [ $1 ] if /^agent-socket:(.*)/;
}
die("could not determine agent socket\n") unless @$agentsocket;
}
sub connect_to_agent {
for my $s (@$agentsocket) {
return 1 if -e $s && connect($agent_sock, sockaddr_un($s));
}
return 0;
}
sub start_agent {
rungpg_fatal("/dev/null", undef, 'gpg-connect-agent', '/bye');
}
sub open_agent {
undef $agent_sock;
socket($agent_sock, PF_UNIX, SOCK_STREAM, 0) || die("socket: $!\n");
if (!connect_to_agent()) {
find_agentsocket_with_gpgconf();
if (!connect_to_agent()) {
start_agent();
connect_to_agent() || die("connect to agent @$agentsocket: $!\n");
}
}
agent_rpc(); # read greeting
}
sub close_agent {
close($agent_sock) if defined $agent_sock;
undef $agent_sock;
}
sub agent_rpc {
my ($cmd, $phrasefile) = @_;
open_agent() unless defined $agent_sock;
my $data = '';
my $error;
eval {
swrite($agent_sock, "$cmd\n") if defined $cmd;
my $res = '';
while (1) {
while ($res !~ /(.*?)\n/) {
my $r = sysread($agent_sock, $res, 4096, length($res));
die("read: $!\n") unless defined $r;
die("unexpected EOF\n") unless $r;
}
die unless $res =~ /(.*?)\n/;
my $line = $1;
$res = substr($res, length($line) + 1);
next if $line =~ /^#/;
next if $line =~ /^S/;
last if $line =~ /^OK/;
if ($line =~ /^ERR ?(.*)/) {
$error = $1;
last;
}
if ($line =~ /^D /) {
$line =~ s/%([a-fA-F0-9]{2})/chr(hex($1))/sge;
$data .= substr($line, 2);
next;
}
if ($line eq 'INQUIRE PASSPHRASE') {
die("unknown passphrase\n") unless defined $phrasefile;
my $passphrase = slurp_first_line($phrasefile);
$passphrase =~ s/([^a-zA-Z0-9])/sprintf("%%%02X",ord($1))/sge;
my $msg = "D $passphrase\nEND\n";
syswrite($agent_sock, $msg) == length($msg) || die("syswrite: $!\n");
next;
}
die("unsupported answer from gpg-agent\n");
}
};
if ($@) {
close_agent();
die($@);
}
die("gpg-agent: $error\n") if defined $error;
return $data;
}
##
## sexp support (used in agent)
##
sub parse_sexp {
my ($l) = @_;
my @l;
die("sexp does not start with '('\n") unless substr($l, 0, 1, '') eq '(';
while (substr($l, 0, 1) ne ')') {
if (substr($l, 0, 1) eq '(') {
push @l, parse_sexp($l);
$l = pop(@l);
} elsif ($l =~ /^(\d+):/) {
my $cnt = $1;
substr($l, 0, length($cnt) + 1, '');
push @l, substr($l, 0, $cnt, '');
} elsif ($l =~ /([0-9a-zA-Z\-\.\/_:*+=]+)/) {
push @l, substr($l, 0, length($1), '');
} else {
die("unterminated sexp\n") if $l eq '';
die("unsupported sexp: ".substr($l, 0, 1)."\n");
}
}
return \@l, substr($l, 1);
}
sub find_in_sexp_rec {
my ($l, $lit) = @_;
return @$l if @$l && $l->[0] eq $lit;
for (@$l) {
next unless ref($_) eq 'ARRAY';
my @r = find_in_sexp_rec($_, $lit);
return @r if @r;
}
return ();
}
sub find_in_sexp {
my ($l, $lit) = @_;
my (undef, $d) = find_in_sexp_rec($l, $lit);
die("could not find $lit\n") unless defined $d;
return $d;
}
sub parse_sexp_signature {
my ($sig) = @_;
($sig) = parse_sexp($sig);
my $sigval = find_in_sexp($sig, 'sig-val');
my $algo = $sigval->[0];
if ($algo eq 'rsa') {
return (1, find_in_sexp($sigval, 's'));
} elsif ($algo eq 'dsa') {
return (17, find_in_sexp($sigval, 'r'), find_in_sexp($sigval, 's'));
} elsif ($algo eq 'ecdsa') {
return (19, find_in_sexp($sigval, 'r'), find_in_sexp($sigval, 's'));
} elsif ($algo eq 'eddsa') {
return (22, find_in_sexp($sigval, 'r'), find_in_sexp($sigval, 's'));
}
die("parse_sexp_signature: unsupported algo $algo\n");
}
##
## gnupg functions
##
sub switch_gnupghome {
my ($gnupghome) = @_;
close_agent();
$agentsocket = [];
$ENV{'GNUPGHOME'} = $gnupghome;
}
sub prepare_tmp_gnupghome {
my $tdir = create_tmpdir();
mkdir("$tdir/gnupg", 0700) || die("mkdir $tdir/gnupg: $!\n");
return ($tdir, "$tdir/gnupg", $ENV{'GNUPGHOME'});
}
sub rungpg_cleanup {
my ($unlinks) = @_;
return unless defined $unlinks;
if (ref($unlinks) eq 'ARRAY') {
unlink($_) for @{$unlinks || []};
} elsif (-d $unlinks) {
remove_tree($unlinks);
}
}
sub rungpg {
my ($stdin, $unlinks, $prg, @args) = @_;
local *RH;
local *WH;
local *KID;
pipe RH, WH;
my $pid = open(KID, "-|");
if (!defined $pid) {
rungpg_cleanup($unlinks) if $unlinks;
die("could not fork: $!\n");
exit(0);
}
if (!$pid) {
delete $SIG{'__DIE__'};
close RH;
if (!open(STDERR, ">&STDOUT")) {
print STDOUT "can't dup stdout: $!\n";
exit(1);
}
open(STDOUT, ">&WH") || die("can't dup writepipe: $!\n");
open(STDIN, "<$stdin") || die("$stdin: $!\n");
close WH;
exec $prg, @args;
die("$prg: $!\n");
}
close WH;
my $out = '';
my $err = '';
1 while sysread(KID, $err, 4096, length($err)) > 0;
1 while sysread(RH, $out, 4096, length($out)) > 0;
close(RH);
my $status = 0;
$status = $? || 255 unless close KID;
$status >>= 8 if $status >= 256;
return ($status, $out, $err);
}
sub rungpg_fatal {
my ($stdin, $unlinks, $prg, @args) = @_;
my ($status, $out, $err) = rungpg($stdin, $unlinks, $prg, @args);
if ($status) {
$err = "Error $status" if $err eq '';
$err =~ s/\n$//s;
rungpg_cleanup($unlinks) if $unlinks;
die("$err\n");
}
return $out;
}
sub find_key {
my ($user, $purpose) = @_;
$purpose ||= 's';
$purpose = qr/$purpose/;
my $lines = rungpg_fatal('/dev/null', undef, $gpg, '--locate-key', '--with-fingerprint', '--with-keygrip', '--with-colons', '--', $user);
my $fpr;
my $grp;
my $keyid;
$keyid = lc(substr($user, -16)) if $purpose eq 's' && $user =~ /^[0-9a-fA-f]{8,}$/;
my $key;
for my $line (split("\n", $lines)) {
next unless $line =~ /^(?:pub|sub|fpr|grp)/;
my @s = split(':', $line);
if ($s[0] eq 'pub' || $s[0] eq 'sub') {
last if $s[0] eq 'pub' && $fpr && $grp; # first matching pubkey wins
undef $key;
next unless $s[11] =~ /$purpose/;
next if $keyid && $s[4] !~ /\Q$keyid\E$/i;
$key = $line;
undef $fpr;
undef $grp;
} elsif ($s[0] eq 'fpr') {
$fpr = $s[9] if $key;
} elsif ($s[0] eq 'grp') {
$grp = $s[9] if $key;
}
}
return (undef, undef) unless $grp && $fpr;
return (uc($fpr), uc($grp));
}
sub read_keycache {
my ($user) = @_;
my ($fd, $fpr, $grp, $rid);
if (open($fd, '<', "$keycache/$user")) {
while(<$fd>) {
chomp;
$fpr = $1 if /^fpr:(\S+)/;
$grp = $1 if /^grp:(\S+)/;
$rid = $1 if /^rid:(\S+)/;
}
close($fd);
}
return ($fpr, $grp, $rid) if $fpr && $grp && $rid;
return (undef, undef, undef);
}
sub write_keycache {
my ($user, $fpr, $grp, $rid) = @_;
mkdir($keycache, 0700) unless -d $keycache;
my $fd;
if (open($fd, '>', "$keycache/.$user.$$")) {
if (print $fd "fpr:$fpr\ngrp:$grp\nrid:$rid\n") {
close($fd) && rename("$keycache/.$user.$$", "$keycache/$user");
} else {
close($fd);
}
unlink("$keycache/.$user.$$");
}
}
sub find_key_keycache {
my ($user, $purpose) = @_;
$purpose ||= 's';
return find_key($user, $purpose) if !$keycache;
my $gnupghome = $ENV{GNUPGHOME};
if (!$gnupghome) {
my $home = $ENV{HOME} || (getpwuid($<))[7];
$gnupghome = "$home/.gnupg" if $home;
}
return find_key($user, $purpose) unless $gnupghome;
my @s = stat("$gnupghome/pubring.kbx");
@s = stat("$gnupghome/pubring.gpg") unless @s;
return find_key($user, $purpose) unless @s;
my $srid = "$s[9]/$s[7]/$s[1]";
my ($fpr, $grp, $rid) = read_keycache("$purpose-$user");
return ($fpr, $grp) if $fpr && $grp && $rid && $rid eq $srid;
($fpr, $grp) = find_key($user, $purpose);
write_keycache("$purpose-$user", $fpr, $grp, $srid) if $fpr && $grp;
return ($fpr, $grp);
}
sub have_pinentry_mode {
my ($status) = rungpg('/dev/null', undef, $gpg, '--pinentry-mode=loopback', '--version');
return !$status;
}
sub have_files_are_digests {
my ($status) = rungpg('/dev/null', undef, $gpg, '--files-are-digests', '--version');
return !$status;
}
sub parse_gpg_kv {
my %kv;
my $lastkey;
for my $l (split(/[\r\n]+/, $_[0])) {
if (defined($lastkey) && ($l eq '' || $l =~ /^[ \t]/)) {
# continuation
$l =~ s/^[ \t]//;
$l =~ s/[ \t]+$//;
$l =~ s/^[ \t]+// if $kv{$lastkey} =~ /\n\z/s;
$l = "\n" if $l eq '';
$kv{$lastkey} .= $l;
next;
}
undef $lastkey;
$l =~ s/^[ \t]*//;
if ($l =~ /^([^ \t]+):[ \t]?(.*)/) {
$lastkey = $1;
$kv{$lastkey} = $2;
} elsif ($l ne '' && $l !~ /^#/) {
die("bad line: $l\n");
}
}
return %kv;
}
sub gpg_privkey_to_info {
my ($key) = @_;