router.c 105 KB

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