40188c7ab64dbb7b9224ffd4e50de376dd97bc7d
[monkeysphere.git] / src / keytrans / pem2openpgp
1 #!/usr/bin/perl -w -T
2
3 # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
4 # User ID as the first argument, and generate an OpenPGP secret key
5 # and certificate from it.
6
7 # WARNING: the secret key material *will* appear on stdout (albeit in
8 # OpenPGP form) -- if you redirect stdout to a file, make sure the
9 # permissions on that file are appropriately locked down!
10
11 # Usage:
12
13 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
14
15 # Authors:
16 #  Jameson Rollins <jrollins@finestructure.net>
17 #  Daniel Kahn Gillmor <dkg@fifthhorseman.net>
18
19 # Started on: 2009-01-07 02:01:19-0500
20
21 # License: GPL v3 or later (we may need to adjust this given that this
22 # connects to OpenSSL via perl)
23
24 use strict;
25 use warnings;
26 use File::Basename;
27 use Crypt::OpenSSL::RSA;
28 use Crypt::OpenSSL::Bignum;
29 use Crypt::OpenSSL::Bignum::CTX;
30 use Digest::SHA1;
31 use MIME::Base64;
32
33 ## make sure all length() and substr() calls use bytes only:
34 use bytes;
35
36 my $old_format_packet_lengths = { one => 0,
37                                   two => 1,
38                                   four => 2,
39                                   indeterminate => 3,
40 };
41
42 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
43 my $asym_algos = { rsa => 1,
44                    elgamal => 16,
45                    dsa => 17,
46                    };
47
48 # see RFC 4880 section 9.2
49 my $ciphers = { plaintext => 0,
50                 idea => 1,
51                 tripledes => 2,
52                 cast5 => 3,
53                 blowfish => 4,
54                 aes128 => 7,
55                 aes192 => 8,
56                 aes256 => 9,
57                 twofish => 10,
58               };
59
60 # see RFC 4880 section 9.3
61 my $zips = { uncompressed => 0,
62              zip => 1,
63              zlib => 2,
64              bzip2 => 3,
65            };
66
67 # see RFC 4880 section 9.4
68 my $digests = { md5 => 1,
69                 sha1 => 2,
70                 ripemd160 => 3,
71                 sha256 => 8,
72                 sha384 => 9,
73                 sha512 => 10,
74                 sha224 => 11,
75               };
76
77 # see RFC 4880 section 5.2.3.21
78 my $usage_flags = { certify => 0x01,
79                     sign => 0x02,
80                     encrypt_comms => 0x04,
81                     encrypt_storage => 0x08,
82                     encrypt => 0x0c, ## both comms and storage
83                     split => 0x10, # the private key is split via secret sharing
84                     authenticate => 0x20,
85                     shared => 0x80, # more than one person holds the entire private key
86                   };
87
88 # see RFC 4880 section 4.3
89 my $packet_types = { pubkey_enc_session => 1,
90                      sig => 2,
91                      symkey_enc_session => 3,
92                      onepass_sig => 4,
93                      seckey => 5,
94                      pubkey => 6,
95                      sec_subkey => 7,
96                      compressed_data => 8,
97                      symenc_data => 9,
98                      marker => 10,
99                      literal => 11,
100                      trust => 12,
101                      uid => 13,
102                      pub_subkey => 14,
103                      uat => 17,
104                      symenc_w_integrity => 18,
105                      mdc => 19,
106                    };
107
108 # see RFC 4880 section 5.2.1
109 my $sig_types = { binary_doc => 0x00,
110                   text_doc => 0x01,
111                   standalone => 0x02,
112                   generic_certification => 0x10,
113                   persona_certification => 0x11,
114                   casual_certification => 0x12,
115                   positive_certification => 0x13,
116                   subkey_binding => 0x18,
117                   primary_key_binding => 0x19,
118                   key_signature => 0x1f,
119                   key_revocation => 0x20,
120                   subkey_revocation => 0x28,
121                   certification_revocation => 0x30,
122                   timestamp => 0x40,
123                   thirdparty => 0x50,
124                 };
125
126
127 # see RFC 4880 section 5.2.3.1
128 my $subpacket_types = { sig_creation_time => 2,
129                         sig_expiration_time => 3,
130                         exportable => 4,
131                         trust_sig => 5,
132                         regex => 6,
133                         revocable => 7,
134                         key_expiration_time => 9,
135                         preferred_cipher => 11,
136                         revocation_key => 12,
137                         issuer => 16,
138                         notation => 20,
139                         preferred_digest => 21,
140                         preferred_compression => 22,
141                         keyserver_prefs => 23,
142                         preferred_keyserver => 24,
143                         primary_uid => 25,
144                         policy_uri => 26,
145                         usage_flags => 27,
146                         signers_uid => 28,
147                         revocation_reason => 29,
148                         features => 30,
149                         signature_target => 31,
150                         embedded_signature => 32,
151                        };
152
153 # bitstring (see RFC 4880 section 5.2.3.24)
154 my $features = { mdc => 0x01
155                };
156
157 # bitstring (see RFC 4880 5.2.3.17)
158 my $keyserver_prefs = { nomodify => 0x80
159                       };
160
161 ###### end lookup tables ######
162
163 # FIXME: if we want to be able to interpret openpgp data as well as
164 # produce it, we need to produce key/value-swapped lookup tables as well.
165
166
167 ########### Math/Utility Functions ##############
168
169
170 # see the bottom of page 43 of RFC 4880
171 sub simple_checksum {
172   my $bytes = shift;
173
174   return unpack("%32W*",$bytes) % 65536;
175 }
176
177 # calculate the multiplicative inverse of a mod b this is euclid's
178 # extended algorithm.  For more information see:
179 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
180 # arguments here should be Crypt::OpenSSL::Bignum objects.  $a should
181 # be the larger of the two values, and the two values should be
182 # coprime.
183
184 sub modular_multi_inverse {
185   my $a = shift;
186   my $b = shift;
187
188
189   my $origdivisor = $b->copy();
190
191   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
192   my $x = Crypt::OpenSSL::Bignum->zero();
193   my $y = Crypt::OpenSSL::Bignum->one();
194   my $lastx = Crypt::OpenSSL::Bignum->one();
195   my $lasty = Crypt::OpenSSL::Bignum->zero();
196
197   my $finalquotient;
198   my $finalremainder;
199
200   while (! $b->is_zero()) {
201     my ($quotient, $remainder) = $a->div($b, $ctx);
202
203     $a = $b;
204     $b = $remainder;
205
206     my $temp = $x;
207     $x = $lastx->sub($quotient->mul($x, $ctx));
208     $lastx = $temp;
209
210     $temp = $y;
211     $y = $lasty->sub($quotient->mul($y, $ctx));
212     $lasty = $temp;
213   }
214
215   if (!$a->is_one()) {
216     die "did this math wrong.\n";
217   }
218
219   # let's make sure that we return a positive value because RFC 4880,
220   # section 3.2 only allows unsigned values:
221
222   ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
223
224   return $finalremainder;
225 }
226
227
228 ############ OpenPGP formatting functions ############
229
230 # make an old-style packet out of the given packet type and body.
231 # old-style  (see RFC 4880 section 4.2)
232 sub make_packet {
233   my $type = shift;
234   my $body = shift;
235   my $options = shift;
236
237   my $len = length($body);
238   my $pseudolen = $len;
239
240   # if the caller wants to use at least N octets of packet length,
241   # pretend that we're using that many.
242   if (defined $options && defined $options->{'packet_length'}) {
243       $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
244   }
245   if ($pseudolen < $len) {
246       $pseudolen = $len;
247   }
248
249   my $lenbytes;
250   my $lencode;
251
252   if ($pseudolen < 2**8) {
253     $lenbytes = $old_format_packet_lengths->{one};
254     $lencode = 'C';
255   } elsif ($pseudolen < 2**16) {
256     $lenbytes = $old_format_packet_lengths->{two};
257     $lencode = 'n';
258   } elsif ($pseudolen < 2**31) {
259     ## not testing against full 32 bits because i don't want to deal
260     ## with potential overflow.
261     $lenbytes = $old_format_packet_lengths->{four};
262     $lencode = 'N';
263   } else {
264     ## what the hell do we do here?
265     $lenbytes = $old_format_packet_lengths->{indeterminate};
266     $lencode = '';
267   }
268
269   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
270     $body;
271 }
272
273
274 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
275 # (RFC 4880 section 3.2)
276 sub mpi_pack {
277   my $num = shift;
278
279   my $val = $num->to_bin();
280   my $mpilen = length($val)*8;
281
282 # this is a kludgy way to get the number of significant bits in the
283 # first byte:
284   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
285
286   $mpilen -= (8 - $bitsinfirstbyte);
287
288   return pack('n', $mpilen).$val;
289 }
290
291 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
292 # for an OpenSSH-style public key format.  see:
293 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
294 sub openssh_mpi_pack {
295   my $num = shift;
296
297   my $val = $num->to_bin();
298   my $mpilen = length($val);
299
300   my $ret = pack('N', $mpilen);
301
302   # if the first bit of the leading byte is high, we should include a
303   # 0 byte:
304   if (ord($val) & 0x80) {
305     $ret = pack('NC', $mpilen+1, 0);
306   }
307
308   return $ret.$val;
309 }
310
311 sub openssh_pubkey_pack {
312   my $key = shift;
313
314   my ($modulus, $exponent) = $key->get_key_parameters();
315
316   return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
317       openssh_mpi_pack($exponent).
318         openssh_mpi_pack($modulus);
319   }
320
321 # pull an OpenPGP-specified MPI off of a given stream, returning it as
322 # a Crypt::OpenSSL::Bignum.
323 sub read_mpi {
324   my $instr = shift;
325
326   my $bitlen;
327   read($instr, $bitlen, 2) or die "could not read MPI length.\n";
328   $bitlen = unpack('n', $bitlen);
329
330   my $ret;
331   read($instr, $ret, ($bitlen + 7)/8) or die "could not read MPI body.\n";
332   return Crypt::OpenSSL::Bignum->new_from_bin($ret);
333 }
334
335
336 # FIXME: genericize these to accept either RSA or DSA keys:
337 sub make_rsa_pub_key_body {
338   my $key = shift;
339   my $timestamp = shift;
340
341   my ($n, $e) = $key->get_key_parameters();
342
343   return
344     pack('CN', 4, $timestamp).
345       pack('C', $asym_algos->{rsa}).
346         mpi_pack($n).
347           mpi_pack($e);
348 }
349
350 sub make_rsa_sec_key_body {
351   my $key = shift;
352   my $timestamp = shift;
353
354   # we're not using $a and $b, but we need them to get to $c.
355   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
356
357   my $c3 = modular_multi_inverse($p, $q);
358
359   my $secret_material = mpi_pack($d).
360     mpi_pack($p).
361       mpi_pack($q).
362         mpi_pack($c3);
363
364   # according to Crypt::OpenSSL::RSA, the closest value we can get out
365   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
366   # RFC 4880, we're actually looking for u, the multiplicative inverse
367   # of p, mod q.  This is why we're calculating the value directly
368   # with modular_multi_inverse.
369
370   return
371     pack('CN', 4, $timestamp).
372       pack('C', $asym_algos->{rsa}).
373         mpi_pack($n).
374           mpi_pack($e).
375             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
376               $secret_material.
377                 pack('n', simple_checksum($secret_material));
378 }
379
380 # expects an RSA key (public or private) and a timestamp
381 sub fingerprint {
382   my $key = shift;
383   my $timestamp = shift;
384
385   my $rsabody = make_rsa_pub_key_body($key, $timestamp);
386
387   return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
388 }
389
390
391 # FIXME: handle DSA keys as well!
392 sub pem2openpgp {
393   my $rsa = shift;
394   my $uid = shift;
395   my $args = shift;
396
397   $rsa->use_sha1_hash();
398
399   # see page 22 of RFC 4880 for why i think this is the right padding
400   # choice to use:
401   $rsa->use_pkcs1_padding();
402
403   if (! $rsa->check_key()) {
404     die "key does not check";
405   }
406
407   my $version = pack('C', 4);
408   # strong assertion of identity:
409   my $sigtype = pack('C', $sig_types->{positive_certification});
410   # RSA
411   my $pubkey_algo = pack('C', $asym_algos->{rsa});
412   # SHA1
413   my $hash_algo = pack('C', $digests->{sha1});
414
415   # FIXME: i'm worried about generating a bazillion new OpenPGP
416   # certificates from the same key, which could easily happen if you run
417   # this script more than once against the same key (because the
418   # timestamps will differ).  How can we prevent this?
419
420   # this environment variable (if set) overrides the current time, to
421   # be able to create a standard key?  If we read the key from a file
422   # instead of stdin, should we use the creation time on the file?
423   my $timestamp = 0;
424   if (defined $args->{timestamp}) {
425     $timestamp = ($args->{timestamp} + 0);
426   } else {
427     $timestamp = time();
428   }
429
430   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
431
432
433   my $flags = 0;
434   if (! defined $args->{usage_flags}) {
435     $flags = $usage_flags->{certify};
436   } else {
437     my @ff = split(",", $args->{usage_flags});
438     foreach my $f (@ff) {
439       if (! defined $usage_flags->{$f}) {
440         die "No such flag $f";
441       }
442       $flags |= $usage_flags->{$f};
443     }
444   }
445
446   my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
447
448
449   # how should we determine how far off to set the expiration date?
450   # default is no expiration.  Specify the timestamp in seconds from the
451   # key creation.
452   my $expiration_packet = '';
453   if (defined $args->{expiration}) {
454     my $expires_in = $args->{expiration} + 0;
455     $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
456   }
457
458
459   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
460   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
461                             $ciphers->{aes256},
462                             $ciphers->{aes192},
463                             $ciphers->{aes128},
464                             $ciphers->{cast5},
465                             $ciphers->{tripledes}
466                            );
467
468   # prefer SHA-1, SHA-256, RIPE-MD/160
469   my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
470                              $digests->{sha1},
471                              $digests->{sha256},
472                              $digests->{ripemd160}
473                             );
474
475   # prefer ZLIB, BZip2, ZIP
476   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
477                             $zips->{zlib},
478                             $zips->{bzip2},
479                             $zips->{zip}
480                            );
481
482   # we support the MDC feature:
483   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
484                                $features->{mdc});
485
486   # keyserver preference: only owner modify (???):
487   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
488                             $keyserver_prefs->{nomodify});
489
490   my $subpackets_to_be_hashed =
491     $creation_time_packet.
492       $usage_packet.
493         $expiration_packet.
494           $pref_sym_algos.
495             $pref_hash_algos.
496               $pref_zip_algos.
497                 $feature_subpacket.
498                   $keyserver_pref;
499
500   my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
501
502   my $sig_data_to_be_hashed =
503     $version.
504       $sigtype.
505         $pubkey_algo.
506           $hash_algo.
507             $subpacket_octets.
508               $subpackets_to_be_hashed;
509
510   my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
511   my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
512
513   # this is for signing.  it needs to be an old-style header with a
514   # 2-packet octet count.
515
516   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
517
518   # take the last 8 bytes of the fingerprint as the keyid:
519   my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
520
521   # the v4 signature trailer is:
522
523   # version number, literal 0xff, and then a 4-byte count of the
524   # signature data itself.
525   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
526
527   my $uid_data =
528     pack('CN', 0xb4, length($uid)).
529       $uid;
530
531   my $datatosign =
532     $key_data.
533       $uid_data.
534         $sig_data_to_be_hashed.
535           $trailer;
536
537   my $data_hash = Digest::SHA1::sha1_hex($datatosign);
538
539   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
540
541   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
542
543   my $sig_body =
544     $sig_data_to_be_hashed.
545       pack('n', length($issuer_packet)).
546         $issuer_packet.
547           pack('n', hex(substr($data_hash, 0, 4))).
548             mpi_pack($sig);
549
550   return
551     make_packet($packet_types->{seckey}, $seckey).
552       make_packet($packet_types->{uid}, $uid).
553         make_packet($packet_types->{sig}, $sig_body);
554 }
555
556
557 sub openpgp2ssh {
558   my $instr = shift;
559   my $fpr = shift;
560
561   if (defined $fpr) {
562     if (length($fpr) < 8) {
563       die "We need at least 8 hex digits of fingerprint.\n";
564     }
565   }
566
567   my $packettag;
568   my $dummy;
569   my $tag;
570
571   my $key;
572
573   while (! eof($instr)) {
574     read($instr, $packettag, 1);
575     $packettag = ord($packettag);
576
577     my $packetlen;
578     if ( ! (0x80 & $packettag)) {
579       die "This is not an OpenPGP packet\n";
580     }
581     if (0x40 & $packettag) {
582       $tag = (0x3f & $packettag);
583       my $nextlen = 0;
584       read($instr, $nextlen, 1);
585       $nextlen = ord($nextlen);
586       if ($nextlen < 192) {
587         $packetlen = $nextlen;
588       } elsif ($nextlen < 224) {
589         my $newoct;
590         read($instr, $newoct, 1);
591         $newoct = ord($newoct);
592         $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
593       } elsif ($nextlen == 255) {
594         read($instr, $nextlen, 4);
595         $packetlen = unpack('N', $nextlen);
596       } else {
597         # packet length is undefined.
598       }
599     } else {
600       my $lentype;
601       $lentype = 0x03 & $packettag;
602       $tag = ( 0x3c & $packettag ) >> 2;
603       if ($lentype == 0) {
604         read($instr, $packetlen, 1) or die "could not read packet length\n";
605         $packetlen = unpack('C', $packetlen);
606       } elsif ($lentype == 1) {
607         read($instr, $packetlen, 2) or die "could not read packet length\n";
608         $packetlen = unpack('n', $packetlen);
609       } elsif ($lentype == 2) {
610         read($instr, $packetlen, 4) or die "could not read packet length\n";
611         $packetlen = unpack('N', $packetlen);
612       } else {
613         # packet length is undefined.
614       }
615     }
616
617     if (! defined($packetlen)) {
618       die "Undefined packet lengths are not supported.\n";
619     }
620
621     if ($tag == $packet_types->{pubkey} ||
622         $tag == $packet_types->{pub_subkey} ||
623         $tag == $packet_types->{seckey} ||
624         $tag == $packet_types->{sec_subkey}) {
625       my $ver;
626       read($instr, $ver, 1) or die "could not read key version\n";
627       $ver = ord($ver);
628       if ($ver != 4) {
629         printf(STDERR "We only work with version 4 keys.  This key appears to be version $ver.\n");
630         read($instr, $dummy, $packetlen - 1) or die "Could not skip past this packet.\n";
631       } else {
632
633         my $timestamp;
634         read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
635         $timestamp = unpack('N', $timestamp);
636
637         my $algo;
638         read($instr, $algo, 1) or die "could not read key algorithm.\n";
639         $algo = ord($algo);
640         if ($algo != $asym_algos->{rsa}) {
641           printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
642           read($instr, $dummy, $packetlen - 6) or die "Could not skip past this packet.\n";
643         } else {
644           ## we have an RSA key.
645           my $modulus = read_mpi($instr);
646           my $exponent = read_mpi($instr);
647
648           my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
649           my $foundfpr = fingerprint($pubkey, $timestamp);
650
651           my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
652
653           # is this a match?
654           if ((!defined($fpr)) ||
655               (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
656             if (defined($key)) {
657               die "Found two matching keys.\n";
658             }
659             $key = $pubkey;
660           }
661
662           if ($tag == $packet_types->{seckey} ||
663               $tag == $packet_types->{sec_subkey}) {
664             die "Cannot deal with secret keys yet!\n";
665           }
666
667         }
668       }
669     } else {
670       read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
671     }
672   }
673
674   if (defined($key)) {
675     return "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '');
676   }
677 }
678
679
680 for (basename($0)) {
681   if (/^pem2openpgp$/) {
682     my $rsa;
683     my $stdin;
684     if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
685       $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
686     } else {
687       $stdin = do {
688         local $/; # slurp!
689         <STDIN>;
690       };
691
692       $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
693     }
694
695     my $uid = shift;
696
697     # FIXME: fail if there is no given user ID; or should we default to
698     # hostname_long() from Sys::Hostname::Long ?
699
700     print pem2openpgp($rsa,
701                       $uid,
702                       { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
703                         expiration => $ENV{PEM2OPENPGP_EXPIRATION},
704                         usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
705                       }
706                      );
707   }
708   elsif (/^openpgp2ssh$/) {
709       my $fpr = shift;
710       my $instream;
711       open($instream,'-');
712       binmode($instream, ":bytes");
713       print openpgp2ssh($instream, $fpr);
714   }
715   else {
716     die "Unrecognized keytrans call.\n";
717   }
718 }
719