router.c 126 KB

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