router.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] = "$Id$";
  7. #include "or.h"
  8. /**
  9. * \file router.c
  10. * \brief OR functionality, including key maintenance, generating
  11. * and uploading server descriptors, retrying OR connections.
  12. **/
  13. extern long stats_n_seconds_working;
  14. /** Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  15. /************************************************************/
  16. /*****
  17. * Key management: ORs only.
  18. *****/
  19. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  20. */
  21. static tor_mutex_t *key_lock=NULL;
  22. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  23. static crypto_pk_env_t *onionkey=NULL;
  24. static crypto_pk_env_t *lastonionkey=NULL;
  25. static crypto_pk_env_t *identitykey=NULL;
  26. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  27. * to update onionkey correctly, call rotate_onion_key().
  28. */
  29. void set_onion_key(crypto_pk_env_t *k) {
  30. tor_mutex_acquire(key_lock);
  31. onionkey = k;
  32. onionkey_set_at = time(NULL);
  33. tor_mutex_release(key_lock);
  34. mark_my_descriptor_dirty();
  35. }
  36. /** Return the current onion key. Requires that the onion key has been
  37. * loaded or generated. */
  38. crypto_pk_env_t *get_onion_key(void) {
  39. tor_assert(onionkey);
  40. return onionkey;
  41. }
  42. /** Return the onion key that was current before the most recent onion
  43. * key rotation. If no rotation has been performed since this process
  44. * started, return NULL.
  45. */
  46. crypto_pk_env_t *get_previous_onion_key(void) {
  47. return lastonionkey;
  48. }
  49. void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  50. {
  51. tor_assert(key);
  52. tor_assert(last);
  53. tor_mutex_acquire(key_lock);
  54. *key = crypto_pk_dup_key(onionkey);
  55. if (lastonionkey)
  56. *last = crypto_pk_dup_key(lastonionkey);
  57. else
  58. *last = NULL;
  59. tor_mutex_release(key_lock);
  60. }
  61. /** Return the time when the onion key was last set. This is either the time
  62. * when the process launched, or the time of the most recent key rotation since
  63. * the process launched.
  64. */
  65. time_t get_onion_key_set_at(void) {
  66. return onionkey_set_at;
  67. }
  68. /** Set the current identity key to k.
  69. */
  70. void set_identity_key(crypto_pk_env_t *k) {
  71. identitykey = k;
  72. }
  73. /** Returns the current identity key; requires that the identity key has been
  74. * set.
  75. */
  76. crypto_pk_env_t *get_identity_key(void) {
  77. tor_assert(identitykey);
  78. return identitykey;
  79. }
  80. /** Return true iff the identity key has been set. */
  81. int identity_key_is_set(void) {
  82. return identitykey != NULL;
  83. }
  84. /** Replace the previous onion key with the current onion key, and generate
  85. * a new previous onion key. Immediately after calling this function,
  86. * the OR should:
  87. * - schedule all previous cpuworkers to shut down _after_ processing
  88. * pending work. (This will cause fresh cpuworkers to be generated.)
  89. * - generate and upload a fresh routerinfo.
  90. */
  91. void rotate_onion_key(void)
  92. {
  93. char fname[512];
  94. char fname_prev[512];
  95. crypto_pk_env_t *prkey;
  96. tor_snprintf(fname,sizeof(fname),
  97. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  98. tor_snprintf(fname_prev,sizeof(fname_prev),
  99. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  100. if (!(prkey = crypto_new_pk_env())) {
  101. log(LOG_ERR, "Error creating crypto environment.");
  102. goto error;
  103. }
  104. if (crypto_pk_generate_key(prkey)) {
  105. log(LOG_ERR, "Error generating onion key");
  106. goto error;
  107. }
  108. if (file_status(fname) == FN_FILE) {
  109. if (replace_file(fname, fname_prev))
  110. goto error;
  111. }
  112. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  113. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  114. goto error;
  115. }
  116. log_fn(LOG_INFO, "Rotating onion key");
  117. tor_mutex_acquire(key_lock);
  118. if (lastonionkey)
  119. crypto_free_pk_env(lastonionkey);
  120. lastonionkey = onionkey;
  121. onionkey = prkey;
  122. onionkey_set_at = time(NULL);
  123. tor_mutex_release(key_lock);
  124. mark_my_descriptor_dirty();
  125. return;
  126. error:
  127. log_fn(LOG_WARN, "Couldn't rotate onion key.");
  128. }
  129. /* Read an RSA secret key key from a file that was once named fname_old,
  130. * but is now named fname_new. Rename the file from old to new as needed.
  131. */
  132. static crypto_pk_env_t *
  133. init_key_from_file_name_changed(const char *fname_old,
  134. const char *fname_new)
  135. {
  136. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  137. /* The new filename is there, or both are, or neither is. */
  138. return init_key_from_file(fname_new);
  139. /* The old filename exists, and the new one doesn't. Rename and load. */
  140. if (rename(fname_old, fname_new) < 0) {
  141. log_fn(LOG_ERR, "Couldn't rename %s to %s: %s", fname_old, fname_new,
  142. strerror(errno));
  143. return NULL;
  144. }
  145. return init_key_from_file(fname_new);
  146. }
  147. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  148. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  149. * key, or NULL on error.
  150. */
  151. crypto_pk_env_t *init_key_from_file(const char *fname)
  152. {
  153. crypto_pk_env_t *prkey = NULL;
  154. FILE *file = NULL;
  155. if (!(prkey = crypto_new_pk_env())) {
  156. log(LOG_ERR, "Error creating crypto environment.");
  157. goto error;
  158. }
  159. switch (file_status(fname)) {
  160. case FN_DIR:
  161. case FN_ERROR:
  162. log(LOG_ERR, "Can't read key from %s", fname);
  163. goto error;
  164. case FN_NOENT:
  165. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  166. if (crypto_pk_generate_key(prkey)) {
  167. log(LOG_ERR, "Error generating onion key");
  168. goto error;
  169. }
  170. if (crypto_pk_check_key(prkey) <= 0) {
  171. log(LOG_ERR, "Generated key seems invalid");
  172. goto error;
  173. }
  174. log(LOG_INFO, "Generated key seems valid");
  175. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  176. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  177. goto error;
  178. }
  179. return prkey;
  180. case FN_FILE:
  181. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  182. log(LOG_ERR, "Error loading private key.");
  183. goto error;
  184. }
  185. return prkey;
  186. default:
  187. tor_assert(0);
  188. }
  189. error:
  190. if (prkey)
  191. crypto_free_pk_env(prkey);
  192. if (file)
  193. fclose(file);
  194. return NULL;
  195. }
  196. /** Initialize all OR private keys, and the TLS context, as necessary.
  197. * On OPs, this only initializes the tls context.
  198. */
  199. int init_keys(void) {
  200. /* XXX009 Two problems with how this is called:
  201. * 1. It should be idempotent for servers, so we can call init_keys
  202. * as much as we need to.
  203. * 2. Clients should rotate their identity keys at least whenever
  204. * their IPs change.
  205. */
  206. char keydir[512];
  207. char keydir2[512];
  208. char fingerprint[FINGERPRINT_LEN+1];
  209. char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
  210. char *cp;
  211. const char *tmp, *mydesc, *datadir;
  212. crypto_pk_env_t *prkey;
  213. char digest[20];
  214. or_options_t *options = get_options();
  215. if (!key_lock)
  216. key_lock = tor_mutex_new();
  217. /* OP's don't need persistent keys; just make up an identity and
  218. * initialize the TLS context. */
  219. if (!server_mode(options)) {
  220. if (!(prkey = crypto_new_pk_env()))
  221. return -1;
  222. if (crypto_pk_generate_key(prkey))
  223. return -1;
  224. set_identity_key(prkey);
  225. /* Create a TLS context; default the client nickname to "client". */
  226. if (tor_tls_context_new(get_identity_key(), 1,
  227. options->Nickname ? options->Nickname : "client",
  228. MAX_SSL_KEY_LIFETIME) < 0) {
  229. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  230. return -1;
  231. }
  232. return 0;
  233. }
  234. /* Make sure DataDirectory exists, and is private. */
  235. datadir = options->DataDirectory;
  236. if (check_private_dir(datadir, CPD_CREATE)) {
  237. return -1;
  238. }
  239. /* Check the key directory. */
  240. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  241. if (check_private_dir(keydir, CPD_CREATE)) {
  242. return -1;
  243. }
  244. cp = keydir + strlen(keydir); /* End of string. */
  245. /* 1. Read identity key. Make it if none is found. */
  246. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  247. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  248. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir2);
  249. prkey = init_key_from_file_name_changed(keydir,keydir2);
  250. if (!prkey) return -1;
  251. set_identity_key(prkey);
  252. /* 2. Read onion key. Make it if none is found. */
  253. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  254. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  255. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir2);
  256. prkey = init_key_from_file_name_changed(keydir,keydir2);
  257. if (!prkey) return -1;
  258. set_onion_key(prkey);
  259. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  260. if (file_status(keydir) == FN_FILE) {
  261. prkey = init_key_from_file(keydir);
  262. if (prkey)
  263. lastonionkey = prkey;
  264. }
  265. /* 3. Initialize link key and TLS context. */
  266. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  267. MAX_SSL_KEY_LIFETIME) < 0) {
  268. log_fn(LOG_ERR, "Error initializing TLS context");
  269. return -1;
  270. }
  271. /* 4. Dump router descriptor to 'router.desc' */
  272. /* Must be called after keys are initialized. */
  273. tmp = mydesc = router_get_my_descriptor();
  274. if (!mydesc) {
  275. log_fn(LOG_ERR, "Error initializing descriptor.");
  276. return -1;
  277. }
  278. if (authdir_mode(options)) {
  279. const char *m;
  280. /* We need to add our own fingerprint so it gets recognized. */
  281. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  282. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  283. return -1;
  284. }
  285. if (dirserv_add_descriptor(&tmp, &m) != 1) {
  286. log(LOG_ERR, "Unable to add own descriptor to directory: %s",
  287. m?m:"<unknown error>");
  288. return -1;
  289. }
  290. }
  291. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  292. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  293. if (write_str_to_file(keydir, mydesc,0)) {
  294. return -1;
  295. }
  296. /* 5. Dump fingerprint to 'fingerprint' */
  297. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  298. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  299. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  300. log_fn(LOG_ERR, "Error computing fingerprint");
  301. return -1;
  302. }
  303. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  304. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  305. "%s %s\n",options->Nickname, fingerprint) < 0) {
  306. log_fn(LOG_ERR, "Error writing fingerprint line");
  307. return -1;
  308. }
  309. if (write_str_to_file(keydir, fingerprint_line, 0))
  310. return -1;
  311. if (!authdir_mode(options))
  312. return 0;
  313. /* 6. [authdirserver only] load approved-routers file */
  314. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  315. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  316. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  317. log_fn(LOG_ERR, "Error loading fingerprints");
  318. return -1;
  319. }
  320. /* 6b. [authdirserver only] add own key to approved directories. */
  321. crypto_pk_get_digest(get_identity_key(), digest);
  322. if (!router_digest_is_trusted_dir(digest)) {
  323. add_trusted_dir_server(options->Address, (uint16_t)options->DirPort, digest);
  324. }
  325. /* 7. [authdirserver only] load old directory, if it's there */
  326. tor_snprintf(keydir,sizeof(keydir),"%s/cached-directory", datadir);
  327. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  328. cp = read_file_to_str(keydir,0);
  329. if (!cp) {
  330. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  331. } else {
  332. if (dirserv_load_from_directory_string(cp) < 0) {
  333. log_fn(LOG_WARN, "Cached directory %s is corrupt, only loaded part of it.", keydir);
  334. tor_free(cp);
  335. return 0;
  336. }
  337. tor_free(cp);
  338. }
  339. /* success */
  340. return 0;
  341. }
  342. /* Keep track of whether we should upload our server descriptor,
  343. * and what type of server we are.
  344. */
  345. /** Whether we can reach our ORPort from the outside. */
  346. static int can_reach_or_port = 0;
  347. /** Whether we can reach our DirPort from the outside. */
  348. static int can_reach_dir_port = 0;
  349. void consider_testing_reachability(void) {
  350. routerinfo_t *me = router_get_my_routerinfo();
  351. if (!can_reach_or_port) {
  352. circuit_launch_by_identity(CIRCUIT_PURPOSE_TESTING, me->identity_digest, 0, 0, 1);
  353. }
  354. if (!can_reach_dir_port && me->dir_port) {
  355. if (me) {
  356. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_DIR, 1, NULL, NULL, 0);
  357. } else {
  358. log_fn(LOG_NOTICE,"Delaying checking DirPort reachability; can't build descriptor.");
  359. }
  360. }
  361. }
  362. /** Annotate that we found our ORPort reachable. */
  363. void router_orport_found_reachable(void) {
  364. can_reach_or_port = 1;
  365. }
  366. /** Annotate that we found our DirPort reachable. */
  367. void router_dirport_found_reachable(void) {
  368. can_reach_dir_port = 1;
  369. }
  370. /** Our router has just moved to a new IP. Reset stats. */
  371. void server_has_changed_ip(void) {
  372. stats_n_seconds_working = 0;
  373. can_reach_or_port = 0;
  374. can_reach_dir_port = 0;
  375. mark_my_descriptor_dirty();
  376. }
  377. /** Return true iff we believe ourselves to be an authoritative
  378. * directory server.
  379. */
  380. int authdir_mode(or_options_t *options) {
  381. return options->AuthoritativeDir != 0;
  382. }
  383. /** Return true iff we try to stay connected to all ORs at once.
  384. */
  385. int clique_mode(or_options_t *options) {
  386. return authdir_mode(options);
  387. }
  388. /** Return true iff we are trying to be a server.
  389. */
  390. int server_mode(or_options_t *options) {
  391. return (options->ORPort != 0 || options->ORBindAddress);
  392. }
  393. /** Remember if we've advertised ourselves to the dirservers. */
  394. static int server_is_advertised=0;
  395. /** Return true iff we have published our descriptor lately.
  396. */
  397. int advertised_server_mode(void) {
  398. return server_is_advertised;
  399. }
  400. static void set_server_advertised(int s) {
  401. server_is_advertised = s;
  402. }
  403. /** Return true iff we are trying to be a socks proxy. */
  404. int proxy_mode(or_options_t *options) {
  405. return (options->SocksPort != 0 || options->SocksBindAddress);
  406. }
  407. /** Decide if we're a publishable server or just a client. We are a server if:
  408. * - We have the AuthoritativeDirectory option set.
  409. * or
  410. * - We don't have the ClientOnly option set; and
  411. * - We have ORPort set; and
  412. * - We believe we are reachable from the outside.
  413. */
  414. static int decide_if_publishable_server(time_t now) {
  415. or_options_t *options = get_options();
  416. if (options->ClientOnly)
  417. return 0;
  418. if (!server_mode(options))
  419. return 0;
  420. if (options->AuthoritativeDir)
  421. return 1;
  422. if (!can_reach_or_port)
  423. return 0;
  424. if (options->DirPort && !can_reach_dir_port)
  425. return 0;
  426. return 1;
  427. }
  428. void consider_publishable_server(time_t now, int force) {
  429. if (decide_if_publishable_server(now)) {
  430. set_server_advertised(1);
  431. router_rebuild_descriptor(force);
  432. router_upload_dir_desc_to_dirservers(force);
  433. } else {
  434. set_server_advertised(0);
  435. }
  436. }
  437. /*
  438. * Clique maintenance
  439. */
  440. /** OR only: if in clique mode, try to open connections to all of the
  441. * other ORs we know about. Otherwise, open connections to those we
  442. * think are in clique mode.
  443. */
  444. void router_retry_connections(void) {
  445. int i;
  446. routerinfo_t *router;
  447. routerlist_t *rl;
  448. or_options_t *options = get_options();
  449. tor_assert(server_mode(options));
  450. router_get_routerlist(&rl);
  451. if (!rl) return;
  452. for (i=0;i < smartlist_len(rl->routers);i++) {
  453. router = smartlist_get(rl->routers, i);
  454. if (router_is_me(router))
  455. continue;
  456. if (!clique_mode(options) && !router_is_clique_mode(router))
  457. continue;
  458. if (!connection_get_by_identity_digest(router->identity_digest,
  459. CONN_TYPE_OR)) {
  460. /* not in the list */
  461. log_fn(LOG_DEBUG,"connecting to OR at %s:%u.",router->address,router->or_port);
  462. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  463. }
  464. }
  465. }
  466. int router_is_clique_mode(routerinfo_t *router) {
  467. if (router_digest_is_trusted_dir(router->identity_digest))
  468. return 1;
  469. return 0;
  470. }
  471. /*
  472. * OR descriptor generation.
  473. */
  474. /** My routerinfo. */
  475. static routerinfo_t *desc_routerinfo = NULL;
  476. /** Boolean: do we need to regenerate the above? */
  477. static int desc_is_dirty = 1;
  478. /** Boolean: do we need to regenerate the above? */
  479. static int desc_needs_upload = 0;
  480. /** OR only: try to upload our signed descriptor to all the directory servers
  481. * we know about. DOCDOC force
  482. */
  483. void router_upload_dir_desc_to_dirservers(int force) {
  484. const char *s;
  485. s = router_get_my_descriptor();
  486. if (!s) {
  487. log_fn(LOG_WARN, "No descriptor; skipping upload");
  488. return;
  489. }
  490. if (!force || !desc_needs_upload)
  491. return;
  492. desc_needs_upload = 0;
  493. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  494. }
  495. #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,accept *:20-22,accept *:53,accept *:79-81,accept *:110,accept *:143,accept *:389,accept *:443,accept *:636,accept *:706,accept *:873,accept *:993,accept *:995,reject *:1214,reject *:4661-4666,reject *:6346-6347,reject *:6419,reject *:6881-6889,accept *:1024-65535,reject *:*"
  496. /** Set the exit policy on <b>router</b> to match the exit policy in the
  497. * current configuration file. If the exit policy doesn't have a catch-all
  498. * rule, then append the default exit policy as well.
  499. */
  500. static void router_add_exit_policy_from_config(routerinfo_t *router) {
  501. addr_policy_t *ep;
  502. struct config_line_t default_policy;
  503. config_parse_addr_policy(get_options()->ExitPolicy, &router->exit_policy);
  504. for (ep = router->exit_policy; ep; ep = ep->next) {
  505. if (ep->msk == 0 && ep->prt_min <= 1 && ep->prt_max >= 65535) {
  506. /* if exitpolicy includes a *:* line, then we're done. */
  507. return;
  508. }
  509. }
  510. /* Else, append the default exitpolicy. */
  511. default_policy.key = NULL;
  512. default_policy.value = (char*)DEFAULT_EXIT_POLICY;
  513. default_policy.next = NULL;
  514. config_parse_addr_policy(&default_policy, &router->exit_policy);
  515. }
  516. /** OR only: Return false if my exit policy says to allow connection to
  517. * conn. Else return true.
  518. */
  519. int router_compare_to_my_exit_policy(connection_t *conn)
  520. {
  521. tor_assert(desc_routerinfo);
  522. /* make sure it's resolved to something. this way we can't get a
  523. 'maybe' below. */
  524. if (!conn->addr)
  525. return -1;
  526. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  527. desc_routerinfo->exit_policy);
  528. }
  529. /** Return true iff <b>router</b> has the same nickname as this OR. (For an
  530. * OP, always returns false.)
  531. */
  532. int router_is_me(routerinfo_t *router)
  533. {
  534. routerinfo_t *me = router_get_my_routerinfo();
  535. tor_assert(router);
  536. if (!me || memcmp(me->identity_digest, router->identity_digest, DIGEST_LEN))
  537. return 0;
  538. return 1;
  539. }
  540. /** Return a routerinfo for this OR, rebuilding a fresh one if
  541. * necessary. Return NULL on error, or if called on an OP. */
  542. routerinfo_t *router_get_my_routerinfo(void)
  543. {
  544. if (!server_mode(get_options()))
  545. return NULL;
  546. if (!desc_routerinfo) {
  547. if (router_rebuild_descriptor(1))
  548. return NULL;
  549. }
  550. return desc_routerinfo;
  551. }
  552. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  553. * one if necessary. Return NULL on error.
  554. */
  555. const char *router_get_my_descriptor(void) {
  556. if (!desc_routerinfo) {
  557. if (router_rebuild_descriptor(1))
  558. return NULL;
  559. }
  560. log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
  561. return desc_routerinfo->signed_descriptor;
  562. }
  563. /** Rebuild a fresh routerinfo and signed server descriptor for this
  564. * OR. Return 0 on success, -1 on error. DOCDOC force
  565. */
  566. int router_rebuild_descriptor(int force) {
  567. routerinfo_t *ri;
  568. uint32_t addr;
  569. char platform[256];
  570. struct in_addr in;
  571. int hibernating = we_are_hibernating();
  572. or_options_t *options = get_options();
  573. char addrbuf[INET_NTOA_BUF_LEN];
  574. if (!desc_is_dirty && !force)
  575. return 0;
  576. if (resolve_my_address(options->Address, &addr) < 0) {
  577. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  578. return -1;
  579. }
  580. ri = tor_malloc_zero(sizeof(routerinfo_t));
  581. in.s_addr = htonl(addr);
  582. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  583. ri->address = tor_strdup(addrbuf);
  584. ri->nickname = tor_strdup(options->Nickname);
  585. ri->addr = addr;
  586. ri->or_port = options->ORPort;
  587. ri->dir_port = hibernating ? 0 : options->DirPort;
  588. ri->published_on = time(NULL);
  589. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  590. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  591. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  592. routerinfo_free(ri);
  593. return -1;
  594. }
  595. get_platform_str(platform, sizeof(platform));
  596. ri->platform = tor_strdup(platform);
  597. ri->bandwidthrate = (int)options->BandwidthRate;
  598. ri->bandwidthburst = (int)options->BandwidthBurst;
  599. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  600. router_add_exit_policy_from_config(ri);
  601. if (desc_routerinfo) /* inherit values */
  602. ri->is_verified = desc_routerinfo->is_verified;
  603. if (options->MyFamily) {
  604. ri->declared_family = smartlist_create();
  605. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  606. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  607. }
  608. ri->signed_descriptor = tor_malloc(8192);
  609. if (router_dump_router_to_string(ri->signed_descriptor, 8192,
  610. ri, get_identity_key())<0) {
  611. log_fn(LOG_WARN, "Couldn't dump router to string.");
  612. return -1;
  613. }
  614. if (desc_routerinfo)
  615. routerinfo_free(desc_routerinfo);
  616. desc_routerinfo = ri;
  617. desc_is_dirty = 0;
  618. desc_needs_upload = 1;
  619. return 0;
  620. }
  621. /** DOCDOC */
  622. void
  623. mark_my_descriptor_dirty(void)
  624. {
  625. desc_is_dirty = 1;
  626. }
  627. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  628. * string describing the version of Tor and the operating system we're
  629. * currently running on.
  630. */
  631. void get_platform_str(char *platform, size_t len)
  632. {
  633. tor_snprintf(platform, len, "Tor %s on %s",
  634. VERSION, get_uname());
  635. return;
  636. }
  637. /* XXX need to audit this thing and count fenceposts. maybe
  638. * refactor so we don't have to keep asking if we're
  639. * near the end of maxlen?
  640. */
  641. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  642. /** OR only: Given a routerinfo for this router, and an identity key to sign
  643. * with, encode the routerinfo as a signed server descriptor and write the
  644. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  645. * failure, and the number of bytes used on success.
  646. */
  647. int router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  648. crypto_pk_env_t *ident_key) {
  649. char *onion_pkey; /* Onion key, PEM-encoded. */
  650. char *identity_pkey; /* Identity key, PEM-encoded. */
  651. char digest[20];
  652. char signature[128];
  653. char published[32];
  654. char fingerprint[FINGERPRINT_LEN+1];
  655. struct in_addr in;
  656. char addrbuf[INET_NTOA_BUF_LEN];
  657. size_t onion_pkeylen, identity_pkeylen;
  658. size_t written;
  659. int result=0;
  660. addr_policy_t *tmpe;
  661. char *bandwidth_usage;
  662. char *family_line;
  663. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  664. char *s_tmp, *s_dup;
  665. const char *cp;
  666. routerinfo_t *ri_tmp;
  667. #endif
  668. /* Make sure the identity key matches the one in the routerinfo. */
  669. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  670. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  671. return -1;
  672. }
  673. /* record our fingerprint, so we can include it in the descriptor */
  674. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  675. log_fn(LOG_ERR, "Error computing fingerprint");
  676. return -1;
  677. }
  678. /* PEM-encode the onion key */
  679. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  680. &onion_pkey,&onion_pkeylen)<0) {
  681. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  682. return -1;
  683. }
  684. /* PEM-encode the identity key key */
  685. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  686. &identity_pkey,&identity_pkeylen)<0) {
  687. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  688. tor_free(onion_pkey);
  689. return -1;
  690. }
  691. /* Encode the publication time. */
  692. format_iso_time(published, router->published_on);
  693. /* How busy have we been? */
  694. bandwidth_usage = rep_hist_get_bandwidth_lines();
  695. if (router->declared_family && smartlist_len(router->declared_family)) {
  696. size_t n;
  697. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  698. n += strlen("opt family ") + 2; /* 1 for \n, 1 for \0. */
  699. family_line = tor_malloc(n);
  700. tor_snprintf(family_line, n, "opt family %s\n", s);
  701. tor_free(s);
  702. } else {
  703. family_line = tor_strdup("");
  704. }
  705. /* Generate the easy portion of the router descriptor. */
  706. result = tor_snprintf(s, maxlen,
  707. "router %s %s %d 0 %d\n"
  708. "platform %s\n"
  709. "published %s\n"
  710. "opt fingerprint %s\n"
  711. "opt uptime %ld\n"
  712. "bandwidth %d %d %d\n"
  713. "onion-key\n%s"
  714. "signing-key\n%s%s%s",
  715. router->nickname,
  716. router->address,
  717. router->or_port,
  718. router->dir_port,
  719. router->platform,
  720. published,
  721. fingerprint,
  722. stats_n_seconds_working,
  723. (int) router->bandwidthrate,
  724. (int) router->bandwidthburst,
  725. (int) router->bandwidthcapacity,
  726. onion_pkey, identity_pkey,
  727. family_line, bandwidth_usage);
  728. tor_free(family_line);
  729. tor_free(onion_pkey);
  730. tor_free(identity_pkey);
  731. tor_free(bandwidth_usage);
  732. if (result < 0)
  733. return -1;
  734. /* From now on, we use 'written' to remember the current length of 's'. */
  735. written = result;
  736. if (get_options()->ContactInfo && strlen(get_options()->ContactInfo)) {
  737. result = tor_snprintf(s+written,maxlen-written, "opt contact %s\n",
  738. get_options()->ContactInfo);
  739. if (result<0)
  740. return -1;
  741. written += result;
  742. }
  743. /* Write the exit policy to the end of 's'. */
  744. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  745. in.s_addr = htonl(tmpe->addr);
  746. /* Write: "accept 1.2.3.4" */
  747. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  748. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  749. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  750. tmpe->msk == 0 ? "*" : addrbuf);
  751. if (result < 0)
  752. return -1;
  753. written += result;
  754. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  755. /* Write "/255.255.0.0" */
  756. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  757. in.s_addr = htonl(tmpe->msk);
  758. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  759. if (result<0)
  760. return -1;
  761. written += result;
  762. }
  763. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  764. /* There is no port set; write ":*" */
  765. if (written+4 > maxlen)
  766. return -1;
  767. strlcat(s+written, ":*\n", maxlen-written);
  768. written += 3;
  769. } else if (tmpe->prt_min == tmpe->prt_max) {
  770. /* There is only one port; write ":80". */
  771. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  772. if (result<0)
  773. return -1;
  774. written += result;
  775. } else {
  776. /* There is a range of ports; write ":79-80". */
  777. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  778. tmpe->prt_max);
  779. if (result<0)
  780. return -1;
  781. written += result;
  782. }
  783. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  784. /* This was a catch-all rule, so future rules are irrelevant. */
  785. break;
  786. } /* end for */
  787. if (written+256 > maxlen) /* Not enough room for signature. */
  788. return -1;
  789. /* Sign the directory */
  790. strlcat(s+written, "router-signature\n", maxlen-written);
  791. written += strlen(s+written);
  792. s[written] = '\0';
  793. if (router_get_router_hash(s, digest) < 0)
  794. return -1;
  795. if (crypto_pk_private_sign(ident_key, signature, digest, 20) < 0) {
  796. log_fn(LOG_WARN, "Error signing digest");
  797. return -1;
  798. }
  799. strlcat(s+written, "-----BEGIN SIGNATURE-----\n", maxlen-written);
  800. written += strlen(s+written);
  801. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  802. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  803. return -1;
  804. }
  805. written += strlen(s+written);
  806. strlcat(s+written, "-----END SIGNATURE-----\n", maxlen-written);
  807. written += strlen(s+written);
  808. if (written+2 > maxlen)
  809. return -1;
  810. /* include a last '\n' */
  811. s[written] = '\n';
  812. s[written+1] = 0;
  813. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  814. cp = s_tmp = s_dup = tor_strdup(s);
  815. ri_tmp = router_parse_entry_from_string(cp, NULL);
  816. if (!ri_tmp) {
  817. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  818. s);
  819. return -1;
  820. }
  821. tor_free(s_dup);
  822. routerinfo_free(ri_tmp);
  823. #endif
  824. return written+1;
  825. }
  826. int is_legal_nickname(const char *s)
  827. {
  828. size_t len;
  829. tor_assert(s);
  830. len = strlen(s);
  831. return len > 0 && len <= MAX_NICKNAME_LEN &&
  832. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  833. }
  834. int is_legal_nickname_or_hexdigest(const char *s)
  835. {
  836. size_t len;
  837. tor_assert(s);
  838. if (*s!='$')
  839. return is_legal_nickname(s);
  840. len = strlen(s);
  841. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  842. }
  843. void router_free_all_keys(void)
  844. {
  845. if (onionkey)
  846. crypto_free_pk_env(onionkey);
  847. if (lastonionkey)
  848. crypto_free_pk_env(lastonionkey);
  849. if (identitykey)
  850. crypto_free_pk_env(identitykey);
  851. if (key_lock)
  852. tor_mutex_free(key_lock);
  853. if (desc_routerinfo)
  854. routerinfo_free(desc_routerinfo);
  855. }