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)
27 use Crypt::OpenSSL::RSA;
28 use Crypt::OpenSSL::Bignum;
29 use Crypt::OpenSSL::Bignum::CTX;
33 ## make sure all length() and substr() calls use bytes only:
36 my $old_format_packet_lengths = { one => 0,
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)
237 my $len = length($body);
238 my $pseudolen = $len;
240 # if the caller wants to use at least N octets of packet length,
241 # pretend that we're using that many.
242 if (defined $options && defined $options->{'packet_length'}) {
243 $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
245 if ($pseudolen < $len) {
252 if ($pseudolen < 2**8) {
253 $lenbytes = $old_format_packet_lengths->{one};
255 } elsif ($pseudolen < 2**16) {
256 $lenbytes = $old_format_packet_lengths->{two};
258 } elsif ($pseudolen < 2**31) {
259 ## not testing against full 32 bits because i don't want to deal
260 ## with potential overflow.
261 $lenbytes = $old_format_packet_lengths->{four};
264 ## what the hell do we do here?
265 $lenbytes = $old_format_packet_lengths->{indeterminate};
269 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
274 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
275 # (RFC 4880 section 3.2)
279 my $val = $num->to_bin();
280 my $mpilen = length($val)*8;
282 # this is a kludgy way to get the number of significant bits in the
284 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
286 $mpilen -= (8 - $bitsinfirstbyte);
288 return pack('n', $mpilen).$val;
291 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
292 # for an OpenSSH-style public key format. see:
293 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
294 sub openssh_mpi_pack {
297 my $val = $num->to_bin();
298 my $mpilen = length($val);
300 my $ret = pack('N', $mpilen);
302 # if the first bit of the leading byte is high, we should include a
304 if (ord($val) & 0x80) {
305 $ret = pack('NC', $mpilen+1, 0);
311 sub openssh_pubkey_pack {
314 my ($modulus, $exponent) = $key->get_key_parameters();
316 return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
317 openssh_mpi_pack($exponent).
318 openssh_mpi_pack($modulus);
321 # pull an OpenPGP-specified MPI off of a given stream, returning it as
322 # a Crypt::OpenSSL::Bignum.
325 my $readtally = shift;
328 read($instr, $bitlen, 2) or die "could not read MPI length.\n";
329 $bitlen = unpack('n', $bitlen);
332 my $bytestoread = ($bitlen + 7)/8;
334 read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
335 $$readtally += $bytestoread;
336 return Crypt::OpenSSL::Bignum->new_from_bin($ret);
340 # FIXME: genericize these to accept either RSA or DSA keys:
341 sub make_rsa_pub_key_body {
343 my $timestamp = shift;
345 my ($n, $e) = $key->get_key_parameters();
348 pack('CN', 4, $timestamp).
349 pack('C', $asym_algos->{rsa}).
354 sub make_rsa_sec_key_body {
356 my $timestamp = shift;
358 # we're not using $a and $b, but we need them to get to $c.
359 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
361 my $c3 = modular_multi_inverse($p, $q);
363 my $secret_material = mpi_pack($d).
368 # according to Crypt::OpenSSL::RSA, the closest value we can get out
369 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
370 # RFC 4880, we're actually looking for u, the multiplicative inverse
371 # of p, mod q. This is why we're calculating the value directly
372 # with modular_multi_inverse.
375 pack('CN', 4, $timestamp).
376 pack('C', $asym_algos->{rsa}).
379 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
381 pack('n', simple_checksum($secret_material));
384 # expects an RSA key (public or private) and a timestamp
387 my $timestamp = shift;
389 my $rsabody = make_rsa_pub_key_body($key, $timestamp);
391 return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
395 # FIXME: handle DSA keys as well!
401 $rsa->use_sha1_hash();
403 # see page 22 of RFC 4880 for why i think this is the right padding
405 $rsa->use_pkcs1_padding();
407 if (! $rsa->check_key()) {
408 die "key does not check";
411 my $version = pack('C', 4);
412 # strong assertion of identity:
413 my $sigtype = pack('C', $sig_types->{positive_certification});
415 my $pubkey_algo = pack('C', $asym_algos->{rsa});
417 my $hash_algo = pack('C', $digests->{sha1});
419 # FIXME: i'm worried about generating a bazillion new OpenPGP
420 # certificates from the same key, which could easily happen if you run
421 # this script more than once against the same key (because the
422 # timestamps will differ). How can we prevent this?
424 # this environment variable (if set) overrides the current time, to
425 # be able to create a standard key? If we read the key from a file
426 # instead of stdin, should we use the creation time on the file?
428 if (defined $args->{timestamp}) {
429 $timestamp = ($args->{timestamp} + 0);
434 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
438 if (! defined $args->{usage_flags}) {
439 $flags = $usage_flags->{certify};
441 my @ff = split(",", $args->{usage_flags});
442 foreach my $f (@ff) {
443 if (! defined $usage_flags->{$f}) {
444 die "No such flag $f";
446 $flags |= $usage_flags->{$f};
450 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
453 # how should we determine how far off to set the expiration date?
454 # default is no expiration. Specify the timestamp in seconds from the
456 my $expiration_packet = '';
457 if (defined $args->{expiration}) {
458 my $expires_in = $args->{expiration} + 0;
459 $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
463 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
464 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
469 $ciphers->{tripledes}
472 # prefer SHA-1, SHA-256, RIPE-MD/160
473 my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
476 $digests->{ripemd160}
479 # prefer ZLIB, BZip2, ZIP
480 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
486 # we support the MDC feature:
487 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
490 # keyserver preference: only owner modify (???):
491 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
492 $keyserver_prefs->{nomodify});
494 my $subpackets_to_be_hashed =
495 $creation_time_packet.
504 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
506 my $sig_data_to_be_hashed =
512 $subpackets_to_be_hashed;
514 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
515 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
517 # this is for signing. it needs to be an old-style header with a
518 # 2-packet octet count.
520 my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
522 # take the last 8 bytes of the fingerprint as the keyid:
523 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
525 # the v4 signature trailer is:
527 # version number, literal 0xff, and then a 4-byte count of the
528 # signature data itself.
529 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
532 pack('CN', 0xb4, length($uid)).
538 $sig_data_to_be_hashed.
541 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
543 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
545 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
548 $sig_data_to_be_hashed.
549 pack('n', length($issuer_packet)).
551 pack('n', hex(substr($data_hash, 0, 4))).
555 make_packet($packet_types->{seckey}, $seckey).
556 make_packet($packet_types->{uid}, $uid).
557 make_packet($packet_types->{sig}, $sig_body);
566 if (length($fpr) < 8) {
567 die "We need at least 8 hex digits of fingerprint.\n";
578 while (! eof($instr)) {
579 read($instr, $packettag, 1);
580 $packettag = ord($packettag);
583 if ( ! (0x80 & $packettag)) {
584 die "This is not an OpenPGP packet\n";
586 if (0x40 & $packettag) {
587 $tag = (0x3f & $packettag);
589 read($instr, $nextlen, 1);
590 $nextlen = ord($nextlen);
591 if ($nextlen < 192) {
592 $packetlen = $nextlen;
593 } elsif ($nextlen < 224) {
595 read($instr, $newoct, 1);
596 $newoct = ord($newoct);
597 $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
598 } elsif ($nextlen == 255) {
599 read($instr, $nextlen, 4);
600 $packetlen = unpack('N', $nextlen);
602 # packet length is undefined.
606 $lentype = 0x03 & $packettag;
607 $tag = ( 0x3c & $packettag ) >> 2;
609 read($instr, $packetlen, 1) or die "could not read packet length\n";
610 $packetlen = unpack('C', $packetlen);
611 } elsif ($lentype == 1) {
612 read($instr, $packetlen, 2) or die "could not read packet length\n";
613 $packetlen = unpack('n', $packetlen);
614 } elsif ($lentype == 2) {
615 read($instr, $packetlen, 4) or die "could not read packet length\n";
616 $packetlen = unpack('N', $packetlen);
618 # packet length is undefined.
622 if (! defined($packetlen)) {
623 die "Undefined packet lengths are not supported.\n";
626 if ($tag == $packet_types->{pubkey} ||
627 $tag == $packet_types->{pub_subkey} ||
628 $tag == $packet_types->{seckey} ||
629 $tag == $packet_types->{sec_subkey}) {
632 read($instr, $ver, 1) or die "could not read key version\n";
637 printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
638 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
642 read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
644 $timestamp = unpack('N', $timestamp);
647 read($instr, $algo, 1) or die "could not read key algorithm.\n";
650 if ($algo != $asym_algos->{rsa}) {
651 printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
652 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
654 ## we have an RSA key.
655 my $modulus = read_mpi($instr, \$readbytes);
656 my $exponent = read_mpi($instr, \$readbytes);
658 my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
659 my $foundfpr = fingerprint($pubkey, $timestamp);
661 my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
664 if ((!defined($fpr)) ||
665 (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
667 die "Found two matching keys.\n";
672 if ($tag == $packet_types->{seckey} ||
673 $tag == $packet_types->{sec_subkey}) {
674 if (!defined($key)) { # we don't think the public part of
676 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
679 read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
683 # secret material is unencrypted
684 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
685 my $d = read_mpi($instr, \$readbytes);
686 my $p = read_mpi($instr, \$readbytes);
687 my $q = read_mpi($instr, \$readbytes);
688 my $u = read_mpi($instr, \$readbytes);
691 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
693 $checksum = unpack('n', $checksum);
695 # FIXME: compare with the checksum! how? the data is
696 # gone into the Crypt::OpenSSL::Bignum
698 $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
704 $key->check_key() or die "Secret key is not a valid RSA key.\n";
706 print(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
707 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
715 read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
724 if (/^pem2openpgp$/) {
729 defined($uid) or die "You must specify a user ID string.\n";
731 # FIXME: fail if there is no given user ID; or should we default to
732 # hostname_long() from Sys::Hostname::Long ?
735 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
736 $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
743 $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
746 print pem2openpgp($rsa,
748 { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
749 expiration => $ENV{PEM2OPENPGP_EXPIRATION},
750 usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
754 elsif (/^openpgp2ssh$/) {
758 binmode($instream, ":bytes");
759 my $key = openpgp2ssh($instream, $fpr);
761 if ($key->is_private()) {
762 print $key->get_private_key_string();
764 print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
767 die "No matching key found.\n";
771 die "Unrecognized keytrans call.\n";