tor-gencert.c 16 KB

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