tor-gencert.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. #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. 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. identity_key_file = tor_strdup(argv[++i]);
  124. } else if (!strcmp(argv[i], "-s")) {
  125. if (i+1>=argc) {
  126. fprintf(stderr, "No argument to -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. certificate_file = tor_strdup(argv[++i]);
  136. } else if (!strcmp(argv[i], "-m")) {
  137. if (i+1>=argc) {
  138. fprintf(stderr, "No argument to -m\n");
  139. return 1;
  140. }
  141. months_lifetime = atoi(argv[++i]);
  142. if (months_lifetime > 24 || months_lifetime < 0) {
  143. fprintf(stderr, "Lifetime (in months) was out of range.\n");
  144. return 1;
  145. }
  146. } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
  147. reuse_signing_key = 1;
  148. } else if (!strcmp(argv[i], "-v")) {
  149. verbose = 1;
  150. } else if (!strcmp(argv[i], "-a")) {
  151. uint32_t addr;
  152. uint16_t port;
  153. char b[INET_NTOA_BUF_LEN];
  154. struct in_addr in;
  155. if (i+1>=argc) {
  156. fprintf(stderr, "No argument to -a\n");
  157. return 1;
  158. }
  159. if (addr_port_lookup(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
  160. return 1;
  161. in.s_addr = htonl(addr);
  162. tor_inet_ntoa(&in, b, sizeof(b));
  163. address = tor_malloc(INET_NTOA_BUF_LEN+32);
  164. tor_snprintf(address, INET_NTOA_BUF_LEN+32, "%s:%d", b, (int)port);
  165. } else if (!strcmp(argv[i], "--create-identity-key")) {
  166. make_new_id = 1;
  167. } else if (!strcmp(argv[i], "--passphrase-fd")) {
  168. if (i+1>=argc) {
  169. fprintf(stderr, "No argument to --passphrase-fd\n");
  170. return 1;
  171. }
  172. passphrase_fd = atoi(argv[++i]);
  173. } else {
  174. fprintf(stderr, "Unrecognized option %s\n", argv[i]);
  175. return 1;
  176. }
  177. }
  178. memwipe(&s, 0, sizeof(s));
  179. if (verbose)
  180. set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
  181. else
  182. set_log_severity_config(LOG_WARN, LOG_ERR, &s);
  183. add_stream_log(&s, "<stderr>", fileno(stderr));
  184. if (!identity_key_file) {
  185. identity_key_file = tor_strdup("./authority_identity_key");
  186. log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
  187. identity_key_file);
  188. }
  189. if (!signing_key_file) {
  190. signing_key_file = tor_strdup("./authority_signing_key");
  191. log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
  192. signing_key_file);
  193. }
  194. if (!certificate_file) {
  195. certificate_file = tor_strdup("./authority_certificate");
  196. log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
  197. certificate_file);
  198. }
  199. if (passphrase_fd >= 0) {
  200. if (load_passphrase()<0)
  201. return 1;
  202. }
  203. return 0;
  204. }
  205. static RSA *
  206. generate_key(int bits)
  207. {
  208. RSA *rsa = NULL;
  209. crypto_pk_t *env = crypto_pk_new();
  210. if (crypto_pk_generate_key_with_bits(env,bits)<0)
  211. goto done;
  212. rsa = crypto_pk_get_rsa_(env);
  213. rsa = RSAPrivateKey_dup(rsa);
  214. done:
  215. crypto_pk_free(env);
  216. return rsa;
  217. }
  218. /** Try to read the identity key from <b>identity_key_file</b>. If no such
  219. * file exists and create_identity_key is set, make a new identity key and
  220. * store it. Return 0 on success, nonzero on failure.
  221. */
  222. static int
  223. load_identity_key(void)
  224. {
  225. file_status_t status = file_status(identity_key_file);
  226. FILE *f;
  227. if (make_new_id) {
  228. open_file_t *open_file = NULL;
  229. RSA *key;
  230. if (status != FN_NOENT) {
  231. log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
  232. "already exists.", identity_key_file);
  233. return 1;
  234. }
  235. log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
  236. IDENTITY_KEY_BITS);
  237. if (!(key = generate_key(IDENTITY_KEY_BITS))) {
  238. log_err(LD_GENERAL, "Couldn't generate identity key.");
  239. crypto_log_errors(LOG_ERR, "Generating identity key");
  240. return 1;
  241. }
  242. identity_key = EVP_PKEY_new();
  243. if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
  244. log_err(LD_GENERAL, "Couldn't assign identity key.");
  245. return 1;
  246. }
  247. if (!(f = start_writing_to_stdio_file(identity_key_file,
  248. OPEN_FLAGS_REPLACE | O_TEXT, 0400,
  249. &open_file)))
  250. return 1;
  251. /* Write the key to the file. If passphrase is not set, takes it from
  252. * the terminal. */
  253. if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
  254. NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  255. passphrase, (int)passphrase_len,
  256. NULL, NULL)) {
  257. log_err(LD_GENERAL, "Couldn't write identity key to %s",
  258. identity_key_file);
  259. crypto_log_errors(LOG_ERR, "Writing identity key");
  260. abort_writing_to_file(open_file);
  261. return 1;
  262. }
  263. finish_writing_to_file(open_file);
  264. } else {
  265. if (status != FN_FILE) {
  266. log_err(LD_GENERAL,
  267. "No identity key found in %s. To specify a location "
  268. "for an identity key, use -i. To generate a new identity key, "
  269. "use --create-identity-key.", identity_key_file);
  270. return 1;
  271. }
  272. if (!(f = fopen(identity_key_file, "r"))) {
  273. log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
  274. identity_key_file, strerror(errno));
  275. return 1;
  276. }
  277. /* Read the key. If passphrase is not set, takes it from the terminal. */
  278. identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
  279. if (!identity_key) {
  280. log_err(LD_GENERAL, "Couldn't read identity key from %s",
  281. identity_key_file);
  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. return 1;
  302. }
  303. fclose(f);
  304. return 0;
  305. }
  306. /** Generate a new signing key and write it to disk. Return 0 on success,
  307. * nonzero on failure. */
  308. static int
  309. generate_signing_key(void)
  310. {
  311. open_file_t *open_file;
  312. FILE *f;
  313. RSA *key;
  314. log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
  315. SIGNING_KEY_BITS);
  316. if (!(key = generate_key(SIGNING_KEY_BITS))) {
  317. log_err(LD_GENERAL, "Couldn't generate signing key.");
  318. crypto_log_errors(LOG_ERR, "Generating signing key");
  319. return 1;
  320. }
  321. signing_key = EVP_PKEY_new();
  322. if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
  323. log_err(LD_GENERAL, "Couldn't assign signing key.");
  324. return 1;
  325. }
  326. if (!(f = start_writing_to_stdio_file(signing_key_file,
  327. OPEN_FLAGS_REPLACE | O_TEXT, 0600,
  328. &open_file)))
  329. return 1;
  330. /* Write signing key with no encryption. */
  331. if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
  332. crypto_log_errors(LOG_WARN, "writing signing key");
  333. abort_writing_to_file(open_file);
  334. return 1;
  335. }
  336. finish_writing_to_file(open_file);
  337. return 0;
  338. }
  339. /** Encode <b>key</b> in the format used in directory documents; return
  340. * a newly allocated string holding the result or NULL on failure. */
  341. static char *
  342. key_to_string(EVP_PKEY *key)
  343. {
  344. BUF_MEM *buf;
  345. BIO *b;
  346. RSA *rsa = EVP_PKEY_get1_RSA(key);
  347. char *result;
  348. if (!rsa)
  349. return NULL;
  350. b = BIO_new(BIO_s_mem());
  351. if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
  352. crypto_log_errors(LOG_WARN, "writing public key to string");
  353. return NULL;
  354. }
  355. BIO_get_mem_ptr(b, &buf);
  356. (void) BIO_set_close(b, BIO_NOCLOSE);
  357. BIO_free(b);
  358. result = tor_malloc(buf->length + 1);
  359. memcpy(result, buf->data, buf->length);
  360. result[buf->length] = 0;
  361. BUF_MEM_free(buf);
  362. return result;
  363. }
  364. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  365. static int
  366. get_fingerprint(EVP_PKEY *pkey, char *out)
  367. {
  368. int r = 1;
  369. crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
  370. if (pk) {
  371. r = crypto_pk_get_fingerprint(pk, out, 0);
  372. crypto_pk_free(pk);
  373. }
  374. return r;
  375. }
  376. /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
  377. static int
  378. get_digest(EVP_PKEY *pkey, char *out)
  379. {
  380. int r = 1;
  381. crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
  382. if (pk) {
  383. r = crypto_pk_get_digest(pk, out);
  384. crypto_pk_free(pk);
  385. }
  386. return r;
  387. }
  388. /** Generate a new certificate for our loaded or generated keys, and write it
  389. * to disk. Return 0 on success, nonzero on failure. */
  390. static int
  391. generate_certificate(void)
  392. {
  393. char buf[8192];
  394. time_t now = time(NULL);
  395. struct tm tm;
  396. char published[ISO_TIME_LEN+1];
  397. char expires[ISO_TIME_LEN+1];
  398. char id_digest[DIGEST_LEN];
  399. char fingerprint[FINGERPRINT_LEN+1];
  400. char *ident = key_to_string(identity_key);
  401. char *signing = key_to_string(signing_key);
  402. FILE *f;
  403. size_t signed_len;
  404. char digest[DIGEST_LEN];
  405. char signature[1024]; /* handles up to 8192-bit keys. */
  406. int r;
  407. get_fingerprint(identity_key, fingerprint);
  408. get_digest(identity_key, id_digest);
  409. tor_localtime_r(&now, &tm);
  410. tm.tm_mon += months_lifetime;
  411. format_iso_time(published, now);
  412. format_iso_time(expires, mktime(&tm));
  413. tor_snprintf(buf, sizeof(buf),
  414. "dir-key-certificate-version 3"
  415. "%s%s"
  416. "\nfingerprint %s\n"
  417. "dir-key-published %s\n"
  418. "dir-key-expires %s\n"
  419. "dir-identity-key\n%s"
  420. "dir-signing-key\n%s"
  421. "dir-key-crosscert\n"
  422. "-----BEGIN ID SIGNATURE-----\n",
  423. address?"\ndir-address ":"", address?address:"",
  424. fingerprint, published, expires, ident, signing
  425. );
  426. tor_free(ident);
  427. tor_free(signing);
  428. /* Append a cross-certification */
  429. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
  430. (unsigned char*)signature,
  431. EVP_PKEY_get1_RSA(signing_key),
  432. RSA_PKCS1_PADDING);
  433. signed_len = strlen(buf);
  434. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  435. strlcat(buf,
  436. "-----END ID SIGNATURE-----\n"
  437. "dir-key-certification\n", sizeof(buf));
  438. signed_len = strlen(buf);
  439. SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
  440. r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
  441. (unsigned char*)signature,
  442. EVP_PKEY_get1_RSA(identity_key),
  443. RSA_PKCS1_PADDING);
  444. strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
  445. signed_len = strlen(buf);
  446. base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
  447. strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
  448. if (!(f = fopen(certificate_file, "w"))) {
  449. log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
  450. certificate_file, strerror(errno));
  451. return 1;
  452. }
  453. if (fputs(buf, f) < 0) {
  454. log_err(LD_GENERAL, "Couldn't write to %s: %s",
  455. certificate_file, strerror(errno));
  456. fclose(f);
  457. return 1;
  458. }
  459. fclose(f);
  460. return 0;
  461. }
  462. /** Entry point to tor-gencert */
  463. int
  464. main(int argc, char **argv)
  465. {
  466. int r = 1;
  467. init_logging();
  468. /* Don't bother using acceleration. */
  469. if (crypto_global_init(0, NULL, NULL)) {
  470. fprintf(stderr, "Couldn't initialize crypto library.\n");
  471. return 1;
  472. }
  473. if (crypto_seed_rng(1)) {
  474. fprintf(stderr, "Couldn't seed RNG.\n");
  475. goto done;
  476. }
  477. /* Make sure that files are made private. */
  478. umask(0077);
  479. if (parse_commandline(argc, argv))
  480. goto done;
  481. if (load_identity_key())
  482. goto done;
  483. if (reuse_signing_key) {
  484. if (load_signing_key())
  485. goto done;
  486. } else {
  487. if (generate_signing_key())
  488. goto done;
  489. }
  490. if (generate_certificate())
  491. goto done;
  492. r = 0;
  493. done:
  494. clear_passphrase();
  495. if (identity_key)
  496. EVP_PKEY_free(identity_key);
  497. if (signing_key)
  498. EVP_PKEY_free(signing_key);
  499. tor_free(address);
  500. crypto_global_cleanup();
  501. return r;
  502. }