router.c 31 KB

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