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