router.c 126 KB

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