router.c 107 KB

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