completed user ID revocation by emitting a bundle (key+uid+selfsig+revsig) that gpg...
[monkeysphere.git] / src / share / keytrans
1 #!/usr/bin/perl -T
2
3 # keytrans: this is an RSA key translation utility; it is capable of
4 # transforming RSA keys (both public keys and secret keys) between
5 # several popular representations, including OpenPGP, PEM-encoded
6 # PKCS#1 DER, and OpenSSH-style public key lines.
7
8 # How it behaves depends on the name under which it is invoked.  The
9 # two implementations currently are: pem2openpgp and openpgp2ssh.
10
11
12
13 # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
14 # User ID as the first argument, and generate an OpenPGP secret key
15 # and certificate from it.
16
17 # WARNING: the secret key material *will* appear on stdout (albeit in
18 # OpenPGP form) -- if you redirect stdout to a file, make sure the
19 # permissions on that file are appropriately locked down!
20
21 # Usage:
22
23 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
24
25
26
27
28 # openpgp2ssh: take a stream of OpenPGP packets containing public or
29 # secret key material on standard input, and a Key ID (or fingerprint)
30 # as the first argument.  Find the matching key in the input stream,
31 # and emit it on stdout in an OpenSSH-compatible format.  If the input
32 # key is an OpenPGP public key (either primary or subkey), the output
33 # will be an OpenSSH single-line public key.  If the input key is an
34 # OpenPGP secret key, the output will be a PEM-encoded RSA key.
35
36 # Example usage:
37
38 # gpg --export-secret-subkeys --export-options export-reset-subkey-passwd $KEYID | \
39 #  openpgp2ssh $KEYID | ssh-add /dev/stdin
40
41
42 # Authors:
43 #  Jameson Rollins <jrollins@finestructure.net>
44 #  Daniel Kahn Gillmor <dkg@fifthhorseman.net>
45
46 # Started on: 2009-01-07 02:01:19-0500
47
48 # License: GPL v3 or later (we may need to adjust this given that this
49 # connects to OpenSSL via perl)
50
51 use strict;
52 use warnings;
53 use File::Basename;
54 use Crypt::OpenSSL::RSA;
55 use Crypt::OpenSSL::Bignum;
56 use Crypt::OpenSSL::Bignum::CTX;
57 use Digest::SHA;
58 use MIME::Base64;
59 use POSIX;
60
61 ## make sure all length() and substr() calls use bytes only:
62 use bytes;
63
64 my $old_format_packet_lengths = { one => 0,
65                                   two => 1,
66                                   four => 2,
67                                   indeterminate => 3,
68 };
69
70 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
71 my $asym_algos = { rsa => 1,
72                    elgamal => 16,
73                    dsa => 17,
74                    };
75
76 # see RFC 4880 section 9.2
77 my $ciphers = { plaintext => 0,
78                 idea => 1,
79                 tripledes => 2,
80                 cast5 => 3,
81                 blowfish => 4,
82                 aes128 => 7,
83                 aes192 => 8,
84                 aes256 => 9,
85                 twofish => 10,
86               };
87
88 # see RFC 4880 section 9.3
89 my $zips = { uncompressed => 0,
90              zip => 1,
91              zlib => 2,
92              bzip2 => 3,
93            };
94
95 # see RFC 4880 section 9.4
96 my $digests = { md5 => 1,
97                 sha1 => 2,
98                 ripemd160 => 3,
99                 sha256 => 8,
100                 sha384 => 9,
101                 sha512 => 10,
102                 sha224 => 11,
103               };
104
105 # see RFC 4880 section 5.2.3.21
106 my $usage_flags = { certify => 0x01,
107                     sign => 0x02,
108                     encrypt_comms => 0x04,
109                     encrypt_storage => 0x08,
110                     encrypt => 0x0c, ## both comms and storage
111                     split => 0x10, # the private key is split via secret sharing
112                     authenticate => 0x20,
113                     shared => 0x80, # more than one person holds the entire private key
114                   };
115
116 # see RFC 4880 section 4.3
117 my $packet_types = { pubkey_enc_session => 1,
118                      sig => 2,
119                      symkey_enc_session => 3,
120                      onepass_sig => 4,
121                      seckey => 5,
122                      pubkey => 6,
123                      sec_subkey => 7,
124                      compressed_data => 8,
125                      symenc_data => 9,
126                      marker => 10,
127                      literal => 11,
128                      trust => 12,
129                      uid => 13,
130                      pub_subkey => 14,
131                      uat => 17,
132                      symenc_w_integrity => 18,
133                      mdc => 19,
134                    };
135
136 # see RFC 4880 section 5.2.1
137 my $sig_types = { binary_doc => 0x00,
138                   text_doc => 0x01,
139                   standalone => 0x02,
140                   generic_certification => 0x10,
141                   persona_certification => 0x11,
142                   casual_certification => 0x12,
143                   positive_certification => 0x13,
144                   subkey_binding => 0x18,
145                   primary_key_binding => 0x19,
146                   key_signature => 0x1f,
147                   key_revocation => 0x20,
148                   subkey_revocation => 0x28,
149                   certification_revocation => 0x30,
150                   timestamp => 0x40,
151                   thirdparty => 0x50,
152                 };
153
154
155 # see RFC 4880 section 5.2.3.23
156 my $revocation_reasons = { no_reason_specified => 0,
157                            key_superseded => 1,
158                            key_compromised => 2,
159                            key_retired => 3,
160                            user_id_no_longer_valid => 32,
161                          };
162
163 # see RFC 4880 section 5.2.3.1
164 my $subpacket_types = { sig_creation_time => 2,
165                         sig_expiration_time => 3,
166                         exportable => 4,
167                         trust_sig => 5,
168                         regex => 6,
169                         revocable => 7,
170                         key_expiration_time => 9,
171                         preferred_cipher => 11,
172                         revocation_key => 12,
173                         issuer => 16,
174                         notation => 20,
175                         preferred_digest => 21,
176                         preferred_compression => 22,
177                         keyserver_prefs => 23,
178                         preferred_keyserver => 24,
179                         primary_uid => 25,
180                         policy_uri => 26,
181                         usage_flags => 27,
182                         signers_uid => 28,
183                         revocation_reason => 29,
184                         features => 30,
185                         signature_target => 31,
186                         embedded_signature => 32,
187                        };
188
189 # bitstring (see RFC 4880 section 5.2.3.24)
190 my $features = { mdc => 0x01
191                };
192
193 # bitstring (see RFC 4880 5.2.3.17)
194 my $keyserver_prefs = { nomodify => 0x80
195                       };
196
197 ###### end lookup tables ######
198
199 # FIXME: if we want to be able to interpret openpgp data as well as
200 # produce it, we need to produce key/value-swapped lookup tables as well.
201
202
203 ########### Math/Utility Functions ##############
204
205
206 # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
207 sub simple_checksum {
208   my $bytes = shift;
209
210   return unpack("%16C*",$bytes);
211 }
212
213 # calculate the multiplicative inverse of a mod b this is euclid's
214 # extended algorithm.  For more information see:
215 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
216 # arguments here should be Crypt::OpenSSL::Bignum objects.  $a should
217 # be the larger of the two values, and the two values should be
218 # coprime.
219
220 sub modular_multi_inverse {
221   my $a = shift;
222   my $b = shift;
223
224
225   my $origdivisor = $b->copy();
226
227   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
228   my $x = Crypt::OpenSSL::Bignum->zero();
229   my $y = Crypt::OpenSSL::Bignum->one();
230   my $lastx = Crypt::OpenSSL::Bignum->one();
231   my $lasty = Crypt::OpenSSL::Bignum->zero();
232
233   my $finalquotient;
234   my $finalremainder;
235
236   while (! $b->is_zero()) {
237     my ($quotient, $remainder) = $a->div($b, $ctx);
238
239     $a = $b;
240     $b = $remainder;
241
242     my $temp = $x;
243     $x = $lastx->sub($quotient->mul($x, $ctx));
244     $lastx = $temp;
245
246     $temp = $y;
247     $y = $lasty->sub($quotient->mul($y, $ctx));
248     $lasty = $temp;
249   }
250
251   if (!$a->is_one()) {
252     die "did this math wrong.\n";
253   }
254
255   # let's make sure that we return a positive value because RFC 4880,
256   # section 3.2 only allows unsigned values:
257
258   ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
259
260   return $finalremainder;
261 }
262
263
264 ############ OpenPGP formatting functions ############
265
266 # make an old-style packet out of the given packet type and body.
267 # old-style  (see RFC 4880 section 4.2)
268 sub make_packet {
269   my $type = shift;
270   my $body = shift;
271   my $options = shift;
272
273   my $len = length($body);
274   my $pseudolen = $len;
275
276   # if the caller wants to use at least N octets of packet length,
277   # pretend that we're using that many.
278   if (defined $options && defined $options->{'packet_length'}) {
279       $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
280   }
281   if ($pseudolen < $len) {
282       $pseudolen = $len;
283   }
284
285   my $lenbytes;
286   my $lencode;
287
288   if ($pseudolen < 2**8) {
289     $lenbytes = $old_format_packet_lengths->{one};
290     $lencode = 'C';
291   } elsif ($pseudolen < 2**16) {
292     $lenbytes = $old_format_packet_lengths->{two};
293     $lencode = 'n';
294   } elsif ($pseudolen < 2**31) {
295     ## not testing against full 32 bits because i don't want to deal
296     ## with potential overflow.
297     $lenbytes = $old_format_packet_lengths->{four};
298     $lencode = 'N';
299   } else {
300     ## what the hell do we do here?
301     $lenbytes = $old_format_packet_lengths->{indeterminate};
302     $lencode = '';
303   }
304
305   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
306     $body;
307 }
308
309
310 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
311 # (RFC 4880 section 3.2)
312 sub mpi_pack {
313   my $num = shift;
314
315   my $val = $num->to_bin();
316   my $mpilen = length($val)*8;
317
318 # this is a kludgy way to get the number of significant bits in the
319 # first byte:
320   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
321
322   $mpilen -= (8 - $bitsinfirstbyte);
323
324   return pack('n', $mpilen).$val;
325 }
326
327 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
328 # for an OpenSSH-style public key format.  see:
329 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
330 sub openssh_mpi_pack {
331   my $num = shift;
332
333   my $val = $num->to_bin();
334   my $mpilen = length($val);
335
336   my $ret = pack('N', $mpilen);
337
338   # if the first bit of the leading byte is high, we should include a
339   # 0 byte:
340   if (ord($val) & 0x80) {
341     $ret = pack('NC', $mpilen+1, 0);
342   }
343
344   return $ret.$val;
345 }
346
347 sub openssh_pubkey_pack {
348   my $key = shift;
349
350   my ($modulus, $exponent) = $key->get_key_parameters();
351
352   return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
353       openssh_mpi_pack($exponent).
354         openssh_mpi_pack($modulus);
355 }
356
357 # pull an OpenPGP-specified MPI off of a given stream, returning it as
358 # a Crypt::OpenSSL::Bignum.
359 sub read_mpi {
360   my $instr = shift;
361   my $readtally = shift;
362
363   my $bitlen;
364   read($instr, $bitlen, 2) or die "could not read MPI length.\n";
365   $bitlen = unpack('n', $bitlen);
366   $$readtally += 2;
367
368   my $bytestoread = POSIX::floor(($bitlen + 7)/8);
369   my $ret;
370   read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
371   $$readtally += $bytestoread;
372   return Crypt::OpenSSL::Bignum->new_from_bin($ret);
373 }
374
375
376 # FIXME: genericize these to accept either RSA or DSA keys:
377 sub make_rsa_pub_key_body {
378   my $key = shift;
379   my $key_timestamp = shift;
380
381   my ($n, $e) = $key->get_key_parameters();
382
383   return
384     pack('CN', 4, $key_timestamp).
385       pack('C', $asym_algos->{rsa}).
386         mpi_pack($n).
387           mpi_pack($e);
388 }
389
390 sub make_rsa_sec_key_body {
391   my $key = shift;
392   my $key_timestamp = shift;
393
394   # we're not using $a and $b, but we need them to get to $c.
395   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
396
397   my $c3 = modular_multi_inverse($p, $q);
398
399   my $secret_material = mpi_pack($d).
400     mpi_pack($p).
401       mpi_pack($q).
402         mpi_pack($c3);
403
404   # according to Crypt::OpenSSL::RSA, the closest value we can get out
405   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
406   # RFC 4880, we're actually looking for u, the multiplicative inverse
407   # of p, mod q.  This is why we're calculating the value directly
408   # with modular_multi_inverse.
409
410   return
411     pack('CN', 4, $key_timestamp).
412       pack('C', $asym_algos->{rsa}).
413         mpi_pack($n).
414           mpi_pack($e).
415             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
416               $secret_material.
417                 pack('n', simple_checksum($secret_material));
418 }
419
420 # expects an RSA key (public or private) and a timestamp
421 sub fingerprint {
422   my $key = shift;
423   my $key_timestamp = shift;
424
425   my $rsabody = make_rsa_pub_key_body($key, $key_timestamp);
426
427   return Digest::SHA::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
428 }
429
430
431 # FIXME: handle DSA keys as well!
432 sub pem2openpgp {
433   my $rsa = shift;
434   my $uid = shift;
435   my $args = shift;
436
437   # strong assertion of identity is the default (for a self-sig):
438   if (! defined $args->{certification_type}) {
439     $args->{certification_type} = $sig_types->{positive_certification};
440   }
441
442   if (! defined $args->{sig_timestamp}) {
443     $args->{sig_timestamp} = time();
444   }
445   if (! defined $args->{key_timestamp}) {
446     $args->{key_timestamp} = $args->{sig_timestamp} + 0;
447   }
448   my $key_timestamp = $args->{key_timestamp};
449
450   # generate and aggregate subpackets:
451
452   # key usage flags:
453   my $flags = 0;
454   if (! defined $args->{usage_flags}) {
455     $flags = $usage_flags->{certify};
456   } else {
457     my @ff = split(",", $args->{usage_flags});
458     foreach my $f (@ff) {
459       if (! defined $usage_flags->{$f}) {
460         die "No such flag $f";
461       }
462       $flags |= $usage_flags->{$f};
463     }
464   }
465   my $usage_subpacket = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
466
467   # how should we determine how far off to set the expiration date?
468   # default is no expiration.  Specify the timestamp in seconds from the
469   # key creation.
470   my $expiration_subpacket = '';
471   if (defined $args->{expiration}) {
472     my $expires_in = $args->{expiration} + 0;
473     $expiration_subpacket = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
474   }
475
476
477   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
478   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
479                             $ciphers->{aes256},
480                             $ciphers->{aes192},
481                             $ciphers->{aes128},
482                             $ciphers->{cast5},
483                             $ciphers->{tripledes}
484                            );
485
486   # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
487   my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
488                              $digests->{sha512},
489                              $digests->{sha384},
490                              $digests->{sha256},
491                              $digests->{sha224},
492                              $digests->{ripemd160},
493                              $digests->{sha1}
494                             );
495
496   # prefer ZLIB, BZip2, ZIP
497   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
498                             $zips->{zlib},
499                             $zips->{bzip2},
500                             $zips->{zip}
501                            );
502
503   # we support the MDC feature:
504   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
505                                $features->{mdc});
506
507   # keyserver preference: only owner modify (???):
508   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
509                             $keyserver_prefs->{nomodify});
510
511
512   $args->{hashed_subpackets} =
513       $usage_subpacket.
514         $expiration_subpacket.
515           $pref_sym_algos.
516             $pref_hash_algos.
517               $pref_zip_algos.
518                 $feature_subpacket.
519                   $keyserver_pref;
520
521   return
522     make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
523       make_packet($packet_types->{uid}, $uid).
524         gensig($rsa, $uid, $args);
525 }
526
527 # FIXME: handle non-RSA keys
528
529 # FIXME: this currently only makes self-sigs -- we should parameterize
530 # it to make certifications over keys other than the issuer.
531 sub gensig {
532   my $rsa = shift;
533   my $uid = shift;
534   my $args = shift;
535
536   # FIXME: allow signature creation using digests other than SHA256
537   $rsa->use_sha256_hash();
538
539   # see page 22 of RFC 4880 for why i think this is the right padding
540   # choice to use:
541   $rsa->use_pkcs1_padding();
542
543   if (! $rsa->check_key()) {
544     die "key does not check\n";
545   }
546
547   my $certtype = $args->{certification_type} + 0;
548
549   my $version = pack('C', 4);
550   my $sigtype = pack('C', $certtype);
551   # RSA
552   my $pubkey_algo = pack('C', $asym_algos->{rsa});
553   # SHA256 FIXME: allow signature creation using digests other than SHA256
554   my $hash_algo = pack('C', $digests->{sha256});
555
556   # FIXME: i'm worried about generating a bazillion new OpenPGP
557   # certificates from the same key, which could easily happen if you run
558   # this script more than once against the same key (because the
559   # timestamps will differ).  How can we prevent this?
560
561   # this argument (if set) overrides the current time, to
562   # be able to create a standard key.  If we read the key from a file
563   # instead of stdin, should we use the creation time on the file?
564   my $sig_timestamp = ($args->{sig_timestamp} + 0);
565   my $key_timestamp = ($args->{key_timestamp} + 0);
566
567   if ($key_timestamp > $sig_timestamp) {
568     die "key timestamp must not be later than signature timestamp\n";
569   }
570
571   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
572
573   my $hashed_subs = $creation_time_packet.$args->{hashed_subpackets};
574
575   my $subpacket_octets = pack('n', length($hashed_subs));
576
577   my $sig_data_to_be_hashed =
578     $version.
579       $sigtype.
580         $pubkey_algo.
581           $hash_algo.
582             $subpacket_octets.
583               $hashed_subs;
584
585   my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
586
587   # this is for signing.  it needs to be an old-style header with a
588   # 2-packet octet count.
589
590   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
591
592   # take the last 8 bytes of the fingerprint as the keyid:
593   my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
594
595   # the v4 signature trailer is:
596
597   # version number, literal 0xff, and then a 4-byte count of the
598   # signature data itself.
599   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
600
601   my $uid_data =
602     pack('CN', 0xb4, length($uid)).
603       $uid;
604
605   my $datatosign =
606     $key_data.
607       $uid_data.
608         $sig_data_to_be_hashed.
609           $trailer;
610
611   # FIXME: handle signatures over digests other than SHA256:
612   my $data_hash = Digest::SHA::sha256_hex($datatosign);
613
614   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
615
616   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
617
618   my $sig_body =
619     $sig_data_to_be_hashed.
620       pack('n', length($issuer_packet)).
621         $issuer_packet.
622           pack('n', hex(substr($data_hash, 0, 4))).
623             mpi_pack($sig);
624
625   return make_packet($packet_types->{sig}, $sig_body);
626 }
627
628 # FIXME: switch to passing the whole packet as the arg, instead of the
629 # input stream.
630
631 # FIXME: think about native perl representation of the packets instead.
632
633 # Put a user ID into the $data
634 sub finduid {
635   my $data = shift;
636   my $instr = shift;
637   my $tag = shift;
638   my $packetlen = shift;
639
640   my $dummy;
641   ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet\n";
642
643   read($instr, $dummy, $packetlen);
644   $data->{uid}->{$dummy} = {};
645   $data->{current}->{uid} = $dummy;
646 }
647
648
649 # find signatures associated with the given fingerprint and user ID.
650 sub findsig {
651   my $data = shift;
652   my $instr = shift;
653   my $tag = shift;
654   my $packetlen = shift;
655
656   ($tag == $packet_types->{sig}) or die "No calling findsig on anything other than a signature packet.\n";
657
658   my $dummy;
659   my $readbytes = 0;
660
661   read($instr, $dummy, $packetlen - $readbytes) or die "Could not read in this packet.\n";
662
663   if ((! defined $data->{key}) ||
664       (! defined $data->{uid}) ||
665       (! defined $data->{uid}->{$data->{target}->{uid}})) {
666     # the user ID we are looking for has not been found yet.
667     return;
668   }
669
670   # FIXME: if we get two primary keys on stdin, both with the same
671   # targetd user ID, we'll store signatures from both keys, which is
672   # probably wrong.
673
674   # the current ID is not what we're looking for:
675   return if ($data->{current}->{uid} ne $data->{target}->{uid});
676
677   # just storing the raw signatures for the moment:
678   push @{$data->{sigs}}, make_packet($packet_types->{sig}, $dummy);
679   return;
680
681 }
682
683 # given an input stream and data, store the found key in data and
684 # consume the rest of the stream corresponding to the packet.
685 # data contains: (fpr: fingerprint to find, key: current best guess at key)
686 sub findkey {
687   my $data = shift;
688   my $instr = shift;
689   my $tag = shift;
690   my $packetlen = shift;
691
692   my $dummy;
693   my $ver;
694   my $readbytes = 0;
695
696   read($instr, $ver, 1) or die "could not read key version\n";
697   $readbytes += 1;
698   $ver = ord($ver);
699
700   if ($ver != 4) {
701     printf(STDERR "We only work with version 4 keys.  This key appears to be version %s.\n", $ver);
702     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
703     return;
704   }
705
706   my $key_timestamp;
707   read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
708   $readbytes += 4;
709   $key_timestamp = unpack('N', $key_timestamp);
710
711   my $algo;
712   read($instr, $algo, 1) or die "could not read key algorithm.\n";
713   $readbytes += 1;
714   $algo = ord($algo);
715   if ($algo != $asym_algos->{rsa}) {
716     printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
717     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
718     return;
719   }
720
721   ## we have an RSA key.
722   my $modulus = read_mpi($instr, \$readbytes);
723   my $exponent = read_mpi($instr, \$readbytes);
724
725   my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
726   my $foundfpr = fingerprint($pubkey, $key_timestamp);
727
728   my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
729   # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
730   $foundfprstr = sprintf("%040s", $foundfprstr);
731
732   # is this a match?
733   if ((!defined($data->{target}->{fpr})) ||
734       (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
735     if (defined($data->{key})) {
736       die "Found two matching keys.\n";
737     }
738     $data->{key} = { 'rsa' => $pubkey,
739                      'timestamp' => $key_timestamp };
740   }
741
742   if ($tag != $packet_types->{seckey} &&
743       $tag != $packet_types->{sec_subkey}) {
744     if ($readbytes < $packetlen) {
745       read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
746     }
747     return;
748   }
749   if (!defined($data->{key})) {
750     # we don't think the public part of this key matches
751     if ($readbytes < $packetlen) {
752       read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
753     }
754     return;
755   }
756
757   my $s2k;
758   read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
759   $readbytes += 1;
760   $s2k = ord($s2k);
761   if ($s2k != 0) {
762     printf(STDERR "We cannot handle encrypted secret keys.  Skipping!\n") ;
763     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
764     return;
765   }
766
767   # secret material is unencrypted
768   # see http://tools.ietf.org/html/rfc4880#section-5.5.3
769   my $d = read_mpi($instr, \$readbytes);
770   my $p = read_mpi($instr, \$readbytes);
771   my $q = read_mpi($instr, \$readbytes);
772   my $u = read_mpi($instr, \$readbytes);
773
774   my $checksum;
775   read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
776   $readbytes += 2;
777   $checksum = unpack('n', $checksum);
778
779   # FIXME: compare with the checksum!  how?  the data is
780   # gone into the Crypt::OpenSSL::Bignum
781
782   $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
783                                                                      $exponent,
784                                                                      $d,
785                                                                      $p,
786                                                                      $q);
787
788   $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
789
790   if ($readbytes < $packetlen) {
791     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
792   }
793 }
794
795 sub openpgp2rsa {
796   my $instr = shift;
797   my $fpr = shift;
798
799   if (defined $fpr) {
800     if (length($fpr) < 8) {
801       die "We need at least 8 hex digits of fingerprint.\n";
802     }
803     $fpr = uc($fpr);
804   }
805
806   my $data = { 'fpr' => $fpr};
807   my $subs = { $packet_types->{pubkey} => \&findkey,
808                $packet_types->{pub_subkey} => \&findkey,
809                $packet_types->{seckey} => \&findkey,
810                $packet_types->{sec_subkey} => \&findkey };
811
812   packetwalk($instr, $subs, $data);
813
814   return $data->{key}->{rsa};
815 }
816
817 sub revokeuserid {
818   my $instr = shift;
819   my $fpr = shift;
820   my $uid = shift;
821   my $sigtime = shift;
822
823   if ((! defined $fpr) ||
824       (length($fpr) < 8)) {
825     die "We need at least 8 hex digits of fingerprint.\n";
826   }
827
828   $fpr = uc($fpr);
829
830   if (! defined $uid) {
831     die "No User ID defined.\n";
832   }
833
834   my $data = { target => { fpr => $fpr,
835                            uid => $uid,
836                          },
837              };
838   my $subs = { $packet_types->{seckey} => \&findkey,
839                $packet_types->{uid} => \&finduid,
840                $packet_types->{sig} => \&findsig,
841              };
842
843   packetwalk($instr, $subs, $data);
844
845   if ((! defined $data->{uid}) ||
846       (! defined $data->{uid}->{$uid})) {
847     die "The User ID \"$uid\" is not associated with this key";
848   }
849
850   if ((! defined $data->{key}) ||
851       (! defined $data->{key}->{rsa}) ||
852       (! defined $data->{key}->{timestamp})) {
853     die "The key requested was not found."
854   }
855
856   my $revocation_reason = 'No longer using this hostname';
857   if (defined $data->{revocation_reason}) {
858     $revocation_reason = $data->{revocation_reason};
859   }
860
861   my $rev_reason_subpkt = prefixsubpacket(pack('CC',
862                                                $subpacket_types->{revocation_reason},
863                                                $revocation_reasons->{user_id_no_longer_valid}).
864                                           $revocation_reason);
865
866   if (! defined $sigtime) {
867     $sigtime = time();
868   }
869   # what does a signature like this look like?
870   my $args = { key_timestamp => $data->{key}->{timestamp},
871                sig_timestamp => $sigtime,
872                certification_type => $sig_types->{certification_revocation},
873                hashed_subpackets => $rev_reason_subpkt,
874              };
875
876   return
877     make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
878       make_packet($packet_types->{uid}, $uid).
879         join('', @{$data->{sigs}}).
880           gensig($data->{key}->{rsa}, $uid, $args);
881 }
882
883
884 # see 5.2.3.1 for tips on how to calculate the length of a subpacket:
885 sub prefixsubpacket {
886   my $subpacket = shift;
887
888   my $len = length($subpacket);
889   my $prefix;
890   use bytes;
891   if ($len < 192) {
892     # one byte:
893     $prefix = pack('C', $len);
894   } elsif ($len < 16576) {
895     my $in = $len - 192;
896     my $second = $in%256;
897     my $first = ($in - $second)>>8;
898     $prefix = pack('CC', $first + 192, $second)
899   } else {
900     $prefix = pack('CN', 255, $len);
901   }
902   return $prefix.$subpacket;
903 }
904
905
906
907 sub packetwalk {
908   my $instr = shift;
909   my $subs = shift;
910   my $data = shift;
911
912   my $packettag;
913   my $dummy;
914   my $tag;
915
916   while (! eof($instr)) {
917     read($instr, $packettag, 1);
918     $packettag = ord($packettag);
919
920     my $packetlen;
921     if ( ! (0x80 & $packettag)) {
922       die "This is not an OpenPGP packet\n";
923     }
924     if (0x40 & $packettag) {
925       # this is a new-format packet.
926       $tag = (0x3f & $packettag);
927       my $nextlen = 0;
928       read($instr, $nextlen, 1);
929       $nextlen = ord($nextlen);
930       if ($nextlen < 192) {
931         $packetlen = $nextlen;
932       } elsif ($nextlen < 224) {
933         my $newoct;
934         read($instr, $newoct, 1);
935         $newoct = ord($newoct);
936         $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
937       } elsif ($nextlen == 255) {
938         read($instr, $nextlen, 4);
939         $packetlen = unpack('N', $nextlen);
940       } else {
941         # packet length is undefined.
942       }
943     } else {
944       # this is an old-format packet.
945       my $lentype;
946       $lentype = 0x03 & $packettag;
947       $tag = ( 0x3c & $packettag ) >> 2;
948       if ($lentype == 0) {
949         read($instr, $packetlen, 1) or die "could not read packet length\n";
950         $packetlen = unpack('C', $packetlen);
951       } elsif ($lentype == 1) {
952         read($instr, $packetlen, 2) or die "could not read packet length\n";
953         $packetlen = unpack('n', $packetlen);
954       } elsif ($lentype == 2) {
955         read($instr, $packetlen, 4) or die "could not read packet length\n";
956         $packetlen = unpack('N', $packetlen);
957       } else {
958         # packet length is undefined.
959       }
960     }
961
962     if (! defined($packetlen)) {
963       die "Undefined packet lengths are not supported.\n";
964     }
965
966     if (defined $subs->{$tag}) {
967       $subs->{$tag}($data, $instr, $tag, $packetlen);
968     } else {
969       read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
970     }
971   }
972
973   return $data->{key};
974 }
975
976
977 for (basename($0)) {
978   if (/^pem2openpgp$/) {
979     my $rsa;
980     my $stdin;
981
982     my $uid = shift;
983     defined($uid) or die "You must specify a user ID string.\n";
984
985     # FIXME: fail if there is no given user ID; or should we default to
986     # hostname_long() from Sys::Hostname::Long ?
987
988     if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
989       $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
990     } else {
991       $stdin = do {
992         local $/; # slurp!
993         <STDIN>;
994       };
995
996       $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
997     }
998
999     print pem2openpgp($rsa,
1000                       $uid,
1001                       { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
1002                         key_timestamp => $ENV{PEM2OPENPGP_KEY_TIMESTAMP},
1003                         expiration => $ENV{PEM2OPENPGP_EXPIRATION},
1004                         usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
1005                       }
1006                      );
1007   }
1008   elsif (/^openpgp2ssh$/) {
1009       my $fpr = shift;
1010       my $instream;
1011       open($instream,'-');
1012       binmode($instream, ":bytes");
1013       my $key = openpgp2rsa($instream, $fpr);
1014       if (defined($key)) {
1015         if ($key->is_private()) {
1016           print $key->get_private_key_string();
1017         } else {
1018           print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
1019         }
1020       } else {
1021         die "No matching key found.\n";
1022       }
1023   }
1024   elsif (/^keytrans$/) {
1025     # subcommands when keytrans is invoked directly are UNSUPPORTED,
1026     # UNDOCUMENTED, and WILL NOT BE MAINTAINED.
1027     my $subcommand = shift;
1028     for ($subcommand) {
1029       if (/^revokeuserid$/) {
1030         my $fpr = shift;
1031         my $uid = shift;
1032         my $instream;
1033         open($instream,'-');
1034         binmode($instream, ":bytes");
1035
1036         my $revcert = revokeuserid($instream, $fpr, $uid, $ENV{KEYTRANS_REVSIG_TIMESTAMP});
1037
1038         print $revcert;
1039       } else {
1040         die "Unrecognized subcomand.  keytrans subcommands are not a stable interface!\n";
1041       }
1042     }
1043   }
1044   else {
1045     die "Unrecognized keytrans call.\n";
1046   }
1047 }
1048