tor-gencert.c 16 KB

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