summaryrefslogtreecommitdiff
path: root/src/keytrans/pem2openpgp
blob: 9b7d8f689dfff6d81cef69ce390abb377ad7c06c (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. # FIXME: genericize these to accept either RSA or DSA keys:
  235. sub make_rsa_pub_key_body {
  236. my $key = shift;
  237. my $timestamp = shift;
  238. my ($n, $e) = $key->get_key_parameters();
  239. return
  240. pack('CN', 4, $timestamp).
  241. pack('C', $asym_algos->{rsa}).
  242. mpi_pack($n).
  243. mpi_pack($e);
  244. }
  245. sub make_rsa_sec_key_body {
  246. my $key = shift;
  247. my $timestamp = shift;
  248. # we're not using $a and $b, but we need them to get to $c.
  249. my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
  250. my $c3 = modular_multi_inverse($p, $q);
  251. my $secret_material = mpi_pack($d).
  252. mpi_pack($p).
  253. mpi_pack($q).
  254. mpi_pack($c3);
  255. # according to Crypt::OpenSSL::RSA, the closest value we can get out
  256. # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
  257. # RFC 4880, we're actually looking for u, the multiplicative inverse
  258. # of p, mod q. This is why we're calculating the value directly
  259. # with modular_multi_inverse.
  260. return
  261. pack('CN', 4, $timestamp).
  262. pack('C', $asym_algos->{rsa}).
  263. mpi_pack($n).
  264. mpi_pack($e).
  265. pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
  266. $secret_material.
  267. pack('n', simple_checksum($secret_material));
  268. }
  269. # expects an RSA key (public or private) and a timestamp
  270. sub fingerprint {
  271. my $key = shift;
  272. my $timestamp = shift;
  273. my $rsabody = make_rsa_pub_key_body($key, $timestamp);
  274. return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  275. }
  276. # FIXME: handle DSA keys as well!
  277. sub pem2openpgp {
  278. my $rsa = shift;
  279. my $uid = shift;
  280. my $args = shift;
  281. $rsa->use_sha1_hash();
  282. # see page 22 of RFC 4880 for why i think this is the right padding
  283. # choice to use:
  284. $rsa->use_pkcs1_padding();
  285. if (! $rsa->check_key()) {
  286. die "key does not check";
  287. }
  288. my $version = pack('C', 4);
  289. # strong assertion of identity:
  290. my $sigtype = pack('C', $sig_types->{positive_certification});
  291. # RSA
  292. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  293. # SHA1
  294. my $hash_algo = pack('C', $digests->{sha1});
  295. # FIXME: i'm worried about generating a bazillion new OpenPGP
  296. # certificates from the same key, which could easily happen if you run
  297. # this script more than once against the same key (because the
  298. # timestamps will differ). How can we prevent this?
  299. # this environment variable (if set) overrides the current time, to
  300. # be able to create a standard key? If we read the key from a file
  301. # instead of stdin, should we use the creation time on the file?
  302. my $timestamp = 0;
  303. if (defined $args->{timestamp}) {
  304. $timestamp = ($args->{timestamp} + 0);
  305. } else {
  306. $timestamp = time();
  307. }
  308. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
  309. my $flags = 0;
  310. if (! defined $args->{usage_flags}) {
  311. $flags = $usage_flags->{certify};
  312. } else {
  313. my @ff = split(",", $args->{usage_flags});
  314. foreach my $f (@ff) {
  315. if (! defined $usage_flags->{$f}) {
  316. die "No such flag $f";
  317. }
  318. $flags |= $usage_flags->{$f};
  319. }
  320. }
  321. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  322. # how should we determine how far off to set the expiration date?
  323. # default is no expiration. Specify the timestamp in seconds from the
  324. # key creation.
  325. my $expiration_packet = '';
  326. if (defined $args->{expiration}) {
  327. my $expires_in = $args->{expiration} + 0;
  328. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  329. }
  330. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  331. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  332. $ciphers->{aes256},
  333. $ciphers->{aes192},
  334. $ciphers->{aes128},
  335. $ciphers->{cast5},
  336. $ciphers->{tripledes}
  337. );
  338. # prefer SHA-1, SHA-256, RIPE-MD/160
  339. my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
  340. $digests->{sha1},
  341. $digests->{sha256},
  342. $digests->{ripemd160}
  343. );
  344. # prefer ZLIB, BZip2, ZIP
  345. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  346. $zips->{zlib},
  347. $zips->{bzip2},
  348. $zips->{zip}
  349. );
  350. # we support the MDC feature:
  351. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  352. $features->{mdc});
  353. # keyserver preference: only owner modify (???):
  354. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  355. $keyserver_prefs->{nomodify});
  356. my $subpackets_to_be_hashed =
  357. $creation_time_packet.
  358. $usage_packet.
  359. $expiration_packet.
  360. $pref_sym_algos.
  361. $pref_hash_algos.
  362. $pref_zip_algos.
  363. $feature_subpacket.
  364. $keyserver_pref;
  365. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  366. my $sig_data_to_be_hashed =
  367. $version.
  368. $sigtype.
  369. $pubkey_algo.
  370. $hash_algo.
  371. $subpacket_octets.
  372. $subpackets_to_be_hashed;
  373. my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
  374. my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
  375. # this is for signing. it needs to be an old-style header with a
  376. # 2-packet octet count.
  377. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  378. # take the last 8 bytes of the fingerprint as the keyid:
  379. my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
  380. # the v4 signature trailer is:
  381. # version number, literal 0xff, and then a 4-byte count of the
  382. # signature data itself.
  383. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  384. my $uid_data =
  385. pack('CN', 0xb4, length($uid)).
  386. $uid;
  387. my $datatosign =
  388. $key_data.
  389. $uid_data.
  390. $sig_data_to_be_hashed.
  391. $trailer;
  392. my $data_hash = Digest::SHA1::sha1_hex($datatosign);
  393. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  394. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  395. my $sig_body =
  396. $sig_data_to_be_hashed.
  397. pack('n', length($issuer_packet)).
  398. $issuer_packet.
  399. pack('n', hex(substr($data_hash, 0, 4))).
  400. mpi_pack($sig);
  401. return
  402. make_packet($packet_types->{seckey}, $seckey).
  403. make_packet($packet_types->{uid}, $uid).
  404. make_packet($packet_types->{sig}, $sig_body);
  405. }
  406. sub openpgp2ssh {
  407. my $instr = shift;
  408. my $fpr = shift;
  409. my $packettag;
  410. read($instr, $packettag, 1);
  411. $packettag = ord($packettag);
  412. my $packetlen;
  413. if ( ! (0x80 & $packettag)) {
  414. print STDERR "This is not an OpenPGP packet";
  415. exit 1;
  416. }
  417. if (0x40 & $packettag) {
  418. print STDERR "This is a new-style packet header";
  419. $tag = (0x3f & $packettag);
  420. } else {
  421. print STDERR "This is an old-style packet header";
  422. $lentype = 0x03 & $packettag;
  423. $tag = (0x3c & $packettag ) >> 2;
  424. if ($lentype == 0) {
  425. read($instr, $packetlen, 1);
  426. $packetlen = unpack('%C', $packetlen);
  427. } elsif ($lentype == 1) {
  428. read($instr, $packetlen, 2);
  429. $packetlen = unpack('%S', $packetlen);
  430. } elsif ($lentype == 2) {
  431. read($instr, $packetlen, 4);
  432. $packetlen = unpack('%L', $packetlen);
  433. }
  434. }
  435. printf(STDERR, "Packet is %d long\n", $packetlen);
  436. print $packettag;
  437. }
  438. for (basename($0)) {
  439. if (/^pem2openpgp$/) {
  440. my $rsa;
  441. my $stdin;
  442. if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
  443. $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
  444. } else {
  445. $stdin = do {
  446. local $/; # slurp!
  447. <STDIN>;
  448. };
  449. $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
  450. }
  451. my $uid = shift;
  452. # FIXME: fail if there is no given user ID; or should we default to
  453. # hostname_long() from Sys::Hostname::Long ?
  454. print pem2openpgp($rsa,
  455. $uid,
  456. { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
  457. expiration => $ENV{PEM2OPENPGP_EXPIRATION},
  458. usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
  459. }
  460. );
  461. }
  462. elsif (/^openpgp2ssh$/) {
  463. my $fpr = shift;
  464. my $instream;
  465. open($instream,'-');
  466. binmode($instream, ":bytes");
  467. openpgp2ssh($instream, $fpr);
  468. }
  469. else {
  470. print STDERR "Unrecognized keytrans call.\n";
  471. die 1;
  472. }
  473. }