summaryrefslogtreecommitdiff
path: root/src/share/keytrans
blob: 255a271c2cefd7f2dd446d5b69e9a275f8116ce5 (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 makeselfsig {
  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. my $key_timestamp = $args->{key_timestamp} + 0;
  350. # generate and aggregate subpackets:
  351. # key usage flags:
  352. my $flags = 0;
  353. if (! defined $args->{usage_flags}) {
  354. $flags = $usage_flags->{certify};
  355. } else {
  356. my @ff = split(",", $args->{usage_flags});
  357. foreach my $f (@ff) {
  358. if (! defined $usage_flags->{$f}) {
  359. die "No such flag $f";
  360. }
  361. $flags |= $usage_flags->{$f};
  362. }
  363. }
  364. my $usage_subpacket = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  365. # how should we determine how far off to set the expiration date?
  366. # default is no expiration. Specify the timestamp in seconds from the
  367. # key creation.
  368. my $expiration_subpacket = '';
  369. if (defined $args->{expiration}) {
  370. my $expires_in = $args->{expiration} + 0;
  371. $expiration_subpacket = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  372. }
  373. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  374. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  375. $ciphers->{aes256},
  376. $ciphers->{aes192},
  377. $ciphers->{aes128},
  378. $ciphers->{cast5},
  379. $ciphers->{tripledes}
  380. );
  381. # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
  382. my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
  383. $digests->{sha512},
  384. $digests->{sha384},
  385. $digests->{sha256},
  386. $digests->{sha224},
  387. $digests->{ripemd160},
  388. $digests->{sha1}
  389. );
  390. # prefer ZLIB, BZip2, ZIP
  391. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  392. $zips->{zlib},
  393. $zips->{bzip2},
  394. $zips->{zip}
  395. );
  396. # we support the MDC feature:
  397. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  398. $features->{mdc});
  399. # keyserver preference: only owner modify (???):
  400. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  401. $keyserver_prefs->{nomodify});
  402. $args->{hashed_subpackets} =
  403. $usage_subpacket.
  404. $expiration_subpacket.
  405. $pref_sym_algos.
  406. $pref_hash_algos.
  407. $pref_zip_algos.
  408. $feature_subpacket.
  409. $keyserver_pref;
  410. return gensig($rsa, $uid, $args);
  411. }
  412. # FIXME: handle non-RSA keys
  413. # FIXME: this currently only makes self-sigs -- we should parameterize
  414. # it to make certifications over keys other than the issuer.
  415. sub gensig {
  416. my $rsa = shift;
  417. my $uid = shift;
  418. my $args = shift;
  419. # FIXME: allow signature creation using digests other than SHA256
  420. $rsa->use_sha256_hash();
  421. # see page 22 of RFC 4880 for why i think this is the right padding
  422. # choice to use:
  423. $rsa->use_pkcs1_padding();
  424. if (! $rsa->check_key()) {
  425. die "key does not check\n";
  426. }
  427. my $certtype = $args->{certification_type} + 0;
  428. my $version = pack('C', 4);
  429. my $sigtype = pack('C', $certtype);
  430. # RSA
  431. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  432. # SHA256 FIXME: allow signature creation using digests other than SHA256
  433. my $hash_algo = pack('C', $digests->{sha256});
  434. # FIXME: i'm worried about generating a bazillion new OpenPGP
  435. # certificates from the same key, which could easily happen if you run
  436. # this script more than once against the same key (because the
  437. # timestamps will differ). How can we prevent this?
  438. # this argument (if set) overrides the current time, to
  439. # be able to create a standard key. If we read the key from a file
  440. # instead of stdin, should we use the creation time on the file?
  441. my $sig_timestamp = ($args->{sig_timestamp} + 0);
  442. my $key_timestamp = ($args->{key_timestamp} + 0);
  443. if ($key_timestamp > $sig_timestamp) {
  444. die "key timestamp must not be later than signature timestamp\n";
  445. }
  446. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
  447. my $hashed_subs = $creation_time_packet.$args->{hashed_subpackets};
  448. my $subpacket_octets = pack('n', length($hashed_subs));
  449. my $sig_data_to_be_hashed =
  450. $version.
  451. $sigtype.
  452. $pubkey_algo.
  453. $hash_algo.
  454. $subpacket_octets.
  455. $hashed_subs;
  456. my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
  457. # this is for signing. it needs to be an old-style header with a
  458. # 2-packet octet count.
  459. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  460. # take the last 8 bytes of the fingerprint as the keyid:
  461. my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
  462. # the v4 signature trailer is:
  463. # version number, literal 0xff, and then a 4-byte count of the
  464. # signature data itself.
  465. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  466. my $uid_data =
  467. pack('CN', 0xb4, length($uid)).
  468. $uid;
  469. my $datatosign =
  470. $key_data.
  471. $uid_data.
  472. $sig_data_to_be_hashed.
  473. $trailer;
  474. # FIXME: handle signatures over digests other than SHA256:
  475. my $data_hash = Digest::SHA::sha256_hex($datatosign);
  476. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  477. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  478. my $sig_body =
  479. $sig_data_to_be_hashed.
  480. pack('n', length($issuer_packet)).
  481. $issuer_packet.
  482. pack('n', hex(substr($data_hash, 0, 4))).
  483. mpi_pack($sig);
  484. return make_packet($packet_types->{sig}, $sig_body);
  485. }
  486. # FIXME: switch to passing the whole packet as the arg, instead of the
  487. # input stream.
  488. # FIXME: think about native perl representation of the packets instead.
  489. # Put a user ID into the $data
  490. sub finduid {
  491. my $data = shift;
  492. my $instr = shift;
  493. my $tag = shift;
  494. my $packetlen = shift;
  495. my $dummy;
  496. ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet\n";
  497. read($instr, $dummy, $packetlen);
  498. $data->{uid}->{$dummy} = {};
  499. $data->{current}->{uid} = $dummy;
  500. }
  501. # find signatures associated with the given fingerprint and user ID.
  502. sub findsig {
  503. my $data = shift;
  504. my $instr = shift;
  505. my $tag = shift;
  506. my $packetlen = shift;
  507. ($tag == $packet_types->{sig}) or die "No calling findsig on anything other than a signature packet.\n";
  508. my $dummy;
  509. my $readbytes = 0;
  510. read($instr, $dummy, $packetlen - $readbytes) or die "Could not read in this packet.\n";
  511. if ((! defined $data->{key}) ||
  512. (! defined $data->{uid}) ||
  513. (! defined $data->{uid}->{$data->{target}->{uid}})) {
  514. # the user ID we are looking for has not been found yet.
  515. return;
  516. }
  517. # FIXME: if we get two primary keys on stdin, both with the same
  518. # targetd user ID, we'll store signatures from both keys, which is
  519. # probably wrong.
  520. # the current ID is not what we're looking for:
  521. return if ($data->{current}->{uid} ne $data->{target}->{uid});
  522. # just storing the raw signatures for the moment:
  523. push @{$data->{sigs}}, make_packet($packet_types->{sig}, $dummy);
  524. return;
  525. }
  526. # given an input stream and data, store the found key in data and
  527. # consume the rest of the stream corresponding to the packet.
  528. # data contains: (fpr: fingerprint to find, key: current best guess at key)
  529. sub findkey {
  530. my $data = shift;
  531. my $instr = shift;
  532. my $tag = shift;
  533. my $packetlen = shift;
  534. my $dummy;
  535. my $ver;
  536. my $readbytes = 0;
  537. read($instr, $ver, 1) or die "could not read key version\n";
  538. $readbytes += 1;
  539. $ver = ord($ver);
  540. if ($ver != 4) {
  541. printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
  542. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  543. return;
  544. }
  545. my $key_timestamp;
  546. read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
  547. $readbytes += 4;
  548. $key_timestamp = unpack('N', $key_timestamp);
  549. my $algo;
  550. read($instr, $algo, 1) or die "could not read key algorithm.\n";
  551. $readbytes += 1;
  552. $algo = ord($algo);
  553. if ($algo != $asym_algos->{rsa}) {
  554. printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
  555. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  556. return;
  557. }
  558. ## we have an RSA key.
  559. my $modulus = read_mpi($instr, \$readbytes);
  560. my $exponent = read_mpi($instr, \$readbytes);
  561. my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
  562. my $foundfpr = fingerprint($pubkey, $key_timestamp);
  563. my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
  564. # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
  565. $foundfprstr = sprintf("%040s", $foundfprstr);
  566. my $matched = 0;
  567. # is this a match?
  568. if ((!defined($data->{target}->{fpr})) ||
  569. (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
  570. if (defined($data->{key})) {
  571. die "Found two matching keys.\n";
  572. }
  573. $data->{key} = { 'rsa' => $pubkey,
  574. 'timestamp' => $key_timestamp };
  575. $matched = 1;
  576. }
  577. if ($tag != $packet_types->{seckey} &&
  578. $tag != $packet_types->{sec_subkey}) {
  579. if ($readbytes < $packetlen) {
  580. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  581. }
  582. return;
  583. }
  584. if (!$matched) {
  585. # we don't think the public part of this key matches
  586. if ($readbytes < $packetlen) {
  587. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  588. }
  589. return;
  590. }
  591. my $s2k;
  592. read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
  593. $readbytes += 1;
  594. $s2k = ord($s2k);
  595. if ($s2k != 0) {
  596. printf(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
  597. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  598. return;
  599. }
  600. # secret material is unencrypted
  601. # see http://tools.ietf.org/html/rfc4880#section-5.5.3
  602. my $d = read_mpi($instr, \$readbytes);
  603. my $p = read_mpi($instr, \$readbytes);
  604. my $q = read_mpi($instr, \$readbytes);
  605. my $u = read_mpi($instr, \$readbytes);
  606. my $checksum;
  607. read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
  608. $readbytes += 2;
  609. $checksum = unpack('n', $checksum);
  610. # FIXME: compare with the checksum! how? the data is
  611. # gone into the Crypt::OpenSSL::Bignum
  612. $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
  613. $exponent,
  614. $d,
  615. $p,
  616. $q);
  617. $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
  618. if ($readbytes < $packetlen) {
  619. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  620. }
  621. }
  622. sub openpgp2rsa {
  623. my $instr = shift;
  624. my $fpr = shift;
  625. if (defined $fpr) {
  626. if (length($fpr) < 8) {
  627. die "We need at least 8 hex digits of fingerprint.\n";
  628. }
  629. $fpr = uc($fpr);
  630. }
  631. my $data = { target => { fpr => $fpr,
  632. },
  633. };
  634. my $subs = { $packet_types->{pubkey} => \&findkey,
  635. $packet_types->{pub_subkey} => \&findkey,
  636. $packet_types->{seckey} => \&findkey,
  637. $packet_types->{sec_subkey} => \&findkey };
  638. packetwalk($instr, $subs, $data);
  639. return $data->{key}->{rsa};
  640. }
  641. sub findkeyfprs {
  642. my $data = shift;
  643. my $instr = shift;
  644. my $tag = shift;
  645. my $packetlen = shift;
  646. findkey($data, $instr, $tag, $packetlen);
  647. if (defined($data->{key})) {
  648. if (defined($data->{key}->{rsa}) && defined($data->{key}->{timestamp})) {
  649. $data->{keys}->{fingerprint($data->{key}->{rsa}, $data->{key}->{timestamp})} = $data->{key};
  650. } else {
  651. die "should have found some key here";
  652. }
  653. undef($data->{key});
  654. }
  655. };
  656. sub getallprimarykeys {
  657. my $instr = shift;
  658. my $subs = { $packet_types->{pubkey} => \&findkeyfprs,
  659. $packet_types->{seckey} => \&findkeyfprs,
  660. };
  661. my $data = {target => { } };
  662. packetwalk($instr, $subs, $data);
  663. if (defined $data->{keys}) {
  664. return $data->{keys};
  665. } else {
  666. return {};
  667. }
  668. }
  669. sub adduserid {
  670. my $instr = shift;
  671. my $fpr = shift;
  672. my $uid = shift;
  673. my $args = shift;
  674. if ((! defined $fpr) ||
  675. (length($fpr) < 8)) {
  676. die "We need at least 8 hex digits of fingerprint.\n";
  677. }
  678. $fpr = uc($fpr);
  679. if (! defined $uid) {
  680. die "No User ID defined.\n";
  681. }
  682. my $data = { target => { fpr => $fpr,
  683. uid => $uid,
  684. },
  685. };
  686. my $subs = { $packet_types->{seckey} => \&findkey,
  687. $packet_types->{uid} => \&finduid,
  688. $packet_types->{sig} => \&findsig,
  689. };
  690. packetwalk($instr, $subs, $data);
  691. if ((! defined $data->{key}) ||
  692. (! defined $data->{key}->{rsa}) ||
  693. (! defined $data->{key}->{timestamp})) {
  694. die "The key requested was not found.\n"
  695. }
  696. if (defined $data->{uid}->{$uid}) {
  697. die "The requested User ID '$uid' is already associated with this key.\n";
  698. }
  699. $args->{key_timestamp} = $data->{key}->{timestamp};
  700. return
  701. make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
  702. make_packet($packet_types->{uid}, $uid).
  703. makeselfsig($data->{key}->{rsa},
  704. $uid,
  705. $args);
  706. }
  707. sub revokeuserid {
  708. my $instr = shift;
  709. my $fpr = shift;
  710. my $uid = shift;
  711. my $sigtime = shift;
  712. if ((! defined $fpr) ||
  713. (length($fpr) < 8)) {
  714. die "We need at least 8 hex digits of fingerprint.\n";
  715. }
  716. $fpr = uc($fpr);
  717. if (! defined $uid) {
  718. die "No User ID defined.\n";
  719. }
  720. my $data = { target => { fpr => $fpr,
  721. uid => $uid,
  722. },
  723. };
  724. my $subs = { $packet_types->{seckey} => \&findkey,
  725. $packet_types->{uid} => \&finduid,
  726. $packet_types->{sig} => \&findsig,
  727. };
  728. packetwalk($instr, $subs, $data);
  729. if ((! defined $data->{uid}) ||
  730. (! defined $data->{uid}->{$uid})) {
  731. die "The User ID \"$uid\" is not associated with this key";
  732. }
  733. if ((! defined $data->{key}) ||
  734. (! defined $data->{key}->{rsa}) ||
  735. (! defined $data->{key}->{timestamp})) {
  736. die "The key requested was not found."
  737. }
  738. my $revocation_reason = 'No longer using this hostname';
  739. if (defined $data->{revocation_reason}) {
  740. $revocation_reason = $data->{revocation_reason};
  741. }
  742. my $rev_reason_subpkt = prefixsubpacket(pack('CC',
  743. $subpacket_types->{revocation_reason},
  744. $revocation_reasons->{user_id_no_longer_valid}).
  745. $revocation_reason);
  746. if (! defined $sigtime) {
  747. $sigtime = time();
  748. }
  749. # what does a signature like this look like?
  750. my $args = { key_timestamp => $data->{key}->{timestamp},
  751. sig_timestamp => $sigtime,
  752. certification_type => $sig_types->{certification_revocation},
  753. hashed_subpackets => $rev_reason_subpkt,
  754. };
  755. return
  756. make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
  757. make_packet($packet_types->{uid}, $uid).
  758. join('', @{$data->{sigs}}).
  759. gensig($data->{key}->{rsa}, $uid, $args);
  760. }
  761. # see 5.2.3.1 for tips on how to calculate the length of a subpacket:
  762. sub prefixsubpacket {
  763. my $subpacket = shift;
  764. my $len = length($subpacket);
  765. my $prefix;
  766. use bytes;
  767. if ($len < 192) {
  768. # one byte:
  769. $prefix = pack('C', $len);
  770. } elsif ($len < 16576) {
  771. my $in = $len - 192;
  772. my $second = $in%256;
  773. my $first = ($in - $second)>>8;
  774. $prefix = pack('CC', $first + 192, $second)
  775. } else {
  776. $prefix = pack('CN', 255, $len);
  777. }
  778. return $prefix.$subpacket;
  779. }
  780. sub packetwalk {
  781. my $instr = shift;
  782. my $subs = shift;
  783. my $data = shift;
  784. my $packettag;
  785. my $dummy;
  786. my $tag;
  787. while (! eof($instr)) {
  788. read($instr, $packettag, 1);
  789. $packettag = ord($packettag);
  790. my $packetlen;
  791. if ( ! (0x80 & $packettag)) {
  792. die "This is not an OpenPGP packet\n";
  793. }
  794. if (0x40 & $packettag) {
  795. # this is a new-format packet.
  796. $tag = (0x3f & $packettag);
  797. my $nextlen = 0;
  798. read($instr, $nextlen, 1);
  799. $nextlen = ord($nextlen);
  800. if ($nextlen < 192) {
  801. $packetlen = $nextlen;
  802. } elsif ($nextlen < 224) {
  803. my $newoct;
  804. read($instr, $newoct, 1);
  805. $newoct = ord($newoct);
  806. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  807. } elsif ($nextlen == 255) {
  808. read($instr, $nextlen, 4);
  809. $packetlen = unpack('N', $nextlen);
  810. } else {
  811. # packet length is undefined.
  812. }
  813. } else {
  814. # this is an old-format packet.
  815. my $lentype;
  816. $lentype = 0x03 & $packettag;
  817. $tag = ( 0x3c & $packettag ) >> 2;
  818. if ($lentype == 0) {
  819. read($instr, $packetlen, 1) or die "could not read packet length\n";
  820. $packetlen = unpack('C', $packetlen);
  821. } elsif ($lentype == 1) {
  822. read($instr, $packetlen, 2) or die "could not read packet length\n";
  823. $packetlen = unpack('n', $packetlen);
  824. } elsif ($lentype == 2) {
  825. read($instr, $packetlen, 4) or die "could not read packet length\n";
  826. $packetlen = unpack('N', $packetlen);
  827. } else {
  828. # packet length is undefined.
  829. }
  830. }
  831. if (! defined($packetlen)) {
  832. die "Undefined packet lengths are not supported.\n";
  833. }
  834. if (defined $subs->{$tag}) {
  835. $subs->{$tag}($data, $instr, $tag, $packetlen);
  836. } else {
  837. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  838. }
  839. }
  840. return $data->{key};
  841. }
  842. for (basename($0)) {
  843. if (/^pem2openpgp$/) {
  844. my $rsa;
  845. my $stdin;
  846. my $uid = shift;
  847. defined($uid) or die "You must specify a user ID string.\n";
  848. # FIXME: fail if there is no given user ID; or should we default to
  849. # hostname_long() from Sys::Hostname::Long ?
  850. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  851. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  852. } else {
  853. $stdin = do {
  854. local $/; # slurp!
  855. <STDIN>;
  856. };
  857. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  858. }
  859. my $key_timestamp = $ENV{PEM2OPENPGP_KEY_TIMESTAMP};
  860. my $sig_timestamp = $ENV{PEM2OPENPGP_TIMESTAMP};
  861. $sig_timestamp = time() if (!defined $sig_timestamp);
  862. $key_timestamp = $sig_timestamp if (!defined $key_timestamp);
  863. print
  864. make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
  865. make_packet($packet_types->{uid}, $uid).
  866. makeselfsig($rsa,
  867. $uid,
  868. { sig_timestamp => $sig_timestamp,
  869. key_timestamp => $key_timestamp,
  870. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  871. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  872. }
  873. );
  874. }
  875. elsif (/^openpgp2ssh$/) {
  876. my $fpr = shift;
  877. my $instream;
  878. open($instream,'-');
  879. binmode($instream, ":bytes");
  880. my $key = openpgp2rsa($instream, $fpr);
  881. if (defined($key)) {
  882. if ($key->is_private()) {
  883. print $key->get_private_key_string();
  884. } else {
  885. print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
  886. }
  887. } else {
  888. die "No matching key found.\n";
  889. }
  890. }
  891. elsif (/^keytrans$/) {
  892. # subcommands when keytrans is invoked directly are UNSUPPORTED,
  893. # UNDOCUMENTED, and WILL NOT BE MAINTAINED.
  894. my $subcommand = shift;
  895. for ($subcommand) {
  896. if (/^revokeuserid$/) {
  897. my $fpr = shift;
  898. my $uid = shift;
  899. my $instream;
  900. open($instream,'-');
  901. binmode($instream, ":bytes");
  902. my $revcert = revokeuserid($instream, $fpr, $uid, $ENV{PEM2OPENPGP_TIMESTAMP});
  903. print $revcert;
  904. } elsif (/^adduserid$/) {
  905. my $fpr = shift;
  906. my $uid = shift;
  907. my $instream;
  908. open($instream,'-');
  909. binmode($instream, ":bytes");
  910. my $newuid = adduserid($instream, $fpr, $uid,
  911. { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  912. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  913. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  914. });
  915. print $newuid;
  916. } elsif (/^listfprs$/) {
  917. my $instream;
  918. open($instream,'-');
  919. binmode($instream, ":bytes");
  920. my $keys = getallprimarykeys($instream);
  921. printf("%s\n", join("\n", map { uc(unpack('H*', $_)) } keys(%{$keys})));
  922. } else {
  923. die "Unrecognized subcommand. keytrans subcommands are not a stable interface!\n";
  924. }
  925. }
  926. }
  927. else {
  928. die "Unrecognized keytrans call.\n";
  929. }
  930. }