router.c 35 KB

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