router.c 129 KB

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