router.c 105 KB

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