router.c 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783
  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-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #define ROUTER_PRIVATE
  7. #include "or.h"
  8. #include "circuitbuild.h"
  9. #include "circuitlist.h"
  10. #include "circuituse.h"
  11. #include "config.h"
  12. #include "connection.h"
  13. #include "control.h"
  14. #include "directory.h"
  15. #include "dirserv.h"
  16. #include "dns.h"
  17. #include "geoip.h"
  18. #include "hibernate.h"
  19. #include "main.h"
  20. #include "networkstatus.h"
  21. #include "nodelist.h"
  22. #include "policies.h"
  23. #include "relay.h"
  24. #include "rephist.h"
  25. #include "router.h"
  26. #include "routerlist.h"
  27. #include "routerparse.h"
  28. #include "transports.h"
  29. /**
  30. * \file router.c
  31. * \brief OR functionality, including key maintenance, generating
  32. * and uploading server descriptors, retrying OR connections.
  33. **/
  34. extern long stats_n_seconds_working;
  35. /************************************************************/
  36. /*****
  37. * Key management: ORs only.
  38. *****/
  39. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  40. */
  41. static tor_mutex_t *key_lock=NULL;
  42. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  43. /** Current private onionskin decryption key: used to decode CREATE cells. */
  44. static crypto_pk_t *onionkey=NULL;
  45. /** Previous private onionskin decryption key: used to decode CREATE cells
  46. * generated by clients that have an older version of our descriptor. */
  47. static crypto_pk_t *lastonionkey=NULL;
  48. /** Private server "identity key": used to sign directory info and TLS
  49. * certificates. Never changes. */
  50. static crypto_pk_t *server_identitykey=NULL;
  51. /** Digest of server_identitykey. */
  52. static char server_identitykey_digest[DIGEST_LEN];
  53. /** Private client "identity key": used to sign bridges' and clients'
  54. * outbound TLS certificates. Regenerated on startup and on IP address
  55. * change. */
  56. static crypto_pk_t *client_identitykey=NULL;
  57. /** Signing key used for v3 directory material; only set for authorities. */
  58. static crypto_pk_t *authority_signing_key = NULL;
  59. /** Key certificate to authenticate v3 directory material; only set for
  60. * authorities. */
  61. static authority_cert_t *authority_key_certificate = NULL;
  62. /** For emergency V3 authority key migration: An extra signing key that we use
  63. * with our old (obsolete) identity key for a while. */
  64. static crypto_pk_t *legacy_signing_key = NULL;
  65. /** For emergency V3 authority key migration: An extra certificate to
  66. * authenticate legacy_signing_key with our obsolete identity key.*/
  67. static authority_cert_t *legacy_key_certificate = NULL;
  68. /* (Note that v3 authorities also have a separate "authority identity key",
  69. * but this key is never actually loaded by the Tor process. Instead, it's
  70. * used by tor-gencert to sign new signing keys and make new key
  71. * certificates. */
  72. /** Replace the current onion key with <b>k</b>. Does not affect
  73. * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
  74. */
  75. static void
  76. set_onion_key(crypto_pk_t *k)
  77. {
  78. if (onionkey && !crypto_pk_cmp_keys(onionkey, k)) {
  79. /* k is already our onion key; free it and return */
  80. crypto_pk_free(k);
  81. return;
  82. }
  83. tor_mutex_acquire(key_lock);
  84. crypto_pk_free(onionkey);
  85. onionkey = k;
  86. tor_mutex_release(key_lock);
  87. mark_my_descriptor_dirty("set onion key");
  88. }
  89. /** Return the current onion key. Requires that the onion key has been
  90. * loaded or generated. */
  91. crypto_pk_t *
  92. get_onion_key(void)
  93. {
  94. tor_assert(onionkey);
  95. return onionkey;
  96. }
  97. /** Store a full copy of the current onion key into *<b>key</b>, and a full
  98. * copy of the most recent onion key into *<b>last</b>.
  99. */
  100. void
  101. dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
  102. {
  103. tor_assert(key);
  104. tor_assert(last);
  105. tor_mutex_acquire(key_lock);
  106. tor_assert(onionkey);
  107. *key = crypto_pk_copy_full(onionkey);
  108. if (lastonionkey)
  109. *last = crypto_pk_copy_full(lastonionkey);
  110. else
  111. *last = NULL;
  112. tor_mutex_release(key_lock);
  113. }
  114. /** Return the time when the onion key was last set. This is either the time
  115. * when the process launched, or the time of the most recent key rotation since
  116. * the process launched.
  117. */
  118. time_t
  119. get_onion_key_set_at(void)
  120. {
  121. return onionkey_set_at;
  122. }
  123. /** Set the current server identity key to <b>k</b>.
  124. */
  125. void
  126. set_server_identity_key(crypto_pk_t *k)
  127. {
  128. crypto_pk_free(server_identitykey);
  129. server_identitykey = k;
  130. crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
  131. }
  132. /** Make sure that we have set up our identity keys to match or not match as
  133. * appropriate, and die with an assertion if we have not. */
  134. static void
  135. assert_identity_keys_ok(void)
  136. {
  137. tor_assert(client_identitykey);
  138. if (public_server_mode(get_options())) {
  139. /* assert that we have set the client and server keys to be equal */
  140. tor_assert(server_identitykey);
  141. tor_assert(0==crypto_pk_cmp_keys(client_identitykey, server_identitykey));
  142. } else {
  143. /* assert that we have set the client and server keys to be unequal */
  144. if (server_identitykey)
  145. tor_assert(0!=crypto_pk_cmp_keys(client_identitykey,
  146. server_identitykey));
  147. }
  148. }
  149. /** Returns the current server identity key; requires that the key has
  150. * been set, and that we are running as a Tor server.
  151. */
  152. crypto_pk_t *
  153. get_server_identity_key(void)
  154. {
  155. tor_assert(server_identitykey);
  156. tor_assert(server_mode(get_options()));
  157. assert_identity_keys_ok();
  158. return server_identitykey;
  159. }
  160. /** Return true iff the server identity key has been set. */
  161. int
  162. server_identity_key_is_set(void)
  163. {
  164. return server_identitykey != NULL;
  165. }
  166. /** Set the current client identity key to <b>k</b>.
  167. */
  168. void
  169. set_client_identity_key(crypto_pk_t *k)
  170. {
  171. crypto_pk_free(client_identitykey);
  172. client_identitykey = k;
  173. }
  174. /** Returns the current client identity key for use on outgoing TLS
  175. * connections; requires that the key has been set.
  176. */
  177. crypto_pk_t *
  178. get_tlsclient_identity_key(void)
  179. {
  180. tor_assert(client_identitykey);
  181. assert_identity_keys_ok();
  182. return client_identitykey;
  183. }
  184. /** Return true iff the client identity key has been set. */
  185. int
  186. client_identity_key_is_set(void)
  187. {
  188. return client_identitykey != NULL;
  189. }
  190. /** Return the key certificate for this v3 (voting) authority, or NULL
  191. * if we have no such certificate. */
  192. authority_cert_t *
  193. get_my_v3_authority_cert(void)
  194. {
  195. return authority_key_certificate;
  196. }
  197. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  198. * if we have no such key. */
  199. crypto_pk_t *
  200. get_my_v3_authority_signing_key(void)
  201. {
  202. return authority_signing_key;
  203. }
  204. /** If we're an authority, and we're using a legacy authority identity key for
  205. * emergency migration purposes, return the certificate associated with that
  206. * key. */
  207. authority_cert_t *
  208. get_my_v3_legacy_cert(void)
  209. {
  210. return legacy_key_certificate;
  211. }
  212. /** If we're an authority, and we're using a legacy authority identity key for
  213. * emergency migration purposes, return that key. */
  214. crypto_pk_t *
  215. get_my_v3_legacy_signing_key(void)
  216. {
  217. return legacy_signing_key;
  218. }
  219. /** Replace the previous onion key with the current onion key, and generate
  220. * a new previous onion key. Immediately after calling this function,
  221. * the OR should:
  222. * - schedule all previous cpuworkers to shut down _after_ processing
  223. * pending work. (This will cause fresh cpuworkers to be generated.)
  224. * - generate and upload a fresh routerinfo.
  225. */
  226. void
  227. rotate_onion_key(void)
  228. {
  229. char *fname, *fname_prev;
  230. crypto_pk_t *prkey;
  231. or_state_t *state = get_or_state();
  232. time_t now;
  233. fname = get_datadir_fname2("keys", "secret_onion_key");
  234. fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
  235. if (!(prkey = crypto_pk_new())) {
  236. log_err(LD_GENERAL,"Error constructing rotated onion key");
  237. goto error;
  238. }
  239. if (crypto_pk_generate_key(prkey)) {
  240. log_err(LD_BUG,"Error generating onion key");
  241. goto error;
  242. }
  243. if (file_status(fname) == FN_FILE) {
  244. if (replace_file(fname, fname_prev))
  245. goto error;
  246. }
  247. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  248. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  249. goto error;
  250. }
  251. log_info(LD_GENERAL, "Rotating onion key");
  252. tor_mutex_acquire(key_lock);
  253. crypto_pk_free(lastonionkey);
  254. lastonionkey = onionkey;
  255. onionkey = prkey;
  256. now = time(NULL);
  257. state->LastRotatedOnionKey = onionkey_set_at = now;
  258. tor_mutex_release(key_lock);
  259. mark_my_descriptor_dirty("rotated onion key");
  260. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  261. goto done;
  262. error:
  263. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  264. if (prkey)
  265. crypto_pk_free(prkey);
  266. done:
  267. tor_free(fname);
  268. tor_free(fname_prev);
  269. }
  270. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  271. * and <b>generate</b> is true, create a new RSA key and save it in
  272. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  273. * errors at level <b>severity</b>.
  274. */
  275. crypto_pk_t *
  276. init_key_from_file(const char *fname, int generate, int severity)
  277. {
  278. crypto_pk_t *prkey = NULL;
  279. if (!(prkey = crypto_pk_new())) {
  280. log(severity, LD_GENERAL,"Error constructing key");
  281. goto error;
  282. }
  283. switch (file_status(fname)) {
  284. case FN_DIR:
  285. case FN_ERROR:
  286. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  287. goto error;
  288. case FN_NOENT:
  289. if (generate) {
  290. if (!have_lockfile()) {
  291. if (try_locking(get_options(), 0)<0) {
  292. /* Make sure that --list-fingerprint only creates new keys
  293. * if there is no possibility for a deadlock. */
  294. log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
  295. "writing any new keys.", fname);
  296. /*XXXX The 'other process' might make a key in a second or two;
  297. * maybe we should wait for it. */
  298. goto error;
  299. }
  300. }
  301. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  302. fname);
  303. if (crypto_pk_generate_key(prkey)) {
  304. log(severity, LD_GENERAL,"Error generating onion key");
  305. goto error;
  306. }
  307. if (crypto_pk_check_key(prkey) <= 0) {
  308. log(severity, LD_GENERAL,"Generated key seems invalid");
  309. goto error;
  310. }
  311. log_info(LD_GENERAL, "Generated key seems valid");
  312. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  313. log(severity, LD_FS,
  314. "Couldn't write generated key to \"%s\".", fname);
  315. goto error;
  316. }
  317. } else {
  318. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  319. }
  320. return prkey;
  321. case FN_FILE:
  322. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  323. log(severity, LD_GENERAL,"Error loading private key.");
  324. goto error;
  325. }
  326. return prkey;
  327. default:
  328. tor_assert(0);
  329. }
  330. error:
  331. if (prkey)
  332. crypto_pk_free(prkey);
  333. return NULL;
  334. }
  335. /** Try to load the vote-signing private key and certificate for being a v3
  336. * directory authority, and make sure they match. If <b>legacy</b>, load a
  337. * legacy key/cert set for emergency key migration; otherwise load the regular
  338. * key/cert set. On success, store them into *<b>key_out</b> and
  339. * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
  340. static int
  341. load_authority_keyset(int legacy, crypto_pk_t **key_out,
  342. authority_cert_t **cert_out)
  343. {
  344. int r = -1;
  345. char *fname = NULL, *cert = NULL;
  346. const char *eos = NULL;
  347. crypto_pk_t *signing_key = NULL;
  348. authority_cert_t *parsed = NULL;
  349. fname = get_datadir_fname2("keys",
  350. legacy ? "legacy_signing_key" : "authority_signing_key");
  351. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  352. if (!signing_key) {
  353. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  354. goto done;
  355. }
  356. tor_free(fname);
  357. fname = get_datadir_fname2("keys",
  358. legacy ? "legacy_certificate" : "authority_certificate");
  359. cert = read_file_to_str(fname, 0, NULL);
  360. if (!cert) {
  361. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  362. fname);
  363. goto done;
  364. }
  365. parsed = authority_cert_parse_from_string(cert, &eos);
  366. if (!parsed) {
  367. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  368. goto done;
  369. }
  370. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  371. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  372. "certificate");
  373. goto done;
  374. }
  375. crypto_pk_free(*key_out);
  376. authority_cert_free(*cert_out);
  377. *key_out = signing_key;
  378. *cert_out = parsed;
  379. r = 0;
  380. signing_key = NULL;
  381. parsed = NULL;
  382. done:
  383. tor_free(fname);
  384. tor_free(cert);
  385. crypto_pk_free(signing_key);
  386. authority_cert_free(parsed);
  387. return r;
  388. }
  389. /** Load the v3 (voting) authority signing key and certificate, if they are
  390. * present. Return -1 if anything is missing, mismatched, or unloadable;
  391. * return 0 on success. */
  392. static int
  393. init_v3_authority_keys(void)
  394. {
  395. if (load_authority_keyset(0, &authority_signing_key,
  396. &authority_key_certificate)<0)
  397. return -1;
  398. if (get_options()->V3AuthUseLegacyKey &&
  399. load_authority_keyset(1, &legacy_signing_key,
  400. &legacy_key_certificate)<0)
  401. return -1;
  402. return 0;
  403. }
  404. /** If we're a v3 authority, check whether we have a certificate that's
  405. * likely to expire soon. Warn if we do, but not too often. */
  406. void
  407. v3_authority_check_key_expiry(void)
  408. {
  409. time_t now, expires;
  410. static time_t last_warned = 0;
  411. int badness, time_left, warn_interval;
  412. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  413. return;
  414. now = time(NULL);
  415. expires = authority_key_certificate->expires;
  416. time_left = (int)( expires - now );
  417. if (time_left <= 0) {
  418. badness = LOG_ERR;
  419. warn_interval = 60*60;
  420. } else if (time_left <= 24*60*60) {
  421. badness = LOG_WARN;
  422. warn_interval = 60*60;
  423. } else if (time_left <= 24*60*60*7) {
  424. badness = LOG_WARN;
  425. warn_interval = 24*60*60;
  426. } else if (time_left <= 24*60*60*30) {
  427. badness = LOG_WARN;
  428. warn_interval = 24*60*60*5;
  429. } else {
  430. return;
  431. }
  432. if (last_warned + warn_interval > now)
  433. return;
  434. if (time_left <= 0) {
  435. log(badness, LD_DIR, "Your v3 authority certificate has expired."
  436. " Generate a new one NOW.");
  437. } else if (time_left <= 24*60*60) {
  438. log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
  439. " Generate a new one NOW.", time_left/(60*60));
  440. } else {
  441. log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
  442. " Generate a new one soon.", time_left/(24*60*60));
  443. }
  444. last_warned = now;
  445. }
  446. /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
  447. * on success, and -1 on failure. */
  448. int
  449. router_initialize_tls_context(void)
  450. {
  451. return tor_tls_context_init(public_server_mode(get_options()),
  452. get_tlsclient_identity_key(),
  453. server_mode(get_options()) ?
  454. get_server_identity_key() : NULL,
  455. MAX_SSL_KEY_LIFETIME_ADVERTISED);
  456. }
  457. /** Initialize all OR private keys, and the TLS context, as necessary.
  458. * On OPs, this only initializes the tls context. Return 0 on success,
  459. * or -1 if Tor should die.
  460. */
  461. int
  462. init_keys(void)
  463. {
  464. char *keydir;
  465. char fingerprint[FINGERPRINT_LEN+1];
  466. /*nickname<space>fp\n\0 */
  467. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  468. const char *mydesc;
  469. crypto_pk_t *prkey;
  470. char digest[DIGEST_LEN];
  471. char v3_digest[DIGEST_LEN];
  472. char *cp;
  473. const or_options_t *options = get_options();
  474. dirinfo_type_t type;
  475. time_t now = time(NULL);
  476. trusted_dir_server_t *ds;
  477. int v3_digest_set = 0;
  478. authority_cert_t *cert = NULL;
  479. if (!key_lock)
  480. key_lock = tor_mutex_new();
  481. /* There are a couple of paths that put us here before we've asked
  482. * openssl to initialize itself. */
  483. if (crypto_global_init(get_options()->HardwareAccel,
  484. get_options()->AccelName,
  485. get_options()->AccelDir)) {
  486. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  487. return -1;
  488. }
  489. /* OP's don't need persistent keys; just make up an identity and
  490. * initialize the TLS context. */
  491. if (!server_mode(options)) {
  492. if (!(prkey = crypto_pk_new()))
  493. return -1;
  494. if (crypto_pk_generate_key(prkey)) {
  495. crypto_pk_free(prkey);
  496. return -1;
  497. }
  498. set_client_identity_key(prkey);
  499. /* Create a TLS context. */
  500. if (router_initialize_tls_context() < 0) {
  501. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  502. return -1;
  503. }
  504. return 0;
  505. }
  506. /* Make sure DataDirectory exists, and is private. */
  507. if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
  508. return -1;
  509. }
  510. /* Check the key directory. */
  511. keydir = get_datadir_fname("keys");
  512. if (check_private_dir(keydir, CPD_CREATE, options->User)) {
  513. tor_free(keydir);
  514. return -1;
  515. }
  516. tor_free(keydir);
  517. /* 1a. Read v3 directory authority key/cert information. */
  518. memset(v3_digest, 0, sizeof(v3_digest));
  519. if (authdir_mode_v3(options)) {
  520. if (init_v3_authority_keys()<0) {
  521. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  522. "were unable to load our v3 authority keys and certificate! "
  523. "Use tor-gencert to generate them. Dying.");
  524. return -1;
  525. }
  526. cert = get_my_v3_authority_cert();
  527. if (cert) {
  528. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  529. v3_digest);
  530. v3_digest_set = 1;
  531. }
  532. }
  533. /* 1b. Read identity key. Make it if none is found. */
  534. keydir = get_datadir_fname2("keys", "secret_id_key");
  535. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  536. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  537. tor_free(keydir);
  538. if (!prkey) return -1;
  539. set_server_identity_key(prkey);
  540. /* 1c. If we are configured as a bridge, generate a client key;
  541. * otherwise, set the server identity key as our client identity
  542. * key. */
  543. if (public_server_mode(options)) {
  544. set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
  545. } else {
  546. if (!(prkey = crypto_pk_new()))
  547. return -1;
  548. if (crypto_pk_generate_key(prkey)) {
  549. crypto_pk_free(prkey);
  550. return -1;
  551. }
  552. set_client_identity_key(prkey);
  553. }
  554. /* 2. Read onion key. Make it if none is found. */
  555. keydir = get_datadir_fname2("keys", "secret_onion_key");
  556. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  557. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  558. tor_free(keydir);
  559. if (!prkey) return -1;
  560. set_onion_key(prkey);
  561. if (options->command == CMD_RUN_TOR) {
  562. /* only mess with the state file if we're actually running Tor */
  563. or_state_t *state = get_or_state();
  564. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  565. /* We allow for some parsing slop, but we don't want to risk accepting
  566. * values in the distant future. If we did, we might never rotate the
  567. * onion key. */
  568. onionkey_set_at = state->LastRotatedOnionKey;
  569. } else {
  570. /* We have no LastRotatedOnionKey set; either we just created the key
  571. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  572. * start the clock ticking now so that we will eventually rotate it even
  573. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  574. state->LastRotatedOnionKey = onionkey_set_at = now;
  575. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  576. time(NULL)+3600 : 0);
  577. }
  578. }
  579. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  580. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  581. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  582. if (prkey)
  583. lastonionkey = prkey;
  584. }
  585. tor_free(keydir);
  586. /* 3. Initialize link key and TLS context. */
  587. if (router_initialize_tls_context() < 0) {
  588. log_err(LD_GENERAL,"Error initializing TLS context");
  589. return -1;
  590. }
  591. /* 4. Build our router descriptor. */
  592. /* Must be called after keys are initialized. */
  593. mydesc = router_get_my_descriptor();
  594. if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
  595. const char *m = NULL;
  596. routerinfo_t *ri;
  597. /* We need to add our own fingerprint so it gets recognized. */
  598. if (dirserv_add_own_fingerprint(options->Nickname,
  599. get_server_identity_key())) {
  600. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  601. return -1;
  602. }
  603. if (mydesc) {
  604. was_router_added_t added;
  605. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
  606. if (!ri) {
  607. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  608. return -1;
  609. }
  610. added = dirserv_add_descriptor(ri, &m, "self");
  611. if (!WRA_WAS_ADDED(added)) {
  612. if (!WRA_WAS_OUTDATED(added)) {
  613. log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
  614. m?m:"<unknown error>");
  615. return -1;
  616. } else {
  617. /* If the descriptor was outdated, that's ok. This can happen
  618. * when some config options are toggled that affect workers, but
  619. * we don't really need new keys yet so the descriptor doesn't
  620. * change and the old one is still fresh. */
  621. log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
  622. "after key init: %s. This is usually not a problem.",
  623. m?m:"<unknown error>");
  624. }
  625. }
  626. }
  627. }
  628. /* 5. Dump fingerprint to 'fingerprint' */
  629. keydir = get_datadir_fname("fingerprint");
  630. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  631. if (crypto_pk_get_fingerprint(get_server_identity_key(),
  632. fingerprint, 0) < 0) {
  633. log_err(LD_GENERAL,"Error computing fingerprint");
  634. tor_free(keydir);
  635. return -1;
  636. }
  637. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  638. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  639. "%s %s\n",options->Nickname, fingerprint) < 0) {
  640. log_err(LD_GENERAL,"Error writing fingerprint line");
  641. tor_free(keydir);
  642. return -1;
  643. }
  644. /* Check whether we need to write the fingerprint file. */
  645. cp = NULL;
  646. if (file_status(keydir) == FN_FILE)
  647. cp = read_file_to_str(keydir, 0, NULL);
  648. if (!cp || strcmp(cp, fingerprint_line)) {
  649. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  650. log_err(LD_FS, "Error writing fingerprint line to file");
  651. tor_free(keydir);
  652. tor_free(cp);
  653. return -1;
  654. }
  655. }
  656. tor_free(cp);
  657. tor_free(keydir);
  658. log(LOG_NOTICE, LD_GENERAL,
  659. "Your Tor server's identity key fingerprint is '%s %s'",
  660. options->Nickname, fingerprint);
  661. if (!authdir_mode(options))
  662. return 0;
  663. /* 6. [authdirserver only] load approved-routers file */
  664. if (dirserv_load_fingerprint_file() < 0) {
  665. log_err(LD_GENERAL,"Error loading fingerprints");
  666. return -1;
  667. }
  668. /* 6b. [authdirserver only] add own key to approved directories. */
  669. crypto_pk_get_digest(get_server_identity_key(), digest);
  670. type = ((options->V1AuthoritativeDir ? V1_DIRINFO : NO_DIRINFO) |
  671. (options->V2AuthoritativeDir ? V2_DIRINFO : NO_DIRINFO) |
  672. (options->V3AuthoritativeDir ?
  673. (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
  674. (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO) |
  675. (options->HSAuthoritativeDir ? HIDSERV_DIRINFO : NO_DIRINFO));
  676. ds = router_get_trusteddirserver_by_digest(digest);
  677. if (!ds) {
  678. ds = add_trusted_dir_server(options->Nickname, NULL,
  679. router_get_advertised_dir_port(options, 0),
  680. router_get_advertised_or_port(options),
  681. digest,
  682. v3_digest,
  683. type);
  684. if (!ds) {
  685. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  686. "couldn't add ourselves to the authority list. Failing.");
  687. return -1;
  688. }
  689. }
  690. if (ds->type != type) {
  691. log_warn(LD_DIR, "Configured authority type does not match authority "
  692. "type in DirServer list. Adjusting. (%d v %d)",
  693. type, ds->type);
  694. ds->type = type;
  695. }
  696. if (v3_digest_set && (ds->type & V3_DIRINFO) &&
  697. tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  698. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  699. "DirServer line. Adjusting.");
  700. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  701. }
  702. if (cert) { /* add my own cert to the list of known certs */
  703. log_info(LD_DIR, "adding my own v3 cert");
  704. if (trusted_dirs_load_certs_from_string(
  705. cert->cache_info.signed_descriptor_body, 0, 0)<0) {
  706. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  707. return -1;
  708. }
  709. }
  710. return 0; /* success */
  711. }
  712. /* Keep track of whether we should upload our server descriptor,
  713. * and what type of server we are.
  714. */
  715. /** Whether we can reach our ORPort from the outside. */
  716. static int can_reach_or_port = 0;
  717. /** Whether we can reach our DirPort from the outside. */
  718. static int can_reach_dir_port = 0;
  719. /** Forget what we have learned about our reachability status. */
  720. void
  721. router_reset_reachability(void)
  722. {
  723. can_reach_or_port = can_reach_dir_port = 0;
  724. }
  725. /** Return 1 if ORPort is known reachable; else return 0. */
  726. int
  727. check_whether_orport_reachable(void)
  728. {
  729. const or_options_t *options = get_options();
  730. return options->AssumeReachable ||
  731. can_reach_or_port;
  732. }
  733. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  734. int
  735. check_whether_dirport_reachable(void)
  736. {
  737. const or_options_t *options = get_options();
  738. return !options->DirPort ||
  739. options->AssumeReachable ||
  740. net_is_disabled() ||
  741. can_reach_dir_port;
  742. }
  743. /** Look at a variety of factors, and return 0 if we don't want to
  744. * advertise the fact that we have a DirPort open. Else return the
  745. * DirPort we want to advertise.
  746. *
  747. * Log a helpful message if we change our mind about whether to publish
  748. * a DirPort.
  749. */
  750. static int
  751. decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
  752. {
  753. static int advertising=1; /* start out assuming we will advertise */
  754. int new_choice=1;
  755. const char *reason = NULL;
  756. /* Section one: reasons to publish or not publish that aren't
  757. * worth mentioning to the user, either because they're obvious
  758. * or because they're normal behavior. */
  759. if (!dir_port) /* short circuit the rest of the function */
  760. return 0;
  761. if (authdir_mode(options)) /* always publish */
  762. return dir_port;
  763. if (net_is_disabled())
  764. return 0;
  765. if (!check_whether_dirport_reachable())
  766. return 0;
  767. if (!router_get_advertised_dir_port(options, dir_port))
  768. return 0;
  769. /* Section two: reasons to publish or not publish that the user
  770. * might find surprising. These are generally config options that
  771. * make us choose not to publish. */
  772. if (accounting_is_enabled(options)) {
  773. /* Don't spend bytes for directory traffic if we could end up hibernating,
  774. * but allow DirPort otherwise. Some people set AccountingMax because
  775. * they're confused or to get statistics. */
  776. int interval_length = accounting_get_interval_length();
  777. uint32_t effective_bw = get_effective_bwrate(options);
  778. if (!interval_length) {
  779. log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
  780. "seconds long. Raising to 1.");
  781. interval_length = 1;
  782. }
  783. log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
  784. "bwrate: %u, AccountingMax: "U64_FORMAT", "
  785. "accounting interval length %d", effective_bw,
  786. U64_PRINTF_ARG(options->AccountingMax),
  787. interval_length);
  788. if (effective_bw >=
  789. options->AccountingMax / interval_length) {
  790. new_choice = 0;
  791. reason = "AccountingMax enabled";
  792. }
  793. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  794. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  795. (options->RelayBandwidthRate > 0 &&
  796. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  797. /* if we're advertising a small amount */
  798. new_choice = 0;
  799. reason = "BandwidthRate under 50KB";
  800. }
  801. if (advertising != new_choice) {
  802. if (new_choice == 1) {
  803. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  804. } else {
  805. tor_assert(reason);
  806. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  807. }
  808. advertising = new_choice;
  809. }
  810. return advertising ? dir_port : 0;
  811. }
  812. /** Some time has passed, or we just got new directory information.
  813. * See if we currently believe our ORPort or DirPort to be
  814. * unreachable. If so, launch a new test for it.
  815. *
  816. * For ORPort, we simply try making a circuit that ends at ourselves.
  817. * Success is noticed in onionskin_answer().
  818. *
  819. * For DirPort, we make a connection via Tor to our DirPort and ask
  820. * for our own server descriptor.
  821. * Success is noticed in connection_dir_client_reached_eof().
  822. */
  823. void
  824. consider_testing_reachability(int test_or, int test_dir)
  825. {
  826. const routerinfo_t *me = router_get_my_routerinfo();
  827. int orport_reachable = check_whether_orport_reachable();
  828. tor_addr_t addr;
  829. const or_options_t *options = get_options();
  830. if (!me)
  831. return;
  832. if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
  833. options->StrictNodes) {
  834. /* If we've excluded ourself, and StrictNodes is set, we can't test
  835. * ourself. */
  836. if (test_or || test_dir) {
  837. #define SELF_EXCLUDED_WARN_INTERVAL 3600
  838. static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
  839. char *msg;
  840. if ((msg = rate_limit_log(&warning_limit, approx_time()))) {
  841. log_warn(LD_CIRC, "Can't peform self-tests for this relay: we have "
  842. "listed ourself in ExcludeNodes, and StrictNodes is set. "
  843. "We cannot learn whether we are usable, and will not "
  844. "be able to advertise ourself.%s", msg);
  845. tor_free(msg);
  846. }
  847. }
  848. return;
  849. }
  850. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  851. extend_info_t *ei;
  852. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  853. !orport_reachable ? "reachability" : "bandwidth",
  854. me->address, me->or_port);
  855. /* XXX IPv6 self testing IPv6 orports will need pref_addr */
  856. ei = extend_info_from_router(me, 0);
  857. circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
  858. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  859. extend_info_free(ei);
  860. }
  861. tor_addr_from_ipv4h(&addr, me->addr);
  862. if (test_dir && !check_whether_dirport_reachable() &&
  863. !connection_get_by_type_addr_port_purpose(
  864. CONN_TYPE_DIR, &addr, me->dir_port,
  865. DIR_PURPOSE_FETCH_SERVERDESC)) {
  866. /* ask myself, via tor, for my server descriptor. */
  867. directory_initiate_command(me->address, &addr,
  868. me->or_port, me->dir_port,
  869. 0, /* does not matter */
  870. 0, me->cache_info.identity_digest,
  871. DIR_PURPOSE_FETCH_SERVERDESC,
  872. ROUTER_PURPOSE_GENERAL,
  873. 1, "authority.z", NULL, 0, 0);
  874. }
  875. }
  876. /** Annotate that we found our ORPort reachable. */
  877. void
  878. router_orport_found_reachable(void)
  879. {
  880. const routerinfo_t *me = router_get_my_routerinfo();
  881. if (!can_reach_or_port && me) {
  882. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  883. "the outside. Excellent.%s",
  884. get_options()->_PublishServerDescriptor != NO_DIRINFO ?
  885. " Publishing server descriptor." : "");
  886. can_reach_or_port = 1;
  887. mark_my_descriptor_dirty("ORPort found reachable");
  888. control_event_server_status(LOG_NOTICE,
  889. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  890. me->address, me->or_port);
  891. }
  892. }
  893. /** Annotate that we found our DirPort reachable. */
  894. void
  895. router_dirport_found_reachable(void)
  896. {
  897. const routerinfo_t *me = router_get_my_routerinfo();
  898. if (!can_reach_dir_port && me) {
  899. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  900. "from the outside. Excellent.");
  901. can_reach_dir_port = 1;
  902. if (decide_to_advertise_dirport(get_options(), me->dir_port))
  903. mark_my_descriptor_dirty("DirPort found reachable");
  904. control_event_server_status(LOG_NOTICE,
  905. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  906. me->address, me->dir_port);
  907. }
  908. }
  909. /** We have enough testing circuits open. Send a bunch of "drop"
  910. * cells down each of them, to exercise our bandwidth. */
  911. void
  912. router_perform_bandwidth_test(int num_circs, time_t now)
  913. {
  914. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  915. int max_cells = num_cells < CIRCWINDOW_START ?
  916. num_cells : CIRCWINDOW_START;
  917. int cells_per_circuit = max_cells / num_circs;
  918. origin_circuit_t *circ = NULL;
  919. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  920. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  921. CIRCUIT_PURPOSE_TESTING))) {
  922. /* dump cells_per_circuit drop cells onto this circ */
  923. int i = cells_per_circuit;
  924. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  925. continue;
  926. circ->_base.timestamp_dirty = now;
  927. while (i-- > 0) {
  928. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  929. RELAY_COMMAND_DROP,
  930. NULL, 0, circ->cpath->prev)<0) {
  931. return; /* stop if error */
  932. }
  933. }
  934. }
  935. }
  936. /** Return true iff our network is in some sense disabled: either we're
  937. * hibernating, entering hibernation, or */
  938. int
  939. net_is_disabled(void)
  940. {
  941. return get_options()->DisableNetwork || we_are_hibernating();
  942. }
  943. /** Return true iff we believe ourselves to be an authoritative
  944. * directory server.
  945. */
  946. int
  947. authdir_mode(const or_options_t *options)
  948. {
  949. return options->AuthoritativeDir != 0;
  950. }
  951. /** Return true iff we believe ourselves to be a v1 authoritative
  952. * directory server.
  953. */
  954. int
  955. authdir_mode_v1(const or_options_t *options)
  956. {
  957. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  958. }
  959. /** Return true iff we believe ourselves to be a v2 authoritative
  960. * directory server.
  961. */
  962. int
  963. authdir_mode_v2(const or_options_t *options)
  964. {
  965. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  966. }
  967. /** Return true iff we believe ourselves to be a v3 authoritative
  968. * directory server.
  969. */
  970. int
  971. authdir_mode_v3(const or_options_t *options)
  972. {
  973. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  974. }
  975. /** Return true iff we are a v1, v2, or v3 directory authority. */
  976. int
  977. authdir_mode_any_main(const or_options_t *options)
  978. {
  979. return options->V1AuthoritativeDir ||
  980. options->V2AuthoritativeDir ||
  981. options->V3AuthoritativeDir;
  982. }
  983. /** Return true if we believe ourselves to be any kind of
  984. * authoritative directory beyond just a hidserv authority. */
  985. int
  986. authdir_mode_any_nonhidserv(const or_options_t *options)
  987. {
  988. return options->BridgeAuthoritativeDir ||
  989. authdir_mode_any_main(options);
  990. }
  991. /** Return true iff we are an authoritative directory server that is
  992. * authoritative about receiving and serving descriptors of type
  993. * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
  994. int
  995. authdir_mode_handles_descs(const or_options_t *options, int purpose)
  996. {
  997. if (purpose < 0)
  998. return authdir_mode_any_nonhidserv(options);
  999. else if (purpose == ROUTER_PURPOSE_GENERAL)
  1000. return authdir_mode_any_main(options);
  1001. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  1002. return (options->BridgeAuthoritativeDir);
  1003. else
  1004. return 0;
  1005. }
  1006. /** Return true iff we are an authoritative directory server that
  1007. * publishes its own network statuses.
  1008. */
  1009. int
  1010. authdir_mode_publishes_statuses(const or_options_t *options)
  1011. {
  1012. if (authdir_mode_bridge(options))
  1013. return 0;
  1014. return authdir_mode_any_nonhidserv(options);
  1015. }
  1016. /** Return true iff we are an authoritative directory server that
  1017. * tests reachability of the descriptors it learns about.
  1018. */
  1019. int
  1020. authdir_mode_tests_reachability(const or_options_t *options)
  1021. {
  1022. return authdir_mode_handles_descs(options, -1);
  1023. }
  1024. /** Return true iff we believe ourselves to be a bridge authoritative
  1025. * directory server.
  1026. */
  1027. int
  1028. authdir_mode_bridge(const or_options_t *options)
  1029. {
  1030. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  1031. }
  1032. /** Return true iff we are trying to be a server.
  1033. */
  1034. int
  1035. server_mode(const or_options_t *options)
  1036. {
  1037. if (options->ClientOnly) return 0;
  1038. return (options->ORPort || options->ORListenAddress);
  1039. }
  1040. /** Return true iff we are trying to be a non-bridge server.
  1041. */
  1042. int
  1043. public_server_mode(const or_options_t *options)
  1044. {
  1045. if (!server_mode(options)) return 0;
  1046. return (!options->BridgeRelay);
  1047. }
  1048. /** Return true iff the combination of options in <b>options</b> and parameters
  1049. * in the consensus mean that we don't want to allow exits from circuits
  1050. * we got from addresses not known to be servers. */
  1051. int
  1052. should_refuse_unknown_exits(const or_options_t *options)
  1053. {
  1054. if (options->RefuseUnknownExits != -1) {
  1055. return options->RefuseUnknownExits;
  1056. } else {
  1057. return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
  1058. }
  1059. }
  1060. /** Remember if we've advertised ourselves to the dirservers. */
  1061. static int server_is_advertised=0;
  1062. /** Return true iff we have published our descriptor lately.
  1063. */
  1064. int
  1065. advertised_server_mode(void)
  1066. {
  1067. return server_is_advertised;
  1068. }
  1069. /**
  1070. * Called with a boolean: set whether we have recently published our
  1071. * descriptor.
  1072. */
  1073. static void
  1074. set_server_advertised(int s)
  1075. {
  1076. server_is_advertised = s;
  1077. }
  1078. /** Return true iff we are trying to proxy client connections. */
  1079. int
  1080. proxy_mode(const or_options_t *options)
  1081. {
  1082. (void)options;
  1083. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1084. if (p->type == CONN_TYPE_AP_LISTENER ||
  1085. p->type == CONN_TYPE_AP_TRANS_LISTENER ||
  1086. p->type == CONN_TYPE_AP_DNS_LISTENER ||
  1087. p->type == CONN_TYPE_AP_NATD_LISTENER)
  1088. return 1;
  1089. } SMARTLIST_FOREACH_END(p);
  1090. return 0;
  1091. }
  1092. /** Decide if we're a publishable server. We are a publishable server if:
  1093. * - We don't have the ClientOnly option set
  1094. * and
  1095. * - We have the PublishServerDescriptor option set to non-empty
  1096. * and
  1097. * - We have ORPort set
  1098. * and
  1099. * - We believe we are reachable from the outside; or
  1100. * - We are an authoritative directory server.
  1101. */
  1102. static int
  1103. decide_if_publishable_server(void)
  1104. {
  1105. const or_options_t *options = get_options();
  1106. if (options->ClientOnly)
  1107. return 0;
  1108. if (options->_PublishServerDescriptor == NO_DIRINFO)
  1109. return 0;
  1110. if (!server_mode(options))
  1111. return 0;
  1112. if (authdir_mode(options))
  1113. return 1;
  1114. if (!router_get_advertised_or_port(options))
  1115. return 0;
  1116. return check_whether_orport_reachable();
  1117. }
  1118. /** Initiate server descriptor upload as reasonable (if server is publishable,
  1119. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  1120. *
  1121. * We need to rebuild the descriptor if it's dirty even if we're not
  1122. * uploading, because our reachability testing *uses* our descriptor to
  1123. * determine what IP address and ports to test.
  1124. */
  1125. void
  1126. consider_publishable_server(int force)
  1127. {
  1128. int rebuilt;
  1129. if (!server_mode(get_options()))
  1130. return;
  1131. rebuilt = router_rebuild_descriptor(0);
  1132. if (decide_if_publishable_server()) {
  1133. set_server_advertised(1);
  1134. if (rebuilt == 0)
  1135. router_upload_dir_desc_to_dirservers(force);
  1136. } else {
  1137. set_server_advertised(0);
  1138. }
  1139. }
  1140. /** Return the port of the first active listener of type
  1141. * <b>listener_type</b>. */
  1142. /** XXX not a very good interface. it's not reliable when there are
  1143. multiple listeners. */
  1144. uint16_t
  1145. router_get_active_listener_port_by_type(int listener_type)
  1146. {
  1147. /* Iterate all connections, find one of the right kind and return
  1148. the port. Not very sophisticated or fast, but effective. */
  1149. const connection_t *c = connection_get_by_type(listener_type);
  1150. if (c)
  1151. return c->port;
  1152. return 0;
  1153. }
  1154. /** Return the port that we should advertise as our ORPort; this is either
  1155. * the one configured in the ORPort option, or the one we actually bound to
  1156. * if ORPort is "auto".
  1157. */
  1158. uint16_t
  1159. router_get_advertised_or_port(const or_options_t *options)
  1160. {
  1161. int port = get_primary_or_port();
  1162. (void)options;
  1163. /* If the port is in 'auto' mode, we have to use
  1164. router_get_listener_port_by_type(). */
  1165. if (port == CFG_AUTO_PORT)
  1166. return router_get_active_listener_port_by_type(CONN_TYPE_OR_LISTENER);
  1167. return port;
  1168. }
  1169. /** Return the port that we should advertise as our DirPort;
  1170. * this is one of three possibilities:
  1171. * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
  1172. * the one configured in the DirPort option,
  1173. * or the one we actually bound to if DirPort is "auto". */
  1174. uint16_t
  1175. router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
  1176. {
  1177. int dirport_configured = get_primary_dir_port();
  1178. (void)options;
  1179. if (!dirport_configured)
  1180. return dirport;
  1181. if (dirport_configured == CFG_AUTO_PORT)
  1182. return router_get_active_listener_port_by_type(CONN_TYPE_DIR_LISTENER);
  1183. return dirport_configured;
  1184. }
  1185. /*
  1186. * OR descriptor generation.
  1187. */
  1188. /** My routerinfo. */
  1189. static routerinfo_t *desc_routerinfo = NULL;
  1190. /** My extrainfo */
  1191. static extrainfo_t *desc_extrainfo = NULL;
  1192. /** Why did we most recently decide to regenerate our descriptor? Used to
  1193. * tell the authorities why we're sending it to them. */
  1194. static const char *desc_gen_reason = NULL;
  1195. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  1196. * now. */
  1197. static time_t desc_clean_since = 0;
  1198. /** Why did we mark the descriptor dirty? */
  1199. static const char *desc_dirty_reason = NULL;
  1200. /** Boolean: do we need to regenerate the above? */
  1201. static int desc_needs_upload = 0;
  1202. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1203. * descriptor successfully yet, try to upload our signed descriptor to
  1204. * all the directory servers we know about.
  1205. */
  1206. void
  1207. router_upload_dir_desc_to_dirservers(int force)
  1208. {
  1209. const routerinfo_t *ri;
  1210. extrainfo_t *ei;
  1211. char *msg;
  1212. size_t desc_len, extra_len = 0, total_len;
  1213. dirinfo_type_t auth = get_options()->_PublishServerDescriptor;
  1214. ri = router_get_my_routerinfo();
  1215. if (!ri) {
  1216. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1217. return;
  1218. }
  1219. ei = router_get_my_extrainfo();
  1220. if (auth == NO_DIRINFO)
  1221. return;
  1222. if (!force && !desc_needs_upload)
  1223. return;
  1224. log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
  1225. force ? " (forced)" : "");
  1226. desc_needs_upload = 0;
  1227. desc_len = ri->cache_info.signed_descriptor_len;
  1228. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1229. total_len = desc_len + extra_len + 1;
  1230. msg = tor_malloc(total_len);
  1231. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1232. if (ei) {
  1233. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1234. }
  1235. msg[desc_len+extra_len] = 0;
  1236. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1237. (auth & BRIDGE_DIRINFO) ?
  1238. ROUTER_PURPOSE_BRIDGE :
  1239. ROUTER_PURPOSE_GENERAL,
  1240. auth, msg, desc_len, extra_len);
  1241. tor_free(msg);
  1242. }
  1243. /** OR only: Check whether my exit policy says to allow connection to
  1244. * conn. Return 0 if we accept; non-0 if we reject.
  1245. */
  1246. int
  1247. router_compare_to_my_exit_policy(edge_connection_t *conn)
  1248. {
  1249. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1250. return -1;
  1251. /* make sure it's resolved to something. this way we can't get a
  1252. 'maybe' below. */
  1253. if (tor_addr_is_null(&conn->_base.addr))
  1254. return -1;
  1255. /* XXXX IPv6 */
  1256. if (tor_addr_family(&conn->_base.addr) != AF_INET)
  1257. return -1;
  1258. return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
  1259. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  1260. }
  1261. /** Return true iff my exit policy is reject *:*. Return -1 if we don't
  1262. * have a descriptor */
  1263. int
  1264. router_my_exit_policy_is_reject_star(void)
  1265. {
  1266. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1267. return -1;
  1268. return desc_routerinfo->policy_is_reject_star;
  1269. }
  1270. /** Return true iff I'm a server and <b>digest</b> is equal to
  1271. * my server identity key digest. */
  1272. int
  1273. router_digest_is_me(const char *digest)
  1274. {
  1275. return (server_identitykey &&
  1276. tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
  1277. }
  1278. /** Return true iff I'm a server and <b>digest</b> is equal to
  1279. * my identity digest. */
  1280. int
  1281. router_extrainfo_digest_is_me(const char *digest)
  1282. {
  1283. extrainfo_t *ei = router_get_my_extrainfo();
  1284. if (!ei)
  1285. return 0;
  1286. return tor_memeq(digest,
  1287. ei->cache_info.signed_descriptor_digest,
  1288. DIGEST_LEN);
  1289. }
  1290. /** A wrapper around router_digest_is_me(). */
  1291. int
  1292. router_is_me(const routerinfo_t *router)
  1293. {
  1294. return router_digest_is_me(router->cache_info.identity_digest);
  1295. }
  1296. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  1297. int
  1298. router_fingerprint_is_me(const char *fp)
  1299. {
  1300. char digest[DIGEST_LEN];
  1301. if (strlen(fp) == HEX_DIGEST_LEN &&
  1302. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  1303. return router_digest_is_me(digest);
  1304. return 0;
  1305. }
  1306. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1307. * necessary. Return NULL on error, or if called on an OP. */
  1308. const routerinfo_t *
  1309. router_get_my_routerinfo(void)
  1310. {
  1311. if (!server_mode(get_options()))
  1312. return NULL;
  1313. if (router_rebuild_descriptor(0))
  1314. return NULL;
  1315. return desc_routerinfo;
  1316. }
  1317. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1318. * one if necessary. Return NULL on error.
  1319. */
  1320. const char *
  1321. router_get_my_descriptor(void)
  1322. {
  1323. const char *body;
  1324. if (!router_get_my_routerinfo())
  1325. return NULL;
  1326. /* Make sure this is nul-terminated. */
  1327. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1328. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1329. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1330. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1331. return body;
  1332. }
  1333. /** Return the extrainfo document for this OR, or NULL if we have none.
  1334. * Rebuilt it (and the server descriptor) if necessary. */
  1335. extrainfo_t *
  1336. router_get_my_extrainfo(void)
  1337. {
  1338. if (!server_mode(get_options()))
  1339. return NULL;
  1340. if (router_rebuild_descriptor(0))
  1341. return NULL;
  1342. return desc_extrainfo;
  1343. }
  1344. /** Return a human-readable string describing what triggered us to generate
  1345. * our current descriptor, or NULL if we don't know. */
  1346. const char *
  1347. router_get_descriptor_gen_reason(void)
  1348. {
  1349. return desc_gen_reason;
  1350. }
  1351. /** A list of nicknames that we've warned about including in our family
  1352. * declaration verbatim rather than as digests. */
  1353. static smartlist_t *warned_nonexistent_family = NULL;
  1354. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1355. /** Make a current best guess at our address, either because
  1356. * it's configured in torrc, or because we've learned it from
  1357. * dirserver headers. Place the answer in *<b>addr</b> and return
  1358. * 0 on success, else return -1 if we have no guess. */
  1359. int
  1360. router_pick_published_address(const or_options_t *options, uint32_t *addr)
  1361. {
  1362. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1363. log_info(LD_CONFIG, "Could not determine our address locally. "
  1364. "Checking if directory headers provide any hints.");
  1365. if (router_guess_address_from_dir_headers(addr) < 0) {
  1366. log_info(LD_CONFIG, "No hints from directory headers either. "
  1367. "Will try again later.");
  1368. return -1;
  1369. }
  1370. }
  1371. log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
  1372. return 0;
  1373. }
  1374. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1375. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1376. * Return 0 on success, -1 on temporary error.
  1377. */
  1378. int
  1379. router_rebuild_descriptor(int force)
  1380. {
  1381. routerinfo_t *ri;
  1382. extrainfo_t *ei;
  1383. uint32_t addr;
  1384. char platform[256];
  1385. int hibernating = we_are_hibernating();
  1386. const or_options_t *options = get_options();
  1387. if (desc_clean_since && !force)
  1388. return 0;
  1389. if (router_pick_published_address(options, &addr) < 0 ||
  1390. router_get_advertised_or_port(options) == 0) {
  1391. /* Stop trying to rebuild our descriptor every second. We'll
  1392. * learn that it's time to try again when ip_address_changed()
  1393. * marks it dirty. */
  1394. desc_clean_since = time(NULL);
  1395. return -1;
  1396. }
  1397. log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
  1398. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1399. ri->cache_info.routerlist_index = -1;
  1400. ri->address = tor_dup_ip(addr);
  1401. ri->nickname = tor_strdup(options->Nickname);
  1402. ri->addr = addr;
  1403. ri->or_port = router_get_advertised_or_port(options);
  1404. ri->dir_port = router_get_advertised_dir_port(options, 0);
  1405. ri->cache_info.published_on = time(NULL);
  1406. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1407. * main thread */
  1408. if (options->BridgeRelay) {
  1409. /* For now, only bridges advertise an ipv6 or-address. And only one. */
  1410. const port_cfg_t *ipv6_orport = NULL;
  1411. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1412. if (p->type == CONN_TYPE_OR_LISTENER &&
  1413. ! p->no_advertise &&
  1414. ! p->ipv4_only &&
  1415. tor_addr_family(&p->addr) == AF_INET6) {
  1416. if (! tor_addr_is_internal(&p->addr, 0)) {
  1417. ipv6_orport = p;
  1418. break;
  1419. } else {
  1420. char addrbuf[TOR_ADDR_BUF_LEN];
  1421. log_warn(LD_CONFIG,
  1422. "Unable to use configured IPv6 address \"%s\" in a "
  1423. "descriptor. Skipping it. "
  1424. "Try specifying a globally reachable address explicitly. ",
  1425. tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
  1426. }
  1427. }
  1428. } SMARTLIST_FOREACH_END(p);
  1429. if (ipv6_orport) {
  1430. tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
  1431. ri->ipv6_orport = ipv6_orport->port;
  1432. }
  1433. }
  1434. ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
  1435. if (crypto_pk_get_digest(ri->identity_pkey,
  1436. ri->cache_info.identity_digest)<0) {
  1437. routerinfo_free(ri);
  1438. return -1;
  1439. }
  1440. get_platform_str(platform, sizeof(platform));
  1441. ri->platform = tor_strdup(platform);
  1442. /* compute ri->bandwidthrate as the min of various options */
  1443. ri->bandwidthrate = get_effective_bwrate(options);
  1444. /* and compute ri->bandwidthburst similarly */
  1445. ri->bandwidthburst = get_effective_bwburst(options);
  1446. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1447. if (dns_seems_to_be_broken() || has_dns_init_failed()) {
  1448. /* DNS is screwed up; don't claim to be an exit. */
  1449. policies_exit_policy_append_reject_star(&ri->exit_policy);
  1450. } else {
  1451. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1452. options->ExitPolicyRejectPrivate,
  1453. ri->address, !options->BridgeRelay);
  1454. }
  1455. ri->policy_is_reject_star =
  1456. policy_is_reject_star(ri->exit_policy);
  1457. #if 0
  1458. /* XXXX NM NM I belive this is safe to remove */
  1459. if (authdir_mode(options))
  1460. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1461. #endif
  1462. if (options->MyFamily && ! options->BridgeRelay) {
  1463. smartlist_t *family;
  1464. if (!warned_nonexistent_family)
  1465. warned_nonexistent_family = smartlist_new();
  1466. family = smartlist_new();
  1467. ri->declared_family = smartlist_new();
  1468. smartlist_split_string(family, options->MyFamily, ",",
  1469. SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1470. SMARTLIST_FOREACH_BEGIN(family, char *, name) {
  1471. const node_t *member;
  1472. if (!strcasecmp(name, options->Nickname))
  1473. goto skip; /* Don't list ourself, that's redundant */
  1474. else
  1475. member = node_get_by_nickname(name, 1);
  1476. if (!member) {
  1477. int is_legal = is_legal_nickname_or_hexdigest(name);
  1478. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1479. !is_legal_hexdigest(name)) {
  1480. if (is_legal)
  1481. log_warn(LD_CONFIG,
  1482. "I have no descriptor for the router named \"%s\" in my "
  1483. "declared family; I'll use the nickname as is, but "
  1484. "this may confuse clients.", name);
  1485. else
  1486. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1487. "declared family, but that isn't a legal nickname. "
  1488. "Skipping it.", escaped(name));
  1489. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1490. }
  1491. if (is_legal) {
  1492. smartlist_add(ri->declared_family, name);
  1493. name = NULL;
  1494. }
  1495. } else if (router_digest_is_me(member->identity)) {
  1496. /* Don't list ourself in our own family; that's redundant */
  1497. /* XXX shouldn't be possible */
  1498. } else {
  1499. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1500. fp[0] = '$';
  1501. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1502. member->identity, DIGEST_LEN);
  1503. smartlist_add(ri->declared_family, fp);
  1504. if (smartlist_string_isin(warned_nonexistent_family, name))
  1505. smartlist_string_remove(warned_nonexistent_family, name);
  1506. }
  1507. skip:
  1508. tor_free(name);
  1509. } SMARTLIST_FOREACH_END(name);
  1510. /* remove duplicates from the list */
  1511. smartlist_sort_strings(ri->declared_family);
  1512. smartlist_uniq_strings(ri->declared_family);
  1513. smartlist_free(family);
  1514. }
  1515. /* Now generate the extrainfo. */
  1516. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1517. ei->cache_info.is_extrainfo = 1;
  1518. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1519. ei->cache_info.published_on = ri->cache_info.published_on;
  1520. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1521. DIGEST_LEN);
  1522. if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
  1523. ei, get_server_identity_key()) < 0) {
  1524. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1525. extrainfo_free(ei);
  1526. ei = NULL;
  1527. } else {
  1528. ei->cache_info.signed_descriptor_len =
  1529. strlen(ei->cache_info.signed_descriptor_body);
  1530. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1531. ei->cache_info.signed_descriptor_len,
  1532. ei->cache_info.signed_descriptor_digest);
  1533. }
  1534. /* Now finish the router descriptor. */
  1535. if (ei) {
  1536. memcpy(ri->cache_info.extra_info_digest,
  1537. ei->cache_info.signed_descriptor_digest,
  1538. DIGEST_LEN);
  1539. } else {
  1540. /* ri was allocated with tor_malloc_zero, so there is no need to
  1541. * zero ri->cache_info.extra_info_digest here. */
  1542. }
  1543. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1544. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1545. ri, get_server_identity_key()) < 0) {
  1546. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1547. routerinfo_free(ri);
  1548. extrainfo_free(ei);
  1549. return -1;
  1550. }
  1551. ri->cache_info.signed_descriptor_len =
  1552. strlen(ri->cache_info.signed_descriptor_body);
  1553. ri->purpose =
  1554. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1555. if (options->BridgeRelay) {
  1556. /* Bridges shouldn't be able to send their descriptors unencrypted,
  1557. anyway, since they don't have a DirPort, and always connect to the
  1558. bridge authority anonymously. But just in case they somehow think of
  1559. sending them on an unencrypted connection, don't allow them to try. */
  1560. ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 0;
  1561. } else {
  1562. ri->cache_info.send_unencrypted = ei->cache_info.send_unencrypted = 1;
  1563. }
  1564. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1565. strlen(ri->cache_info.signed_descriptor_body),
  1566. ri->cache_info.signed_descriptor_digest);
  1567. if (ei) {
  1568. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1569. }
  1570. routerinfo_free(desc_routerinfo);
  1571. desc_routerinfo = ri;
  1572. extrainfo_free(desc_extrainfo);
  1573. desc_extrainfo = ei;
  1574. desc_clean_since = time(NULL);
  1575. desc_needs_upload = 1;
  1576. desc_gen_reason = desc_dirty_reason;
  1577. desc_dirty_reason = NULL;
  1578. control_event_my_descriptor_changed();
  1579. return 0;
  1580. }
  1581. /** If our router descriptor ever goes this long without being regenerated
  1582. * because something changed, we force an immediate regenerate-and-upload. */
  1583. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  1584. /** If our router descriptor seems to be missing or unacceptable according
  1585. * to the authorities, regenerate and reupload it _this_ often. */
  1586. #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
  1587. /** Mark descriptor out of date if it's been "too long" since we last tried
  1588. * to upload one. */
  1589. void
  1590. mark_my_descriptor_dirty_if_too_old(time_t now)
  1591. {
  1592. networkstatus_t *ns;
  1593. const routerstatus_t *rs;
  1594. const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
  1595. const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
  1596. const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
  1597. /* If it's already dirty, don't mark it. */
  1598. if (! desc_clean_since)
  1599. return;
  1600. /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
  1601. * time to rebuild it. */
  1602. if (desc_clean_since < slow_cutoff) {
  1603. mark_my_descriptor_dirty("time for new descriptor");
  1604. return;
  1605. }
  1606. /* Now we see whether we want to be retrying frequently or no. The
  1607. * rule here is that we'll retry frequently if we aren't listed in the
  1608. * live consensus we have, or if the publication time of the
  1609. * descriptor listed for us in the consensus is very old. */
  1610. ns = networkstatus_get_live_consensus(now);
  1611. if (ns) {
  1612. rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
  1613. if (rs == NULL)
  1614. retry_fast_reason = "not listed in consensus";
  1615. else if (rs->published_on < slow_cutoff)
  1616. retry_fast_reason = "version listed in consensus is quite old";
  1617. }
  1618. if (retry_fast_reason && desc_clean_since < fast_cutoff)
  1619. mark_my_descriptor_dirty(retry_fast_reason);
  1620. }
  1621. /** Call when the current descriptor is out of date. */
  1622. void
  1623. mark_my_descriptor_dirty(const char *reason)
  1624. {
  1625. const or_options_t *options = get_options();
  1626. if (server_mode(options) && options->_PublishServerDescriptor)
  1627. log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
  1628. desc_clean_since = 0;
  1629. if (!desc_dirty_reason)
  1630. desc_dirty_reason = reason;
  1631. }
  1632. /** How frequently will we republish our descriptor because of large (factor
  1633. * of 2) shifts in estimated bandwidth? */
  1634. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1635. /** Check whether bandwidth has changed a lot since the last time we announced
  1636. * bandwidth. If so, mark our descriptor dirty. */
  1637. void
  1638. check_descriptor_bandwidth_changed(time_t now)
  1639. {
  1640. static time_t last_changed = 0;
  1641. uint64_t prev, cur;
  1642. if (!desc_routerinfo)
  1643. return;
  1644. prev = desc_routerinfo->bandwidthcapacity;
  1645. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1646. if ((prev != cur && (!prev || !cur)) ||
  1647. cur > prev*2 ||
  1648. cur < prev/2) {
  1649. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1650. log_info(LD_GENERAL,
  1651. "Measured bandwidth has changed; rebuilding descriptor.");
  1652. mark_my_descriptor_dirty("bandwidth has changed");
  1653. last_changed = now;
  1654. }
  1655. }
  1656. }
  1657. /** Note at log level severity that our best guess of address has changed from
  1658. * <b>prev</b> to <b>cur</b>. */
  1659. static void
  1660. log_addr_has_changed(int severity,
  1661. const tor_addr_t *prev,
  1662. const tor_addr_t *cur,
  1663. const char *source)
  1664. {
  1665. char addrbuf_prev[TOR_ADDR_BUF_LEN];
  1666. char addrbuf_cur[TOR_ADDR_BUF_LEN];
  1667. if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
  1668. strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
  1669. if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
  1670. strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
  1671. if (!tor_addr_is_null(prev))
  1672. log_fn(severity, LD_GENERAL,
  1673. "Our IP Address has changed from %s to %s; "
  1674. "rebuilding descriptor (source: %s).",
  1675. addrbuf_prev, addrbuf_cur, source);
  1676. else
  1677. log_notice(LD_GENERAL,
  1678. "Guessed our IP address as %s (source: %s).",
  1679. addrbuf_cur, source);
  1680. }
  1681. /** Check whether our own address as defined by the Address configuration
  1682. * has changed. This is for routers that get their address from a service
  1683. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1684. void
  1685. check_descriptor_ipaddress_changed(time_t now)
  1686. {
  1687. uint32_t prev, cur;
  1688. const or_options_t *options = get_options();
  1689. (void) now;
  1690. if (!desc_routerinfo)
  1691. return;
  1692. /* XXXX ipv6 */
  1693. prev = desc_routerinfo->addr;
  1694. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1695. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1696. return;
  1697. }
  1698. if (prev != cur) {
  1699. tor_addr_t tmp_prev, tmp_cur;
  1700. tor_addr_from_ipv4h(&tmp_prev, prev);
  1701. tor_addr_from_ipv4h(&tmp_cur, cur);
  1702. log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, "resolve");
  1703. ip_address_changed(0);
  1704. }
  1705. }
  1706. /** The most recently guessed value of our IP address, based on directory
  1707. * headers. */
  1708. static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
  1709. /** A directory server <b>d_conn</b> told us our IP address is
  1710. * <b>suggestion</b>.
  1711. * If this address is different from the one we think we are now, and
  1712. * if our computer doesn't actually know its IP address, then switch. */
  1713. void
  1714. router_new_address_suggestion(const char *suggestion,
  1715. const dir_connection_t *d_conn)
  1716. {
  1717. tor_addr_t addr;
  1718. uint32_t cur = 0; /* Current IPv4 address. */
  1719. const or_options_t *options = get_options();
  1720. /* first, learn what the IP address actually is */
  1721. if (tor_addr_parse(&addr, suggestion) == -1) {
  1722. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1723. escaped(suggestion));
  1724. return;
  1725. }
  1726. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1727. if (!server_mode(options)) {
  1728. tor_addr_copy(&last_guessed_ip, &addr);
  1729. return;
  1730. }
  1731. /* XXXX ipv6 */
  1732. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1733. /* We're all set -- we already know our address. Great. */
  1734. tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
  1735. need it later */
  1736. return;
  1737. }
  1738. if (tor_addr_is_internal(&addr, 0)) {
  1739. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1740. return;
  1741. }
  1742. if (tor_addr_eq(&d_conn->_base.addr, &addr)) {
  1743. /* Don't believe anybody who says our IP is their IP. */
  1744. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  1745. "but he's just reporting his own IP address. Ignoring.",
  1746. suggestion);
  1747. return;
  1748. }
  1749. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1750. * us an answer different from what we had the last time we managed to
  1751. * resolve it. */
  1752. if (!tor_addr_eq(&last_guessed_ip, &addr)) {
  1753. control_event_server_status(LOG_NOTICE,
  1754. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1755. suggestion);
  1756. log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
  1757. d_conn->_base.address);
  1758. ip_address_changed(0);
  1759. tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
  1760. will fetch it */
  1761. }
  1762. }
  1763. /** We failed to resolve our address locally, but we'd like to build
  1764. * a descriptor and publish / test reachability. If we have a guess
  1765. * about our address based on directory headers, answer it and return
  1766. * 0; else return -1. */
  1767. static int
  1768. router_guess_address_from_dir_headers(uint32_t *guess)
  1769. {
  1770. if (!tor_addr_is_null(&last_guessed_ip)) {
  1771. *guess = tor_addr_to_ipv4h(&last_guessed_ip);
  1772. return 0;
  1773. }
  1774. return -1;
  1775. }
  1776. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1777. * string describing the version of Tor and the operating system we're
  1778. * currently running on.
  1779. */
  1780. void
  1781. get_platform_str(char *platform, size_t len)
  1782. {
  1783. tor_snprintf(platform, len, "Tor %s on %s",
  1784. get_short_version(), get_uname());
  1785. }
  1786. /* XXX need to audit this thing and count fenceposts. maybe
  1787. * refactor so we don't have to keep asking if we're
  1788. * near the end of maxlen?
  1789. */
  1790. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1791. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1792. * with, encode the routerinfo as a signed server descriptor and write the
  1793. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1794. * failure, and the number of bytes used on success.
  1795. */
  1796. int
  1797. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1798. crypto_pk_t *ident_key)
  1799. {
  1800. char *onion_pkey; /* Onion key, PEM-encoded. */
  1801. char *identity_pkey; /* Identity key, PEM-encoded. */
  1802. char digest[DIGEST_LEN];
  1803. char published[ISO_TIME_LEN+1];
  1804. char fingerprint[FINGERPRINT_LEN+1];
  1805. int has_extra_info_digest;
  1806. char extra_info_digest[HEX_DIGEST_LEN+1];
  1807. size_t onion_pkeylen, identity_pkeylen;
  1808. size_t written;
  1809. int result=0;
  1810. addr_policy_t *tmpe;
  1811. char *family_line;
  1812. char *extra_or_address = NULL;
  1813. const or_options_t *options = get_options();
  1814. /* Make sure the identity key matches the one in the routerinfo. */
  1815. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1816. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1817. "match router's public key!");
  1818. return -1;
  1819. }
  1820. /* record our fingerprint, so we can include it in the descriptor */
  1821. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1822. log_err(LD_BUG,"Error computing fingerprint");
  1823. return -1;
  1824. }
  1825. /* PEM-encode the onion key */
  1826. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1827. &onion_pkey,&onion_pkeylen)<0) {
  1828. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1829. return -1;
  1830. }
  1831. /* PEM-encode the identity key */
  1832. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1833. &identity_pkey,&identity_pkeylen)<0) {
  1834. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1835. tor_free(onion_pkey);
  1836. return -1;
  1837. }
  1838. /* Encode the publication time. */
  1839. format_iso_time(published, router->cache_info.published_on);
  1840. if (router->declared_family && smartlist_len(router->declared_family)) {
  1841. char *family = smartlist_join_strings(router->declared_family,
  1842. " ", 0, NULL);
  1843. tor_asprintf(&family_line, "family %s\n", family);
  1844. tor_free(family);
  1845. } else {
  1846. family_line = tor_strdup("");
  1847. }
  1848. has_extra_info_digest =
  1849. ! tor_digest_is_zero(router->cache_info.extra_info_digest);
  1850. if (has_extra_info_digest) {
  1851. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1852. router->cache_info.extra_info_digest, DIGEST_LEN);
  1853. }
  1854. if (router->ipv6_orport &&
  1855. tor_addr_family(&router->ipv6_addr) == AF_INET6) {
  1856. char addr[TOR_ADDR_BUF_LEN];
  1857. const char *a;
  1858. a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
  1859. if (a) {
  1860. tor_asprintf(&extra_or_address,
  1861. "or-address %s:%d\n", a, router->ipv6_orport);
  1862. log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
  1863. }
  1864. }
  1865. /* Generate the easy portion of the router descriptor. */
  1866. result = tor_snprintf(s, maxlen,
  1867. "router %s %s %d 0 %d\n"
  1868. "%s"
  1869. "platform %s\n"
  1870. "opt protocols Link 1 2 Circuit 1\n"
  1871. "published %s\n"
  1872. "opt fingerprint %s\n"
  1873. "uptime %ld\n"
  1874. "bandwidth %d %d %d\n"
  1875. "%s%s%s%s"
  1876. "onion-key\n%s"
  1877. "signing-key\n%s"
  1878. "%s%s%s%s",
  1879. router->nickname,
  1880. router->address,
  1881. router->or_port,
  1882. decide_to_advertise_dirport(options, router->dir_port),
  1883. extra_or_address ? extra_or_address : "",
  1884. router->platform,
  1885. published,
  1886. fingerprint,
  1887. stats_n_seconds_working,
  1888. (int) router->bandwidthrate,
  1889. (int) router->bandwidthburst,
  1890. (int) router->bandwidthcapacity,
  1891. has_extra_info_digest ? "opt extra-info-digest " : "",
  1892. has_extra_info_digest ? extra_info_digest : "",
  1893. has_extra_info_digest ? "\n" : "",
  1894. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1895. onion_pkey, identity_pkey,
  1896. family_line,
  1897. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1898. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
  1899. options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
  1900. tor_free(family_line);
  1901. tor_free(onion_pkey);
  1902. tor_free(identity_pkey);
  1903. tor_free(extra_or_address);
  1904. if (result < 0) {
  1905. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1906. return -1;
  1907. }
  1908. /* From now on, we use 'written' to remember the current length of 's'. */
  1909. written = result;
  1910. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1911. const char *ci = options->ContactInfo;
  1912. if (strchr(ci, '\n') || strchr(ci, '\r'))
  1913. ci = escaped(ci);
  1914. result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
  1915. if (result<0) {
  1916. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1917. return -1;
  1918. }
  1919. written += result;
  1920. }
  1921. /* Write the exit policy to the end of 's'. */
  1922. if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
  1923. strlcat(s+written, "reject *:*\n", maxlen-written);
  1924. written += strlen("reject *:*\n");
  1925. tmpe = NULL;
  1926. } else if (router->exit_policy) {
  1927. int i;
  1928. for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
  1929. tmpe = smartlist_get(router->exit_policy, i);
  1930. result = policy_write_item(s+written, maxlen-written, tmpe, 1);
  1931. if (result < 0) {
  1932. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1933. return -1;
  1934. }
  1935. tor_assert(result == (int)strlen(s+written));
  1936. written += result;
  1937. if (written+2 > maxlen) {
  1938. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1939. return -1;
  1940. }
  1941. s[written++] = '\n';
  1942. }
  1943. }
  1944. if (written + DIROBJ_MAX_SIG_LEN > maxlen) {
  1945. /* Not enough room for signature. */
  1946. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1947. return -1;
  1948. }
  1949. /* Sign the descriptor */
  1950. strlcpy(s+written, "router-signature\n", maxlen-written);
  1951. written += strlen(s+written);
  1952. s[written] = '\0';
  1953. if (router_get_router_hash(s, strlen(s), digest) < 0) {
  1954. return -1;
  1955. }
  1956. note_crypto_pk_op(SIGN_RTR);
  1957. if (router_append_dirobj_signature(s+written,maxlen-written,
  1958. digest,DIGEST_LEN,ident_key)<0) {
  1959. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1960. return -1;
  1961. }
  1962. written += strlen(s+written);
  1963. if (written+2 > maxlen) {
  1964. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1965. return -1;
  1966. }
  1967. /* include a last '\n' */
  1968. s[written] = '\n';
  1969. s[written+1] = 0;
  1970. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1971. {
  1972. char *s_dup;
  1973. const char *cp;
  1974. routerinfo_t *ri_tmp;
  1975. cp = s_dup = tor_strdup(s);
  1976. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1977. if (!ri_tmp) {
  1978. log_err(LD_BUG,
  1979. "We just generated a router descriptor we can't parse.");
  1980. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1981. return -1;
  1982. }
  1983. tor_free(s_dup);
  1984. routerinfo_free(ri_tmp);
  1985. }
  1986. #endif
  1987. return (int)written+1;
  1988. }
  1989. /** Copy the primary (IPv4) OR port (IP address and TCP port) for
  1990. * <b>router</b> into *<b>ap_out</b>. */
  1991. void
  1992. router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  1993. {
  1994. tor_assert(ap_out != NULL);
  1995. tor_addr_from_ipv4h(&ap_out->addr, router->addr);
  1996. ap_out->port = router->or_port;
  1997. }
  1998. /** Return 1 if we prefer the IPv6 address and OR TCP port of
  1999. * <b>router</b>, else 0.
  2000. *
  2001. * We prefer the IPv6 address if the router has one and
  2002. * i) the routerinfo_t says so
  2003. * or
  2004. * ii) the router has no IPv4 address. */
  2005. int
  2006. router_ipv6_preferred(const routerinfo_t *router)
  2007. {
  2008. return (!tor_addr_is_null(&router->ipv6_addr)
  2009. && (router->ipv6_preferred || router->addr == 0));
  2010. }
  2011. /** Copy the preferred OR port (IP address and TCP port) for
  2012. * <b>router</b> into *<b>addr_out</b>. */
  2013. void
  2014. router_get_pref_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  2015. {
  2016. if (router_ipv6_preferred(router))
  2017. router_get_pref_ipv6_orport(router, ap_out);
  2018. else
  2019. router_get_prim_orport(router, ap_out);
  2020. }
  2021. /** Copy the preferred IPv6 OR port (IP address and TCP port) for
  2022. * <b>router</b> into *<b>ap_out</b>. */
  2023. void
  2024. router_get_pref_ipv6_orport(const routerinfo_t *router,
  2025. tor_addr_port_t *ap_out)
  2026. {
  2027. tor_assert(ap_out != NULL);
  2028. tor_addr_copy(&ap_out->addr, &router->ipv6_addr);
  2029. ap_out->port = router->ipv6_orport;
  2030. }
  2031. /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
  2032. * Otherwise return 0. */
  2033. int
  2034. router_has_addr(const routerinfo_t *router, const tor_addr_t *addr)
  2035. {
  2036. return
  2037. tor_addr_eq_ipv4h(addr, router->addr) ||
  2038. tor_addr_eq(&router->ipv6_addr, addr);
  2039. }
  2040. int
  2041. router_has_orport(const routerinfo_t *router, const tor_addr_port_t *orport)
  2042. {
  2043. return
  2044. (tor_addr_eq_ipv4h(&orport->addr, router->addr) &&
  2045. orport->port == router->or_port) ||
  2046. (tor_addr_eq(&orport->addr, &router->ipv6_addr) &&
  2047. orport->port == router->ipv6_orport);
  2048. }
  2049. /** Load the contents of <b>filename</b>, find the last line starting with
  2050. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  2051. * the past or more than 1 hour in the future with respect to <b>now</b>,
  2052. * and write the file contents starting with that line to *<b>out</b>.
  2053. * Return 1 for success, 0 if the file does not exist, or -1 if the file
  2054. * does not contain a line matching these criteria or other failure. */
  2055. static int
  2056. load_stats_file(const char *filename, const char *end_line, time_t now,
  2057. char **out)
  2058. {
  2059. int r = -1;
  2060. char *fname = get_datadir_fname(filename);
  2061. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  2062. time_t written;
  2063. switch (file_status(fname)) {
  2064. case FN_FILE:
  2065. /* X022 Find an alternative to reading the whole file to memory. */
  2066. if ((contents = read_file_to_str(fname, 0, NULL))) {
  2067. tmp = strstr(contents, end_line);
  2068. /* Find last block starting with end_line */
  2069. while (tmp) {
  2070. start = tmp;
  2071. tmp = strstr(tmp + 1, end_line);
  2072. }
  2073. if (!start)
  2074. goto notfound;
  2075. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  2076. goto notfound;
  2077. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  2078. if (parse_iso_time(timestr, &written) < 0)
  2079. goto notfound;
  2080. if (written < now - (25*60*60) || written > now + (1*60*60))
  2081. goto notfound;
  2082. *out = tor_strdup(start);
  2083. r = 1;
  2084. }
  2085. notfound:
  2086. tor_free(contents);
  2087. break;
  2088. case FN_NOENT:
  2089. r = 0;
  2090. break;
  2091. case FN_ERROR:
  2092. case FN_DIR:
  2093. default:
  2094. break;
  2095. }
  2096. tor_free(fname);
  2097. return r;
  2098. }
  2099. /** Write the contents of <b>extrainfo</b> and aggregated statistics to
  2100. * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
  2101. * success, negative on failure. */
  2102. int
  2103. extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
  2104. crypto_pk_t *ident_key)
  2105. {
  2106. const or_options_t *options = get_options();
  2107. char identity[HEX_DIGEST_LEN+1];
  2108. char published[ISO_TIME_LEN+1];
  2109. char digest[DIGEST_LEN];
  2110. char *bandwidth_usage;
  2111. int result;
  2112. static int write_stats_to_extrainfo = 1;
  2113. char sig[DIROBJ_MAX_SIG_LEN+1];
  2114. char *s, *pre, *contents, *cp, *s_dup = NULL;
  2115. time_t now = time(NULL);
  2116. smartlist_t *chunks = smartlist_new();
  2117. extrainfo_t *ei_tmp = NULL;
  2118. base16_encode(identity, sizeof(identity),
  2119. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  2120. format_iso_time(published, extrainfo->cache_info.published_on);
  2121. bandwidth_usage = rep_hist_get_bandwidth_lines();
  2122. tor_asprintf(&pre, "extra-info %s %s\npublished %s\n%s",
  2123. extrainfo->nickname, identity,
  2124. published, bandwidth_usage);
  2125. tor_free(bandwidth_usage);
  2126. smartlist_add(chunks, pre);
  2127. if (geoip_is_loaded()) {
  2128. smartlist_add_asprintf(chunks, "geoip-db-digest %s\n", geoip_db_digest());
  2129. }
  2130. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  2131. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  2132. if (options->DirReqStatistics &&
  2133. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  2134. "dirreq-stats-end", now, &contents) > 0) {
  2135. smartlist_add(chunks, contents);
  2136. }
  2137. if (options->EntryStatistics &&
  2138. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  2139. "entry-stats-end", now, &contents) > 0) {
  2140. smartlist_add(chunks, contents);
  2141. }
  2142. if (options->CellStatistics &&
  2143. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  2144. "cell-stats-end", now, &contents) > 0) {
  2145. smartlist_add(chunks, contents);
  2146. }
  2147. if (options->ExitPortStatistics &&
  2148. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  2149. "exit-stats-end", now, &contents) > 0) {
  2150. smartlist_add(chunks, contents);
  2151. }
  2152. if (options->ConnDirectionStatistics &&
  2153. load_stats_file("stats"PATH_SEPARATOR"conn-stats",
  2154. "conn-bi-direct", now, &contents) > 0) {
  2155. smartlist_add(chunks, contents);
  2156. }
  2157. }
  2158. /* Add information about the pluggable transports we support. */
  2159. if (options->ServerTransportPlugin) {
  2160. char *pluggable_transports = pt_get_extra_info_descriptor_string();
  2161. if (pluggable_transports)
  2162. smartlist_add(chunks, pluggable_transports);
  2163. }
  2164. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  2165. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  2166. if (bridge_stats) {
  2167. smartlist_add(chunks, tor_strdup(bridge_stats));
  2168. }
  2169. }
  2170. smartlist_add(chunks, tor_strdup("router-signature\n"));
  2171. s = smartlist_join_strings(chunks, "", 0, NULL);
  2172. while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
  2173. /* So long as there are at least two chunks (one for the initial
  2174. * extra-info line and one for the router-signature), we can keep removing
  2175. * things. */
  2176. if (smartlist_len(chunks) > 2) {
  2177. /* We remove the next-to-last element (remember, len-1 is the last
  2178. element), since we need to keep the router-signature element. */
  2179. int idx = smartlist_len(chunks) - 2;
  2180. char *e = smartlist_get(chunks, idx);
  2181. smartlist_del_keeporder(chunks, idx);
  2182. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2183. "with statistics that exceeds the 50 KB "
  2184. "upload limit. Removing last added "
  2185. "statistics.");
  2186. tor_free(e);
  2187. tor_free(s);
  2188. s = smartlist_join_strings(chunks, "", 0, NULL);
  2189. } else {
  2190. log_warn(LD_BUG, "We just generated an extra-info descriptors that "
  2191. "exceeds the 50 KB upload limit.");
  2192. goto err;
  2193. }
  2194. }
  2195. memset(sig, 0, sizeof(sig));
  2196. if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
  2197. router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
  2198. ident_key) < 0) {
  2199. log_warn(LD_BUG, "Could not append signature to extra-info "
  2200. "descriptor.");
  2201. goto err;
  2202. }
  2203. smartlist_add(chunks, tor_strdup(sig));
  2204. tor_free(s);
  2205. s = smartlist_join_strings(chunks, "", 0, NULL);
  2206. cp = s_dup = tor_strdup(s);
  2207. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  2208. if (!ei_tmp) {
  2209. if (write_stats_to_extrainfo) {
  2210. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  2211. "with statistics that we can't parse. Not "
  2212. "adding statistics to this or any future "
  2213. "extra-info descriptors.");
  2214. write_stats_to_extrainfo = 0;
  2215. result = extrainfo_dump_to_string(s_out, extrainfo, ident_key);
  2216. goto done;
  2217. } else {
  2218. log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
  2219. "can't parse.");
  2220. goto err;
  2221. }
  2222. }
  2223. *s_out = s;
  2224. s = NULL; /* prevent free */
  2225. result = 0;
  2226. goto done;
  2227. err:
  2228. result = -1;
  2229. done:
  2230. tor_free(s);
  2231. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2232. smartlist_free(chunks);
  2233. tor_free(s_dup);
  2234. extrainfo_free(ei_tmp);
  2235. return result;
  2236. }
  2237. /** Return true iff <b>s</b> is a legally valid server nickname. */
  2238. int
  2239. is_legal_nickname(const char *s)
  2240. {
  2241. size_t len;
  2242. tor_assert(s);
  2243. len = strlen(s);
  2244. return len > 0 && len <= MAX_NICKNAME_LEN &&
  2245. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  2246. }
  2247. /** Return true iff <b>s</b> is a legally valid server nickname or
  2248. * hex-encoded identity-key digest. */
  2249. int
  2250. is_legal_nickname_or_hexdigest(const char *s)
  2251. {
  2252. if (*s!='$')
  2253. return is_legal_nickname(s);
  2254. else
  2255. return is_legal_hexdigest(s);
  2256. }
  2257. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  2258. * digest. */
  2259. int
  2260. is_legal_hexdigest(const char *s)
  2261. {
  2262. size_t len;
  2263. tor_assert(s);
  2264. if (s[0] == '$') s++;
  2265. len = strlen(s);
  2266. if (len > HEX_DIGEST_LEN) {
  2267. if (s[HEX_DIGEST_LEN] == '=' ||
  2268. s[HEX_DIGEST_LEN] == '~') {
  2269. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  2270. return 0;
  2271. } else {
  2272. return 0;
  2273. }
  2274. }
  2275. return (len >= HEX_DIGEST_LEN &&
  2276. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  2277. }
  2278. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2279. * hold a human-readable description of a node with identity digest
  2280. * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
  2281. * and address <b>addr</b> or <b>addr32h</b>.
  2282. *
  2283. * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
  2284. * NULL. The <b>addr32h</b> field is optional and may be set to 0.
  2285. *
  2286. * Return a pointer to the front of <b>buf</b>.
  2287. */
  2288. const char *
  2289. format_node_description(char *buf,
  2290. const char *id_digest,
  2291. int is_named,
  2292. const char *nickname,
  2293. const tor_addr_t *addr,
  2294. uint32_t addr32h)
  2295. {
  2296. char *cp;
  2297. if (!buf)
  2298. return "<NULL BUFFER>";
  2299. buf[0] = '$';
  2300. base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  2301. cp = buf+1+HEX_DIGEST_LEN;
  2302. if (nickname) {
  2303. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2304. strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  2305. cp += strlen(cp);
  2306. }
  2307. if (addr32h || addr) {
  2308. memcpy(cp, " at ", 4);
  2309. cp += 4;
  2310. if (addr) {
  2311. tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
  2312. } else {
  2313. struct in_addr in;
  2314. in.s_addr = htonl(addr32h);
  2315. tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
  2316. }
  2317. }
  2318. return buf;
  2319. }
  2320. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2321. * hold a human-readable description of <b>ri</b>.
  2322. *
  2323. *
  2324. * Return a pointer to the front of <b>buf</b>.
  2325. */
  2326. const char *
  2327. router_get_description(char *buf, const routerinfo_t *ri)
  2328. {
  2329. if (!ri)
  2330. return "<null>";
  2331. return format_node_description(buf,
  2332. ri->cache_info.identity_digest,
  2333. router_is_named(ri),
  2334. ri->nickname,
  2335. NULL,
  2336. ri->addr);
  2337. }
  2338. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2339. * hold a human-readable description of <b>node</b>.
  2340. *
  2341. * Return a pointer to the front of <b>buf</b>.
  2342. */
  2343. const char *
  2344. node_get_description(char *buf, const node_t *node)
  2345. {
  2346. const char *nickname = NULL;
  2347. uint32_t addr32h = 0;
  2348. int is_named = 0;
  2349. if (!node)
  2350. return "<null>";
  2351. if (node->rs) {
  2352. nickname = node->rs->nickname;
  2353. is_named = node->rs->is_named;
  2354. addr32h = node->rs->addr;
  2355. } else if (node->ri) {
  2356. nickname = node->ri->nickname;
  2357. addr32h = node->ri->addr;
  2358. }
  2359. return format_node_description(buf,
  2360. node->identity,
  2361. is_named,
  2362. nickname,
  2363. NULL,
  2364. addr32h);
  2365. }
  2366. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2367. * hold a human-readable description of <b>rs</b>.
  2368. *
  2369. * Return a pointer to the front of <b>buf</b>.
  2370. */
  2371. const char *
  2372. routerstatus_get_description(char *buf, const routerstatus_t *rs)
  2373. {
  2374. if (!rs)
  2375. return "<null>";
  2376. return format_node_description(buf,
  2377. rs->identity_digest,
  2378. rs->is_named,
  2379. rs->nickname,
  2380. NULL,
  2381. rs->addr);
  2382. }
  2383. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  2384. * hold a human-readable description of <b>ei</b>.
  2385. *
  2386. * Return a pointer to the front of <b>buf</b>.
  2387. */
  2388. const char *
  2389. extend_info_get_description(char *buf, const extend_info_t *ei)
  2390. {
  2391. if (!ei)
  2392. return "<null>";
  2393. return format_node_description(buf,
  2394. ei->identity_digest,
  2395. 0,
  2396. ei->nickname,
  2397. &ei->addr,
  2398. 0);
  2399. }
  2400. /** Return a human-readable description of the routerinfo_t <b>ri</b>.
  2401. *
  2402. * This function is not thread-safe. Each call to this function invalidates
  2403. * previous values returned by this function.
  2404. */
  2405. const char *
  2406. router_describe(const routerinfo_t *ri)
  2407. {
  2408. static char buf[NODE_DESC_BUF_LEN];
  2409. return router_get_description(buf, ri);
  2410. }
  2411. /** Return a human-readable description of the node_t <b>node</b>.
  2412. *
  2413. * This function is not thread-safe. Each call to this function invalidates
  2414. * previous values returned by this function.
  2415. */
  2416. const char *
  2417. node_describe(const node_t *node)
  2418. {
  2419. static char buf[NODE_DESC_BUF_LEN];
  2420. return node_get_description(buf, node);
  2421. }
  2422. /** Return a human-readable description of the routerstatus_t <b>rs</b>.
  2423. *
  2424. * This function is not thread-safe. Each call to this function invalidates
  2425. * previous values returned by this function.
  2426. */
  2427. const char *
  2428. routerstatus_describe(const routerstatus_t *rs)
  2429. {
  2430. static char buf[NODE_DESC_BUF_LEN];
  2431. return routerstatus_get_description(buf, rs);
  2432. }
  2433. /** Return a human-readable description of the extend_info_t <b>ri</b>.
  2434. *
  2435. * This function is not thread-safe. Each call to this function invalidates
  2436. * previous values returned by this function.
  2437. */
  2438. const char *
  2439. extend_info_describe(const extend_info_t *ei)
  2440. {
  2441. static char buf[NODE_DESC_BUF_LEN];
  2442. return extend_info_get_description(buf, ei);
  2443. }
  2444. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2445. * verbose representation of the identity of <b>router</b>. The format is:
  2446. * A dollar sign.
  2447. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2448. * A "=" if the router is named; a "~" if it is not.
  2449. * The router's nickname.
  2450. **/
  2451. void
  2452. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  2453. {
  2454. const char *good_digest = networkstatus_get_router_digest_by_nickname(
  2455. router->nickname);
  2456. int is_named = good_digest && tor_memeq(good_digest,
  2457. router->cache_info.identity_digest,
  2458. DIGEST_LEN);
  2459. buf[0] = '$';
  2460. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  2461. DIGEST_LEN);
  2462. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2463. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2464. }
  2465. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2466. * verbose representation of the identity of <b>router</b>. The format is:
  2467. * A dollar sign.
  2468. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2469. * A "=" if the router is named; a "~" if it is not.
  2470. * The router's nickname.
  2471. **/
  2472. void
  2473. routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
  2474. {
  2475. buf[0] = '$';
  2476. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
  2477. DIGEST_LEN);
  2478. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  2479. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2480. }
  2481. /** Forget that we have issued any router-related warnings, so that we'll
  2482. * warn again if we see the same errors. */
  2483. void
  2484. router_reset_warnings(void)
  2485. {
  2486. if (warned_nonexistent_family) {
  2487. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2488. smartlist_clear(warned_nonexistent_family);
  2489. }
  2490. }
  2491. /** Given a router purpose, convert it to a string. Don't call this on
  2492. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  2493. * know its string representation. */
  2494. const char *
  2495. router_purpose_to_string(uint8_t p)
  2496. {
  2497. switch (p)
  2498. {
  2499. case ROUTER_PURPOSE_GENERAL: return "general";
  2500. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  2501. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  2502. default:
  2503. tor_assert(0);
  2504. }
  2505. return NULL;
  2506. }
  2507. /** Given a string, convert it to a router purpose. */
  2508. uint8_t
  2509. router_purpose_from_string(const char *s)
  2510. {
  2511. if (!strcmp(s, "general"))
  2512. return ROUTER_PURPOSE_GENERAL;
  2513. else if (!strcmp(s, "bridge"))
  2514. return ROUTER_PURPOSE_BRIDGE;
  2515. else if (!strcmp(s, "controller"))
  2516. return ROUTER_PURPOSE_CONTROLLER;
  2517. else
  2518. return ROUTER_PURPOSE_UNKNOWN;
  2519. }
  2520. /** Release all static resources held in router.c */
  2521. void
  2522. router_free_all(void)
  2523. {
  2524. crypto_pk_free(onionkey);
  2525. crypto_pk_free(lastonionkey);
  2526. crypto_pk_free(server_identitykey);
  2527. crypto_pk_free(client_identitykey);
  2528. tor_mutex_free(key_lock);
  2529. routerinfo_free(desc_routerinfo);
  2530. extrainfo_free(desc_extrainfo);
  2531. crypto_pk_free(authority_signing_key);
  2532. authority_cert_free(authority_key_certificate);
  2533. crypto_pk_free(legacy_signing_key);
  2534. authority_cert_free(legacy_key_certificate);
  2535. if (warned_nonexistent_family) {
  2536. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2537. smartlist_free(warned_nonexistent_family);
  2538. }
  2539. }