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