3 # keytrans: this is an RSA key translation utility; it is capable of
4 # transforming RSA keys (both public keys and secret keys) between
5 # several popular representations, including OpenPGP, PEM-encoded
6 # PKCS#1 DER, and OpenSSH-style public key lines.
8 # How it behaves depends on the name under which it is invoked. The
9 # two implementations currently are: pem2openpgp and openpgp2ssh.
13 # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
14 # User ID as the first argument, and generate an OpenPGP secret key
15 # and certificate from it.
17 # WARNING: the secret key material *will* appear on stdout (albeit in
18 # OpenPGP form) -- if you redirect stdout to a file, make sure the
19 # permissions on that file are appropriately locked down!
23 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
28 # openpgp2ssh: take a stream of OpenPGP packets containing public or
29 # secret key material on standard input, and a Key ID (or fingerprint)
30 # as the first argument. Find the matching key in the input stream,
31 # and emit it on stdout in an OpenSSH-compatible format. If the input
32 # key is an OpenPGP public key (either primary or subkey), the output
33 # will be an OpenSSH single-line public key. If the input key is an
34 # OpenPGP secret key, the output will be a PEM-encoded RSA key.
38 # gpg --export-secret-subkeys --export-options export-reset-subkey-passwd $KEYID | \
39 # openpgp2ssh $KEYID | ssh-add /dev/stdin
43 # Jameson Rollins <jrollins@finestructure.net>
44 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
46 # Started on: 2009-01-07 02:01:19-0500
48 # License: GPL v3 or later (we may need to adjust this given that this
49 # connects to OpenSSL via perl)
54 use Crypt::OpenSSL::RSA;
55 use Crypt::OpenSSL::Bignum;
56 use Crypt::OpenSSL::Bignum::CTX;
61 ## make sure all length() and substr() calls use bytes only:
64 my $old_format_packet_lengths = { one => 0,
70 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
71 my $asym_algos = { rsa => 1,
76 # see RFC 4880 section 9.2
77 my $ciphers = { plaintext => 0,
88 # see RFC 4880 section 9.3
89 my $zips = { uncompressed => 0,
95 # see RFC 4880 section 9.4
96 my $digests = { md5 => 1,
105 # see RFC 4880 section 5.2.3.21
106 my $usage_flags = { certify => 0x01,
108 encrypt_comms => 0x04,
109 encrypt_storage => 0x08,
110 encrypt => 0x0c, ## both comms and storage
111 split => 0x10, # the private key is split via secret sharing
112 authenticate => 0x20,
113 shared => 0x80, # more than one person holds the entire private key
116 # see RFC 4880 section 4.3
117 my $packet_types = { pubkey_enc_session => 1,
119 symkey_enc_session => 3,
124 compressed_data => 8,
132 symenc_w_integrity => 18,
136 # see RFC 4880 section 5.2.1
137 my $sig_types = { binary_doc => 0x00,
140 generic_certification => 0x10,
141 persona_certification => 0x11,
142 casual_certification => 0x12,
143 positive_certification => 0x13,
144 subkey_binding => 0x18,
145 primary_key_binding => 0x19,
146 key_signature => 0x1f,
147 key_revocation => 0x20,
148 subkey_revocation => 0x28,
149 certification_revocation => 0x30,
155 # see RFC 4880 section 5.2.3.1
156 my $subpacket_types = { sig_creation_time => 2,
157 sig_expiration_time => 3,
162 key_expiration_time => 9,
163 preferred_cipher => 11,
164 revocation_key => 12,
167 preferred_digest => 21,
168 preferred_compression => 22,
169 keyserver_prefs => 23,
170 preferred_keyserver => 24,
175 revocation_reason => 29,
177 signature_target => 31,
178 embedded_signature => 32,
181 # bitstring (see RFC 4880 section 5.2.3.24)
182 my $features = { mdc => 0x01
185 # bitstring (see RFC 4880 5.2.3.17)
186 my $keyserver_prefs = { nomodify => 0x80
189 ###### end lookup tables ######
191 # FIXME: if we want to be able to interpret openpgp data as well as
192 # produce it, we need to produce key/value-swapped lookup tables as well.
195 ########### Math/Utility Functions ##############
198 # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
199 sub simple_checksum {
202 return unpack("%16C*",$bytes);
205 # calculate the multiplicative inverse of a mod b this is euclid's
206 # extended algorithm. For more information see:
207 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
208 # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
209 # be the larger of the two values, and the two values should be
212 sub modular_multi_inverse {
217 my $origdivisor = $b->copy();
219 my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
220 my $x = Crypt::OpenSSL::Bignum->zero();
221 my $y = Crypt::OpenSSL::Bignum->one();
222 my $lastx = Crypt::OpenSSL::Bignum->one();
223 my $lasty = Crypt::OpenSSL::Bignum->zero();
228 while (! $b->is_zero()) {
229 my ($quotient, $remainder) = $a->div($b, $ctx);
235 $x = $lastx->sub($quotient->mul($x, $ctx));
239 $y = $lasty->sub($quotient->mul($y, $ctx));
244 die "did this math wrong.\n";
247 # let's make sure that we return a positive value because RFC 4880,
248 # section 3.2 only allows unsigned values:
250 ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
252 return $finalremainder;
256 ############ OpenPGP formatting functions ############
258 # make an old-style packet out of the given packet type and body.
259 # old-style (see RFC 4880 section 4.2)
265 my $len = length($body);
266 my $pseudolen = $len;
268 # if the caller wants to use at least N octets of packet length,
269 # pretend that we're using that many.
270 if (defined $options && defined $options->{'packet_length'}) {
271 $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
273 if ($pseudolen < $len) {
280 if ($pseudolen < 2**8) {
281 $lenbytes = $old_format_packet_lengths->{one};
283 } elsif ($pseudolen < 2**16) {
284 $lenbytes = $old_format_packet_lengths->{two};
286 } elsif ($pseudolen < 2**31) {
287 ## not testing against full 32 bits because i don't want to deal
288 ## with potential overflow.
289 $lenbytes = $old_format_packet_lengths->{four};
292 ## what the hell do we do here?
293 $lenbytes = $old_format_packet_lengths->{indeterminate};
297 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
302 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
303 # (RFC 4880 section 3.2)
307 my $val = $num->to_bin();
308 my $mpilen = length($val)*8;
310 # this is a kludgy way to get the number of significant bits in the
312 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
314 $mpilen -= (8 - $bitsinfirstbyte);
316 return pack('n', $mpilen).$val;
319 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
320 # for an OpenSSH-style public key format. see:
321 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
322 sub openssh_mpi_pack {
325 my $val = $num->to_bin();
326 my $mpilen = length($val);
328 my $ret = pack('N', $mpilen);
330 # if the first bit of the leading byte is high, we should include a
332 if (ord($val) & 0x80) {
333 $ret = pack('NC', $mpilen+1, 0);
339 sub openssh_pubkey_pack {
342 my ($modulus, $exponent) = $key->get_key_parameters();
344 return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
345 openssh_mpi_pack($exponent).
346 openssh_mpi_pack($modulus);
349 # pull an OpenPGP-specified MPI off of a given stream, returning it as
350 # a Crypt::OpenSSL::Bignum.
353 my $readtally = shift;
356 read($instr, $bitlen, 2) or die "could not read MPI length.\n";
357 $bitlen = unpack('n', $bitlen);
360 my $bytestoread = POSIX::floor(($bitlen + 7)/8);
362 read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
363 $$readtally += $bytestoread;
364 return Crypt::OpenSSL::Bignum->new_from_bin($ret);
368 # FIXME: genericize these to accept either RSA or DSA keys:
369 sub make_rsa_pub_key_body {
371 my $timestamp = shift;
373 my ($n, $e) = $key->get_key_parameters();
376 pack('CN', 4, $timestamp).
377 pack('C', $asym_algos->{rsa}).
382 sub make_rsa_sec_key_body {
384 my $timestamp = shift;
386 # we're not using $a and $b, but we need them to get to $c.
387 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
389 my $c3 = modular_multi_inverse($p, $q);
391 my $secret_material = mpi_pack($d).
396 # according to Crypt::OpenSSL::RSA, the closest value we can get out
397 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
398 # RFC 4880, we're actually looking for u, the multiplicative inverse
399 # of p, mod q. This is why we're calculating the value directly
400 # with modular_multi_inverse.
403 pack('CN', 4, $timestamp).
404 pack('C', $asym_algos->{rsa}).
407 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
409 pack('n', simple_checksum($secret_material));
412 # expects an RSA key (public or private) and a timestamp
415 my $timestamp = shift;
417 my $rsabody = make_rsa_pub_key_body($key, $timestamp);
419 return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
423 # FIXME: handle DSA keys as well!
429 $rsa->use_sha256_hash();
431 # see page 22 of RFC 4880 for why i think this is the right padding
433 $rsa->use_pkcs1_padding();
435 if (! $rsa->check_key()) {
436 die "key does not check";
439 my $version = pack('C', 4);
440 # strong assertion of identity:
441 my $sigtype = pack('C', $sig_types->{positive_certification});
443 my $pubkey_algo = pack('C', $asym_algos->{rsa});
445 my $hash_algo = pack('C', $digests->{sha256});
447 # FIXME: i'm worried about generating a bazillion new OpenPGP
448 # certificates from the same key, which could easily happen if you run
449 # this script more than once against the same key (because the
450 # timestamps will differ). How can we prevent this?
452 # this environment variable (if set) overrides the current time, to
453 # be able to create a standard key? If we read the key from a file
454 # instead of stdin, should we use the creation time on the file?
456 if (defined $args->{timestamp}) {
457 $timestamp = ($args->{timestamp} + 0);
462 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
466 if (! defined $args->{usage_flags}) {
467 $flags = $usage_flags->{certify};
469 my @ff = split(",", $args->{usage_flags});
470 foreach my $f (@ff) {
471 if (! defined $usage_flags->{$f}) {
472 die "No such flag $f";
474 $flags |= $usage_flags->{$f};
478 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
481 # how should we determine how far off to set the expiration date?
482 # default is no expiration. Specify the timestamp in seconds from the
484 my $expiration_packet = '';
485 if (defined $args->{expiration}) {
486 my $expires_in = $args->{expiration} + 0;
487 $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
491 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
492 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
497 $ciphers->{tripledes}
500 # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
501 my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
506 $digests->{ripemd160},
510 # prefer ZLIB, BZip2, ZIP
511 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
517 # we support the MDC feature:
518 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
521 # keyserver preference: only owner modify (???):
522 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
523 $keyserver_prefs->{nomodify});
525 my $subpackets_to_be_hashed =
526 $creation_time_packet.
535 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
537 my $sig_data_to_be_hashed =
543 $subpackets_to_be_hashed;
545 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
546 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
548 # this is for signing. it needs to be an old-style header with a
549 # 2-packet octet count.
551 my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
553 # take the last 8 bytes of the fingerprint as the keyid:
554 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
556 # the v4 signature trailer is:
558 # version number, literal 0xff, and then a 4-byte count of the
559 # signature data itself.
560 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
563 pack('CN', 0xb4, length($uid)).
569 $sig_data_to_be_hashed.
572 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
574 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
576 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
579 $sig_data_to_be_hashed.
580 pack('n', length($issuer_packet)).
582 pack('n', hex(substr($data_hash, 0, 4))).
586 make_packet($packet_types->{seckey}, $seckey).
587 make_packet($packet_types->{uid}, $uid).
588 make_packet($packet_types->{sig}, $sig_body);
597 if (length($fpr) < 8) {
598 die "We need at least 8 hex digits of fingerprint.\n";
609 while (! eof($instr)) {
610 read($instr, $packettag, 1);
611 $packettag = ord($packettag);
614 if ( ! (0x80 & $packettag)) {
615 die "This is not an OpenPGP packet\n";
617 if (0x40 & $packettag) {
618 $tag = (0x3f & $packettag);
620 read($instr, $nextlen, 1);
621 $nextlen = ord($nextlen);
622 if ($nextlen < 192) {
623 $packetlen = $nextlen;
624 } elsif ($nextlen < 224) {
626 read($instr, $newoct, 1);
627 $newoct = ord($newoct);
628 $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
629 } elsif ($nextlen == 255) {
630 read($instr, $nextlen, 4);
631 $packetlen = unpack('N', $nextlen);
633 # packet length is undefined.
637 $lentype = 0x03 & $packettag;
638 $tag = ( 0x3c & $packettag ) >> 2;
640 read($instr, $packetlen, 1) or die "could not read packet length\n";
641 $packetlen = unpack('C', $packetlen);
642 } elsif ($lentype == 1) {
643 read($instr, $packetlen, 2) or die "could not read packet length\n";
644 $packetlen = unpack('n', $packetlen);
645 } elsif ($lentype == 2) {
646 read($instr, $packetlen, 4) or die "could not read packet length\n";
647 $packetlen = unpack('N', $packetlen);
649 # packet length is undefined.
653 if (! defined($packetlen)) {
654 die "Undefined packet lengths are not supported.\n";
657 if ($tag == $packet_types->{pubkey} ||
658 $tag == $packet_types->{pub_subkey} ||
659 $tag == $packet_types->{seckey} ||
660 $tag == $packet_types->{sec_subkey}) {
663 read($instr, $ver, 1) or die "could not read key version\n";
668 printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
669 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
673 read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
675 $timestamp = unpack('N', $timestamp);
678 read($instr, $algo, 1) or die "could not read key algorithm.\n";
681 if ($algo != $asym_algos->{rsa}) {
682 printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
683 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
685 ## we have an RSA key.
686 my $modulus = read_mpi($instr, \$readbytes);
687 my $exponent = read_mpi($instr, \$readbytes);
689 my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
690 my $foundfpr = fingerprint($pubkey, $timestamp);
692 my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
695 if ((!defined($fpr)) ||
696 (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
698 die "Found two matching keys.\n";
703 if ($tag == $packet_types->{seckey} ||
704 $tag == $packet_types->{sec_subkey}) {
705 if (!defined($key)) { # we don't think the public part of
707 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
710 read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
714 # secret material is unencrypted
715 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
716 my $d = read_mpi($instr, \$readbytes);
717 my $p = read_mpi($instr, \$readbytes);
718 my $q = read_mpi($instr, \$readbytes);
719 my $u = read_mpi($instr, \$readbytes);
722 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
724 $checksum = unpack('n', $checksum);
726 # FIXME: compare with the checksum! how? the data is
727 # gone into the Crypt::OpenSSL::Bignum
729 $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
735 $key->check_key() or die "Secret key is not a valid RSA key.\n";
737 print(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
738 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
746 read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
755 if (/^pem2openpgp$/) {
760 defined($uid) or die "You must specify a user ID string.\n";
762 # FIXME: fail if there is no given user ID; or should we default to
763 # hostname_long() from Sys::Hostname::Long ?
766 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
767 $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
774 $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
777 print pem2openpgp($rsa,
779 { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
780 expiration => $ENV{PEM2OPENPGP_EXPIRATION},
781 usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
785 elsif (/^openpgp2ssh$/) {
789 binmode($instream, ":bytes");
790 my $key = openpgp2ssh($instream, $fpr);
792 if ($key->is_private()) {
793 print $key->get_private_key_string();
795 print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
798 die "No matching key found.\n";
802 die "Unrecognized keytrans call.\n";