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