pem2openpgp: reorganization, cleanup of comments, adding a warning about secret mater...
[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
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   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
189   my $x = Crypt::OpenSSL::Bignum->zero();
190   my $y = Crypt::OpenSSL::Bignum->one();
191   my $lastx = Crypt::OpenSSL::Bignum->one();
192   my $lasty = Crypt::OpenSSL::Bignum->zero();
193
194   while (! $b->is_zero()) {
195     my ($quotient, $remainder) = $a->div($b, $ctx);
196
197     $a = $b;
198     $b = $remainder;
199
200     my $temp = $x;
201     $x = $lastx->sub($quotient->mul($x, $ctx));
202     $lastx = $temp;
203
204     $temp = $y;
205     $y = $lasty->sub($quotient->mul($y, $ctx));
206     $lasty = $temp;
207   }
208
209   if (!$a->is_one()) {
210     die "did this math wrong.\n";
211   }
212
213   return $lastx;
214 }
215
216
217 ############ OpenPGP formatting functions ############
218
219 # make an old-style packet out of the given packet type and body.
220 # old-style  (see RFC 4880 section 4.2)
221 sub make_packet {
222   my $type = shift;
223   my $body = shift;
224
225   my $len = length($body);
226
227   my $lenbytes;
228   my $lencode;
229
230   if ($len < 2**8) {
231     $lenbytes = 0;
232     $lencode = 'C';
233   } elsif ($len < 2**16) {
234     $lenbytes = 1;
235     $lencode = 'n';
236   } elsif ($len < 2**31) {
237     ## not testing against full 32 bits because i don't want to deal
238     ## with potential overflow.
239     $lenbytes = 2;
240     $lencode = 'N';
241   } else {
242     ## what the hell do we do here?
243     $lenbytes = 3;
244     $lencode = '';
245   }
246
247   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
248     $body;
249 }
250
251
252 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
253 # (RFC 4880 section 3.2)
254 sub mpi_pack {
255   my $num = shift;
256
257   my $val = $num->to_bin();
258   my $mpilen = length($val)*8;
259
260 # this is a kludgy way to get the number of significant bits in the
261 # first byte:
262   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
263
264   $mpilen -= (8 - $bitsinfirstbyte);
265
266   return pack('n', $mpilen).$val;
267 }
268
269 # FIXME: genericize these to accept either RSA or DSA keys:
270 sub make_rsa_pub_key_body {
271   my $key = shift;
272   my $timestamp = shift;
273
274   my ($n, $e) = $key->get_key_parameters();
275
276   return
277     pack('CN', 4, $timestamp).
278       pack('C', $asym_algos->{rsa}).
279         mpi_pack($n).
280           mpi_pack($e);
281 }
282
283 sub make_rsa_sec_key_body {
284   my $key = shift;
285   my $timestamp = shift;
286
287   # we're not using $a and $b, but we need them to get to $c.
288   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
289
290   my $secret_material = mpi_pack($d).
291     mpi_pack($p).
292       mpi_pack($q).
293         mpi_pack(modular_multi_inverse($p, $q));
294
295   # according to Crypt::OpenSSL::RSA, the closest value we can get out
296   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
297   # RFC 4880, we're actually looking for u, the multiplicative inverse
298   # of p, mod q.  This is why we're calculating the value directly
299   # with modular_multi_inverse.
300
301   return
302     pack('CN', 4, $timestamp).
303       pack('C', $asym_algos->{rsa}).
304         mpi_pack($n).
305           mpi_pack($e).
306             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
307               $secret_material.
308                 pack('n', simple_checksum($secret_material));
309 }
310
311 # expects an RSA key (public or private) and a timestamp
312 sub fingerprint {
313   my $key = shift;
314   my $timestamp = shift;
315
316   my $rsabody = make_rsa_pub_key_body($key, $timestamp);
317
318   return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
319 }
320
321 # we're just not dealing with newline business right now.  slurp in
322 # the whole file.
323 undef $/;
324 my $buf = <STDIN>;
325
326
327 my $rsa = Crypt::OpenSSL::RSA->new_private_key($buf);
328
329 $rsa->use_sha1_hash();
330
331 # see page 22 of RFC 4880 for why i think this is the right padding
332 # choice to use:
333 $rsa->use_pkcs1_padding();
334
335 if (! $rsa->check_key()) {
336   die "key does not check";
337 }
338
339 my $version = pack('C', 4);
340 # strong assertion of identity:
341 my $sigtype = pack('C', $sig_types->{positive_certification});
342 # RSA
343 my $pubkey_algo = pack('C', $asym_algos->{rsa});
344 # SHA1
345 my $hash_algo = pack('C', $digests->{sha1});
346
347 # FIXME: i'm worried about generating a bazillion new OpenPGP
348 # certificates from the same key, which could easily happen if you run
349 # this script more than once against the same key (because the
350 # timestamps will differ).  How can we prevent this?
351
352 # could an environment variable (if set) override the current time, to
353 # be able to create a standard key?  If we read the key from a file
354 # instead of stdin, should we use the creation time on the file?
355 my $timestamp = time();
356
357 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
358
359
360 # FIXME: HARDCODED: what if someone wants to select a different set of
361 # usage flags?  For now, we do only authentication because that's what
362 # monkeysphere needs.
363 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $usage_flags->{authenticate});
364
365
366 # FIXME: HARDCODED: how should we determine how far off to set the
367 # expiration date?  default is to expire in 2 days, which is insanely
368 # short (but good for testing).  The user ought to be able to decide
369 # this directly, rather than having to do "monkeysphere-server
370 # extend-key".
371 my $expires_in = 86400*2;
372 my $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
373
374
375 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
376 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
377                           $ciphers->{aes256},
378                           $ciphers->{aes192},
379                           $ciphers->{aes128},
380                           $ciphers->{cast5},
381                           $ciphers->{tripledes}
382                          );
383
384 # prefer SHA-1, SHA-256, RIPE-MD/160
385 my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
386                            $digests->{sha1},
387                            $digests->{sha256},
388                            $digests->{ripemd160}
389                           );
390
391 # prefer ZLIB, BZip2, ZIP
392 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
393                           $zips->{zlib},
394                           $zips->{bzip2},
395                           $zips->{zip}
396                          );
397
398 # we support the MDC feature:
399 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
400                              $features->{mdc});
401
402 # keyserver preference: only owner modify (???):
403 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
404                           $keyserver_prefs->{nomodify});
405
406 my $subpackets_to_be_hashed =
407   $creation_time_packet.
408   $usage_packet.
409   $expiration_packet.
410   $pref_sym_algos.
411   $pref_hash_algos.
412   $pref_zip_algos.
413   $feature_subpacket.
414   $keyserver_pref;
415
416 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
417
418 my $sig_data_to_be_hashed =
419   $version.
420   $sigtype.
421   $pubkey_algo.
422   $hash_algo.
423   $subpacket_octets.
424   $subpackets_to_be_hashed;
425
426 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
427 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
428
429 my $key_data = make_packet($packet_types->{pubkey}, $pubkey);
430
431 # take the last 8 bytes of the fingerprint as the keyid:
432 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
433
434 # the v4 signature trailer is:
435
436 # version number, literal 0xff, and then a 4-byte count of the
437 # signature data itself.
438 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
439
440 my $uid_data =
441   pack('CN', 0xb4, length($uid)).
442   $uid;
443
444 my $datatosign =
445   $key_data.
446   $uid_data.
447   $sig_data_to_be_hashed.
448   $trailer;
449
450 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
451
452
453 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
454
455 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
456
457 my $sig_body =
458   $sig_data_to_be_hashed.
459   pack('n', length($issuer_packet)).
460   $issuer_packet.
461   pack('n', hex(substr($data_hash, 0, 4))).
462   mpi_pack($sig);
463
464 print
465   make_packet($packet_types->{seckey}, $seckey).
466   make_packet($packet_types->{uid}, $uid).
467   make_packet($packet_types->{sig}, $sig_body);
468
469