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;
34 ## make sure all length() and substr() calls use bytes only:
37 my $old_format_packet_lengths = { one => 0,
43 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
44 my $asym_algos = { rsa => 1,
49 # see RFC 4880 section 9.2
50 my $ciphers = { plaintext => 0,
61 # see RFC 4880 section 9.3
62 my $zips = { uncompressed => 0,
68 # see RFC 4880 section 9.4
69 my $digests = { md5 => 1,
78 # see RFC 4880 section 5.2.3.21
79 my $usage_flags = { certify => 0x01,
81 encrypt_comms => 0x04,
82 encrypt_storage => 0x08,
83 encrypt => 0x0c, ## both comms and storage
84 split => 0x10, # the private key is split via secret sharing
86 shared => 0x80, # more than one person holds the entire private key
89 # see RFC 4880 section 4.3
90 my $packet_types = { pubkey_enc_session => 1,
92 symkey_enc_session => 3,
105 symenc_w_integrity => 18,
109 # see RFC 4880 section 5.2.1
110 my $sig_types = { binary_doc => 0x00,
113 generic_certification => 0x10,
114 persona_certification => 0x11,
115 casual_certification => 0x12,
116 positive_certification => 0x13,
117 subkey_binding => 0x18,
118 primary_key_binding => 0x19,
119 key_signature => 0x1f,
120 key_revocation => 0x20,
121 subkey_revocation => 0x28,
122 certification_revocation => 0x30,
128 # see RFC 4880 section 5.2.3.1
129 my $subpacket_types = { sig_creation_time => 2,
130 sig_expiration_time => 3,
135 key_expiration_time => 9,
136 preferred_cipher => 11,
137 revocation_key => 12,
140 preferred_digest => 21,
141 preferred_compression => 22,
142 keyserver_prefs => 23,
143 preferred_keyserver => 24,
148 revocation_reason => 29,
150 signature_target => 31,
151 embedded_signature => 32,
154 # bitstring (see RFC 4880 section 5.2.3.24)
155 my $features = { mdc => 0x01
158 # bitstring (see RFC 4880 5.2.3.17)
159 my $keyserver_prefs = { nomodify => 0x80
162 ###### end lookup tables ######
164 # FIXME: if we want to be able to interpret openpgp data as well as
165 # produce it, we need to produce key/value-swapped lookup tables as well.
168 ########### Math/Utility Functions ##############
171 # see the bottom of page 43 of RFC 4880
172 sub simple_checksum {
175 return unpack("%32W*",$bytes) % 65536;
178 # calculate the multiplicative inverse of a mod b this is euclid's
179 # extended algorithm. For more information see:
180 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
181 # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
182 # be the larger of the two values, and the two values should be
185 sub modular_multi_inverse {
190 my $origdivisor = $b->copy();
192 my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
193 my $x = Crypt::OpenSSL::Bignum->zero();
194 my $y = Crypt::OpenSSL::Bignum->one();
195 my $lastx = Crypt::OpenSSL::Bignum->one();
196 my $lasty = Crypt::OpenSSL::Bignum->zero();
201 while (! $b->is_zero()) {
202 my ($quotient, $remainder) = $a->div($b, $ctx);
208 $x = $lastx->sub($quotient->mul($x, $ctx));
212 $y = $lasty->sub($quotient->mul($y, $ctx));
217 die "did this math wrong.\n";
220 # let's make sure that we return a positive value because RFC 4880,
221 # section 3.2 only allows unsigned values:
223 ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
225 return $finalremainder;
229 ############ OpenPGP formatting functions ############
231 # make an old-style packet out of the given packet type and body.
232 # old-style (see RFC 4880 section 4.2)
238 my $len = length($body);
239 my $pseudolen = $len;
241 # if the caller wants to use at least N octets of packet length,
242 # pretend that we're using that many.
243 if (defined $options && defined $options->{'packet_length'}) {
244 $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
246 if ($pseudolen < $len) {
253 if ($pseudolen < 2**8) {
254 $lenbytes = $old_format_packet_lengths->{one};
256 } elsif ($pseudolen < 2**16) {
257 $lenbytes = $old_format_packet_lengths->{two};
259 } elsif ($pseudolen < 2**31) {
260 ## not testing against full 32 bits because i don't want to deal
261 ## with potential overflow.
262 $lenbytes = $old_format_packet_lengths->{four};
265 ## what the hell do we do here?
266 $lenbytes = $old_format_packet_lengths->{indeterminate};
270 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
275 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
276 # (RFC 4880 section 3.2)
280 my $val = $num->to_bin();
281 my $mpilen = length($val)*8;
283 # this is a kludgy way to get the number of significant bits in the
285 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
287 $mpilen -= (8 - $bitsinfirstbyte);
289 return pack('n', $mpilen).$val;
292 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
293 # for an OpenSSH-style public key format. see:
294 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
295 sub openssh_mpi_pack {
298 my $val = $num->to_bin();
299 my $mpilen = length($val);
301 my $ret = pack('N', $mpilen);
303 # if the first bit of the leading byte is high, we should include a
305 if (ord($val) & 0x80) {
306 $ret = pack('NC', $mpilen+1, 0);
312 sub openssh_pubkey_pack {
315 my ($modulus, $exponent) = $key->get_key_parameters();
317 return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
318 openssh_mpi_pack($exponent).
319 openssh_mpi_pack($modulus);
322 # pull an OpenPGP-specified MPI off of a given stream, returning it as
323 # a Crypt::OpenSSL::Bignum.
326 my $readtally = shift;
329 read($instr, $bitlen, 2) or die "could not read MPI length.\n";
330 $bitlen = unpack('n', $bitlen);
333 my $bytestoread = POSIX::floor(($bitlen + 7)/8);
335 read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
336 $$readtally += $bytestoread;
337 return Crypt::OpenSSL::Bignum->new_from_bin($ret);
341 # FIXME: genericize these to accept either RSA or DSA keys:
342 sub make_rsa_pub_key_body {
344 my $timestamp = shift;
346 my ($n, $e) = $key->get_key_parameters();
349 pack('CN', 4, $timestamp).
350 pack('C', $asym_algos->{rsa}).
355 sub make_rsa_sec_key_body {
357 my $timestamp = shift;
359 # we're not using $a and $b, but we need them to get to $c.
360 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
362 my $c3 = modular_multi_inverse($p, $q);
364 my $secret_material = mpi_pack($d).
369 # according to Crypt::OpenSSL::RSA, the closest value we can get out
370 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
371 # RFC 4880, we're actually looking for u, the multiplicative inverse
372 # of p, mod q. This is why we're calculating the value directly
373 # with modular_multi_inverse.
376 pack('CN', 4, $timestamp).
377 pack('C', $asym_algos->{rsa}).
380 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
382 pack('n', simple_checksum($secret_material));
385 # expects an RSA key (public or private) and a timestamp
388 my $timestamp = shift;
390 my $rsabody = make_rsa_pub_key_body($key, $timestamp);
392 return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
396 # FIXME: handle DSA keys as well!
402 $rsa->use_sha1_hash();
404 # see page 22 of RFC 4880 for why i think this is the right padding
406 $rsa->use_pkcs1_padding();
408 if (! $rsa->check_key()) {
409 die "key does not check";
412 my $version = pack('C', 4);
413 # strong assertion of identity:
414 my $sigtype = pack('C', $sig_types->{positive_certification});
416 my $pubkey_algo = pack('C', $asym_algos->{rsa});
418 my $hash_algo = pack('C', $digests->{sha1});
420 # FIXME: i'm worried about generating a bazillion new OpenPGP
421 # certificates from the same key, which could easily happen if you run
422 # this script more than once against the same key (because the
423 # timestamps will differ). How can we prevent this?
425 # this environment variable (if set) overrides the current time, to
426 # be able to create a standard key? If we read the key from a file
427 # instead of stdin, should we use the creation time on the file?
429 if (defined $args->{timestamp}) {
430 $timestamp = ($args->{timestamp} + 0);
435 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
439 if (! defined $args->{usage_flags}) {
440 $flags = $usage_flags->{certify};
442 my @ff = split(",", $args->{usage_flags});
443 foreach my $f (@ff) {
444 if (! defined $usage_flags->{$f}) {
445 die "No such flag $f";
447 $flags |= $usage_flags->{$f};
451 my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
454 # how should we determine how far off to set the expiration date?
455 # default is no expiration. Specify the timestamp in seconds from the
457 my $expiration_packet = '';
458 if (defined $args->{expiration}) {
459 my $expires_in = $args->{expiration} + 0;
460 $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
464 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
465 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
470 $ciphers->{tripledes}
473 # prefer SHA-1, SHA-256, RIPE-MD/160
474 my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
477 $digests->{ripemd160}
480 # prefer ZLIB, BZip2, ZIP
481 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
487 # we support the MDC feature:
488 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
491 # keyserver preference: only owner modify (???):
492 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
493 $keyserver_prefs->{nomodify});
495 my $subpackets_to_be_hashed =
496 $creation_time_packet.
505 my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
507 my $sig_data_to_be_hashed =
513 $subpackets_to_be_hashed;
515 my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
516 my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
518 # this is for signing. it needs to be an old-style header with a
519 # 2-packet octet count.
521 my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
523 # take the last 8 bytes of the fingerprint as the keyid:
524 my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
526 # the v4 signature trailer is:
528 # version number, literal 0xff, and then a 4-byte count of the
529 # signature data itself.
530 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
533 pack('CN', 0xb4, length($uid)).
539 $sig_data_to_be_hashed.
542 my $data_hash = Digest::SHA1::sha1_hex($datatosign);
544 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
546 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
549 $sig_data_to_be_hashed.
550 pack('n', length($issuer_packet)).
552 pack('n', hex(substr($data_hash, 0, 4))).
556 make_packet($packet_types->{seckey}, $seckey).
557 make_packet($packet_types->{uid}, $uid).
558 make_packet($packet_types->{sig}, $sig_body);
567 if (length($fpr) < 8) {
568 die "We need at least 8 hex digits of fingerprint.\n";
579 while (! eof($instr)) {
580 read($instr, $packettag, 1);
581 $packettag = ord($packettag);
584 if ( ! (0x80 & $packettag)) {
585 die "This is not an OpenPGP packet\n";
587 if (0x40 & $packettag) {
588 $tag = (0x3f & $packettag);
590 read($instr, $nextlen, 1);
591 $nextlen = ord($nextlen);
592 if ($nextlen < 192) {
593 $packetlen = $nextlen;
594 } elsif ($nextlen < 224) {
596 read($instr, $newoct, 1);
597 $newoct = ord($newoct);
598 $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
599 } elsif ($nextlen == 255) {
600 read($instr, $nextlen, 4);
601 $packetlen = unpack('N', $nextlen);
603 # packet length is undefined.
607 $lentype = 0x03 & $packettag;
608 $tag = ( 0x3c & $packettag ) >> 2;
610 read($instr, $packetlen, 1) or die "could not read packet length\n";
611 $packetlen = unpack('C', $packetlen);
612 } elsif ($lentype == 1) {
613 read($instr, $packetlen, 2) or die "could not read packet length\n";
614 $packetlen = unpack('n', $packetlen);
615 } elsif ($lentype == 2) {
616 read($instr, $packetlen, 4) or die "could not read packet length\n";
617 $packetlen = unpack('N', $packetlen);
619 # packet length is undefined.
623 if (! defined($packetlen)) {
624 die "Undefined packet lengths are not supported.\n";
627 if ($tag == $packet_types->{pubkey} ||
628 $tag == $packet_types->{pub_subkey} ||
629 $tag == $packet_types->{seckey} ||
630 $tag == $packet_types->{sec_subkey}) {
633 read($instr, $ver, 1) or die "could not read key version\n";
638 printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
639 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
643 read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
645 $timestamp = unpack('N', $timestamp);
648 read($instr, $algo, 1) or die "could not read key algorithm.\n";
651 if ($algo != $asym_algos->{rsa}) {
652 printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
653 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
655 ## we have an RSA key.
656 my $modulus = read_mpi($instr, \$readbytes);
657 my $exponent = read_mpi($instr, \$readbytes);
659 my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
660 my $foundfpr = fingerprint($pubkey, $timestamp);
662 my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
665 if ((!defined($fpr)) ||
666 (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
668 die "Found two matching keys.\n";
673 if ($tag == $packet_types->{seckey} ||
674 $tag == $packet_types->{sec_subkey}) {
675 if (!defined($key)) { # we don't think the public part of
677 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
680 read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
684 # secret material is unencrypted
685 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
686 my $d = read_mpi($instr, \$readbytes);
687 my $p = read_mpi($instr, \$readbytes);
688 my $q = read_mpi($instr, \$readbytes);
689 my $u = read_mpi($instr, \$readbytes);
692 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
694 $checksum = unpack('n', $checksum);
696 # FIXME: compare with the checksum! how? the data is
697 # gone into the Crypt::OpenSSL::Bignum
699 $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
705 $key->check_key() or die "Secret key is not a valid RSA key.\n";
707 print(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
708 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
716 read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
725 if (/^pem2openpgp$/) {
730 defined($uid) or die "You must specify a user ID string.\n";
732 # FIXME: fail if there is no given user ID; or should we default to
733 # hostname_long() from Sys::Hostname::Long ?
736 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
737 $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
744 $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
747 print pem2openpgp($rsa,
749 { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
750 expiration => $ENV{PEM2OPENPGP_EXPIRATION},
751 usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
755 elsif (/^openpgp2ssh$/) {
759 binmode($instream, ":bytes");
760 my $key = openpgp2ssh($instream, $fpr);
762 if ($key->is_private()) {
763 print $key->get_private_key_string();
765 print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
768 die "No matching key found.\n";
772 die "Unrecognized keytrans call.\n";