tor-gencert.c 16 KB

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