summaryrefslogtreecommitdiff
path: root/src/share/keytrans
blob: ae4fb0993980afb1de16558a227775486ab89b5e (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. # is this a match?
  567. if ((!defined($data->{target}->{fpr})) ||
  568. (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
  569. if (defined($data->{key})) {
  570. die "Found two matching keys.\n";
  571. }
  572. $data->{key} = { 'rsa' => $pubkey,
  573. 'timestamp' => $key_timestamp };
  574. }
  575. if ($tag != $packet_types->{seckey} &&
  576. $tag != $packet_types->{sec_subkey}) {
  577. if ($readbytes < $packetlen) {
  578. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  579. }
  580. return;
  581. }
  582. if (!defined($data->{key})) {
  583. # we don't think the public part of this key matches
  584. if ($readbytes < $packetlen) {
  585. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  586. }
  587. return;
  588. }
  589. my $s2k;
  590. read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
  591. $readbytes += 1;
  592. $s2k = ord($s2k);
  593. if ($s2k != 0) {
  594. printf(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
  595. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  596. return;
  597. }
  598. # secret material is unencrypted
  599. # see http://tools.ietf.org/html/rfc4880#section-5.5.3
  600. my $d = read_mpi($instr, \$readbytes);
  601. my $p = read_mpi($instr, \$readbytes);
  602. my $q = read_mpi($instr, \$readbytes);
  603. my $u = read_mpi($instr, \$readbytes);
  604. my $checksum;
  605. read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
  606. $readbytes += 2;
  607. $checksum = unpack('n', $checksum);
  608. # FIXME: compare with the checksum! how? the data is
  609. # gone into the Crypt::OpenSSL::Bignum
  610. $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
  611. $exponent,
  612. $d,
  613. $p,
  614. $q);
  615. $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
  616. if ($readbytes < $packetlen) {
  617. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  618. }
  619. }
  620. sub openpgp2rsa {
  621. my $instr = shift;
  622. my $fpr = shift;
  623. if (defined $fpr) {
  624. if (length($fpr) < 8) {
  625. die "We need at least 8 hex digits of fingerprint.\n";
  626. }
  627. $fpr = uc($fpr);
  628. }
  629. my $data = { target => { fpr => $fpr,
  630. },
  631. };
  632. my $subs = { $packet_types->{pubkey} => \&findkey,
  633. $packet_types->{pub_subkey} => \&findkey,
  634. $packet_types->{seckey} => \&findkey,
  635. $packet_types->{sec_subkey} => \&findkey };
  636. packetwalk($instr, $subs, $data);
  637. return $data->{key}->{rsa};
  638. }
  639. sub adduserid {
  640. my $instr = shift;
  641. my $fpr = shift;
  642. my $uid = shift;
  643. my $args = shift;
  644. if ((! defined $fpr) ||
  645. (length($fpr) < 8)) {
  646. die "We need at least 8 hex digits of fingerprint.\n";
  647. }
  648. $fpr = uc($fpr);
  649. if (! defined $uid) {
  650. die "No User ID defined.\n";
  651. }
  652. my $data = { target => { fpr => $fpr,
  653. uid => $uid,
  654. },
  655. };
  656. my $subs = { $packet_types->{seckey} => \&findkey,
  657. $packet_types->{uid} => \&finduid,
  658. $packet_types->{sig} => \&findsig,
  659. };
  660. packetwalk($instr, $subs, $data);
  661. if ((! defined $data->{key}) ||
  662. (! defined $data->{key}->{rsa}) ||
  663. (! defined $data->{key}->{timestamp})) {
  664. die "The key requested was not found.\n"
  665. }
  666. if (defined $data->{uid}->{$uid}) {
  667. die "The requested User ID '$uid' is already associated with this key.\n";
  668. }
  669. $args->{key_timestamp} = $data->{key}->{timestamp};
  670. return
  671. make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
  672. make_packet($packet_types->{uid}, $uid).
  673. makeselfsig($data->{key}->{rsa},
  674. $uid,
  675. $args);
  676. }
  677. sub revokeuserid {
  678. my $instr = shift;
  679. my $fpr = shift;
  680. my $uid = shift;
  681. my $sigtime = shift;
  682. if ((! defined $fpr) ||
  683. (length($fpr) < 8)) {
  684. die "We need at least 8 hex digits of fingerprint.\n";
  685. }
  686. $fpr = uc($fpr);
  687. if (! defined $uid) {
  688. die "No User ID defined.\n";
  689. }
  690. my $data = { target => { fpr => $fpr,
  691. uid => $uid,
  692. },
  693. };
  694. my $subs = { $packet_types->{seckey} => \&findkey,
  695. $packet_types->{uid} => \&finduid,
  696. $packet_types->{sig} => \&findsig,
  697. };
  698. packetwalk($instr, $subs, $data);
  699. if ((! defined $data->{uid}) ||
  700. (! defined $data->{uid}->{$uid})) {
  701. die "The User ID \"$uid\" is not associated with this key";
  702. }
  703. if ((! defined $data->{key}) ||
  704. (! defined $data->{key}->{rsa}) ||
  705. (! defined $data->{key}->{timestamp})) {
  706. die "The key requested was not found."
  707. }
  708. my $revocation_reason = 'No longer using this hostname';
  709. if (defined $data->{revocation_reason}) {
  710. $revocation_reason = $data->{revocation_reason};
  711. }
  712. my $rev_reason_subpkt = prefixsubpacket(pack('CC',
  713. $subpacket_types->{revocation_reason},
  714. $revocation_reasons->{user_id_no_longer_valid}).
  715. $revocation_reason);
  716. if (! defined $sigtime) {
  717. $sigtime = time();
  718. }
  719. # what does a signature like this look like?
  720. my $args = { key_timestamp => $data->{key}->{timestamp},
  721. sig_timestamp => $sigtime,
  722. certification_type => $sig_types->{certification_revocation},
  723. hashed_subpackets => $rev_reason_subpkt,
  724. };
  725. return
  726. make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
  727. make_packet($packet_types->{uid}, $uid).
  728. join('', @{$data->{sigs}}).
  729. gensig($data->{key}->{rsa}, $uid, $args);
  730. }
  731. # see 5.2.3.1 for tips on how to calculate the length of a subpacket:
  732. sub prefixsubpacket {
  733. my $subpacket = shift;
  734. my $len = length($subpacket);
  735. my $prefix;
  736. use bytes;
  737. if ($len < 192) {
  738. # one byte:
  739. $prefix = pack('C', $len);
  740. } elsif ($len < 16576) {
  741. my $in = $len - 192;
  742. my $second = $in%256;
  743. my $first = ($in - $second)>>8;
  744. $prefix = pack('CC', $first + 192, $second)
  745. } else {
  746. $prefix = pack('CN', 255, $len);
  747. }
  748. return $prefix.$subpacket;
  749. }
  750. sub packetwalk {
  751. my $instr = shift;
  752. my $subs = shift;
  753. my $data = shift;
  754. my $packettag;
  755. my $dummy;
  756. my $tag;
  757. while (! eof($instr)) {
  758. read($instr, $packettag, 1);
  759. $packettag = ord($packettag);
  760. my $packetlen;
  761. if ( ! (0x80 & $packettag)) {
  762. die "This is not an OpenPGP packet\n";
  763. }
  764. if (0x40 & $packettag) {
  765. # this is a new-format packet.
  766. $tag = (0x3f & $packettag);
  767. my $nextlen = 0;
  768. read($instr, $nextlen, 1);
  769. $nextlen = ord($nextlen);
  770. if ($nextlen < 192) {
  771. $packetlen = $nextlen;
  772. } elsif ($nextlen < 224) {
  773. my $newoct;
  774. read($instr, $newoct, 1);
  775. $newoct = ord($newoct);
  776. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  777. } elsif ($nextlen == 255) {
  778. read($instr, $nextlen, 4);
  779. $packetlen = unpack('N', $nextlen);
  780. } else {
  781. # packet length is undefined.
  782. }
  783. } else {
  784. # this is an old-format packet.
  785. my $lentype;
  786. $lentype = 0x03 & $packettag;
  787. $tag = ( 0x3c & $packettag ) >> 2;
  788. if ($lentype == 0) {
  789. read($instr, $packetlen, 1) or die "could not read packet length\n";
  790. $packetlen = unpack('C', $packetlen);
  791. } elsif ($lentype == 1) {
  792. read($instr, $packetlen, 2) or die "could not read packet length\n";
  793. $packetlen = unpack('n', $packetlen);
  794. } elsif ($lentype == 2) {
  795. read($instr, $packetlen, 4) or die "could not read packet length\n";
  796. $packetlen = unpack('N', $packetlen);
  797. } else {
  798. # packet length is undefined.
  799. }
  800. }
  801. if (! defined($packetlen)) {
  802. die "Undefined packet lengths are not supported.\n";
  803. }
  804. if (defined $subs->{$tag}) {
  805. $subs->{$tag}($data, $instr, $tag, $packetlen);
  806. } else {
  807. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  808. }
  809. }
  810. return $data->{key};
  811. }
  812. for (basename($0)) {
  813. if (/^pem2openpgp$/) {
  814. my $rsa;
  815. my $stdin;
  816. my $uid = shift;
  817. defined($uid) or die "You must specify a user ID string.\n";
  818. # FIXME: fail if there is no given user ID; or should we default to
  819. # hostname_long() from Sys::Hostname::Long ?
  820. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  821. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  822. } else {
  823. $stdin = do {
  824. local $/; # slurp!
  825. <STDIN>;
  826. };
  827. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  828. }
  829. my $key_timestamp = $ENV{PEM2OPENPGP_KEY_TIMESTAMP};
  830. my $sig_timestamp = $ENV{PEM2OPENPGP_TIMESTAMP};
  831. $sig_timestamp = time() if (!defined $sig_timestamp);
  832. $key_timestamp = $sig_timestamp if (!defined $key_timestamp);
  833. print
  834. make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
  835. make_packet($packet_types->{uid}, $uid).
  836. makeselfsig($rsa,
  837. $uid,
  838. { sig_timestamp => $sig_timestamp,
  839. key_timestamp => $key_timestamp,
  840. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  841. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  842. }
  843. );
  844. }
  845. elsif (/^openpgp2ssh$/) {
  846. my $fpr = shift;
  847. my $instream;
  848. open($instream,'-');
  849. binmode($instream, ":bytes");
  850. my $key = openpgp2rsa($instream, $fpr);
  851. if (defined($key)) {
  852. if ($key->is_private()) {
  853. print $key->get_private_key_string();
  854. } else {
  855. print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
  856. }
  857. } else {
  858. die "No matching key found.\n";
  859. }
  860. }
  861. elsif (/^keytrans$/) {
  862. # subcommands when keytrans is invoked directly are UNSUPPORTED,
  863. # UNDOCUMENTED, and WILL NOT BE MAINTAINED.
  864. my $subcommand = shift;
  865. for ($subcommand) {
  866. if (/^revokeuserid$/) {
  867. my $fpr = shift;
  868. my $uid = shift;
  869. my $instream;
  870. open($instream,'-');
  871. binmode($instream, ":bytes");
  872. my $revcert = revokeuserid($instream, $fpr, $uid, $ENV{PEM2OPENPGP_TIMESTAMP});
  873. print $revcert;
  874. } elsif (/^adduserid$/) {
  875. my $fpr = shift;
  876. my $uid = shift;
  877. my $instream;
  878. open($instream,'-');
  879. binmode($instream, ":bytes");
  880. my $newuid = adduserid($instream, $fpr, $uid,
  881. { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  882. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  883. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  884. });
  885. print $newuid;
  886. } else {
  887. die "Unrecognized subcommand. keytrans subcommands are not a stable interface!\n";
  888. }
  889. }
  890. }
  891. else {
  892. die "Unrecognized keytrans call.\n";
  893. }
  894. }