router.c 105 KB

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