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