functionalize the bulk of pem2openpgp.
[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 Crypt::OpenSSL::RSA;
27 use Crypt::OpenSSL::Bignum;
28 use Crypt::OpenSSL::Bignum::CTX;
29 use Digest::SHA1;
30 use MIME::Base64;
31
32 ## make sure all length() and substr() calls use bytes only:
33 use bytes;
34
35 my $old_format_packet_lengths = { one => 0,
36                                   two => 1,
37                                   four => 2,
38                                   indeterminate => 3,
39 };
40
41 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
42 my $asym_algos = { rsa => 1,
43                    elgamal => 16,
44                    dsa => 17,
45                    };
46
47 # see RFC 4880 section 9.2
48 my $ciphers = { plaintext => 0,
49                 idea => 1,
50                 tripledes => 2,
51                 cast5 => 3,
52                 blowfish => 4,
53                 aes128 => 7,
54                 aes192 => 8,
55                 aes256 => 9,
56                 twofish => 10,
57               };
58
59 # see RFC 4880 section 9.3
60 my $zips = { uncompressed => 0,
61              zip => 1,
62              zlib => 2,
63              bzip2 => 3,
64            };
65
66 # see RFC 4880 section 9.4
67 my $digests = { md5 => 1,
68                 sha1 => 2,
69                 ripemd160 => 3,
70                 sha256 => 8,
71                 sha384 => 9,
72                 sha512 => 10,
73                 sha224 => 11,
74               };
75
76 # see RFC 4880 section 5.2.3.21
77 my $usage_flags = { certify => 0x01,
78                     sign => 0x02,
79                     encrypt_comms => 0x04,
80                     encrypt_storage => 0x08,
81                     encrypt => 0x0c, ## both comms and storage
82                     split => 0x10, # the private key is split via secret sharing
83                     authenticate => 0x20,
84                     shared => 0x80, # more than one person holds the entire private key
85                   };
86
87 # see RFC 4880 section 4.3
88 my $packet_types = { pubkey_enc_session => 1,
89                      sig => 2,
90                      symkey_enc_session => 3,
91                      onepass_sig => 4,
92                      seckey => 5,
93                      pubkey => 6,
94                      sec_subkey => 7,
95                      compressed_data => 8,
96                      symenc_data => 9,
97                      marker => 10,
98                      literal => 11,
99                      trust => 12,
100                      uid => 13,
101                      pub_subkey => 14,
102                      uat => 17,
103                      symenc_w_integrity => 18,
104                      mdc => 19,
105                    };
106
107 # see RFC 4880 section 5.2.1
108 my $sig_types = { binary_doc => 0x00,
109                   text_doc => 0x01,
110                   standalone => 0x02,
111                   generic_certification => 0x10,
112                   persona_certification => 0x11,
113                   casual_certification => 0x12,
114                   positive_certification => 0x13,
115                   subkey_binding => 0x18,
116                   primary_key_binding => 0x19,
117                   key_signature => 0x1f,
118                   key_revocation => 0x20,
119                   subkey_revocation => 0x28,
120                   certification_revocation => 0x30,
121                   timestamp => 0x40,
122                   thirdparty => 0x50,
123                 };
124
125
126 # see RFC 4880 section 5.2.3.1
127 my $subpacket_types = { sig_creation_time => 2,
128                         sig_expiration_time => 3,
129                         exportable => 4,
130                         trust_sig => 5,
131                         regex => 6,
132                         revocable => 7,
133                         key_expiration_time => 9,
134                         preferred_cipher => 11,
135                         revocation_key => 12,
136                         issuer => 16,
137                         notation => 20,
138                         preferred_digest => 21,
139                         preferred_compression => 22,
140                         keyserver_prefs => 23,
141                         preferred_keyserver => 24,
142                         primary_uid => 25,
143                         policy_uri => 26,
144                         usage_flags => 27,
145                         signers_uid => 28,
146                         revocation_reason => 29,
147                         features => 30,
148                         signature_target => 31,
149                         embedded_signature => 32,
150                        };
151
152 # bitstring (see RFC 4880 section 5.2.3.24)
153 my $features = { mdc => 0x01
154                };
155
156 # bitstring (see RFC 4880 5.2.3.17)
157 my $keyserver_prefs = { nomodify => 0x80
158                       };
159
160 ###### end lookup tables ######
161
162 # FIXME: if we want to be able to interpret openpgp data as well as
163 # produce it, we need to produce key/value-swapped lookup tables as well.
164
165
166 ########### Math/Utility Functions ##############
167
168
169 # see the bottom of page 43 of RFC 4880
170 sub simple_checksum {
171   my $bytes = shift;
172
173   return unpack("%32W*",$bytes) % 65536;
174 }
175
176 # calculate the multiplicative inverse of a mod b this is euclid's
177 # extended algorithm.  For more information see:
178 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
179 # arguments here should be Crypt::OpenSSL::Bignum objects.  $a should
180 # be the larger of the two values, and the two values should be
181 # coprime.
182
183 sub modular_multi_inverse {
184   my $a = shift;
185   my $b = shift;
186
187
188   my $origdivisor = $b->copy();
189
190   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
191   my $x = Crypt::OpenSSL::Bignum->zero();
192   my $y = Crypt::OpenSSL::Bignum->one();
193   my $lastx = Crypt::OpenSSL::Bignum->one();
194   my $lasty = Crypt::OpenSSL::Bignum->zero();
195
196   my $finalquotient;
197   my $finalremainder;
198
199   while (! $b->is_zero()) {
200     my ($quotient, $remainder) = $a->div($b, $ctx);
201
202     $a = $b;
203     $b = $remainder;
204
205     my $temp = $x;
206     $x = $lastx->sub($quotient->mul($x, $ctx));
207     $lastx = $temp;
208
209     $temp = $y;
210     $y = $lasty->sub($quotient->mul($y, $ctx));
211     $lasty = $temp;
212   }
213
214   if (!$a->is_one()) {
215     die "did this math wrong.\n";
216   }
217
218   # let's make sure that we return a positive value because RFC 4880,
219   # section 3.2 only allows unsigned values:
220
221   ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
222
223   return $finalremainder;
224 }
225
226
227 ############ OpenPGP formatting functions ############
228
229 # make an old-style packet out of the given packet type and body.
230 # old-style  (see RFC 4880 section 4.2)
231 sub make_packet {
232   my $type = shift;
233   my $body = shift;
234   my $options = shift;
235
236   my $len = length($body);
237   my $pseudolen = $len;
238
239   # if the caller wants to use at least N octets of packet length,
240   # pretend that we're using that many.
241   if (defined $options && defined $options->{'packet_length'}) {
242       $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
243   }
244   if ($pseudolen < $len) {
245       $pseudolen = $len;
246   }
247
248   my $lenbytes;
249   my $lencode;
250
251   if ($pseudolen < 2**8) {
252     $lenbytes = $old_format_packet_lengths->{one};
253     $lencode = 'C';
254   } elsif ($pseudolen < 2**16) {
255     $lenbytes = $old_format_packet_lengths->{two};
256     $lencode = 'n';
257   } elsif ($pseudolen < 2**31) {
258     ## not testing against full 32 bits because i don't want to deal
259     ## with potential overflow.
260     $lenbytes = $old_format_packet_lengths->{four};
261     $lencode = 'N';
262   } else {
263     ## what the hell do we do here?
264     $lenbytes = $old_format_packet_lengths->{indeterminate};
265     $lencode = '';
266   }
267
268   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
269     $body;
270 }
271
272
273 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
274 # (RFC 4880 section 3.2)
275 sub mpi_pack {
276   my $num = shift;
277
278   my $val = $num->to_bin();
279   my $mpilen = length($val)*8;
280
281 # this is a kludgy way to get the number of significant bits in the
282 # first byte:
283   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
284
285   $mpilen -= (8 - $bitsinfirstbyte);
286
287   return pack('n', $mpilen).$val;
288 }
289
290 # FIXME: genericize these to accept either RSA or DSA keys:
291 sub make_rsa_pub_key_body {
292   my $key = shift;
293   my $timestamp = shift;
294
295   my ($n, $e) = $key->get_key_parameters();
296
297   return
298     pack('CN', 4, $timestamp).
299       pack('C', $asym_algos->{rsa}).
300         mpi_pack($n).
301           mpi_pack($e);
302 }
303
304 sub make_rsa_sec_key_body {
305   my $key = shift;
306   my $timestamp = shift;
307
308   # we're not using $a and $b, but we need them to get to $c.
309   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
310
311   my $c3 = modular_multi_inverse($p, $q);
312
313   my $secret_material = mpi_pack($d).
314     mpi_pack($p).
315       mpi_pack($q).
316         mpi_pack($c3);
317
318   # according to Crypt::OpenSSL::RSA, the closest value we can get out
319   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
320   # RFC 4880, we're actually looking for u, the multiplicative inverse
321   # of p, mod q.  This is why we're calculating the value directly
322   # with modular_multi_inverse.
323
324   return
325     pack('CN', 4, $timestamp).
326       pack('C', $asym_algos->{rsa}).
327         mpi_pack($n).
328           mpi_pack($e).
329             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
330               $secret_material.
331                 pack('n', simple_checksum($secret_material));
332 }
333
334 # expects an RSA key (public or private) and a timestamp
335 sub fingerprint {
336   my $key = shift;
337   my $timestamp = shift;
338
339   my $rsabody = make_rsa_pub_key_body($key, $timestamp);
340
341   return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
342 }
343
344
345 # FIXME: handle DSA keys as well!
346 sub pem2openpgp {
347   my $rsa = shift;
348   my $uid = shift;
349   my $args = shift;
350
351   $rsa->use_sha1_hash();
352
353   # see page 22 of RFC 4880 for why i think this is the right padding
354   # choice to use:
355   $rsa->use_pkcs1_padding();
356
357   if (! $rsa->check_key()) {
358     die "key does not check";
359   }
360
361   my $version = pack('C', 4);
362   # strong assertion of identity:
363   my $sigtype = pack('C', $sig_types->{positive_certification});
364   # RSA
365   my $pubkey_algo = pack('C', $asym_algos->{rsa});
366   # SHA1
367   my $hash_algo = pack('C', $digests->{sha1});
368
369   # FIXME: i'm worried about generating a bazillion new OpenPGP
370   # certificates from the same key, which could easily happen if you run
371   # this script more than once against the same key (because the
372   # timestamps will differ).  How can we prevent this?
373
374   # this environment variable (if set) overrides the current time, to
375   # be able to create a standard key?  If we read the key from a file
376   # instead of stdin, should we use the creation time on the file?
377   my $timestamp = 0;
378   if (defined $args->{timestamp}) {
379     $timestamp = ($args->{timestamp} + 0);
380   } else {
381     $timestamp = time();
382   }
383
384   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
385
386
387   my $flags = 0;
388   if (! defined $args->{usage_flags}) {
389     $flags = $usage_flags->{certify};
390   } else {
391     my @ff = split(",", $args->{usage_flags});
392     foreach my $f (@ff) {
393       if (! defined $usage_flags->{$f}) {
394         die "No such flag $f";
395       }
396       $flags |= $usage_flags->{$f};
397     }
398   }
399
400   my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
401
402
403   # how should we determine how far off to set the expiration date?
404   # default is no expiration.  Specify the timestamp in seconds from the
405   # key creation.
406   my $expiration_packet = '';
407   if (defined $args->{expiration}) {
408     my $expires_in = $args->{expiration} + 0;
409     $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
410   }
411
412
413   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
414   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
415                             $ciphers->{aes256},
416                             $ciphers->{aes192},
417                             $ciphers->{aes128},
418                             $ciphers->{cast5},
419                             $ciphers->{tripledes}
420                            );
421
422   # prefer SHA-1, SHA-256, RIPE-MD/160
423   my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
424                              $digests->{sha1},
425                              $digests->{sha256},
426                              $digests->{ripemd160}
427                             );
428
429   # prefer ZLIB, BZip2, ZIP
430   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
431                             $zips->{zlib},
432                             $zips->{bzip2},
433                             $zips->{zip}
434                            );
435
436   # we support the MDC feature:
437   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
438                                $features->{mdc});
439
440   # keyserver preference: only owner modify (???):
441   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
442                             $keyserver_prefs->{nomodify});
443
444   my $subpackets_to_be_hashed =
445     $creation_time_packet.
446       $usage_packet.
447         $expiration_packet.
448           $pref_sym_algos.
449             $pref_hash_algos.
450               $pref_zip_algos.
451                 $feature_subpacket.
452                   $keyserver_pref;
453
454   my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
455
456   my $sig_data_to_be_hashed =
457     $version.
458       $sigtype.
459         $pubkey_algo.
460           $hash_algo.
461             $subpacket_octets.
462               $subpackets_to_be_hashed;
463
464   my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
465   my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
466
467   # this is for signing.  it needs to be an old-style header with a
468   # 2-packet octet count.
469
470   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
471
472   # take the last 8 bytes of the fingerprint as the keyid:
473   my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
474
475   # the v4 signature trailer is:
476
477   # version number, literal 0xff, and then a 4-byte count of the
478   # signature data itself.
479   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
480
481   my $uid_data =
482     pack('CN', 0xb4, length($uid)).
483       $uid;
484
485   my $datatosign =
486     $key_data.
487       $uid_data.
488         $sig_data_to_be_hashed.
489           $trailer;
490
491   my $data_hash = Digest::SHA1::sha1_hex($datatosign);
492
493   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
494
495   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
496
497   my $sig_body =
498     $sig_data_to_be_hashed.
499       pack('n', length($issuer_packet)).
500         $issuer_packet.
501           pack('n', hex(substr($data_hash, 0, 4))).
502             mpi_pack($sig);
503
504   return
505     make_packet($packet_types->{seckey}, $seckey).
506       make_packet($packet_types->{uid}, $uid).
507         make_packet($packet_types->{sig}, $sig_body);
508 }
509
510
511 my $rsa;
512 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
513   $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
514 } else {
515   # slurp in the entire stdin:
516   undef $/;
517   my $stdin = <STDIN>;
518
519   $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
520 }
521
522 my $uid = shift;
523
524 # FIXME: fail if there is no given user ID; or should we default to
525 # hostname_long() from Sys::Hostname::Long ?
526
527 print pem2openpgp($rsa,
528                   $uid,
529                   { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
530                     expiration => $ENV{PEM2OPENPGP_EXPIRATION},
531                     usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
532                    }
533                  );
534