router.c 129 KB

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