router.c 105 KB

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