router.c 68 KB

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