router.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] =
  7. "$Id$";
  8. #define ROUTER_PRIVATE
  9. #include "or.h"
  10. /**
  11. * \file router.c
  12. * \brief OR functionality, including key maintenance, generating
  13. * and uploading server descriptors, retrying OR connections.
  14. **/
  15. extern long stats_n_seconds_working;
  16. /************************************************************/
  17. /*****
  18. * Key management: ORs only.
  19. *****/
  20. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  21. */
  22. static tor_mutex_t *key_lock=NULL;
  23. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  24. /** Current private onionskin decryption key: used to decode CREATE cells. */
  25. static crypto_pk_env_t *onionkey=NULL;
  26. /** Previous private onionskin decription key: used to decode CREATE cells
  27. * generated by clients that have an older version of our descriptor. */
  28. static crypto_pk_env_t *lastonionkey=NULL;
  29. /** Private "identity key": used to sign directory info and TLS
  30. * certificates. Never changes. */
  31. static crypto_pk_env_t *identitykey=NULL;
  32. /** Digest of identitykey. */
  33. static char identitykey_digest[DIGEST_LEN];
  34. /** Signing key used for v3 directory material; only set for authorities. */
  35. static crypto_pk_env_t *authority_signing_key = NULL;
  36. /** Key certificate to authenticate v3 directory material; only set for
  37. * authorities. */
  38. static authority_cert_t *authority_key_certificate = NULL;
  39. /* (Note that v3 authorities also have a separate "authority identity key",
  40. * but this key is never actually loaded by the Tor process. Instead, it's
  41. * used by tor-gencert to sign new signing keys and make new key
  42. * certificates. */
  43. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  44. * to update onionkey correctly, call rotate_onion_key().
  45. */
  46. static void
  47. set_onion_key(crypto_pk_env_t *k)
  48. {
  49. tor_mutex_acquire(key_lock);
  50. onionkey = k;
  51. onionkey_set_at = time(NULL);
  52. tor_mutex_release(key_lock);
  53. mark_my_descriptor_dirty();
  54. }
  55. /** Return the current onion key. Requires that the onion key has been
  56. * loaded or generated. */
  57. crypto_pk_env_t *
  58. get_onion_key(void)
  59. {
  60. tor_assert(onionkey);
  61. return onionkey;
  62. }
  63. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  64. * of the most recent onion key into *<b>last</b>.
  65. */
  66. void
  67. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  68. {
  69. tor_assert(key);
  70. tor_assert(last);
  71. tor_mutex_acquire(key_lock);
  72. tor_assert(onionkey);
  73. *key = crypto_pk_dup_key(onionkey);
  74. if (lastonionkey)
  75. *last = crypto_pk_dup_key(lastonionkey);
  76. else
  77. *last = NULL;
  78. tor_mutex_release(key_lock);
  79. }
  80. /** Return the time when the onion key was last set. This is either the time
  81. * when the process launched, or the time of the most recent key rotation since
  82. * the process launched.
  83. */
  84. time_t
  85. get_onion_key_set_at(void)
  86. {
  87. return onionkey_set_at;
  88. }
  89. /** Set the current identity key to k.
  90. */
  91. void
  92. set_identity_key(crypto_pk_env_t *k)
  93. {
  94. if (identitykey)
  95. crypto_free_pk_env(identitykey);
  96. identitykey = k;
  97. crypto_pk_get_digest(identitykey, identitykey_digest);
  98. }
  99. /** Returns the current identity key; requires that the identity key has been
  100. * set.
  101. */
  102. crypto_pk_env_t *
  103. get_identity_key(void)
  104. {
  105. tor_assert(identitykey);
  106. return identitykey;
  107. }
  108. /** Return true iff the identity key has been set. */
  109. int
  110. identity_key_is_set(void)
  111. {
  112. return identitykey != NULL;
  113. }
  114. /** Return the key certificate for this v3 (voting) authority, or NULL
  115. * if we have no such certificate. */
  116. authority_cert_t *
  117. get_my_v3_authority_cert(void)
  118. {
  119. return authority_key_certificate;
  120. }
  121. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  122. * if we have no such key. */
  123. crypto_pk_env_t *
  124. get_my_v3_authority_signing_key(void)
  125. {
  126. return authority_signing_key;
  127. }
  128. /** Replace the previous onion key with the current onion key, and generate
  129. * a new previous onion key. Immediately after calling this function,
  130. * the OR should:
  131. * - schedule all previous cpuworkers to shut down _after_ processing
  132. * pending work. (This will cause fresh cpuworkers to be generated.)
  133. * - generate and upload a fresh routerinfo.
  134. */
  135. void
  136. rotate_onion_key(void)
  137. {
  138. char fname[512];
  139. char fname_prev[512];
  140. crypto_pk_env_t *prkey;
  141. or_state_t *state = get_or_state();
  142. time_t now;
  143. tor_snprintf(fname,sizeof(fname),
  144. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",
  145. get_options()->DataDirectory);
  146. tor_snprintf(fname_prev,sizeof(fname_prev),
  147. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key.old",
  148. get_options()->DataDirectory);
  149. if (!(prkey = crypto_new_pk_env())) {
  150. log_err(LD_GENERAL,"Error constructing rotated onion key");
  151. goto error;
  152. }
  153. if (crypto_pk_generate_key(prkey)) {
  154. log_err(LD_BUG,"Error generating onion key");
  155. goto error;
  156. }
  157. if (file_status(fname) == FN_FILE) {
  158. if (replace_file(fname, fname_prev))
  159. goto error;
  160. }
  161. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  162. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  163. goto error;
  164. }
  165. log_info(LD_GENERAL, "Rotating onion key");
  166. tor_mutex_acquire(key_lock);
  167. if (lastonionkey)
  168. crypto_free_pk_env(lastonionkey);
  169. lastonionkey = onionkey;
  170. onionkey = prkey;
  171. now = time(NULL);
  172. state->LastRotatedOnionKey = onionkey_set_at = now;
  173. tor_mutex_release(key_lock);
  174. mark_my_descriptor_dirty();
  175. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  176. return;
  177. error:
  178. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  179. }
  180. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  181. * and <b>generate</b> is true, create a new RSA key and save it in
  182. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  183. * errors at level <b>severity</b>.
  184. */
  185. crypto_pk_env_t *
  186. init_key_from_file(const char *fname, int generate, int severity)
  187. {
  188. crypto_pk_env_t *prkey = NULL;
  189. FILE *file = NULL;
  190. if (!(prkey = crypto_new_pk_env())) {
  191. log(severity, LD_GENERAL,"Error constructing key");
  192. goto error;
  193. }
  194. switch (file_status(fname)) {
  195. case FN_DIR:
  196. case FN_ERROR:
  197. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  198. goto error;
  199. case FN_NOENT:
  200. if (generate) {
  201. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  202. fname);
  203. if (crypto_pk_generate_key(prkey)) {
  204. log(severity, LD_GENERAL,"Error generating onion key");
  205. goto error;
  206. }
  207. if (crypto_pk_check_key(prkey) <= 0) {
  208. log(severity, LD_GENERAL,"Generated key seems invalid");
  209. goto error;
  210. }
  211. log_info(LD_GENERAL, "Generated key seems valid");
  212. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  213. log(severity, LD_FS,
  214. "Couldn't write generated key to \"%s\".", fname);
  215. goto error;
  216. }
  217. } else {
  218. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  219. }
  220. return prkey;
  221. case FN_FILE:
  222. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  223. log(severity, LD_GENERAL,"Error loading private key.");
  224. goto error;
  225. }
  226. return prkey;
  227. default:
  228. tor_assert(0);
  229. }
  230. error:
  231. if (prkey)
  232. crypto_free_pk_env(prkey);
  233. if (file)
  234. fclose(file);
  235. return NULL;
  236. }
  237. /** Load the v3 (voting) authority signing key and certificate from
  238. * <b>keydir</b>, if they are present. */
  239. /* XXXX020 maybe move to dirserv.c */
  240. static void
  241. init_v3_authority_keys(const char *keydir)
  242. {
  243. char *fname = NULL, *cert = NULL;
  244. const char *eos = NULL;
  245. size_t fname_len = strlen(keydir) + 64;
  246. crypto_pk_env_t *signing_key = NULL;
  247. authority_cert_t *parsed = NULL;
  248. fname = tor_malloc(fname_len);
  249. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"authority_signing_key",
  250. keydir);
  251. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  252. if (!signing_key) {
  253. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  254. goto done;
  255. }
  256. tor_snprintf(fname, fname_len, "%s"PATH_SEPARATOR"authority_certificate",
  257. keydir);
  258. cert = read_file_to_str(fname, 0, NULL);
  259. if (!cert) {
  260. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  261. fname);
  262. goto done;
  263. }
  264. parsed = authority_cert_parse_from_string(cert, &eos);
  265. if (!parsed) {
  266. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  267. goto done;
  268. }
  269. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  270. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  271. "certificate");
  272. goto done;
  273. }
  274. parsed->cache_info.signed_descriptor_body = cert;
  275. parsed->cache_info.signed_descriptor_len = eos-cert;
  276. cert = NULL;
  277. authority_key_certificate = parsed;
  278. authority_signing_key = signing_key;
  279. parsed = NULL;
  280. signing_key = NULL;
  281. done:
  282. tor_free(fname);
  283. tor_free(cert);
  284. if (signing_key)
  285. crypto_free_pk_env(signing_key);
  286. if (parsed)
  287. authority_cert_free(parsed);
  288. }
  289. /** Initialize all OR private keys, and the TLS context, as necessary.
  290. * On OPs, this only initializes the tls context. Return 0 on success,
  291. * or -1 if Tor should die.
  292. */
  293. int
  294. init_keys(void)
  295. {
  296. char keydir[512];
  297. char fingerprint[FINGERPRINT_LEN+1];
  298. /*nickname<space>fp\n\0 */
  299. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  300. const char *mydesc, *datadir;
  301. crypto_pk_env_t *prkey;
  302. char digest[20];
  303. char v3_digest[20];
  304. char *cp;
  305. or_options_t *options = get_options();
  306. or_state_t *state = get_or_state();
  307. authority_type_t type;
  308. time_t now = time(NULL);
  309. if (!key_lock)
  310. key_lock = tor_mutex_new();
  311. /* OP's don't need persistent keys; just make up an identity and
  312. * initialize the TLS context. */
  313. if (!server_mode(options)) {
  314. if (!(prkey = crypto_new_pk_env()))
  315. return -1;
  316. if (crypto_pk_generate_key(prkey))
  317. return -1;
  318. set_identity_key(prkey);
  319. /* Create a TLS context; default the client nickname to "client". */
  320. if (tor_tls_context_new(get_identity_key(),
  321. options->Nickname ? options->Nickname : "client",
  322. MAX_SSL_KEY_LIFETIME) < 0) {
  323. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  324. return -1;
  325. }
  326. return 0;
  327. }
  328. /* Make sure DataDirectory exists, and is private. */
  329. datadir = options->DataDirectory;
  330. if (check_private_dir(datadir, CPD_CREATE)) {
  331. return -1;
  332. }
  333. /* Check the key directory. */
  334. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"keys", datadir);
  335. if (check_private_dir(keydir, CPD_CREATE)) {
  336. return -1;
  337. }
  338. /* 1a. Read v3 directory authority key/cert information. */
  339. memset(v3_digest, 0, sizeof(v3_digest));
  340. if (authdir_mode_v3(options)) {
  341. init_v3_authority_keys(keydir);
  342. if (get_my_v3_authority_cert()) {
  343. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  344. v3_digest);
  345. }
  346. }
  347. /* 1. Read identity key. Make it if none is found. */
  348. tor_snprintf(keydir,sizeof(keydir),
  349. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_id_key",datadir);
  350. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  351. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  352. if (!prkey) return -1;
  353. set_identity_key(prkey);
  354. /* 2. Read onion key. Make it if none is found. */
  355. tor_snprintf(keydir,sizeof(keydir),
  356. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",datadir);
  357. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  358. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  359. if (!prkey) return -1;
  360. set_onion_key(prkey);
  361. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  362. /* We allow for some parsing slop, but we don't want to risk accepting
  363. * values in the distant future. If we did, we might never rotate the
  364. * onion key. */
  365. onionkey_set_at = state->LastRotatedOnionKey;
  366. } else {
  367. /* We have no LastRotatedOnionKey set; either we just created the key
  368. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  369. * start the clock ticking now so that we will eventually rotate it even
  370. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  371. state->LastRotatedOnionKey = onionkey_set_at = now;
  372. or_state_mark_dirty(state, options->AvoidDiskWrites ? time(NULL)+3600 : 0);
  373. }
  374. tor_snprintf(keydir,sizeof(keydir),
  375. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key.old",datadir);
  376. if (file_status(keydir) == FN_FILE) {
  377. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  378. if (prkey)
  379. lastonionkey = prkey;
  380. }
  381. /* 3. Initialize link key and TLS context. */
  382. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  383. MAX_SSL_KEY_LIFETIME) < 0) {
  384. log_err(LD_GENERAL,"Error initializing TLS context");
  385. return -1;
  386. }
  387. /* 4. Build our router descriptor. */
  388. /* Must be called after keys are initialized. */
  389. mydesc = router_get_my_descriptor();
  390. if (authdir_mode(options)) {
  391. const char *m;
  392. routerinfo_t *ri;
  393. /* We need to add our own fingerprint so it gets recognized. */
  394. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  395. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  396. return -1;
  397. }
  398. if (mydesc) {
  399. ri = router_parse_entry_from_string(mydesc, NULL, 1);
  400. if (!ri) {
  401. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  402. return -1;
  403. }
  404. if (dirserv_add_descriptor(ri, &m) < 0) {
  405. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  406. m?m:"<unknown error>");
  407. return -1;
  408. }
  409. }
  410. }
  411. /* 5. Dump fingerprint to 'fingerprint' */
  412. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"fingerprint", datadir);
  413. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  414. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  415. log_err(LD_GENERAL,"Error computing fingerprint");
  416. return -1;
  417. }
  418. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  419. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  420. "%s %s\n",options->Nickname, fingerprint) < 0) {
  421. log_err(LD_GENERAL,"Error writing fingerprint line");
  422. return -1;
  423. }
  424. /* Check whether we need to write the fingerprint file. */
  425. cp = NULL;
  426. if (file_status(keydir) == FN_FILE)
  427. cp = read_file_to_str(keydir, 0, NULL);
  428. if (!cp || strcmp(cp, fingerprint_line)) {
  429. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  430. log_err(LD_FS, "Error writing fingerprint line to file");
  431. return -1;
  432. }
  433. }
  434. tor_free(cp);
  435. log(LOG_NOTICE, LD_GENERAL,
  436. "Your Tor server's identity key fingerprint is '%s %s'",
  437. options->Nickname, fingerprint);
  438. if (!authdir_mode(options))
  439. return 0;
  440. /* 6. [authdirserver only] load approved-routers file */
  441. if (dirserv_load_fingerprint_file() < 0) {
  442. log_err(LD_GENERAL,"Error loading fingerprints");
  443. return -1;
  444. }
  445. /* 6b. [authdirserver only] add own key to approved directories. */
  446. crypto_pk_get_digest(get_identity_key(), digest);
  447. type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : 0) |
  448. (options->V2AuthoritativeDir ? V2_AUTHORITY : 0) |
  449. (options->V3AuthoritativeDir ? V3_AUTHORITY : 0) |
  450. (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : 0) |
  451. (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : 0));
  452. if (!router_digest_is_trusted_dir(digest)) {
  453. add_trusted_dir_server(options->Nickname, NULL,
  454. (uint16_t)options->DirPort,
  455. (uint16_t)options->ORPort,
  456. digest,
  457. v3_digest,
  458. type);
  459. }
  460. return 0; /* success */
  461. }
  462. /* Keep track of whether we should upload our server descriptor,
  463. * and what type of server we are.
  464. */
  465. /** Whether we can reach our ORPort from the outside. */
  466. static int can_reach_or_port = 0;
  467. /** Whether we can reach our DirPort from the outside. */
  468. static int can_reach_dir_port = 0;
  469. /** Forget what we have learned about our reachability status. */
  470. void
  471. router_reset_reachability(void)
  472. {
  473. can_reach_or_port = can_reach_dir_port = 0;
  474. }
  475. /** Return 1 if ORPort is known reachable; else return 0. */
  476. int
  477. check_whether_orport_reachable(void)
  478. {
  479. or_options_t *options = get_options();
  480. return options->AssumeReachable ||
  481. can_reach_or_port;
  482. }
  483. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  484. int
  485. check_whether_dirport_reachable(void)
  486. {
  487. or_options_t *options = get_options();
  488. return !options->DirPort ||
  489. options->AssumeReachable ||
  490. we_are_hibernating() ||
  491. can_reach_dir_port;
  492. }
  493. /** Look at a variety of factors, and return 0 if we don't want to
  494. * advertise the fact that we have a DirPort open. Else return the
  495. * DirPort we want to advertise.
  496. *
  497. * Log a helpful message if we change our mind about whether to publish
  498. * a DirPort.
  499. */
  500. static int
  501. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  502. {
  503. static int advertising=1; /* start out assuming we will advertise */
  504. int new_choice=1;
  505. const char *reason = NULL;
  506. /* Section one: reasons to publish or not publish that aren't
  507. * worth mentioning to the user, either because they're obvious
  508. * or because they're normal behavior. */
  509. if (!router->dir_port) /* short circuit the rest of the function */
  510. return 0;
  511. if (authdir_mode(options)) /* always publish */
  512. return router->dir_port;
  513. if (we_are_hibernating())
  514. return 0;
  515. if (!check_whether_dirport_reachable())
  516. return 0;
  517. /* Section two: reasons to publish or not publish that the user
  518. * might find surprising. These are generally config options that
  519. * make us choose not to publish. */
  520. if (accounting_is_enabled(options)) {
  521. /* if we might potentially hibernate */
  522. new_choice = 0;
  523. reason = "AccountingMax enabled";
  524. } else if (router->bandwidthrate < 51200) {
  525. /* if we're advertising a small amount */
  526. new_choice = 0;
  527. reason = "BandwidthRate under 50KB";
  528. }
  529. if (advertising != new_choice) {
  530. if (new_choice == 1) {
  531. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", router->dir_port);
  532. } else {
  533. tor_assert(reason);
  534. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  535. }
  536. advertising = new_choice;
  537. }
  538. return advertising ? router->dir_port : 0;
  539. }
  540. /** Some time has passed, or we just got new directory information.
  541. * See if we currently believe our ORPort or DirPort to be
  542. * unreachable. If so, launch a new test for it.
  543. *
  544. * For ORPort, we simply try making a circuit that ends at ourselves.
  545. * Success is noticed in onionskin_answer().
  546. *
  547. * For DirPort, we make a connection via Tor to our DirPort and ask
  548. * for our own server descriptor.
  549. * Success is noticed in connection_dir_client_reached_eof().
  550. */
  551. void
  552. consider_testing_reachability(int test_or, int test_dir)
  553. {
  554. routerinfo_t *me = router_get_my_routerinfo();
  555. int orport_reachable = check_whether_orport_reachable();
  556. if (!me)
  557. return;
  558. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  559. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  560. !orport_reachable ? "reachability" : "bandwidth",
  561. me->address, me->or_port);
  562. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, 0, me, 0, 1, 1);
  563. control_event_server_status(LOG_NOTICE,
  564. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  565. me->address, me->or_port);
  566. }
  567. if (test_dir && !check_whether_dirport_reachable() &&
  568. !connection_get_by_type_addr_port_purpose(
  569. CONN_TYPE_DIR, me->addr, me->dir_port,
  570. DIR_PURPOSE_FETCH_SERVERDESC)) {
  571. /* ask myself, via tor, for my server descriptor. */
  572. directory_initiate_command(me->address, me->addr,
  573. me->or_port, me->dir_port,
  574. 0, me->cache_info.identity_digest,
  575. DIR_PURPOSE_FETCH_SERVERDESC,
  576. ROUTER_PURPOSE_GENERAL,
  577. 1, "authority.z", NULL, 0);
  578. control_event_server_status(LOG_NOTICE,
  579. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  580. me->address, me->dir_port);
  581. }
  582. }
  583. /** Annotate that we found our ORPort reachable. */
  584. void
  585. router_orport_found_reachable(void)
  586. {
  587. if (!can_reach_or_port) {
  588. routerinfo_t *me = router_get_my_routerinfo();
  589. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  590. "the outside. Excellent.%s",
  591. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  592. " Publishing server descriptor." : "");
  593. can_reach_or_port = 1;
  594. mark_my_descriptor_dirty();
  595. if (!me)
  596. return;
  597. control_event_server_status(LOG_NOTICE,
  598. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  599. me->address, me->dir_port);
  600. }
  601. }
  602. /** Annotate that we found our DirPort reachable. */
  603. void
  604. router_dirport_found_reachable(void)
  605. {
  606. if (!can_reach_dir_port) {
  607. routerinfo_t *me = router_get_my_routerinfo();
  608. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  609. "from the outside. Excellent.");
  610. can_reach_dir_port = 1;
  611. mark_my_descriptor_dirty();
  612. if (!me)
  613. return;
  614. control_event_server_status(LOG_NOTICE,
  615. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  616. me->address, me->dir_port);
  617. }
  618. }
  619. /** We have enough testing circuits open. Send a bunch of "drop"
  620. * cells down each of them, to exercise our bandwidth. */
  621. void
  622. router_perform_bandwidth_test(int num_circs, time_t now)
  623. {
  624. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  625. int max_cells = num_cells < CIRCWINDOW_START ?
  626. num_cells : CIRCWINDOW_START;
  627. int cells_per_circuit = max_cells / num_circs;
  628. origin_circuit_t *circ = NULL;
  629. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  630. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  631. CIRCUIT_PURPOSE_TESTING))) {
  632. /* dump cells_per_circuit drop cells onto this circ */
  633. int i = cells_per_circuit;
  634. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  635. continue;
  636. circ->_base.timestamp_dirty = now;
  637. while (i-- > 0) {
  638. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  639. RELAY_COMMAND_DROP,
  640. NULL, 0, circ->cpath->prev)<0) {
  641. return; /* stop if error */
  642. }
  643. }
  644. }
  645. }
  646. /** Return true iff we believe ourselves to be an authoritative
  647. * directory server.
  648. */
  649. int
  650. authdir_mode(or_options_t *options)
  651. {
  652. return options->AuthoritativeDir != 0;
  653. }
  654. /** Return true iff we believe ourselves to be a v1 authoritative
  655. * directory server.
  656. */
  657. int
  658. authdir_mode_v1(or_options_t *options)
  659. {
  660. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  661. }
  662. /** Return true iff we believe ourselves to be a v2 authoritative
  663. * directory server.
  664. */
  665. int
  666. authdir_mode_v2(or_options_t *options)
  667. {
  668. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  669. }
  670. /** Return true iff we believe ourselves to be a v3 authoritative
  671. * directory server.
  672. */
  673. int
  674. authdir_mode_v3(or_options_t *options)
  675. {
  676. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  677. }
  678. /** DOCDOC */
  679. int
  680. authdir_mode_any_nonbridge(or_options_t *options)
  681. {
  682. return authdir_mode(options) &&
  683. (options->V1AuthoritativeDir ||
  684. options->V2AuthoritativeDir ||
  685. options->V3AuthoritativeDir);
  686. }
  687. /** Return true iff we are an authoritative directory server that
  688. * is willing to receive or serve descriptors on its dirport.
  689. */
  690. int
  691. authdir_mode_handles_descs(or_options_t *options)
  692. {
  693. return authdir_mode_any_nonbridge(options) ||
  694. authdir_mode_bridge(options);
  695. }
  696. /** Return true iff we are an authoritative directory server that
  697. * publishes its own network statuses.
  698. */
  699. int
  700. authdir_mode_publishes_statuses(or_options_t *options)
  701. {
  702. if (authdir_mode_bridge(options))
  703. return 0;
  704. return authdir_mode_any_nonbridge(options);
  705. }
  706. /** Return true iff we are an authoritative directory server that
  707. * tests reachability of the descriptors it learns about.
  708. */
  709. int
  710. authdir_mode_tests_reachability(or_options_t *options)
  711. {
  712. return authdir_mode_any_nonbridge(options);
  713. }
  714. /** Return true iff we believe ourselves to be a bridge authoritative
  715. * directory server.
  716. */
  717. int
  718. authdir_mode_bridge(or_options_t *options)
  719. {
  720. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  721. }
  722. /** Return true iff we try to stay connected to all ORs at once.
  723. */
  724. int
  725. clique_mode(or_options_t *options)
  726. {
  727. return authdir_mode_tests_reachability(options);
  728. }
  729. /** Return true iff we are trying to be a server.
  730. */
  731. int
  732. server_mode(or_options_t *options)
  733. {
  734. if (options->ClientOnly) return 0;
  735. return (options->ORPort != 0 || options->ORListenAddress);
  736. }
  737. /** Remember if we've advertised ourselves to the dirservers. */
  738. static int server_is_advertised=0;
  739. /** Return true iff we have published our descriptor lately.
  740. */
  741. int
  742. advertised_server_mode(void)
  743. {
  744. return server_is_advertised;
  745. }
  746. /**
  747. * Called with a boolean: set whether we have recently published our
  748. * descriptor.
  749. */
  750. static void
  751. set_server_advertised(int s)
  752. {
  753. server_is_advertised = s;
  754. }
  755. /** Return true iff we are trying to be a socks proxy. */
  756. int
  757. proxy_mode(or_options_t *options)
  758. {
  759. return (options->SocksPort != 0 || options->SocksListenAddress);
  760. }
  761. /** Decide if we're a publishable server. We are a publishable server if:
  762. * - We don't have the ClientOnly option set
  763. * and
  764. * - We have the PublishServerDescriptor option set to non-empty
  765. * and
  766. * - We have ORPort set
  767. * and
  768. * - We believe we are reachable from the outside; or
  769. * - We are an authoritative directory server.
  770. */
  771. static int
  772. decide_if_publishable_server(void)
  773. {
  774. or_options_t *options = get_options();
  775. if (options->ClientOnly)
  776. return 0;
  777. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  778. return 0;
  779. if (!server_mode(options))
  780. return 0;
  781. if (authdir_mode(options))
  782. return 1;
  783. return check_whether_orport_reachable();
  784. }
  785. /** Initiate server descriptor upload as reasonable (if server is publishable,
  786. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  787. *
  788. * We need to rebuild the descriptor if it's dirty even if we're not
  789. * uploading, because our reachability testing *uses* our descriptor to
  790. * determine what IP address and ports to test.
  791. */
  792. void
  793. consider_publishable_server(int force)
  794. {
  795. int rebuilt;
  796. if (!server_mode(get_options()))
  797. return;
  798. rebuilt = router_rebuild_descriptor(0);
  799. if (decide_if_publishable_server()) {
  800. set_server_advertised(1);
  801. if (rebuilt == 0)
  802. router_upload_dir_desc_to_dirservers(force);
  803. } else {
  804. set_server_advertised(0);
  805. }
  806. }
  807. /*
  808. * Clique maintenance -- to be phased out.
  809. */
  810. /** Return true iff we believe this OR tries to keep connections open
  811. * to all other ORs. */
  812. int
  813. router_is_clique_mode(routerinfo_t *router)
  814. {
  815. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  816. return 1;
  817. return 0;
  818. }
  819. /*
  820. * OR descriptor generation.
  821. */
  822. /** My routerinfo. */
  823. static routerinfo_t *desc_routerinfo = NULL;
  824. /** My extrainfo */
  825. static extrainfo_t *desc_extrainfo = NULL;
  826. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  827. * now. */
  828. static time_t desc_clean_since = 0;
  829. /** Boolean: do we need to regenerate the above? */
  830. static int desc_needs_upload = 0;
  831. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  832. * descriptor successfully yet, try to upload our signed descriptor to
  833. * all the directory servers we know about.
  834. */
  835. void
  836. router_upload_dir_desc_to_dirservers(int force)
  837. {
  838. routerinfo_t *ri;
  839. extrainfo_t *ei;
  840. char *msg;
  841. size_t desc_len, extra_len = 0, total_len;
  842. authority_type_t auth = get_options()->_PublishServerDescriptor;
  843. ri = router_get_my_routerinfo();
  844. if (!ri) {
  845. log_info(LD_GENERAL, "No descriptor; skipping upload");
  846. return;
  847. }
  848. ei = router_get_my_extrainfo();
  849. if (auth == NO_AUTHORITY)
  850. return;
  851. if (!force && !desc_needs_upload)
  852. return;
  853. desc_needs_upload = 0;
  854. desc_len = ri->cache_info.signed_descriptor_len;
  855. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  856. total_len = desc_len + extra_len + 1;
  857. msg = tor_malloc(total_len);
  858. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  859. if (ei) {
  860. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  861. }
  862. msg[desc_len+extra_len] = 0;
  863. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  864. (auth & BRIDGE_AUTHORITY) ?
  865. ROUTER_PURPOSE_BRIDGE :
  866. ROUTER_PURPOSE_GENERAL,
  867. auth, msg, desc_len, extra_len);
  868. tor_free(msg);
  869. }
  870. /** OR only: Check whether my exit policy says to allow connection to
  871. * conn. Return 0 if we accept; non-0 if we reject.
  872. */
  873. int
  874. router_compare_to_my_exit_policy(edge_connection_t *conn)
  875. {
  876. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  877. return -1;
  878. /* make sure it's resolved to something. this way we can't get a
  879. 'maybe' below. */
  880. if (!conn->_base.addr)
  881. return -1;
  882. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  883. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  884. }
  885. /** Return true iff I'm a server and <b>digest</b> is equal to
  886. * my identity digest. */
  887. int
  888. router_digest_is_me(const char *digest)
  889. {
  890. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  891. }
  892. /** A wrapper around router_digest_is_me(). */
  893. int
  894. router_is_me(routerinfo_t *router)
  895. {
  896. return router_digest_is_me(router->cache_info.identity_digest);
  897. }
  898. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  899. int
  900. router_fingerprint_is_me(const char *fp)
  901. {
  902. char digest[DIGEST_LEN];
  903. if (strlen(fp) == HEX_DIGEST_LEN &&
  904. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  905. return router_digest_is_me(digest);
  906. return 0;
  907. }
  908. /** Return a routerinfo for this OR, rebuilding a fresh one if
  909. * necessary. Return NULL on error, or if called on an OP. */
  910. routerinfo_t *
  911. router_get_my_routerinfo(void)
  912. {
  913. if (!server_mode(get_options()))
  914. return NULL;
  915. if (router_rebuild_descriptor(0))
  916. return NULL;
  917. return desc_routerinfo;
  918. }
  919. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  920. * one if necessary. Return NULL on error.
  921. */
  922. const char *
  923. router_get_my_descriptor(void)
  924. {
  925. const char *body;
  926. if (!router_get_my_routerinfo())
  927. return NULL;
  928. /* Make sure this is nul-terminated. */
  929. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  930. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  931. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  932. log_debug(LD_GENERAL,"my desc is '%s'", body);
  933. return body;
  934. }
  935. /* Return the extrainfo document for this OR, or NULL if we have none.
  936. * Rebuilt it (and the server descriptor) if necessary. */
  937. extrainfo_t *
  938. router_get_my_extrainfo(void)
  939. {
  940. if (!server_mode(get_options()))
  941. return NULL;
  942. if (router_rebuild_descriptor(0))
  943. return NULL;
  944. return desc_extrainfo;
  945. }
  946. /** A list of nicknames that we've warned about including in our family
  947. * declaration verbatim rather than as digests. */
  948. static smartlist_t *warned_nonexistent_family = NULL;
  949. static int router_guess_address_from_dir_headers(uint32_t *guess);
  950. /** Return our current best guess at our address, either because
  951. * it's configured in torrc, or because we've learned it from
  952. * dirserver headers. */
  953. int
  954. router_pick_published_address(or_options_t *options, uint32_t *addr)
  955. {
  956. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  957. log_info(LD_CONFIG, "Could not determine our address locally. "
  958. "Checking if directory headers provide any hints.");
  959. if (router_guess_address_from_dir_headers(addr) < 0) {
  960. log_info(LD_CONFIG, "No hints from directory headers either. "
  961. "Will try again later.");
  962. return -1;
  963. }
  964. }
  965. return 0;
  966. }
  967. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  968. * routerinfo, signed server descriptor, and extra-info document for this OR.
  969. * Return 0 on success, -1 on temporary error.
  970. */
  971. int
  972. router_rebuild_descriptor(int force)
  973. {
  974. routerinfo_t *ri;
  975. extrainfo_t *ei;
  976. uint32_t addr;
  977. char platform[256];
  978. int hibernating = we_are_hibernating();
  979. or_options_t *options = get_options();
  980. if (desc_clean_since && !force)
  981. return 0;
  982. if (router_pick_published_address(options, &addr) < 0) {
  983. /* Stop trying to rebuild our descriptor every second. We'll
  984. * learn that it's time to try again when server_has_changed_ip()
  985. * marks it dirty. */
  986. desc_clean_since = time(NULL);
  987. return -1;
  988. }
  989. ri = tor_malloc_zero(sizeof(routerinfo_t));
  990. ri->routerlist_index = -1;
  991. ri->address = tor_dup_addr(addr);
  992. ri->nickname = tor_strdup(options->Nickname);
  993. ri->addr = addr;
  994. ri->or_port = options->ORPort;
  995. ri->dir_port = options->DirPort;
  996. ri->cache_info.published_on = time(NULL);
  997. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  998. * main thread */
  999. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  1000. if (crypto_pk_get_digest(ri->identity_pkey,
  1001. ri->cache_info.identity_digest)<0) {
  1002. routerinfo_free(ri);
  1003. return -1;
  1004. }
  1005. get_platform_str(platform, sizeof(platform));
  1006. ri->platform = tor_strdup(platform);
  1007. /* compute ri->bandwidthrate as the min of various options */
  1008. ri->bandwidthrate = (int)options->BandwidthRate;
  1009. if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
  1010. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  1011. if (options->RelayBandwidthRate > 0 &&
  1012. ri->bandwidthrate > options->RelayBandwidthRate)
  1013. ri->bandwidthrate = (int)options->RelayBandwidthRate;
  1014. /* and compute ri->bandwidthburst similarly */
  1015. ri->bandwidthburst = (int)options->BandwidthBurst;
  1016. if (options->RelayBandwidthBurst > 0 &&
  1017. ri->bandwidthburst > options->RelayBandwidthBurst)
  1018. ri->bandwidthburst = (int)options->RelayBandwidthBurst;
  1019. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1020. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1021. options->ExitPolicyRejectPrivate);
  1022. if (desc_routerinfo) { /* inherit values */
  1023. ri->is_valid = desc_routerinfo->is_valid;
  1024. ri->is_running = desc_routerinfo->is_running;
  1025. ri->is_named = desc_routerinfo->is_named;
  1026. }
  1027. if (authdir_mode(options))
  1028. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1029. if (options->MyFamily) {
  1030. smartlist_t *family;
  1031. if (!warned_nonexistent_family)
  1032. warned_nonexistent_family = smartlist_create();
  1033. family = smartlist_create();
  1034. ri->declared_family = smartlist_create();
  1035. smartlist_split_string(family, options->MyFamily, ",",
  1036. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1037. SMARTLIST_FOREACH(family, char *, name,
  1038. {
  1039. routerinfo_t *member;
  1040. if (!strcasecmp(name, options->Nickname))
  1041. member = ri;
  1042. else
  1043. member = router_get_by_nickname(name, 1);
  1044. if (!member) {
  1045. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1046. !is_legal_hexdigest(name)) {
  1047. log_warn(LD_CONFIG,
  1048. "I have no descriptor for the router named \"%s\" "
  1049. "in my declared family; I'll use the nickname as is, but "
  1050. "this may confuse clients.", name);
  1051. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1052. }
  1053. smartlist_add(ri->declared_family, name);
  1054. name = NULL;
  1055. } else if (router_is_me(member)) {
  1056. /* Don't list ourself in our own family; that's redundant */
  1057. } else {
  1058. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1059. fp[0] = '$';
  1060. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1061. member->cache_info.identity_digest, DIGEST_LEN);
  1062. smartlist_add(ri->declared_family, fp);
  1063. if (smartlist_string_isin(warned_nonexistent_family, name))
  1064. smartlist_string_remove(warned_nonexistent_family, name);
  1065. }
  1066. tor_free(name);
  1067. });
  1068. /* remove duplicates from the list */
  1069. smartlist_sort_strings(ri->declared_family);
  1070. smartlist_uniq_strings(ri->declared_family);
  1071. smartlist_free(family);
  1072. }
  1073. /* Now generate the extrainfo. */
  1074. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1075. ei->cache_info.is_extrainfo = 1;
  1076. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1077. ei->cache_info.published_on = ri->cache_info.published_on;
  1078. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1079. DIGEST_LEN);
  1080. ei->cache_info.signed_descriptor_body = tor_malloc(8192);
  1081. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
  1082. ei, get_identity_key()) < 0) {
  1083. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1084. return -1;
  1085. }
  1086. ei->cache_info.signed_descriptor_len =
  1087. strlen(ei->cache_info.signed_descriptor_body);
  1088. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1089. ei->cache_info.signed_descriptor_digest);
  1090. /* Now finish the router descriptor. */
  1091. memcpy(ri->cache_info.extra_info_digest,
  1092. ei->cache_info.signed_descriptor_digest,
  1093. DIGEST_LEN);
  1094. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1095. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1096. ri, get_identity_key())<0) {
  1097. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1098. return -1;
  1099. }
  1100. ri->cache_info.signed_descriptor_len =
  1101. strlen(ri->cache_info.signed_descriptor_body);
  1102. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1103. ri->cache_info.signed_descriptor_digest);
  1104. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL));
  1105. if (desc_routerinfo)
  1106. routerinfo_free(desc_routerinfo);
  1107. desc_routerinfo = ri;
  1108. if (desc_extrainfo)
  1109. extrainfo_free(desc_extrainfo);
  1110. desc_extrainfo = ei;
  1111. desc_clean_since = time(NULL);
  1112. desc_needs_upload = 1;
  1113. control_event_my_descriptor_changed();
  1114. return 0;
  1115. }
  1116. /** Mark descriptor out of date if it's older than <b>when</b> */
  1117. void
  1118. mark_my_descriptor_dirty_if_older_than(time_t when)
  1119. {
  1120. if (desc_clean_since < when)
  1121. mark_my_descriptor_dirty();
  1122. }
  1123. /** Call when the current descriptor is out of date. */
  1124. void
  1125. mark_my_descriptor_dirty(void)
  1126. {
  1127. desc_clean_since = 0;
  1128. }
  1129. /** How frequently will we republish our descriptor because of large (factor
  1130. * of 2) shifts in estimated bandwidth? */
  1131. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1132. /** Check whether bandwidth has changed a lot since the last time we announced
  1133. * bandwidth. If so, mark our descriptor dirty. */
  1134. void
  1135. check_descriptor_bandwidth_changed(time_t now)
  1136. {
  1137. static time_t last_changed = 0;
  1138. uint64_t prev, cur;
  1139. if (!desc_routerinfo)
  1140. return;
  1141. prev = desc_routerinfo->bandwidthcapacity;
  1142. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1143. if ((prev != cur && (!prev || !cur)) ||
  1144. cur > prev*2 ||
  1145. cur < prev/2) {
  1146. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1147. log_info(LD_GENERAL,
  1148. "Measured bandwidth has changed; rebuilding descriptor.");
  1149. mark_my_descriptor_dirty();
  1150. last_changed = now;
  1151. }
  1152. }
  1153. }
  1154. /** Note at log level severity that our best guess of address has changed from
  1155. * <b>prev</b> to <b>cur</b>. */
  1156. static void
  1157. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  1158. {
  1159. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1160. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1161. struct in_addr in_prev;
  1162. struct in_addr in_cur;
  1163. in_prev.s_addr = htonl(prev);
  1164. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1165. in_cur.s_addr = htonl(cur);
  1166. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1167. if (prev)
  1168. log_fn(severity, LD_GENERAL,
  1169. "Our IP Address has changed from %s to %s; "
  1170. "rebuilding descriptor.",
  1171. addrbuf_prev, addrbuf_cur);
  1172. else
  1173. log_notice(LD_GENERAL,
  1174. "Guessed our IP address as %s.",
  1175. addrbuf_cur);
  1176. }
  1177. /** Check whether our own address as defined by the Address configuration
  1178. * has changed. This is for routers that get their address from a service
  1179. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1180. void
  1181. check_descriptor_ipaddress_changed(time_t now)
  1182. {
  1183. uint32_t prev, cur;
  1184. or_options_t *options = get_options();
  1185. (void) now;
  1186. if (!desc_routerinfo)
  1187. return;
  1188. prev = desc_routerinfo->addr;
  1189. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1190. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1191. return;
  1192. }
  1193. if (prev != cur) {
  1194. log_addr_has_changed(LOG_INFO, prev, cur);
  1195. ip_address_changed(0);
  1196. }
  1197. }
  1198. /** The most recently guessed value of our IP address, based on directory
  1199. * headers. */
  1200. static uint32_t last_guessed_ip = 0;
  1201. /** A directory server told us our IP address is <b>suggestion</b>.
  1202. * If this address is different from the one we think we are now, and
  1203. * if our computer doesn't actually know its IP address, then switch. */
  1204. void
  1205. router_new_address_suggestion(const char *suggestion)
  1206. {
  1207. uint32_t addr, cur = 0;
  1208. struct in_addr in;
  1209. or_options_t *options = get_options();
  1210. /* first, learn what the IP address actually is */
  1211. if (!tor_inet_aton(suggestion, &in)) {
  1212. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1213. escaped(suggestion));
  1214. return;
  1215. }
  1216. addr = ntohl(in.s_addr);
  1217. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1218. if (!server_mode(options)) {
  1219. last_guessed_ip = addr; /* store it in case we need it later */
  1220. return;
  1221. }
  1222. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1223. /* We're all set -- we already know our address. Great. */
  1224. last_guessed_ip = cur; /* store it in case we need it later */
  1225. return;
  1226. }
  1227. if (is_internal_IP(addr, 0)) {
  1228. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1229. return;
  1230. }
  1231. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1232. * us an answer different from what we had the last time we managed to
  1233. * resolve it. */
  1234. if (last_guessed_ip != addr) {
  1235. control_event_server_status(LOG_NOTICE,
  1236. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1237. suggestion);
  1238. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  1239. ip_address_changed(0);
  1240. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1241. }
  1242. }
  1243. /** We failed to resolve our address locally, but we'd like to build
  1244. * a descriptor and publish / test reachability. If we have a guess
  1245. * about our address based on directory headers, answer it and return
  1246. * 0; else return -1. */
  1247. static int
  1248. router_guess_address_from_dir_headers(uint32_t *guess)
  1249. {
  1250. if (last_guessed_ip) {
  1251. *guess = last_guessed_ip;
  1252. return 0;
  1253. }
  1254. return -1;
  1255. }
  1256. extern const char tor_svn_revision[]; /* from main.c */
  1257. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1258. * string describing the version of Tor and the operating system we're
  1259. * currently running on.
  1260. */
  1261. void
  1262. get_platform_str(char *platform, size_t len)
  1263. {
  1264. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1265. }
  1266. /* XXX need to audit this thing and count fenceposts. maybe
  1267. * refactor so we don't have to keep asking if we're
  1268. * near the end of maxlen?
  1269. */
  1270. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1271. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1272. * with, encode the routerinfo as a signed server descriptor and write the
  1273. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1274. * failure, and the number of bytes used on success.
  1275. */
  1276. int
  1277. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1278. crypto_pk_env_t *ident_key)
  1279. {
  1280. char *onion_pkey; /* Onion key, PEM-encoded. */
  1281. char *identity_pkey; /* Identity key, PEM-encoded. */
  1282. char digest[DIGEST_LEN];
  1283. char published[ISO_TIME_LEN+1];
  1284. char fingerprint[FINGERPRINT_LEN+1];
  1285. char extra_info_digest[HEX_DIGEST_LEN+1];
  1286. size_t onion_pkeylen, identity_pkeylen;
  1287. size_t written;
  1288. int result=0;
  1289. addr_policy_t *tmpe;
  1290. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1291. char *bandwidth_usage;
  1292. #endif
  1293. char *family_line;
  1294. or_options_t *options = get_options();
  1295. /* Make sure the identity key matches the one in the routerinfo. */
  1296. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1297. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1298. "match router's public key!");
  1299. return -1;
  1300. }
  1301. /* record our fingerprint, so we can include it in the descriptor */
  1302. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1303. log_err(LD_BUG,"Error computing fingerprint");
  1304. return -1;
  1305. }
  1306. /* PEM-encode the onion key */
  1307. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1308. &onion_pkey,&onion_pkeylen)<0) {
  1309. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1310. return -1;
  1311. }
  1312. /* PEM-encode the identity key key */
  1313. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1314. &identity_pkey,&identity_pkeylen)<0) {
  1315. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1316. tor_free(onion_pkey);
  1317. return -1;
  1318. }
  1319. /* Encode the publication time. */
  1320. format_iso_time(published, router->cache_info.published_on);
  1321. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1322. /* How busy have we been? */
  1323. bandwidth_usage = rep_hist_get_bandwidth_lines(0);
  1324. #endif
  1325. if (router->declared_family && smartlist_len(router->declared_family)) {
  1326. size_t n;
  1327. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1328. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1329. family_line = tor_malloc(n);
  1330. tor_snprintf(family_line, n, "family %s\n", family);
  1331. tor_free(family);
  1332. } else {
  1333. family_line = tor_strdup("");
  1334. }
  1335. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1336. router->cache_info.extra_info_digest, DIGEST_LEN);
  1337. /* Generate the easy portion of the router descriptor. */
  1338. result = tor_snprintf(s, maxlen,
  1339. "router %s %s %d 0 %d\n"
  1340. "platform %s\n"
  1341. "published %s\n"
  1342. "opt fingerprint %s\n"
  1343. "uptime %ld\n"
  1344. "bandwidth %d %d %d\n"
  1345. "opt extra-info-digest %s\n%s"
  1346. "onion-key\n%s"
  1347. "signing-key\n%s"
  1348. "%s%s%s",
  1349. router->nickname,
  1350. router->address,
  1351. router->or_port,
  1352. decide_to_advertise_dirport(options, router),
  1353. router->platform,
  1354. published,
  1355. fingerprint,
  1356. stats_n_seconds_working,
  1357. (int) router->bandwidthrate,
  1358. (int) router->bandwidthburst,
  1359. (int) router->bandwidthcapacity,
  1360. extra_info_digest,
  1361. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1362. onion_pkey, identity_pkey,
  1363. family_line,
  1364. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1365. bandwidth_usage,
  1366. #else
  1367. "",
  1368. #endif
  1369. we_are_hibernating() ? "opt hibernating 1\n" : "");
  1370. tor_free(family_line);
  1371. tor_free(onion_pkey);
  1372. tor_free(identity_pkey);
  1373. #ifdef INCLUDE_BW_INFO_IN_ROUTERDESCS
  1374. tor_free(bandwidth_usage);
  1375. #endif
  1376. if (result < 0) {
  1377. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1378. return -1;
  1379. }
  1380. /* From now on, we use 'written' to remember the current length of 's'. */
  1381. written = result;
  1382. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1383. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1384. options->ContactInfo);
  1385. if (result<0) {
  1386. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1387. return -1;
  1388. }
  1389. written += result;
  1390. }
  1391. /* Write the exit policy to the end of 's'. */
  1392. tmpe = router->exit_policy;
  1393. if (dns_seems_to_be_broken()) {
  1394. /* DNS is screwed up; don't claim to be an exit. */
  1395. strlcat(s+written, "reject *:*\n", maxlen-written);
  1396. written += strlen("reject *:*\n");
  1397. tmpe = NULL;
  1398. }
  1399. for ( ; tmpe; tmpe=tmpe->next) {
  1400. result = policy_write_item(s+written, maxlen-written, tmpe);
  1401. if (result < 0) {
  1402. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1403. return -1;
  1404. }
  1405. tor_assert(result == (int)strlen(s+written));
  1406. written += result;
  1407. if (written+2 > maxlen) {
  1408. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1409. return -1;
  1410. }
  1411. s[written++] = '\n';
  1412. }
  1413. if (written+256 > maxlen) { /* Not enough room for signature. */
  1414. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1415. return -1;
  1416. }
  1417. /* Sign the directory */
  1418. strlcpy(s+written, "router-signature\n", maxlen-written);
  1419. written += strlen(s+written);
  1420. s[written] = '\0';
  1421. if (router_get_router_hash(s, digest) < 0) {
  1422. return -1;
  1423. }
  1424. note_crypto_pk_op(SIGN_RTR);
  1425. if (router_append_dirobj_signature(s+written,maxlen-written,
  1426. digest,ident_key)<0) {
  1427. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1428. return -1;
  1429. }
  1430. written += strlen(s+written);
  1431. if (written+2 > maxlen) {
  1432. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1433. return -1;
  1434. }
  1435. /* include a last '\n' */
  1436. s[written] = '\n';
  1437. s[written+1] = 0;
  1438. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1439. {
  1440. char *s_dup;
  1441. const char *cp;
  1442. routerinfo_t *ri_tmp;
  1443. cp = s_dup = tor_strdup(s);
  1444. ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
  1445. if (!ri_tmp) {
  1446. log_err(LD_BUG,
  1447. "We just generated a router descriptor we can't parse.");
  1448. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1449. return -1;
  1450. }
  1451. tor_free(s_dup);
  1452. routerinfo_free(ri_tmp);
  1453. }
  1454. #endif
  1455. return written+1;
  1456. }
  1457. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1458. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1459. * negative on failure. */
  1460. int
  1461. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1462. crypto_pk_env_t *ident_key)
  1463. {
  1464. char identity[HEX_DIGEST_LEN+1];
  1465. char published[ISO_TIME_LEN+1];
  1466. char digest[DIGEST_LEN];
  1467. char *bandwidth_usage;
  1468. int result;
  1469. size_t len;
  1470. base16_encode(identity, sizeof(identity),
  1471. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1472. format_iso_time(published, extrainfo->cache_info.published_on);
  1473. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1474. result = tor_snprintf(s, maxlen,
  1475. "extra-info %s %s\n"
  1476. "published %s\n%s"
  1477. "router-signature\n",
  1478. extrainfo->nickname, identity,
  1479. published, bandwidth_usage);
  1480. tor_free(bandwidth_usage);
  1481. if (result<0)
  1482. return -1;
  1483. len = strlen(s);
  1484. if (router_get_extrainfo_hash(s, digest)<0)
  1485. return -1;
  1486. if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
  1487. return -1;
  1488. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1489. {
  1490. char *cp, *s_dup;
  1491. extrainfo_t *ei_tmp;
  1492. cp = s_dup = tor_strdup(s);
  1493. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1494. if (!ei_tmp) {
  1495. log_err(LD_BUG,
  1496. "We just generated an extrainfo descriptor we can't parse.");
  1497. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1498. return -1;
  1499. }
  1500. tor_free(s_dup);
  1501. extrainfo_free(ei_tmp);
  1502. }
  1503. #endif
  1504. return strlen(s)+1;
  1505. }
  1506. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1507. int
  1508. is_legal_nickname(const char *s)
  1509. {
  1510. size_t len;
  1511. tor_assert(s);
  1512. len = strlen(s);
  1513. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1514. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1515. }
  1516. /** Return true iff <b>s</b> is a legally valid server nickname or
  1517. * hex-encoded identity-key digest. */
  1518. int
  1519. is_legal_nickname_or_hexdigest(const char *s)
  1520. {
  1521. if (*s!='$')
  1522. return is_legal_nickname(s);
  1523. else
  1524. return is_legal_hexdigest(s);
  1525. }
  1526. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1527. * digest. */
  1528. int
  1529. is_legal_hexdigest(const char *s)
  1530. {
  1531. size_t len;
  1532. tor_assert(s);
  1533. if (s[0] == '$') s++;
  1534. len = strlen(s);
  1535. if (len > HEX_DIGEST_LEN) {
  1536. if (s[HEX_DIGEST_LEN] == '=' ||
  1537. s[HEX_DIGEST_LEN] == '~') {
  1538. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1539. return 0;
  1540. } else {
  1541. return 0;
  1542. }
  1543. }
  1544. return (len >= HEX_DIGEST_LEN &&
  1545. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1546. }
  1547. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1548. * verbose representation of the identity of <b>router</b>. The format is:
  1549. * A dollar sign.
  1550. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1551. * A "=" if the router is named; a "~" if it is not.
  1552. * The router's nickname.
  1553. **/
  1554. void
  1555. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1556. {
  1557. buf[0] = '$';
  1558. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1559. DIGEST_LEN);
  1560. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1561. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1562. }
  1563. /** Forget that we have issued any router-related warnings, so that we'll
  1564. * warn again if we see the same errors. */
  1565. void
  1566. router_reset_warnings(void)
  1567. {
  1568. if (warned_nonexistent_family) {
  1569. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1570. smartlist_clear(warned_nonexistent_family);
  1571. }
  1572. }
  1573. /** Release all static resources held in router.c */
  1574. void
  1575. router_free_all(void)
  1576. {
  1577. if (onionkey)
  1578. crypto_free_pk_env(onionkey);
  1579. if (lastonionkey)
  1580. crypto_free_pk_env(lastonionkey);
  1581. if (identitykey)
  1582. crypto_free_pk_env(identitykey);
  1583. if (key_lock)
  1584. tor_mutex_free(key_lock);
  1585. if (desc_routerinfo)
  1586. routerinfo_free(desc_routerinfo);
  1587. if (desc_extrainfo)
  1588. extrainfo_free(desc_extrainfo);
  1589. if (authority_signing_key)
  1590. crypto_free_pk_env(authority_signing_key);
  1591. if (authority_key_certificate)
  1592. authority_cert_free(authority_key_certificate);
  1593. if (warned_nonexistent_family) {
  1594. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1595. smartlist_free(warned_nonexistent_family);
  1596. }
  1597. }