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