router.c 68 KB

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