router.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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.
  522. */
  523. void
  524. router_retry_connections(void)
  525. {
  526. int i;
  527. routerinfo_t *router;
  528. routerlist_t *rl;
  529. or_options_t *options = get_options();
  530. tor_assert(server_mode(options));
  531. router_get_routerlist(&rl);
  532. if (!rl) return;
  533. for (i=0;i < smartlist_len(rl->routers);i++) {
  534. router = smartlist_get(rl->routers, i);
  535. if (router_is_me(router))
  536. continue;
  537. if (!clique_mode(options) && !router_is_clique_mode(router))
  538. continue;
  539. if (!connection_get_by_identity_digest(router->identity_digest,
  540. CONN_TYPE_OR)) {
  541. /* not in the list */
  542. log_fn(LOG_DEBUG,"connecting to OR at %s:%u.",router->address,router->or_port);
  543. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  544. }
  545. }
  546. }
  547. /** Return true iff this OR should try to keep connections open to all
  548. * other ORs. */
  549. int
  550. router_is_clique_mode(routerinfo_t *router)
  551. {
  552. if (router_digest_is_trusted_dir(router->identity_digest))
  553. return 1;
  554. return 0;
  555. }
  556. /*
  557. * OR descriptor generation.
  558. */
  559. /** My routerinfo. */
  560. static routerinfo_t *desc_routerinfo = NULL;
  561. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  562. * now. */
  563. static time_t desc_clean_since = 0;
  564. /** Boolean: do we need to regenerate the above? */
  565. static int desc_needs_upload = 0;
  566. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  567. * descriptor successfully yet, try to upload our signed descriptor to
  568. * all the directory servers we know about.
  569. */
  570. void
  571. router_upload_dir_desc_to_dirservers(int force)
  572. {
  573. const char *s;
  574. s = router_get_my_descriptor();
  575. if (!s) {
  576. log_fn(LOG_WARN, "No descriptor; skipping upload");
  577. return;
  578. }
  579. if (!force || !desc_needs_upload)
  580. return;
  581. desc_needs_upload = 0;
  582. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  583. }
  584. /** OR only: Check whether my exit policy says to allow connection to
  585. * conn. Return 0 if we accept; non-0 if we reject.
  586. */
  587. int
  588. router_compare_to_my_exit_policy(connection_t *conn)
  589. {
  590. tor_assert(desc_routerinfo);
  591. /* make sure it's resolved to something. this way we can't get a
  592. 'maybe' below. */
  593. if (!conn->addr)
  594. return -1;
  595. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  596. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  597. }
  598. /** Return true iff I'm a server and <b>digest</b> is equal to
  599. * my identity digest. */
  600. int
  601. router_digest_is_me(const char *digest)
  602. {
  603. routerinfo_t *me = router_get_my_routerinfo();
  604. if (!me || memcmp(me->identity_digest, digest, DIGEST_LEN))
  605. return 0;
  606. return 1;
  607. }
  608. /** A wrapper around router_digest_is_me(). */
  609. int
  610. router_is_me(routerinfo_t *router)
  611. {
  612. return router_digest_is_me(router->identity_digest);
  613. }
  614. /** Return a routerinfo for this OR, rebuilding a fresh one if
  615. * necessary. Return NULL on error, or if called on an OP. */
  616. routerinfo_t *
  617. router_get_my_routerinfo(void)
  618. {
  619. if (!server_mode(get_options()))
  620. return NULL;
  621. if (!desc_routerinfo) {
  622. if (router_rebuild_descriptor(1))
  623. return NULL;
  624. }
  625. return desc_routerinfo;
  626. }
  627. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  628. * one if necessary. Return NULL on error.
  629. */
  630. const char *
  631. router_get_my_descriptor(void)
  632. {
  633. if (!desc_routerinfo) {
  634. if (router_rebuild_descriptor(1))
  635. return NULL;
  636. }
  637. log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
  638. return desc_routerinfo->signed_descriptor;
  639. }
  640. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  641. * a fresh routerinfo and signed server descriptor for this OR.
  642. * Return 0 on success, -1 on error.
  643. */
  644. int
  645. router_rebuild_descriptor(int force)
  646. {
  647. routerinfo_t *ri;
  648. uint32_t addr;
  649. char platform[256];
  650. struct in_addr in;
  651. int hibernating = we_are_hibernating();
  652. or_options_t *options = get_options();
  653. char addrbuf[INET_NTOA_BUF_LEN];
  654. if (desc_clean_since && !force)
  655. return 0;
  656. if (resolve_my_address(options, &addr) < 0) {
  657. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  658. return -1;
  659. }
  660. ri = tor_malloc_zero(sizeof(routerinfo_t));
  661. in.s_addr = htonl(addr);
  662. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  663. ri->address = tor_strdup(addrbuf);
  664. ri->nickname = tor_strdup(options->Nickname);
  665. ri->addr = addr;
  666. ri->or_port = options->ORPort;
  667. ri->dir_port = hibernating ?
  668. 0 : options->DirPort;
  669. ri->published_on = time(NULL);
  670. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  671. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  672. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  673. routerinfo_free(ri);
  674. return -1;
  675. }
  676. get_platform_str(platform, sizeof(platform));
  677. ri->platform = tor_strdup(platform);
  678. ri->bandwidthrate = (int)options->BandwidthRate;
  679. ri->bandwidthburst = (int)options->BandwidthBurst;
  680. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  681. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  682. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  683. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
  684. options_append_default_exit_policy(&ri->exit_policy);
  685. if (desc_routerinfo) /* inherit values */
  686. ri->is_verified = desc_routerinfo->is_verified;
  687. if (options->MyFamily) {
  688. ri->declared_family = smartlist_create();
  689. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  690. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  691. }
  692. ri->signed_descriptor = tor_malloc(8192);
  693. if (router_dump_router_to_string(ri->signed_descriptor, 8192,
  694. ri, get_identity_key())<0) {
  695. log_fn(LOG_WARN, "Couldn't dump router to string.");
  696. return -1;
  697. }
  698. if (desc_routerinfo)
  699. routerinfo_free(desc_routerinfo);
  700. desc_routerinfo = ri;
  701. desc_clean_since = time(NULL);
  702. desc_needs_upload = 1;
  703. return 0;
  704. }
  705. /** Mark descriptor out of date if it's older than <b>when</b> */
  706. void
  707. mark_my_descriptor_dirty_if_older_than(time_t when)
  708. {
  709. if (desc_clean_since < when)
  710. mark_my_descriptor_dirty();
  711. }
  712. /** Call when the current descriptor is out of date. */
  713. void
  714. mark_my_descriptor_dirty(void)
  715. {
  716. desc_clean_since = 0;
  717. }
  718. #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
  719. /** Check whether bandwidth has changed a lot since the last time we announced
  720. * bandwidth. If so, mark our descriptor dirty.*/
  721. void
  722. check_descriptor_bandwidth_changed(time_t now)
  723. {
  724. static time_t last_changed = 0;
  725. uint64_t prev, cur;
  726. if (!desc_routerinfo)
  727. return;
  728. prev = desc_routerinfo->bandwidthcapacity;
  729. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  730. if ((prev != cur && (!prev || !cur)) ||
  731. cur > prev*2 ||
  732. cur < prev/2) {
  733. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  734. log_fn(LOG_INFO,"Measured bandwidth has changed; rebuilding descriptor.");
  735. mark_my_descriptor_dirty();
  736. last_changed = now;
  737. }
  738. }
  739. }
  740. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  741. * string describing the version of Tor and the operating system we're
  742. * currently running on.
  743. */
  744. void
  745. get_platform_str(char *platform, size_t len)
  746. {
  747. tor_snprintf(platform, len, "Tor %s on %s",
  748. VERSION, get_uname());
  749. return;
  750. }
  751. /* XXX need to audit this thing and count fenceposts. maybe
  752. * refactor so we don't have to keep asking if we're
  753. * near the end of maxlen?
  754. */
  755. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  756. /** OR only: Given a routerinfo for this router, and an identity key to sign
  757. * with, encode the routerinfo as a signed server descriptor and write the
  758. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  759. * failure, and the number of bytes used on success.
  760. */
  761. int
  762. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  763. crypto_pk_env_t *ident_key)
  764. {
  765. char *onion_pkey; /* Onion key, PEM-encoded. */
  766. char *identity_pkey; /* Identity key, PEM-encoded. */
  767. char digest[20];
  768. char signature[128];
  769. char published[32];
  770. char fingerprint[FINGERPRINT_LEN+1];
  771. struct in_addr in;
  772. char addrbuf[INET_NTOA_BUF_LEN];
  773. size_t onion_pkeylen, identity_pkeylen;
  774. size_t written;
  775. int result=0;
  776. addr_policy_t *tmpe;
  777. char *bandwidth_usage;
  778. char *family_line;
  779. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  780. char *s_tmp, *s_dup;
  781. const char *cp;
  782. routerinfo_t *ri_tmp;
  783. #endif
  784. or_options_t *options = get_options();
  785. /* Make sure the identity key matches the one in the routerinfo. */
  786. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  787. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  788. return -1;
  789. }
  790. /* record our fingerprint, so we can include it in the descriptor */
  791. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  792. log_fn(LOG_ERR, "Error computing fingerprint");
  793. return -1;
  794. }
  795. /* PEM-encode the onion key */
  796. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  797. &onion_pkey,&onion_pkeylen)<0) {
  798. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  799. return -1;
  800. }
  801. /* PEM-encode the identity key key */
  802. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  803. &identity_pkey,&identity_pkeylen)<0) {
  804. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  805. tor_free(onion_pkey);
  806. return -1;
  807. }
  808. /* Encode the publication time. */
  809. format_iso_time(published, router->published_on);
  810. /* How busy have we been? */
  811. bandwidth_usage = rep_hist_get_bandwidth_lines();
  812. if (router->declared_family && smartlist_len(router->declared_family)) {
  813. size_t n;
  814. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  815. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  816. family_line = tor_malloc(n);
  817. tor_snprintf(family_line, n, "family %s\n", s);
  818. tor_free(s);
  819. } else {
  820. family_line = tor_strdup("");
  821. }
  822. /* Generate the easy portion of the router descriptor. */
  823. result = tor_snprintf(s, maxlen,
  824. "router %s %s %d 0 %d\n"
  825. "platform %s\n"
  826. "published %s\n"
  827. "opt fingerprint %s\n"
  828. "uptime %ld\n"
  829. "bandwidth %d %d %d\n"
  830. "onion-key\n%s"
  831. "signing-key\n%s%s%s%s",
  832. router->nickname,
  833. router->address,
  834. router->or_port,
  835. (authdir_mode(options) || check_whether_dirport_reachable()) ?
  836. router->dir_port : 0,
  837. router->platform,
  838. published,
  839. fingerprint,
  840. stats_n_seconds_working,
  841. (int) router->bandwidthrate,
  842. (int) router->bandwidthburst,
  843. (int) router->bandwidthcapacity,
  844. onion_pkey, identity_pkey,
  845. family_line, bandwidth_usage,
  846. we_are_hibernating() ? "opt hibernating 1\n" : "");
  847. tor_free(family_line);
  848. tor_free(onion_pkey);
  849. tor_free(identity_pkey);
  850. tor_free(bandwidth_usage);
  851. if (result < 0)
  852. return -1;
  853. /* From now on, we use 'written' to remember the current length of 's'. */
  854. written = result;
  855. if (options->ContactInfo && strlen(options->ContactInfo)) {
  856. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  857. options->ContactInfo);
  858. if (result<0)
  859. return -1;
  860. written += result;
  861. }
  862. /* Write the exit policy to the end of 's'. */
  863. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  864. /* Write: "accept 1.2.3.4" */
  865. in.s_addr = htonl(tmpe->addr);
  866. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  867. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  868. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  869. tmpe->msk == 0 ? "*" : addrbuf);
  870. if (result < 0)
  871. return -1;
  872. written += result;
  873. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  874. /* Write "/255.255.0.0" */
  875. in.s_addr = htonl(tmpe->msk);
  876. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  877. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  878. if (result<0)
  879. return -1;
  880. written += result;
  881. }
  882. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  883. /* There is no port set; write ":*" */
  884. if (written+4 > maxlen)
  885. return -1;
  886. strlcat(s+written, ":*\n", maxlen-written);
  887. written += 3;
  888. } else if (tmpe->prt_min == tmpe->prt_max) {
  889. /* There is only one port; write ":80". */
  890. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  891. if (result<0)
  892. return -1;
  893. written += result;
  894. } else {
  895. /* There is a range of ports; write ":79-80". */
  896. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  897. tmpe->prt_max);
  898. if (result<0)
  899. return -1;
  900. written += result;
  901. }
  902. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  903. /* This was a catch-all rule, so future rules are irrelevant. */
  904. break;
  905. } /* end for */
  906. if (written+256 > maxlen) /* Not enough room for signature. */
  907. return -1;
  908. /* Sign the directory */
  909. strlcat(s+written, "router-signature\n", maxlen-written);
  910. written += strlen(s+written);
  911. s[written] = '\0';
  912. if (router_get_router_hash(s, digest) < 0)
  913. return -1;
  914. if (crypto_pk_private_sign(ident_key, signature, digest, 20) < 0) {
  915. log_fn(LOG_WARN, "Error signing digest");
  916. return -1;
  917. }
  918. strlcat(s+written, "-----BEGIN SIGNATURE-----\n", maxlen-written);
  919. written += strlen(s+written);
  920. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  921. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  922. return -1;
  923. }
  924. written += strlen(s+written);
  925. strlcat(s+written, "-----END SIGNATURE-----\n", maxlen-written);
  926. written += strlen(s+written);
  927. if (written+2 > maxlen)
  928. return -1;
  929. /* include a last '\n' */
  930. s[written] = '\n';
  931. s[written+1] = 0;
  932. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  933. cp = s_tmp = s_dup = tor_strdup(s);
  934. ri_tmp = router_parse_entry_from_string(cp, NULL);
  935. if (!ri_tmp) {
  936. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  937. s);
  938. return -1;
  939. }
  940. tor_free(s_dup);
  941. routerinfo_free(ri_tmp);
  942. #endif
  943. return written+1;
  944. }
  945. /** Return true iff <b>s</b> is a legally valid server nickname. */
  946. int
  947. is_legal_nickname(const char *s)
  948. {
  949. size_t len;
  950. tor_assert(s);
  951. len = strlen(s);
  952. return len > 0 && len <= MAX_NICKNAME_LEN &&
  953. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  954. }
  955. /** Return true iff <b>s</b> is a legally valid server nickname or
  956. * hex-encoded identity-key digest. */
  957. int
  958. is_legal_nickname_or_hexdigest(const char *s)
  959. {
  960. size_t len;
  961. tor_assert(s);
  962. if (*s!='$')
  963. return is_legal_nickname(s);
  964. len = strlen(s);
  965. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  966. }
  967. /** Release all resources held in router keys. */
  968. void
  969. router_free_all_keys(void)
  970. {
  971. if (onionkey)
  972. crypto_free_pk_env(onionkey);
  973. if (lastonionkey)
  974. crypto_free_pk_env(lastonionkey);
  975. if (identitykey)
  976. crypto_free_pk_env(identitykey);
  977. if (key_lock)
  978. tor_mutex_free(key_lock);
  979. if (desc_routerinfo)
  980. routerinfo_free(desc_routerinfo);
  981. }