tor-gencert.c 13 KB

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