tor-gencert.c 15 KB

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