summaryrefslogtreecommitdiff
path: root/src/share/keytrans
blob: 8b2e2ea52b926a006896de9b1adee71eea6b1f32 (plain)
  1. #!/usr/bin/perl -w -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::SHA1;
  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 43 of RFC 4880
  161. sub simple_checksum {
  162. my $bytes = shift;
  163. return unpack("%32W*",$bytes) % 65536;
  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 $timestamp = shift;
  292. my ($n, $e) = $key->get_key_parameters();
  293. return
  294. pack('CN', 4, $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 $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, $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 $timestamp = shift;
  327. my $rsabody = make_rsa_pub_key_body($key, $timestamp);
  328. return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  329. }
  330. # FIXME: handle DSA keys as well!
  331. sub pem2openpgp {
  332. my $rsa = shift;
  333. my $uid = shift;
  334. my $args = shift;
  335. $rsa->use_sha1_hash();
  336. # see page 22 of RFC 4880 for why i think this is the right padding
  337. # choice to use:
  338. $rsa->use_pkcs1_padding();
  339. if (! $rsa->check_key()) {
  340. die "key does not check";
  341. }
  342. my $version = pack('C', 4);
  343. # strong assertion of identity:
  344. my $sigtype = pack('C', $sig_types->{positive_certification});
  345. # RSA
  346. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  347. # SHA1
  348. my $hash_algo = pack('C', $digests->{sha1});
  349. # FIXME: i'm worried about generating a bazillion new OpenPGP
  350. # certificates from the same key, which could easily happen if you run
  351. # this script more than once against the same key (because the
  352. # timestamps will differ). How can we prevent this?
  353. # this environment variable (if set) overrides the current time, to
  354. # be able to create a standard key? If we read the key from a file
  355. # instead of stdin, should we use the creation time on the file?
  356. my $timestamp = 0;
  357. if (defined $args->{timestamp}) {
  358. $timestamp = ($args->{timestamp} + 0);
  359. } else {
  360. $timestamp = time();
  361. }
  362. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
  363. my $flags = 0;
  364. if (! defined $args->{usage_flags}) {
  365. $flags = $usage_flags->{certify};
  366. } else {
  367. my @ff = split(",", $args->{usage_flags});
  368. foreach my $f (@ff) {
  369. if (! defined $usage_flags->{$f}) {
  370. die "No such flag $f";
  371. }
  372. $flags |= $usage_flags->{$f};
  373. }
  374. }
  375. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  376. # how should we determine how far off to set the expiration date?
  377. # default is no expiration. Specify the timestamp in seconds from the
  378. # key creation.
  379. my $expiration_packet = '';
  380. if (defined $args->{expiration}) {
  381. my $expires_in = $args->{expiration} + 0;
  382. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  383. }
  384. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  385. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  386. $ciphers->{aes256},
  387. $ciphers->{aes192},
  388. $ciphers->{aes128},
  389. $ciphers->{cast5},
  390. $ciphers->{tripledes}
  391. );
  392. # prefer SHA-1, SHA-256, RIPE-MD/160
  393. my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
  394. $digests->{sha1},
  395. $digests->{sha256},
  396. $digests->{ripemd160}
  397. );
  398. # prefer ZLIB, BZip2, ZIP
  399. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  400. $zips->{zlib},
  401. $zips->{bzip2},
  402. $zips->{zip}
  403. );
  404. # we support the MDC feature:
  405. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  406. $features->{mdc});
  407. # keyserver preference: only owner modify (???):
  408. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  409. $keyserver_prefs->{nomodify});
  410. my $subpackets_to_be_hashed =
  411. $creation_time_packet.
  412. $usage_packet.
  413. $expiration_packet.
  414. $pref_sym_algos.
  415. $pref_hash_algos.
  416. $pref_zip_algos.
  417. $feature_subpacket.
  418. $keyserver_pref;
  419. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  420. my $sig_data_to_be_hashed =
  421. $version.
  422. $sigtype.
  423. $pubkey_algo.
  424. $hash_algo.
  425. $subpacket_octets.
  426. $subpackets_to_be_hashed;
  427. my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
  428. my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
  429. # this is for signing. it needs to be an old-style header with a
  430. # 2-packet octet count.
  431. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  432. # take the last 8 bytes of the fingerprint as the keyid:
  433. my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
  434. # the v4 signature trailer is:
  435. # version number, literal 0xff, and then a 4-byte count of the
  436. # signature data itself.
  437. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  438. my $uid_data =
  439. pack('CN', 0xb4, length($uid)).
  440. $uid;
  441. my $datatosign =
  442. $key_data.
  443. $uid_data.
  444. $sig_data_to_be_hashed.
  445. $trailer;
  446. my $data_hash = Digest::SHA1::sha1_hex($datatosign);
  447. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  448. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  449. my $sig_body =
  450. $sig_data_to_be_hashed.
  451. pack('n', length($issuer_packet)).
  452. $issuer_packet.
  453. pack('n', hex(substr($data_hash, 0, 4))).
  454. mpi_pack($sig);
  455. return
  456. make_packet($packet_types->{seckey}, $seckey).
  457. make_packet($packet_types->{uid}, $uid).
  458. make_packet($packet_types->{sig}, $sig_body);
  459. }
  460. sub openpgp2ssh {
  461. my $instr = shift;
  462. my $fpr = shift;
  463. if (defined $fpr) {
  464. if (length($fpr) < 8) {
  465. die "We need at least 8 hex digits of fingerprint.\n";
  466. }
  467. $fpr = uc($fpr);
  468. }
  469. my $packettag;
  470. my $dummy;
  471. my $tag;
  472. my $key;
  473. while (! eof($instr)) {
  474. read($instr, $packettag, 1);
  475. $packettag = ord($packettag);
  476. my $packetlen;
  477. if ( ! (0x80 & $packettag)) {
  478. die "This is not an OpenPGP packet\n";
  479. }
  480. if (0x40 & $packettag) {
  481. $tag = (0x3f & $packettag);
  482. my $nextlen = 0;
  483. read($instr, $nextlen, 1);
  484. $nextlen = ord($nextlen);
  485. if ($nextlen < 192) {
  486. $packetlen = $nextlen;
  487. } elsif ($nextlen < 224) {
  488. my $newoct;
  489. read($instr, $newoct, 1);
  490. $newoct = ord($newoct);
  491. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  492. } elsif ($nextlen == 255) {
  493. read($instr, $nextlen, 4);
  494. $packetlen = unpack('N', $nextlen);
  495. } else {
  496. # packet length is undefined.
  497. }
  498. } else {
  499. my $lentype;
  500. $lentype = 0x03 & $packettag;
  501. $tag = ( 0x3c & $packettag ) >> 2;
  502. if ($lentype == 0) {
  503. read($instr, $packetlen, 1) or die "could not read packet length\n";
  504. $packetlen = unpack('C', $packetlen);
  505. } elsif ($lentype == 1) {
  506. read($instr, $packetlen, 2) or die "could not read packet length\n";
  507. $packetlen = unpack('n', $packetlen);
  508. } elsif ($lentype == 2) {
  509. read($instr, $packetlen, 4) or die "could not read packet length\n";
  510. $packetlen = unpack('N', $packetlen);
  511. } else {
  512. # packet length is undefined.
  513. }
  514. }
  515. if (! defined($packetlen)) {
  516. die "Undefined packet lengths are not supported.\n";
  517. }
  518. if ($tag == $packet_types->{pubkey} ||
  519. $tag == $packet_types->{pub_subkey} ||
  520. $tag == $packet_types->{seckey} ||
  521. $tag == $packet_types->{sec_subkey}) {
  522. my $ver;
  523. my $readbytes = 0;
  524. read($instr, $ver, 1) or die "could not read key version\n";
  525. $readbytes += 1;
  526. $ver = ord($ver);
  527. if ($ver != 4) {
  528. printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
  529. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  530. } else {
  531. my $timestamp;
  532. read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
  533. $readbytes += 4;
  534. $timestamp = unpack('N', $timestamp);
  535. my $algo;
  536. read($instr, $algo, 1) or die "could not read key algorithm.\n";
  537. $readbytes += 1;
  538. $algo = ord($algo);
  539. if ($algo != $asym_algos->{rsa}) {
  540. printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
  541. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  542. } else {
  543. ## we have an RSA key.
  544. my $modulus = read_mpi($instr, \$readbytes);
  545. my $exponent = read_mpi($instr, \$readbytes);
  546. my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
  547. my $foundfpr = fingerprint($pubkey, $timestamp);
  548. my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
  549. # is this a match?
  550. if ((!defined($fpr)) ||
  551. (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
  552. if (defined($key)) {
  553. die "Found two matching keys.\n";
  554. }
  555. $key = $pubkey;
  556. }
  557. if ($tag == $packet_types->{seckey} ||
  558. $tag == $packet_types->{sec_subkey}) {
  559. if (!defined($key)) { # we don't think the public part of
  560. # this key matches
  561. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  562. } else {
  563. my $s2k;
  564. read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
  565. $readbytes += 1;
  566. $s2k = ord($s2k);
  567. if ($s2k == 0) {
  568. # secret material is unencrypted
  569. # see http://tools.ietf.org/html/rfc4880#section-5.5.3
  570. my $d = read_mpi($instr, \$readbytes);
  571. my $p = read_mpi($instr, \$readbytes);
  572. my $q = read_mpi($instr, \$readbytes);
  573. my $u = read_mpi($instr, \$readbytes);
  574. my $checksum;
  575. read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
  576. $readbytes += 2;
  577. $checksum = unpack('n', $checksum);
  578. # FIXME: compare with the checksum! how? the data is
  579. # gone into the Crypt::OpenSSL::Bignum
  580. $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
  581. $exponent,
  582. $d,
  583. $p,
  584. $q);
  585. $key->check_key() or die "Secret key is not a valid RSA key.\n";
  586. } else {
  587. print(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
  588. read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
  589. }
  590. }
  591. }
  592. }
  593. }
  594. } else {
  595. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  596. }
  597. }
  598. return $key;
  599. }
  600. for (basename($0)) {
  601. if (/^pem2openpgp$/) {
  602. my $rsa;
  603. my $stdin;
  604. my $uid = shift;
  605. defined($uid) or die "You must specify a user ID string.\n";
  606. # FIXME: fail if there is no given user ID; or should we default to
  607. # hostname_long() from Sys::Hostname::Long ?
  608. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  609. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  610. } else {
  611. $stdin = do {
  612. local $/; # slurp!
  613. <STDIN>;
  614. };
  615. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  616. }
  617. print pem2openpgp($rsa,
  618. $uid,
  619. { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  620. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  621. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  622. }
  623. );
  624. }
  625. elsif (/^openpgp2ssh$/) {
  626. my $fpr = shift;
  627. my $instream;
  628. open($instream,'-');
  629. binmode($instream, ":bytes");
  630. my $key = openpgp2ssh($instream, $fpr);
  631. if (defined($key)) {
  632. if ($key->is_private()) {
  633. print $key->get_private_key_string();
  634. } else {
  635. print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
  636. }
  637. } else {
  638. die "No matching key found.\n";
  639. }
  640. }
  641. else {
  642. die "Unrecognized keytrans call.\n";
  643. }
  644. }