tor-gencert.c 16 KB

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