tor-gencert.c 16 KB

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