router.c 31 KB

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