tor-gencert.c 16 KB

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