tor-gencert.c 16 KB

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