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 *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. 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(mydesc, &m) < 0) {
  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(NULL, (uint16_t)options->DirPort, digest,
  344. options->V1AuthoritativeDir);
  345. }
  346. /* success */
  347. return 0;
  348. }
  349. /* Keep track of whether we should upload our server descriptor,
  350. * and what type of server we are.
  351. */
  352. /** Whether we can reach our ORPort from the outside. */
  353. static int can_reach_or_port = 0;
  354. /** Whether we can reach our DirPort from the outside. */
  355. static int can_reach_dir_port = 0;
  356. /** Return 1 if or port is known reachable; else return 0. */
  357. int
  358. check_whether_orport_reachable(void)
  359. {
  360. or_options_t *options = get_options();
  361. return clique_mode(options) ||
  362. options->AssumeReachable ||
  363. can_reach_or_port;
  364. }
  365. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  366. int
  367. check_whether_dirport_reachable(void)
  368. {
  369. or_options_t *options = get_options();
  370. return !options->DirPort ||
  371. options->AssumeReachable ||
  372. can_reach_dir_port;
  373. }
  374. /**DOCDOC*/
  375. void
  376. consider_testing_reachability(void)
  377. {
  378. routerinfo_t *me = router_get_my_routerinfo();
  379. if (!me) {
  380. log_fn(LOG_WARN,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
  381. return;
  382. }
  383. if (!check_whether_orport_reachable()) {
  384. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  385. }
  386. if (!check_whether_dirport_reachable()) {
  387. if (me) {
  388. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_DIR, 1, NULL, NULL, 0);
  389. } else {
  390. log(LOG_NOTICE,"Delaying checking DirPort reachability; can't build descriptor.");
  391. }
  392. }
  393. }
  394. /** Annotate that we found our ORPort reachable. */
  395. void
  396. router_orport_found_reachable(void)
  397. {
  398. if (!can_reach_or_port) {
  399. if (!clique_mode(get_options()))
  400. log(LOG_NOTICE,"Your ORPort is reachable from the outside. Excellent.%s",
  401. get_options()->NoPublish ? "" : " Publishing server descriptor.");
  402. can_reach_or_port = 1;
  403. mark_my_descriptor_dirty();
  404. consider_publishable_server(time(NULL), 1);
  405. }
  406. }
  407. /** Annotate that we found our DirPort reachable. */
  408. void
  409. router_dirport_found_reachable(void)
  410. {
  411. if (!can_reach_dir_port) {
  412. log(LOG_NOTICE,"Your DirPort is reachable from the outside. Excellent.");
  413. can_reach_dir_port = 1;
  414. }
  415. }
  416. /** Our router has just moved to a new IP. Reset stats. */
  417. void
  418. server_has_changed_ip(void)
  419. {
  420. stats_n_seconds_working = 0;
  421. can_reach_or_port = 0;
  422. can_reach_dir_port = 0;
  423. mark_my_descriptor_dirty();
  424. }
  425. /** Return true iff we believe ourselves to be an authoritative
  426. * directory server.
  427. */
  428. int
  429. authdir_mode(or_options_t *options)
  430. {
  431. return options->AuthoritativeDir != 0;
  432. }
  433. /** Return true iff we try to stay connected to all ORs at once.
  434. */
  435. int
  436. clique_mode(or_options_t *options)
  437. {
  438. return authdir_mode(options);
  439. }
  440. /** Return true iff we are trying to be a server.
  441. */
  442. int
  443. server_mode(or_options_t *options)
  444. {
  445. if (options->ClientOnly) return 0;
  446. return (options->ORPort != 0 || options->ORBindAddress);
  447. }
  448. /** Remember if we've advertised ourselves to the dirservers. */
  449. static int server_is_advertised=0;
  450. /** Return true iff we have published our descriptor lately.
  451. */
  452. int
  453. advertised_server_mode(void)
  454. {
  455. return server_is_advertised;
  456. }
  457. /**
  458. * Called with a boolean: set whether we have recently published our descriptor.
  459. */
  460. static void
  461. set_server_advertised(int s)
  462. {
  463. server_is_advertised = s;
  464. }
  465. /** Return true iff we are trying to be a socks proxy. */
  466. int
  467. proxy_mode(or_options_t *options)
  468. {
  469. return (options->SocksPort != 0 || options->SocksBindAddress);
  470. }
  471. /** Decide if we're a publishable server. We are a publishable server if:
  472. * - We don't have the ClientOnly option set
  473. * and
  474. * - We don't have the NoPublish option set
  475. * and
  476. * - We have ORPort set
  477. * and
  478. * - We believe we are reachable from the outside; or
  479. * - We have the AuthoritativeDirectory option set.
  480. */
  481. static int
  482. decide_if_publishable_server(time_t now)
  483. {
  484. or_options_t *options = get_options();
  485. if (options->ClientOnly)
  486. return 0;
  487. if (options->NoPublish)
  488. return 0;
  489. if (!server_mode(options))
  490. return 0;
  491. if (options->AuthoritativeDir)
  492. return 1;
  493. return check_whether_orport_reachable();
  494. }
  495. /** Initiate server descriptor upload as reasonable (if server is publishable,
  496. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  497. */
  498. void
  499. consider_publishable_server(time_t now, int force)
  500. {
  501. if (decide_if_publishable_server(now)) {
  502. set_server_advertised(1);
  503. if (router_rebuild_descriptor(0) == 0)
  504. router_upload_dir_desc_to_dirservers(force);
  505. } else {
  506. set_server_advertised(0);
  507. }
  508. }
  509. /*
  510. * Clique maintenance
  511. */
  512. /** OR only: if in clique mode, try to open connections to all of the
  513. * other ORs we know about. Otherwise, open connections to those we
  514. * think are in clique mode.o
  515. *
  516. * If <b>force</b> is zero, only open the connection if we don't already
  517. * have one.
  518. */
  519. void
  520. router_retry_connections(int force)
  521. {
  522. int i;
  523. time_t now = time(NULL);
  524. routerinfo_t *router;
  525. routerlist_t *rl;
  526. or_options_t *options = get_options();
  527. tor_assert(server_mode(options));
  528. router_get_routerlist(&rl);
  529. if (!rl) return;
  530. for (i=0;i < smartlist_len(rl->routers);i++) {
  531. router = smartlist_get(rl->routers, i);
  532. if (router_is_me(router))
  533. continue;
  534. if (!clique_mode(options) && !router_is_clique_mode(router))
  535. continue;
  536. if (force ||
  537. !connection_get_by_identity_digest(router->identity_digest,
  538. CONN_TYPE_OR)) {
  539. log_fn(LOG_INFO,"%sconnecting to %s at %s:%u.",
  540. clique_mode(options) ? "(forced) " : "",
  541. router->nickname, router->address, router->or_port);
  542. /* Remember when we started trying to determine reachability */
  543. if (!router->testing_since)
  544. router->testing_since = now;
  545. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  546. }
  547. }
  548. }
  549. /** Return true iff this OR should try to keep connections open to all
  550. * other ORs. */
  551. int
  552. router_is_clique_mode(routerinfo_t *router)
  553. {
  554. if (router_digest_is_trusted_dir(router->identity_digest))
  555. return 1;
  556. return 0;
  557. }
  558. /*
  559. * OR descriptor generation.
  560. */
  561. /** My routerinfo. */
  562. static routerinfo_t *desc_routerinfo = NULL;
  563. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  564. * now. */
  565. static time_t desc_clean_since = 0;
  566. /** Boolean: do we need to regenerate the above? */
  567. static int desc_needs_upload = 0;
  568. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  569. * descriptor successfully yet, try to upload our signed descriptor to
  570. * all the directory servers we know about.
  571. */
  572. void
  573. router_upload_dir_desc_to_dirservers(int force)
  574. {
  575. const char *s;
  576. s = router_get_my_descriptor();
  577. if (!s) {
  578. log_fn(LOG_WARN, "No descriptor; skipping upload");
  579. return;
  580. }
  581. if (!force && !desc_needs_upload)
  582. return;
  583. desc_needs_upload = 0;
  584. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  585. }
  586. /** OR only: Check whether my exit policy says to allow connection to
  587. * conn. Return 0 if we accept; non-0 if we reject.
  588. */
  589. int
  590. router_compare_to_my_exit_policy(connection_t *conn)
  591. {
  592. tor_assert(desc_routerinfo);
  593. /* make sure it's resolved to something. this way we can't get a
  594. 'maybe' below. */
  595. if (!conn->addr)
  596. return -1;
  597. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  598. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  599. }
  600. /** Return true iff I'm a server and <b>digest</b> is equal to
  601. * my identity digest. */
  602. int
  603. router_digest_is_me(const char *digest)
  604. {
  605. routerinfo_t *me = router_get_my_routerinfo();
  606. if (!me || memcmp(me->identity_digest, digest, DIGEST_LEN))
  607. return 0;
  608. return 1;
  609. }
  610. /** A wrapper around router_digest_is_me(). */
  611. int
  612. router_is_me(routerinfo_t *router)
  613. {
  614. return router_digest_is_me(router->identity_digest);
  615. }
  616. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  617. int
  618. router_fingerprint_is_me(const char *fp)
  619. {
  620. char digest[DIGEST_LEN];
  621. if (strlen(fp) == HEX_DIGEST_LEN &&
  622. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  623. return router_digest_is_me(digest);
  624. return 0;
  625. }
  626. /** Return a routerinfo for this OR, rebuilding a fresh one if
  627. * necessary. Return NULL on error, or if called on an OP. */
  628. routerinfo_t *
  629. router_get_my_routerinfo(void)
  630. {
  631. if (!server_mode(get_options()))
  632. return NULL;
  633. if (!desc_routerinfo) {
  634. if (router_rebuild_descriptor(1))
  635. return NULL;
  636. }
  637. return desc_routerinfo;
  638. }
  639. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  640. * one if necessary. Return NULL on error.
  641. */
  642. const char *
  643. router_get_my_descriptor(void)
  644. {
  645. if (!desc_routerinfo) {
  646. if (router_rebuild_descriptor(1))
  647. return NULL;
  648. }
  649. log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
  650. return desc_routerinfo->signed_descriptor;
  651. }
  652. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  653. * a fresh routerinfo and signed server descriptor for this OR.
  654. * Return 0 on success, -1 on error.
  655. */
  656. int
  657. router_rebuild_descriptor(int force)
  658. {
  659. routerinfo_t *ri;
  660. uint32_t addr;
  661. char platform[256];
  662. int hibernating = we_are_hibernating();
  663. or_options_t *options = get_options();
  664. if (desc_clean_since && !force)
  665. return 0;
  666. if (resolve_my_address(options, &addr, NULL) < 0) {
  667. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  668. return -1;
  669. }
  670. ri = tor_malloc_zero(sizeof(routerinfo_t));
  671. ri->address = tor_dup_addr(addr);
  672. ri->nickname = tor_strdup(options->Nickname);
  673. ri->addr = addr;
  674. ri->or_port = options->ORPort;
  675. ri->dir_port = hibernating ?
  676. 0 : options->DirPort;
  677. ri->published_on = time(NULL);
  678. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  679. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  680. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  681. routerinfo_free(ri);
  682. return -1;
  683. }
  684. get_platform_str(platform, sizeof(platform));
  685. ri->platform = tor_strdup(platform);
  686. ri->bandwidthrate = (int)options->BandwidthRate;
  687. ri->bandwidthburst = (int)options->BandwidthBurst;
  688. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  689. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  690. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  691. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
  692. options_append_default_exit_policy(&ri->exit_policy);
  693. if (desc_routerinfo) /* inherit values */
  694. ri->is_verified = desc_routerinfo->is_verified;
  695. if (authdir_mode(options))
  696. ri->is_verified = 1; /* believe in yourself */
  697. if (options->MyFamily) {
  698. ri->declared_family = smartlist_create();
  699. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  700. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  701. }
  702. ri->signed_descriptor = tor_malloc(8192);
  703. if (router_dump_router_to_string(ri->signed_descriptor, 8192,
  704. ri, get_identity_key())<0) {
  705. log_fn(LOG_WARN, "Couldn't dump router to string.");
  706. return -1;
  707. }
  708. ri->signed_descriptor_len = strlen(ri->signed_descriptor);
  709. crypto_digest(ri->signed_descriptor_digest,
  710. ri->signed_descriptor, ri->signed_descriptor_len);
  711. if (desc_routerinfo)
  712. routerinfo_free(desc_routerinfo);
  713. desc_routerinfo = ri;
  714. desc_clean_since = time(NULL);
  715. desc_needs_upload = 1;
  716. return 0;
  717. }
  718. /** Mark descriptor out of date if it's older than <b>when</b> */
  719. void
  720. mark_my_descriptor_dirty_if_older_than(time_t when)
  721. {
  722. if (desc_clean_since < when)
  723. mark_my_descriptor_dirty();
  724. }
  725. /** Call when the current descriptor is out of date. */
  726. void
  727. mark_my_descriptor_dirty(void)
  728. {
  729. desc_clean_since = 0;
  730. }
  731. #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
  732. /** Check whether bandwidth has changed a lot since the last time we announced
  733. * bandwidth. If so, mark our descriptor dirty.*/
  734. void
  735. check_descriptor_bandwidth_changed(time_t now)
  736. {
  737. static time_t last_changed = 0;
  738. uint64_t prev, cur;
  739. if (!desc_routerinfo)
  740. return;
  741. prev = desc_routerinfo->bandwidthcapacity;
  742. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  743. if ((prev != cur && (!prev || !cur)) ||
  744. cur > prev*2 ||
  745. cur < prev/2) {
  746. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  747. log_fn(LOG_INFO,"Measured bandwidth has changed; rebuilding descriptor.");
  748. mark_my_descriptor_dirty();
  749. last_changed = now;
  750. }
  751. }
  752. }
  753. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  754. * string describing the version of Tor and the operating system we're
  755. * currently running on.
  756. */
  757. void
  758. get_platform_str(char *platform, size_t len)
  759. {
  760. tor_snprintf(platform, len, "Tor %s on %s",
  761. VERSION, get_uname());
  762. return;
  763. }
  764. /* XXX need to audit this thing and count fenceposts. maybe
  765. * refactor so we don't have to keep asking if we're
  766. * near the end of maxlen?
  767. */
  768. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  769. /** OR only: Given a routerinfo for this router, and an identity key to sign
  770. * with, encode the routerinfo as a signed server descriptor and write the
  771. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  772. * failure, and the number of bytes used on success.
  773. */
  774. int
  775. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  776. crypto_pk_env_t *ident_key)
  777. {
  778. char *onion_pkey; /* Onion key, PEM-encoded. */
  779. char *identity_pkey; /* Identity key, PEM-encoded. */
  780. char digest[DIGEST_LEN];
  781. char published[ISO_TIME_LEN+1];
  782. char fingerprint[FINGERPRINT_LEN+1];
  783. struct in_addr in;
  784. char addrbuf[INET_NTOA_BUF_LEN];
  785. size_t onion_pkeylen, identity_pkeylen;
  786. size_t written;
  787. int result=0;
  788. addr_policy_t *tmpe;
  789. char *bandwidth_usage;
  790. char *family_line;
  791. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  792. char *s_tmp, *s_dup;
  793. const char *cp;
  794. routerinfo_t *ri_tmp;
  795. #endif
  796. or_options_t *options = get_options();
  797. /* Make sure the identity key matches the one in the routerinfo. */
  798. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  799. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  800. return -1;
  801. }
  802. /* record our fingerprint, so we can include it in the descriptor */
  803. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  804. log_fn(LOG_ERR, "Error computing fingerprint");
  805. return -1;
  806. }
  807. /* PEM-encode the onion key */
  808. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  809. &onion_pkey,&onion_pkeylen)<0) {
  810. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  811. return -1;
  812. }
  813. /* PEM-encode the identity key key */
  814. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  815. &identity_pkey,&identity_pkeylen)<0) {
  816. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  817. tor_free(onion_pkey);
  818. return -1;
  819. }
  820. /* Encode the publication time. */
  821. format_iso_time(published, router->published_on);
  822. /* How busy have we been? */
  823. bandwidth_usage = rep_hist_get_bandwidth_lines();
  824. if (router->declared_family && smartlist_len(router->declared_family)) {
  825. size_t n;
  826. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  827. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  828. family_line = tor_malloc(n);
  829. tor_snprintf(family_line, n, "family %s\n", s);
  830. tor_free(s);
  831. } else {
  832. family_line = tor_strdup("");
  833. }
  834. /* Generate the easy portion of the router descriptor. */
  835. result = tor_snprintf(s, maxlen,
  836. "router %s %s %d 0 %d\n"
  837. "platform %s\n"
  838. "published %s\n"
  839. "opt fingerprint %s\n"
  840. "uptime %ld\n"
  841. "bandwidth %d %d %d\n"
  842. "onion-key\n%s"
  843. "signing-key\n%s%s%s%s",
  844. router->nickname,
  845. router->address,
  846. router->or_port,
  847. (authdir_mode(options) || check_whether_dirport_reachable()) ?
  848. router->dir_port : 0,
  849. router->platform,
  850. published,
  851. fingerprint,
  852. stats_n_seconds_working,
  853. (int) router->bandwidthrate,
  854. (int) router->bandwidthburst,
  855. (int) router->bandwidthcapacity,
  856. onion_pkey, identity_pkey,
  857. family_line, bandwidth_usage,
  858. we_are_hibernating() ? "opt hibernating 1\n" : "");
  859. tor_free(family_line);
  860. tor_free(onion_pkey);
  861. tor_free(identity_pkey);
  862. tor_free(bandwidth_usage);
  863. if (result < 0)
  864. return -1;
  865. /* From now on, we use 'written' to remember the current length of 's'. */
  866. written = result;
  867. if (options->ContactInfo && strlen(options->ContactInfo)) {
  868. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  869. options->ContactInfo);
  870. if (result<0)
  871. return -1;
  872. written += result;
  873. }
  874. /* Write the exit policy to the end of 's'. */
  875. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  876. /* Write: "accept 1.2.3.4" */
  877. in.s_addr = htonl(tmpe->addr);
  878. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  879. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  880. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  881. tmpe->msk == 0 ? "*" : addrbuf);
  882. if (result < 0)
  883. return -1;
  884. written += result;
  885. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  886. /* Write "/255.255.0.0" */
  887. in.s_addr = htonl(tmpe->msk);
  888. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  889. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  890. if (result<0)
  891. return -1;
  892. written += result;
  893. }
  894. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  895. /* There is no port set; write ":*" */
  896. if (written+4 > maxlen)
  897. return -1;
  898. strlcat(s+written, ":*\n", maxlen-written);
  899. written += 3;
  900. } else if (tmpe->prt_min == tmpe->prt_max) {
  901. /* There is only one port; write ":80". */
  902. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  903. if (result<0)
  904. return -1;
  905. written += result;
  906. } else {
  907. /* There is a range of ports; write ":79-80". */
  908. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  909. tmpe->prt_max);
  910. if (result<0)
  911. return -1;
  912. written += result;
  913. }
  914. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  915. /* This was a catch-all rule, so future rules are irrelevant. */
  916. break;
  917. } /* end for */
  918. if (written+256 > maxlen) /* Not enough room for signature. */
  919. return -1;
  920. /* Sign the directory */
  921. strlcat(s+written, "router-signature\n", maxlen-written);
  922. written += strlen(s+written);
  923. s[written] = '\0';
  924. if (router_get_router_hash(s, digest) < 0)
  925. return -1;
  926. if (router_append_dirobj_signature(s+written,maxlen-written,
  927. digest,ident_key)<0) {
  928. log_fn(LOG_WARN, "Couldn't sign router descriptor");
  929. return -1;
  930. }
  931. written += strlen(s+written);
  932. if (written+2 > maxlen)
  933. return -1;
  934. /* include a last '\n' */
  935. s[written] = '\n';
  936. s[written+1] = 0;
  937. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  938. cp = s_tmp = s_dup = tor_strdup(s);
  939. ri_tmp = router_parse_entry_from_string(cp, NULL);
  940. if (!ri_tmp) {
  941. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  942. s);
  943. return -1;
  944. }
  945. tor_free(s_dup);
  946. routerinfo_free(ri_tmp);
  947. #endif
  948. return written+1;
  949. }
  950. /** Return true iff <b>s</b> is a legally valid server nickname. */
  951. int
  952. is_legal_nickname(const char *s)
  953. {
  954. size_t len;
  955. tor_assert(s);
  956. len = strlen(s);
  957. return len > 0 && len <= MAX_NICKNAME_LEN &&
  958. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  959. }
  960. /** Return true iff <b>s</b> is a legally valid server nickname or
  961. * hex-encoded identity-key digest. */
  962. int
  963. is_legal_nickname_or_hexdigest(const char *s)
  964. {
  965. size_t len;
  966. tor_assert(s);
  967. if (*s!='$')
  968. return is_legal_nickname(s);
  969. len = strlen(s);
  970. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  971. }
  972. /** Release all resources held in router keys. */
  973. void
  974. router_free_all_keys(void)
  975. {
  976. if (onionkey)
  977. crypto_free_pk_env(onionkey);
  978. if (lastonionkey)
  979. crypto_free_pk_env(lastonionkey);
  980. if (identitykey)
  981. crypto_free_pk_env(identitykey);
  982. if (key_lock)
  983. tor_mutex_free(key_lock);
  984. if (desc_routerinfo)
  985. routerinfo_free(desc_routerinfo);
  986. }