tor-gencert.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* Copyright (c) 2007-2012, 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. #define CRYPTO_PRIVATE
  25. #include "compat.h"
  26. #include "../common/util.h"
  27. #include "../common/torlog.h"
  28. #include "crypto.h"
  29. #include "address.h"
  30. #define IDENTITY_KEY_BITS 3072
  31. #define SIGNING_KEY_BITS 1024
  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. log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  73. doing, msg, lib, func);
  74. } else {
  75. log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", 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. memset(buf, 0, sizeof(buf));
  95. return 0;
  96. }
  97. static void
  98. clear_passphrase(void)
  99. {
  100. if (passphrase) {
  101. memset(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. memset(&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. return 1;
  282. }
  283. fclose(f);
  284. }
  285. return 0;
  286. }
  287. /** Load a saved signing key from disk. Return 0 on success, nonzero on
  288. * failure. */
  289. static int
  290. load_signing_key(void)
  291. {
  292. FILE *f;
  293. if (!(f = fopen(signing_key_file, "r"))) {
  294. log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
  295. signing_key_file, strerror(errno));
  296. return 1;
  297. }
  298. if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
  299. log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
  300. return 1;
  301. }
  302. fclose(f);
  303. return 0;
  304. }
  305. /** Generate a new signing key and write it to disk. Return 0 on success,
  306. * nonzero on failure. */
  307. static int
  308. generate_signing_key(void)
  309. {
  310. open_file_t *open_file;
  311. FILE *f;
  312. RSA *key;
  313. log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
  314. SIGNING_KEY_BITS);
  315. if (!(key = generate_key(SIGNING_KEY_BITS))) {
  316. log_err(LD_GENERAL, "Couldn't generate signing key.");
  317. crypto_log_errors(LOG_ERR, "Generating signing key");
  318. return 1;
  319. }
  320. signing_key = EVP_PKEY_new();
  321. if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
  322. log_err(LD_GENERAL, "Couldn't assign signing key.");
  323. return 1;
  324. }
  325. if (!(f = start_writing_to_stdio_file(signing_key_file,
  326. OPEN_FLAGS_REPLACE | O_TEXT, 0600,
  327. &open_file)))
  328. return 1;
  329. /* Write signing key with no encryption. */
  330. if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
  331. crypto_log_errors(LOG_WARN, "writing signing key");
  332. abort_writing_to_file(open_file);
  333. return 1;
  334. }
  335. finish_writing_to_file(open_file);
  336. return 0;
  337. }
  338. /** Encode <b>key</b> in the format used in directory documents; return
  339. * a newly allocated string holding the result or NULL on failure. */
  340. static char *
  341. key_to_string(EVP_PKEY *key)
  342. {
  343. BUF_MEM *buf;
  344. BIO *b;
  345. RSA *rsa = EVP_PKEY_get1_RSA(key);
  346. char *result;
  347. if (!rsa)
  348. return NULL;
  349. b = BIO_new(BIO_s_mem());
  350. if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
  351. crypto_log_errors(LOG_WARN, "writing public key to string");
  352. return NULL;
  353. }
  354. BIO_get_mem_ptr(b, &buf);
  355. (void) BIO_set_close(b, BIO_NOCLOSE);
  356. BIO_free(b);
  357. result = tor_malloc(buf->length + 1);
  358. memcpy(result, buf->data, buf->length);
  359. result[buf->length] = 0;
  360. BUF_MEM_free(buf);
  361. return result;
  362. }
  363. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  364. static int
  365. get_fingerprint(EVP_PKEY *pkey, char *out)
  366. {
  367. int r = 1;
  368. crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
  369. if (pk) {
  370. r = crypto_pk_get_fingerprint(pk, out, 0);
  371. crypto_pk_free(pk);
  372. }
  373. return r;
  374. }
  375. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  376. static int
  377. get_digest(EVP_PKEY *pkey, char *out)
  378. {
  379. int r = 1;
  380. crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
  381. if (pk) {
  382. r = crypto_pk_get_digest(pk, out);
  383. crypto_pk_free(pk);
  384. }
  385. return r;
  386. }
  387. /** Generate a new certificate for our loaded or generated keys, and write it
  388. * to disk. Return 0 on success, nonzero on failure. */
  389. static int
  390. generate_certificate(void)
  391. {
  392. char buf[8192];
  393. time_t now = time(NULL);
  394. struct tm tm;
  395. char published[ISO_TIME_LEN+1];
  396. char expires[ISO_TIME_LEN+1];
  397. char id_digest[DIGEST_LEN];
  398. char fingerprint[FINGERPRINT_LEN+1];
  399. char *ident = key_to_string(identity_key);
  400. char *signing = key_to_string(signing_key);
  401. FILE *f;
  402. size_t signed_len;
  403. char digest[DIGEST_LEN];
  404. char signature[1024]; /* handles up to 8192-bit keys. */
  405. int r;
  406. get_fingerprint(identity_key, fingerprint);
  407. get_digest(identity_key, id_digest);
  408. tor_localtime_r(&now, &tm);
  409. tm.tm_mon += months_lifetime;
  410. format_iso_time(published, now);
  411. format_iso_time(expires, mktime(&tm));
  412. tor_snprintf(buf, sizeof(buf),
  413. "dir-key-certificate-version 3"
  414. "%s%s"
  415. "\nfingerprint %s\n"
  416. "dir-key-published %s\n"
  417. "dir-key-expires %s\n"
  418. "dir-identity-key\n%s"
  419. "dir-signing-key\n%s"
  420. "dir-key-crosscert\n"
  421. "-----BEGIN ID SIGNATURE-----\n",
  422. address?"\ndir-address ":"", address?address:"",
  423. fingerprint, published, expires, ident, signing
  424. );
  425. tor_free(ident);
  426. tor_free(signing);
  427. /* Append a cross-certification */
  428. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
  429. (unsigned char*)signature,
  430. EVP_PKEY_get1_RSA(signing_key),
  431. RSA_PKCS1_PADDING);
  432. signed_len = strlen(buf);
  433. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  434. strlcat(buf,
  435. "-----END ID SIGNATURE-----\n"
  436. "dir-key-certification\n", sizeof(buf));
  437. signed_len = strlen(buf);
  438. SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
  439. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
  440. (unsigned char*)signature,
  441. EVP_PKEY_get1_RSA(identity_key),
  442. RSA_PKCS1_PADDING);
  443. strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
  444. signed_len = strlen(buf);
  445. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  446. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  447. if (!(f = fopen(certificate_file, "w"))) {
  448. log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
  449. certificate_file, strerror(errno));
  450. return 1;
  451. }
  452. if (fputs(buf, f) < 0) {
  453. log_err(LD_GENERAL, "Couldn't write to %s: %s",
  454. certificate_file, strerror(errno));
  455. fclose(f);
  456. return 1;
  457. }
  458. fclose(f);
  459. return 0;
  460. }
  461. /** Entry point to tor-gencert */
  462. int
  463. main(int argc, char **argv)
  464. {
  465. int r = 1;
  466. init_logging();
  467. /* Don't bother using acceleration. */
  468. if (crypto_global_init(0, NULL, NULL)) {
  469. fprintf(stderr, "Couldn't initialize crypto library.\n");
  470. return 1;
  471. }
  472. if (crypto_seed_rng(1)) {
  473. fprintf(stderr, "Couldn't seed RNG.\n");
  474. goto done;
  475. }
  476. /* Make sure that files are made private. */
  477. umask(0077);
  478. if (parse_commandline(argc, argv))
  479. goto done;
  480. if (load_identity_key())
  481. goto done;
  482. if (reuse_signing_key) {
  483. if (load_signing_key())
  484. goto done;
  485. } else {
  486. if (generate_signing_key())
  487. goto done;
  488. }
  489. if (generate_certificate())
  490. goto done;
  491. r = 0;
  492. done:
  493. clear_passphrase();
  494. if (identity_key)
  495. EVP_PKEY_free(identity_key);
  496. if (signing_key)
  497. EVP_PKEY_free(signing_key);
  498. tor_free(address);
  499. crypto_global_cleanup();
  500. return r;
  501. }