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.
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!
13 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
16 # Jameson Rollins <jrollins@finestructure.net>
17 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
19 # Started on: 2009-01-07 02:01:19-0500
21 # License: GPL v3 or later (we may need to adjust this given that this
22 # connects to OpenSSL via perl)
26 use Crypt::OpenSSL::RSA;
27 use Crypt::OpenSSL::Bignum;
28 use Crypt::OpenSSL::Bignum::CTX;
32 ## make sure all length() and substr() calls use bytes only:
37 # FIXME: fail if there is no given user ID; or should we default to
38 # hostname_long() from Sys::Hostname::Long ?
42 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
43 my $asym_algos = { rsa => 1,
48 # see RFC 4880 section 9.2
49 my $ciphers = { plaintext => 0,
60 # see RFC 4880 section 9.3
61 my $zips = { uncompressed => 0,
67 # see RFC 4880 section 9.4
68 my $digests = { md5 => 1,
77 # see RFC 4880 section 5.2.3.21
78 my $usage_flags = { certify => 0x01,
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
85 shared => 0x80, # more than one person holds the entire private key
88 # see RFC 4880 section 4.3
89 my $packet_types = { pubkey_enc_session => 1,
91 symkey_enc_session => 3,
104 symenc_w_integrity => 18,
108 # see RFC 4880 section 5.2.1
109 my $sig_types = { binary_doc => 0x00,
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,
127 # see RFC 4880 section 5.2.3.1
128 my $subpacket_types = { sig_creation_time => 2,
129 sig_expiration_time => 3,
134 key_expiration_time => 9,
135 preferred_cipher => 11,
136 revocation_key => 12,
139 preferred_digest => 21,
140 preferred_compression => 22,
141 keyserver_prefs => 23,
142 preferred_keyserver => 24,
147 revocation_reason => 29,
149 signature_target => 31,
150 embedded_signature => 32,
153 # bitstring (see RFC 4880 section 5.2.3.24)
154 my $features = { mdc => 0x01
157 # bitstring (see RFC 4880 5.2.3.17)
158 my $keyserver_prefs = { nomodify => 0x80
161 ###### end lookup tables ######
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.
167 ########### Math/Utility Functions ##############
170 # see the bottom of page 43 of RFC 4880
171 sub simple_checksum {
174 return unpack("%32W*",$bytes) % 65536;
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
184 sub modular_multi_inverse {
189 my $origdivisor = $b->copy();
191 my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
192 my $x = Crypt::OpenSSL::Bignum->zero();
193 my $y = Crypt::OpenSSL::Bignum->one();
194 my $lastx = Crypt::OpenSSL::Bignum->one();
195 my $lasty = Crypt::OpenSSL::Bignum->zero();
200 while (! $b->is_zero()) {
201 my ($quotient, $remainder) = $a->div($b, $ctx);
207 $x = $lastx->sub($quotient->mul($x, $ctx));
211 $y = $lasty->sub($quotient->mul($y, $ctx));
216 die "did this math wrong.\n";
219 # let's make sure that we return a positive value because RFC 4880,
220 # section 3.2 only allows unsigned values:
222 ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
224 return $finalremainder;
228 ############ OpenPGP formatting functions ############
230 # make an old-style packet out of the given packet type and body.
231 # old-style (see RFC 4880 section 4.2)
236 my $len = length($body);
244 } elsif ($len < 2**16) {
247 } elsif ($len < 2**31) {
248 ## not testing against full 32 bits because i don't want to deal
249 ## with potential overflow.
253 ## what the hell do we do here?
258 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
263 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
264 # (RFC 4880 section 3.2)
268 my $val = $num->to_bin();
269 my $mpilen = length($val)*8;
271 # this is a kludgy way to get the number of significant bits in the
273 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
275 $mpilen -= (8 - $bitsinfirstbyte);
277 return pack('n', $mpilen).$val;
280 # FIXME: genericize these to accept either RSA or DSA keys:
281 sub make_rsa_pub_key_body {
283 my $timestamp = shift;
285 my ($n, $e) = $key->get_key_parameters();
288 pack('CN', 4, $timestamp).
289 pack('C', $asym_algos->{rsa}).
294 sub make_rsa_sec_key_body {
296 my $timestamp = shift;
298 # we're not using $a and $b, but we need them to get to $c.
299 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
301 my $c3 = modular_multi_inverse($p, $q);
303 my $secret_material = mpi_pack($d).
308 # according to Crypt::OpenSSL::RSA, the closest value we can get out
309 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
310 # RFC 4880, we're actually looking for u, the multiplicative inverse
311 # of p, mod q. This is why we're calculating the value directly
312 # with modular_multi_inverse.
315 pack('CN', 4, $timestamp).
316 pack('C', $asym_algos->{rsa}).
319 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
321 pack('n', simple_checksum($secret_material));
324 # expects an RSA key (public or private) and a timestamp
327 my $timestamp = shift;
329 my $rsabody = make_rsa_pub_key_body($key, $timestamp);
331 return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
334 # we're just not dealing with newline business right now. slurp in
340 my $rsa = Crypt::OpenSSL::RSA->new_private_key($buf);
342 $rsa->use_sha1_hash();
344 # see page 22 of RFC 4880 for why i think this is the right padding
346 $rsa->use_pkcs1_padding();
348 if (! $rsa->check_key()) {
349 die "key does not check";
352 my $version = pack('C', 4);
353 # strong assertion of identity:
354 my $sigtype = pack('C', $sig_types->{positive_certification});
356 my $pubkey_algo = pack('C', $asym_algos->{rsa});
358 my $hash_algo = pack('C', $digests->{sha1});
360 # FIXME: i'm worried about generating a bazillion new OpenPGP
361 # certificates from the same key, which could easily happen if you run
362 # this script more than once against the same key (because the
363 # timestamps will differ). How can we prevent this?
365 # this environment variable (if set) overrides the current time, to
366 # be able to create a standard key? If we read the key from a file
367 # instead of stdin, should we use the creation time on the file?
369 if (defined $ENV{PEM2OPENPGP_TIMESTAMP}) {
370 $timestamp = ($ENV{PEM2OPENPGP_TIMESTAMP} + 0);
375 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
379 if (! defined $ENV{PEM2OPENPGP_USAGE_FLAGS}) {
380 $flags = $usage_flags->{certify};
382 my @ff = split(",", $ENV{PEM2OPENPGP_USAGE_FLAGS});
383 foreach my $f (@ff) {
384 if (! defined $usage_flags->{$f}) {
385 die "No such flag $f";
387 $flags |= $usage_flags->{$f};
391 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
394 # how should we determine how far off to set the expiration date?
395 # default is no expiration. Specify the timestamp in seconds from the
397 my $expiration_packet = '';
398 if (defined $ENV{PEM2OPENPGP_EXPIRATION}) {
399 my $expires_in = $ENV{PEM2OPENPGP_EXPIRATION} + 0;
400 $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
404 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
405 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
410 $ciphers->{tripledes}
413 # prefer SHA-1, SHA-256, RIPE-MD/160
414 my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
417 $digests->{ripemd160}
420 # prefer ZLIB, BZip2, ZIP
421 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
427 # we support the MDC feature:
428 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
431 # keyserver preference: only owner modify (???):
432 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
433 $keyserver_prefs->{nomodify});
435 my $subpackets_to_be_hashed =
436 $creation_time_packet.
445 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
447 my $sig_data_to_be_hashed =
453 $subpackets_to_be_hashed;
455 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
456 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
458 my $key_data = make_packet($packet_types->{pubkey}, $pubkey);
460 # take the last 8 bytes of the fingerprint as the keyid:
461 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
463 # the v4 signature trailer is:
465 # version number, literal 0xff, and then a 4-byte count of the
466 # signature data itself.
467 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
470 pack('CN', 0xb4, length($uid)).
476 $sig_data_to_be_hashed.
479 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
482 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
484 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
487 $sig_data_to_be_hashed.
488 pack('n', length($issuer_packet)).
490 pack('n', hex(substr($data_hash, 0, 4))).
494 make_packet($packet_types->{seckey}, $seckey).
495 make_packet($packet_types->{uid}, $uid).
496 make_packet($packet_types->{sig}, $sig_body);