tor-gencert.c 16 KB

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