tor-gencert.c 16 KB

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