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