router.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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. * 2. Clients should rotate their identity keys at least whenever
  226. * their IPs change.
  227. */
  228. char keydir[512];
  229. char keydir2[512];
  230. char fingerprint[FINGERPRINT_LEN+1];
  231. char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
  232. char *cp;
  233. const char *tmp, *mydesc, *datadir;
  234. crypto_pk_env_t *prkey;
  235. char digest[20];
  236. or_options_t *options = get_options();
  237. if (!key_lock)
  238. key_lock = tor_mutex_new();
  239. /* OP's don't need persistent keys; just make up an identity and
  240. * initialize the TLS context. */
  241. if (!server_mode(options)) {
  242. if (!(prkey = crypto_new_pk_env()))
  243. return -1;
  244. if (crypto_pk_generate_key(prkey))
  245. return -1;
  246. set_identity_key(prkey);
  247. /* Create a TLS context; default the client nickname to "client". */
  248. if (tor_tls_context_new(get_identity_key(), 1,
  249. options->Nickname ? options->Nickname : "client",
  250. MAX_SSL_KEY_LIFETIME) < 0) {
  251. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  252. return -1;
  253. }
  254. return 0;
  255. }
  256. /* Make sure DataDirectory exists, and is private. */
  257. datadir = options->DataDirectory;
  258. if (check_private_dir(datadir, CPD_CREATE)) {
  259. return -1;
  260. }
  261. /* Check the key directory. */
  262. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  263. if (check_private_dir(keydir, CPD_CREATE)) {
  264. return -1;
  265. }
  266. cp = keydir + strlen(keydir); /* End of string. */
  267. /* 1. Read identity key. Make it if none is found. */
  268. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  269. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  270. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir2);
  271. prkey = init_key_from_file_name_changed(keydir,keydir2);
  272. if (!prkey) return -1;
  273. set_identity_key(prkey);
  274. /* 2. Read onion key. Make it if none is found. */
  275. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  276. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  277. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir2);
  278. prkey = init_key_from_file_name_changed(keydir,keydir2);
  279. if (!prkey) return -1;
  280. set_onion_key(prkey);
  281. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  282. if (file_status(keydir) == FN_FILE) {
  283. prkey = init_key_from_file(keydir);
  284. if (prkey)
  285. lastonionkey = prkey;
  286. }
  287. /* 3. Initialize link key and TLS context. */
  288. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  289. MAX_SSL_KEY_LIFETIME) < 0) {
  290. log_fn(LOG_ERR, "Error initializing TLS context");
  291. return -1;
  292. }
  293. /* 4. Dump router descriptor to 'router.desc' */
  294. /* Must be called after keys are initialized. */
  295. tmp = mydesc = router_get_my_descriptor();
  296. if (!mydesc) {
  297. log_fn(LOG_ERR, "Error initializing descriptor.");
  298. return -1;
  299. }
  300. if (authdir_mode(options)) {
  301. const char *m;
  302. /* We need to add our own fingerprint so it gets recognized. */
  303. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  304. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  305. return -1;
  306. }
  307. if (dirserv_add_descriptor(&tmp, &m) != 1) {
  308. log(LOG_ERR, "Unable to add own descriptor to directory: %s",
  309. m?m:"<unknown error>");
  310. return -1;
  311. }
  312. }
  313. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  314. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  315. if (write_str_to_file(keydir, mydesc,0)) {
  316. return -1;
  317. }
  318. /* 5. Dump fingerprint to 'fingerprint' */
  319. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  320. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  321. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  322. log_fn(LOG_ERR, "Error computing fingerprint");
  323. return -1;
  324. }
  325. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  326. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  327. "%s %s\n",options->Nickname, fingerprint) < 0) {
  328. log_fn(LOG_ERR, "Error writing fingerprint line");
  329. return -1;
  330. }
  331. if (write_str_to_file(keydir, fingerprint_line, 0))
  332. return -1;
  333. if (!authdir_mode(options))
  334. return 0;
  335. /* 6. [authdirserver only] load approved-routers file */
  336. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  337. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  338. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  339. log_fn(LOG_ERR, "Error loading fingerprints");
  340. return -1;
  341. }
  342. /* 6b. [authdirserver only] add own key to approved directories. */
  343. crypto_pk_get_digest(get_identity_key(), digest);
  344. if (!router_digest_is_trusted_dir(digest)) {
  345. add_trusted_dir_server(options->Address, (uint16_t)options->DirPort, digest);
  346. }
  347. /* 7. [authdirserver only] load old directory, if it's there */
  348. tor_snprintf(keydir,sizeof(keydir),"%s/cached-directory", datadir);
  349. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  350. cp = read_file_to_str(keydir,0);
  351. if (!cp) {
  352. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  353. } else {
  354. if (dirserv_load_from_directory_string(cp) < 0) {
  355. log_fn(LOG_WARN, "Cached directory %s is corrupt, only loaded part of it.", keydir);
  356. tor_free(cp);
  357. return 0;
  358. }
  359. tor_free(cp);
  360. }
  361. /* success */
  362. return 0;
  363. }
  364. /* Keep track of whether we should upload our server descriptor,
  365. * and what type of server we are.
  366. */
  367. /** Whether we can reach our ORPort from the outside. */
  368. static int can_reach_or_port = 0;
  369. /** Whether we can reach our DirPort from the outside. */
  370. static int can_reach_dir_port = 0;
  371. /** Return 1 if or port is known reachable; else return 0. */
  372. int
  373. check_whether_orport_reachable(void)
  374. {
  375. return clique_mode(get_options()) || can_reach_or_port;
  376. }
  377. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  378. int
  379. check_whether_dirport_reachable(void)
  380. {
  381. return !get_options()->DirPort || can_reach_dir_port;
  382. }
  383. /**DOCDOC*/
  384. void
  385. consider_testing_reachability(void)
  386. {
  387. routerinfo_t *me = router_get_my_routerinfo();
  388. if (!me) {
  389. log_fn(LOG_WARN,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
  390. return;
  391. }
  392. if (!check_whether_orport_reachable()) {
  393. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  394. }
  395. if (!check_whether_dirport_reachable()) {
  396. if (me) {
  397. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_DIR, 1, NULL, NULL, 0);
  398. } else {
  399. log(LOG_NOTICE,"Delaying checking DirPort reachability; can't build descriptor.");
  400. }
  401. }
  402. }
  403. /** Annotate that we found our ORPort reachable. */
  404. void
  405. router_orport_found_reachable(void)
  406. {
  407. if (!can_reach_or_port) {
  408. if (!clique_mode(get_options()))
  409. log(LOG_NOTICE,"Your ORPort is reachable from the outside. Excellent.%s",
  410. get_options()->NoPublish ? "" : " Publishing server descriptor.");
  411. can_reach_or_port = 1;
  412. consider_publishable_server(time(NULL), 1);
  413. }
  414. }
  415. /** Annotate that we found our DirPort reachable. */
  416. void
  417. router_dirport_found_reachable(void)
  418. {
  419. if (!can_reach_dir_port) {
  420. log(LOG_NOTICE,"Your DirPort is reachable from the outside. Excellent.");
  421. can_reach_dir_port = 1;
  422. }
  423. }
  424. /** Our router has just moved to a new IP. Reset stats. */
  425. void
  426. server_has_changed_ip(void)
  427. {
  428. stats_n_seconds_working = 0;
  429. can_reach_or_port = 0;
  430. can_reach_dir_port = 0;
  431. mark_my_descriptor_dirty();
  432. }
  433. /** Return true iff we believe ourselves to be an authoritative
  434. * directory server.
  435. */
  436. int
  437. authdir_mode(or_options_t *options)
  438. {
  439. return options->AuthoritativeDir != 0;
  440. }
  441. /** Return true iff we try to stay connected to all ORs at once.
  442. */
  443. int
  444. clique_mode(or_options_t *options)
  445. {
  446. return authdir_mode(options);
  447. }
  448. /** Return true iff we are trying to be a server.
  449. */
  450. int
  451. server_mode(or_options_t *options)
  452. {
  453. if (options->ClientOnly) return 0;
  454. return (options->ORPort != 0 || options->ORBindAddress);
  455. }
  456. /** Remember if we've advertised ourselves to the dirservers. */
  457. static int server_is_advertised=0;
  458. /** Return true iff we have published our descriptor lately.
  459. */
  460. int
  461. advertised_server_mode(void)
  462. {
  463. return server_is_advertised;
  464. }
  465. /**
  466. * Called with a boolean: set whether we have recently published our descriptor.
  467. */
  468. static void
  469. set_server_advertised(int s)
  470. {
  471. server_is_advertised = s;
  472. }
  473. /** Return true iff we are trying to be a socks proxy. */
  474. int
  475. proxy_mode(or_options_t *options)
  476. {
  477. return (options->SocksPort != 0 || options->SocksBindAddress);
  478. }
  479. /** Decide if we're a publishable server. We are a publishable server if:
  480. * - We don't have the ClientOnly option set
  481. * and
  482. * - We don't have the NoPublish option set
  483. * and
  484. * - We have ORPort set
  485. * and
  486. * - We believe we are reachable from the outside; or
  487. * - We have the AuthoritativeDirectory option set.
  488. */
  489. static int
  490. decide_if_publishable_server(time_t now)
  491. {
  492. or_options_t *options = get_options();
  493. if (options->ClientOnly)
  494. return 0;
  495. if (options->NoPublish)
  496. return 0;
  497. if (!server_mode(options))
  498. return 0;
  499. if (options->AuthoritativeDir)
  500. return 1;
  501. return check_whether_orport_reachable();
  502. }
  503. /** Initiate server descriptor upload as reasonable (if server is publishable,
  504. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  505. */
  506. void
  507. consider_publishable_server(time_t now, int force)
  508. {
  509. if (decide_if_publishable_server(now)) {
  510. set_server_advertised(1);
  511. if (router_rebuild_descriptor(force) == 0)
  512. router_upload_dir_desc_to_dirservers(force);
  513. } else {
  514. set_server_advertised(0);
  515. }
  516. }
  517. /*
  518. * Clique maintenance
  519. */
  520. /** OR only: if in clique mode, try to open connections to all of the
  521. * other ORs we know about. Otherwise, open connections to those we
  522. * think are in clique mode.
  523. */
  524. void
  525. router_retry_connections(void)
  526. {
  527. int i;
  528. routerinfo_t *router;
  529. routerlist_t *rl;
  530. or_options_t *options = get_options();
  531. tor_assert(server_mode(options));
  532. router_get_routerlist(&rl);
  533. if (!rl) return;
  534. for (i=0;i < smartlist_len(rl->routers);i++) {
  535. router = smartlist_get(rl->routers, i);
  536. if (router_is_me(router))
  537. continue;
  538. if (!clique_mode(options) && !router_is_clique_mode(router))
  539. continue;
  540. if (!connection_get_by_identity_digest(router->identity_digest,
  541. CONN_TYPE_OR)) {
  542. /* not in the list */
  543. log_fn(LOG_DEBUG,"connecting to OR at %s:%u.",router->address,router->or_port);
  544. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  545. }
  546. }
  547. }
  548. /** Return true iff this OR should try to keep connections open to all
  549. * other ORs. */
  550. int
  551. router_is_clique_mode(routerinfo_t *router)
  552. {
  553. if (router_digest_is_trusted_dir(router->identity_digest))
  554. return 1;
  555. return 0;
  556. }
  557. /*
  558. * OR descriptor generation.
  559. */
  560. /** My routerinfo. */
  561. static routerinfo_t *desc_routerinfo = NULL;
  562. /** Boolean: do we need to regenerate the above? */
  563. static int desc_is_dirty = 1;
  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 false if we accept; true 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_is_dirty && !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);
  684. config_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_is_dirty = 0;
  702. desc_needs_upload = 1;
  703. return 0;
  704. }
  705. /** Call when the current descriptor is out of date. */
  706. void
  707. mark_my_descriptor_dirty(void)
  708. {
  709. desc_is_dirty = 1;
  710. }
  711. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  712. * string describing the version of Tor and the operating system we're
  713. * currently running on.
  714. */
  715. void
  716. get_platform_str(char *platform, size_t len)
  717. {
  718. tor_snprintf(platform, len, "Tor %s on %s",
  719. VERSION, get_uname());
  720. return;
  721. }
  722. /* XXX need to audit this thing and count fenceposts. maybe
  723. * refactor so we don't have to keep asking if we're
  724. * near the end of maxlen?
  725. */
  726. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  727. /** OR only: Given a routerinfo for this router, and an identity key to sign
  728. * with, encode the routerinfo as a signed server descriptor and write the
  729. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  730. * failure, and the number of bytes used on success.
  731. */
  732. int
  733. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  734. crypto_pk_env_t *ident_key)
  735. {
  736. char *onion_pkey; /* Onion key, PEM-encoded. */
  737. char *identity_pkey; /* Identity key, PEM-encoded. */
  738. char digest[20];
  739. char signature[128];
  740. char published[32];
  741. char fingerprint[FINGERPRINT_LEN+1];
  742. struct in_addr in;
  743. char addrbuf[INET_NTOA_BUF_LEN];
  744. size_t onion_pkeylen, identity_pkeylen;
  745. size_t written;
  746. int result=0;
  747. addr_policy_t *tmpe;
  748. char *bandwidth_usage;
  749. char *family_line;
  750. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  751. char *s_tmp, *s_dup;
  752. const char *cp;
  753. routerinfo_t *ri_tmp;
  754. #endif
  755. /* Make sure the identity key matches the one in the routerinfo. */
  756. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  757. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  758. return -1;
  759. }
  760. /* record our fingerprint, so we can include it in the descriptor */
  761. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  762. log_fn(LOG_ERR, "Error computing fingerprint");
  763. return -1;
  764. }
  765. /* PEM-encode the onion key */
  766. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  767. &onion_pkey,&onion_pkeylen)<0) {
  768. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  769. return -1;
  770. }
  771. /* PEM-encode the identity key key */
  772. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  773. &identity_pkey,&identity_pkeylen)<0) {
  774. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  775. tor_free(onion_pkey);
  776. return -1;
  777. }
  778. /* Encode the publication time. */
  779. format_iso_time(published, router->published_on);
  780. /* How busy have we been? */
  781. bandwidth_usage = rep_hist_get_bandwidth_lines();
  782. if (router->declared_family && smartlist_len(router->declared_family)) {
  783. size_t n;
  784. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  785. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  786. family_line = tor_malloc(n);
  787. tor_snprintf(family_line, n, "family %s\n", s);
  788. tor_free(s);
  789. } else {
  790. family_line = tor_strdup("");
  791. }
  792. /* Generate the easy portion of the router descriptor. */
  793. result = tor_snprintf(s, maxlen,
  794. "router %s %s %d 0 %d\n"
  795. "platform %s\n"
  796. "published %s\n"
  797. "opt fingerprint %s\n"
  798. "uptime %ld\n"
  799. "bandwidth %d %d %d\n"
  800. "onion-key\n%s"
  801. "signing-key\n%s%s%s%s",
  802. router->nickname,
  803. router->address,
  804. router->or_port,
  805. check_whether_dirport_reachable() ? router->dir_port : 0,
  806. router->platform,
  807. published,
  808. fingerprint,
  809. stats_n_seconds_working,
  810. (int) router->bandwidthrate,
  811. (int) router->bandwidthburst,
  812. (int) router->bandwidthcapacity,
  813. onion_pkey, identity_pkey,
  814. family_line, bandwidth_usage,
  815. we_are_hibernating() ? "opt hibernating 1\n" : "");
  816. tor_free(family_line);
  817. tor_free(onion_pkey);
  818. tor_free(identity_pkey);
  819. tor_free(bandwidth_usage);
  820. if (result < 0)
  821. return -1;
  822. /* From now on, we use 'written' to remember the current length of 's'. */
  823. written = result;
  824. if (get_options()->ContactInfo && strlen(get_options()->ContactInfo)) {
  825. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  826. get_options()->ContactInfo);
  827. if (result<0)
  828. return -1;
  829. written += result;
  830. }
  831. /* Write the exit policy to the end of 's'. */
  832. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  833. /* Write: "accept 1.2.3.4" */
  834. in.s_addr = htonl(tmpe->addr);
  835. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  836. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  837. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  838. tmpe->msk == 0 ? "*" : addrbuf);
  839. if (result < 0)
  840. return -1;
  841. written += result;
  842. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  843. /* Write "/255.255.0.0" */
  844. in.s_addr = htonl(tmpe->msk);
  845. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  846. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  847. if (result<0)
  848. return -1;
  849. written += result;
  850. }
  851. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  852. /* There is no port set; write ":*" */
  853. if (written+4 > maxlen)
  854. return -1;
  855. strlcat(s+written, ":*\n", maxlen-written);
  856. written += 3;
  857. } else if (tmpe->prt_min == tmpe->prt_max) {
  858. /* There is only one port; write ":80". */
  859. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  860. if (result<0)
  861. return -1;
  862. written += result;
  863. } else {
  864. /* There is a range of ports; write ":79-80". */
  865. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  866. tmpe->prt_max);
  867. if (result<0)
  868. return -1;
  869. written += result;
  870. }
  871. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  872. /* This was a catch-all rule, so future rules are irrelevant. */
  873. break;
  874. } /* end for */
  875. if (written+256 > maxlen) /* Not enough room for signature. */
  876. return -1;
  877. /* Sign the directory */
  878. strlcat(s+written, "router-signature\n", maxlen-written);
  879. written += strlen(s+written);
  880. s[written] = '\0';
  881. if (router_get_router_hash(s, digest) < 0)
  882. return -1;
  883. if (crypto_pk_private_sign(ident_key, signature, digest, 20) < 0) {
  884. log_fn(LOG_WARN, "Error signing digest");
  885. return -1;
  886. }
  887. strlcat(s+written, "-----BEGIN SIGNATURE-----\n", maxlen-written);
  888. written += strlen(s+written);
  889. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  890. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  891. return -1;
  892. }
  893. written += strlen(s+written);
  894. strlcat(s+written, "-----END SIGNATURE-----\n", maxlen-written);
  895. written += strlen(s+written);
  896. if (written+2 > maxlen)
  897. return -1;
  898. /* include a last '\n' */
  899. s[written] = '\n';
  900. s[written+1] = 0;
  901. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  902. cp = s_tmp = s_dup = tor_strdup(s);
  903. ri_tmp = router_parse_entry_from_string(cp, NULL);
  904. if (!ri_tmp) {
  905. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  906. s);
  907. return -1;
  908. }
  909. tor_free(s_dup);
  910. routerinfo_free(ri_tmp);
  911. #endif
  912. return written+1;
  913. }
  914. /** Return true iff <b>s</b> is a legally valid server nickname. */
  915. int
  916. is_legal_nickname(const char *s)
  917. {
  918. size_t len;
  919. tor_assert(s);
  920. len = strlen(s);
  921. return len > 0 && len <= MAX_NICKNAME_LEN &&
  922. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  923. }
  924. /** Return true iff <b>s</b> is a legally valid server nickname or
  925. * hex-encoded identity-key digest. */
  926. int
  927. is_legal_nickname_or_hexdigest(const char *s)
  928. {
  929. size_t len;
  930. tor_assert(s);
  931. if (*s!='$')
  932. return is_legal_nickname(s);
  933. len = strlen(s);
  934. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  935. }
  936. /** Release all resources held in router keys. */
  937. void
  938. router_free_all_keys(void)
  939. {
  940. if (onionkey)
  941. crypto_free_pk_env(onionkey);
  942. if (lastonionkey)
  943. crypto_free_pk_env(lastonionkey);
  944. if (identitykey)
  945. crypto_free_pk_env(identitykey);
  946. if (key_lock)
  947. tor_mutex_free(key_lock);
  948. if (desc_routerinfo)
  949. routerinfo_free(desc_routerinfo);
  950. }