router.c 126 KB

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