router.c 115 KB

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