summaryrefslogtreecommitdiff
path: root/src/keytrans/pem2openpgp
blob: 7abe52c16cbda092f2aa990ec4beda7d4427612a (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 $origdivisor = $b->copy();
  155. my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
  156. my $x = Crypt::OpenSSL::Bignum->zero();
  157. my $y = Crypt::OpenSSL::Bignum->one();
  158. my $lastx = Crypt::OpenSSL::Bignum->one();
  159. my $lasty = Crypt::OpenSSL::Bignum->zero();
  160. my $finalquotient;
  161. my $finalremainder;
  162. while (! $b->is_zero()) {
  163. my ($quotient, $remainder) = $a->div($b, $ctx);
  164. $a = $b;
  165. $b = $remainder;
  166. my $temp = $x;
  167. $x = $lastx->sub($quotient->mul($x, $ctx));
  168. $lastx = $temp;
  169. $temp = $y;
  170. $y = $lasty->sub($quotient->mul($y, $ctx));
  171. $lasty = $temp;
  172. }
  173. if (!$a->is_one()) {
  174. die "did this math wrong.\n";
  175. }
  176. # let's make sure that we return a positive value because RFC 4880,
  177. # section 3.2 only allows unsigned values:
  178. ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
  179. return $finalremainder;
  180. }
  181. ############ OpenPGP formatting functions ############
  182. # make an old-style packet out of the given packet type and body.
  183. # old-style (see RFC 4880 section 4.2)
  184. sub make_packet {
  185. my $type = shift;
  186. my $body = shift;
  187. my $len = length($body);
  188. my $lenbytes;
  189. my $lencode;
  190. if ($len < 2**8) {
  191. $lenbytes = 0;
  192. $lencode = 'C';
  193. } elsif ($len < 2**16) {
  194. $lenbytes = 1;
  195. $lencode = 'n';
  196. } elsif ($len < 2**31) {
  197. ## not testing against full 32 bits because i don't want to deal
  198. ## with potential overflow.
  199. $lenbytes = 2;
  200. $lencode = 'N';
  201. } else {
  202. ## what the hell do we do here?
  203. $lenbytes = 3;
  204. $lencode = '';
  205. }
  206. return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
  207. $body;
  208. }
  209. # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
  210. # (RFC 4880 section 3.2)
  211. sub mpi_pack {
  212. my $num = shift;
  213. my $val = $num->to_bin();
  214. my $mpilen = length($val)*8;
  215. # this is a kludgy way to get the number of significant bits in the
  216. # first byte:
  217. my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
  218. $mpilen -= (8 - $bitsinfirstbyte);
  219. return pack('n', $mpilen).$val;
  220. }
  221. # FIXME: genericize these to accept either RSA or DSA keys:
  222. sub make_rsa_pub_key_body {
  223. my $key = shift;
  224. my $timestamp = shift;
  225. my ($n, $e) = $key->get_key_parameters();
  226. return
  227. pack('CN', 4, $timestamp).
  228. pack('C', $asym_algos->{rsa}).
  229. mpi_pack($n).
  230. mpi_pack($e);
  231. }
  232. sub make_rsa_sec_key_body {
  233. my $key = shift;
  234. my $timestamp = shift;
  235. # we're not using $a and $b, but we need them to get to $c.
  236. my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
  237. my $c3 = modular_multi_inverse($p, $q);
  238. my $secret_material = mpi_pack($d).
  239. mpi_pack($p).
  240. mpi_pack($q).
  241. mpi_pack($c3);
  242. # according to Crypt::OpenSSL::RSA, the closest value we can get out
  243. # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
  244. # RFC 4880, we're actually looking for u, the multiplicative inverse
  245. # of p, mod q. This is why we're calculating the value directly
  246. # with modular_multi_inverse.
  247. return
  248. pack('CN', 4, $timestamp).
  249. pack('C', $asym_algos->{rsa}).
  250. mpi_pack($n).
  251. mpi_pack($e).
  252. pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
  253. $secret_material.
  254. pack('n', simple_checksum($secret_material));
  255. }
  256. # expects an RSA key (public or private) and a timestamp
  257. sub fingerprint {
  258. my $key = shift;
  259. my $timestamp = shift;
  260. my $rsabody = make_rsa_pub_key_body($key, $timestamp);
  261. return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
  262. }
  263. # we're just not dealing with newline business right now. slurp in
  264. # the whole file.
  265. undef $/;
  266. my $buf = <STDIN>;
  267. my $rsa = Crypt::OpenSSL::RSA->new_private_key($buf);
  268. $rsa->use_sha1_hash();
  269. # see page 22 of RFC 4880 for why i think this is the right padding
  270. # choice to use:
  271. $rsa->use_pkcs1_padding();
  272. if (! $rsa->check_key()) {
  273. die "key does not check";
  274. }
  275. my $version = pack('C', 4);
  276. # strong assertion of identity:
  277. my $sigtype = pack('C', $sig_types->{positive_certification});
  278. # RSA
  279. my $pubkey_algo = pack('C', $asym_algos->{rsa});
  280. # SHA1
  281. my $hash_algo = pack('C', $digests->{sha1});
  282. # FIXME: i'm worried about generating a bazillion new OpenPGP
  283. # certificates from the same key, which could easily happen if you run
  284. # this script more than once against the same key (because the
  285. # timestamps will differ). How can we prevent this?
  286. # this environment variable (if set) overrides the current time, to
  287. # be able to create a standard key? If we read the key from a file
  288. # instead of stdin, should we use the creation time on the file?
  289. my $timestamp = 0;
  290. if (defined $ENV{PEM2OPENPGP_TIMESTAMP}) {
  291. $timestamp = ($ENV{PEM2OPENPGP_TIMESTAMP} + 0);
  292. } else {
  293. $timestamp = time();
  294. }
  295. my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
  296. my $flags = 0;
  297. if (! defined $ENV{PEM2OPENPGP_USAGE_FLAGS}) {
  298. $flags = $usage_flags->{certify};
  299. } else {
  300. my @ff = split(",", $ENV{PEM2OPENPGP_USAGE_FLAGS});
  301. foreach my $f (@ff) {
  302. if (! defined $usage_flags->{$f}) {
  303. die "No such flag $f";
  304. }
  305. $flags |= $usage_flags->{$f};
  306. }
  307. }
  308. my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
  309. # how should we determine how far off to set the expiration date?
  310. # default is no expiration. Specify the timestamp in seconds from the
  311. # key creation.
  312. my $expiration_packet = '';
  313. if (defined $ENV{PEM2OPENPGP_EXPIRATION}) {
  314. my $expires_in = $ENV{PEM2OPENPGP_EXPIRATION} + 0;
  315. $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
  316. }
  317. # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
  318. my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
  319. $ciphers->{aes256},
  320. $ciphers->{aes192},
  321. $ciphers->{aes128},
  322. $ciphers->{cast5},
  323. $ciphers->{tripledes}
  324. );
  325. # prefer SHA-1, SHA-256, RIPE-MD/160
  326. my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
  327. $digests->{sha1},
  328. $digests->{sha256},
  329. $digests->{ripemd160}
  330. );
  331. # prefer ZLIB, BZip2, ZIP
  332. my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
  333. $zips->{zlib},
  334. $zips->{bzip2},
  335. $zips->{zip}
  336. );
  337. # we support the MDC feature:
  338. my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
  339. $features->{mdc});
  340. # keyserver preference: only owner modify (???):
  341. my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
  342. $keyserver_prefs->{nomodify});
  343. my $subpackets_to_be_hashed =
  344. $creation_time_packet.
  345. $usage_packet.
  346. $expiration_packet.
  347. $pref_sym_algos.
  348. $pref_hash_algos.
  349. $pref_zip_algos.
  350. $feature_subpacket.
  351. $keyserver_pref;
  352. my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
  353. my $sig_data_to_be_hashed =
  354. $version.
  355. $sigtype.
  356. $pubkey_algo.
  357. $hash_algo.
  358. $subpacket_octets.
  359. $subpackets_to_be_hashed;
  360. my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
  361. my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
  362. my $key_data = make_packet($packet_types->{pubkey}, $pubkey);
  363. # take the last 8 bytes of the fingerprint as the keyid:
  364. my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
  365. # the v4 signature trailer is:
  366. # version number, literal 0xff, and then a 4-byte count of the
  367. # signature data itself.
  368. my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
  369. my $uid_data =
  370. pack('CN', 0xb4, length($uid)).
  371. $uid;
  372. my $datatosign =
  373. $key_data.
  374. $uid_data.
  375. $sig_data_to_be_hashed.
  376. $trailer;
  377. my $data_hash = Digest::SHA1::sha1_hex($datatosign);
  378. my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
  379. my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
  380. my $sig_body =
  381. $sig_data_to_be_hashed.
  382. pack('n', length($issuer_packet)).
  383. $issuer_packet.
  384. pack('n', hex(substr($data_hash, 0, 4))).
  385. mpi_pack($sig);
  386. print
  387. make_packet($packet_types->{seckey}, $seckey).
  388. make_packet($packet_types->{uid}, $uid).
  389. make_packet($packet_types->{sig}, $sig_body);