summaryrefslogtreecommitdiff
path: root/src/keytrans/pem2openpgp
blob: ae7c91f88e905830245230cd1fc7a084cdfdd1fc (plain)
  1. #!/usr/bin/perl -w -T
  2. # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
  3. # User ID as the first argument, and generate an OpenPGP secret key
  4. # and certificate from it.
  5. # WARNING: the secret key material *will* appear on stdout (albeit in
  6. # OpenPGP form) -- if you redirect stdout to a file, make sure the
  7. # permissions on that file are appropriately locked down!
  8. # Usage:
  9. # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
  10. # Authors:
  11. # Jameson Rollins <jrollins@finestructure.net>
  12. # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
  13. # Started on: 2009-01-07 02:01:19-0500
  14. # License: GPL v3 or later (we may need to adjust this given that this
  15. # connects to OpenSSL via perl)
  16. use strict;
  17. use warnings;
  18. use File::Basename;
  19. use Crypt::OpenSSL::RSA;
  20. use Crypt::OpenSSL::Bignum;
  21. use Crypt::OpenSSL::Bignum::CTX;
  22. use Digest::SHA1;
  23. use MIME::Base64;
  24. ## make sure all length() and substr() calls use bytes only:
  25. use bytes;
  26. my $old_format_packet_lengths = { one => 0,
  27. two => 1,
  28. four => 2,
  29. indeterminate => 3,
  30. };
  31. # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
  32. my $asym_algos = { rsa => 1,
  33. elgamal => 16,
  34. dsa => 17,
  35. };
  36. # see RFC 4880 section 9.2
  37. my $ciphers = { plaintext => 0,
  38. idea => 1,
  39. tripledes => 2,
  40. cast5 => 3,
  41. blowfish => 4,
  42. aes128 => 7,
  43. aes192 => 8,
  44. aes256 => 9,
  45. twofish => 10,
  46. };
  47. # see RFC 4880 section 9.3
  48. my $zips = { uncompressed => 0,
  49. zip => 1,
  50. zlib => 2,
  51. bzip2 => 3,
  52. };
  53. # see RFC 4880 section 9.4
  54. my $digests = { md5 => 1,
  55. sha1 => 2,
  56. ripemd160 => 3,
  57. sha256 => 8,
  58. sha384 => 9,
  59. sha512 => 10,
  60. sha224 => 11,
  61. };
  62. # see RFC 4880 section 5.2.3.21
  63. my $usage_flags = { certify => 0x01,
  64. sign => 0x02,
  65. encrypt_comms => 0x04,
  66. encrypt_storage => 0x08,
  67. encrypt => 0x0c, ## both comms and storage
  68. split => 0x10, # the private key is split via secret sharing
  69. authenticate => 0x20,
  70. shared => 0x80, # more than one person holds the entire private key
  71. };
  72. # see RFC 4880 section 4.3
  73. my $packet_types = { pubkey_enc_session => 1,
  74. sig => 2,
  75. symkey_enc_session => 3,
  76. onepass_sig => 4,
  77. seckey => 5,
  78. pubkey => 6,
  79. sec_subkey => 7,
  80. compressed_data => 8,
  81. symenc_data => 9,
  82. marker => 10,
  83. literal => 11,
  84. trust => 12,
  85. uid => 13,
  86. pub_subkey => 14,
  87. uat => 17,
  88. symenc_w_integrity => 18,
  89. mdc => 19,
  90. };
  91. # see RFC 4880 section 5.2.1
  92. my $sig_types = { binary_doc => 0x00,
  93. text_doc => 0x01,
  94. standalone => 0x02,
  95. generic_certification => 0x10,
  96. persona_certification => 0x11,
  97. casual_certification => 0x12,
  98. positive_certification => 0x13,
  99. subkey_binding => 0x18,
  100. primary_key_binding => 0x19,
  101. key_signature => 0x1f,
  102. key_revocation => 0x20,
  103. subkey_revocation => 0x28,
  104. certification_revocation => 0x30,
  105. timestamp => 0x40,
  106. thirdparty => 0x50,
  107. };
  108. # see RFC 4880 section 5.2.3.1
  109. my $subpacket_types = { sig_creation_time => 2,
  110. sig_expiration_time => 3,
  111. exportable => 4,
  112. trust_sig => 5,
  113. regex => 6,
  114. revocable => 7,
  115. key_expiration_time => 9,
  116. preferred_cipher => 11,
  117. revocation_key => 12,
  118. issuer => 16,
  119. notation => 20,
  120. preferred_digest => 21,
  121. preferred_compression => 22,
  122. keyserver_prefs => 23,
  123. preferred_keyserver => 24,
  124. primary_uid => 25,
  125. policy_uri => 26,
  126. usage_flags => 27,
  127. signers_uid => 28,
  128. revocation_reason => 29,
  129. features => 30,
  130. signature_target => 31,
  131. embedded_signature => 32,
  132. };
  133. # bitstring (see RFC 4880 section 5.2.3.24)
  134. my $features = { mdc => 0x01
  135. };
  136. # bitstring (see RFC 4880 5.2.3.17)
  137. my $keyserver_prefs = { nomodify => 0x80
  138. };
  139. ###### end lookup tables ######
  140. # FIXME: if we want to be able to interpret openpgp data as well as
  141. # produce it, we need to produce key/value-swapped lookup tables as well.
  142. ########### Math/Utility Functions ##############
  143. # see the bottom of page 43 of RFC 4880
  144. sub simple_checksum {
  145. my $bytes = shift;
  146. return unpack("%32W*",$bytes) % 65536;
  147. }
  148. # calculate the multiplicative inverse of a mod b this is euclid's
  149. # extended algorithm. For more information see:
  150. # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
  151. # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
  152. # be the larger of the two values, and the two values should be
  153. # coprime.
  154. sub modular_multi_inverse {
  155. my $a = shift;
  156. my $b = shift;
  157. my $origdivisor = $b->copy();
  158. my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
  159. my $x = Crypt::OpenSSL::Bignum->zero();
  160. my $y = Crypt::OpenSSL::Bignum->one();
  161. my $lastx = Crypt::OpenSSL::Bignum->one();
  162. my $lasty = Crypt::OpenSSL::Bignum->zero();
  163. my $finalquotient;
  164. my $finalremainder;
  165. while (! $b->is_zero()) {
  166. my ($quotient, $remainder) = $a->div($b, $ctx);
  167. $a = $b;
  168. $b = $remainder;
  169. my $temp = $x;
  170. $x = $lastx->sub($quotient->mul($x, $ctx));
  171. $lastx = $temp;
  172. $temp = $y;
  173. $y = $lasty->sub($quotient->mul($y, $ctx));
  174. $lasty = $temp;
  175. }
  176. if (!$a->is_one()) {
  177. die "did this math wrong.\n";
  178. }
  179. # let's make sure that we return a positive value because RFC 4880,
  180. # section 3.2 only allows unsigned values:
  181. ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
  182. return $finalremainder;
  183. }
  184. ############ OpenPGP formatting functions ############
  185. # make an old-style packet out of the given packet type and body.
  186. # old-style (see RFC 4880 section 4.2)
  187. sub make_packet {
  188. my $type = shift;
  189. my $body = shift;
  190. my $options = shift;
  191. my $len = length($body);
  192. my $pseudolen = $len;
  193. # if the caller wants to use at least N octets of packet length,
  194. # pretend that we're using that many.
  195. if (defined $options && defined $options->{'packet_length'}) {
  196. $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
  197. }
  198. if ($pseudolen < $len) {
  199. $pseudolen = $len;
  200. }
  201. my $lenbytes;
  202. my $lencode;
  203. if ($pseudolen < 2**8) {
  204. $lenbytes = $old_format_packet_lengths->{one};
  205. $lencode = 'C';
  206. } elsif ($pseudolen < 2**16) {
  207. $lenbytes = $old_format_packet_lengths->{two};
  208. $lencode = 'n';
  209. } elsif ($pseudolen < 2**31) {
  210. ## not testing against full 32 bits because i don't want to deal
  211. ## with potential overflow.
  212. $lenbytes = $old_format_packet_lengths->{four};
  213. $lencode = 'N';
  214. } else {
  215. ## what the hell do we do here?
  216. $lenbytes = $old_format_packet_lengths->{indeterminate};
  217. $lencode = '';
  218. }
  219. return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
  220. $body;
  221. }
  222. # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
  223. # (RFC 4880 section 3.2)
  224. sub mpi_pack {
  225. my $num = shift;
  226. my $val = $num->to_bin();
  227. my $mpilen = length($val)*8;
  228. # this is a kludgy way to get the number of significant bits in the
  229. # first byte:
  230. my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
  231. $mpilen -= (8 - $bitsinfirstbyte);
  232. return pack('n', $mpilen).$val;
  233. }
  234. # pull an OpenPGP-specified MPI off of a given stream.
  235. sub read_mpi {
  236. my $instr = shift;
  237. my $bitlen;
  238. read($instr, $bitlen, 2) or die "could not read MPI length.\n";
  239. $bitlen = unpack('n', $bitlen);
  240. my $ret;
  241. read($instr, $ret, ($bitlen + 7)/8) or die "could not read MPI body.\n";
  242. return Crypt::OpenSSL::Bignum->new_from_bin($ret);
  243. }
  244. # FIXME: genericize these to accept either RSA or DSA keys:
  245. sub make_rsa_pub_key_body {
  246. my $key = shift;
  247. my $timestamp = shift;
  248. my ($n, $e) = $key->get_key_parameters();
  249. return
  250. pack('CN', 4, $timestamp).
  251. pack('C', $asym_algos->{rsa}).
  252. mpi_pack($n).
  253. mpi_pack($e);
  254. }
  255. sub make_rsa_sec_key_body {
  256. my $key = shift;
  257. my $timestamp = shift;
  258. # we're not using $a and $b, but we need them to get to $c.
  259. my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
  260. my $c3 = modular_multi_inverse($p, $q);
  261. my $secret_material = mpi_pack($d).
  262. mpi_pack($p).
  263. mpi_pack($q).
  264. mpi_pack($c3);
  265. # according to Crypt::OpenSSL::RSA, the closest value we can get out
  266. # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
  267. # RFC 4880, we're actually looking for u, the multiplicative inverse
  268. # of p, mod q. This is why we're calculating the value directly
  269. # with modular_multi_inverse.
  270. return
  271. pack('CN', 4, $timestamp).
  272. pack('C', $asym_algos->{rsa}).
  273. mpi_pack($n).
  274. mpi_pack($e).
  275. pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
  276. $secret_material.
  277. pack('n', simple_checksum($secret_material));
  278. }
  279. # expects an RSA key (public or private) and a timestamp
  280. sub fingerprint {
  281. my $key = shift;
  282. my $timestamp = shift;
  283. my $rsabody = make_rsa_pub_key_body($key, $timestamp);
  284. return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  285. }
  286. # FIXME: handle DSA keys as well!
  287. sub pem2openpgp {
  288. my $rsa = shift;
  289. my $uid = shift;
  290. my $args = shift;
  291. $rsa->use_sha1_hash();
  292. # see page 22 of RFC 4880 for why i think this is the right padding
  293. # choice to use:
  294. $rsa->use_pkcs1_padding();
  295. if (! $rsa->check_key()) {
  296. die "key does not check";
  297. }
  298. my $version = pack('C', 4);
  299. # strong assertion of identity:
  300. my $sigtype = pack('C', $sig_types->{positive_certification});
  301. # RSA
  302. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  303. # SHA1
  304. my $hash_algo = pack('C', $digests->{sha1});
  305. # FIXME: i'm worried about generating a bazillion new OpenPGP
  306. # certificates from the same key, which could easily happen if you run
  307. # this script more than once against the same key (because the
  308. # timestamps will differ). How can we prevent this?
  309. # this environment variable (if set) overrides the current time, to
  310. # be able to create a standard key? If we read the key from a file
  311. # instead of stdin, should we use the creation time on the file?
  312. my $timestamp = 0;
  313. if (defined $args->{timestamp}) {
  314. $timestamp = ($args->{timestamp} + 0);
  315. } else {
  316. $timestamp = time();
  317. }
  318. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
  319. my $flags = 0;
  320. if (! defined $args->{usage_flags}) {
  321. $flags = $usage_flags->{certify};
  322. } else {
  323. my @ff = split(",", $args->{usage_flags});
  324. foreach my $f (@ff) {
  325. if (! defined $usage_flags->{$f}) {
  326. die "No such flag $f";
  327. }
  328. $flags |= $usage_flags->{$f};
  329. }
  330. }
  331. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  332. # how should we determine how far off to set the expiration date?
  333. # default is no expiration. Specify the timestamp in seconds from the
  334. # key creation.
  335. my $expiration_packet = '';
  336. if (defined $args->{expiration}) {
  337. my $expires_in = $args->{expiration} + 0;
  338. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  339. }
  340. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  341. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  342. $ciphers->{aes256},
  343. $ciphers->{aes192},
  344. $ciphers->{aes128},
  345. $ciphers->{cast5},
  346. $ciphers->{tripledes}
  347. );
  348. # prefer SHA-1, SHA-256, RIPE-MD/160
  349. my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
  350. $digests->{sha1},
  351. $digests->{sha256},
  352. $digests->{ripemd160}
  353. );
  354. # prefer ZLIB, BZip2, ZIP
  355. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  356. $zips->{zlib},
  357. $zips->{bzip2},
  358. $zips->{zip}
  359. );
  360. # we support the MDC feature:
  361. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  362. $features->{mdc});
  363. # keyserver preference: only owner modify (???):
  364. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  365. $keyserver_prefs->{nomodify});
  366. my $subpackets_to_be_hashed =
  367. $creation_time_packet.
  368. $usage_packet.
  369. $expiration_packet.
  370. $pref_sym_algos.
  371. $pref_hash_algos.
  372. $pref_zip_algos.
  373. $feature_subpacket.
  374. $keyserver_pref;
  375. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  376. my $sig_data_to_be_hashed =
  377. $version.
  378. $sigtype.
  379. $pubkey_algo.
  380. $hash_algo.
  381. $subpacket_octets.
  382. $subpackets_to_be_hashed;
  383. my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
  384. my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
  385. # this is for signing. it needs to be an old-style header with a
  386. # 2-packet octet count.
  387. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  388. # take the last 8 bytes of the fingerprint as the keyid:
  389. my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
  390. # the v4 signature trailer is:
  391. # version number, literal 0xff, and then a 4-byte count of the
  392. # signature data itself.
  393. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  394. my $uid_data =
  395. pack('CN', 0xb4, length($uid)).
  396. $uid;
  397. my $datatosign =
  398. $key_data.
  399. $uid_data.
  400. $sig_data_to_be_hashed.
  401. $trailer;
  402. my $data_hash = Digest::SHA1::sha1_hex($datatosign);
  403. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  404. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  405. my $sig_body =
  406. $sig_data_to_be_hashed.
  407. pack('n', length($issuer_packet)).
  408. $issuer_packet.
  409. pack('n', hex(substr($data_hash, 0, 4))).
  410. mpi_pack($sig);
  411. return
  412. make_packet($packet_types->{seckey}, $seckey).
  413. make_packet($packet_types->{uid}, $uid).
  414. make_packet($packet_types->{sig}, $sig_body);
  415. }
  416. sub openpgp2ssh {
  417. my $instr = shift;
  418. my $fpr = shift;
  419. my $packettag;
  420. my $dummy;
  421. my $tag;
  422. while (! eof($instr)) {
  423. read($instr, $packettag, 1);
  424. $packettag = ord($packettag);
  425. my $packetlen;
  426. if ( ! (0x80 & $packettag)) {
  427. die "This is not an OpenPGP packet\n";
  428. }
  429. if (0x40 & $packettag) {
  430. $tag = (0x3f & $packettag);
  431. my $nextlen = 0;
  432. read($instr, $nextlen, 1);
  433. $nextlen = ord($nextlen);
  434. if ($nextlen < 192) {
  435. $packetlen = $nextlen;
  436. } elsif ($nextlen < 224) {
  437. my $newoct;
  438. read($instr, $newoct, 1);
  439. $newoct = ord($newoct);
  440. $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
  441. } elsif ($nextlen == 255) {
  442. read($instr, $nextlen, 4);
  443. $packetlen = unpack('N', $nextlen);
  444. } else {
  445. # packet length is undefined.
  446. }
  447. } else {
  448. my $lentype;
  449. $lentype = 0x03 & $packettag;
  450. $tag = ( 0x3c & $packettag ) >> 2;
  451. if ($lentype == 0) {
  452. read($instr, $packetlen, 1) or die "could not read packet length\n";
  453. $packetlen = unpack('C', $packetlen);
  454. } elsif ($lentype == 1) {
  455. read($instr, $packetlen, 2) or die "could not read packet length\n";
  456. $packetlen = unpack('n', $packetlen);
  457. } elsif ($lentype == 2) {
  458. read($instr, $packetlen, 4) or die "could not read packet length\n";
  459. $packetlen = unpack('N', $packetlen);
  460. } else {
  461. # packet length is undefined.
  462. }
  463. }
  464. if (! defined($packetlen)) {
  465. die "Undefined packet lengths are not supported.\n";
  466. }
  467. if ($tag == $packet_types->{pubkey} ||
  468. $tag == $packet_types->{pub_subkey} ||
  469. $tag == $packet_types->{seckey} ||
  470. $tag == $packet_types->{sec_subkey}) {
  471. printf(STDERR "Packet type %d\n", $tag);
  472. my $ver;
  473. read($instr, $ver, 1) or die "could not read key version\n";
  474. $ver = ord($ver);
  475. if ($ver != 4) {
  476. printf(STDERR "We only work with version 4 keys. This key appears to be version $ver.\n");
  477. read($instr, $dummy, $packetlen - 1) or die "Could not skip past this packet.\n";
  478. } else {
  479. my $timestamp;
  480. read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
  481. $timestamp = unpack('N', $timestamp);
  482. my $algo;
  483. read($instr, $algo, 1) or die "could not read key algorithm.\n";
  484. $algo = ord($algo);
  485. if ($algo != $asym_algos->{rsa}) {
  486. printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
  487. read($instr, $dummy, $packetlen - 6) or die "Could not skip past this packet.\n";
  488. } else {
  489. ## we have an RSA key.
  490. my $modulus = read_mpi($instr);
  491. my $exponent = read_mpi($instr);
  492. my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
  493. my $foundfpr = fingerprint($pubkey, $timestamp);
  494. printf(STDERR "key fpr: %s\n", Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex());
  495. if ($tag == $packet_types->{seckey} ||
  496. $tag == $packet_types->{sec_subkey}) {
  497. die "Cannot deal with secret keys yet!\n";
  498. }
  499. }
  500. }
  501. } else {
  502. read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
  503. }
  504. }
  505. print $tag;
  506. }
  507. for (basename($0)) {
  508. if (/^pem2openpgp$/) {
  509. my $rsa;
  510. my $stdin;
  511. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  512. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  513. } else {
  514. $stdin = do {
  515. local $/; # slurp!
  516. <STDIN>;
  517. };
  518. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  519. }
  520. my $uid = shift;
  521. # FIXME: fail if there is no given user ID; or should we default to
  522. # hostname_long() from Sys::Hostname::Long ?
  523. print pem2openpgp($rsa,
  524. $uid,
  525. { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  526. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  527. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  528. }
  529. );
  530. }
  531. elsif (/^openpgp2ssh$/) {
  532. my $fpr = shift;
  533. my $instream;
  534. open($instream,'-');
  535. binmode($instream, ":bytes");
  536. openpgp2ssh($instream, $fpr);
  537. }
  538. else {
  539. die "Unrecognized keytrans call.\n";
  540. }
  541. }