router.c 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818
  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-2017, 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_rand.h"
  15. #include "crypto_util.h"
  16. #include "crypto_curve25519.h"
  17. #include "directory.h"
  18. #include "dirserv.h"
  19. #include "dns.h"
  20. #include "geoip.h"
  21. #include "hibernate.h"
  22. #include "main.h"
  23. #include "networkstatus.h"
  24. #include "nodelist.h"
  25. #include "policies.h"
  26. #include "protover.h"
  27. #include "relay.h"
  28. #include "rephist.h"
  29. #include "router.h"
  30. #include "routerkeys.h"
  31. #include "routerlist.h"
  32. #include "routerparse.h"
  33. #include "statefile.h"
  34. #include "torcert.h"
  35. #include "transports.h"
  36. #include "routerset.h"
  37. #include "dirauth/mode.h"
  38. #include "port_cfg_st.h"
  39. /**
  40. * \file router.c
  41. * \brief Miscellaneous relay functionality, including RSA key maintenance,
  42. * generating and uploading server descriptors, picking an address to
  43. * advertise, and so on.
  44. *
  45. * This module handles the job of deciding whether we are a Tor relay, and if
  46. * so what kind. (Mostly through functions like server_mode() that inspect an
  47. * or_options_t, but in some cases based on our own capabilities, such as when
  48. * we are deciding whether to be a directory cache in
  49. * router_has_bandwidth_to_be_dirserver().)
  50. *
  51. * Also in this module are the functions to generate our own routerinfo_t and
  52. * extrainfo_t, and to encode those to signed strings for upload to the
  53. * directory authorities.
  54. *
  55. * This module also handles key maintenance for RSA and Curve25519-ntor keys,
  56. * and for our TLS context. (These functions should eventually move to
  57. * routerkeys.c along with the code that handles Ed25519 keys now.)
  58. **/
  59. /************************************************************/
  60. /*****
  61. * Key management: ORs only.
  62. *****/
  63. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  64. */
  65. static tor_mutex_t *key_lock=NULL;
  66. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  67. /** Current private onionskin decryption key: used to decode CREATE cells. */
  68. static crypto_pk_t *onionkey=NULL;
  69. /** Previous private onionskin decryption key: used to decode CREATE cells
  70. * generated by clients that have an older version of our descriptor. */
  71. static crypto_pk_t *lastonionkey=NULL;
  72. /** Current private ntor secret key: used to perform the ntor handshake. */
  73. static curve25519_keypair_t curve25519_onion_key;
  74. /** Previous private ntor secret key: used to perform the ntor handshake
  75. * with clients that have an older version of our descriptor. */
  76. static curve25519_keypair_t last_curve25519_onion_key;
  77. /** Private server "identity key": used to sign directory info and TLS
  78. * certificates. Never changes. */
  79. static crypto_pk_t *server_identitykey=NULL;
  80. /** Digest of server_identitykey. */
  81. static char server_identitykey_digest[DIGEST_LEN];
  82. /** Private client "identity key": used to sign bridges' and clients'
  83. * outbound TLS certificates. Regenerated on startup and on IP address
  84. * change. */
  85. static crypto_pk_t *client_identitykey=NULL;
  86. /** Signing key used for v3 directory material; only set for authorities. */
  87. static crypto_pk_t *authority_signing_key = NULL;
  88. /** Key certificate to authenticate v3 directory material; only set for
  89. * authorities. */
  90. static authority_cert_t *authority_key_certificate = NULL;
  91. /** For emergency V3 authority key migration: An extra signing key that we use
  92. * with our old (obsolete) identity key for a while. */
  93. static crypto_pk_t *legacy_signing_key = NULL;
  94. /** For emergency V3 authority key migration: An extra certificate to
  95. * authenticate legacy_signing_key with our obsolete identity key.*/
  96. static authority_cert_t *legacy_key_certificate = NULL;
  97. /* (Note that v3 authorities also have a separate "authority identity key",
  98. * but this key is never actually loaded by the Tor process. Instead, it's
  99. * used by tor-gencert to sign new signing keys and make new key
  100. * certificates. */
  101. const char *format_node_description(char *buf,
  102. const char *id_digest,
  103. int is_named,
  104. const char *nickname,
  105. const tor_addr_t *addr,
  106. uint32_t addr32h);
  107. /** Return a readonly string with human readable description
  108. * of <b>err</b>.
  109. */
  110. const char *
  111. routerinfo_err_to_string(int err)
  112. {
  113. switch (err) {
  114. case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
  115. return "No known exit address yet";
  116. case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
  117. return "Cannot parse descriptor";
  118. case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
  119. return "Not running in server mode";
  120. case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
  121. return "Key digest failed";
  122. case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
  123. return "Cannot generate descriptor";
  124. case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
  125. return "Descriptor still rebuilding - not ready yet";
  126. }
  127. log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
  128. tor_assert_unreached();
  129. return "Unknown error";
  130. }
  131. /** Return true if we expect given error to be transient.
  132. * Return false otherwise.
  133. */
  134. int
  135. routerinfo_err_is_transient(int err)
  136. {
  137. switch (err) {
  138. case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
  139. return 1;
  140. case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
  141. return 1;
  142. case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
  143. return 0;
  144. case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
  145. return 0; // XXX: bug?
  146. case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
  147. return 1;
  148. case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
  149. return 1;
  150. }
  151. return 0;
  152. }
  153. /** Replace the current onion key with <b>k</b>. Does not affect
  154. * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
  155. */
  156. static void
  157. set_onion_key(crypto_pk_t *k)
  158. {
  159. if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
  160. /* k is already our onion key; free it and return */
  161. crypto_pk_free(k);
  162. return;
  163. }
  164. tor_mutex_acquire(key_lock);
  165. crypto_pk_free(onionkey);
  166. onionkey = k;
  167. tor_mutex_release(key_lock);
  168. mark_my_descriptor_dirty("set onion key");
  169. }
  170. /** Return the current onion key. Requires that the onion key has been
  171. * loaded or generated. */
  172. crypto_pk_t *
  173. get_onion_key(void)
  174. {
  175. tor_assert(onionkey);
  176. return onionkey;
  177. }
  178. /** Store a full copy of the current onion key into *<b>key</b>, and a full
  179. * copy of the most recent onion key into *<b>last</b>. Store NULL into
  180. * a pointer if the corresponding key does not exist.
  181. */
  182. void
  183. dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
  184. {
  185. tor_assert(key);
  186. tor_assert(last);
  187. tor_mutex_acquire(key_lock);
  188. if (onionkey)
  189. *key = crypto_pk_copy_full(onionkey);
  190. else
  191. *key = NULL;
  192. if (lastonionkey)
  193. *last = crypto_pk_copy_full(lastonionkey);
  194. else
  195. *last = NULL;
  196. tor_mutex_release(key_lock);
  197. }
  198. /** Expire our old set of onion keys. This is done by setting
  199. * last_curve25519_onion_key and lastonionkey to all zero's and NULL
  200. * respectively.
  201. *
  202. * This function does not perform any grace period checks for the old onion
  203. * keys.
  204. */
  205. void
  206. expire_old_onion_keys(void)
  207. {
  208. char *fname = NULL;
  209. tor_mutex_acquire(key_lock);
  210. /* Free lastonionkey and set it to NULL. */
  211. if (lastonionkey) {
  212. crypto_pk_free(lastonionkey);
  213. lastonionkey = NULL;
  214. }
  215. /* We zero out the keypair. See the tor_mem_is_zero() check made in
  216. * construct_ntor_key_map() below. */
  217. memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
  218. tor_mutex_release(key_lock);
  219. fname = get_keydir_fname("secret_onion_key.old");
  220. if (file_status(fname) == FN_FILE) {
  221. if (tor_unlink(fname) != 0) {
  222. log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
  223. fname, strerror(errno));
  224. }
  225. }
  226. tor_free(fname);
  227. fname = get_keydir_fname("secret_onion_key_ntor.old");
  228. if (file_status(fname) == FN_FILE) {
  229. if (tor_unlink(fname) != 0) {
  230. log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
  231. fname, strerror(errno));
  232. }
  233. }
  234. tor_free(fname);
  235. }
  236. /** Return the current secret onion key for the ntor handshake. Must only
  237. * be called from the main thread. */
  238. static const curve25519_keypair_t *
  239. get_current_curve25519_keypair(void)
  240. {
  241. return &curve25519_onion_key;
  242. }
  243. /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
  244. * handshake. Must only be called from the main thread. */
  245. di_digest256_map_t *
  246. construct_ntor_key_map(void)
  247. {
  248. di_digest256_map_t *m = NULL;
  249. if (!tor_mem_is_zero((const char*)
  250. curve25519_onion_key.pubkey.public_key,
  251. CURVE25519_PUBKEY_LEN)) {
  252. dimap_add_entry(&m,
  253. curve25519_onion_key.pubkey.public_key,
  254. tor_memdup(&curve25519_onion_key,
  255. sizeof(curve25519_keypair_t)));
  256. }
  257. if (!tor_mem_is_zero((const char*)
  258. last_curve25519_onion_key.pubkey.public_key,
  259. CURVE25519_PUBKEY_LEN)) {
  260. dimap_add_entry(&m,
  261. last_curve25519_onion_key.pubkey.public_key,
  262. tor_memdup(&last_curve25519_onion_key,
  263. sizeof(curve25519_keypair_t)));
  264. }
  265. return m;
  266. }
  267. /** Helper used to deallocate a di_digest256_map_t returned by
  268. * construct_ntor_key_map. */
  269. static void
  270. ntor_key_map_free_helper(void *arg)
  271. {
  272. curve25519_keypair_t *k = arg;
  273. memwipe(k, 0, sizeof(*k));
  274. tor_free(k);
  275. }
  276. /** Release all storage from a keymap returned by construct_ntor_key_map. */
  277. void
  278. ntor_key_map_free_(di_digest256_map_t *map)
  279. {
  280. if (!map)
  281. return;
  282. dimap_free(map, ntor_key_map_free_helper);
  283. }
  284. /** Return the time when the onion key was last set. This is either the time
  285. * when the process launched, or the time of the most recent key rotation since
  286. * the process launched.
  287. */
  288. time_t
  289. get_onion_key_set_at(void)
  290. {
  291. return onionkey_set_at;
  292. }
  293. /** Set the current server identity key to <b>k</b>.
  294. */
  295. void
  296. set_server_identity_key(crypto_pk_t *k)
  297. {
  298. crypto_pk_free(server_identitykey);
  299. server_identitykey = k;
  300. if (crypto_pk_get_digest(server_identitykey,
  301. server_identitykey_digest) < 0) {
  302. log_err(LD_BUG, "Couldn't compute our own identity key digest.");
  303. tor_assert(0);
  304. }
  305. }
  306. /** Make sure that we have set up our identity keys to match or not match as
  307. * appropriate, and die with an assertion if we have not. */
  308. static void
  309. assert_identity_keys_ok(void)
  310. {
  311. if (1)
  312. return;
  313. tor_assert(client_identitykey);
  314. if (public_server_mode(get_options())) {
  315. /* assert that we have set the client and server keys to be equal */
  316. tor_assert(server_identitykey);
  317. tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
  318. } else {
  319. /* assert that we have set the client and server keys to be unequal */
  320. if (server_identitykey)
  321. tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
  322. }
  323. }
  324. /** Returns the current server identity key; requires that the key has
  325. * been set, and that we are running as a Tor server.
  326. */
  327. crypto_pk_t *
  328. get_server_identity_key(void)
  329. {
  330. tor_assert(server_identitykey);
  331. tor_assert(server_mode(get_options()));
  332. assert_identity_keys_ok();
  333. return server_identitykey;
  334. }
  335. /** Return true iff we are a server and the server identity key
  336. * has been set. */
  337. int
  338. server_identity_key_is_set(void)
  339. {
  340. return server_mode(get_options()) && server_identitykey != NULL;
  341. }
  342. /** Set the current client identity key to <b>k</b>.
  343. */
  344. void
  345. set_client_identity_key(crypto_pk_t *k)
  346. {
  347. crypto_pk_free(client_identitykey);
  348. client_identitykey = k;
  349. }
  350. /** Returns the current client identity key for use on outgoing TLS
  351. * connections; requires that the key has been set.
  352. */
  353. crypto_pk_t *
  354. get_tlsclient_identity_key(void)
  355. {
  356. tor_assert(client_identitykey);
  357. assert_identity_keys_ok();
  358. return client_identitykey;
  359. }
  360. /** Return true iff the client identity key has been set. */
  361. int
  362. client_identity_key_is_set(void)
  363. {
  364. return client_identitykey != NULL;
  365. }
  366. /** Return the key certificate for this v3 (voting) authority, or NULL
  367. * if we have no such certificate. */
  368. MOCK_IMPL(authority_cert_t *,
  369. get_my_v3_authority_cert, (void))
  370. {
  371. return authority_key_certificate;
  372. }
  373. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  374. * if we have no such key. */
  375. crypto_pk_t *
  376. get_my_v3_authority_signing_key(void)
  377. {
  378. return authority_signing_key;
  379. }
  380. /** If we're an authority, and we're using a legacy authority identity key for
  381. * emergency migration purposes, return the certificate associated with that
  382. * key. */
  383. authority_cert_t *
  384. get_my_v3_legacy_cert(void)
  385. {
  386. return legacy_key_certificate;
  387. }
  388. /** If we're an authority, and we're using a legacy authority identity key for
  389. * emergency migration purposes, return that key. */
  390. crypto_pk_t *
  391. get_my_v3_legacy_signing_key(void)
  392. {
  393. return legacy_signing_key;
  394. }
  395. /** Replace the previous onion key with the current onion key, and generate
  396. * a new previous onion key. Immediately after calling this function,
  397. * the OR should:
  398. * - schedule all previous cpuworkers to shut down _after_ processing
  399. * pending work. (This will cause fresh cpuworkers to be generated.)
  400. * - generate and upload a fresh routerinfo.
  401. */
  402. void
  403. rotate_onion_key(void)
  404. {
  405. char *fname, *fname_prev;
  406. crypto_pk_t *prkey = NULL;
  407. or_state_t *state = get_or_state();
  408. curve25519_keypair_t new_curve25519_keypair;
  409. time_t now;
  410. fname = get_keydir_fname("secret_onion_key");
  411. fname_prev = get_keydir_fname("secret_onion_key.old");
  412. /* There isn't much point replacing an old key with an empty file */
  413. if (file_status(fname) == FN_FILE) {
  414. if (replace_file(fname, fname_prev))
  415. goto error;
  416. }
  417. if (!(prkey = crypto_pk_new())) {
  418. log_err(LD_GENERAL,"Error constructing rotated onion key");
  419. goto error;
  420. }
  421. if (crypto_pk_generate_key(prkey)) {
  422. log_err(LD_BUG,"Error generating onion key");
  423. goto error;
  424. }
  425. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  426. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  427. goto error;
  428. }
  429. tor_free(fname);
  430. tor_free(fname_prev);
  431. fname = get_keydir_fname("secret_onion_key_ntor");
  432. fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
  433. if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
  434. goto error;
  435. /* There isn't much point replacing an old key with an empty file */
  436. if (file_status(fname) == FN_FILE) {
  437. if (replace_file(fname, fname_prev))
  438. goto error;
  439. }
  440. if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
  441. "onion") < 0) {
  442. log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
  443. goto error;
  444. }
  445. log_info(LD_GENERAL, "Rotating onion key");
  446. tor_mutex_acquire(key_lock);
  447. crypto_pk_free(lastonionkey);
  448. lastonionkey = onionkey;
  449. onionkey = prkey;
  450. memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
  451. sizeof(curve25519_keypair_t));
  452. memcpy(&curve25519_onion_key, &new_curve25519_keypair,
  453. sizeof(curve25519_keypair_t));
  454. now = time(NULL);
  455. state->LastRotatedOnionKey = onionkey_set_at = now;
  456. tor_mutex_release(key_lock);
  457. mark_my_descriptor_dirty("rotated onion key");
  458. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  459. goto done;
  460. error:
  461. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  462. if (prkey)
  463. crypto_pk_free(prkey);
  464. done:
  465. memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
  466. tor_free(fname);
  467. tor_free(fname_prev);
  468. }
  469. /** Log greeting message that points to new relay lifecycle document the
  470. * first time this function has been called.
  471. */
  472. static void
  473. log_new_relay_greeting(void)
  474. {
  475. static int already_logged = 0;
  476. if (already_logged)
  477. return;
  478. tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
  479. "Thanks for helping the Tor network! If you wish to know "
  480. "what will happen in the upcoming weeks regarding its usage, "
  481. "have a look at https://blog.torproject.org/blog/lifecycle-of"
  482. "-a-new-relay");
  483. already_logged = 1;
  484. }
  485. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  486. * and <b>generate</b> is true, create a new RSA key and save it in
  487. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  488. * errors at level <b>severity</b>. If <b>log_greeting</b> is non-zero and a
  489. * new key was created, log_new_relay_greeting() is called.
  490. */
  491. crypto_pk_t *
  492. init_key_from_file(const char *fname, int generate, int severity,
  493. int log_greeting)
  494. {
  495. crypto_pk_t *prkey = NULL;
  496. if (!(prkey = crypto_pk_new())) {
  497. tor_log(severity, LD_GENERAL,"Error constructing key");
  498. goto error;
  499. }
  500. switch (file_status(fname)) {
  501. case FN_DIR:
  502. case FN_ERROR:
  503. tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  504. goto error;
  505. /* treat empty key files as if the file doesn't exist, and,
  506. * if generate is set, replace the empty file in
  507. * crypto_pk_write_private_key_to_filename() */
  508. case FN_NOENT:
  509. case FN_EMPTY:
  510. if (generate) {
  511. if (!have_lockfile()) {
  512. if (try_locking(get_options(), 0)<0) {
  513. /* Make sure that --list-fingerprint only creates new keys
  514. * if there is no possibility for a deadlock. */
  515. tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
  516. "Not writing any new keys.", fname);
  517. /*XXXX The 'other process' might make a key in a second or two;
  518. * maybe we should wait for it. */
  519. goto error;
  520. }
  521. }
  522. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  523. fname);
  524. if (crypto_pk_generate_key(prkey)) {
  525. tor_log(severity, LD_GENERAL,"Error generating onion key");
  526. goto error;
  527. }
  528. if (crypto_pk_check_key(prkey) <= 0) {
  529. tor_log(severity, LD_GENERAL,"Generated key seems invalid");
  530. goto error;
  531. }
  532. log_info(LD_GENERAL, "Generated key seems valid");
  533. if (log_greeting) {
  534. log_new_relay_greeting();
  535. }
  536. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  537. tor_log(severity, LD_FS,
  538. "Couldn't write generated key to \"%s\".", fname);
  539. goto error;
  540. }
  541. } else {
  542. tor_log(severity, LD_GENERAL, "No key found in \"%s\"", fname);
  543. goto error;
  544. }
  545. return prkey;
  546. case FN_FILE:
  547. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  548. tor_log(severity, LD_GENERAL,"Error loading private key.");
  549. goto error;
  550. }
  551. return prkey;
  552. default:
  553. tor_assert(0);
  554. }
  555. error:
  556. if (prkey)
  557. crypto_pk_free(prkey);
  558. return NULL;
  559. }
  560. /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
  561. * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
  562. * is true, create a new keypair and write it into the file. If there are
  563. * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
  564. * in their ASCII wrapper. */
  565. static int
  566. init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
  567. const char *fname,
  568. int generate,
  569. int severity,
  570. const char *tag)
  571. {
  572. switch (file_status(fname)) {
  573. case FN_DIR:
  574. case FN_ERROR:
  575. tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  576. goto error;
  577. /* treat empty key files as if the file doesn't exist, and, if generate
  578. * is set, replace the empty file in curve25519_keypair_write_to_file() */
  579. case FN_NOENT:
  580. case FN_EMPTY:
  581. if (generate) {
  582. if (!have_lockfile()) {
  583. if (try_locking(get_options(), 0)<0) {
  584. /* Make sure that --list-fingerprint only creates new keys
  585. * if there is no possibility for a deadlock. */
  586. tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
  587. "Not writing any new keys.", fname);
  588. /*XXXX The 'other process' might make a key in a second or two;
  589. * maybe we should wait for it. */
  590. goto error;
  591. }
  592. }
  593. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  594. fname);
  595. if (curve25519_keypair_generate(keys_out, 1) < 0)
  596. goto error;
  597. if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
  598. tor_log(severity, LD_FS,
  599. "Couldn't write generated key to \"%s\".", fname);
  600. memwipe(keys_out, 0, sizeof(*keys_out));
  601. goto error;
  602. }
  603. } else {
  604. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  605. }
  606. return 0;
  607. case FN_FILE:
  608. {
  609. char *tag_in=NULL;
  610. if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
  611. tor_log(severity, LD_GENERAL,"Error loading private key.");
  612. tor_free(tag_in);
  613. goto error;
  614. }
  615. if (!tag_in || strcmp(tag_in, tag)) {
  616. tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
  617. escaped(tag_in));
  618. tor_free(tag_in);
  619. goto error;
  620. }
  621. tor_free(tag_in);
  622. return 0;
  623. }
  624. default:
  625. tor_assert(0);
  626. }
  627. error:
  628. return -1;
  629. }
  630. /** Try to load the vote-signing private key and certificate for being a v3
  631. * directory authority, and make sure they match. If <b>legacy</b>, load a
  632. * legacy key/cert set for emergency key migration; otherwise load the regular
  633. * key/cert set. On success, store them into *<b>key_out</b> and
  634. * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
  635. static int
  636. load_authority_keyset(int legacy, crypto_pk_t **key_out,
  637. authority_cert_t **cert_out)
  638. {
  639. int r = -1;
  640. char *fname = NULL, *cert = NULL;
  641. const char *eos = NULL;
  642. crypto_pk_t *signing_key = NULL;
  643. authority_cert_t *parsed = NULL;
  644. fname = get_keydir_fname(
  645. legacy ? "legacy_signing_key" : "authority_signing_key");
  646. signing_key = init_key_from_file(fname, 0, LOG_ERR, 0);
  647. if (!signing_key) {
  648. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  649. goto done;
  650. }
  651. tor_free(fname);
  652. fname = get_keydir_fname(
  653. legacy ? "legacy_certificate" : "authority_certificate");
  654. cert = read_file_to_str(fname, 0, NULL);
  655. if (!cert) {
  656. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  657. fname);
  658. goto done;
  659. }
  660. parsed = authority_cert_parse_from_string(cert, &eos);
  661. if (!parsed) {
  662. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  663. goto done;
  664. }
  665. if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
  666. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  667. "certificate");
  668. goto done;
  669. }
  670. crypto_pk_free(*key_out);
  671. authority_cert_free(*cert_out);
  672. *key_out = signing_key;
  673. *cert_out = parsed;
  674. r = 0;
  675. signing_key = NULL;
  676. parsed = NULL;
  677. done:
  678. tor_free(fname);
  679. tor_free(cert);
  680. crypto_pk_free(signing_key);
  681. authority_cert_free(parsed);
  682. return r;
  683. }
  684. /** Load the v3 (voting) authority signing key and certificate, if they are
  685. * present. Return -1 if anything is missing, mismatched, or unloadable;
  686. * return 0 on success. */
  687. static int
  688. init_v3_authority_keys(void)
  689. {
  690. if (load_authority_keyset(0, &authority_signing_key,
  691. &authority_key_certificate)<0)
  692. return -1;
  693. if (get_options()->V3AuthUseLegacyKey &&
  694. load_authority_keyset(1, &legacy_signing_key,
  695. &legacy_key_certificate)<0)
  696. return -1;
  697. return 0;
  698. }
  699. /** If we're a v3 authority, check whether we have a certificate that's
  700. * likely to expire soon. Warn if we do, but not too often. */
  701. void
  702. v3_authority_check_key_expiry(void)
  703. {
  704. time_t now, expires;
  705. static time_t last_warned = 0;
  706. int badness, time_left, warn_interval;
  707. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  708. return;
  709. now = time(NULL);
  710. expires = authority_key_certificate->expires;
  711. time_left = (int)( expires - now );
  712. if (time_left <= 0) {
  713. badness = LOG_ERR;
  714. warn_interval = 60*60;
  715. } else if (time_left <= 24*60*60) {
  716. badness = LOG_WARN;
  717. warn_interval = 60*60;
  718. } else if (time_left <= 24*60*60*7) {
  719. badness = LOG_WARN;
  720. warn_interval = 24*60*60;
  721. } else if (time_left <= 24*60*60*30) {
  722. badness = LOG_WARN;
  723. warn_interval = 24*60*60*5;
  724. } else {
  725. return;
  726. }
  727. if (last_warned + warn_interval > now)
  728. return;
  729. if (time_left <= 0) {
  730. tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
  731. " Generate a new one NOW.");
  732. } else if (time_left <= 24*60*60) {
  733. tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
  734. "hours; Generate a new one NOW.", time_left/(60*60));
  735. } else {
  736. tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
  737. "days; Generate a new one soon.", time_left/(24*60*60));
  738. }
  739. last_warned = now;
  740. }
  741. /** Get the lifetime of an onion key in days. This value is defined by the
  742. * network consesus parameter "onion-key-rotation-days". Always returns a value
  743. * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
  744. * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
  745. */
  746. static int
  747. get_onion_key_rotation_days_(void)
  748. {
  749. return networkstatus_get_param(NULL,
  750. "onion-key-rotation-days",
  751. DEFAULT_ONION_KEY_LIFETIME_DAYS,
  752. MIN_ONION_KEY_LIFETIME_DAYS,
  753. MAX_ONION_KEY_LIFETIME_DAYS);
  754. }
  755. /** Get the current lifetime of an onion key in seconds. This value is defined
  756. * by the network consesus parameter "onion-key-rotation-days", but the value
  757. * is converted to seconds.
  758. */
  759. int
  760. get_onion_key_lifetime(void)
  761. {
  762. return get_onion_key_rotation_days_()*24*60*60;
  763. }
  764. /** Get the grace period of an onion key in seconds. This value is defined by
  765. * the network consesus parameter "onion-key-grace-period-days", but the value
  766. * is converted to seconds.
  767. */
  768. int
  769. get_onion_key_grace_period(void)
  770. {
  771. int grace_period;
  772. grace_period = networkstatus_get_param(NULL,
  773. "onion-key-grace-period-days",
  774. DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
  775. MIN_ONION_KEY_GRACE_PERIOD_DAYS,
  776. get_onion_key_rotation_days_());
  777. return grace_period*24*60*60;
  778. }
  779. /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
  780. * on success, and -1 on failure. */
  781. int
  782. router_initialize_tls_context(void)
  783. {
  784. unsigned int flags = 0;
  785. const or_options_t *options = get_options();
  786. int lifetime = options->SSLKeyLifetime;
  787. if (public_server_mode(options))
  788. flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
  789. if (!lifetime) { /* we should guess a good ssl cert lifetime */
  790. /* choose between 5 and 365 days, and round to the day */
  791. unsigned int five_days = 5*24*3600;
  792. unsigned int one_year = 365*24*3600;
  793. lifetime = crypto_rand_int_range(five_days, one_year);
  794. lifetime -= lifetime % (24*3600);
  795. if (crypto_rand_int(2)) {
  796. /* Half the time we expire at midnight, and half the time we expire
  797. * one second before midnight. (Some CAs wobble their expiry times a
  798. * bit in practice, perhaps to reduce collision attacks; see ticket
  799. * 8443 for details about observed certs in the wild.) */
  800. lifetime--;
  801. }
  802. }
  803. /* It's ok to pass lifetime in as an unsigned int, since
  804. * config_parse_interval() checked it. */
  805. return tor_tls_context_init(flags,
  806. get_tlsclient_identity_key(),
  807. server_mode(options) ?
  808. get_server_identity_key() : NULL,
  809. (unsigned int)lifetime);
  810. }
  811. /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
  812. * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
  813. * -1 if Tor should die,
  814. */
  815. STATIC int
  816. router_write_fingerprint(int hashed)
  817. {
  818. char *keydir = NULL, *cp = NULL;
  819. const char *fname = hashed ? "hashed-fingerprint" :
  820. "fingerprint";
  821. char fingerprint[FINGERPRINT_LEN+1];
  822. const or_options_t *options = get_options();
  823. char *fingerprint_line = NULL;
  824. int result = -1;
  825. keydir = get_datadir_fname(fname);
  826. log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
  827. hashed ? "hashed " : "", keydir);
  828. if (!hashed) {
  829. if (crypto_pk_get_fingerprint(get_server_identity_key(),
  830. fingerprint, 0) < 0) {
  831. log_err(LD_GENERAL,"Error computing fingerprint");
  832. goto done;
  833. }
  834. } else {
  835. if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
  836. fingerprint) < 0) {
  837. log_err(LD_GENERAL,"Error computing hashed fingerprint");
  838. goto done;
  839. }
  840. }
  841. tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
  842. /* Check whether we need to write the (hashed-)fingerprint file. */
  843. cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
  844. if (!cp || strcmp(cp, fingerprint_line)) {
  845. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  846. log_err(LD_FS, "Error writing %sfingerprint line to file",
  847. hashed ? "hashed " : "");
  848. goto done;
  849. }
  850. }
  851. log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
  852. hashed ? "bridge's hashed" : "server's", options->Nickname,
  853. fingerprint);
  854. result = 0;
  855. done:
  856. tor_free(cp);
  857. tor_free(keydir);
  858. tor_free(fingerprint_line);
  859. return result;
  860. }
  861. static int
  862. init_keys_common(void)
  863. {
  864. if (!key_lock)
  865. key_lock = tor_mutex_new();
  866. /* There are a couple of paths that put us here before we've asked
  867. * openssl to initialize itself. */
  868. if (crypto_global_init(get_options()->HardwareAccel,
  869. get_options()->AccelName,
  870. get_options()->AccelDir)) {
  871. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  872. return -1;
  873. }
  874. return 0;
  875. }
  876. int
  877. init_keys_client(void)
  878. {
  879. crypto_pk_t *prkey;
  880. if (init_keys_common() < 0)
  881. return -1;
  882. if (!(prkey = crypto_pk_new()))
  883. return -1;
  884. if (crypto_pk_generate_key(prkey)) {
  885. crypto_pk_free(prkey);
  886. return -1;
  887. }
  888. set_client_identity_key(prkey);
  889. /* Create a TLS context. */
  890. if (router_initialize_tls_context() < 0) {
  891. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  892. return -1;
  893. }
  894. return 0;
  895. }
  896. /** Initialize all OR private keys, and the TLS context, as necessary.
  897. * On OPs, this only initializes the tls context. Return 0 on success,
  898. * or -1 if Tor should die.
  899. */
  900. int
  901. init_keys(void)
  902. {
  903. char *keydir;
  904. const char *mydesc;
  905. crypto_pk_t *prkey;
  906. char digest[DIGEST_LEN];
  907. char v3_digest[DIGEST_LEN];
  908. const or_options_t *options = get_options();
  909. dirinfo_type_t type;
  910. time_t now = time(NULL);
  911. dir_server_t *ds;
  912. int v3_digest_set = 0;
  913. authority_cert_t *cert = NULL;
  914. /* OP's don't need persistent keys; just make up an identity and
  915. * initialize the TLS context. */
  916. if (!server_mode(options)) {
  917. return init_keys_client();
  918. }
  919. if (init_keys_common() < 0)
  920. return -1;
  921. if (create_keys_directory(options) < 0)
  922. return -1;
  923. /* 1a. Read v3 directory authority key/cert information. */
  924. memset(v3_digest, 0, sizeof(v3_digest));
  925. if (authdir_mode_v3(options)) {
  926. if (init_v3_authority_keys()<0) {
  927. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  928. "were unable to load our v3 authority keys and certificate! "
  929. "Use tor-gencert to generate them. Dying.");
  930. return -1;
  931. }
  932. cert = get_my_v3_authority_cert();
  933. if (cert) {
  934. if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  935. v3_digest) < 0) {
  936. log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
  937. "digest.");
  938. return -1;
  939. }
  940. v3_digest_set = 1;
  941. }
  942. }
  943. /* 1b. Read identity key. Make it if none is found. */
  944. keydir = get_keydir_fname("secret_id_key");
  945. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  946. prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
  947. tor_free(keydir);
  948. if (!prkey) return -1;
  949. set_server_identity_key(prkey);
  950. /* 1c. If we are configured as a bridge, generate a client key;
  951. * otherwise, set the server identity key as our client identity
  952. * key. */
  953. if (public_server_mode(options)) {
  954. set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
  955. } else {
  956. if (!(prkey = crypto_pk_new()))
  957. return -1;
  958. if (crypto_pk_generate_key(prkey)) {
  959. crypto_pk_free(prkey);
  960. return -1;
  961. }
  962. set_client_identity_key(prkey);
  963. }
  964. /* 1d. Load all ed25519 keys */
  965. const int new_signing_key = load_ed_keys(options,now);
  966. if (new_signing_key < 0)
  967. return -1;
  968. /* 2. Read onion key. Make it if none is found. */
  969. keydir = get_keydir_fname("secret_onion_key");
  970. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  971. prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
  972. tor_free(keydir);
  973. if (!prkey) return -1;
  974. set_onion_key(prkey);
  975. if (options->command == CMD_RUN_TOR) {
  976. /* only mess with the state file if we're actually running Tor */
  977. or_state_t *state = get_or_state();
  978. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  979. /* We allow for some parsing slop, but we don't want to risk accepting
  980. * values in the distant future. If we did, we might never rotate the
  981. * onion key. */
  982. onionkey_set_at = state->LastRotatedOnionKey;
  983. } else {
  984. /* We have no LastRotatedOnionKey set; either we just created the key
  985. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  986. * start the clock ticking now so that we will eventually rotate it even
  987. * if we don't stay up for the full lifetime of an onion key. */
  988. state->LastRotatedOnionKey = onionkey_set_at = now;
  989. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  990. time(NULL)+3600 : 0);
  991. }
  992. }
  993. keydir = get_keydir_fname("secret_onion_key.old");
  994. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  995. /* Load keys from non-empty files only.
  996. * Missing old keys won't be replaced with freshly generated keys. */
  997. prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
  998. if (prkey)
  999. lastonionkey = prkey;
  1000. }
  1001. tor_free(keydir);
  1002. {
  1003. /* 2b. Load curve25519 onion keys. */
  1004. int r;
  1005. keydir = get_keydir_fname("secret_onion_key_ntor");
  1006. r = init_curve25519_keypair_from_file(&curve25519_onion_key,
  1007. keydir, 1, LOG_ERR, "onion");
  1008. tor_free(keydir);
  1009. if (r<0)
  1010. return -1;
  1011. keydir = get_keydir_fname("secret_onion_key_ntor.old");
  1012. if (tor_mem_is_zero((const char *)
  1013. last_curve25519_onion_key.pubkey.public_key,
  1014. CURVE25519_PUBKEY_LEN) &&
  1015. file_status(keydir) == FN_FILE) {
  1016. /* Load keys from non-empty files only.
  1017. * Missing old keys won't be replaced with freshly generated keys. */
  1018. init_curve25519_keypair_from_file(&last_curve25519_onion_key,
  1019. keydir, 0, LOG_ERR, "onion");
  1020. }
  1021. tor_free(keydir);
  1022. }
  1023. /* 3. Initialize link key and TLS context. */
  1024. if (router_initialize_tls_context() < 0) {
  1025. log_err(LD_GENERAL,"Error initializing TLS context");
  1026. return -1;
  1027. }
  1028. /* 3b. Get an ed25519 link certificate. Note that we need to do this
  1029. * after we set up the TLS context */
  1030. if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
  1031. log_err(LD_GENERAL,"Couldn't make link cert");
  1032. return -1;
  1033. }
  1034. /* 4. Build our router descriptor. */
  1035. /* Must be called after keys are initialized. */
  1036. mydesc = router_get_my_descriptor();
  1037. if (authdir_mode_v3(options)) {
  1038. const char *m = NULL;
  1039. routerinfo_t *ri;
  1040. /* We need to add our own fingerprint so it gets recognized. */
  1041. if (dirserv_add_own_fingerprint(get_server_identity_key())) {
  1042. log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
  1043. return -1;
  1044. }
  1045. if (mydesc) {
  1046. was_router_added_t added;
  1047. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
  1048. if (!ri) {
  1049. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  1050. return -1;
  1051. }
  1052. added = dirserv_add_descriptor(ri, &m, "self");
  1053. if (!WRA_WAS_ADDED(added)) {
  1054. if (!WRA_WAS_OUTDATED(added)) {
  1055. log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
  1056. m?m:"<unknown error>");
  1057. return -1;
  1058. } else {
  1059. /* If the descriptor was outdated, that's ok. This can happen
  1060. * when some config options are toggled that affect workers, but
  1061. * we don't really need new keys yet so the descriptor doesn't
  1062. * change and the old one is still fresh. */
  1063. log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
  1064. "after key init: %s This is usually not a problem.",
  1065. m?m:"<unknown error>");
  1066. }
  1067. }
  1068. }
  1069. }
  1070. /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
  1071. if (router_write_fingerprint(0)) {
  1072. log_err(LD_FS, "Error writing fingerprint to file");
  1073. return -1;
  1074. }
  1075. if (!public_server_mode(options) && router_write_fingerprint(1)) {
  1076. log_err(LD_FS, "Error writing hashed fingerprint to file");
  1077. return -1;
  1078. }
  1079. if (!authdir_mode(options))
  1080. return 0;
  1081. /* 6. [authdirserver only] load approved-routers file */
  1082. if (dirserv_load_fingerprint_file() < 0) {
  1083. log_err(LD_GENERAL,"Error loading fingerprints");
  1084. return -1;
  1085. }
  1086. /* 6b. [authdirserver only] add own key to approved directories. */
  1087. crypto_pk_get_digest(get_server_identity_key(), digest);
  1088. type = ((options->V3AuthoritativeDir ?
  1089. (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
  1090. (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
  1091. ds = router_get_trusteddirserver_by_digest(digest);
  1092. if (!ds) {
  1093. ds = trusted_dir_server_new(options->Nickname, NULL,
  1094. router_get_advertised_dir_port(options, 0),
  1095. router_get_advertised_or_port(options),
  1096. NULL,
  1097. digest,
  1098. v3_digest,
  1099. type, 0.0);
  1100. if (!ds) {
  1101. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  1102. "couldn't add ourselves to the authority list. Failing.");
  1103. return -1;
  1104. }
  1105. dir_server_add(ds);
  1106. }
  1107. if (ds->type != type) {
  1108. log_warn(LD_DIR, "Configured authority type does not match authority "
  1109. "type in DirAuthority list. Adjusting. (%d v %d)",
  1110. type, ds->type);
  1111. ds->type = type;
  1112. }
  1113. if (v3_digest_set && (ds->type & V3_DIRINFO) &&
  1114. tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  1115. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  1116. "DirAuthority line. Adjusting.");
  1117. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  1118. }
  1119. if (cert) { /* add my own cert to the list of known certs */
  1120. log_info(LD_DIR, "adding my own v3 cert");
  1121. if (trusted_dirs_load_certs_from_string(
  1122. cert->cache_info.signed_descriptor_body,
  1123. TRUSTED_DIRS_CERTS_SRC_SELF, 0,
  1124. NULL)<0) {
  1125. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  1126. return -1;
  1127. }
  1128. }
  1129. return 0; /* success */
  1130. }
  1131. /* Keep track of whether we should upload our server descriptor,
  1132. * and what type of server we are.
  1133. */
  1134. /** Whether we can reach our ORPort from the outside. */
  1135. static int can_reach_or_port = 0;
  1136. /** Whether we can reach our DirPort from the outside. */
  1137. static int can_reach_dir_port = 0;
  1138. /** Forget what we have learned about our reachability status. */
  1139. void
  1140. router_reset_reachability(void)
  1141. {
  1142. can_reach_or_port = can_reach_dir_port = 0;
  1143. }
  1144. /** Return 1 if we won't do reachability checks, because:
  1145. * - AssumeReachable is set, or
  1146. * - the network is disabled.
  1147. * Otherwise, return 0.
  1148. */
  1149. static int
  1150. router_reachability_checks_disabled(const or_options_t *options)
  1151. {
  1152. return options->AssumeReachable ||
  1153. net_is_disabled();
  1154. }
  1155. /** Return 0 if we need to do an ORPort reachability check, because:
  1156. * - no reachability check has been done yet, or
  1157. * - we've initiated reachability checks, but none have succeeded.
  1158. * Return 1 if we don't need to do an ORPort reachability check, because:
  1159. * - we've seen a successful reachability check, or
  1160. * - AssumeReachable is set, or
  1161. * - the network is disabled.
  1162. */
  1163. int
  1164. check_whether_orport_reachable(const or_options_t *options)
  1165. {
  1166. int reach_checks_disabled = router_reachability_checks_disabled(options);
  1167. return reach_checks_disabled ||
  1168. can_reach_or_port;
  1169. }
  1170. /** Return 0 if we need to do a DirPort reachability check, because:
  1171. * - no reachability check has been done yet, or
  1172. * - we've initiated reachability checks, but none have succeeded.
  1173. * Return 1 if we don't need to do a DirPort reachability check, because:
  1174. * - we've seen a successful reachability check, or
  1175. * - there is no DirPort set, or
  1176. * - AssumeReachable is set, or
  1177. * - the network is disabled.
  1178. */
  1179. int
  1180. check_whether_dirport_reachable(const or_options_t *options)
  1181. {
  1182. int reach_checks_disabled = router_reachability_checks_disabled(options) ||
  1183. !options->DirPort_set;
  1184. return reach_checks_disabled ||
  1185. can_reach_dir_port;
  1186. }
  1187. /** The lower threshold of remaining bandwidth required to advertise (or
  1188. * automatically provide) directory services */
  1189. /* XXX Should this be increased? */
  1190. #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
  1191. /** Return true iff we have enough configured bandwidth to advertise or
  1192. * automatically provide directory services from cache directory
  1193. * information. */
  1194. static int
  1195. router_has_bandwidth_to_be_dirserver(const or_options_t *options)
  1196. {
  1197. if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
  1198. return 0;
  1199. }
  1200. if (options->RelayBandwidthRate > 0 &&
  1201. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
  1202. return 0;
  1203. }
  1204. return 1;
  1205. }
  1206. /** Helper: Return 1 if we have sufficient resources for serving directory
  1207. * requests, return 0 otherwise.
  1208. * dir_port is either 0 or the configured DirPort number.
  1209. * If AccountingMax is set less than our advertised bandwidth, then don't
  1210. * serve requests. Likewise, if our advertised bandwidth is less than
  1211. * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
  1212. */
  1213. static int
  1214. router_should_be_dirserver(const or_options_t *options, int dir_port)
  1215. {
  1216. static int advertising=1; /* start out assuming we will advertise */
  1217. int new_choice=1;
  1218. const char *reason = NULL;
  1219. if (accounting_is_enabled(options) &&
  1220. get_options()->AccountingRule != ACCT_IN) {
  1221. /* Don't spend bytes for directory traffic if we could end up hibernating,
  1222. * but allow DirPort otherwise. Some relay operators set AccountingMax
  1223. * because they're confused or to get statistics. Directory traffic has a
  1224. * much larger effect on output than input so there is no reason to turn it
  1225. * off if using AccountingRule in. */
  1226. int interval_length = accounting_get_interval_length();
  1227. uint32_t effective_bw = get_effective_bwrate(options);
  1228. uint64_t acc_bytes;
  1229. if (!interval_length) {
  1230. log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
  1231. "seconds long. Raising to 1.");
  1232. interval_length = 1;
  1233. }
  1234. log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
  1235. "bwrate: %u, AccountingMax: "U64_FORMAT", "
  1236. "accounting interval length %d",
  1237. dir_port ? "dirport" : "begindir",
  1238. effective_bw, U64_PRINTF_ARG(options->AccountingMax),
  1239. interval_length);
  1240. acc_bytes = options->AccountingMax;
  1241. if (get_options()->AccountingRule == ACCT_SUM)
  1242. acc_bytes /= 2;
  1243. if (effective_bw >=
  1244. acc_bytes / interval_length) {
  1245. new_choice = 0;
  1246. reason = "AccountingMax enabled";
  1247. }
  1248. } else if (! router_has_bandwidth_to_be_dirserver(options)) {
  1249. /* if we're advertising a small amount */
  1250. new_choice = 0;
  1251. reason = "BandwidthRate under 50KB";
  1252. }
  1253. if (advertising != new_choice) {
  1254. if (new_choice == 1) {
  1255. if (dir_port > 0)
  1256. log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
  1257. else
  1258. log_notice(LD_DIR, "Advertising directory service support");
  1259. } else {
  1260. tor_assert(reason);
  1261. log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
  1262. dir_port ? "Port" : "ectory Service support", reason);
  1263. }
  1264. advertising = new_choice;
  1265. }
  1266. return advertising;
  1267. }
  1268. /** Return 1 if we are configured to accept either relay or directory requests
  1269. * from clients and we aren't at risk of exceeding our bandwidth limits, thus
  1270. * we should be a directory server. If not, return 0.
  1271. */
  1272. int
  1273. dir_server_mode(const or_options_t *options)
  1274. {
  1275. if (!options->DirCache)
  1276. return 0;
  1277. return options->DirPort_set ||
  1278. (server_mode(options) && router_has_bandwidth_to_be_dirserver(options));
  1279. }
  1280. /** Look at a variety of factors, and return 0 if we don't want to
  1281. * advertise the fact that we have a DirPort open or begindir support, else
  1282. * return 1.
  1283. *
  1284. * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
  1285. * must be 0.
  1286. *
  1287. * Log a helpful message if we change our mind about whether to publish.
  1288. */
  1289. static int
  1290. decide_to_advertise_dir_impl(const or_options_t *options,
  1291. uint16_t dir_port,
  1292. int supports_tunnelled_dir_requests)
  1293. {
  1294. /* Part one: reasons to publish or not publish that aren't
  1295. * worth mentioning to the user, either because they're obvious
  1296. * or because they're normal behavior. */
  1297. /* short circuit the rest of the function */
  1298. if (!dir_port && !supports_tunnelled_dir_requests)
  1299. return 0;
  1300. if (authdir_mode(options)) /* always publish */
  1301. return 1;
  1302. if (net_is_disabled())
  1303. return 0;
  1304. if (dir_port && !router_get_advertised_dir_port(options, dir_port))
  1305. return 0;
  1306. if (supports_tunnelled_dir_requests &&
  1307. !router_get_advertised_or_port(options))
  1308. return 0;
  1309. /* Part two: consider config options that could make us choose to
  1310. * publish or not publish that the user might find surprising. */
  1311. return router_should_be_dirserver(options, dir_port);
  1312. }
  1313. /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
  1314. * advertise the fact that we have a DirPort open, else return the
  1315. * DirPort we want to advertise.
  1316. */
  1317. static int
  1318. router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
  1319. {
  1320. /* supports_tunnelled_dir_requests is not relevant, pass 0 */
  1321. return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
  1322. }
  1323. /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
  1324. * advertise the fact that we support begindir requests, else return 1.
  1325. */
  1326. static int
  1327. router_should_advertise_begindir(const or_options_t *options,
  1328. int supports_tunnelled_dir_requests)
  1329. {
  1330. /* dir_port is not relevant, pass 0 */
  1331. return decide_to_advertise_dir_impl(options, 0,
  1332. supports_tunnelled_dir_requests);
  1333. }
  1334. /** Allocate and return a new extend_info_t that can be used to build
  1335. * a circuit to or through the router <b>r</b>. Uses the primary
  1336. * address of the router, so should only be called on a server. */
  1337. static extend_info_t *
  1338. extend_info_from_router(const routerinfo_t *r)
  1339. {
  1340. tor_addr_port_t ap;
  1341. tor_assert(r);
  1342. /* Make sure we don't need to check address reachability */
  1343. tor_assert_nonfatal(router_skip_or_reachability(get_options(), 0));
  1344. const ed25519_public_key_t *ed_id_key;
  1345. if (r->cache_info.signing_key_cert)
  1346. ed_id_key = &r->cache_info.signing_key_cert->signing_key;
  1347. else
  1348. ed_id_key = NULL;
  1349. router_get_prim_orport(r, &ap);
  1350. return extend_info_new(r->nickname, r->cache_info.identity_digest,
  1351. ed_id_key,
  1352. r->onion_pkey, r->onion_curve25519_pkey,
  1353. &ap.addr, ap.port);
  1354. }
  1355. /**See if we currently believe our ORPort or DirPort to be
  1356. * unreachable. If so, return 1 else return 0.
  1357. */
  1358. static int
  1359. router_should_check_reachability(int test_or, int test_dir)
  1360. {
  1361. const routerinfo_t *me = router_get_my_routerinfo();
  1362. const or_options_t *options = get_options();
  1363. if (!me)
  1364. return 0;
  1365. if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
  1366. options->StrictNodes) {
  1367. /* If we've excluded ourself, and StrictNodes is set, we can't test
  1368. * ourself. */
  1369. if (test_or || test_dir) {
  1370. #define SELF_EXCLUDED_WARN_INTERVAL 3600
  1371. static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
  1372. log_fn_ratelim(&warning_limit, LOG_WARN, LD_CIRC,
  1373. "Can't peform self-tests for this relay: we have "
  1374. "listed ourself in ExcludeNodes, and StrictNodes is set. "
  1375. "We cannot learn whether we are usable, and will not "
  1376. "be able to advertise ourself.");
  1377. }
  1378. return 0;
  1379. }
  1380. return 1;
  1381. }
  1382. /** Some time has passed, or we just got new directory information.
  1383. * See if we currently believe our ORPort or DirPort to be
  1384. * unreachable. If so, launch a new test for it.
  1385. *
  1386. * For ORPort, we simply try making a circuit that ends at ourselves.
  1387. * Success is noticed in onionskin_answer().
  1388. *
  1389. * For DirPort, we make a connection via Tor to our DirPort and ask
  1390. * for our own server descriptor.
  1391. * Success is noticed in connection_dir_client_reached_eof().
  1392. */
  1393. void
  1394. router_do_reachability_checks(int test_or, int test_dir)
  1395. {
  1396. const routerinfo_t *me = router_get_my_routerinfo();
  1397. const or_options_t *options = get_options();
  1398. int orport_reachable = check_whether_orport_reachable(options);
  1399. tor_addr_t addr;
  1400. if (router_should_check_reachability(test_or, test_dir)) {
  1401. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  1402. extend_info_t *ei = extend_info_from_router(me);
  1403. /* XXX IPv6 self testing */
  1404. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  1405. !orport_reachable ? "reachability" : "bandwidth",
  1406. fmt_addr32(me->addr), me->or_port);
  1407. circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
  1408. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1409. extend_info_free(ei);
  1410. }
  1411. /* XXX IPv6 self testing */
  1412. tor_addr_from_ipv4h(&addr, me->addr);
  1413. if (test_dir && !check_whether_dirport_reachable(options) &&
  1414. !connection_get_by_type_addr_port_purpose(
  1415. CONN_TYPE_DIR, &addr, me->dir_port,
  1416. DIR_PURPOSE_FETCH_SERVERDESC)) {
  1417. tor_addr_port_t my_orport, my_dirport;
  1418. memcpy(&my_orport.addr, &addr, sizeof(addr));
  1419. memcpy(&my_dirport.addr, &addr, sizeof(addr));
  1420. my_orport.port = me->or_port;
  1421. my_dirport.port = me->dir_port;
  1422. /* ask myself, via tor, for my server descriptor. */
  1423. directory_request_t *req =
  1424. directory_request_new(DIR_PURPOSE_FETCH_SERVERDESC);
  1425. directory_request_set_or_addr_port(req, &my_orport);
  1426. directory_request_set_dir_addr_port(req, &my_dirport);
  1427. directory_request_set_directory_id_digest(req,
  1428. me->cache_info.identity_digest);
  1429. // ask via an anon circuit, connecting to our dirport.
  1430. directory_request_set_indirection(req, DIRIND_ANON_DIRPORT);
  1431. directory_request_set_resource(req, "authority.z");
  1432. directory_initiate_request(req);
  1433. directory_request_free(req);
  1434. }
  1435. }
  1436. }
  1437. /** Annotate that we found our ORPort reachable. */
  1438. void
  1439. router_orport_found_reachable(void)
  1440. {
  1441. const routerinfo_t *me = router_get_my_routerinfo();
  1442. const or_options_t *options = get_options();
  1443. if (!can_reach_or_port && me) {
  1444. char *address = tor_dup_ip(me->addr);
  1445. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  1446. "the outside. Excellent.%s",
  1447. options->PublishServerDescriptor_ != NO_DIRINFO
  1448. && check_whether_dirport_reachable(options) ?
  1449. " Publishing server descriptor." : "");
  1450. can_reach_or_port = 1;
  1451. mark_my_descriptor_dirty("ORPort found reachable");
  1452. /* This is a significant enough change to upload immediately,
  1453. * at least in a test network */
  1454. if (options->TestingTorNetwork == 1) {
  1455. reschedule_descriptor_update_check();
  1456. }
  1457. control_event_server_status(LOG_NOTICE,
  1458. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  1459. address, me->or_port);
  1460. tor_free(address);
  1461. }
  1462. }
  1463. /** Annotate that we found our DirPort reachable. */
  1464. void
  1465. router_dirport_found_reachable(void)
  1466. {
  1467. const routerinfo_t *me = router_get_my_routerinfo();
  1468. const or_options_t *options = get_options();
  1469. if (!can_reach_dir_port && me) {
  1470. char *address = tor_dup_ip(me->addr);
  1471. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  1472. "from the outside. Excellent.%s",
  1473. options->PublishServerDescriptor_ != NO_DIRINFO
  1474. && check_whether_orport_reachable(options) ?
  1475. " Publishing server descriptor." : "");
  1476. can_reach_dir_port = 1;
  1477. if (router_should_advertise_dirport(options, me->dir_port)) {
  1478. mark_my_descriptor_dirty("DirPort found reachable");
  1479. /* This is a significant enough change to upload immediately,
  1480. * at least in a test network */
  1481. if (options->TestingTorNetwork == 1) {
  1482. reschedule_descriptor_update_check();
  1483. }
  1484. }
  1485. control_event_server_status(LOG_NOTICE,
  1486. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  1487. address, me->dir_port);
  1488. tor_free(address);
  1489. }
  1490. }
  1491. /** We have enough testing circuits open. Send a bunch of "drop"
  1492. * cells down each of them, to exercise our bandwidth. */
  1493. void
  1494. router_perform_bandwidth_test(int num_circs, time_t now)
  1495. {
  1496. int num_cells = (int)(get_options()->BandwidthRate * 10 /
  1497. CELL_MAX_NETWORK_SIZE);
  1498. int max_cells = num_cells < CIRCWINDOW_START ?
  1499. num_cells : CIRCWINDOW_START;
  1500. int cells_per_circuit = max_cells / num_circs;
  1501. origin_circuit_t *circ = NULL;
  1502. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  1503. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  1504. CIRCUIT_PURPOSE_TESTING))) {
  1505. /* dump cells_per_circuit drop cells onto this circ */
  1506. int i = cells_per_circuit;
  1507. if (circ->base_.state != CIRCUIT_STATE_OPEN)
  1508. continue;
  1509. circ->base_.timestamp_dirty = now;
  1510. while (i-- > 0) {
  1511. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  1512. RELAY_COMMAND_DROP,
  1513. NULL, 0, circ->cpath->prev)<0) {
  1514. return; /* stop if error */
  1515. }
  1516. }
  1517. }
  1518. }
  1519. /** Return true iff our network is in some sense disabled or shutting down:
  1520. * either we're hibernating, entering hibernation, or the network is turned
  1521. * off with DisableNetwork. */
  1522. int
  1523. net_is_disabled(void)
  1524. {
  1525. return get_options()->DisableNetwork || we_are_hibernating();
  1526. }
  1527. /** Return true iff our network is in some sense "completely disabled" either
  1528. * we're fully hibernating or the network is turned off with
  1529. * DisableNetwork. */
  1530. int
  1531. net_is_completely_disabled(void)
  1532. {
  1533. return get_options()->DisableNetwork || we_are_fully_hibernating();
  1534. }
  1535. /** Return true iff we believe ourselves to be an authoritative
  1536. * directory server.
  1537. */
  1538. int
  1539. authdir_mode(const or_options_t *options)
  1540. {
  1541. return options->AuthoritativeDir != 0;
  1542. }
  1543. /** Return true iff we are an authoritative directory server that is
  1544. * authoritative about receiving and serving descriptors of type
  1545. * <b>purpose</b> on its dirport.
  1546. */
  1547. int
  1548. authdir_mode_handles_descs(const or_options_t *options, int purpose)
  1549. {
  1550. if (BUG(purpose < 0)) /* Deprecated. */
  1551. return authdir_mode(options);
  1552. else if (purpose == ROUTER_PURPOSE_GENERAL)
  1553. return authdir_mode_v3(options);
  1554. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  1555. return authdir_mode_bridge(options);
  1556. else
  1557. return 0;
  1558. }
  1559. /** Return true iff we are an authoritative directory server that
  1560. * publishes its own network statuses.
  1561. */
  1562. int
  1563. authdir_mode_publishes_statuses(const or_options_t *options)
  1564. {
  1565. if (authdir_mode_bridge(options))
  1566. return 0;
  1567. return authdir_mode(options);
  1568. }
  1569. /** Return true iff we are an authoritative directory server that
  1570. * tests reachability of the descriptors it learns about.
  1571. */
  1572. int
  1573. authdir_mode_tests_reachability(const or_options_t *options)
  1574. {
  1575. return authdir_mode(options);
  1576. }
  1577. /** Return true iff we believe ourselves to be a bridge authoritative
  1578. * directory server.
  1579. */
  1580. int
  1581. authdir_mode_bridge(const or_options_t *options)
  1582. {
  1583. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  1584. }
  1585. /** Return true iff we are trying to be a server.
  1586. */
  1587. MOCK_IMPL(int,
  1588. server_mode,(const or_options_t *options))
  1589. {
  1590. if (options->ClientOnly) return 0;
  1591. return (options->ORPort_set);
  1592. }
  1593. /** Return true iff we are trying to be a non-bridge server.
  1594. */
  1595. MOCK_IMPL(int,
  1596. public_server_mode,(const or_options_t *options))
  1597. {
  1598. if (!server_mode(options)) return 0;
  1599. return (!options->BridgeRelay);
  1600. }
  1601. /** Return true iff the combination of options in <b>options</b> and parameters
  1602. * in the consensus mean that we don't want to allow exits from circuits
  1603. * we got from addresses not known to be servers. */
  1604. int
  1605. should_refuse_unknown_exits(const or_options_t *options)
  1606. {
  1607. if (options->RefuseUnknownExits != -1) {
  1608. return options->RefuseUnknownExits;
  1609. } else {
  1610. return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
  1611. }
  1612. }
  1613. /** Remember if we've advertised ourselves to the dirservers. */
  1614. static int server_is_advertised=0;
  1615. /** Return true iff we have published our descriptor lately.
  1616. */
  1617. MOCK_IMPL(int,
  1618. advertised_server_mode,(void))
  1619. {
  1620. return server_is_advertised;
  1621. }
  1622. /**
  1623. * Called with a boolean: set whether we have recently published our
  1624. * descriptor.
  1625. */
  1626. static void
  1627. set_server_advertised(int s)
  1628. {
  1629. server_is_advertised = s;
  1630. }
  1631. /** Return true iff we are trying to proxy client connections. */
  1632. int
  1633. proxy_mode(const or_options_t *options)
  1634. {
  1635. (void)options;
  1636. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  1637. if (p->type == CONN_TYPE_AP_LISTENER ||
  1638. p->type == CONN_TYPE_AP_TRANS_LISTENER ||
  1639. p->type == CONN_TYPE_AP_DNS_LISTENER ||
  1640. p->type == CONN_TYPE_AP_NATD_LISTENER)
  1641. return 1;
  1642. } SMARTLIST_FOREACH_END(p);
  1643. return 0;
  1644. }
  1645. /** Decide if we're a publishable server. We are a publishable server if:
  1646. * - We don't have the ClientOnly option set
  1647. * and
  1648. * - We have the PublishServerDescriptor option set to non-empty
  1649. * and
  1650. * - We have ORPort set
  1651. * and
  1652. * - We believe our ORPort and DirPort (if present) are reachable from
  1653. * the outside; or
  1654. * - We believe our ORPort is reachable from the outside, and we can't
  1655. * check our DirPort because the consensus has no exits; or
  1656. * - We are an authoritative directory server.
  1657. */
  1658. static int
  1659. decide_if_publishable_server(void)
  1660. {
  1661. const or_options_t *options = get_options();
  1662. if (options->ClientOnly)
  1663. return 0;
  1664. if (options->PublishServerDescriptor_ == NO_DIRINFO)
  1665. return 0;
  1666. if (!server_mode(options))
  1667. return 0;
  1668. if (authdir_mode(options))
  1669. return 1;
  1670. if (!router_get_advertised_or_port(options))
  1671. return 0;
  1672. if (!check_whether_orport_reachable(options))
  1673. return 0;
  1674. if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
  1675. /* All set: there are no exits in the consensus (maybe this is a tiny
  1676. * test network), so we can't check our DirPort reachability. */
  1677. return 1;
  1678. } else {
  1679. return check_whether_dirport_reachable(options);
  1680. }
  1681. }
  1682. /** Initiate server descriptor upload as reasonable (if server is publishable,
  1683. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  1684. *
  1685. * We need to rebuild the descriptor if it's dirty even if we're not
  1686. * uploading, because our reachability testing *uses* our descriptor to
  1687. * determine what IP address and ports to test.
  1688. */
  1689. void
  1690. consider_publishable_server(int force)
  1691. {
  1692. int rebuilt;
  1693. if (!server_mode(get_options()))
  1694. return;
  1695. rebuilt = router_rebuild_descriptor(0);
  1696. if (decide_if_publishable_server()) {
  1697. set_server_advertised(1);
  1698. if (rebuilt == 0)
  1699. router_upload_dir_desc_to_dirservers(force);
  1700. } else {
  1701. set_server_advertised(0);
  1702. }
  1703. }
  1704. /** Return the port of the first active listener of type
  1705. * <b>listener_type</b>. */
  1706. /** XXX not a very good interface. it's not reliable when there are
  1707. multiple listeners. */
  1708. uint16_t
  1709. router_get_active_listener_port_by_type_af(int listener_type,
  1710. sa_family_t family)
  1711. {
  1712. /* Iterate all connections, find one of the right kind and return
  1713. the port. Not very sophisticated or fast, but effective. */
  1714. smartlist_t *conns = get_connection_array();
  1715. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  1716. if (conn->type == listener_type && !conn->marked_for_close &&
  1717. conn->socket_family == family) {
  1718. return conn->port;
  1719. }
  1720. } SMARTLIST_FOREACH_END(conn);
  1721. return 0;
  1722. }
  1723. /** Return the port that we should advertise as our ORPort; this is either
  1724. * the one configured in the ORPort option, or the one we actually bound to
  1725. * if ORPort is "auto".
  1726. */
  1727. uint16_t
  1728. router_get_advertised_or_port(const or_options_t *options)
  1729. {
  1730. return router_get_advertised_or_port_by_af(options, AF_INET);
  1731. }
  1732. /** As router_get_advertised_or_port(), but allows an address family argument.
  1733. */
  1734. uint16_t
  1735. router_get_advertised_or_port_by_af(const or_options_t *options,
  1736. sa_family_t family)
  1737. {
  1738. int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
  1739. family);
  1740. (void)options;
  1741. /* If the port is in 'auto' mode, we have to use
  1742. router_get_listener_port_by_type(). */
  1743. if (port == CFG_AUTO_PORT)
  1744. return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
  1745. family);
  1746. return port;
  1747. }
  1748. /** Return the port that we should advertise as our DirPort;
  1749. * this is one of three possibilities:
  1750. * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
  1751. * the one configured in the DirPort option,
  1752. * or the one we actually bound to if DirPort is "auto". */
  1753. uint16_t
  1754. router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
  1755. {
  1756. int dirport_configured = get_primary_dir_port();
  1757. (void)options;
  1758. if (!dirport_configured)
  1759. return dirport;
  1760. if (dirport_configured == CFG_AUTO_PORT)
  1761. return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
  1762. AF_INET);
  1763. return dirport_configured;
  1764. }
  1765. /*
  1766. * OR descriptor generation.
  1767. */
  1768. /** My routerinfo. */
  1769. static routerinfo_t *desc_routerinfo = NULL;
  1770. /** My extrainfo */
  1771. static extrainfo_t *desc_extrainfo = NULL;
  1772. /** Why did we most recently decide to regenerate our descriptor? Used to
  1773. * tell the authorities why we're sending it to them. */
  1774. static const char *desc_gen_reason = "uninitialized reason";
  1775. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  1776. * now. */
  1777. static time_t desc_clean_since = 0;
  1778. /** Why did we mark the descriptor dirty? */
  1779. static const char *desc_dirty_reason = "Tor just started";
  1780. /** Boolean: do we need to regenerate the above? */
  1781. static int desc_needs_upload = 0;
  1782. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1783. * descriptor successfully yet, try to upload our signed descriptor to
  1784. * all the directory servers we know about.
  1785. */
  1786. void
  1787. router_upload_dir_desc_to_dirservers(int force)
  1788. {
  1789. const routerinfo_t *ri;
  1790. extrainfo_t *ei;
  1791. char *msg;
  1792. size_t desc_len, extra_len = 0, total_len;
  1793. dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
  1794. ri = router_get_my_routerinfo();
  1795. if (!ri) {
  1796. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1797. return;
  1798. }
  1799. ei = router_get_my_extrainfo();
  1800. if (auth == NO_DIRINFO)
  1801. return;
  1802. if (!force && !desc_needs_upload)
  1803. return;
  1804. log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
  1805. force ? " (forced)" : "");
  1806. desc_needs_upload = 0;
  1807. desc_len = ri->cache_info.signed_descriptor_len;
  1808. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1809. total_len = desc_len + extra_len + 1;
  1810. msg = tor_malloc(total_len);
  1811. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1812. if (ei) {
  1813. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1814. }
  1815. msg[desc_len+extra_len] = 0;
  1816. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1817. (auth & BRIDGE_DIRINFO) ?
  1818. ROUTER_PURPOSE_BRIDGE :
  1819. ROUTER_PURPOSE_GENERAL,
  1820. auth, msg, desc_len, extra_len);
  1821. tor_free(msg);
  1822. }
  1823. /** OR only: Check whether my exit policy says to allow connection to
  1824. * conn. Return 0 if we accept; non-0 if we reject.
  1825. */
  1826. int
  1827. router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
  1828. {
  1829. const routerinfo_t *me = router_get_my_routerinfo();
  1830. if (!me) /* make sure routerinfo exists */
  1831. return -1;
  1832. /* make sure it's resolved to something. this way we can't get a
  1833. 'maybe' below. */
  1834. if (tor_addr_is_null(addr))
  1835. return -1;
  1836. /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
  1837. * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
  1838. * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
  1839. * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
  1840. * summary. */
  1841. if ((tor_addr_family(addr) == AF_INET ||
  1842. tor_addr_family(addr) == AF_INET6)) {
  1843. return compare_tor_addr_to_addr_policy(addr, port,
  1844. me->exit_policy) != ADDR_POLICY_ACCEPTED;
  1845. #if 0
  1846. } else if (tor_addr_family(addr) == AF_INET6) {
  1847. return get_options()->IPv6Exit &&
  1848. desc_routerinfo->ipv6_exit_policy &&
  1849. compare_tor_addr_to_short_policy(addr, port,
  1850. me->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
  1851. #endif /* 0 */
  1852. } else {
  1853. return -1;
  1854. }
  1855. }
  1856. /** Return true iff my exit policy is reject *:*. Return -1 if we don't
  1857. * have a descriptor */
  1858. MOCK_IMPL(int,
  1859. router_my_exit_policy_is_reject_star,(void))
  1860. {
  1861. if (!router_get_my_routerinfo()) /* make sure routerinfo exists */
  1862. return -1;
  1863. return router_get_my_routerinfo()->policy_is_reject_star;
  1864. }
  1865. /** Return true iff I'm a server and <b>digest</b> is equal to
  1866. * my server identity key digest. */
  1867. int
  1868. router_digest_is_me(const char *digest)
  1869. {
  1870. return (server_identitykey &&
  1871. tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
  1872. }
  1873. /** Return my identity digest. */
  1874. const uint8_t *
  1875. router_get_my_id_digest(void)
  1876. {
  1877. return (const uint8_t *)server_identitykey_digest;
  1878. }
  1879. /** Return true iff I'm a server and <b>digest</b> is equal to
  1880. * my identity digest. */
  1881. int
  1882. router_extrainfo_digest_is_me(const char *digest)
  1883. {
  1884. extrainfo_t *ei = router_get_my_extrainfo();
  1885. if (!ei)
  1886. return 0;
  1887. return tor_memeq(digest,
  1888. ei->cache_info.signed_descriptor_digest,
  1889. DIGEST_LEN);
  1890. }
  1891. /** A wrapper around router_digest_is_me(). */
  1892. int
  1893. router_is_me(const routerinfo_t *router)
  1894. {
  1895. return router_digest_is_me(router->cache_info.identity_digest);
  1896. }
  1897. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1898. * necessary. Return NULL on error, or if called on an OP. */
  1899. MOCK_IMPL(const routerinfo_t *,
  1900. router_get_my_routerinfo,(void))
  1901. {
  1902. return router_get_my_routerinfo_with_err(NULL);
  1903. }
  1904. /** Return routerinfo of this OR. Rebuild it from
  1905. * scratch if needed. Set <b>*err</b> to 0 on success or to
  1906. * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
  1907. */
  1908. MOCK_IMPL(const routerinfo_t *,
  1909. router_get_my_routerinfo_with_err,(int *err))
  1910. {
  1911. if (!server_mode(get_options())) {
  1912. if (err)
  1913. *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
  1914. return NULL;
  1915. }
  1916. if (!desc_clean_since) {
  1917. int rebuild_err = router_rebuild_descriptor(0);
  1918. if (rebuild_err < 0) {
  1919. if (err)
  1920. *err = rebuild_err;
  1921. return NULL;
  1922. }
  1923. }
  1924. if (!desc_routerinfo) {
  1925. if (err)
  1926. *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
  1927. return NULL;
  1928. }
  1929. if (err)
  1930. *err = 0;
  1931. return desc_routerinfo;
  1932. }
  1933. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1934. * one if necessary. Return NULL on error.
  1935. */
  1936. const char *
  1937. router_get_my_descriptor(void)
  1938. {
  1939. const char *body;
  1940. const routerinfo_t *me = router_get_my_routerinfo();
  1941. if (! me)
  1942. return NULL;
  1943. tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
  1944. body = signed_descriptor_get_body(&me->cache_info);
  1945. /* Make sure this is nul-terminated. */
  1946. tor_assert(!body[me->cache_info.signed_descriptor_len]);
  1947. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1948. return body;
  1949. }
  1950. /** Return the extrainfo document for this OR, or NULL if we have none.
  1951. * Rebuilt it (and the server descriptor) if necessary. */
  1952. extrainfo_t *
  1953. router_get_my_extrainfo(void)
  1954. {
  1955. if (!server_mode(get_options()))
  1956. return NULL;
  1957. if (router_rebuild_descriptor(0))
  1958. return NULL;
  1959. return desc_extrainfo;
  1960. }
  1961. /** Return a human-readable string describing what triggered us to generate
  1962. * our current descriptor, or NULL if we don't know. */
  1963. const char *
  1964. router_get_descriptor_gen_reason(void)
  1965. {
  1966. return desc_gen_reason;
  1967. }
  1968. /** A list of nicknames that we've warned about including in our family
  1969. * declaration verbatim rather than as digests. */
  1970. static smartlist_t *warned_nonexistent_family = NULL;
  1971. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1972. /** Make a current best guess at our address, either because
  1973. * it's configured in torrc, or because we've learned it from
  1974. * dirserver headers. Place the answer in *<b>addr</b> and return
  1975. * 0 on success, else return -1 if we have no guess.
  1976. *
  1977. * If <b>cache_only</b> is true, just return any cached answers, and
  1978. * don't try to get any new answers.
  1979. */
  1980. MOCK_IMPL(int,
  1981. router_pick_published_address,(const or_options_t *options, uint32_t *addr,
  1982. int cache_only))
  1983. {
  1984. /* First, check the cached output from resolve_my_address(). */
  1985. *addr = get_last_resolved_addr();
  1986. if (*addr)
  1987. return 0;
  1988. /* Second, consider doing a resolve attempt right here. */
  1989. if (!cache_only) {
  1990. if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
  1991. log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
  1992. return 0;
  1993. }
  1994. }
  1995. /* Third, check the cached output from router_new_address_suggestion(). */
  1996. if (router_guess_address_from_dir_headers(addr) >= 0)
  1997. return 0;
  1998. /* We have no useful cached answers. Return failure. */
  1999. return -1;
  2000. }
  2001. /* Like router_check_descriptor_address_consistency, but specifically for the
  2002. * ORPort or DirPort.
  2003. * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
  2004. static void
  2005. router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
  2006. int listener_type)
  2007. {
  2008. tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
  2009. listener_type == CONN_TYPE_DIR_LISTENER);
  2010. /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
  2011. */
  2012. int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
  2013. AF_INET);
  2014. if (port_v4_cfg != 0 &&
  2015. !port_exists_by_type_addr32h_port(listener_type,
  2016. ipv4h_desc_addr, port_v4_cfg, 1)) {
  2017. const tor_addr_t *port_addr = get_first_advertised_addr_by_type_af(
  2018. listener_type,
  2019. AF_INET);
  2020. /* If we're building a descriptor with no advertised address,
  2021. * something is terribly wrong. */
  2022. tor_assert(port_addr);
  2023. tor_addr_t desc_addr;
  2024. char port_addr_str[TOR_ADDR_BUF_LEN];
  2025. char desc_addr_str[TOR_ADDR_BUF_LEN];
  2026. tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
  2027. tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
  2028. tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
  2029. const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
  2030. "OR" : "Dir");
  2031. log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
  2032. "descriptor address %s. If you have a static public IPv4 "
  2033. "address, use 'Address <IPv4>' and 'OutboundBindAddress "
  2034. "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
  2035. "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
  2036. "NoAdvertise'.",
  2037. listener_str, port_addr_str, desc_addr_str, listener_str,
  2038. listener_str, listener_str);
  2039. }
  2040. }
  2041. /* Tor relays only have one IPv4 address in the descriptor, which is derived
  2042. * from the Address torrc option, or guessed using various methods in
  2043. * router_pick_published_address().
  2044. * Warn the operator if there is no ORPort on the descriptor address
  2045. * ipv4h_desc_addr.
  2046. * Warn the operator if there is no DirPort on the descriptor address.
  2047. * This catches a few common config errors:
  2048. * - operators who expect ORPorts and DirPorts to be advertised on the
  2049. * ports' listen addresses, rather than the torrc Address (or guessed
  2050. * addresses in the absence of an Address config). This includes
  2051. * operators who attempt to put their ORPort and DirPort on different
  2052. * addresses;
  2053. * - discrepancies between guessed addresses and configured listen
  2054. * addresses (when the Address option isn't set).
  2055. * If a listener is listening on all IPv4 addresses, it is assumed that it
  2056. * is listening on the configured Address, and no messages are logged.
  2057. * If an operators has specified NoAdvertise ORPorts in a NAT setting,
  2058. * no messages are logged, unless they have specified other advertised
  2059. * addresses.
  2060. * The message tells operators to configure an ORPort and DirPort that match
  2061. * the Address (using NoListen if needed).
  2062. */
  2063. static void
  2064. router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
  2065. {
  2066. router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
  2067. CONN_TYPE_OR_LISTENER);
  2068. router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
  2069. CONN_TYPE_DIR_LISTENER);
  2070. }
  2071. /** Build a fresh routerinfo, signed server descriptor, and extra-info document
  2072. * for this OR. Set r to the generated routerinfo, e to the generated
  2073. * extra-info document. Return 0 on success, -1 on temporary error. Failure to
  2074. * generate an extra-info document is not an error and is indicated by setting
  2075. * e to NULL. Caller is responsible for freeing generated documents if 0 is
  2076. * returned.
  2077. */
  2078. int
  2079. router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
  2080. {
  2081. routerinfo_t *ri;
  2082. extrainfo_t *ei;
  2083. uint32_t addr;
  2084. char platform[256];
  2085. int hibernating = we_are_hibernating();
  2086. const or_options_t *options = get_options();
  2087. if (router_pick_published_address(options, &addr, 0) < 0) {
  2088. log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
  2089. return TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
  2090. }
  2091. /* Log a message if the address in the descriptor doesn't match the ORPort
  2092. * and DirPort addresses configured by the operator. */
  2093. router_check_descriptor_address_consistency(addr);
  2094. ri = tor_malloc_zero(sizeof(routerinfo_t));
  2095. ri->cache_info.routerlist_index = -1;
  2096. ri->nickname = tor_strdup(options->Nickname);
  2097. ri->addr = addr;
  2098. ri->or_port = router_get_advertised_or_port(options);
  2099. ri->dir_port = router_get_advertised_dir_port(options, 0);
  2100. ri->supports_tunnelled_dir_requests =
  2101. directory_permits_begindir_requests(options);
  2102. ri->cache_info.published_on = time(NULL);
  2103. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  2104. * main thread */
  2105. ri->onion_curve25519_pkey =
  2106. tor_memdup(&get_current_curve25519_keypair()->pubkey,
  2107. sizeof(curve25519_public_key_t));
  2108. /* For now, at most one IPv6 or-address is being advertised. */
  2109. {
  2110. const port_cfg_t *ipv6_orport = NULL;
  2111. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
  2112. if (p->type == CONN_TYPE_OR_LISTENER &&
  2113. ! p->server_cfg.no_advertise &&
  2114. ! p->server_cfg.bind_ipv4_only &&
  2115. tor_addr_family(&p->addr) == AF_INET6) {
  2116. /* Like IPv4, if the relay is configured using the default
  2117. * authorities, disallow internal IPs. Otherwise, allow them. */
  2118. const int default_auth = using_default_dir_authorities(options);
  2119. if (! tor_addr_is_internal(&p->addr, 0) || ! default_auth) {
  2120. ipv6_orport = p;
  2121. break;
  2122. } else {
  2123. char addrbuf[TOR_ADDR_BUF_LEN];
  2124. log_warn(LD_CONFIG,
  2125. "Unable to use configured IPv6 address \"%s\" in a "
  2126. "descriptor. Skipping it. "
  2127. "Try specifying a globally reachable address explicitly.",
  2128. tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
  2129. }
  2130. }
  2131. } SMARTLIST_FOREACH_END(p);
  2132. if (ipv6_orport) {
  2133. tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
  2134. ri->ipv6_orport = ipv6_orport->port;
  2135. }
  2136. }
  2137. ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
  2138. if (crypto_pk_get_digest(ri->identity_pkey,
  2139. ri->cache_info.identity_digest)<0) {
  2140. routerinfo_free(ri);
  2141. return TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
  2142. }
  2143. ri->cache_info.signing_key_cert =
  2144. tor_cert_dup(get_master_signing_key_cert());
  2145. get_platform_str(platform, sizeof(platform));
  2146. ri->platform = tor_strdup(platform);
  2147. ri->protocol_list = tor_strdup(protover_get_supported_protocols());
  2148. /* compute ri->bandwidthrate as the min of various options */
  2149. ri->bandwidthrate = get_effective_bwrate(options);
  2150. /* and compute ri->bandwidthburst similarly */
  2151. ri->bandwidthburst = get_effective_bwburst(options);
  2152. /* Report bandwidth, unless we're hibernating or shutting down */
  2153. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  2154. if (dns_seems_to_be_broken() || has_dns_init_failed()) {
  2155. /* DNS is screwed up; don't claim to be an exit. */
  2156. policies_exit_policy_append_reject_star(&ri->exit_policy);
  2157. } else {
  2158. policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,
  2159. &ri->exit_policy);
  2160. }
  2161. ri->policy_is_reject_star =
  2162. policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
  2163. policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
  2164. if (options->IPv6Exit) {
  2165. char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
  2166. if (p_tmp)
  2167. ri->ipv6_exit_policy = parse_short_policy(p_tmp);
  2168. tor_free(p_tmp);
  2169. }
  2170. if (options->MyFamily && ! options->BridgeRelay) {
  2171. if (!warned_nonexistent_family)
  2172. warned_nonexistent_family = smartlist_new();
  2173. ri->declared_family = smartlist_new();
  2174. config_line_t *family;
  2175. for (family = options->MyFamily; family; family = family->next) {
  2176. char *name = family->value;
  2177. const node_t *member;
  2178. if (!strcasecmp(name, options->Nickname))
  2179. continue; /* Don't list ourself, that's redundant */
  2180. else
  2181. member = node_get_by_nickname(name, 0);
  2182. if (!member) {
  2183. int is_legal = is_legal_nickname_or_hexdigest(name);
  2184. if (!smartlist_contains_string(warned_nonexistent_family, name) &&
  2185. !is_legal_hexdigest(name)) {
  2186. if (is_legal)
  2187. log_warn(LD_CONFIG,
  2188. "I have no descriptor for the router named \"%s\" in my "
  2189. "declared family; I'll use the nickname as is, but "
  2190. "this may confuse clients.", name);
  2191. else
  2192. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  2193. "declared family, but that isn't a legal nickname. "
  2194. "Skipping it.", escaped(name));
  2195. smartlist_add_strdup(warned_nonexistent_family, name);
  2196. }
  2197. if (is_legal) {
  2198. smartlist_add_strdup(ri->declared_family, name);
  2199. }
  2200. } else if (router_digest_is_me(member->identity)) {
  2201. /* Don't list ourself in our own family; that's redundant */
  2202. /* XXX shouldn't be possible */
  2203. } else {
  2204. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  2205. fp[0] = '$';
  2206. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  2207. member->identity, DIGEST_LEN);
  2208. smartlist_add(ri->declared_family, fp);
  2209. if (smartlist_contains_string(warned_nonexistent_family, name))
  2210. smartlist_string_remove(warned_nonexistent_family, name);
  2211. }
  2212. }
  2213. /* remove duplicates from the list */
  2214. smartlist_sort_strings(ri->declared_family);
  2215. smartlist_uniq_strings(ri->declared_family);
  2216. }
  2217. /* Now generate the extrainfo. */
  2218. ei = tor_malloc_zero(sizeof(extrainfo_t));
  2219. ei->cache_info.is_extrainfo = 1;
  2220. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  2221. ei->cache_info.published_on = ri->cache_info.published_on;
  2222. ei->cache_info.signing_key_cert =
  2223. tor_cert_dup(get_master_signing_key_cert());
  2224. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  2225. DIGEST_LEN);
  2226. if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
  2227. ei, get_server_identity_key(),
  2228. get_master_signing_keypair()) < 0) {
  2229. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  2230. extrainfo_free(ei);
  2231. ei = NULL;
  2232. } else {
  2233. ei->cache_info.signed_descriptor_len =
  2234. strlen(ei->cache_info.signed_descriptor_body);
  2235. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  2236. ei->cache_info.signed_descriptor_len,
  2237. ei->cache_info.signed_descriptor_digest);
  2238. crypto_digest256((char*) ei->digest256,
  2239. ei->cache_info.signed_descriptor_body,
  2240. ei->cache_info.signed_descriptor_len,
  2241. DIGEST_SHA256);
  2242. }
  2243. /* Now finish the router descriptor. */
  2244. if (ei) {
  2245. memcpy(ri->cache_info.extra_info_digest,
  2246. ei->cache_info.signed_descriptor_digest,
  2247. DIGEST_LEN);
  2248. memcpy(ri->cache_info.extra_info_digest256,
  2249. ei->digest256,
  2250. DIGEST256_LEN);
  2251. } else {
  2252. /* ri was allocated with tor_malloc_zero, so there is no need to
  2253. * zero ri->cache_info.extra_info_digest here. */
  2254. }
  2255. if (! (ri->cache_info.signed_descriptor_body =
  2256. router_dump_router_to_string(ri, get_server_identity_key(),
  2257. get_onion_key(),
  2258. get_current_curve25519_keypair(),
  2259. get_master_signing_keypair())) ) {
  2260. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  2261. routerinfo_free(ri);
  2262. extrainfo_free(ei);
  2263. return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
  2264. }
  2265. ri->cache_info.signed_descriptor_len =
  2266. strlen(ri->cache_info.signed_descriptor_body);
  2267. ri->purpose =
  2268. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  2269. if (options->BridgeRelay) {
  2270. /* Bridges shouldn't be able to send their descriptors unencrypted,
  2271. anyway, since they don't have a DirPort, and always connect to the
  2272. bridge authority anonymously. But just in case they somehow think of
  2273. sending them on an unencrypted connection, don't allow them to try. */
  2274. ri->cache_info.send_unencrypted = 0;
  2275. if (ei)
  2276. ei->cache_info.send_unencrypted = 0;
  2277. } else {
  2278. ri->cache_info.send_unencrypted = 1;
  2279. if (ei)
  2280. ei->cache_info.send_unencrypted = 1;
  2281. }
  2282. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  2283. strlen(ri->cache_info.signed_descriptor_body),
  2284. ri->cache_info.signed_descriptor_digest);
  2285. if (ei) {
  2286. tor_assert(!
  2287. routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
  2288. &ri->cache_info, NULL));
  2289. }
  2290. *r = ri;
  2291. *e = ei;
  2292. return 0;
  2293. }
  2294. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  2295. * routerinfo, signed server descriptor, and extra-info document for this OR.
  2296. * Return 0 on success, -1 on temporary error.
  2297. */
  2298. int
  2299. router_rebuild_descriptor(int force)
  2300. {
  2301. int err = 0;
  2302. routerinfo_t *ri;
  2303. extrainfo_t *ei;
  2304. uint32_t addr;
  2305. const or_options_t *options = get_options();
  2306. if (desc_clean_since && !force)
  2307. return 0;
  2308. if (router_pick_published_address(options, &addr, 0) < 0 ||
  2309. router_get_advertised_or_port(options) == 0) {
  2310. /* Stop trying to rebuild our descriptor every second. We'll
  2311. * learn that it's time to try again when ip_address_changed()
  2312. * marks it dirty. */
  2313. desc_clean_since = time(NULL);
  2314. return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
  2315. }
  2316. log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
  2317. err = router_build_fresh_descriptor(&ri, &ei);
  2318. if (err < 0) {
  2319. return err;
  2320. }
  2321. routerinfo_free(desc_routerinfo);
  2322. desc_routerinfo = ri;
  2323. extrainfo_free(desc_extrainfo);
  2324. desc_extrainfo = ei;
  2325. desc_clean_since = time(NULL);
  2326. desc_needs_upload = 1;
  2327. desc_gen_reason = desc_dirty_reason;
  2328. if (BUG(desc_gen_reason == NULL)) {
  2329. desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
  2330. }
  2331. desc_dirty_reason = NULL;
  2332. control_event_my_descriptor_changed();
  2333. return 0;
  2334. }
  2335. /** If our router descriptor ever goes this long without being regenerated
  2336. * because something changed, we force an immediate regenerate-and-upload. */
  2337. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  2338. /** If our router descriptor seems to be missing or unacceptable according
  2339. * to the authorities, regenerate and reupload it _this_ often. */
  2340. #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
  2341. /** Mark descriptor out of date if it's been "too long" since we last tried
  2342. * to upload one. */
  2343. void
  2344. mark_my_descriptor_dirty_if_too_old(time_t now)
  2345. {
  2346. networkstatus_t *ns;
  2347. const routerstatus_t *rs;
  2348. const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
  2349. const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
  2350. const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
  2351. /* If it's already dirty, don't mark it. */
  2352. if (! desc_clean_since)
  2353. return;
  2354. /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
  2355. * time to rebuild it. */
  2356. if (desc_clean_since < slow_cutoff) {
  2357. mark_my_descriptor_dirty("time for new descriptor");
  2358. return;
  2359. }
  2360. /* Now we see whether we want to be retrying frequently or no. The
  2361. * rule here is that we'll retry frequently if we aren't listed in the
  2362. * live consensus we have, or if the publication time of the
  2363. * descriptor listed for us in the consensus is very old. */
  2364. ns = networkstatus_get_live_consensus(now);
  2365. if (ns) {
  2366. rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
  2367. if (rs == NULL)
  2368. retry_fast_reason = "not listed in consensus";
  2369. else if (rs->published_on < slow_cutoff)
  2370. retry_fast_reason = "version listed in consensus is quite old";
  2371. }
  2372. if (retry_fast_reason && desc_clean_since < fast_cutoff)
  2373. mark_my_descriptor_dirty(retry_fast_reason);
  2374. }
  2375. /** Call when the current descriptor is out of date. */
  2376. void
  2377. mark_my_descriptor_dirty(const char *reason)
  2378. {
  2379. const or_options_t *options = get_options();
  2380. if (BUG(reason == NULL)) {
  2381. reason = "marked descriptor dirty for unspecified reason";
  2382. }
  2383. if (server_mode(options) && options->PublishServerDescriptor_)
  2384. log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
  2385. desc_clean_since = 0;
  2386. if (!desc_dirty_reason)
  2387. desc_dirty_reason = reason;
  2388. }
  2389. /** How frequently will we republish our descriptor because of large (factor
  2390. * of 2) shifts in estimated bandwidth? Note: We don't use this constant
  2391. * if our previous bandwidth estimate was exactly 0. */
  2392. #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
  2393. /** Check whether bandwidth has changed a lot since the last time we announced
  2394. * bandwidth. If so, mark our descriptor dirty. */
  2395. void
  2396. check_descriptor_bandwidth_changed(time_t now)
  2397. {
  2398. static time_t last_changed = 0;
  2399. uint64_t prev, cur;
  2400. if (!router_get_my_routerinfo())
  2401. return;
  2402. prev = router_get_my_routerinfo()->bandwidthcapacity;
  2403. /* Consider ourselves to have zero bandwidth if we're hibernating or
  2404. * shutting down. */
  2405. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  2406. if ((prev != cur && (!prev || !cur)) ||
  2407. cur > prev*2 ||
  2408. cur < prev/2) {
  2409. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
  2410. log_info(LD_GENERAL,
  2411. "Measured bandwidth has changed; rebuilding descriptor.");
  2412. mark_my_descriptor_dirty("bandwidth has changed");
  2413. last_changed = now;
  2414. }
  2415. }
  2416. }
  2417. /** Note at log level severity that our best guess of address has changed from
  2418. * <b>prev</b> to <b>cur</b>. */
  2419. static void
  2420. log_addr_has_changed(int severity,
  2421. const tor_addr_t *prev,
  2422. const tor_addr_t *cur,
  2423. const char *source)
  2424. {
  2425. char addrbuf_prev[TOR_ADDR_BUF_LEN];
  2426. char addrbuf_cur[TOR_ADDR_BUF_LEN];
  2427. if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
  2428. strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
  2429. if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
  2430. strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
  2431. if (!tor_addr_is_null(prev))
  2432. log_fn(severity, LD_GENERAL,
  2433. "Our IP Address has changed from %s to %s; "
  2434. "rebuilding descriptor (source: %s).",
  2435. addrbuf_prev, addrbuf_cur, source);
  2436. else
  2437. log_notice(LD_GENERAL,
  2438. "Guessed our IP address as %s (source: %s).",
  2439. addrbuf_cur, source);
  2440. }
  2441. /** Check whether our own address as defined by the Address configuration
  2442. * has changed. This is for routers that get their address from a service
  2443. * like dyndns. If our address has changed, mark our descriptor dirty. */
  2444. void
  2445. check_descriptor_ipaddress_changed(time_t now)
  2446. {
  2447. uint32_t prev, cur;
  2448. const or_options_t *options = get_options();
  2449. const char *method = NULL;
  2450. char *hostname = NULL;
  2451. (void) now;
  2452. if (router_get_my_routerinfo() == NULL)
  2453. return;
  2454. /* XXXX ipv6 */
  2455. prev = router_get_my_routerinfo()->addr;
  2456. if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
  2457. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  2458. return;
  2459. }
  2460. if (prev != cur) {
  2461. char *source;
  2462. tor_addr_t tmp_prev, tmp_cur;
  2463. tor_addr_from_ipv4h(&tmp_prev, prev);
  2464. tor_addr_from_ipv4h(&tmp_cur, cur);
  2465. tor_asprintf(&source, "METHOD=%s%s%s", method,
  2466. hostname ? " HOSTNAME=" : "",
  2467. hostname ? hostname : "");
  2468. log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
  2469. tor_free(source);
  2470. ip_address_changed(0);
  2471. }
  2472. tor_free(hostname);
  2473. }
  2474. /** The most recently guessed value of our IP address, based on directory
  2475. * headers. */
  2476. static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
  2477. /** A directory server <b>d_conn</b> told us our IP address is
  2478. * <b>suggestion</b>.
  2479. * If this address is different from the one we think we are now, and
  2480. * if our computer doesn't actually know its IP address, then switch. */
  2481. void
  2482. router_new_address_suggestion(const char *suggestion,
  2483. const dir_connection_t *d_conn)
  2484. {
  2485. tor_addr_t addr;
  2486. uint32_t cur = 0; /* Current IPv4 address. */
  2487. const or_options_t *options = get_options();
  2488. /* first, learn what the IP address actually is */
  2489. if (tor_addr_parse(&addr, suggestion) == -1) {
  2490. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  2491. escaped(suggestion));
  2492. return;
  2493. }
  2494. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  2495. if (!server_mode(options)) {
  2496. tor_addr_copy(&last_guessed_ip, &addr);
  2497. return;
  2498. }
  2499. /* XXXX ipv6 */
  2500. cur = get_last_resolved_addr();
  2501. if (cur ||
  2502. resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
  2503. /* We're all set -- we already know our address. Great. */
  2504. tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
  2505. need it later */
  2506. return;
  2507. }
  2508. if (tor_addr_is_internal(&addr, 0)) {
  2509. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  2510. return;
  2511. }
  2512. if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
  2513. /* Don't believe anybody who says our IP is their IP. */
  2514. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  2515. "but they are just reporting their own IP address. Ignoring.",
  2516. suggestion);
  2517. return;
  2518. }
  2519. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  2520. * us an answer different from what we had the last time we managed to
  2521. * resolve it. */
  2522. if (!tor_addr_eq(&last_guessed_ip, &addr)) {
  2523. control_event_server_status(LOG_NOTICE,
  2524. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  2525. suggestion);
  2526. log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
  2527. d_conn->base_.address);
  2528. ip_address_changed(0);
  2529. tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
  2530. will fetch it */
  2531. }
  2532. }
  2533. /** We failed to resolve our address locally, but we'd like to build
  2534. * a descriptor and publish / test reachability. If we have a guess
  2535. * about our address based on directory headers, answer it and return
  2536. * 0; else return -1. */
  2537. static int
  2538. router_guess_address_from_dir_headers(uint32_t *guess)
  2539. {
  2540. if (!tor_addr_is_null(&last_guessed_ip)) {
  2541. *guess = tor_addr_to_ipv4h(&last_guessed_ip);
  2542. return 0;
  2543. }
  2544. return -1;
  2545. }
  2546. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  2547. * string describing the version of Tor and the operating system we're
  2548. * currently running on.
  2549. */
  2550. STATIC void
  2551. get_platform_str(char *platform, size_t len)
  2552. {
  2553. tor_snprintf(platform, len, "Tor %s on %s",
  2554. get_short_version(), get_uname());
  2555. }
  2556. /* XXX need to audit this thing and count fenceposts. maybe
  2557. * refactor so we don't have to keep asking if we're
  2558. * near the end of maxlen?
  2559. */
  2560. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  2561. /** OR only: Given a routerinfo for this router, and an identity key to sign
  2562. * with, encode the routerinfo as a signed server descriptor and return a new
  2563. * string encoding the result, or NULL on failure.
  2564. */
  2565. char *
  2566. router_dump_router_to_string(routerinfo_t *router,
  2567. const crypto_pk_t *ident_key,
  2568. const crypto_pk_t *tap_key,
  2569. const curve25519_keypair_t *ntor_keypair,
  2570. const ed25519_keypair_t *signing_keypair)
  2571. {
  2572. char *address = NULL;
  2573. char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
  2574. char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
  2575. char digest[DIGEST256_LEN];
  2576. char published[ISO_TIME_LEN+1];
  2577. char fingerprint[FINGERPRINT_LEN+1];
  2578. char *extra_info_line = NULL;
  2579. size_t onion_pkeylen, identity_pkeylen;
  2580. char *family_line = NULL;
  2581. char *extra_or_address = NULL;
  2582. const or_options_t *options = get_options();
  2583. smartlist_t *chunks = NULL;
  2584. char *output = NULL;
  2585. const int emit_ed_sigs = signing_keypair &&
  2586. router->cache_info.signing_key_cert;
  2587. char *ed_cert_line = NULL;
  2588. char *rsa_tap_cc_line = NULL;
  2589. char *ntor_cc_line = NULL;
  2590. char *proto_line = NULL;
  2591. /* Make sure the identity key matches the one in the routerinfo. */
  2592. if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
  2593. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  2594. "match router's public key!");
  2595. goto err;
  2596. }
  2597. if (emit_ed_sigs) {
  2598. if (!router->cache_info.signing_key_cert->signing_key_included ||
  2599. !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
  2600. &signing_keypair->pubkey)) {
  2601. log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
  2602. "ed25519 key chain %d",
  2603. router->cache_info.signing_key_cert->signing_key_included);
  2604. goto err;
  2605. }
  2606. }
  2607. /* record our fingerprint, so we can include it in the descriptor */
  2608. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  2609. log_err(LD_BUG,"Error computing fingerprint");
  2610. goto err;
  2611. }
  2612. if (emit_ed_sigs) {
  2613. /* Encode ed25519 signing cert */
  2614. char ed_cert_base64[256];
  2615. char ed_fp_base64[ED25519_BASE64_LEN+1];
  2616. if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
  2617. (const char*)router->cache_info.signing_key_cert->encoded,
  2618. router->cache_info.signing_key_cert->encoded_len,
  2619. BASE64_ENCODE_MULTILINE) < 0) {
  2620. log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
  2621. goto err;
  2622. }
  2623. if (ed25519_public_to_base64(ed_fp_base64,
  2624. &router->cache_info.signing_key_cert->signing_key)<0) {
  2625. log_err(LD_BUG,"Couldn't base64-encode identity key\n");
  2626. goto err;
  2627. }
  2628. tor_asprintf(&ed_cert_line, "identity-ed25519\n"
  2629. "-----BEGIN ED25519 CERT-----\n"
  2630. "%s"
  2631. "-----END ED25519 CERT-----\n"
  2632. "master-key-ed25519 %s\n",
  2633. ed_cert_base64, ed_fp_base64);
  2634. }
  2635. /* PEM-encode the onion key */
  2636. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  2637. &onion_pkey,&onion_pkeylen)<0) {
  2638. log_warn(LD_BUG,"write onion_pkey to string failed!");
  2639. goto err;
  2640. }
  2641. /* PEM-encode the identity key */
  2642. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  2643. &identity_pkey,&identity_pkeylen)<0) {
  2644. log_warn(LD_BUG,"write identity_pkey to string failed!");
  2645. goto err;
  2646. }
  2647. /* Cross-certify with RSA key */
  2648. if (tap_key && router->cache_info.signing_key_cert &&
  2649. router->cache_info.signing_key_cert->signing_key_included) {
  2650. char buf[256];
  2651. int tap_cc_len = 0;
  2652. uint8_t *tap_cc =
  2653. make_tap_onion_key_crosscert(tap_key,
  2654. &router->cache_info.signing_key_cert->signing_key,
  2655. router->identity_pkey,
  2656. &tap_cc_len);
  2657. if (!tap_cc) {
  2658. log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
  2659. goto err;
  2660. }
  2661. if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
  2662. BASE64_ENCODE_MULTILINE) < 0) {
  2663. log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
  2664. tor_free(tap_cc);
  2665. goto err;
  2666. }
  2667. tor_free(tap_cc);
  2668. tor_asprintf(&rsa_tap_cc_line,
  2669. "onion-key-crosscert\n"
  2670. "-----BEGIN CROSSCERT-----\n"
  2671. "%s"
  2672. "-----END CROSSCERT-----\n", buf);
  2673. }
  2674. /* Cross-certify with onion keys */
  2675. if (ntor_keypair && router->cache_info.signing_key_cert &&
  2676. router->cache_info.signing_key_cert->signing_key_included) {
  2677. int sign = 0;
  2678. char buf[256];
  2679. /* XXXX Base the expiration date on the actual onion key expiration time?*/
  2680. tor_cert_t *cert =
  2681. make_ntor_onion_key_crosscert(ntor_keypair,
  2682. &router->cache_info.signing_key_cert->signing_key,
  2683. router->cache_info.published_on,
  2684. get_onion_key_lifetime(), &sign);
  2685. if (!cert) {
  2686. log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
  2687. goto err;
  2688. }
  2689. tor_assert(sign == 0 || sign == 1);
  2690. if (base64_encode(buf, sizeof(buf),
  2691. (const char*)cert->encoded, cert->encoded_len,
  2692. BASE64_ENCODE_MULTILINE)<0) {
  2693. log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
  2694. tor_cert_free(cert);
  2695. goto err;
  2696. }
  2697. tor_cert_free(cert);
  2698. tor_asprintf(&ntor_cc_line,
  2699. "ntor-onion-key-crosscert %d\n"
  2700. "-----BEGIN ED25519 CERT-----\n"
  2701. "%s"
  2702. "-----END ED25519 CERT-----\n", sign, buf);
  2703. }
  2704. /* Encode the publication time. */
  2705. format_iso_time(published, router->cache_info.published_on);
  2706. if (router->declared_family && smartlist_len(router->declared_family)) {
  2707. char *family = smartlist_join_strings(router->declared_family,
  2708. " ", 0, NULL);
  2709. tor_asprintf(&family_line, "family %s\n", family);
  2710. tor_free(family);
  2711. } else {
  2712. family_line = tor_strdup("");
  2713. }
  2714. if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
  2715. char extra_info_digest[HEX_DIGEST_LEN+1];
  2716. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  2717. router->cache_info.extra_info_digest, DIGEST_LEN);
  2718. if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
  2719. char d256_64[BASE64_DIGEST256_LEN+1];
  2720. digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
  2721. tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
  2722. extra_info_digest, d256_64);
  2723. } else {
  2724. tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
  2725. extra_info_digest);
  2726. }
  2727. }
  2728. if (router->ipv6_orport &&
  2729. tor_addr_family(&router->ipv6_addr) == AF_INET6) {
  2730. char addr[TOR_ADDR_BUF_LEN];
  2731. const char *a;
  2732. a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
  2733. if (a) {
  2734. tor_asprintf(&extra_or_address,
  2735. "or-address %s:%d\n", a, router->ipv6_orport);
  2736. log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
  2737. }
  2738. }
  2739. if (router->protocol_list) {
  2740. tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
  2741. } else {
  2742. proto_line = tor_strdup("");
  2743. }
  2744. address = tor_dup_ip(router->addr);
  2745. chunks = smartlist_new();
  2746. /* Generate the easy portion of the router descriptor. */
  2747. smartlist_add_asprintf(chunks,
  2748. "router %s %s %d 0 %d\n"
  2749. "%s"
  2750. "%s"
  2751. "platform %s\n"
  2752. "%s"
  2753. "published %s\n"
  2754. "fingerprint %s\n"
  2755. "uptime %ld\n"
  2756. "bandwidth %d %d %d\n"
  2757. "%s%s"
  2758. "onion-key\n%s"
  2759. "signing-key\n%s"
  2760. "%s%s"
  2761. "%s%s%s",
  2762. router->nickname,
  2763. address,
  2764. router->or_port,
  2765. router_should_advertise_dirport(options, router->dir_port),
  2766. ed_cert_line ? ed_cert_line : "",
  2767. extra_or_address ? extra_or_address : "",
  2768. router->platform,
  2769. proto_line,
  2770. published,
  2771. fingerprint,
  2772. get_uptime(),
  2773. (int) router->bandwidthrate,
  2774. (int) router->bandwidthburst,
  2775. (int) router->bandwidthcapacity,
  2776. extra_info_line ? extra_info_line : "",
  2777. (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
  2778. "caches-extra-info\n" : "",
  2779. onion_pkey, identity_pkey,
  2780. rsa_tap_cc_line ? rsa_tap_cc_line : "",
  2781. ntor_cc_line ? ntor_cc_line : "",
  2782. family_line,
  2783. we_are_hibernating() ? "hibernating 1\n" : "",
  2784. "hidden-service-dir\n");
  2785. if (options->ContactInfo && strlen(options->ContactInfo)) {
  2786. const char *ci = options->ContactInfo;
  2787. if (strchr(ci, '\n') || strchr(ci, '\r'))
  2788. ci = escaped(ci);
  2789. smartlist_add_asprintf(chunks, "contact %s\n", ci);
  2790. }
  2791. if (options->BridgeRelay) {
  2792. const char *bd;
  2793. if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
  2794. bd = options->BridgeDistribution;
  2795. } else {
  2796. bd = "any";
  2797. }
  2798. if (strchr(bd, '\n') || strchr(bd, '\r'))
  2799. bd = escaped(bd);
  2800. smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
  2801. }
  2802. if (router->onion_curve25519_pkey) {
  2803. char kbuf[128];
  2804. base64_encode(kbuf, sizeof(kbuf),
  2805. (const char *)router->onion_curve25519_pkey->public_key,
  2806. CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
  2807. smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
  2808. } else {
  2809. /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
  2810. log_err(LD_BUG, "A relay must have an ntor onion key");
  2811. goto err;
  2812. }
  2813. /* Write the exit policy to the end of 's'. */
  2814. if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
  2815. smartlist_add_strdup(chunks, "reject *:*\n");
  2816. } else if (router->exit_policy) {
  2817. char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
  2818. if (!exit_policy)
  2819. goto err;
  2820. smartlist_add_asprintf(chunks, "%s\n", exit_policy);
  2821. tor_free(exit_policy);
  2822. }
  2823. if (router->ipv6_exit_policy) {
  2824. char *p6 = write_short_policy(router->ipv6_exit_policy);
  2825. if (p6 && strcmp(p6, "reject 1-65535")) {
  2826. smartlist_add_asprintf(chunks,
  2827. "ipv6-policy %s\n", p6);
  2828. }
  2829. tor_free(p6);
  2830. }
  2831. if (router_should_advertise_begindir(options,
  2832. router->supports_tunnelled_dir_requests)) {
  2833. smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
  2834. }
  2835. /* Sign the descriptor with Ed25519 */
  2836. if (emit_ed_sigs) {
  2837. smartlist_add_strdup(chunks, "router-sig-ed25519 ");
  2838. crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
  2839. ED_DESC_SIGNATURE_PREFIX,
  2840. chunks, "", DIGEST_SHA256);
  2841. ed25519_signature_t sig;
  2842. char buf[ED25519_SIG_BASE64_LEN+1];
  2843. if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
  2844. signing_keypair) < 0)
  2845. goto err;
  2846. if (ed25519_signature_to_base64(buf, &sig) < 0)
  2847. goto err;
  2848. smartlist_add_asprintf(chunks, "%s\n", buf);
  2849. }
  2850. /* Sign the descriptor with RSA */
  2851. smartlist_add_strdup(chunks, "router-signature\n");
  2852. crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
  2853. {
  2854. char *sig;
  2855. if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
  2856. log_warn(LD_BUG, "Couldn't sign router descriptor");
  2857. goto err;
  2858. }
  2859. smartlist_add(chunks, sig);
  2860. }
  2861. /* include a last '\n' */
  2862. smartlist_add_strdup(chunks, "\n");
  2863. output = smartlist_join_strings(chunks, "", 0, NULL);
  2864. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  2865. {
  2866. char *s_dup;
  2867. const char *cp;
  2868. routerinfo_t *ri_tmp;
  2869. cp = s_dup = tor_strdup(output);
  2870. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
  2871. if (!ri_tmp) {
  2872. log_err(LD_BUG,
  2873. "We just generated a router descriptor we can't parse.");
  2874. log_err(LD_BUG, "Descriptor was: <<%s>>", output);
  2875. goto err;
  2876. }
  2877. tor_free(s_dup);
  2878. routerinfo_free(ri_tmp);
  2879. }
  2880. #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
  2881. goto done;
  2882. err:
  2883. tor_free(output); /* sets output to NULL */
  2884. done:
  2885. if (chunks) {
  2886. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2887. smartlist_free(chunks);
  2888. }
  2889. tor_free(address);
  2890. tor_free(family_line);
  2891. tor_free(onion_pkey);
  2892. tor_free(identity_pkey);
  2893. tor_free(extra_or_address);
  2894. tor_free(ed_cert_line);
  2895. tor_free(rsa_tap_cc_line);
  2896. tor_free(ntor_cc_line);
  2897. tor_free(extra_info_line);
  2898. tor_free(proto_line);
  2899. return output;
  2900. }
  2901. /**
  2902. * OR only: Given <b>router</b>, produce a string with its exit policy.
  2903. * If <b>include_ipv4</b> is true, include IPv4 entries.
  2904. * If <b>include_ipv6</b> is true, include IPv6 entries.
  2905. */
  2906. char *
  2907. router_dump_exit_policy_to_string(const routerinfo_t *router,
  2908. int include_ipv4,
  2909. int include_ipv6)
  2910. {
  2911. if ((!router->exit_policy) || (router->policy_is_reject_star)) {
  2912. return tor_strdup("reject *:*");
  2913. }
  2914. return policy_dump_to_string(router->exit_policy,
  2915. include_ipv4,
  2916. include_ipv6);
  2917. }
  2918. /** Copy the primary (IPv4) OR port (IP address and TCP port) for
  2919. * <b>router</b> into *<b>ap_out</b>. */
  2920. void
  2921. router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
  2922. {
  2923. tor_assert(ap_out != NULL);
  2924. tor_addr_from_ipv4h(&ap_out->addr, router->addr);
  2925. ap_out->port = router->or_port;
  2926. }
  2927. /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
  2928. * Otherwise return 0. */
  2929. int
  2930. router_has_addr(const routerinfo_t *router, const tor_addr_t *addr)
  2931. {
  2932. return
  2933. tor_addr_eq_ipv4h(addr, router->addr) ||
  2934. tor_addr_eq(&router->ipv6_addr, addr);
  2935. }
  2936. int
  2937. router_has_orport(const routerinfo_t *router, const tor_addr_port_t *orport)
  2938. {
  2939. return
  2940. (tor_addr_eq_ipv4h(&orport->addr, router->addr) &&
  2941. orport->port == router->or_port) ||
  2942. (tor_addr_eq(&orport->addr, &router->ipv6_addr) &&
  2943. orport->port == router->ipv6_orport);
  2944. }
  2945. /** Load the contents of <b>filename</b>, find the last line starting with
  2946. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  2947. * the past or more than 1 hour in the future with respect to <b>now</b>,
  2948. * and write the file contents starting with that line to *<b>out</b>.
  2949. * Return 1 for success, 0 if the file does not exist or is empty, or -1
  2950. * if the file does not contain a line matching these criteria or other
  2951. * failure. */
  2952. static int
  2953. load_stats_file(const char *filename, const char *end_line, time_t now,
  2954. char **out)
  2955. {
  2956. int r = -1;
  2957. char *fname = get_datadir_fname(filename);
  2958. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  2959. time_t written;
  2960. switch (file_status(fname)) {
  2961. case FN_FILE:
  2962. /* X022 Find an alternative to reading the whole file to memory. */
  2963. if ((contents = read_file_to_str(fname, 0, NULL))) {
  2964. tmp = strstr(contents, end_line);
  2965. /* Find last block starting with end_line */
  2966. while (tmp) {
  2967. start = tmp;
  2968. tmp = strstr(tmp + 1, end_line);
  2969. }
  2970. if (!start)
  2971. goto notfound;
  2972. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  2973. goto notfound;
  2974. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  2975. if (parse_iso_time(timestr, &written) < 0)
  2976. goto notfound;
  2977. if (written < now - (25*60*60) || written > now + (1*60*60))
  2978. goto notfound;
  2979. *out = tor_strdup(start);
  2980. r = 1;
  2981. }
  2982. notfound:
  2983. tor_free(contents);
  2984. break;
  2985. /* treat empty stats files as if the file doesn't exist */
  2986. case FN_NOENT:
  2987. case FN_EMPTY:
  2988. r = 0;
  2989. break;
  2990. case FN_ERROR:
  2991. case FN_DIR:
  2992. default:
  2993. break;
  2994. }
  2995. tor_free(fname);
  2996. return r;
  2997. }
  2998. /** Write the contents of <b>extrainfo</b> and aggregated statistics to
  2999. * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
  3000. * success, negative on failure. */
  3001. int
  3002. extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
  3003. crypto_pk_t *ident_key,
  3004. const ed25519_keypair_t *signing_keypair)
  3005. {
  3006. const or_options_t *options = get_options();
  3007. char identity[HEX_DIGEST_LEN+1];
  3008. char published[ISO_TIME_LEN+1];
  3009. char digest[DIGEST_LEN];
  3010. char *bandwidth_usage;
  3011. int result;
  3012. static int write_stats_to_extrainfo = 1;
  3013. char sig[DIROBJ_MAX_SIG_LEN+1];
  3014. char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
  3015. time_t now = time(NULL);
  3016. smartlist_t *chunks = smartlist_new();
  3017. extrainfo_t *ei_tmp = NULL;
  3018. const int emit_ed_sigs = signing_keypair &&
  3019. extrainfo->cache_info.signing_key_cert;
  3020. char *ed_cert_line = NULL;
  3021. base16_encode(identity, sizeof(identity),
  3022. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  3023. format_iso_time(published, extrainfo->cache_info.published_on);
  3024. bandwidth_usage = rep_hist_get_bandwidth_lines();
  3025. if (emit_ed_sigs) {
  3026. if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
  3027. !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
  3028. &signing_keypair->pubkey)) {
  3029. log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
  3030. "mismatched ed25519 key chain %d",
  3031. extrainfo->cache_info.signing_key_cert->signing_key_included);
  3032. goto err;
  3033. }
  3034. char ed_cert_base64[256];
  3035. if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
  3036. (const char*)extrainfo->cache_info.signing_key_cert->encoded,
  3037. extrainfo->cache_info.signing_key_cert->encoded_len,
  3038. BASE64_ENCODE_MULTILINE) < 0) {
  3039. log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
  3040. goto err;
  3041. }
  3042. tor_asprintf(&ed_cert_line, "identity-ed25519\n"
  3043. "-----BEGIN ED25519 CERT-----\n"
  3044. "%s"
  3045. "-----END ED25519 CERT-----\n", ed_cert_base64);
  3046. } else {
  3047. ed_cert_line = tor_strdup("");
  3048. }
  3049. tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
  3050. extrainfo->nickname, identity,
  3051. ed_cert_line,
  3052. published, bandwidth_usage);
  3053. smartlist_add(chunks, pre);
  3054. if (geoip_is_loaded(AF_INET))
  3055. smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
  3056. geoip_db_digest(AF_INET));
  3057. if (geoip_is_loaded(AF_INET6))
  3058. smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
  3059. geoip_db_digest(AF_INET6));
  3060. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  3061. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  3062. if (options->DirReqStatistics &&
  3063. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  3064. "dirreq-stats-end", now, &contents) > 0) {
  3065. smartlist_add(chunks, contents);
  3066. }
  3067. if (options->HiddenServiceStatistics &&
  3068. load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
  3069. "hidserv-stats-end", now, &contents) > 0) {
  3070. smartlist_add(chunks, contents);
  3071. }
  3072. if (options->EntryStatistics &&
  3073. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  3074. "entry-stats-end", now, &contents) > 0) {
  3075. smartlist_add(chunks, contents);
  3076. }
  3077. if (options->CellStatistics &&
  3078. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  3079. "cell-stats-end", now, &contents) > 0) {
  3080. smartlist_add(chunks, contents);
  3081. }
  3082. if (options->ExitPortStatistics &&
  3083. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  3084. "exit-stats-end", now, &contents) > 0) {
  3085. smartlist_add(chunks, contents);
  3086. }
  3087. if (options->ConnDirectionStatistics &&
  3088. load_stats_file("stats"PATH_SEPARATOR"conn-stats",
  3089. "conn-bi-direct", now, &contents) > 0) {
  3090. smartlist_add(chunks, contents);
  3091. }
  3092. }
  3093. if (options->PaddingStatistics) {
  3094. contents = rep_hist_get_padding_count_lines();
  3095. if (contents)
  3096. smartlist_add(chunks, contents);
  3097. }
  3098. /* Add information about the pluggable transports we support. */
  3099. if (options->ServerTransportPlugin) {
  3100. char *pluggable_transports = pt_get_extra_info_descriptor_string();
  3101. if (pluggable_transports)
  3102. smartlist_add(chunks, pluggable_transports);
  3103. }
  3104. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  3105. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  3106. if (bridge_stats) {
  3107. smartlist_add_strdup(chunks, bridge_stats);
  3108. }
  3109. }
  3110. if (emit_ed_sigs) {
  3111. char sha256_digest[DIGEST256_LEN];
  3112. smartlist_add_strdup(chunks, "router-sig-ed25519 ");
  3113. crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
  3114. ED_DESC_SIGNATURE_PREFIX,
  3115. chunks, "", DIGEST_SHA256);
  3116. ed25519_signature_t ed_sig;
  3117. char buf[ED25519_SIG_BASE64_LEN+1];
  3118. if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
  3119. signing_keypair) < 0)
  3120. goto err;
  3121. if (ed25519_signature_to_base64(buf, &ed_sig) < 0)
  3122. goto err;
  3123. smartlist_add_asprintf(chunks, "%s\n", buf);
  3124. }
  3125. smartlist_add_strdup(chunks, "router-signature\n");
  3126. s = smartlist_join_strings(chunks, "", 0, NULL);
  3127. while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
  3128. /* So long as there are at least two chunks (one for the initial
  3129. * extra-info line and one for the router-signature), we can keep removing
  3130. * things. */
  3131. if (smartlist_len(chunks) > 2) {
  3132. /* We remove the next-to-last element (remember, len-1 is the last
  3133. element), since we need to keep the router-signature element. */
  3134. int idx = smartlist_len(chunks) - 2;
  3135. char *e = smartlist_get(chunks, idx);
  3136. smartlist_del_keeporder(chunks, idx);
  3137. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  3138. "with statistics that exceeds the 50 KB "
  3139. "upload limit. Removing last added "
  3140. "statistics.");
  3141. tor_free(e);
  3142. tor_free(s);
  3143. s = smartlist_join_strings(chunks, "", 0, NULL);
  3144. } else {
  3145. log_warn(LD_BUG, "We just generated an extra-info descriptors that "
  3146. "exceeds the 50 KB upload limit.");
  3147. goto err;
  3148. }
  3149. }
  3150. memset(sig, 0, sizeof(sig));
  3151. if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
  3152. router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
  3153. ident_key) < 0) {
  3154. log_warn(LD_BUG, "Could not append signature to extra-info "
  3155. "descriptor.");
  3156. goto err;
  3157. }
  3158. smartlist_add_strdup(chunks, sig);
  3159. tor_free(s);
  3160. s = smartlist_join_strings(chunks, "", 0, NULL);
  3161. cp = s_dup = tor_strdup(s);
  3162. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
  3163. if (!ei_tmp) {
  3164. if (write_stats_to_extrainfo) {
  3165. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  3166. "with statistics that we can't parse. Not "
  3167. "adding statistics to this or any future "
  3168. "extra-info descriptors.");
  3169. write_stats_to_extrainfo = 0;
  3170. result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
  3171. signing_keypair);
  3172. goto done;
  3173. } else {
  3174. log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
  3175. "can't parse.");
  3176. goto err;
  3177. }
  3178. }
  3179. *s_out = s;
  3180. s = NULL; /* prevent free */
  3181. result = 0;
  3182. goto done;
  3183. err:
  3184. result = -1;
  3185. done:
  3186. tor_free(s);
  3187. SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
  3188. smartlist_free(chunks);
  3189. tor_free(s_dup);
  3190. tor_free(ed_cert_line);
  3191. extrainfo_free(ei_tmp);
  3192. tor_free(bandwidth_usage);
  3193. return result;
  3194. }
  3195. /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
  3196. * containing between 1 and MAX_NICKNAME_LEN characters from
  3197. * LEGAL_NICKNAME_CHARACTERS.) */
  3198. int
  3199. is_legal_nickname(const char *s)
  3200. {
  3201. size_t len;
  3202. tor_assert(s);
  3203. len = strlen(s);
  3204. return len > 0 && len <= MAX_NICKNAME_LEN &&
  3205. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  3206. }
  3207. /** Return true iff <b>s</b> is a valid server nickname or
  3208. * hex-encoded identity-key digest. */
  3209. int
  3210. is_legal_nickname_or_hexdigest(const char *s)
  3211. {
  3212. if (*s!='$')
  3213. return is_legal_nickname(s);
  3214. else
  3215. return is_legal_hexdigest(s);
  3216. }
  3217. /** Return true iff <b>s</b> is a valid hex-encoded identity-key
  3218. * digest. (That is, an optional $, followed by 40 hex characters,
  3219. * followed by either nothing, or = or ~ followed by a nickname, or
  3220. * a character other than =, ~, or a hex character.)
  3221. */
  3222. int
  3223. is_legal_hexdigest(const char *s)
  3224. {
  3225. size_t len;
  3226. tor_assert(s);
  3227. if (s[0] == '$') s++;
  3228. len = strlen(s);
  3229. if (len > HEX_DIGEST_LEN) {
  3230. if (s[HEX_DIGEST_LEN] == '=' ||
  3231. s[HEX_DIGEST_LEN] == '~') {
  3232. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  3233. return 0;
  3234. } else {
  3235. return 0;
  3236. }
  3237. }
  3238. return (len >= HEX_DIGEST_LEN &&
  3239. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  3240. }
  3241. /**
  3242. * Longest allowed output of format_node_description, plus 1 character for
  3243. * NUL. This allows space for:
  3244. * "$FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF~xxxxxxxxxxxxxxxxxxx at"
  3245. * " [ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255]"
  3246. * plus a terminating NUL.
  3247. */
  3248. #define NODE_DESC_BUF_LEN (MAX_VERBOSE_NICKNAME_LEN+4+TOR_ADDR_BUF_LEN)
  3249. /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
  3250. * hold a human-readable description of a node with identity digest
  3251. * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
  3252. * and address <b>addr</b> or <b>addr32h</b>.
  3253. *
  3254. * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
  3255. * NULL. The <b>addr32h</b> field is optional and may be set to 0.
  3256. *
  3257. * Return a pointer to the front of <b>buf</b>.
  3258. */
  3259. const char *
  3260. format_node_description(char *buf,
  3261. const char *id_digest,
  3262. int is_named,
  3263. const char *nickname,
  3264. const tor_addr_t *addr,
  3265. uint32_t addr32h)
  3266. {
  3267. char *cp;
  3268. if (!buf)
  3269. return "<NULL BUFFER>";
  3270. buf[0] = '$';
  3271. base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  3272. cp = buf+1+HEX_DIGEST_LEN;
  3273. if (nickname) {
  3274. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  3275. strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  3276. cp += strlen(cp);
  3277. }
  3278. if (addr32h || addr) {
  3279. memcpy(cp, " at ", 4);
  3280. cp += 4;
  3281. if (addr) {
  3282. tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
  3283. } else {
  3284. struct in_addr in;
  3285. in.s_addr = htonl(addr32h);
  3286. tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
  3287. }
  3288. }
  3289. return buf;
  3290. }
  3291. /** Return a human-readable description of the routerinfo_t <b>ri</b>.
  3292. *
  3293. * This function is not thread-safe. Each call to this function invalidates
  3294. * previous values returned by this function.
  3295. */
  3296. const char *
  3297. router_describe(const routerinfo_t *ri)
  3298. {
  3299. static char buf[NODE_DESC_BUF_LEN];
  3300. if (!ri)
  3301. return "<null>";
  3302. return format_node_description(buf,
  3303. ri->cache_info.identity_digest,
  3304. 0,
  3305. ri->nickname,
  3306. NULL,
  3307. ri->addr);
  3308. }
  3309. /** Return a human-readable description of the node_t <b>node</b>.
  3310. *
  3311. * This function is not thread-safe. Each call to this function invalidates
  3312. * previous values returned by this function.
  3313. */
  3314. const char *
  3315. node_describe(const node_t *node)
  3316. {
  3317. static char buf[NODE_DESC_BUF_LEN];
  3318. const char *nickname = NULL;
  3319. uint32_t addr32h = 0;
  3320. int is_named = 0;
  3321. if (!node)
  3322. return "<null>";
  3323. if (node->rs) {
  3324. nickname = node->rs->nickname;
  3325. is_named = node->rs->is_named;
  3326. addr32h = node->rs->addr;
  3327. } else if (node->ri) {
  3328. nickname = node->ri->nickname;
  3329. addr32h = node->ri->addr;
  3330. }
  3331. return format_node_description(buf,
  3332. node->identity,
  3333. is_named,
  3334. nickname,
  3335. NULL,
  3336. addr32h);
  3337. }
  3338. /** Return a human-readable description of the routerstatus_t <b>rs</b>.
  3339. *
  3340. * This function is not thread-safe. Each call to this function invalidates
  3341. * previous values returned by this function.
  3342. */
  3343. const char *
  3344. routerstatus_describe(const routerstatus_t *rs)
  3345. {
  3346. static char buf[NODE_DESC_BUF_LEN];
  3347. if (!rs)
  3348. return "<null>";
  3349. return format_node_description(buf,
  3350. rs->identity_digest,
  3351. rs->is_named,
  3352. rs->nickname,
  3353. NULL,
  3354. rs->addr);
  3355. }
  3356. /** Return a human-readable description of the extend_info_t <b>ei</b>.
  3357. *
  3358. * This function is not thread-safe. Each call to this function invalidates
  3359. * previous values returned by this function.
  3360. */
  3361. const char *
  3362. extend_info_describe(const extend_info_t *ei)
  3363. {
  3364. static char buf[NODE_DESC_BUF_LEN];
  3365. if (!ei)
  3366. return "<null>";
  3367. return format_node_description(buf,
  3368. ei->identity_digest,
  3369. 0,
  3370. ei->nickname,
  3371. &ei->addr,
  3372. 0);
  3373. }
  3374. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  3375. * verbose representation of the identity of <b>router</b>. The format is:
  3376. * A dollar sign.
  3377. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  3378. * A "=" if the router is named (no longer implemented); a "~" if it is not.
  3379. * The router's nickname.
  3380. **/
  3381. void
  3382. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  3383. {
  3384. buf[0] = '$';
  3385. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  3386. DIGEST_LEN);
  3387. buf[1+HEX_DIGEST_LEN] = '~';
  3388. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  3389. }
  3390. /** Forget that we have issued any router-related warnings, so that we'll
  3391. * warn again if we see the same errors. */
  3392. void
  3393. router_reset_warnings(void)
  3394. {
  3395. if (warned_nonexistent_family) {
  3396. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  3397. smartlist_clear(warned_nonexistent_family);
  3398. }
  3399. }
  3400. /** Given a router purpose, convert it to a string. Don't call this on
  3401. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  3402. * know its string representation. */
  3403. const char *
  3404. router_purpose_to_string(uint8_t p)
  3405. {
  3406. switch (p)
  3407. {
  3408. case ROUTER_PURPOSE_GENERAL: return "general";
  3409. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  3410. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  3411. default:
  3412. tor_assert(0);
  3413. }
  3414. return NULL;
  3415. }
  3416. /** Given a string, convert it to a router purpose. */
  3417. uint8_t
  3418. router_purpose_from_string(const char *s)
  3419. {
  3420. if (!strcmp(s, "general"))
  3421. return ROUTER_PURPOSE_GENERAL;
  3422. else if (!strcmp(s, "bridge"))
  3423. return ROUTER_PURPOSE_BRIDGE;
  3424. else if (!strcmp(s, "controller"))
  3425. return ROUTER_PURPOSE_CONTROLLER;
  3426. else
  3427. return ROUTER_PURPOSE_UNKNOWN;
  3428. }
  3429. /** Release all static resources held in router.c */
  3430. void
  3431. router_free_all(void)
  3432. {
  3433. crypto_pk_free(onionkey);
  3434. crypto_pk_free(lastonionkey);
  3435. crypto_pk_free(server_identitykey);
  3436. crypto_pk_free(client_identitykey);
  3437. tor_mutex_free(key_lock);
  3438. routerinfo_free(desc_routerinfo);
  3439. extrainfo_free(desc_extrainfo);
  3440. crypto_pk_free(authority_signing_key);
  3441. authority_cert_free(authority_key_certificate);
  3442. crypto_pk_free(legacy_signing_key);
  3443. authority_cert_free(legacy_key_certificate);
  3444. memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
  3445. memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
  3446. if (warned_nonexistent_family) {
  3447. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  3448. smartlist_free(warned_nonexistent_family);
  3449. }
  3450. }
  3451. /** Return a smartlist of tor_addr_port_t's with all the OR ports of
  3452. <b>ri</b>. Note that freeing of the items in the list as well as
  3453. the smartlist itself is the callers responsibility. */
  3454. smartlist_t *
  3455. router_get_all_orports(const routerinfo_t *ri)
  3456. {
  3457. tor_assert(ri);
  3458. node_t fake_node;
  3459. memset(&fake_node, 0, sizeof(fake_node));
  3460. /* we don't modify ri, fake_node is passed as a const node_t *
  3461. */
  3462. fake_node.ri = (routerinfo_t *)ri;
  3463. return node_get_all_orports(&fake_node);
  3464. }