router.c 127 KB

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