router.c 31 KB

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