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. */
  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. consider_publishable_server(time(NULL), 1);
  411. }
  412. }
  413. /** Annotate that we found our DirPort reachable. */
  414. void
  415. router_dirport_found_reachable(void)
  416. {
  417. if (!can_reach_dir_port) {
  418. log(LOG_NOTICE,"Your DirPort is reachable from the outside. Excellent.");
  419. can_reach_dir_port = 1;
  420. }
  421. }
  422. /** Our router has just moved to a new IP. Reset stats. */
  423. void
  424. server_has_changed_ip(void)
  425. {
  426. stats_n_seconds_working = 0;
  427. can_reach_or_port = 0;
  428. can_reach_dir_port = 0;
  429. mark_my_descriptor_dirty();
  430. }
  431. /** Return true iff we believe ourselves to be an authoritative
  432. * directory server.
  433. */
  434. int
  435. authdir_mode(or_options_t *options)
  436. {
  437. return options->AuthoritativeDir != 0;
  438. }
  439. /** Return true iff we try to stay connected to all ORs at once.
  440. */
  441. int
  442. clique_mode(or_options_t *options)
  443. {
  444. return authdir_mode(options);
  445. }
  446. /** Return true iff we are trying to be a server.
  447. */
  448. int
  449. server_mode(or_options_t *options)
  450. {
  451. if (options->ClientOnly) return 0;
  452. return (options->ORPort != 0 || options->ORBindAddress);
  453. }
  454. /** Remember if we've advertised ourselves to the dirservers. */
  455. static int server_is_advertised=0;
  456. /** Return true iff we have published our descriptor lately.
  457. */
  458. int
  459. advertised_server_mode(void)
  460. {
  461. return server_is_advertised;
  462. }
  463. /**
  464. * Called with a boolean: set whether we have recently published our descriptor.
  465. */
  466. static void
  467. set_server_advertised(int s)
  468. {
  469. server_is_advertised = s;
  470. }
  471. /** Return true iff we are trying to be a socks proxy. */
  472. int
  473. proxy_mode(or_options_t *options)
  474. {
  475. return (options->SocksPort != 0 || options->SocksBindAddress);
  476. }
  477. /** Decide if we're a publishable server. We are a publishable server if:
  478. * - We don't have the ClientOnly option set
  479. * and
  480. * - We don't have the NoPublish option set
  481. * and
  482. * - We have ORPort set
  483. * and
  484. * - We believe we are reachable from the outside; or
  485. * - We have the AuthoritativeDirectory option set.
  486. */
  487. static int
  488. decide_if_publishable_server(time_t now)
  489. {
  490. or_options_t *options = get_options();
  491. if (options->ClientOnly)
  492. return 0;
  493. if (options->NoPublish)
  494. return 0;
  495. if (!server_mode(options))
  496. return 0;
  497. if (options->AuthoritativeDir)
  498. return 1;
  499. return check_whether_orport_reachable();
  500. }
  501. /** Initiate server descriptor upload as reasonable (if server is publishable,
  502. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  503. */
  504. void
  505. consider_publishable_server(time_t now, int force)
  506. {
  507. if (decide_if_publishable_server(now)) {
  508. set_server_advertised(1);
  509. if (router_rebuild_descriptor(force) == 0)
  510. router_upload_dir_desc_to_dirservers(force);
  511. } else {
  512. set_server_advertised(0);
  513. }
  514. }
  515. /*
  516. * Clique maintenance
  517. */
  518. /** OR only: if in clique mode, try to open connections to all of the
  519. * other ORs we know about. Otherwise, open connections to those we
  520. * think are in clique mode.
  521. */
  522. void
  523. router_retry_connections(void)
  524. {
  525. int i;
  526. routerinfo_t *router;
  527. routerlist_t *rl;
  528. or_options_t *options = get_options();
  529. tor_assert(server_mode(options));
  530. router_get_routerlist(&rl);
  531. if (!rl) return;
  532. for (i=0;i < smartlist_len(rl->routers);i++) {
  533. router = smartlist_get(rl->routers, i);
  534. if (router_is_me(router))
  535. continue;
  536. if (!clique_mode(options) && !router_is_clique_mode(router))
  537. continue;
  538. if (!connection_get_by_identity_digest(router->identity_digest,
  539. CONN_TYPE_OR)) {
  540. /* not in the list */
  541. log_fn(LOG_DEBUG,"connecting to OR at %s:%u.",router->address,router->or_port);
  542. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  543. }
  544. }
  545. }
  546. /** Return true iff this OR should try to keep connections open to all
  547. * other ORs. */
  548. int
  549. router_is_clique_mode(routerinfo_t *router)
  550. {
  551. if (router_digest_is_trusted_dir(router->identity_digest))
  552. return 1;
  553. return 0;
  554. }
  555. /*
  556. * OR descriptor generation.
  557. */
  558. /** My routerinfo. */
  559. static routerinfo_t *desc_routerinfo = NULL;
  560. /** Boolean: do we need to regenerate the above? */
  561. static int desc_is_dirty = 1;
  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 a routerinfo for this OR, rebuilding a fresh one if
  613. * necessary. Return NULL on error, or if called on an OP. */
  614. routerinfo_t *
  615. router_get_my_routerinfo(void)
  616. {
  617. if (!server_mode(get_options()))
  618. return NULL;
  619. if (!desc_routerinfo) {
  620. if (router_rebuild_descriptor(1))
  621. return NULL;
  622. }
  623. return desc_routerinfo;
  624. }
  625. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  626. * one if necessary. Return NULL on error.
  627. */
  628. const char *
  629. router_get_my_descriptor(void)
  630. {
  631. if (!desc_routerinfo) {
  632. if (router_rebuild_descriptor(1))
  633. return NULL;
  634. }
  635. log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
  636. return desc_routerinfo->signed_descriptor;
  637. }
  638. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  639. * a fresh routerinfo and signed server descriptor for this OR.
  640. * Return 0 on success, -1 on error.
  641. */
  642. int
  643. router_rebuild_descriptor(int force)
  644. {
  645. routerinfo_t *ri;
  646. uint32_t addr;
  647. char platform[256];
  648. struct in_addr in;
  649. int hibernating = we_are_hibernating();
  650. or_options_t *options = get_options();
  651. char addrbuf[INET_NTOA_BUF_LEN];
  652. if (!desc_is_dirty && !force)
  653. return 0;
  654. if (resolve_my_address(options, &addr) < 0) {
  655. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  656. return -1;
  657. }
  658. ri = tor_malloc_zero(sizeof(routerinfo_t));
  659. in.s_addr = htonl(addr);
  660. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  661. ri->address = tor_strdup(addrbuf);
  662. ri->nickname = tor_strdup(options->Nickname);
  663. ri->addr = addr;
  664. ri->or_port = options->ORPort;
  665. ri->dir_port = hibernating ?
  666. 0 : options->DirPort;
  667. ri->published_on = time(NULL);
  668. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  669. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  670. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  671. routerinfo_free(ri);
  672. return -1;
  673. }
  674. get_platform_str(platform, sizeof(platform));
  675. ri->platform = tor_strdup(platform);
  676. ri->bandwidthrate = (int)options->BandwidthRate;
  677. ri->bandwidthburst = (int)options->BandwidthBurst;
  678. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  679. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  680. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  681. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy);
  682. options_append_default_exit_policy(&ri->exit_policy);
  683. if (desc_routerinfo) /* inherit values */
  684. ri->is_verified = desc_routerinfo->is_verified;
  685. if (options->MyFamily) {
  686. ri->declared_family = smartlist_create();
  687. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  688. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  689. }
  690. ri->signed_descriptor = tor_malloc(8192);
  691. if (router_dump_router_to_string(ri->signed_descriptor, 8192,
  692. ri, get_identity_key())<0) {
  693. log_fn(LOG_WARN, "Couldn't dump router to string.");
  694. return -1;
  695. }
  696. if (desc_routerinfo)
  697. routerinfo_free(desc_routerinfo);
  698. desc_routerinfo = ri;
  699. desc_is_dirty = 0;
  700. desc_needs_upload = 1;
  701. return 0;
  702. }
  703. /** Call when the current descriptor is out of date. */
  704. void
  705. mark_my_descriptor_dirty(void)
  706. {
  707. desc_is_dirty = 1;
  708. }
  709. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  710. * string describing the version of Tor and the operating system we're
  711. * currently running on.
  712. */
  713. void
  714. get_platform_str(char *platform, size_t len)
  715. {
  716. tor_snprintf(platform, len, "Tor %s on %s",
  717. VERSION, get_uname());
  718. return;
  719. }
  720. /* XXX need to audit this thing and count fenceposts. maybe
  721. * refactor so we don't have to keep asking if we're
  722. * near the end of maxlen?
  723. */
  724. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  725. /** OR only: Given a routerinfo for this router, and an identity key to sign
  726. * with, encode the routerinfo as a signed server descriptor and write the
  727. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  728. * failure, and the number of bytes used on success.
  729. */
  730. int
  731. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  732. crypto_pk_env_t *ident_key)
  733. {
  734. char *onion_pkey; /* Onion key, PEM-encoded. */
  735. char *identity_pkey; /* Identity key, PEM-encoded. */
  736. char digest[20];
  737. char signature[128];
  738. char published[32];
  739. char fingerprint[FINGERPRINT_LEN+1];
  740. struct in_addr in;
  741. char addrbuf[INET_NTOA_BUF_LEN];
  742. size_t onion_pkeylen, identity_pkeylen;
  743. size_t written;
  744. int result=0;
  745. addr_policy_t *tmpe;
  746. char *bandwidth_usage;
  747. char *family_line;
  748. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  749. char *s_tmp, *s_dup;
  750. const char *cp;
  751. routerinfo_t *ri_tmp;
  752. #endif
  753. or_options_t *options = get_options();
  754. /* Make sure the identity key matches the one in the routerinfo. */
  755. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  756. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  757. return -1;
  758. }
  759. /* record our fingerprint, so we can include it in the descriptor */
  760. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  761. log_fn(LOG_ERR, "Error computing fingerprint");
  762. return -1;
  763. }
  764. /* PEM-encode the onion key */
  765. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  766. &onion_pkey,&onion_pkeylen)<0) {
  767. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  768. return -1;
  769. }
  770. /* PEM-encode the identity key key */
  771. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  772. &identity_pkey,&identity_pkeylen)<0) {
  773. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  774. tor_free(onion_pkey);
  775. return -1;
  776. }
  777. /* Encode the publication time. */
  778. format_iso_time(published, router->published_on);
  779. /* How busy have we been? */
  780. bandwidth_usage = rep_hist_get_bandwidth_lines();
  781. if (router->declared_family && smartlist_len(router->declared_family)) {
  782. size_t n;
  783. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  784. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  785. family_line = tor_malloc(n);
  786. tor_snprintf(family_line, n, "family %s\n", s);
  787. tor_free(s);
  788. } else {
  789. family_line = tor_strdup("");
  790. }
  791. /* Generate the easy portion of the router descriptor. */
  792. result = tor_snprintf(s, maxlen,
  793. "router %s %s %d 0 %d\n"
  794. "platform %s\n"
  795. "published %s\n"
  796. "opt fingerprint %s\n"
  797. "uptime %ld\n"
  798. "bandwidth %d %d %d\n"
  799. "onion-key\n%s"
  800. "signing-key\n%s%s%s%s",
  801. router->nickname,
  802. router->address,
  803. router->or_port,
  804. (authdir_mode(options) || check_whether_dirport_reachable()) ?
  805. 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 (options->ContactInfo && strlen(options->ContactInfo)) {
  825. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  826. 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. }