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 ?
41 my $old_format_packet_lengths = { one => 0,
47 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
48 my $asym_algos = { rsa => 1,
53 # see RFC 4880 section 9.2
54 my $ciphers = { plaintext => 0,
65 # see RFC 4880 section 9.3
66 my $zips = { uncompressed => 0,
72 # see RFC 4880 section 9.4
73 my $digests = { md5 => 1,
82 # see RFC 4880 section 5.2.3.21
83 my $usage_flags = { certify => 0x01,
85 encrypt_comms => 0x04,
86 encrypt_storage => 0x08,
87 encrypt => 0x0c, ## both comms and storage
88 split => 0x10, # the private key is split via secret sharing
90 shared => 0x80, # more than one person holds the entire private key
93 # see RFC 4880 section 4.3
94 my $packet_types = { pubkey_enc_session => 1,
96 symkey_enc_session => 3,
101 compressed_data => 8,
109 symenc_w_integrity => 18,
113 # see RFC 4880 section 5.2.1
114 my $sig_types = { binary_doc => 0x00,
117 generic_certification => 0x10,
118 persona_certification => 0x11,
119 casual_certification => 0x12,
120 positive_certification => 0x13,
121 subkey_binding => 0x18,
122 primary_key_binding => 0x19,
123 key_signature => 0x1f,
124 key_revocation => 0x20,
125 subkey_revocation => 0x28,
126 certification_revocation => 0x30,
132 # see RFC 4880 section 5.2.3.1
133 my $subpacket_types = { sig_creation_time => 2,
134 sig_expiration_time => 3,
139 key_expiration_time => 9,
140 preferred_cipher => 11,
141 revocation_key => 12,
144 preferred_digest => 21,
145 preferred_compression => 22,
146 keyserver_prefs => 23,
147 preferred_keyserver => 24,
152 revocation_reason => 29,
154 signature_target => 31,
155 embedded_signature => 32,
158 # bitstring (see RFC 4880 section 5.2.3.24)
159 my $features = { mdc => 0x01
162 # bitstring (see RFC 4880 5.2.3.17)
163 my $keyserver_prefs = { nomodify => 0x80
166 ###### end lookup tables ######
168 # FIXME: if we want to be able to interpret openpgp data as well as
169 # produce it, we need to produce key/value-swapped lookup tables as well.
172 ########### Math/Utility Functions ##############
175 # see the bottom of page 43 of RFC 4880
176 sub simple_checksum {
179 return unpack("%32W*",$bytes) % 65536;
182 # calculate the multiplicative inverse of a mod b this is euclid's
183 # extended algorithm. For more information see:
184 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
185 # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
186 # be the larger of the two values, and the two values should be
189 sub modular_multi_inverse {
194 my $origdivisor = $b->copy();
196 my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
197 my $x = Crypt::OpenSSL::Bignum->zero();
198 my $y = Crypt::OpenSSL::Bignum->one();
199 my $lastx = Crypt::OpenSSL::Bignum->one();
200 my $lasty = Crypt::OpenSSL::Bignum->zero();
205 while (! $b->is_zero()) {
206 my ($quotient, $remainder) = $a->div($b, $ctx);
212 $x = $lastx->sub($quotient->mul($x, $ctx));
216 $y = $lasty->sub($quotient->mul($y, $ctx));
221 die "did this math wrong.\n";
224 # let's make sure that we return a positive value because RFC 4880,
225 # section 3.2 only allows unsigned values:
227 ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
229 return $finalremainder;
233 ############ OpenPGP formatting functions ############
235 # make an old-style packet out of the given packet type and body.
236 # old-style (see RFC 4880 section 4.2)
242 my $len = length($body);
243 my $pseudolen = $len;
245 # if the caller wants to use at least N octets of packet length,
246 # pretend that we're using that many.
247 if (defined $options && defined $options->{'packet_length'}) {
248 $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
250 if ($pseudolen < $len) {
257 if ($pseudolen < 2**8) {
258 $lenbytes = $old_format_packet_lengths->{one};
260 } elsif ($pseudolen < 2**16) {
261 $lenbytes = $old_format_packet_lengths->{two};
263 } elsif ($pseudolen < 2**31) {
264 ## not testing against full 32 bits because i don't want to deal
265 ## with potential overflow.
266 $lenbytes = $old_format_packet_lengths->{four};
269 ## what the hell do we do here?
270 $lenbytes = $old_format_packet_lengths->{indeterminate};
274 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
279 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
280 # (RFC 4880 section 3.2)
284 my $val = $num->to_bin();
285 my $mpilen = length($val)*8;
287 # this is a kludgy way to get the number of significant bits in the
289 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
291 $mpilen -= (8 - $bitsinfirstbyte);
293 return pack('n', $mpilen).$val;
296 # FIXME: genericize these to accept either RSA or DSA keys:
297 sub make_rsa_pub_key_body {
299 my $timestamp = shift;
301 my ($n, $e) = $key->get_key_parameters();
304 pack('CN', 4, $timestamp).
305 pack('C', $asym_algos->{rsa}).
310 sub make_rsa_sec_key_body {
312 my $timestamp = shift;
314 # we're not using $a and $b, but we need them to get to $c.
315 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
317 my $c3 = modular_multi_inverse($p, $q);
319 my $secret_material = mpi_pack($d).
324 # according to Crypt::OpenSSL::RSA, the closest value we can get out
325 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
326 # RFC 4880, we're actually looking for u, the multiplicative inverse
327 # of p, mod q. This is why we're calculating the value directly
328 # with modular_multi_inverse.
331 pack('CN', 4, $timestamp).
332 pack('C', $asym_algos->{rsa}).
335 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
337 pack('n', simple_checksum($secret_material));
340 # expects an RSA key (public or private) and a timestamp
343 my $timestamp = shift;
345 my $rsabody = make_rsa_pub_key_body($key, $timestamp);
347 return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
352 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
353 $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
355 # we're just not dealing with newline business right now. slurp in
358 $rsa = Crypt::OpenSSL::RSA->new_private_key(<STDIN>);
361 $rsa->use_sha1_hash();
363 # see page 22 of RFC 4880 for why i think this is the right padding
365 $rsa->use_pkcs1_padding();
367 if (! $rsa->check_key()) {
368 die "key does not check";
371 my $version = pack('C', 4);
372 # strong assertion of identity:
373 my $sigtype = pack('C', $sig_types->{positive_certification});
375 my $pubkey_algo = pack('C', $asym_algos->{rsa});
377 my $hash_algo = pack('C', $digests->{sha1});
379 # FIXME: i'm worried about generating a bazillion new OpenPGP
380 # certificates from the same key, which could easily happen if you run
381 # this script more than once against the same key (because the
382 # timestamps will differ). How can we prevent this?
384 # this environment variable (if set) overrides the current time, to
385 # be able to create a standard key? If we read the key from a file
386 # instead of stdin, should we use the creation time on the file?
388 if (defined $ENV{PEM2OPENPGP_TIMESTAMP}) {
389 $timestamp = ($ENV{PEM2OPENPGP_TIMESTAMP} + 0);
394 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
398 if (! defined $ENV{PEM2OPENPGP_USAGE_FLAGS}) {
399 $flags = $usage_flags->{certify};
401 my @ff = split(",", $ENV{PEM2OPENPGP_USAGE_FLAGS});
402 foreach my $f (@ff) {
403 if (! defined $usage_flags->{$f}) {
404 die "No such flag $f";
406 $flags |= $usage_flags->{$f};
410 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
413 # how should we determine how far off to set the expiration date?
414 # default is no expiration. Specify the timestamp in seconds from the
416 my $expiration_packet = '';
417 if (defined $ENV{PEM2OPENPGP_EXPIRATION}) {
418 my $expires_in = $ENV{PEM2OPENPGP_EXPIRATION} + 0;
419 $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
423 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
424 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
429 $ciphers->{tripledes}
432 # prefer SHA-1, SHA-256, RIPE-MD/160
433 my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
436 $digests->{ripemd160}
439 # prefer ZLIB, BZip2, ZIP
440 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
446 # we support the MDC feature:
447 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
450 # keyserver preference: only owner modify (???):
451 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
452 $keyserver_prefs->{nomodify});
454 my $subpackets_to_be_hashed =
455 $creation_time_packet.
464 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
466 my $sig_data_to_be_hashed =
472 $subpackets_to_be_hashed;
474 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
475 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
477 # this is for signing. it needs to be an old-style header with a
478 # 2-packet octet count.
480 my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
482 # take the last 8 bytes of the fingerprint as the keyid:
483 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
485 # the v4 signature trailer is:
487 # version number, literal 0xff, and then a 4-byte count of the
488 # signature data itself.
489 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
492 pack('CN', 0xb4, length($uid)).
498 $sig_data_to_be_hashed.
501 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
503 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
505 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
508 $sig_data_to_be_hashed.
509 pack('n', length($issuer_packet)).
511 pack('n', hex(substr($data_hash, 0, 4))).
515 make_packet($packet_types->{seckey}, $seckey).
516 make_packet($packet_types->{uid}, $uid).
517 make_packet($packet_types->{sig}, $sig_body);