tor-gencert.c 17 KB

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