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