router.c 129 KB

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