router.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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[] =
  7. "$Id$";
  8. #include "or.h"
  9. /**
  10. * \file router.c
  11. * \brief OR functionality, including key maintenance, generating
  12. * and uploading server descriptors, retrying OR connections.
  13. **/
  14. extern long stats_n_seconds_working;
  15. /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  16. /************************************************************/
  17. /*****
  18. * Key management: ORs only.
  19. *****/
  20. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  21. */
  22. static tor_mutex_t *key_lock=NULL;
  23. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  24. static crypto_pk_env_t *onionkey=NULL;
  25. static crypto_pk_env_t *lastonionkey=NULL;
  26. static crypto_pk_env_t *identitykey=NULL;
  27. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  28. * to update onionkey correctly, call rotate_onion_key().
  29. */
  30. void
  31. set_onion_key(crypto_pk_env_t *k)
  32. {
  33. tor_mutex_acquire(key_lock);
  34. onionkey = k;
  35. onionkey_set_at = time(NULL);
  36. tor_mutex_release(key_lock);
  37. mark_my_descriptor_dirty();
  38. }
  39. /** Return the current onion key. Requires that the onion key has been
  40. * loaded or generated. */
  41. crypto_pk_env_t *
  42. get_onion_key(void)
  43. {
  44. tor_assert(onionkey);
  45. return onionkey;
  46. }
  47. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  48. * of the most recent onion key into *<b>last</b>.
  49. */
  50. void
  51. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  52. {
  53. tor_assert(key);
  54. tor_assert(last);
  55. tor_mutex_acquire(key_lock);
  56. *key = crypto_pk_dup_key(onionkey);
  57. if (lastonionkey)
  58. *last = crypto_pk_dup_key(lastonionkey);
  59. else
  60. *last = NULL;
  61. tor_mutex_release(key_lock);
  62. }
  63. /** Return the time when the onion key was last set. This is either the time
  64. * when the process launched, or the time of the most recent key rotation since
  65. * the process launched.
  66. */
  67. time_t
  68. get_onion_key_set_at(void)
  69. {
  70. return onionkey_set_at;
  71. }
  72. /** Set the current identity key to k.
  73. */
  74. void
  75. set_identity_key(crypto_pk_env_t *k)
  76. {
  77. if (identitykey)
  78. crypto_free_pk_env(identitykey);
  79. identitykey = k;
  80. }
  81. /** Returns the current identity key; requires that the identity key has been
  82. * set.
  83. */
  84. crypto_pk_env_t *
  85. get_identity_key(void)
  86. {
  87. tor_assert(identitykey);
  88. return identitykey;
  89. }
  90. /** Return true iff the identity key has been set. */
  91. int
  92. identity_key_is_set(void)
  93. {
  94. return identitykey != NULL;
  95. }
  96. /** Replace the previous onion key with the current onion key, and generate
  97. * a new previous onion key. Immediately after calling this function,
  98. * the OR should:
  99. * - schedule all previous cpuworkers to shut down _after_ processing
  100. * pending work. (This will cause fresh cpuworkers to be generated.)
  101. * - generate and upload a fresh routerinfo.
  102. */
  103. void
  104. rotate_onion_key(void)
  105. {
  106. char fname[512];
  107. char fname_prev[512];
  108. crypto_pk_env_t *prkey;
  109. tor_snprintf(fname,sizeof(fname),
  110. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  111. tor_snprintf(fname_prev,sizeof(fname_prev),
  112. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  113. if (!(prkey = crypto_new_pk_env())) {
  114. err(LD_GENERAL,"Error creating crypto environment.");
  115. goto error;
  116. }
  117. if (crypto_pk_generate_key(prkey)) {
  118. err(LD_BUG,"Error generating onion key");
  119. goto error;
  120. }
  121. if (file_status(fname) == FN_FILE) {
  122. if (replace_file(fname, fname_prev))
  123. goto error;
  124. }
  125. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  126. err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  127. goto error;
  128. }
  129. info(LD_GENERAL, "Rotating onion key");
  130. tor_mutex_acquire(key_lock);
  131. if (lastonionkey)
  132. crypto_free_pk_env(lastonionkey);
  133. lastonionkey = onionkey;
  134. onionkey = prkey;
  135. onionkey_set_at = time(NULL);
  136. tor_mutex_release(key_lock);
  137. mark_my_descriptor_dirty();
  138. return;
  139. error:
  140. warn(LD_GENERAL, "Couldn't rotate onion key.");
  141. }
  142. /* Read an RSA secret key key from a file that was once named fname_old,
  143. * but is now named fname_new. Rename the file from old to new as needed.
  144. */
  145. static crypto_pk_env_t *
  146. init_key_from_file_name_changed(const char *fname_old,
  147. const char *fname_new)
  148. {
  149. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  150. /* The new filename is there, or both are, or neither is. */
  151. return init_key_from_file(fname_new);
  152. /* The old filename exists, and the new one doesn't. Rename and load. */
  153. if (rename(fname_old, fname_new) < 0) {
  154. log_fn(LOG_ERR, LD_FS, "Couldn't rename \"%s\" to \"%s\": %s",
  155. fname_old, fname_new, strerror(errno));
  156. return NULL;
  157. }
  158. return init_key_from_file(fname_new);
  159. }
  160. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  161. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  162. * key, or NULL on error.
  163. */
  164. crypto_pk_env_t *
  165. init_key_from_file(const char *fname)
  166. {
  167. crypto_pk_env_t *prkey = NULL;
  168. FILE *file = NULL;
  169. if (!(prkey = crypto_new_pk_env())) {
  170. err(LD_GENERAL,"Error creating crypto environment.");
  171. goto error;
  172. }
  173. switch (file_status(fname)) {
  174. case FN_DIR:
  175. case FN_ERROR:
  176. err(LD_FS,"Can't read key from \"%s\"", fname);
  177. goto error;
  178. case FN_NOENT:
  179. info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.", fname);
  180. if (crypto_pk_generate_key(prkey)) {
  181. err(LD_GENERAL,"Error generating onion key");
  182. goto error;
  183. }
  184. if (crypto_pk_check_key(prkey) <= 0) {
  185. err(LD_GENERAL,"Generated key seems invalid");
  186. goto error;
  187. }
  188. info(LD_GENERAL, "Generated key seems valid");
  189. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  190. err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  191. goto error;
  192. }
  193. return prkey;
  194. case FN_FILE:
  195. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  196. err(LD_GENERAL,"Error loading private key.");
  197. goto error;
  198. }
  199. return prkey;
  200. default:
  201. tor_assert(0);
  202. }
  203. error:
  204. if (prkey)
  205. crypto_free_pk_env(prkey);
  206. if (file)
  207. fclose(file);
  208. return NULL;
  209. }
  210. /** Initialize all OR private keys, and the TLS context, as necessary.
  211. * On OPs, this only initializes the tls context.
  212. */
  213. int
  214. init_keys(void)
  215. {
  216. /* XXX009 Two problems with how this is called:
  217. * 1. It should be idempotent for servers, so we can call init_keys
  218. * as much as we need to.
  219. */
  220. char keydir[512];
  221. char keydir2[512];
  222. char fingerprint[FINGERPRINT_LEN+1];
  223. /*nickname fp\n\0 */
  224. char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  225. char *cp;
  226. const char *mydesc, *datadir;
  227. crypto_pk_env_t *prkey;
  228. char digest[20];
  229. or_options_t *options = get_options();
  230. if (!key_lock)
  231. key_lock = tor_mutex_new();
  232. /* OP's don't need persistent keys; just make up an identity and
  233. * initialize the TLS context. */
  234. if (!server_mode(options)) {
  235. if (!(prkey = crypto_new_pk_env()))
  236. return -1;
  237. if (crypto_pk_generate_key(prkey))
  238. return -1;
  239. set_identity_key(prkey);
  240. /* Create a TLS context; default the client nickname to "client". */
  241. if (tor_tls_context_new(get_identity_key(), 1,
  242. options->Nickname ? options->Nickname : "client",
  243. MAX_SSL_KEY_LIFETIME) < 0) {
  244. err(LD_GENERAL,"Error creating TLS context for OP.");
  245. return -1;
  246. }
  247. return 0;
  248. }
  249. /* Make sure DataDirectory exists, and is private. */
  250. datadir = options->DataDirectory;
  251. if (check_private_dir(datadir, CPD_CREATE)) {
  252. return -1;
  253. }
  254. /* Check the key directory. */
  255. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  256. if (check_private_dir(keydir, CPD_CREATE)) {
  257. return -1;
  258. }
  259. cp = keydir + strlen(keydir); /* End of string. */
  260. /* 1. Read identity key. Make it if none is found. */
  261. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  262. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  263. info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
  264. prkey = init_key_from_file_name_changed(keydir,keydir2);
  265. if (!prkey) return -1;
  266. set_identity_key(prkey);
  267. /* 2. Read onion key. Make it if none is found. */
  268. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  269. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  270. info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
  271. prkey = init_key_from_file_name_changed(keydir,keydir2);
  272. if (!prkey) return -1;
  273. set_onion_key(prkey);
  274. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  275. if (file_status(keydir) == FN_FILE) {
  276. prkey = init_key_from_file(keydir);
  277. if (prkey)
  278. lastonionkey = prkey;
  279. }
  280. /* 3. Initialize link key and TLS context. */
  281. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  282. MAX_SSL_KEY_LIFETIME) < 0) {
  283. err(LD_GENERAL,"Error initializing TLS context");
  284. return -1;
  285. }
  286. /* 4. Dump router descriptor to 'router.desc' */
  287. /* Must be called after keys are initialized. */
  288. mydesc = router_get_my_descriptor();
  289. if (!mydesc) {
  290. err(LD_GENERAL,"Error initializing descriptor.");
  291. return -1;
  292. }
  293. if (authdir_mode(options)) {
  294. const char *m;
  295. /* We need to add our own fingerprint so it gets recognized. */
  296. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  297. err(LD_GENERAL,"Error adding own fingerprint to approved set");
  298. return -1;
  299. }
  300. if (dirserv_add_descriptor(mydesc, &m) < 0) {
  301. err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  302. m?m:"<unknown error>");
  303. return -1;
  304. }
  305. }
  306. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  307. info(LD_GENERAL,"Dumping descriptor to \"%s\"...",keydir);
  308. if (write_str_to_file(keydir, mydesc,0)) {
  309. return -1;
  310. }
  311. /* 5. Dump fingerprint to 'fingerprint' */
  312. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  313. info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  314. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  315. err(LD_GENERAL,"Error computing fingerprint");
  316. return -1;
  317. }
  318. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  319. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  320. "%s %s\n",options->Nickname, fingerprint) < 0) {
  321. err(LD_GENERAL,"Error writing fingerprint line");
  322. return -1;
  323. }
  324. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  325. err(LD_FS, "Error writing fingerprint line to file");
  326. return -1;
  327. }
  328. if (!authdir_mode(options))
  329. return 0;
  330. /* 6. [authdirserver only] load approved-routers file */
  331. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  332. info(LD_DIRSERV,"Loading approved fingerprints from \"%s\"...",keydir);
  333. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  334. err(LD_GENERAL,"Error loading fingerprints");
  335. return -1;
  336. }
  337. /* 6b. [authdirserver only] add own key to approved directories. */
  338. crypto_pk_get_digest(get_identity_key(), digest);
  339. if (!router_digest_is_trusted_dir(digest)) {
  340. add_trusted_dir_server(options->Nickname, NULL,
  341. (uint16_t)options->DirPort, digest,
  342. options->V1AuthoritativeDir);
  343. }
  344. /* success */
  345. return 0;
  346. }
  347. /* Keep track of whether we should upload our server descriptor,
  348. * and what type of server we are.
  349. */
  350. /** Whether we can reach our ORPort from the outside. */
  351. static int can_reach_or_port = 0;
  352. /** Whether we can reach our DirPort from the outside. */
  353. static int can_reach_dir_port = 0;
  354. /** Return 1 if or port is known reachable; else return 0. */
  355. int
  356. check_whether_orport_reachable(void)
  357. {
  358. or_options_t *options = get_options();
  359. return clique_mode(options) ||
  360. options->AssumeReachable ||
  361. can_reach_or_port;
  362. }
  363. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  364. int
  365. check_whether_dirport_reachable(void)
  366. {
  367. or_options_t *options = get_options();
  368. return !options->DirPort ||
  369. options->AssumeReachable ||
  370. we_are_hibernating() ||
  371. can_reach_dir_port;
  372. }
  373. /** Look at a variety of factors, and return 0 if we don't want to
  374. * advertise the fact that we have a DirPort open. Else return the
  375. * DirPort we want to advertise. */
  376. static int
  377. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  378. {
  379. if (!router->dir_port) /* short circuit the rest of the function */
  380. return 0;
  381. if (authdir_mode(options)) /* always publish */
  382. return router->dir_port;
  383. if (we_are_hibernating())
  384. return 0;
  385. if (!check_whether_dirport_reachable())
  386. return 0;
  387. if (router->bandwidthcapacity >= router->bandwidthrate) {
  388. /* check if we might potentially hibernate. */
  389. if (options->AccountingMax != 0)
  390. return 0;
  391. /* also check if we're advertising a small amount, and have
  392. a "boring" DirPort. */
  393. if (router->bandwidthrate < 50000 && router->dir_port > 1024)
  394. return 0;
  395. }
  396. /* Sounds like a great idea. Let's publish it. */
  397. return router->dir_port;
  398. }
  399. /** Some time has passed, or we just got new directory information.
  400. * See if we currently believe our ORPort or DirPort to be
  401. * unreachable. If so, launch a new test for it.
  402. *
  403. * For ORPort, we simply try making a circuit that ends at ourselves.
  404. * Success is noticed in onionskin_answer().
  405. *
  406. * For DirPort, we make a connection via Tor to our DirPort and ask
  407. * for our own server descriptor.
  408. * Success is noticed in connection_dir_client_reached_eof().
  409. */
  410. void
  411. consider_testing_reachability(void)
  412. {
  413. routerinfo_t *me = router_get_my_routerinfo();
  414. if (!me) {
  415. warn(LD_BUG,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
  416. return;
  417. }
  418. if (!check_whether_orport_reachable()) {
  419. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  420. }
  421. if (!check_whether_dirport_reachable()) {
  422. /* ask myself, via tor, for my server descriptor. */
  423. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
  424. 1, "authority", NULL, 0);
  425. }
  426. }
  427. /** Annotate that we found our ORPort reachable. */
  428. void
  429. router_orport_found_reachable(void)
  430. {
  431. if (!can_reach_or_port) {
  432. if (!clique_mode(get_options()))
  433. notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  434. "the outside. Excellent.%s",
  435. get_options()->NoPublish ? "" : " Publishing server descriptor.");
  436. can_reach_or_port = 1;
  437. mark_my_descriptor_dirty();
  438. consider_publishable_server(time(NULL), 1);
  439. }
  440. }
  441. /** Annotate that we found our DirPort reachable. */
  442. void
  443. router_dirport_found_reachable(void)
  444. {
  445. if (!can_reach_dir_port) {
  446. notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  447. "from the outside. Excellent.");
  448. can_reach_dir_port = 1;
  449. }
  450. }
  451. /** Our router has just moved to a new IP. Reset stats. */
  452. void
  453. server_has_changed_ip(void)
  454. {
  455. stats_n_seconds_working = 0;
  456. can_reach_or_port = 0;
  457. can_reach_dir_port = 0;
  458. mark_my_descriptor_dirty();
  459. }
  460. /** Return true iff we believe ourselves to be an authoritative
  461. * directory server.
  462. */
  463. int
  464. authdir_mode(or_options_t *options)
  465. {
  466. return options->AuthoritativeDir != 0;
  467. }
  468. /** Return true iff we try to stay connected to all ORs at once.
  469. */
  470. int
  471. clique_mode(or_options_t *options)
  472. {
  473. return authdir_mode(options);
  474. }
  475. /** Return true iff we are trying to be a server.
  476. */
  477. int
  478. server_mode(or_options_t *options)
  479. {
  480. if (options->ClientOnly) return 0;
  481. return (options->ORPort != 0 || options->ORListenAddress);
  482. }
  483. /** Remember if we've advertised ourselves to the dirservers. */
  484. static int server_is_advertised=0;
  485. /** Return true iff we have published our descriptor lately.
  486. */
  487. int
  488. advertised_server_mode(void)
  489. {
  490. return server_is_advertised;
  491. }
  492. /**
  493. * Called with a boolean: set whether we have recently published our
  494. * descriptor.
  495. */
  496. static void
  497. set_server_advertised(int s)
  498. {
  499. server_is_advertised = s;
  500. }
  501. /** Return true iff we are trying to be a socks proxy. */
  502. int
  503. proxy_mode(or_options_t *options)
  504. {
  505. return (options->SocksPort != 0 || options->SocksListenAddress);
  506. }
  507. /** Decide if we're a publishable server. We are a publishable server if:
  508. * - We don't have the ClientOnly option set
  509. * and
  510. * - We don't have the NoPublish option set
  511. * and
  512. * - We have ORPort set
  513. * and
  514. * - We believe we are reachable from the outside; or
  515. * - We have the AuthoritativeDirectory option set.
  516. */
  517. static int
  518. decide_if_publishable_server(time_t now)
  519. {
  520. or_options_t *options = get_options();
  521. if (options->ClientOnly)
  522. return 0;
  523. if (options->NoPublish)
  524. return 0;
  525. if (!server_mode(options))
  526. return 0;
  527. if (options->AuthoritativeDir)
  528. return 1;
  529. return check_whether_orport_reachable();
  530. }
  531. /** Initiate server descriptor upload as reasonable (if server is publishable,
  532. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  533. */
  534. void
  535. consider_publishable_server(time_t now, int force)
  536. {
  537. if (decide_if_publishable_server(now)) {
  538. set_server_advertised(1);
  539. if (router_rebuild_descriptor(0) == 0)
  540. router_upload_dir_desc_to_dirservers(force);
  541. } else {
  542. set_server_advertised(0);
  543. }
  544. }
  545. /*
  546. * Clique maintenance
  547. */
  548. /** OR only: if in clique mode, try to open connections to all of the
  549. * other ORs we know about. Otherwise, open connections to those we
  550. * think are in clique mode.o
  551. *
  552. * If <b>force</b> is zero, only open the connection if we don't already
  553. * have one.
  554. */
  555. void
  556. router_retry_connections(int force)
  557. {
  558. time_t now = time(NULL);
  559. routerlist_t *rl = router_get_routerlist();
  560. or_options_t *options = get_options();
  561. tor_assert(server_mode(options));
  562. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
  563. const char *id_digest = router->cache_info.identity_digest;
  564. if (router_is_me(router))
  565. continue;
  566. if (!clique_mode(options) && !router_is_clique_mode(router))
  567. continue;
  568. if (force ||
  569. !connection_or_get_by_identity_digest(id_digest)) {
  570. debug(LD_OR,"%sconnecting to %s at %s:%u.",
  571. clique_mode(options) ? "(forced) " : "",
  572. router->nickname, router->address, router->or_port);
  573. /* Remember when we started trying to determine reachability */
  574. if (!router->testing_since)
  575. router->testing_since = now;
  576. connection_or_connect(router->addr, router->or_port,
  577. id_digest);
  578. }
  579. });
  580. }
  581. /** Return true iff this OR should try to keep connections open to all
  582. * other ORs. */
  583. int
  584. router_is_clique_mode(routerinfo_t *router)
  585. {
  586. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  587. return 1;
  588. return 0;
  589. }
  590. /*
  591. * OR descriptor generation.
  592. */
  593. /** My routerinfo. */
  594. static routerinfo_t *desc_routerinfo = NULL;
  595. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  596. * now. */
  597. static time_t desc_clean_since = 0;
  598. /** Boolean: do we need to regenerate the above? */
  599. static int desc_needs_upload = 0;
  600. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  601. * descriptor successfully yet, try to upload our signed descriptor to
  602. * all the directory servers we know about.
  603. */
  604. void
  605. router_upload_dir_desc_to_dirservers(int force)
  606. {
  607. const char *s;
  608. s = router_get_my_descriptor();
  609. if (!s) {
  610. warn(LD_GENERAL, "No descriptor; skipping upload");
  611. return;
  612. }
  613. if (!force && !desc_needs_upload)
  614. return;
  615. desc_needs_upload = 0;
  616. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  617. }
  618. /** OR only: Check whether my exit policy says to allow connection to
  619. * conn. Return 0 if we accept; non-0 if we reject.
  620. */
  621. int
  622. router_compare_to_my_exit_policy(connection_t *conn)
  623. {
  624. tor_assert(desc_routerinfo);
  625. /* make sure it's resolved to something. this way we can't get a
  626. 'maybe' below. */
  627. if (!conn->addr)
  628. return -1;
  629. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  630. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  631. }
  632. /** Return true iff I'm a server and <b>digest</b> is equal to
  633. * my identity digest. */
  634. int
  635. router_digest_is_me(const char *digest)
  636. {
  637. routerinfo_t *me = router_get_my_routerinfo();
  638. if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
  639. return 0;
  640. return 1;
  641. }
  642. /** A wrapper around router_digest_is_me(). */
  643. int
  644. router_is_me(routerinfo_t *router)
  645. {
  646. return router_digest_is_me(router->cache_info.identity_digest);
  647. }
  648. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  649. int
  650. router_fingerprint_is_me(const char *fp)
  651. {
  652. char digest[DIGEST_LEN];
  653. if (strlen(fp) == HEX_DIGEST_LEN &&
  654. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  655. return router_digest_is_me(digest);
  656. return 0;
  657. }
  658. /** Return a routerinfo for this OR, rebuilding a fresh one if
  659. * necessary. Return NULL on error, or if called on an OP. */
  660. routerinfo_t *
  661. router_get_my_routerinfo(void)
  662. {
  663. if (!server_mode(get_options()))
  664. return NULL;
  665. if (!desc_routerinfo) {
  666. if (router_rebuild_descriptor(1))
  667. return NULL;
  668. }
  669. return desc_routerinfo;
  670. }
  671. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  672. * one if necessary. Return NULL on error.
  673. */
  674. const char *
  675. router_get_my_descriptor(void)
  676. {
  677. if (!desc_routerinfo) {
  678. if (router_rebuild_descriptor(1))
  679. return NULL;
  680. }
  681. debug(LD_GENERAL,"my desc is '%s'",
  682. desc_routerinfo->cache_info.signed_descriptor);
  683. return desc_routerinfo->cache_info.signed_descriptor;
  684. }
  685. /*DOCDOC*/
  686. static smartlist_t *warned_nonexistent_family = NULL;
  687. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  688. * a fresh routerinfo and signed server descriptor for this OR.
  689. * Return 0 on success, -1 on error.
  690. */
  691. int
  692. router_rebuild_descriptor(int force)
  693. {
  694. routerinfo_t *ri;
  695. uint32_t addr;
  696. char platform[256];
  697. int hibernating = we_are_hibernating();
  698. or_options_t *options = get_options();
  699. if (desc_clean_since && !force)
  700. return 0;
  701. if (resolve_my_address(options, &addr, NULL) < 0) {
  702. warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  703. return -1;
  704. }
  705. ri = tor_malloc_zero(sizeof(routerinfo_t));
  706. ri->address = tor_dup_addr(addr);
  707. ri->nickname = tor_strdup(options->Nickname);
  708. ri->addr = addr;
  709. ri->or_port = options->ORPort;
  710. ri->dir_port = options->DirPort;
  711. ri->cache_info.published_on = time(NULL);
  712. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  713. * main thread */
  714. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  715. if (crypto_pk_get_digest(ri->identity_pkey,
  716. ri->cache_info.identity_digest)<0) {
  717. routerinfo_free(ri);
  718. return -1;
  719. }
  720. get_platform_str(platform, sizeof(platform));
  721. ri->platform = tor_strdup(platform);
  722. ri->bandwidthrate = (int)options->BandwidthRate;
  723. ri->bandwidthburst = (int)options->BandwidthBurst;
  724. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  725. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  726. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  727. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
  728. options_append_default_exit_policy(&ri->exit_policy);
  729. if (desc_routerinfo) { /* inherit values */
  730. ri->is_verified = desc_routerinfo->is_verified;
  731. ri->is_running = desc_routerinfo->is_running;
  732. ri->is_named = desc_routerinfo->is_named;
  733. }
  734. if (authdir_mode(options))
  735. ri->is_verified = ri->is_named = 1; /* believe in yourself */
  736. if (options->MyFamily) {
  737. smartlist_t *family;
  738. if (!warned_nonexistent_family)
  739. warned_nonexistent_family = smartlist_create();
  740. family = smartlist_create();
  741. ri->declared_family = smartlist_create();
  742. smartlist_split_string(family, options->MyFamily, ",",
  743. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  744. SMARTLIST_FOREACH(family, char *, name,
  745. {
  746. routerinfo_t *member;
  747. if (!strcasecmp(name, options->Nickname))
  748. member = ri;
  749. else
  750. member = router_get_by_nickname(name, 1);
  751. if (!member) {
  752. if (!smartlist_string_isin(warned_nonexistent_family, name)) {
  753. warn(LD_CONFIG, "I have no descriptor for the router named \"%s\" "
  754. "in my declared family; I'll use the nickname as is, but "
  755. "this may confuse clients.", name);
  756. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  757. }
  758. smartlist_add(ri->declared_family, name);
  759. name = NULL;
  760. } else {
  761. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  762. fp[0] = '$';
  763. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  764. member->cache_info.identity_digest, DIGEST_LEN);
  765. smartlist_add(ri->declared_family, fp);
  766. if (smartlist_string_isin(warned_nonexistent_family, name))
  767. smartlist_string_remove(warned_nonexistent_family, name);
  768. }
  769. tor_free(name);
  770. });
  771. smartlist_free(family);
  772. }
  773. ri->cache_info.signed_descriptor = tor_malloc(8192);
  774. if (router_dump_router_to_string(ri->cache_info.signed_descriptor, 8192,
  775. ri, get_identity_key())<0) {
  776. warn(LD_BUG, "Couldn't allocate string for descriptor.");
  777. return -1;
  778. }
  779. ri->cache_info.signed_descriptor_len =
  780. strlen(ri->cache_info.signed_descriptor);
  781. crypto_digest(ri->cache_info.signed_descriptor_digest,
  782. ri->cache_info.signed_descriptor,
  783. ri->cache_info.signed_descriptor_len);
  784. if (desc_routerinfo)
  785. routerinfo_free(desc_routerinfo);
  786. desc_routerinfo = ri;
  787. desc_clean_since = time(NULL);
  788. desc_needs_upload = 1;
  789. return 0;
  790. }
  791. /** Mark descriptor out of date if it's older than <b>when</b> */
  792. void
  793. mark_my_descriptor_dirty_if_older_than(time_t when)
  794. {
  795. if (desc_clean_since < when)
  796. mark_my_descriptor_dirty();
  797. }
  798. /** Call when the current descriptor is out of date. */
  799. void
  800. mark_my_descriptor_dirty(void)
  801. {
  802. desc_clean_since = 0;
  803. }
  804. #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
  805. /** Check whether bandwidth has changed a lot since the last time we announced
  806. * bandwidth. If so, mark our descriptor dirty. */
  807. void
  808. check_descriptor_bandwidth_changed(time_t now)
  809. {
  810. static time_t last_changed = 0;
  811. uint64_t prev, cur;
  812. if (!desc_routerinfo)
  813. return;
  814. prev = desc_routerinfo->bandwidthcapacity;
  815. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  816. if ((prev != cur && (!prev || !cur)) ||
  817. cur > prev*2 ||
  818. cur < prev/2) {
  819. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  820. info(LD_GENERAL,
  821. "Measured bandwidth has changed; rebuilding descriptor.");
  822. mark_my_descriptor_dirty();
  823. last_changed = now;
  824. }
  825. }
  826. }
  827. /** Check whether our own address as defined by the Address configuration
  828. * has changed. This is for routers that get their address from a service
  829. * like dyndns. If our address has changed, mark our descriptor dirty. */
  830. void
  831. check_descriptor_ipaddress_changed(time_t now)
  832. {
  833. uint32_t prev, cur;
  834. or_options_t *options = get_options();
  835. if (!desc_routerinfo)
  836. return;
  837. prev = desc_routerinfo->addr;
  838. if (resolve_my_address(options, &cur, NULL) < 0) {
  839. warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  840. return;
  841. }
  842. if (prev != cur) {
  843. char addrbuf_prev[INET_NTOA_BUF_LEN];
  844. char addrbuf_cur[INET_NTOA_BUF_LEN];
  845. struct in_addr in_prev;
  846. struct in_addr in_cur;
  847. in_prev.s_addr = htonl(prev);
  848. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  849. in_cur.s_addr = htonl(cur);
  850. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  851. info(LD_GENERAL,
  852. "Our IP Address has changed from %s to %s; rebuilding descriptor.",
  853. addrbuf_prev, addrbuf_cur);
  854. mark_my_descriptor_dirty();
  855. }
  856. }
  857. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  858. * string describing the version of Tor and the operating system we're
  859. * currently running on.
  860. */
  861. void
  862. get_platform_str(char *platform, size_t len)
  863. {
  864. tor_snprintf(platform, len, "Tor %s on %s",
  865. VERSION, get_uname());
  866. return;
  867. }
  868. /* XXX need to audit this thing and count fenceposts. maybe
  869. * refactor so we don't have to keep asking if we're
  870. * near the end of maxlen?
  871. */
  872. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  873. /** OR only: Given a routerinfo for this router, and an identity key to sign
  874. * with, encode the routerinfo as a signed server descriptor and write the
  875. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  876. * failure, and the number of bytes used on success.
  877. */
  878. int
  879. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  880. crypto_pk_env_t *ident_key)
  881. {
  882. char *onion_pkey; /* Onion key, PEM-encoded. */
  883. char *identity_pkey; /* Identity key, PEM-encoded. */
  884. char digest[DIGEST_LEN];
  885. char published[ISO_TIME_LEN+1];
  886. char fingerprint[FINGERPRINT_LEN+1];
  887. struct in_addr in;
  888. char addrbuf[INET_NTOA_BUF_LEN];
  889. size_t onion_pkeylen, identity_pkeylen;
  890. size_t written;
  891. int result=0;
  892. addr_policy_t *tmpe;
  893. char *bandwidth_usage;
  894. char *family_line;
  895. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  896. char *s_tmp, *s_dup;
  897. const char *cp;
  898. routerinfo_t *ri_tmp;
  899. #endif
  900. or_options_t *options = get_options();
  901. /* Make sure the identity key matches the one in the routerinfo. */
  902. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  903. warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  904. "match router's public key!");
  905. return -1;
  906. }
  907. /* record our fingerprint, so we can include it in the descriptor */
  908. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  909. err(LD_BUG,"Error computing fingerprint");
  910. return -1;
  911. }
  912. /* PEM-encode the onion key */
  913. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  914. &onion_pkey,&onion_pkeylen)<0) {
  915. warn(LD_BUG,"write onion_pkey to string failed!");
  916. return -1;
  917. }
  918. /* PEM-encode the identity key key */
  919. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  920. &identity_pkey,&identity_pkeylen)<0) {
  921. warn(LD_BUG,"write identity_pkey to string failed!");
  922. tor_free(onion_pkey);
  923. return -1;
  924. }
  925. /* Encode the publication time. */
  926. format_iso_time(published, router->cache_info.published_on);
  927. /* How busy have we been? */
  928. bandwidth_usage = rep_hist_get_bandwidth_lines();
  929. if (router->declared_family && smartlist_len(router->declared_family)) {
  930. size_t n;
  931. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  932. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  933. family_line = tor_malloc(n);
  934. tor_snprintf(family_line, n, "family %s\n", s);
  935. tor_free(s);
  936. } else {
  937. family_line = tor_strdup("");
  938. }
  939. /* Generate the easy portion of the router descriptor. */
  940. result = tor_snprintf(s, maxlen,
  941. "router %s %s %d 0 %d\n"
  942. "platform %s\n"
  943. "published %s\n"
  944. "opt fingerprint %s\n"
  945. "uptime %ld\n"
  946. "bandwidth %d %d %d\n"
  947. "onion-key\n%s"
  948. "signing-key\n%s%s%s%s",
  949. router->nickname,
  950. router->address,
  951. router->or_port,
  952. decide_to_advertise_dirport(options, router),
  953. router->platform,
  954. published,
  955. fingerprint,
  956. stats_n_seconds_working,
  957. (int) router->bandwidthrate,
  958. (int) router->bandwidthburst,
  959. (int) router->bandwidthcapacity,
  960. onion_pkey, identity_pkey,
  961. family_line, bandwidth_usage,
  962. we_are_hibernating() ? "opt hibernating 1\n" : "");
  963. tor_free(family_line);
  964. tor_free(onion_pkey);
  965. tor_free(identity_pkey);
  966. tor_free(bandwidth_usage);
  967. if (result < 0)
  968. return -1;
  969. /* From now on, we use 'written' to remember the current length of 's'. */
  970. written = result;
  971. if (options->ContactInfo && strlen(options->ContactInfo)) {
  972. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  973. options->ContactInfo);
  974. if (result<0)
  975. return -1;
  976. written += result;
  977. }
  978. /* Write the exit policy to the end of 's'. */
  979. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  980. /* Write: "accept 1.2.3.4" */
  981. in.s_addr = htonl(tmpe->addr);
  982. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  983. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  984. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  985. tmpe->msk == 0 ? "*" : addrbuf);
  986. if (result < 0)
  987. return -1;
  988. written += result;
  989. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  990. /* Write "/255.255.0.0" */
  991. in.s_addr = htonl(tmpe->msk);
  992. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  993. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  994. if (result<0)
  995. return -1;
  996. written += result;
  997. }
  998. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  999. /* There is no port set; write ":*" */
  1000. if (written+4 > maxlen)
  1001. return -1;
  1002. strlcat(s+written, ":*\n", maxlen-written);
  1003. written += 3;
  1004. } else if (tmpe->prt_min == tmpe->prt_max) {
  1005. /* There is only one port; write ":80". */
  1006. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  1007. if (result<0)
  1008. return -1;
  1009. written += result;
  1010. } else {
  1011. /* There is a range of ports; write ":79-80". */
  1012. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n",
  1013. tmpe->prt_min, tmpe->prt_max);
  1014. if (result<0)
  1015. return -1;
  1016. written += result;
  1017. }
  1018. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  1019. /* This was a catch-all rule, so future rules are irrelevant. */
  1020. break;
  1021. } /* end for */
  1022. if (written+256 > maxlen) /* Not enough room for signature. */
  1023. return -1;
  1024. /* Sign the directory */
  1025. strlcat(s+written, "router-signature\n", maxlen-written);
  1026. written += strlen(s+written);
  1027. s[written] = '\0';
  1028. if (router_get_router_hash(s, digest) < 0)
  1029. return -1;
  1030. if (router_append_dirobj_signature(s+written,maxlen-written,
  1031. digest,ident_key)<0) {
  1032. warn(LD_BUG, "Couldn't sign router descriptor");
  1033. return -1;
  1034. }
  1035. written += strlen(s+written);
  1036. if (written+2 > maxlen)
  1037. return -1;
  1038. /* include a last '\n' */
  1039. s[written] = '\n';
  1040. s[written+1] = 0;
  1041. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1042. cp = s_tmp = s_dup = tor_strdup(s);
  1043. ri_tmp = router_parse_entry_from_string(cp, NULL);
  1044. if (!ri_tmp) {
  1045. err(LD_BUG,"We just generated a router descriptor we can't parse: <<%s>>",
  1046. s);
  1047. return -1;
  1048. }
  1049. tor_free(s_dup);
  1050. routerinfo_free(ri_tmp);
  1051. #endif
  1052. return written+1;
  1053. }
  1054. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1055. int
  1056. is_legal_nickname(const char *s)
  1057. {
  1058. size_t len;
  1059. tor_assert(s);
  1060. len = strlen(s);
  1061. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1062. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1063. }
  1064. /** Return true iff <b>s</b> is a legally valid server nickname or
  1065. * hex-encoded identity-key digest. */
  1066. int
  1067. is_legal_nickname_or_hexdigest(const char *s)
  1068. {
  1069. size_t len;
  1070. tor_assert(s);
  1071. if (*s!='$')
  1072. return is_legal_nickname(s);
  1073. len = strlen(s);
  1074. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  1075. }
  1076. /** Forget that we have issued any router-related warnings, so that we'll
  1077. * warn again if we see the same errors. */
  1078. void
  1079. router_reset_warnings(void)
  1080. {
  1081. if (warned_nonexistent_family) {
  1082. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1083. smartlist_clear(warned_nonexistent_family);
  1084. }
  1085. }
  1086. /** Release all static resources held in router.c */
  1087. void
  1088. router_free_all(void)
  1089. {
  1090. if (onionkey)
  1091. crypto_free_pk_env(onionkey);
  1092. if (lastonionkey)
  1093. crypto_free_pk_env(lastonionkey);
  1094. if (identitykey)
  1095. crypto_free_pk_env(identitykey);
  1096. if (key_lock)
  1097. tor_mutex_free(key_lock);
  1098. if (desc_routerinfo)
  1099. routerinfo_free(desc_routerinfo);
  1100. if (warned_nonexistent_family) {
  1101. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1102. smartlist_free(warned_nonexistent_family);
  1103. }
  1104. }