summaryrefslogtreecommitdiff
path: root/src/share/keytrans
blob: a13d3827a474a518252f82281c1250638fe6dbcb (plain)
  1. #!/usr/bin/perl -T
  2. # keytrans: this is an RSA key translation utility; it is capable of
  3. # transforming RSA keys (both public keys and secret keys) between
  4. # several popular representations, including OpenPGP, PEM-encoded
  5. # PKCS#1 DER, and OpenSSH-style public key lines.
  6. # How it behaves depends on the name under which it is invoked. The
  7. # two implementations currently are: pem2openpgp and openpgp2ssh.
  8. # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
  9. # User ID as the first argument, and generate an OpenPGP secret key
  10. # and certificate from it.
  11. # WARNING: the secret key material *will* appear on stdout (albeit in
  12. # OpenPGP form) -- if you redirect stdout to a file, make sure the
  13. # permissions on that file are appropriately locked down!
  14. # Usage:
  15. # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
  16. # openpgp2ssh: take a stream of OpenPGP packets containing public or
  17. # secret key material on standard input, and a Key ID (or fingerprint)
  18. # as the first argument. Find the matching key in the input stream,
  19. # and emit it on stdout in an OpenSSH-compatible format. If the input
  20. # key is an OpenPGP public key (either primary or subkey), the output
  21. # will be an OpenSSH single-line public key. If the input key is an
  22. # OpenPGP secret key, the output will be a PEM-encoded RSA key.
  23. # Example usage:
  24. # gpg --export-secret-subkeys --export-options export-reset-subkey-passwd $KEYID | \
  25. # openpgp2ssh $KEYID | ssh-add /dev/stdin
  26. # Authors:
  27. # Jameson Rollins <jrollins@finestructure.net>
  28. # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
  29. # Started on: 2009-01-07 02:01:19-0500
  30. # License: GPL v3 or later (we may need to adjust this given that this
  31. # connects to OpenSSL via perl)
  32. use strict;
  33. use warnings;
  34. use File::Basename;
  35. use Crypt::OpenSSL::RSA;
  36. use Crypt::OpenSSL::Bignum;
  37. use Crypt::OpenSSL::Bignum::CTX;
  38. use Digest::SHA;
  39. use MIME::Base64;
  40. use POSIX;
  41. ## make sure all length() and substr() calls use bytes only:
  42. use bytes;
  43. my $old_format_packet_lengths = { one => 0,
  44. two => 1,
  45. four => 2,
  46. indeterminate => 3,
  47. };
  48. # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
  49. my $asym_algos = { rsa => 1,
  50. elgamal => 16,
  51. dsa => 17,
  52. };
  53. # see RFC 4880 section 9.2
  54. my $ciphers = { plaintext => 0,
  55. idea => 1,
  56. tripledes => 2,
  57. cast5 => 3,
  58. blowfish => 4,
  59. aes128 => 7,
  60. aes192 => 8,
  61. aes256 => 9,
  62. twofish => 10,
  63. };
  64. # see RFC 4880 section 9.3
  65. my $zips = { uncompressed => 0,
  66. zip => 1,
  67. zlib => 2,
  68. bzip2 => 3,
  69. };
  70. # see RFC 4880 section 9.4
  71. my $digests = { md5 => 1,
  72. sha1 => 2,
  73. ripemd160 => 3,
  74. sha256 => 8,
  75. sha384 => 9,
  76. sha512 => 10,
  77. sha224 => 11,
  78. };
  79. # see RFC 4880 section 5.2.3.21
  80. my $usage_flags = { certify => 0x01,
  81. sign => 0x02,
  82. encrypt_comms => 0x04,
  83. encrypt_storage => 0x08,
  84. encrypt => 0x0c, ## both comms and storage
  85. split => 0x10, # the private key is split via secret sharing
  86. authenticate => 0x20,
  87. shared => 0x80, # more than one person holds the entire private key
  88. };
  89. # see RFC 4880 section 4.3
  90. my $packet_types = { pubkey_enc_session => 1,
  91. sig => 2,
  92. symkey_enc_session => 3,
  93. onepass_sig => 4,
  94. seckey => 5,
  95. pubkey => 6,
  96. sec_subkey => 7,
  97. compressed_data => 8,
  98. symenc_data => 9,
  99. marker => 10,
  100. literal => 11,
  101. trust => 12,
  102. uid => 13,
  103. pub_subkey => 14,
  104. uat => 17,
  105. symenc_w_integrity => 18,
  106. mdc => 19,
  107. };
  108. # see RFC 4880 section 5.2.1
  109. my $sig_types = { binary_doc => 0x00,
  110. text_doc => 0x01,
  111. standalone => 0x02,
  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,
  122. timestamp => 0x40,
  123. thirdparty => 0x50,
  124. };
  125. # see RFC 4880 section 5.2.3.1
  126. my $subpacket_types = { sig_creation_time => 2,
  127. sig_expiration_time => 3,
  128. exportable => 4,
  129. trust_sig => 5,
  130. regex => 6,
  131. revocable => 7,
  132. key_expiration_time => 9,
  133. preferred_cipher => 11,
  134. revocation_key => 12,
  135. issuer => 16,
  136. notation => 20,
  137. preferred_digest => 21,
  138. preferred_compression => 22,
  139. keyserver_prefs => 23,
  140. preferred_keyserver => 24,
  141. primary_uid => 25,
  142. policy_uri => 26,
  143. usage_flags => 27,
  144. signers_uid => 28,
  145. revocation_reason => 29,
  146. features => 30,
  147. signature_target => 31,
  148. embedded_signature => 32,
  149. };
  150. # bitstring (see RFC 4880 section 5.2.3.24)
  151. my $features = { mdc => 0x01
  152. };
  153. # bitstring (see RFC 4880 5.2.3.17)
  154. my $keyserver_prefs = { nomodify => 0x80
  155. };
  156. ###### end lookup tables ######
  157. # FIXME: if we want to be able to interpret openpgp data as well as
  158. # produce it, we need to produce key/value-swapped lookup tables as well.
  159. ########### Math/Utility Functions ##############
  160. # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
  161. sub simple_checksum {
  162. my $bytes = shift;
  163. return unpack("%16C*",$bytes);
  164. }
  165. # calculate the multiplicative inverse of a mod b this is euclid's
  166. # extended algorithm. For more information see:
  167. # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
  168. # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
  169. # be the larger of the two values, and the two values should be
  170. # coprime.
  171. sub modular_multi_inverse {
  172. my $a = shift;
  173. my $b = shift;
  174. my $origdivisor = $b->copy();
  175. my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
  176. my $x = Crypt::OpenSSL::Bignum->zero();
  177. my $y = Crypt::OpenSSL::Bignum->one();
  178. my $lastx = Crypt::OpenSSL::Bignum->one();
  179. my $lasty = Crypt::OpenSSL::Bignum->zero();
  180. my $finalquotient;
  181. my $finalremainder;
  182. while (! $b->is_zero()) {
  183. my ($quotient, $remainder) = $a->div($b, $ctx);
  184. $a = $b;
  185. $b = $remainder;
  186. my $temp = $x;
  187. $x = $lastx->sub($quotient->mul($x, $ctx));
  188. $lastx = $temp;
  189. $temp = $y;
  190. $y = $lasty->sub($quotient->mul($y, $ctx));
  191. $lasty = $temp;
  192. }
  193. if (!$a->is_one()) {
  194. die "did this math wrong.\n";
  195. }
  196. # let's make sure that we return a positive value because RFC 4880,
  197. # section 3.2 only allows unsigned values:
  198. ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
  199. return $finalremainder;
  200. }
  201. ############ OpenPGP formatting functions ############
  202. # make an old-style packet out of the given packet type and body.
  203. # old-style (see RFC 4880 section 4.2)
  204. sub make_packet {
  205. my $type = shift;
  206. my $body = shift;
  207. my $options = shift;
  208. my $len = length($body);
  209. my $pseudolen = $len;
  210. # if the caller wants to use at least N octets of packet length,
  211. # pretend that we're using that many.
  212. if (defined $options && defined $options->{'packet_length'}) {
  213. $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
  214. }
  215. if ($pseudolen < $len) {
  216. $pseudolen = $len;
  217. }
  218. my $lenbytes;
  219. my $lencode;
  220. if ($pseudolen < 2**8) {
  221. $lenbytes = $old_format_packet_lengths->{one};
  222. $lencode = 'C';
  223. } elsif ($pseudolen < 2**16) {
  224. $lenbytes = $old_format_packet_lengths->{two};
  225. $lencode = 'n';
  226. } elsif ($pseudolen < 2**31) {
  227. ## not testing against full 32 bits because i don't want to deal
  228. ## with potential overflow.
  229. $lenbytes = $old_format_packet_lengths->{four};
  230. $lencode = 'N';
  231. } else {
  232. ## what the hell do we do here?
  233. $lenbytes = $old_format_packet_lengths->{indeterminate};
  234. $lencode = '';
  235. }
  236. return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
  237. $body;
  238. }
  239. # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
  240. # (RFC 4880 section 3.2)
  241. sub mpi_pack {
  242. my $num = shift;
  243. my $val = $num->to_bin();
  244. my $mpilen = length($val)*8;
  245. # this is a kludgy way to get the number of significant bits in the
  246. # first byte:
  247. my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
  248. $mpilen -= (8 - $bitsinfirstbyte);
  249. return pack('n', $mpilen).$val;
  250. }
  251. # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
  252. # for an OpenSSH-style public key format. see:
  253. # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
  254. sub openssh_mpi_pack {
  255. my $num = shift;
  256. my $val = $num->to_bin();
  257. my $mpilen = length($val);
  258. my $ret = pack('N', $mpilen);
  259. # if the first bit of the leading byte is high, we should include a
  260. # 0 byte:
  261. if (ord($val) & 0x80) {
  262. $ret = pack('NC', $mpilen+1, 0);
  263. }
  264. return $ret.$val;
  265. }
  266. sub openssh_pubkey_pack {
  267. my $key = shift;
  268. my ($modulus, $exponent) = $key->get_key_parameters();
  269. return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
  270. openssh_mpi_pack($exponent).
  271. openssh_mpi_pack($modulus);
  272. }
  273. # pull an OpenPGP-specified MPI off of a given stream, returning it as
  274. # a Crypt::OpenSSL::Bignum.
  275. sub read_mpi {
  276. my $instr = shift;
  277. my $readtally = shift;
  278. my $bitlen;
  279. read($instr, $bitlen, 2) or die "could not read MPI length.\n";
  280. $bitlen = unpack('n', $bitlen);
  281. $$readtally += 2;
  282. my $bytestoread = POSIX::floor(($bitlen + 7)/8);
  283. my $ret;
  284. read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
  285. $$readtally += $bytestoread;
  286. return Crypt::OpenSSL::Bignum->new_from_bin($ret);
  287. }
  288. # FIXME: genericize these to accept either RSA or DSA keys:
  289. sub make_rsa_pub_key_body {
  290. my $key = shift;
  291. my $key_timestamp = shift;
  292. my ($n, $e) = $key->get_key_parameters();
  293. return
  294. pack('CN', 4, $key_timestamp).
  295. pack('C', $asym_algos->{rsa}).
  296. mpi_pack($n).
  297. mpi_pack($e);
  298. }
  299. sub make_rsa_sec_key_body {
  300. my $key = shift;
  301. my $key_timestamp = shift;
  302. # we're not using $a and $b, but we need them to get to $c.
  303. my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
  304. my $c3 = modular_multi_inverse($p, $q);
  305. my $secret_material = mpi_pack($d).
  306. mpi_pack($p).
  307. mpi_pack($q).
  308. mpi_pack($c3);
  309. # according to Crypt::OpenSSL::RSA, the closest value we can get out
  310. # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
  311. # RFC 4880, we're actually looking for u, the multiplicative inverse
  312. # of p, mod q. This is why we're calculating the value directly
  313. # with modular_multi_inverse.
  314. return
  315. pack('CN', 4, $key_timestamp).
  316. pack('C', $asym_algos->{rsa}).
  317. mpi_pack($n).
  318. mpi_pack($e).
  319. pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
  320. $secret_material.
  321. pack('n', simple_checksum($secret_material));
  322. }
  323. # expects an RSA key (public or private) and a timestamp
  324. sub fingerprint {
  325. my $key = shift;
  326. my $key_timestamp = shift;
  327. my $rsabody = make_rsa_pub_key_body($key, $key_timestamp);
  328. return Digest::SHA::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  329. }
  330. # FIXME: handle DSA keys as well!
  331. sub pem2openpgp {
  332. my $rsa = shift;
  333. my $uid = shift;
  334. my $args = shift;
  335. $rsa->use_sha256_hash();
  336. # see page 22 of RFC 4880 for why i think this is the right padding
  337. # choice to use:
  338. $rsa->use_pkcs1_padding();
  339. if (! $rsa->check_key()) {
  340. die "key does not check";
  341. }
  342. # strong assertion of identity is the default (for a self-sig):
  343. my $certtype = $sig_types->{positive_certification};
  344. if (defined $args->{certification_type}) {
  345. $certtype = $args->{certification_type} + 0;
  346. }
  347. my $version = pack('C', 4);
  348. my $sigtype = pack('C', $certtype);
  349. # RSA
  350. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  351. # SHA256
  352. my $hash_algo = pack('C', $digests->{sha256});
  353. # FIXME: i'm worried about generating a bazillion new OpenPGP
  354. # certificates from the same key, which could easily happen if you run
  355. # this script more than once against the same key (because the
  356. # timestamps will differ). How can we prevent this?
  357. # this argument (if set) overrides the current time, to
  358. # be able to create a standard key. If we read the key from a file
  359. # instead of stdin, should we use the creation time on the file?
  360. my $sig_timestamp = 0;
  361. if (defined $args->{sig_timestamp}) {
  362. $sig_timestamp = ($args->{sig_timestamp} + 0);
  363. } else {
  364. $sig_timestamp = time();
  365. }
  366. my $key_timestamp = $sig_timestamp;
  367. if (defined $args->{key_timestamp}) {
  368. $key_timestamp = ($args->{key_timestamp} + 0);
  369. }
  370. if ($key_timestamp > $sig_timestamp) {
  371. die "key timestamp must not be later than signature timestamp";
  372. }
  373. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
  374. my $flags = 0;
  375. if (! defined $args->{usage_flags}) {
  376. $flags = $usage_flags->{certify};
  377. } else {
  378. my @ff = split(",", $args->{usage_flags});
  379. foreach my $f (@ff) {
  380. if (! defined $usage_flags->{$f}) {
  381. die "No such flag $f";
  382. }
  383. $flags |= $usage_flags->{$f};
  384. }
  385. }
  386. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  387. # how should we determine how far off to set the expiration date?
  388. # default is no expiration. Specify the timestamp in seconds from the
  389. # key creation.
  390. my $expiration_packet = '';
  391. if (defined $args->{expiration}) {
  392. my $expires_in = $args->{expiration} + 0;
  393. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  394. }
  395. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  396. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  397. $ciphers->{aes256},
  398. $ciphers->{aes192},
  399. $ciphers->{aes128},
  400. $ciphers->{cast5},
  401. $ciphers->{tripledes}
  402. );
  403. # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
  404. my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
  405. $digests->{sha512},
  406. $digests->{sha384},
  407. $digests->{sha256},
  408. $digests->{sha224},
  409. $digests->{ripemd160},
  410. $digests->{sha1}
  411. );
  412. # prefer ZLIB, BZip2, ZIP
  413. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  414. $zips->{zlib},
  415. $zips->{bzip2},
  416. $zips->{zip}
  417. );
  418. # we support the MDC feature:
  419. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  420. $features->{mdc});
  421. # keyserver preference: only owner modify (???):
  422. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  423. $keyserver_prefs->{nomodify});
  424. my $subpackets_to_be_hashed =
  425. $creation_time_packet.
  426. $usage_packet.
  427. $expiration_packet.
  428. $pref_sym_algos.
  429. $pref_hash_algos.
  430. $pref_zip_algos.
  431. $feature_subpacket.
  432. $keyserver_pref;
  433. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  434. my $sig_data_to_be_hashed =
  435. $version.
  436. $sigtype.
  437. $pubkey_algo.
  438. $hash_algo.
  439. $subpacket_octets.
  440. $subpackets_to_be_hashed;
  441. my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
  442. my $seckey = make_rsa_sec_key_body($rsa, $key_timestamp);
  443. # this is for signing. it needs to be an old-style header with a
  444. # 2-packet octet count.
  445. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  446. # take the last 8 bytes of the fingerprint as the keyid:
  447. my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
  448. # the v4 signature trailer is:
  449. # version number, literal 0xff, and then a 4-byte count of the
  450. # signature data itself.
  451. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  452. my $uid_data =
  453. pack('CN', 0xb4, length($uid)).
  454. $uid;
  455. my $datatosign =
  456. $key_data.
  457. $uid_data.
  458. $sig_data_to_be_hashed.
  459. $trailer;
  460. my $data_hash = Digest::SHA::sha256_hex($datatosign);
  461. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  462. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  463. my $sig_body =
  464. $sig_data_to_be_hashed.
  465. pack('n', length($issuer_packet)).
  466. $issuer_packet.
  467. pack('n', hex(substr($data_hash, 0, 4))).
  468. mpi_pack($sig);
  469. return
  470. make_packet($packet_types->{seckey}, $seckey).
  471. make_packet($packet_types->{uid}, $uid).
  472. make_packet($packet_types->{sig}, $sig_body);
  473. }
  474. # FIXME: switch to passing the whole packet as the arg, instead of the
  475. # input stream.
  476. # FIXME: think about native perl representation of the packets instead.
  477. # Put a user ID into the $data
  478. sub finduid {
  479. my $data = shift;
  480. my $instr = shift;
  481. my $tag = shift;
  482. my $packetlen = shift;
  483. my $dummy;
  484. ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet";
  485. read($instr, $dummy, $packetlen);
  486. $data->{uid} = $dummy;
  487. }
  488. # find signatures associated with the given fingerprint and user ID.
  489. sub findsig {
  490. my $data = shift;
  491. my $instr = shift;
  492. my $tag = shift;
  493. my $packetlen = shift;
  494. ($tag == $packet_types->{sig}) or die "No calling revuid on anything other than a signature packet.";
  495. if ((undef $data->{key}) ||
  496. (undef $data->{uid}) ||
  497. ($data->{uid} ne $data->{target}->{uid})) {
  498. # this is not the user ID we are looking for.
  499. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  500. }
  501. my $data;
  502. read($instr, $data, 6) or die "could not read signature header\n";
  503. my ($ver, $sigtype, $pubkeyalgo, $digestalgo, $subpacketsize) = unpack('CCCCn', $data);
  504. if ($ver != 4) {
  505. printf(STDERR "We only work with version 4 signatures.");
  506. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  507. return;
  508. }
  509. if ($pubkeyalgo != $asym_algos->{rsa}) {
  510. printf(STDERR "We can only work with RSA at the moment");
  511. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  512. return;
  513. }
  514. if ($sigtype != $sig_types->{positive_certification}) {
  515. # FIXME: some weird implementations might have made generic,
  516. # persona, or casual certifications instead of positive
  517. # certifications for self-sigs. Probably should handle them too.
  518. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  519. return;
  520. }
  521. my $subpackets;
  522. read($instr, $subpackets, $subpacketsize) or die "could not read hashed signature subpackets.\n";
  523. read($instr, $subpacketsize, 2) or die "could not read unhashed signature subpacket size.\n";
  524. $subpacketsize = unpack('n', $subpacketsize);
  525. my $unhashedsubpackets;
  526. read($instr, $unhashedsubpackets, $subpacketsize) or die "could not read unhashed signature subpackets.\n";
  527. my $hashtail;
  528. read($instr, $hashtail, 2) or die "could not read left 16 bits of digest.\n";
  529. # RSA signatures should read in how many MPIs?
  530. # reason for revocation
  531. # non-revocable
  532. }
  533. # FIXME: to do in order to generate a proper revocation certificate:
  534. # parse subpackets
  535. # given an input stream and data, store the found key in data and
  536. # consume the rest of the stream corresponding to the packet.
  537. # data contains: (fpr: fingerprint to find, key: current best guess at key)
  538. sub findkey {
  539. my $data = shift;
  540. my $instr = shift;
  541. my $tag = shift;
  542. my $packetlen = shift;
  543. my $dummy;
  544. my $ver;
  545. my $readbytes = 0;
  546. read($instr, $ver, 1) or die "could not read key version\n";
  547. $readbytes += 1;
  548. $ver = ord($ver);
  549. if ($ver != 4) {
  550. printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
  551. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  552. return;
  553. }
  554. my $key_timestamp;
  555. read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
  556. $readbytes += 4;
  557. $key_timestamp = unpack('N', $key_timestamp);
  558. my $algo;
  559. read($instr, $algo, 1) or die "could not read key algorithm.\n";
  560. $readbytes += 1;
  561. $algo = ord($algo);
  562. if ($algo != $asym_algos->{rsa}) {
  563. printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
  564. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  565. return;
  566. }
  567. ## we have an RSA key.
  568. my $modulus = read_mpi($instr, \$readbytes);
  569. my $exponent = read_mpi($instr, \$readbytes);
  570. my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
  571. my $foundfpr = fingerprint($pubkey, $key_timestamp);
  572. my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
  573. # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
  574. $foundfprstr = sprintf("%040s", $foundfprstr);
  575. # is this a match?
  576. if ((!defined($data->{target}->{fpr})) ||
  577. (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
  578. if (defined($data->{key})) {
  579. die "Found two matching keys.\n";
  580. }
  581. $data->{key} = $pubkey;
  582. }
  583. if ($tag != $packet_types->{seckey} &&
  584. $tag != $packet_types->{sec_subkey}) {
  585. if ($readbytes < $packetlen) {
  586. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  587. }
  588. return;
  589. }
  590. if (!defined($data->{key})) {
  591. # we don't think the public part of this key matches
  592. if ($readbytes < $packetlen) {
  593. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  594. }
  595. return;
  596. }
  597. my $s2k;
  598. read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
  599. $readbytes += 1;
  600. $s2k = ord($s2k);
  601. if ($s2k != 0) {
  602. printf(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
  603. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  604. return;
  605. }
  606. # secret material is unencrypted
  607. # see http://tools.ietf.org/html/rfc4880#section-5.5.3
  608. my $d = read_mpi($instr, \$readbytes);
  609. my $p = read_mpi($instr, \$readbytes);
  610. my $q = read_mpi($instr, \$readbytes);
  611. my $u = read_mpi($instr, \$readbytes);
  612. my $checksum;
  613. read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
  614. $readbytes += 2;
  615. $checksum = unpack('n', $checksum);
  616. # FIXME: compare with the checksum! how? the data is
  617. # gone into the Crypt::OpenSSL::Bignum
  618. $data->{key} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
  619. $exponent,
  620. $d,
  621. $p,
  622. $q);
  623. $data->{key}->check_key() or die "Secret key is not a valid RSA key.\n";
  624. if ($readbytes < $packetlen) {
  625. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  626. }
  627. }
  628. sub openpgp2ssh {
  629. my $instr = shift;
  630. my $fpr = shift;
  631. if (defined $fpr) {
  632. if (length($fpr) < 8) {
  633. die "We need at least 8 hex digits of fingerprint.\n";
  634. }
  635. $fpr = uc($fpr);
  636. }
  637. my $data = { 'fpr' => $fpr};
  638. my $subs = { $packet_types->{pubkey} => \&findkey,
  639. $packet_types->{pub_subkey} => \&findkey,
  640. $packet_types->{seckey} => \&findkey,
  641. $packet_types->{sec_subkey} => \&findkey };
  642. packetwalk($instr, $subs, $data);
  643. return $data->{key};
  644. }
  645. sub revokeuserid {
  646. my $instr = shift;
  647. my $fpr = shift;
  648. my $uid = shift;
  649. if (defined $fpr) {
  650. if (length($fpr) < 8) {
  651. die "We need at least 8 hex digits of fingerprint.\n";
  652. }
  653. $fpr = uc($fpr);
  654. }
  655. my $data = { target => { fpr => $fpr,
  656. uid => $uid, },
  657. };
  658. my $subs = { $packet_types->{pubkey} => \&findkey,
  659. $packet_types->{pub_subkey} => \&findkey,
  660. $packet_types->{seckey} => \&findkey,
  661. $packet_types->{sec_subkey} => \&findkey,
  662. $packet_types->{uid} => \&finduid,
  663. $packet_types->{sig} => \&revuid,
  664. };
  665. }
  666. sub packetwalk {
  667. my $instr = shift;
  668. my $subs = shift;
  669. my $data = shift;
  670. my $packettag;
  671. my $dummy;
  672. my $tag;
  673. while (! eof($instr)) {
  674. read($instr, $packettag, 1);
  675. $packettag = ord($packettag);
  676. my $packetlen;
  677. if ( ! (0x80 & $packettag)) {
  678. die "This is not an OpenPGP packet\n";
  679. }
  680. if (0x40 & $packettag) {
  681. # this is a new-format packet.
  682. $tag = (0x3f & $packettag);
  683. my $nextlen = 0;
  684. read($instr, $nextlen, 1);
  685. $nextlen = ord($nextlen);
  686. if ($nextlen < 192) {
  687. $packetlen = $nextlen;
  688. } elsif ($nextlen < 224) {
  689. my $newoct;
  690. read($instr, $newoct, 1);
  691. $newoct = ord($newoct);
  692. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  693. } elsif ($nextlen == 255) {
  694. read($instr, $nextlen, 4);
  695. $packetlen = unpack('N', $nextlen);
  696. } else {
  697. # packet length is undefined.
  698. }
  699. } else {
  700. # this is an old-format packet.
  701. my $lentype;
  702. $lentype = 0x03 & $packettag;
  703. $tag = ( 0x3c & $packettag ) >> 2;
  704. if ($lentype == 0) {
  705. read($instr, $packetlen, 1) or die "could not read packet length\n";
  706. $packetlen = unpack('C', $packetlen);
  707. } elsif ($lentype == 1) {
  708. read($instr, $packetlen, 2) or die "could not read packet length\n";
  709. $packetlen = unpack('n', $packetlen);
  710. } elsif ($lentype == 2) {
  711. read($instr, $packetlen, 4) or die "could not read packet length\n";
  712. $packetlen = unpack('N', $packetlen);
  713. } else {
  714. # packet length is undefined.
  715. }
  716. }
  717. if (! defined($packetlen)) {
  718. die "Undefined packet lengths are not supported.\n";
  719. }
  720. if (defined $subs->{$tag}) {
  721. $subs->{$tag}($data, $instr, $tag, $packetlen);
  722. } else {
  723. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  724. }
  725. }
  726. return $data->{key};
  727. }
  728. for (basename($0)) {
  729. if (/^pem2openpgp$/) {
  730. my $rsa;
  731. my $stdin;
  732. my $uid = shift;
  733. defined($uid) or die "You must specify a user ID string.\n";
  734. # FIXME: fail if there is no given user ID; or should we default to
  735. # hostname_long() from Sys::Hostname::Long ?
  736. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  737. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  738. } else {
  739. $stdin = do {
  740. local $/; # slurp!
  741. <STDIN>;
  742. };
  743. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  744. }
  745. print pem2openpgp($rsa,
  746. $uid,
  747. { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  748. key_timestamp => $ENV{PEM2OPENPGP_KEY_TIMESTAMP},
  749. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  750. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  751. }
  752. );
  753. }
  754. elsif (/^openpgp2ssh$/) {
  755. my $fpr = shift;
  756. my $instream;
  757. open($instream,'-');
  758. binmode($instream, ":bytes");
  759. my $key = openpgp2ssh($instream, $fpr);
  760. if (defined($key)) {
  761. if ($key->is_private()) {
  762. print $key->get_private_key_string();
  763. } else {
  764. print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
  765. }
  766. } else {
  767. die "No matching key found.\n";
  768. }
  769. }
  770. else {
  771. die "Unrecognized keytrans call.\n";
  772. }
  773. }