router.c 98 KB

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