router.c 127 KB

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