router.c 129 KB

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