171a1f64a910c0035ebea864fded44bbbf840b42
[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.1
156 my $subpacket_types = { sig_creation_time => 2,
157                         sig_expiration_time => 3,
158                         exportable => 4,
159                         trust_sig => 5,
160                         regex => 6,
161                         revocable => 7,
162                         key_expiration_time => 9,
163                         preferred_cipher => 11,
164                         revocation_key => 12,
165                         issuer => 16,
166                         notation => 20,
167                         preferred_digest => 21,
168                         preferred_compression => 22,
169                         keyserver_prefs => 23,
170                         preferred_keyserver => 24,
171                         primary_uid => 25,
172                         policy_uri => 26,
173                         usage_flags => 27,
174                         signers_uid => 28,
175                         revocation_reason => 29,
176                         features => 30,
177                         signature_target => 31,
178                         embedded_signature => 32,
179                        };
180
181 # bitstring (see RFC 4880 section 5.2.3.24)
182 my $features = { mdc => 0x01
183                };
184
185 # bitstring (see RFC 4880 5.2.3.17)
186 my $keyserver_prefs = { nomodify => 0x80
187                       };
188
189 ###### end lookup tables ######
190
191 # FIXME: if we want to be able to interpret openpgp data as well as
192 # produce it, we need to produce key/value-swapped lookup tables as well.
193
194
195 ########### Math/Utility Functions ##############
196
197
198 # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
199 sub simple_checksum {
200   my $bytes = shift;
201
202   return unpack("%16C*",$bytes);
203 }
204
205 # calculate the multiplicative inverse of a mod b this is euclid's
206 # extended algorithm.  For more information see:
207 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
208 # arguments here should be Crypt::OpenSSL::Bignum objects.  $a should
209 # be the larger of the two values, and the two values should be
210 # coprime.
211
212 sub modular_multi_inverse {
213   my $a = shift;
214   my $b = shift;
215
216
217   my $origdivisor = $b->copy();
218
219   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
220   my $x = Crypt::OpenSSL::Bignum->zero();
221   my $y = Crypt::OpenSSL::Bignum->one();
222   my $lastx = Crypt::OpenSSL::Bignum->one();
223   my $lasty = Crypt::OpenSSL::Bignum->zero();
224
225   my $finalquotient;
226   my $finalremainder;
227
228   while (! $b->is_zero()) {
229     my ($quotient, $remainder) = $a->div($b, $ctx);
230
231     $a = $b;
232     $b = $remainder;
233
234     my $temp = $x;
235     $x = $lastx->sub($quotient->mul($x, $ctx));
236     $lastx = $temp;
237
238     $temp = $y;
239     $y = $lasty->sub($quotient->mul($y, $ctx));
240     $lasty = $temp;
241   }
242
243   if (!$a->is_one()) {
244     die "did this math wrong.\n";
245   }
246
247   # let's make sure that we return a positive value because RFC 4880,
248   # section 3.2 only allows unsigned values:
249
250   ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
251
252   return $finalremainder;
253 }
254
255
256 ############ OpenPGP formatting functions ############
257
258 # make an old-style packet out of the given packet type and body.
259 # old-style  (see RFC 4880 section 4.2)
260 sub make_packet {
261   my $type = shift;
262   my $body = shift;
263   my $options = shift;
264
265   my $len = length($body);
266   my $pseudolen = $len;
267
268   # if the caller wants to use at least N octets of packet length,
269   # pretend that we're using that many.
270   if (defined $options && defined $options->{'packet_length'}) {
271       $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
272   }
273   if ($pseudolen < $len) {
274       $pseudolen = $len;
275   }
276
277   my $lenbytes;
278   my $lencode;
279
280   if ($pseudolen < 2**8) {
281     $lenbytes = $old_format_packet_lengths->{one};
282     $lencode = 'C';
283   } elsif ($pseudolen < 2**16) {
284     $lenbytes = $old_format_packet_lengths->{two};
285     $lencode = 'n';
286   } elsif ($pseudolen < 2**31) {
287     ## not testing against full 32 bits because i don't want to deal
288     ## with potential overflow.
289     $lenbytes = $old_format_packet_lengths->{four};
290     $lencode = 'N';
291   } else {
292     ## what the hell do we do here?
293     $lenbytes = $old_format_packet_lengths->{indeterminate};
294     $lencode = '';
295   }
296
297   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
298     $body;
299 }
300
301
302 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
303 # (RFC 4880 section 3.2)
304 sub mpi_pack {
305   my $num = shift;
306
307   my $val = $num->to_bin();
308   my $mpilen = length($val)*8;
309
310 # this is a kludgy way to get the number of significant bits in the
311 # first byte:
312   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
313
314   $mpilen -= (8 - $bitsinfirstbyte);
315
316   return pack('n', $mpilen).$val;
317 }
318
319 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
320 # for an OpenSSH-style public key format.  see:
321 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
322 sub openssh_mpi_pack {
323   my $num = shift;
324
325   my $val = $num->to_bin();
326   my $mpilen = length($val);
327
328   my $ret = pack('N', $mpilen);
329
330   # if the first bit of the leading byte is high, we should include a
331   # 0 byte:
332   if (ord($val) & 0x80) {
333     $ret = pack('NC', $mpilen+1, 0);
334   }
335
336   return $ret.$val;
337 }
338
339 sub openssh_pubkey_pack {
340   my $key = shift;
341
342   my ($modulus, $exponent) = $key->get_key_parameters();
343
344   return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
345       openssh_mpi_pack($exponent).
346         openssh_mpi_pack($modulus);
347 }
348
349 # pull an OpenPGP-specified MPI off of a given stream, returning it as
350 # a Crypt::OpenSSL::Bignum.
351 sub read_mpi {
352   my $instr = shift;
353   my $readtally = shift;
354
355   my $bitlen;
356   read($instr, $bitlen, 2) or die "could not read MPI length.\n";
357   $bitlen = unpack('n', $bitlen);
358   $$readtally += 2;
359
360   my $bytestoread = POSIX::floor(($bitlen + 7)/8);
361   my $ret;
362   read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
363   $$readtally += $bytestoread;
364   return Crypt::OpenSSL::Bignum->new_from_bin($ret);
365 }
366
367
368 # FIXME: genericize these to accept either RSA or DSA keys:
369 sub make_rsa_pub_key_body {
370   my $key = shift;
371   my $key_timestamp = shift;
372
373   my ($n, $e) = $key->get_key_parameters();
374
375   return
376     pack('CN', 4, $key_timestamp).
377       pack('C', $asym_algos->{rsa}).
378         mpi_pack($n).
379           mpi_pack($e);
380 }
381
382 sub make_rsa_sec_key_body {
383   my $key = shift;
384   my $key_timestamp = shift;
385
386   # we're not using $a and $b, but we need them to get to $c.
387   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
388
389   my $c3 = modular_multi_inverse($p, $q);
390
391   my $secret_material = mpi_pack($d).
392     mpi_pack($p).
393       mpi_pack($q).
394         mpi_pack($c3);
395
396   # according to Crypt::OpenSSL::RSA, the closest value we can get out
397   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
398   # RFC 4880, we're actually looking for u, the multiplicative inverse
399   # of p, mod q.  This is why we're calculating the value directly
400   # with modular_multi_inverse.
401
402   return
403     pack('CN', 4, $key_timestamp).
404       pack('C', $asym_algos->{rsa}).
405         mpi_pack($n).
406           mpi_pack($e).
407             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
408               $secret_material.
409                 pack('n', simple_checksum($secret_material));
410 }
411
412 # expects an RSA key (public or private) and a timestamp
413 sub fingerprint {
414   my $key = shift;
415   my $key_timestamp = shift;
416
417   my $rsabody = make_rsa_pub_key_body($key, $key_timestamp);
418
419   return Digest::SHA::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
420 }
421
422
423 # FIXME: handle DSA keys as well!
424 sub pem2openpgp {
425   my $rsa = shift;
426   my $uid = shift;
427   my $args = shift;
428
429   # strong assertion of identity is the default (for a self-sig):
430   if (! defined $args->{certification_type}) {
431     $args->{certification_type} = $sig_types->{positive_certification};
432   }
433
434   if (! defined $args->{sig_timestamp}) {
435     $args->{sig_timestamp} = time();
436   }
437   if (! defined $args->{key_timestamp}) {
438     $args->{key_timestamp} = $args->{sig_timestamp} + 0;
439   }
440   my $key_timestamp = $args->{key_timestamp};
441
442   # generate and aggregate subpackets:
443
444   # key usage flags:
445   my $flags = 0;
446   if (! defined $args->{usage_flags}) {
447     $flags = $usage_flags->{certify};
448   } else {
449     my @ff = split(",", $args->{usage_flags});
450     foreach my $f (@ff) {
451       if (! defined $usage_flags->{$f}) {
452         die "No such flag $f";
453       }
454       $flags |= $usage_flags->{$f};
455     }
456   }
457   my $usage_subpacket = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
458
459   # how should we determine how far off to set the expiration date?
460   # default is no expiration.  Specify the timestamp in seconds from the
461   # key creation.
462   my $expiration_subpacket = '';
463   if (defined $args->{expiration}) {
464     my $expires_in = $args->{expiration} + 0;
465     $expiration_subpacket = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
466   }
467
468
469   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
470   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
471                             $ciphers->{aes256},
472                             $ciphers->{aes192},
473                             $ciphers->{aes128},
474                             $ciphers->{cast5},
475                             $ciphers->{tripledes}
476                            );
477
478   # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
479   my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
480                              $digests->{sha512},
481                              $digests->{sha384},
482                              $digests->{sha256},
483                              $digests->{sha224},
484                              $digests->{ripemd160},
485                              $digests->{sha1}
486                             );
487
488   # prefer ZLIB, BZip2, ZIP
489   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
490                             $zips->{zlib},
491                             $zips->{bzip2},
492                             $zips->{zip}
493                            );
494
495   # we support the MDC feature:
496   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
497                                $features->{mdc});
498
499   # keyserver preference: only owner modify (???):
500   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
501                             $keyserver_prefs->{nomodify});
502
503
504   $args->{hashed_subpackets} =
505       $usage_subpacket.
506         $expiration_subpacket.
507           $pref_sym_algos.
508             $pref_hash_algos.
509               $pref_zip_algos.
510                 $feature_subpacket.
511                   $keyserver_pref;
512
513   return
514     make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
515       make_packet($packet_types->{uid}, $uid).
516         gensig($rsa, $uid, $args);
517 }
518
519 # FIXME: handle non-RSA keys
520
521 # FIXME: this currently only makes self-sigs -- we should parameterize
522 # it to make certifications over keys other than the issuer.
523 sub gensig {
524   my $rsa = shift;
525   my $uid = shift;
526   my $args = shift;
527
528   # FIXME: allow signature creation using digests other than SHA256
529   $rsa->use_sha256_hash();
530
531   # see page 22 of RFC 4880 for why i think this is the right padding
532   # choice to use:
533   $rsa->use_pkcs1_padding();
534
535   if (! $rsa->check_key()) {
536     die "key does not check";
537   }
538
539   my $certtype = $args->{certification_type} + 0;
540
541   my $version = pack('C', 4);
542   my $sigtype = pack('C', $certtype);
543   # RSA
544   my $pubkey_algo = pack('C', $asym_algos->{rsa});
545   # SHA256 FIXME: allow signature creation using digests other than SHA256
546   my $hash_algo = pack('C', $digests->{sha256});
547
548   # FIXME: i'm worried about generating a bazillion new OpenPGP
549   # certificates from the same key, which could easily happen if you run
550   # this script more than once against the same key (because the
551   # timestamps will differ).  How can we prevent this?
552
553   # this argument (if set) overrides the current time, to
554   # be able to create a standard key.  If we read the key from a file
555   # instead of stdin, should we use the creation time on the file?
556   my $sig_timestamp = ($args->{sig_timestamp} + 0);
557   my $key_timestamp = ($args->{key_timestamp} + 0);
558
559   if ($key_timestamp > $sig_timestamp) {
560     die "key timestamp must not be later than signature timestamp";
561   }
562
563   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
564
565   my $hashed_subs = $creation_time_packet.$args->{hashed_subpackets};
566
567   my $subpacket_octets = pack('n', length($hashed_subs));
568
569   my $sig_data_to_be_hashed =
570     $version.
571       $sigtype.
572         $pubkey_algo.
573           $hash_algo.
574             $subpacket_octets.
575               $hashed_subs;
576
577   my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
578
579   # this is for signing.  it needs to be an old-style header with a
580   # 2-packet octet count.
581
582   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
583
584   # take the last 8 bytes of the fingerprint as the keyid:
585   my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
586
587   # the v4 signature trailer is:
588
589   # version number, literal 0xff, and then a 4-byte count of the
590   # signature data itself.
591   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
592
593   my $uid_data =
594     pack('CN', 0xb4, length($uid)).
595       $uid;
596
597   my $datatosign =
598     $key_data.
599       $uid_data.
600         $sig_data_to_be_hashed.
601           $trailer;
602
603
604   # FIXME: handle signatures over digests other than SHA256:
605   my $data_hash = Digest::SHA::sha256_hex($datatosign);
606
607   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
608
609   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
610
611   my $sig_body =
612     $sig_data_to_be_hashed.
613       pack('n', length($issuer_packet)).
614         $issuer_packet.
615           pack('n', hex(substr($data_hash, 0, 4))).
616             mpi_pack($sig);
617
618   return make_packet($packet_types->{sig}, $sig_body);
619 }
620
621 # FIXME: switch to passing the whole packet as the arg, instead of the
622 # input stream.
623
624 # FIXME: think about native perl representation of the packets instead.
625
626 # Put a user ID into the $data
627 sub finduid {
628   my $data = shift;
629   my $instr = shift;
630   my $tag = shift;
631   my $packetlen = shift;
632
633   my $dummy;
634   ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet";
635
636   read($instr, $dummy, $packetlen);
637   $data->{uid} = {} unless defined $data->{uid};
638   $data->{uid}->{$dummy} = {};
639 }
640
641
642 # find signatures associated with the given fingerprint and user ID.
643 sub findsig {
644   my $data = shift;
645   my $instr = shift;
646   my $tag = shift;
647   my $packetlen = shift;
648
649   ($tag == $packet_types->{sig}) or die "No calling findsig on anything other than a signature packet.";
650
651   my $dummy;
652   my $readbytes = 0;
653
654   if ((undef $data->{key}) ||
655       (undef $data->{uid}) ||
656       (undef $data->{uid}->{$data->{target}->{uid}})) {
657     # this is not the user ID we are looking for.
658     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
659   }
660
661   read($instr, $data, 6) or die "could not read signature header\n";
662   my ($ver, $sigtype, $pubkeyalgo, $digestalgo, $subpacketsize) = unpack('CCCCn', $data);
663   if ($ver != 4) {
664     printf(STDERR "We only work with version 4 signatures.");
665     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
666     return;
667   }
668   if ($pubkeyalgo != $asym_algos->{rsa}) {
669     printf(STDERR "We can only work with RSA at the moment");
670     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
671     return;
672   }
673   if ($sigtype != $sig_types->{positive_certification}) {
674     # FIXME: some weird implementations might have made generic,
675     # persona, or casual certifications instead of positive
676     # certifications for self-sigs.  Probably should handle them too.
677     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
678     return;
679   }
680
681   my $subpackets;
682   read($instr, $subpackets, $subpacketsize) or die "could not read hashed signature subpackets.\n";
683
684   read($instr, $subpacketsize, 2) or die "could not read unhashed signature subpacket size.\n";
685   $subpacketsize = unpack('n', $subpacketsize);
686
687   my $unhashedsubpackets;
688   read($instr, $unhashedsubpackets, $subpacketsize) or die "could not read unhashed signature subpackets.\n";
689
690   my $hashtail;
691   read($instr, $hashtail, 2) or die "could not read left 16 bits of digest.\n";
692
693   # FIXME: RSA signatures should read in how many MPIs?
694
695 }
696
697 # given an input stream and data, store the found key in data and
698 # consume the rest of the stream corresponding to the packet.
699 # data contains: (fpr: fingerprint to find, key: current best guess at key)
700 sub findkey {
701   my $data = shift;
702   my $instr = shift;
703   my $tag = shift;
704   my $packetlen = shift;
705
706   my $dummy;
707   my $ver;
708   my $readbytes = 0;
709
710   read($instr, $ver, 1) or die "could not read key version\n";
711   $readbytes += 1;
712   $ver = ord($ver);
713
714   if ($ver != 4) {
715     printf(STDERR "We only work with version 4 keys.  This key appears to be version %s.\n", $ver);
716     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
717     return;
718   }
719
720   my $key_timestamp;
721   read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
722   $readbytes += 4;
723   $key_timestamp = unpack('N', $key_timestamp);
724
725   my $algo;
726   read($instr, $algo, 1) or die "could not read key algorithm.\n";
727   $readbytes += 1;
728   $algo = ord($algo);
729   if ($algo != $asym_algos->{rsa}) {
730     printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
731     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
732     return;
733   }
734
735   ## we have an RSA key.
736   my $modulus = read_mpi($instr, \$readbytes);
737   my $exponent = read_mpi($instr, \$readbytes);
738
739   my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
740   my $foundfpr = fingerprint($pubkey, $key_timestamp);
741
742   my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
743   # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
744   $foundfprstr = sprintf("%040s", $foundfprstr);
745
746   # is this a match?
747   if ((!defined($data->{target}->{fpr})) ||
748       (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
749     if (defined($data->{key})) {
750       die "Found two matching keys.\n";
751     }
752     $data->{key} = { 'rsa' => $pubkey,
753                      'timestamp' => $key_timestamp };
754   }
755
756   if ($tag != $packet_types->{seckey} &&
757       $tag != $packet_types->{sec_subkey}) {
758     if ($readbytes < $packetlen) {
759       read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
760     }
761     return;
762   }
763   if (!defined($data->{key})) {
764     # we don't think the public part of this key matches
765     if ($readbytes < $packetlen) {
766       read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
767     }
768     return;
769   }
770
771   my $s2k;
772   read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
773   $readbytes += 1;
774   $s2k = ord($s2k);
775   if ($s2k != 0) {
776     printf(STDERR "We cannot handle encrypted secret keys.  Skipping!\n") ;
777     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
778     return;
779   }
780
781   # secret material is unencrypted
782   # see http://tools.ietf.org/html/rfc4880#section-5.5.3
783   my $d = read_mpi($instr, \$readbytes);
784   my $p = read_mpi($instr, \$readbytes);
785   my $q = read_mpi($instr, \$readbytes);
786   my $u = read_mpi($instr, \$readbytes);
787
788   my $checksum;
789   read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
790   $readbytes += 2;
791   $checksum = unpack('n', $checksum);
792
793   # FIXME: compare with the checksum!  how?  the data is
794   # gone into the Crypt::OpenSSL::Bignum
795
796   $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
797                                                                      $exponent,
798                                                                      $d,
799                                                                      $p,
800                                                                      $q);
801
802   $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
803
804   if ($readbytes < $packetlen) {
805     read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
806   }
807 }
808
809 sub openpgp2rsa {
810   my $instr = shift;
811   my $fpr = shift;
812
813   if (defined $fpr) {
814     if (length($fpr) < 8) {
815       die "We need at least 8 hex digits of fingerprint.\n";
816     }
817     $fpr = uc($fpr);
818   }
819
820   my $data = { 'fpr' => $fpr};
821   my $subs = { $packet_types->{pubkey} => \&findkey,
822                $packet_types->{pub_subkey} => \&findkey,
823                $packet_types->{seckey} => \&findkey,
824                $packet_types->{sec_subkey} => \&findkey };
825
826   packetwalk($instr, $subs, $data);
827
828   return $data->{key}->{rsa};
829 }
830
831 sub revokeuserid {
832   my $instr = shift;
833   my $fpr = shift;
834   my $uid = shift;
835
836   if ((! defined $fpr) ||
837       (length($fpr) < 8)) {
838     die "We need at least 8 hex digits of fingerprint.\n";
839   }
840
841   $fpr = uc($fpr);
842
843   if (! defined $uid) {
844     die "No User ID defined.\n";
845   }
846
847   my $data = { target => { fpr => $fpr,
848                          },
849              };
850   my $subs = { $packet_types->{seckey} => \&findkey,
851                $packet_types->{uid} => \&finduid
852              };
853
854   packetwalk($instr, $subs, $data);
855
856   if ((! defined $data->{uid}) ||
857       (! defined $data->{uid}->{$uid})) {
858     die "The User ID \"$uid\" is not associated with this key";
859   }
860
861   if ((! defined $data->{key}) ||
862       (! defined $data->{key}->{rsa}) ||
863       (! defined $data->{key}->{timestamp})) {
864     die "The key requested was not found."
865   }
866
867   # what does a signature like this look like?
868
869   return 'abc';
870 }
871
872
873
874 sub packetwalk {
875   my $instr = shift;
876   my $subs = shift;
877   my $data = shift;
878
879   my $packettag;
880   my $dummy;
881   my $tag;
882
883   while (! eof($instr)) {
884     read($instr, $packettag, 1);
885     $packettag = ord($packettag);
886
887     my $packetlen;
888     if ( ! (0x80 & $packettag)) {
889       die "This is not an OpenPGP packet\n";
890     }
891     if (0x40 & $packettag) {
892       # this is a new-format packet.
893       $tag = (0x3f & $packettag);
894       my $nextlen = 0;
895       read($instr, $nextlen, 1);
896       $nextlen = ord($nextlen);
897       if ($nextlen < 192) {
898         $packetlen = $nextlen;
899       } elsif ($nextlen < 224) {
900         my $newoct;
901         read($instr, $newoct, 1);
902         $newoct = ord($newoct);
903         $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
904       } elsif ($nextlen == 255) {
905         read($instr, $nextlen, 4);
906         $packetlen = unpack('N', $nextlen);
907       } else {
908         # packet length is undefined.
909       }
910     } else {
911       # this is an old-format packet.
912       my $lentype;
913       $lentype = 0x03 & $packettag;
914       $tag = ( 0x3c & $packettag ) >> 2;
915       if ($lentype == 0) {
916         read($instr, $packetlen, 1) or die "could not read packet length\n";
917         $packetlen = unpack('C', $packetlen);
918       } elsif ($lentype == 1) {
919         read($instr, $packetlen, 2) or die "could not read packet length\n";
920         $packetlen = unpack('n', $packetlen);
921       } elsif ($lentype == 2) {
922         read($instr, $packetlen, 4) or die "could not read packet length\n";
923         $packetlen = unpack('N', $packetlen);
924       } else {
925         # packet length is undefined.
926       }
927     }
928
929     if (! defined($packetlen)) {
930       die "Undefined packet lengths are not supported.\n";
931     }
932
933     if (defined $subs->{$tag}) {
934       $subs->{$tag}($data, $instr, $tag, $packetlen);
935     } else {
936       read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
937     }
938   }
939
940   return $data->{key};
941 }
942
943
944 for (basename($0)) {
945   if (/^pem2openpgp$/) {
946     my $rsa;
947     my $stdin;
948
949     my $uid = shift;
950     defined($uid) or die "You must specify a user ID string.\n";
951
952     # FIXME: fail if there is no given user ID; or should we default to
953     # hostname_long() from Sys::Hostname::Long ?
954
955     if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
956       $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
957     } else {
958       $stdin = do {
959         local $/; # slurp!
960         <STDIN>;
961       };
962
963       $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
964     }
965
966     print pem2openpgp($rsa,
967                       $uid,
968                       { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
969                         key_timestamp => $ENV{PEM2OPENPGP_KEY_TIMESTAMP},
970                         expiration => $ENV{PEM2OPENPGP_EXPIRATION},
971                         usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
972                       }
973                      );
974   }
975   elsif (/^openpgp2ssh$/) {
976       my $fpr = shift;
977       my $instream;
978       open($instream,'-');
979       binmode($instream, ":bytes");
980       my $key = openpgp2rsa($instream, $fpr);
981       if (defined($key)) {
982         if ($key->is_private()) {
983           print $key->get_private_key_string();
984         } else {
985           print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
986         }
987       } else {
988         die "No matching key found.\n";
989       }
990   }
991   elsif (/^revokeuserid$/) {
992     my $fpr = shift;
993     my $uid = shift;
994     my $instream;
995     open($instream,'-');
996     binmode($instream, ":bytes");
997
998     my $revcert = revokeuserid($instream, $fpr, $uid);
999
1000     print $revcert;
1001   }
1002   else {
1003     die "Unrecognized keytrans call.\n";
1004   }
1005 }
1006