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