router.c 129 KB

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