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