tor-gencert.c 16 KB

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