summaryrefslogtreecommitdiff
path: root/src/keytrans/pem2openpgp
blob: c765002b2a1cec100b95476589e105e06d51dfd0 (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. # we're just not dealing with newline business right now. slurp in
  279. # the whole file.
  280. undef $/;
  281. my $buf = <STDIN>;
  282. my $rsa = Crypt::OpenSSL::RSA->new_private_key($buf);
  283. $rsa->use_sha1_hash();
  284. # see page 22 of RFC 4880 for why i think this is the right padding
  285. # choice to use:
  286. $rsa->use_pkcs1_padding();
  287. if (! $rsa->check_key()) {
  288. die "key does not check";
  289. }
  290. my $version = pack('C', 4);
  291. # strong assertion of identity:
  292. my $sigtype = pack('C', $sig_types->{positive_certification});
  293. # RSA
  294. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  295. # SHA1
  296. my $hash_algo = pack('C', $digests->{sha1});
  297. # FIXME: i'm worried about generating a bazillion new OpenPGP
  298. # certificates from the same key, which could easily happen if you run
  299. # this script more than once against the same key (because the
  300. # timestamps will differ). How can we prevent this?
  301. # this environment variable (if set) overrides the current time, to
  302. # be able to create a standard key? If we read the key from a file
  303. # instead of stdin, should we use the creation time on the file?
  304. my $timestamp = 0;
  305. if (defined $ENV{PEM2OPENPGP_TIMESTAMP}) {
  306. $timestamp = ($ENV{PEM2OPENPGP_TIMESTAMP} + 0);
  307. } else {
  308. $timestamp = time();
  309. }
  310. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
  311. my $flags = 0;
  312. if (! defined $ENV{PEM2OPENPGP_USAGE_FLAGS}) {
  313. $flags = $usage_flags->{certify};
  314. } else {
  315. my @ff = split(",", $ENV{PEM2OPENPGP_USAGE_FLAGS});
  316. foreach my $f (@ff) {
  317. if (! defined $usage_flags->{$f}) {
  318. die "No such flag $f";
  319. }
  320. $flags |= $usage_flags->{$f};
  321. }
  322. }
  323. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  324. # how should we determine how far off to set the expiration date?
  325. # default is no expiration. Specify the timestamp in seconds from the
  326. # key creation.
  327. my $expiration_packet = '';
  328. if (defined $ENV{PEM2OPENPGP_EXPIRATION}) {
  329. my $expires_in = $ENV{PEM2OPENPGP_EXPIRATION} + 0;
  330. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  331. }
  332. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  333. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  334. $ciphers->{aes256},
  335. $ciphers->{aes192},
  336. $ciphers->{aes128},
  337. $ciphers->{cast5},
  338. $ciphers->{tripledes}
  339. );
  340. # prefer SHA-1, SHA-256, RIPE-MD/160
  341. my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
  342. $digests->{sha1},
  343. $digests->{sha256},
  344. $digests->{ripemd160}
  345. );
  346. # prefer ZLIB, BZip2, ZIP
  347. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  348. $zips->{zlib},
  349. $zips->{bzip2},
  350. $zips->{zip}
  351. );
  352. # we support the MDC feature:
  353. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  354. $features->{mdc});
  355. # keyserver preference: only owner modify (???):
  356. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  357. $keyserver_prefs->{nomodify});
  358. my $subpackets_to_be_hashed =
  359. $creation_time_packet.
  360. $usage_packet.
  361. $expiration_packet.
  362. $pref_sym_algos.
  363. $pref_hash_algos.
  364. $pref_zip_algos.
  365. $feature_subpacket.
  366. $keyserver_pref;
  367. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  368. my $sig_data_to_be_hashed =
  369. $version.
  370. $sigtype.
  371. $pubkey_algo.
  372. $hash_algo.
  373. $subpacket_octets.
  374. $subpackets_to_be_hashed;
  375. my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
  376. my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
  377. # this is for signing. it needs to be an old-style header with a
  378. # 2-packet octet count.
  379. my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
  380. # take the last 8 bytes of the fingerprint as the keyid:
  381. my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
  382. # the v4 signature trailer is:
  383. # version number, literal 0xff, and then a 4-byte count of the
  384. # signature data itself.
  385. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  386. my $uid_data =
  387. pack('CN', 0xb4, length($uid)).
  388. $uid;
  389. my $datatosign =
  390. $key_data.
  391. $uid_data.
  392. $sig_data_to_be_hashed.
  393. $trailer;
  394. my $data_hash = Digest::SHA1::sha1_hex($datatosign);
  395. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  396. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  397. my $sig_body =
  398. $sig_data_to_be_hashed.
  399. pack('n', length($issuer_packet)).
  400. $issuer_packet.
  401. pack('n', hex(substr($data_hash, 0, 4))).
  402. mpi_pack($sig);
  403. print
  404. make_packet($packet_types->{seckey}, $seckey).
  405. make_packet($packet_types->{uid}, $uid).
  406. make_packet($packet_types->{sig}, $sig_body);