tor-gencert.c 15 KB

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