router.c 126 KB

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