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