tor-gencert.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /* Copyright (c) 2007-2011, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "orconfig.h"
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <openssl/evp.h>
  11. #include <openssl/pem.h>
  12. #include <openssl/rsa.h>
  13. #include <openssl/objects.h>
  14. #include <openssl/obj_mac.h>
  15. #include <openssl/err.h>
  16. #include <errno.h>
  17. #if 0
  18. #include <stdlib.h>
  19. #include <stdarg.h>
  20. #include <assert.h>
  21. #endif
  22. #define CRYPTO_PRIVATE
  23. #include "compat.h"
  24. #include "../common/util.h"
  25. #include "../common/torlog.h"
  26. #include "crypto.h"
  27. #include "address.h"
  28. #define IDENTITY_KEY_BITS 3072
  29. #define SIGNING_KEY_BITS 1024
  30. #define DEFAULT_LIFETIME 12
  31. /* These globals are set via command line options. */
  32. char *identity_key_file = NULL;
  33. char *signing_key_file = NULL;
  34. char *certificate_file = NULL;
  35. int reuse_signing_key = 0;
  36. int verbose = 0;
  37. int make_new_id = 0;
  38. int months_lifetime = DEFAULT_LIFETIME;
  39. int passphrase_fd = -1;
  40. char *address = NULL;
  41. char *passphrase = NULL;
  42. size_t passphrase_len = 0;
  43. EVP_PKEY *identity_key = NULL;
  44. EVP_PKEY *signing_key = NULL;
  45. /** Write a usage message for tor-gencert to stderr. */
  46. static void
  47. show_help(void)
  48. {
  49. fprintf(stderr, "Syntax:\n"
  50. "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
  51. " [-i identity_key_file] [-s signing_key_file] "
  52. "[-c certificate_file]\n"
  53. " [-m lifetime_in_months] [-a address:port] "
  54. "[--passphrase-fd <fd>]\n");
  55. }
  56. /* XXXX copied from crypto.c */
  57. static void
  58. crypto_log_errors(int severity, const char *doing)
  59. {
  60. unsigned long err;
  61. const char *msg, *lib, *func;
  62. while ((err = ERR_get_error()) != 0) {
  63. msg = (const char*)ERR_reason_error_string(err);
  64. lib = (const char*)ERR_lib_error_string(err);
  65. func = (const char*)ERR_func_error_string(err);
  66. if (!msg) msg = "(null)";
  67. if (!lib) lib = "(null)";
  68. if (!func) func = "(null)";
  69. if (doing) {
  70. log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  71. doing, msg, lib, func);
  72. } else {
  73. log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
  74. }
  75. }
  76. }
  77. /** Read the passphrase from the passphrase fd. */
  78. static int
  79. load_passphrase(void)
  80. {
  81. char *cp;
  82. char buf[1024]; /* "Ought to be enough for anybody." */
  83. ssize_t n = read_all(passphrase_fd, buf, sizeof(buf), 0);
  84. if (n < 0) {
  85. log_err(LD_GENERAL, "Couldn't read from passphrase fd: %s",
  86. strerror(errno));
  87. return -1;
  88. }
  89. cp = memchr(buf, '\n', n);
  90. passphrase_len = cp-buf;
  91. passphrase = tor_strndup(buf, passphrase_len);
  92. memset(buf, 0, sizeof(buf));
  93. return 0;
  94. }
  95. static void
  96. clear_passphrase(void)
  97. {
  98. if (passphrase) {
  99. memset(passphrase, 0, passphrase_len);
  100. tor_free(passphrase);
  101. }
  102. }
  103. /** Read the command line options from <b>argc</b> and <b>argv</b>,
  104. * setting global option vars as needed.
  105. */
  106. static int
  107. parse_commandline(int argc, char **argv)
  108. {
  109. int i;
  110. log_severity_list_t s;
  111. for (i = 1; i < argc; ++i) {
  112. if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
  113. show_help();
  114. return 1;
  115. } else if (!strcmp(argv[i], "-i")) {
  116. if (i+1>=argc) {
  117. fprintf(stderr, "No argument to -i\n");
  118. return 1;
  119. }
  120. identity_key_file = tor_strdup(argv[++i]);
  121. } else if (!strcmp(argv[i], "-s")) {
  122. if (i+1>=argc) {
  123. fprintf(stderr, "No argument to -s\n");
  124. return 1;
  125. }
  126. signing_key_file = tor_strdup(argv[++i]);
  127. } else if (!strcmp(argv[i], "-c")) {
  128. if (i+1>=argc) {
  129. fprintf(stderr, "No argument to -c\n");
  130. return 1;
  131. }
  132. certificate_file = tor_strdup(argv[++i]);
  133. } else if (!strcmp(argv[i], "-m")) {
  134. if (i+1>=argc) {
  135. fprintf(stderr, "No argument to -m\n");
  136. return 1;
  137. }
  138. months_lifetime = atoi(argv[++i]);
  139. if (months_lifetime > 24 || months_lifetime < 0) {
  140. fprintf(stderr, "Lifetime (in months) was out of range.\n");
  141. return 1;
  142. }
  143. } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
  144. reuse_signing_key = 1;
  145. } else if (!strcmp(argv[i], "-v")) {
  146. verbose = 1;
  147. } else if (!strcmp(argv[i], "-a")) {
  148. uint32_t addr;
  149. uint16_t port;
  150. char b[INET_NTOA_BUF_LEN];
  151. struct in_addr in;
  152. if (i+1>=argc) {
  153. fprintf(stderr, "No argument to -a\n");
  154. return 1;
  155. }
  156. if (addr_port_lookup(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
  157. return 1;
  158. in.s_addr = htonl(addr);
  159. tor_inet_ntoa(&in, b, sizeof(b));
  160. address = tor_malloc(INET_NTOA_BUF_LEN+32);
  161. tor_snprintf(address, INET_NTOA_BUF_LEN+32, "%s:%d", b, (int)port);
  162. } else if (!strcmp(argv[i], "--create-identity-key")) {
  163. make_new_id = 1;
  164. } else if (!strcmp(argv[i], "--passphrase-fd")) {
  165. if (i+1>=argc) {
  166. fprintf(stderr, "No argument to --passphrase-fd\n");
  167. return 1;
  168. }
  169. passphrase_fd = atoi(argv[++i]);
  170. } else {
  171. fprintf(stderr, "Unrecognized option %s\n", argv[i]);
  172. return 1;
  173. }
  174. }
  175. memset(&s, 0, sizeof(s));
  176. if (verbose)
  177. set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
  178. else
  179. set_log_severity_config(LOG_WARN, LOG_ERR, &s);
  180. add_stream_log(&s, "<stderr>", fileno(stderr));
  181. if (!identity_key_file) {
  182. identity_key_file = tor_strdup("./authority_identity_key");
  183. log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
  184. identity_key_file);
  185. }
  186. if (!signing_key_file) {
  187. signing_key_file = tor_strdup("./authority_signing_key");
  188. log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
  189. signing_key_file);
  190. }
  191. if (!certificate_file) {
  192. certificate_file = tor_strdup("./authority_certificate");
  193. log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
  194. certificate_file);
  195. }
  196. if (passphrase_fd >= 0) {
  197. if (load_passphrase()<0)
  198. return 1;
  199. }
  200. return 0;
  201. }
  202. static RSA *
  203. generate_key(int bits)
  204. {
  205. RSA *rsa = NULL;
  206. crypto_pk_t *env = crypto_pk_new();
  207. if (crypto_pk_generate_key_with_bits(env,bits)<0)
  208. goto done;
  209. rsa = _crypto_pk_get_rsa(env);
  210. rsa = RSAPrivateKey_dup(rsa);
  211. done:
  212. crypto_pk_free(env);
  213. return rsa;
  214. }
  215. /** Try to read the identity key from <b>identity_key_file</b>. If no such
  216. * file exists and create_identity_key is set, make a new identity key and
  217. * store it. Return 0 on success, nonzero on failure.
  218. */
  219. static int
  220. load_identity_key(void)
  221. {
  222. file_status_t status = file_status(identity_key_file);
  223. FILE *f;
  224. if (make_new_id) {
  225. open_file_t *open_file = NULL;
  226. RSA *key;
  227. if (status != FN_NOENT) {
  228. log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
  229. "already exists.", identity_key_file);
  230. return 1;
  231. }
  232. log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
  233. IDENTITY_KEY_BITS);
  234. if (!(key = generate_key(IDENTITY_KEY_BITS))) {
  235. log_err(LD_GENERAL, "Couldn't generate identity key.");
  236. crypto_log_errors(LOG_ERR, "Generating identity key");
  237. return 1;
  238. }
  239. identity_key = EVP_PKEY_new();
  240. if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
  241. log_err(LD_GENERAL, "Couldn't assign identity key.");
  242. return 1;
  243. }
  244. if (!(f = start_writing_to_stdio_file(identity_key_file,
  245. OPEN_FLAGS_REPLACE | O_TEXT, 0400,
  246. &open_file)))
  247. return 1;
  248. /* Write the key to the file. If passphrase is not set, takes it from
  249. * the terminal. */
  250. if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
  251. NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  252. passphrase, (int)passphrase_len,
  253. NULL, NULL)) {
  254. log_err(LD_GENERAL, "Couldn't write identity key to %s",
  255. identity_key_file);
  256. crypto_log_errors(LOG_ERR, "Writing identity key");
  257. abort_writing_to_file(open_file);
  258. return 1;
  259. }
  260. finish_writing_to_file(open_file);
  261. } else {
  262. if (status != FN_FILE) {
  263. log_err(LD_GENERAL,
  264. "No identity key found in %s. To specify a location "
  265. "for an identity key, use -i. To generate a new identity key, "
  266. "use --create-identity-key.", identity_key_file);
  267. return 1;
  268. }
  269. if (!(f = fopen(identity_key_file, "r"))) {
  270. log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
  271. identity_key_file, strerror(errno));
  272. return 1;
  273. }
  274. /* Read the key. If passphrase is not set, takes it from the terminal. */
  275. identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
  276. if (!identity_key) {
  277. log_err(LD_GENERAL, "Couldn't read identity key from %s",
  278. identity_key_file);
  279. return 1;
  280. }
  281. fclose(f);
  282. }
  283. return 0;
  284. }
  285. /** Load a saved signing key from disk. Return 0 on success, nonzero on
  286. * failure. */
  287. static int
  288. load_signing_key(void)
  289. {
  290. FILE *f;
  291. if (!(f = fopen(signing_key_file, "r"))) {
  292. log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
  293. signing_key_file, strerror(errno));
  294. return 1;
  295. }
  296. if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
  297. log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
  298. return 1;
  299. }
  300. fclose(f);
  301. return 0;
  302. }
  303. /** Generate a new signing key and write it to disk. Return 0 on success,
  304. * nonzero on failure. */
  305. static int
  306. generate_signing_key(void)
  307. {
  308. open_file_t *open_file;
  309. FILE *f;
  310. RSA *key;
  311. log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
  312. SIGNING_KEY_BITS);
  313. if (!(key = generate_key(SIGNING_KEY_BITS))) {
  314. log_err(LD_GENERAL, "Couldn't generate signing key.");
  315. crypto_log_errors(LOG_ERR, "Generating signing key");
  316. return 1;
  317. }
  318. signing_key = EVP_PKEY_new();
  319. if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
  320. log_err(LD_GENERAL, "Couldn't assign signing key.");
  321. return 1;
  322. }
  323. if (!(f = start_writing_to_stdio_file(signing_key_file,
  324. OPEN_FLAGS_REPLACE | O_TEXT, 0600,
  325. &open_file)))
  326. return 1;
  327. /* Write signing key with no encryption. */
  328. if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
  329. crypto_log_errors(LOG_WARN, "writing signing key");
  330. abort_writing_to_file(open_file);
  331. return 1;
  332. }
  333. finish_writing_to_file(open_file);
  334. return 0;
  335. }
  336. /** Encode <b>key</b> in the format used in directory documents; return
  337. * a newly allocated string holding the result or NULL on failure. */
  338. static char *
  339. key_to_string(EVP_PKEY *key)
  340. {
  341. BUF_MEM *buf;
  342. BIO *b;
  343. RSA *rsa = EVP_PKEY_get1_RSA(key);
  344. char *result;
  345. if (!rsa)
  346. return NULL;
  347. b = BIO_new(BIO_s_mem());
  348. if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
  349. crypto_log_errors(LOG_WARN, "writing public key to string");
  350. return NULL;
  351. }
  352. BIO_get_mem_ptr(b, &buf);
  353. (void) BIO_set_close(b, BIO_NOCLOSE);
  354. BIO_free(b);
  355. result = tor_malloc(buf->length + 1);
  356. memcpy(result, buf->data, buf->length);
  357. result[buf->length] = 0;
  358. BUF_MEM_free(buf);
  359. return result;
  360. }
  361. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  362. static int
  363. get_fingerprint(EVP_PKEY *pkey, char *out)
  364. {
  365. int r = 1;
  366. crypto_pk_t *pk = _crypto_new_pk_from_rsa(EVP_PKEY_get1_RSA(pkey));
  367. if (pk) {
  368. r = crypto_pk_get_fingerprint(pk, out, 0);
  369. crypto_pk_free(pk);
  370. }
  371. return r;
  372. }
  373. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  374. static int
  375. get_digest(EVP_PKEY *pkey, char *out)
  376. {
  377. int r = 1;
  378. crypto_pk_t *pk = _crypto_new_pk_from_rsa(EVP_PKEY_get1_RSA(pkey));
  379. if (pk) {
  380. r = crypto_pk_get_digest(pk, out);
  381. crypto_pk_free(pk);
  382. }
  383. return r;
  384. }
  385. /** Generate a new certificate for our loaded or generated keys, and write it
  386. * to disk. Return 0 on success, nonzero on failure. */
  387. static int
  388. generate_certificate(void)
  389. {
  390. char buf[8192];
  391. time_t now = time(NULL);
  392. struct tm tm;
  393. char published[ISO_TIME_LEN+1];
  394. char expires[ISO_TIME_LEN+1];
  395. char id_digest[DIGEST_LEN];
  396. char fingerprint[FINGERPRINT_LEN+1];
  397. char *ident = key_to_string(identity_key);
  398. char *signing = key_to_string(signing_key);
  399. FILE *f;
  400. size_t signed_len;
  401. char digest[DIGEST_LEN];
  402. char signature[1024]; /* handles up to 8192-bit keys. */
  403. int r;
  404. get_fingerprint(identity_key, fingerprint);
  405. get_digest(identity_key, id_digest);
  406. tor_localtime_r(&now, &tm);
  407. tm.tm_mon += months_lifetime;
  408. format_iso_time(published, now);
  409. format_iso_time(expires, mktime(&tm));
  410. tor_snprintf(buf, sizeof(buf),
  411. "dir-key-certificate-version 3"
  412. "%s%s"
  413. "\nfingerprint %s\n"
  414. "dir-key-published %s\n"
  415. "dir-key-expires %s\n"
  416. "dir-identity-key\n%s"
  417. "dir-signing-key\n%s"
  418. "dir-key-crosscert\n"
  419. "-----BEGIN ID SIGNATURE-----\n",
  420. address?"\ndir-address ":"", address?address:"",
  421. fingerprint, published, expires, ident, signing
  422. );
  423. tor_free(ident);
  424. tor_free(signing);
  425. /* Append a cross-certification */
  426. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
  427. (unsigned char*)signature,
  428. EVP_PKEY_get1_RSA(signing_key),
  429. RSA_PKCS1_PADDING);
  430. signed_len = strlen(buf);
  431. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  432. strlcat(buf,
  433. "-----END ID SIGNATURE-----\n"
  434. "dir-key-certification\n", sizeof(buf));
  435. signed_len = strlen(buf);
  436. SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
  437. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
  438. (unsigned char*)signature,
  439. EVP_PKEY_get1_RSA(identity_key),
  440. RSA_PKCS1_PADDING);
  441. strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
  442. signed_len = strlen(buf);
  443. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  444. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  445. if (!(f = fopen(certificate_file, "w"))) {
  446. log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
  447. certificate_file, strerror(errno));
  448. return 1;
  449. }
  450. fputs(buf, f);
  451. fclose(f);
  452. return 0;
  453. }
  454. /** Entry point to tor-gencert */
  455. int
  456. main(int argc, char **argv)
  457. {
  458. int r = 1;
  459. init_logging();
  460. /* Don't bother using acceleration. */
  461. if (crypto_global_init(0, NULL, NULL)) {
  462. fprintf(stderr, "Couldn't initialize crypto library.\n");
  463. return 1;
  464. }
  465. if (crypto_seed_rng(1)) {
  466. fprintf(stderr, "Couldn't seed RNG.\n");
  467. goto done;
  468. }
  469. /* Make sure that files are made private. */
  470. umask(0077);
  471. if (parse_commandline(argc, argv))
  472. goto done;
  473. if (load_identity_key())
  474. goto done;
  475. if (reuse_signing_key) {
  476. if (load_signing_key())
  477. goto done;
  478. } else {
  479. if (generate_signing_key())
  480. goto done;
  481. }
  482. if (generate_certificate())
  483. goto done;
  484. r = 0;
  485. done:
  486. clear_passphrase();
  487. if (identity_key)
  488. EVP_PKEY_free(identity_key);
  489. if (signing_key)
  490. EVP_PKEY_free(signing_key);
  491. tor_free(address);
  492. crypto_global_cleanup();
  493. return r;
  494. }