tor-gencert.c 16 KB

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