summaryrefslogtreecommitdiff
path: root/src/share/keytrans
blob: ad65ed32585829b40d4332154bc08167b97461d8 (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.23
  126. my $revocation_reasons = { no_reason_specified => 0,
  127. key_superseded => 1,
  128. key_compromised => 2,
  129. key_retired => 3,
  130. user_id_no_longer_valid => 32,
  131. };
  132. # see RFC 4880 section 5.2.3.1
  133. my $subpacket_types = { sig_creation_time => 2,
  134. sig_expiration_time => 3,
  135. exportable => 4,
  136. trust_sig => 5,
  137. regex => 6,
  138. revocable => 7,
  139. key_expiration_time => 9,
  140. preferred_cipher => 11,
  141. revocation_key => 12,
  142. issuer => 16,
  143. notation => 20,
  144. preferred_digest => 21,
  145. preferred_compression => 22,
  146. keyserver_prefs => 23,
  147. preferred_keyserver => 24,
  148. primary_uid => 25,
  149. policy_uri => 26,
  150. usage_flags => 27,
  151. signers_uid => 28,
  152. revocation_reason => 29,
  153. features => 30,
  154. signature_target => 31,
  155. embedded_signature => 32,
  156. };
  157. # bitstring (see RFC 4880 section 5.2.3.24)
  158. my $features = { mdc => 0x01
  159. };
  160. # bitstring (see RFC 4880 5.2.3.17)
  161. my $keyserver_prefs = { nomodify => 0x80
  162. };
  163. ###### 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.
  166. ########### Math/Utility Functions ##############
  167. # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
  168. sub simple_checksum {
  169. my $bytes = shift;
  170. return unpack("%16C*",$bytes);
  171. }
  172. # calculate the multiplicative inverse of a mod b this is euclid's
  173. # extended algorithm. For more information see:
  174. # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
  175. # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
  176. # be the larger of the two values, and the two values should be
  177. # coprime.
  178. sub modular_multi_inverse {
  179. my $a = shift;
  180. my $b = shift;
  181. my $origdivisor = $b->copy();
  182. my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
  183. my $x = Crypt::OpenSSL::Bignum->zero();
  184. my $y = Crypt::OpenSSL::Bignum->one();
  185. my $lastx = Crypt::OpenSSL::Bignum->one();
  186. my $lasty = Crypt::OpenSSL::Bignum->zero();
  187. my $finalquotient;
  188. my $finalremainder;
  189. while (! $b->is_zero()) {
  190. my ($quotient, $remainder) = $a->div($b, $ctx);
  191. $a = $b;
  192. $b = $remainder;
  193. my $temp = $x;
  194. $x = $lastx->sub($quotient->mul($x, $ctx));
  195. $lastx = $temp;
  196. $temp = $y;
  197. $y = $lasty->sub($quotient->mul($y, $ctx));
  198. $lasty = $temp;
  199. }
  200. if (!$a->is_one()) {
  201. die "did this math wrong.\n";
  202. }
  203. # let's make sure that we return a positive value because RFC 4880,
  204. # section 3.2 only allows unsigned values:
  205. ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
  206. return $finalremainder;
  207. }
  208. ############ OpenPGP formatting functions ############
  209. # make an old-style packet out of the given packet type and body.
  210. # old-style (see RFC 4880 section 4.2)
  211. sub make_packet {
  212. my $type = shift;
  213. my $body = shift;
  214. my $options = shift;
  215. my $len = length($body);
  216. my $pseudolen = $len;
  217. # if the caller wants to use at least N octets of packet length,
  218. # pretend that we're using that many.
  219. if (defined $options && defined $options->{'packet_length'}) {
  220. $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
  221. }
  222. if ($pseudolen < $len) {
  223. $pseudolen = $len;
  224. }
  225. my $lenbytes;
  226. my $lencode;
  227. if ($pseudolen < 2**8) {
  228. $lenbytes = $old_format_packet_lengths->{one};
  229. $lencode = 'C';
  230. } elsif ($pseudolen < 2**16) {
  231. $lenbytes = $old_format_packet_lengths->{two};
  232. $lencode = 'n';
  233. } elsif ($pseudolen < 2**31) {
  234. ## not testing against full 32 bits because i don't want to deal
  235. ## with potential overflow.
  236. $lenbytes = $old_format_packet_lengths->{four};
  237. $lencode = 'N';
  238. } else {
  239. ## what the hell do we do here?
  240. $lenbytes = $old_format_packet_lengths->{indeterminate};
  241. $lencode = '';
  242. }
  243. return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
  244. $body;
  245. }
  246. # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
  247. # (RFC 4880 section 3.2)
  248. sub mpi_pack {
  249. my $num = shift;
  250. my $val = $num->to_bin();
  251. my $mpilen = length($val)*8;
  252. # this is a kludgy way to get the number of significant bits in the
  253. # first byte:
  254. my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
  255. $mpilen -= (8 - $bitsinfirstbyte);
  256. return pack('n', $mpilen).$val;
  257. }
  258. # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
  259. # for an OpenSSH-style public key format. see:
  260. # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
  261. sub openssh_mpi_pack {
  262. my $num = shift;
  263. my $val = $num->to_bin();
  264. my $mpilen = length($val);
  265. my $ret = pack('N', $mpilen);
  266. # if the first bit of the leading byte is high, we should include a
  267. # 0 byte:
  268. if (ord($val) & 0x80) {
  269. $ret = pack('NC', $mpilen+1, 0);
  270. }
  271. return $ret.$val;
  272. }
  273. sub openssh_pubkey_pack {
  274. my $key = shift;
  275. my ($modulus, $exponent) = $key->get_key_parameters();
  276. return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
  277. openssh_mpi_pack($exponent).
  278. openssh_mpi_pack($modulus);
  279. }
  280. # pull an OpenPGP-specified MPI off of a given stream, returning it as
  281. # a Crypt::OpenSSL::Bignum.
  282. sub read_mpi {
  283. my $instr = shift;
  284. my $readtally = shift;
  285. my $bitlen;
  286. read($instr, $bitlen, 2) or die "could not read MPI length.\n";
  287. $bitlen = unpack('n', $bitlen);
  288. $$readtally += 2;
  289. my $bytestoread = POSIX::floor(($bitlen + 7)/8);
  290. my $ret;
  291. read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
  292. $$readtally += $bytestoread;
  293. return Crypt::OpenSSL::Bignum->new_from_bin($ret);
  294. }
  295. # FIXME: genericize these to accept either RSA or DSA keys:
  296. sub make_rsa_pub_key_body {
  297. my $key = shift;
  298. my $key_timestamp = shift;
  299. my ($n, $e) = $key->get_key_parameters();
  300. return
  301. pack('CN', 4, $key_timestamp).
  302. pack('C', $asym_algos->{rsa}).
  303. mpi_pack($n).
  304. mpi_pack($e);
  305. }
  306. sub make_rsa_sec_key_body {
  307. my $key = shift;
  308. my $key_timestamp = shift;
  309. # we're not using $a and $b, but we need them to get to $c.
  310. my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
  311. my $c3 = modular_multi_inverse($p, $q);
  312. my $secret_material = mpi_pack($d).
  313. mpi_pack($p).
  314. mpi_pack($q).
  315. mpi_pack($c3);
  316. # according to Crypt::OpenSSL::RSA, the closest value we can get out
  317. # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
  318. # RFC 4880, we're actually looking for u, the multiplicative inverse
  319. # of p, mod q. This is why we're calculating the value directly
  320. # with modular_multi_inverse.
  321. return
  322. pack('CN', 4, $key_timestamp).
  323. pack('C', $asym_algos->{rsa}).
  324. mpi_pack($n).
  325. mpi_pack($e).
  326. pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
  327. $secret_material.
  328. pack('n', simple_checksum($secret_material));
  329. }
  330. # expects an RSA key (public or private) and a timestamp
  331. sub fingerprint {
  332. my $key = shift;
  333. my $key_timestamp = shift;
  334. my $rsabody = make_rsa_pub_key_body($key, $key_timestamp);
  335. return Digest::SHA::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  336. }
  337. # FIXME: handle DSA keys as well!
  338. sub pem2openpgp {
  339. my $rsa = shift;
  340. my $uid = shift;
  341. my $args = shift;
  342. # strong assertion of identity is the default (for a self-sig):
  343. if (! defined $args->{certification_type}) {
  344. $args->{certification_type} = $sig_types->{positive_certification};
  345. }
  346. if (! defined $args->{sig_timestamp}) {
  347. $args->{sig_timestamp} = time();
  348. }
  349. if (! defined $args->{key_timestamp}) {
  350. $args->{key_timestamp} = $args->{sig_timestamp} + 0;
  351. }
  352. my $key_timestamp = $args->{key_timestamp};
  353. # generate and aggregate subpackets:
  354. # key usage flags:
  355. my $flags = 0;
  356. if (! defined $args->{usage_flags}) {
  357. $flags = $usage_flags->{certify};
  358. } else {
  359. my @ff = split(",", $args->{usage_flags});
  360. foreach my $f (@ff) {
  361. if (! defined $usage_flags->{$f}) {
  362. die "No such flag $f";
  363. }
  364. $flags |= $usage_flags->{$f};
  365. }
  366. }
  367. my $usage_subpacket = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  368. # how should we determine how far off to set the expiration date?
  369. # default is no expiration. Specify the timestamp in seconds from the
  370. # key creation.
  371. my $expiration_subpacket = '';
  372. if (defined $args->{expiration}) {
  373. my $expires_in = $args->{expiration} + 0;
  374. $expiration_subpacket = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  375. }
  376. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  377. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  378. $ciphers->{aes256},
  379. $ciphers->{aes192},
  380. $ciphers->{aes128},
  381. $ciphers->{cast5},
  382. $ciphers->{tripledes}
  383. );
  384. # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
  385. my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
  386. $digests->{sha512},
  387. $digests->{sha384},
  388. $digests->{sha256},
  389. $digests->{sha224},
  390. $digests->{ripemd160},
  391. $digests->{sha1}
  392. );
  393. # prefer ZLIB, BZip2, ZIP
  394. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  395. $zips->{zlib},
  396. $zips->{bzip2},
  397. $zips->{zip}
  398. );
  399. # we support the MDC feature:
  400. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  401. $features->{mdc});
  402. # keyserver preference: only owner modify (???):
  403. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  404. $keyserver_prefs->{nomodify});
  405. $args->{hashed_subpackets} =
  406. $usage_subpacket.
  407. $expiration_subpacket.
  408. $pref_sym_algos.
  409. $pref_hash_algos.
  410. $pref_zip_algos.
  411. $feature_subpacket.
  412. $keyserver_pref;
  413. return
  414. make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
  415. make_packet($packet_types->{uid}, $uid).
  416. gensig($rsa, $uid, $args);
  417. }
  418. # FIXME: handle non-RSA keys
  419. # FIXME: this currently only makes self-sigs -- we should parameterize
  420. # it to make certifications over keys other than the issuer.
  421. sub gensig {
  422. my $rsa = shift;
  423. my $uid = shift;
  424. my $args = shift;
  425. # FIXME: allow signature creation using digests other than SHA256
  426. $rsa->use_sha256_hash();
  427. # see page 22 of RFC 4880 for why i think this is the right padding
  428. # choice to use:
  429. $rsa->use_pkcs1_padding();
  430. if (! $rsa->check_key()) {
  431. die "key does not check\n";
  432. }
  433. my $certtype = $args->{certification_type} + 0;
  434. my $version = pack('C', 4);
  435. my $sigtype = pack('C', $certtype);
  436. # RSA
  437. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  438. # SHA256 FIXME: allow signature creation using digests other than SHA256
  439. my $hash_algo = pack('C', $digests->{sha256});
  440. # FIXME: i'm worried about generating a bazillion new OpenPGP
  441. # certificates from the same key, which could easily happen if you run
  442. # this script more than once against the same key (because the
  443. # timestamps will differ). How can we prevent this?
  444. # this argument (if set) overrides the current time, to
  445. # be able to create a standard key. If we read the key from a file
  446. # instead of stdin, should we use the creation time on the file?
  447. my $sig_timestamp = ($args->{sig_timestamp} + 0);
  448. my $key_timestamp = ($args->{key_timestamp} + 0);
  449. if ($key_timestamp > $sig_timestamp) {
  450. die "key timestamp must not be later than signature timestamp\n";
  451. }
  452. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
  453. my $hashed_subs = $creation_time_packet.$args->{hashed_subpackets};
  454. my $subpacket_octets = pack('n', length($hashed_subs));
  455. my $sig_data_to_be_hashed =
  456. $version.
  457. $sigtype.
  458. $pubkey_algo.
  459. $hash_algo.
  460. $subpacket_octets.
  461. $hashed_subs;
  462. my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
  463. # this is for signing. it needs to be an old-style header with a
  464. # 2-packet octet count.
  465. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  466. # take the last 8 bytes of the fingerprint as the keyid:
  467. my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
  468. # the v4 signature trailer is:
  469. # version number, literal 0xff, and then a 4-byte count of the
  470. # signature data itself.
  471. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  472. my $uid_data =
  473. pack('CN', 0xb4, length($uid)).
  474. $uid;
  475. my $datatosign =
  476. $key_data.
  477. $uid_data.
  478. $sig_data_to_be_hashed.
  479. $trailer;
  480. # FIXME: handle signatures over digests other than SHA256:
  481. my $data_hash = Digest::SHA::sha256_hex($datatosign);
  482. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  483. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  484. my $sig_body =
  485. $sig_data_to_be_hashed.
  486. pack('n', length($issuer_packet)).
  487. $issuer_packet.
  488. pack('n', hex(substr($data_hash, 0, 4))).
  489. mpi_pack($sig);
  490. return make_packet($packet_types->{sig}, $sig_body);
  491. }
  492. # FIXME: switch to passing the whole packet as the arg, instead of the
  493. # input stream.
  494. # FIXME: think about native perl representation of the packets instead.
  495. # Put a user ID into the $data
  496. sub finduid {
  497. my $data = shift;
  498. my $instr = shift;
  499. my $tag = shift;
  500. my $packetlen = shift;
  501. my $dummy;
  502. ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet\n";
  503. read($instr, $dummy, $packetlen);
  504. $data->{uid}->{$dummy} = {};
  505. $data->{current}->{uid} = $dummy;
  506. }
  507. # find signatures associated with the given fingerprint and user ID.
  508. sub findsig {
  509. my $data = shift;
  510. my $instr = shift;
  511. my $tag = shift;
  512. my $packetlen = shift;
  513. ($tag == $packet_types->{sig}) or die "No calling findsig on anything other than a signature packet.\n";
  514. my $dummy;
  515. my $readbytes = 0;
  516. read($instr, $dummy, $packetlen - $readbytes) or die "Could not read in this packet.\n";
  517. if ((! defined $data->{key}) ||
  518. (! defined $data->{uid}) ||
  519. (! defined $data->{uid}->{$data->{target}->{uid}})) {
  520. # the user ID we are looking for has not been found yet.
  521. return;
  522. }
  523. # FIXME: if we get two primary keys on stdin, both with the same
  524. # targetd user ID, we'll store signatures from both keys, which is
  525. # probably wrong.
  526. # the current ID is not what we're looking for:
  527. return if ($data->{current}->{uid} ne $data->{target}->{uid});
  528. # just storing the raw signatures for the moment:
  529. push @{$data->{sigs}}, make_packet($packet_types->{sig}, $dummy);
  530. return;
  531. }
  532. # given an input stream and data, store the found key in data and
  533. # consume the rest of the stream corresponding to the packet.
  534. # data contains: (fpr: fingerprint to find, key: current best guess at key)
  535. sub findkey {
  536. my $data = shift;
  537. my $instr = shift;
  538. my $tag = shift;
  539. my $packetlen = shift;
  540. my $dummy;
  541. my $ver;
  542. my $readbytes = 0;
  543. read($instr, $ver, 1) or die "could not read key version\n";
  544. $readbytes += 1;
  545. $ver = ord($ver);
  546. if ($ver != 4) {
  547. printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
  548. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  549. return;
  550. }
  551. my $key_timestamp;
  552. read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
  553. $readbytes += 4;
  554. $key_timestamp = unpack('N', $key_timestamp);
  555. my $algo;
  556. read($instr, $algo, 1) or die "could not read key algorithm.\n";
  557. $readbytes += 1;
  558. $algo = ord($algo);
  559. if ($algo != $asym_algos->{rsa}) {
  560. printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
  561. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  562. return;
  563. }
  564. ## we have an RSA key.
  565. my $modulus = read_mpi($instr, \$readbytes);
  566. my $exponent = read_mpi($instr, \$readbytes);
  567. my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
  568. my $foundfpr = fingerprint($pubkey, $key_timestamp);
  569. my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
  570. # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
  571. $foundfprstr = sprintf("%040s", $foundfprstr);
  572. # is this a match?
  573. if ((!defined($data->{target}->{fpr})) ||
  574. (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
  575. if (defined($data->{key})) {
  576. die "Found two matching keys.\n";
  577. }
  578. $data->{key} = { 'rsa' => $pubkey,
  579. 'timestamp' => $key_timestamp };
  580. }
  581. if ($tag != $packet_types->{seckey} &&
  582. $tag != $packet_types->{sec_subkey}) {
  583. if ($readbytes < $packetlen) {
  584. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  585. }
  586. return;
  587. }
  588. if (!defined($data->{key})) {
  589. # we don't think the public part of this key matches
  590. if ($readbytes < $packetlen) {
  591. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  592. }
  593. return;
  594. }
  595. my $s2k;
  596. read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
  597. $readbytes += 1;
  598. $s2k = ord($s2k);
  599. if ($s2k != 0) {
  600. printf(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
  601. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  602. return;
  603. }
  604. # secret material is unencrypted
  605. # see http://tools.ietf.org/html/rfc4880#section-5.5.3
  606. my $d = read_mpi($instr, \$readbytes);
  607. my $p = read_mpi($instr, \$readbytes);
  608. my $q = read_mpi($instr, \$readbytes);
  609. my $u = read_mpi($instr, \$readbytes);
  610. my $checksum;
  611. read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
  612. $readbytes += 2;
  613. $checksum = unpack('n', $checksum);
  614. # FIXME: compare with the checksum! how? the data is
  615. # gone into the Crypt::OpenSSL::Bignum
  616. $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
  617. $exponent,
  618. $d,
  619. $p,
  620. $q);
  621. $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
  622. if ($readbytes < $packetlen) {
  623. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  624. }
  625. }
  626. sub openpgp2rsa {
  627. my $instr = shift;
  628. my $fpr = shift;
  629. if (defined $fpr) {
  630. if (length($fpr) < 8) {
  631. die "We need at least 8 hex digits of fingerprint.\n";
  632. }
  633. $fpr = uc($fpr);
  634. }
  635. my $data = { 'fpr' => $fpr};
  636. my $subs = { $packet_types->{pubkey} => \&findkey,
  637. $packet_types->{pub_subkey} => \&findkey,
  638. $packet_types->{seckey} => \&findkey,
  639. $packet_types->{sec_subkey} => \&findkey };
  640. packetwalk($instr, $subs, $data);
  641. return $data->{key}->{rsa};
  642. }
  643. sub revokeuserid {
  644. my $instr = shift;
  645. my $fpr = shift;
  646. my $uid = shift;
  647. my $sigtime = shift;
  648. if ((! defined $fpr) ||
  649. (length($fpr) < 8)) {
  650. die "We need at least 8 hex digits of fingerprint.\n";
  651. }
  652. $fpr = uc($fpr);
  653. if (! defined $uid) {
  654. die "No User ID defined.\n";
  655. }
  656. my $data = { target => { fpr => $fpr,
  657. uid => $uid,
  658. },
  659. };
  660. my $subs = { $packet_types->{seckey} => \&findkey,
  661. $packet_types->{uid} => \&finduid,
  662. $packet_types->{sig} => \&findsig,
  663. };
  664. packetwalk($instr, $subs, $data);
  665. if ((! defined $data->{uid}) ||
  666. (! defined $data->{uid}->{$uid})) {
  667. die "The User ID \"$uid\" is not associated with this key";
  668. }
  669. if ((! defined $data->{key}) ||
  670. (! defined $data->{key}->{rsa}) ||
  671. (! defined $data->{key}->{timestamp})) {
  672. die "The key requested was not found."
  673. }
  674. my $revocation_reason = 'No longer using this hostname';
  675. if (defined $data->{revocation_reason}) {
  676. $revocation_reason = $data->{revocation_reason};
  677. }
  678. my $rev_reason_subpkt = prefixsubpacket(pack('CC',
  679. $subpacket_types->{revocation_reason},
  680. $revocation_reasons->{user_id_no_longer_valid}).
  681. $revocation_reason);
  682. if (! defined $sigtime) {
  683. $sigtime = time();
  684. }
  685. # what does a signature like this look like?
  686. my $args = { key_timestamp => $data->{key}->{timestamp},
  687. sig_timestamp => $sigtime,
  688. certification_type => $sig_types->{certification_revocation},
  689. hashed_subpackets => $rev_reason_subpkt,
  690. };
  691. return
  692. make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
  693. make_packet($packet_types->{uid}, $uid).
  694. join('', @{$data->{sigs}}).
  695. gensig($data->{key}->{rsa}, $uid, $args);
  696. }
  697. # see 5.2.3.1 for tips on how to calculate the length of a subpacket:
  698. sub prefixsubpacket {
  699. my $subpacket = shift;
  700. my $len = length($subpacket);
  701. my $prefix;
  702. use bytes;
  703. if ($len < 192) {
  704. # one byte:
  705. $prefix = pack('C', $len);
  706. } elsif ($len < 16576) {
  707. my $in = $len - 192;
  708. my $second = $in%256;
  709. my $first = ($in - $second)>>8;
  710. $prefix = pack('CC', $first + 192, $second)
  711. } else {
  712. $prefix = pack('CN', 255, $len);
  713. }
  714. return $prefix.$subpacket;
  715. }
  716. sub packetwalk {
  717. my $instr = shift;
  718. my $subs = shift;
  719. my $data = shift;
  720. my $packettag;
  721. my $dummy;
  722. my $tag;
  723. while (! eof($instr)) {
  724. read($instr, $packettag, 1);
  725. $packettag = ord($packettag);
  726. my $packetlen;
  727. if ( ! (0x80 & $packettag)) {
  728. die "This is not an OpenPGP packet\n";
  729. }
  730. if (0x40 & $packettag) {
  731. # this is a new-format packet.
  732. $tag = (0x3f & $packettag);
  733. my $nextlen = 0;
  734. read($instr, $nextlen, 1);
  735. $nextlen = ord($nextlen);
  736. if ($nextlen < 192) {
  737. $packetlen = $nextlen;
  738. } elsif ($nextlen < 224) {
  739. my $newoct;
  740. read($instr, $newoct, 1);
  741. $newoct = ord($newoct);
  742. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  743. } elsif ($nextlen == 255) {
  744. read($instr, $nextlen, 4);
  745. $packetlen = unpack('N', $nextlen);
  746. } else {
  747. # packet length is undefined.
  748. }
  749. } else {
  750. # this is an old-format packet.
  751. my $lentype;
  752. $lentype = 0x03 & $packettag;
  753. $tag = ( 0x3c & $packettag ) >> 2;
  754. if ($lentype == 0) {
  755. read($instr, $packetlen, 1) or die "could not read packet length\n";
  756. $packetlen = unpack('C', $packetlen);
  757. } elsif ($lentype == 1) {
  758. read($instr, $packetlen, 2) or die "could not read packet length\n";
  759. $packetlen = unpack('n', $packetlen);
  760. } elsif ($lentype == 2) {
  761. read($instr, $packetlen, 4) or die "could not read packet length\n";
  762. $packetlen = unpack('N', $packetlen);
  763. } else {
  764. # packet length is undefined.
  765. }
  766. }
  767. if (! defined($packetlen)) {
  768. die "Undefined packet lengths are not supported.\n";
  769. }
  770. if (defined $subs->{$tag}) {
  771. $subs->{$tag}($data, $instr, $tag, $packetlen);
  772. } else {
  773. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  774. }
  775. }
  776. return $data->{key};
  777. }
  778. for (basename($0)) {
  779. if (/^pem2openpgp$/) {
  780. my $rsa;
  781. my $stdin;
  782. my $uid = shift;
  783. defined($uid) or die "You must specify a user ID string.\n";
  784. # FIXME: fail if there is no given user ID; or should we default to
  785. # hostname_long() from Sys::Hostname::Long ?
  786. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  787. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  788. } else {
  789. $stdin = do {
  790. local $/; # slurp!
  791. <STDIN>;
  792. };
  793. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  794. }
  795. print pem2openpgp($rsa,
  796. $uid,
  797. { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  798. key_timestamp => $ENV{PEM2OPENPGP_KEY_TIMESTAMP},
  799. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  800. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  801. }
  802. );
  803. }
  804. elsif (/^openpgp2ssh$/) {
  805. my $fpr = shift;
  806. my $instream;
  807. open($instream,'-');
  808. binmode($instream, ":bytes");
  809. my $key = openpgp2rsa($instream, $fpr);
  810. if (defined($key)) {
  811. if ($key->is_private()) {
  812. print $key->get_private_key_string();
  813. } else {
  814. print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
  815. }
  816. } else {
  817. die "No matching key found.\n";
  818. }
  819. }
  820. elsif (/^keytrans$/) {
  821. # subcommands when keytrans is invoked directly are UNSUPPORTED,
  822. # UNDOCUMENTED, and WILL NOT BE MAINTAINED.
  823. my $subcommand = shift;
  824. for ($subcommand) {
  825. if (/^revokeuserid$/) {
  826. my $fpr = shift;
  827. my $uid = shift;
  828. my $instream;
  829. open($instream,'-');
  830. binmode($instream, ":bytes");
  831. my $revcert = revokeuserid($instream, $fpr, $uid, $ENV{KEYTRANS_REVSIG_TIMESTAMP});
  832. print $revcert;
  833. } else {
  834. die "Unrecognized subcomand. keytrans subcommands are not a stable interface!\n";
  835. }
  836. }
  837. }
  838. else {
  839. die "Unrecognized keytrans call.\n";
  840. }
  841. }