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