router.c 105 KB

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