hs_service.c 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132
  1. /* Copyright (c) 2016-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_service.c
  5. * \brief Implement next generation hidden service functionality
  6. **/
  7. #define HS_SERVICE_PRIVATE
  8. #include "core/or/or.h"
  9. #include "app/config/config.h"
  10. #include "app/config/statefile.h"
  11. #include "core/mainloop/connection.h"
  12. #include "core/mainloop/mainloop.h"
  13. #include "core/or/circuitbuild.h"
  14. #include "core/or/circuitlist.h"
  15. #include "core/or/circuituse.h"
  16. #include "core/or/relay.h"
  17. #include "feature/client/circpathbias.h"
  18. #include "feature/dirclient/dirclient.h"
  19. #include "feature/dircommon/directory.h"
  20. #include "feature/hs_common/shared_random_client.h"
  21. #include "feature/keymgt/loadkey.h"
  22. #include "feature/nodelist/describe.h"
  23. #include "feature/nodelist/networkstatus.h"
  24. #include "feature/nodelist/nickname.h"
  25. #include "feature/nodelist/node_select.h"
  26. #include "feature/nodelist/nodelist.h"
  27. #include "feature/rend/rendservice.h"
  28. #include "lib/crypt_ops/crypto_ope.h"
  29. #include "lib/crypt_ops/crypto_rand.h"
  30. #include "lib/crypt_ops/crypto_rand.h"
  31. #include "lib/crypt_ops/crypto_util.h"
  32. #include "feature/hs/hs_circuit.h"
  33. #include "feature/hs/hs_common.h"
  34. #include "feature/hs/hs_config.h"
  35. #include "feature/hs/hs_control.h"
  36. #include "feature/hs/hs_descriptor.h"
  37. #include "feature/hs/hs_ident.h"
  38. #include "feature/hs/hs_intropoint.h"
  39. #include "feature/hs/hs_service.h"
  40. #include "feature/hs/hs_stats.h"
  41. #include "feature/dircommon/dir_connection_st.h"
  42. #include "core/or/edge_connection_st.h"
  43. #include "core/or/extend_info_st.h"
  44. #include "feature/nodelist/networkstatus_st.h"
  45. #include "feature/nodelist/node_st.h"
  46. #include "core/or/origin_circuit_st.h"
  47. #include "app/config/or_state_st.h"
  48. #include "feature/nodelist/routerstatus_st.h"
  49. #include "lib/encoding/confline.h"
  50. #include "lib/crypt_ops/crypto_format.h"
  51. /* Trunnel */
  52. #include "trunnel/ed25519_cert.h"
  53. #include "trunnel/hs/cell_common.h"
  54. #include "trunnel/hs/cell_establish_intro.h"
  55. #ifdef HAVE_SYS_STAT_H
  56. #include <sys/stat.h>
  57. #endif
  58. #ifdef HAVE_UNISTD_H
  59. #include <unistd.h>
  60. #endif
  61. /* Helper macro. Iterate over every service in the global map. The var is the
  62. * name of the service pointer. */
  63. #define FOR_EACH_SERVICE_BEGIN(var) \
  64. STMT_BEGIN \
  65. hs_service_t **var##_iter, *var; \
  66. HT_FOREACH(var##_iter, hs_service_ht, hs_service_map) { \
  67. var = *var##_iter;
  68. #define FOR_EACH_SERVICE_END } STMT_END ;
  69. /* Helper macro. Iterate over both current and previous descriptor of a
  70. * service. The var is the name of the descriptor pointer. This macro skips
  71. * any descriptor object of the service that is NULL. */
  72. #define FOR_EACH_DESCRIPTOR_BEGIN(service, var) \
  73. STMT_BEGIN \
  74. hs_service_descriptor_t *var; \
  75. for (int var ## _loop_idx = 0; var ## _loop_idx < 2; \
  76. ++var ## _loop_idx) { \
  77. (var ## _loop_idx == 0) ? (var = service->desc_current) : \
  78. (var = service->desc_next); \
  79. if (var == NULL) continue;
  80. #define FOR_EACH_DESCRIPTOR_END } STMT_END ;
  81. /* Onion service directory file names. */
  82. static const char fname_keyfile_prefix[] = "hs_ed25519";
  83. static const char dname_client_pubkeys[] = "authorized_clients";
  84. static const char fname_hostname[] = "hostname";
  85. static const char address_tld[] = "onion";
  86. /* Staging list of service object. When configuring service, we add them to
  87. * this list considered a staging area and they will get added to our global
  88. * map once the keys have been loaded. These two steps are separated because
  89. * loading keys requires that we are an actual running tor process. */
  90. static smartlist_t *hs_service_staging_list;
  91. /** True if the list of available router descriptors might have changed which
  92. * might result in an altered hash ring. Check if the hash ring changed and
  93. * reupload if needed */
  94. static int consider_republishing_hs_descriptors = 0;
  95. /* Static declaration. */
  96. static int load_client_keys(hs_service_t *service);
  97. static void set_descriptor_revision_counter(hs_service_descriptor_t *hs_desc,
  98. time_t now, bool is_current);
  99. static int build_service_desc_superencrypted(const hs_service_t *service,
  100. hs_service_descriptor_t *desc);
  101. static void move_descriptors(hs_service_t *src, hs_service_t *dst);
  102. static int service_encode_descriptor(const hs_service_t *service,
  103. const hs_service_descriptor_t *desc,
  104. const ed25519_keypair_t *signing_kp,
  105. char **encoded_out);
  106. /* Helper: Function to compare two objects in the service map. Return 1 if the
  107. * two service have the same master public identity key. */
  108. static inline int
  109. hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
  110. {
  111. tor_assert(first);
  112. tor_assert(second);
  113. /* Simple key compare. */
  114. return ed25519_pubkey_eq(&first->keys.identity_pk,
  115. &second->keys.identity_pk);
  116. }
  117. /* Helper: Function for the service hash table code below. The key used is the
  118. * master public identity key which is ultimately the onion address. */
  119. static inline unsigned int
  120. hs_service_ht_hash(const hs_service_t *service)
  121. {
  122. tor_assert(service);
  123. return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
  124. sizeof(service->keys.identity_pk.pubkey));
  125. }
  126. /* This is _the_ global hash map of hidden services which indexed the service
  127. * contained in it by master public identity key which is roughly the onion
  128. * address of the service. */
  129. static struct hs_service_ht *hs_service_map;
  130. /* Register the service hash table. */
  131. HT_PROTOTYPE(hs_service_ht, /* Name of hashtable. */
  132. hs_service_t, /* Object contained in the map. */
  133. hs_service_node, /* The name of the HT_ENTRY member. */
  134. hs_service_ht_hash, /* Hashing function. */
  135. hs_service_ht_eq) /* Compare function for objects. */
  136. HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
  137. hs_service_ht_hash, hs_service_ht_eq,
  138. 0.6, tor_reallocarray, tor_free_)
  139. /* Query the given service map with a public key and return a service object
  140. * if found else NULL. It is also possible to set a directory path in the
  141. * search query. If pk is NULL, then it will be set to zero indicating the
  142. * hash table to compare the directory path instead. */
  143. STATIC hs_service_t *
  144. find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
  145. {
  146. hs_service_t dummy_service;
  147. tor_assert(map);
  148. tor_assert(pk);
  149. memset(&dummy_service, 0, sizeof(dummy_service));
  150. ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
  151. return HT_FIND(hs_service_ht, map, &dummy_service);
  152. }
  153. /* Register the given service in the given map. If the service already exists
  154. * in the map, -1 is returned. On success, 0 is returned and the service
  155. * ownership has been transferred to the global map. */
  156. STATIC int
  157. register_service(hs_service_ht *map, hs_service_t *service)
  158. {
  159. tor_assert(map);
  160. tor_assert(service);
  161. tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
  162. if (find_service(map, &service->keys.identity_pk)) {
  163. /* Existing service with the same key. Do not register it. */
  164. return -1;
  165. }
  166. /* Taking ownership of the object at this point. */
  167. HT_INSERT(hs_service_ht, map, service);
  168. /* If we just modified the global map, we notify. */
  169. if (map == hs_service_map) {
  170. hs_service_map_has_changed();
  171. }
  172. return 0;
  173. }
  174. /* Remove a given service from the given map. If service is NULL or the
  175. * service key is unset, return gracefully. */
  176. STATIC void
  177. remove_service(hs_service_ht *map, hs_service_t *service)
  178. {
  179. hs_service_t *elm;
  180. tor_assert(map);
  181. /* Ignore if no service or key is zero. */
  182. if (BUG(service == NULL) ||
  183. BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
  184. return;
  185. }
  186. elm = HT_REMOVE(hs_service_ht, map, service);
  187. if (elm) {
  188. tor_assert(elm == service);
  189. } else {
  190. log_warn(LD_BUG, "Could not find service in the global map "
  191. "while removing service %s",
  192. escaped(service->config.directory_path));
  193. }
  194. /* If we just modified the global map, we notify. */
  195. if (map == hs_service_map) {
  196. hs_service_map_has_changed();
  197. }
  198. }
  199. /* Set the default values for a service configuration object <b>c</b>. */
  200. static void
  201. set_service_default_config(hs_service_config_t *c,
  202. const or_options_t *options)
  203. {
  204. (void) options;
  205. tor_assert(c);
  206. c->ports = smartlist_new();
  207. c->directory_path = NULL;
  208. c->max_streams_per_rdv_circuit = 0;
  209. c->max_streams_close_circuit = 0;
  210. c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
  211. c->allow_unknown_ports = 0;
  212. c->is_single_onion = 0;
  213. c->dir_group_readable = 0;
  214. c->is_ephemeral = 0;
  215. }
  216. /* From a service configuration object config, clear everything from it
  217. * meaning free allocated pointers and reset the values. */
  218. STATIC void
  219. service_clear_config(hs_service_config_t *config)
  220. {
  221. if (config == NULL) {
  222. return;
  223. }
  224. tor_free(config->directory_path);
  225. if (config->ports) {
  226. SMARTLIST_FOREACH(config->ports, rend_service_port_config_t *, p,
  227. rend_service_port_config_free(p););
  228. smartlist_free(config->ports);
  229. }
  230. if (config->clients) {
  231. SMARTLIST_FOREACH(config->clients, hs_service_authorized_client_t *, p,
  232. service_authorized_client_free(p));
  233. smartlist_free(config->clients);
  234. }
  235. memset(config, 0, sizeof(*config));
  236. }
  237. /* Helper function to return a human readable description of the given intro
  238. * point object.
  239. *
  240. * This function is not thread-safe. Each call to this invalidates the
  241. * previous values returned by it. */
  242. static const char *
  243. describe_intro_point(const hs_service_intro_point_t *ip)
  244. {
  245. /* Hex identity digest of the IP prefixed by the $ sign and ends with NUL
  246. * byte hence the plus two. */
  247. static char buf[HEX_DIGEST_LEN + 2];
  248. const char *legacy_id = NULL;
  249. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  250. const hs_desc_link_specifier_t *, lspec) {
  251. if (lspec->type == LS_LEGACY_ID) {
  252. legacy_id = (const char *) lspec->u.legacy_id;
  253. break;
  254. }
  255. } SMARTLIST_FOREACH_END(lspec);
  256. /* For now, we only print the identity digest but we could improve this with
  257. * much more information such as the ed25519 identity has well. */
  258. buf[0] = '$';
  259. if (legacy_id) {
  260. base16_encode(buf + 1, HEX_DIGEST_LEN + 1, legacy_id, DIGEST_LEN);
  261. }
  262. return buf;
  263. }
  264. /* Return the lower bound of maximum INTRODUCE2 cells per circuit before we
  265. * rotate intro point (defined by a consensus parameter or the default
  266. * value). */
  267. static int32_t
  268. get_intro_point_min_introduce2(void)
  269. {
  270. /* The [0, 2147483647] range is quite large to accommodate anything we decide
  271. * in the future. */
  272. return networkstatus_get_param(NULL, "hs_intro_min_introduce2",
  273. INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  274. 0, INT32_MAX);
  275. }
  276. /* Return the upper bound of maximum INTRODUCE2 cells per circuit before we
  277. * rotate intro point (defined by a consensus parameter or the default
  278. * value). */
  279. static int32_t
  280. get_intro_point_max_introduce2(void)
  281. {
  282. /* The [0, 2147483647] range is quite large to accommodate anything we decide
  283. * in the future. */
  284. return networkstatus_get_param(NULL, "hs_intro_max_introduce2",
  285. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS,
  286. 0, INT32_MAX);
  287. }
  288. /* Return the minimum lifetime in seconds of an introduction point defined by a
  289. * consensus parameter or the default value. */
  290. static int32_t
  291. get_intro_point_min_lifetime(void)
  292. {
  293. #define MIN_INTRO_POINT_LIFETIME_TESTING 10
  294. if (get_options()->TestingTorNetwork) {
  295. return MIN_INTRO_POINT_LIFETIME_TESTING;
  296. }
  297. /* The [0, 2147483647] range is quite large to accommodate anything we decide
  298. * in the future. */
  299. return networkstatus_get_param(NULL, "hs_intro_min_lifetime",
  300. INTRO_POINT_LIFETIME_MIN_SECONDS,
  301. 0, INT32_MAX);
  302. }
  303. /* Return the maximum lifetime in seconds of an introduction point defined by a
  304. * consensus parameter or the default value. */
  305. static int32_t
  306. get_intro_point_max_lifetime(void)
  307. {
  308. #define MAX_INTRO_POINT_LIFETIME_TESTING 30
  309. if (get_options()->TestingTorNetwork) {
  310. return MAX_INTRO_POINT_LIFETIME_TESTING;
  311. }
  312. /* The [0, 2147483647] range is quite large to accommodate anything we decide
  313. * in the future. */
  314. return networkstatus_get_param(NULL, "hs_intro_max_lifetime",
  315. INTRO_POINT_LIFETIME_MAX_SECONDS,
  316. 0, INT32_MAX);
  317. }
  318. /* Return the number of extra introduction point defined by a consensus
  319. * parameter or the default value. */
  320. static int32_t
  321. get_intro_point_num_extra(void)
  322. {
  323. /* The [0, 128] range bounds the number of extra introduction point allowed.
  324. * Above 128 intro points, it's getting a bit crazy. */
  325. return networkstatus_get_param(NULL, "hs_intro_num_extra",
  326. NUM_INTRO_POINTS_EXTRA, 0, 128);
  327. }
  328. /* Helper: Function that needs to return 1 for the HT for each loop which
  329. * frees every service in an hash map. */
  330. static int
  331. ht_free_service_(struct hs_service_t *service, void *data)
  332. {
  333. (void) data;
  334. hs_service_free(service);
  335. /* This function MUST return 1 so the given object is then removed from the
  336. * service map leading to this free of the object being safe. */
  337. return 1;
  338. }
  339. /* Free every service that can be found in the global map. Once done, clear
  340. * and free the global map. */
  341. static void
  342. service_free_all(void)
  343. {
  344. if (hs_service_map) {
  345. /* The free helper function returns 1 so this is safe. */
  346. hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
  347. HT_CLEAR(hs_service_ht, hs_service_map);
  348. tor_free(hs_service_map);
  349. hs_service_map = NULL;
  350. }
  351. if (hs_service_staging_list) {
  352. /* Cleanup staging list. */
  353. SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
  354. hs_service_free(s));
  355. smartlist_free(hs_service_staging_list);
  356. hs_service_staging_list = NULL;
  357. }
  358. }
  359. /* Free a given service intro point object. */
  360. STATIC void
  361. service_intro_point_free_(hs_service_intro_point_t *ip)
  362. {
  363. if (!ip) {
  364. return;
  365. }
  366. memwipe(&ip->auth_key_kp, 0, sizeof(ip->auth_key_kp));
  367. memwipe(&ip->enc_key_kp, 0, sizeof(ip->enc_key_kp));
  368. crypto_pk_free(ip->legacy_key);
  369. replaycache_free(ip->replay_cache);
  370. hs_intropoint_clear(&ip->base);
  371. tor_free(ip);
  372. }
  373. /* Helper: free an hs_service_intro_point_t object. This function is used by
  374. * digest256map_free() which requires a void * pointer. */
  375. static void
  376. service_intro_point_free_void(void *obj)
  377. {
  378. service_intro_point_free_(obj);
  379. }
  380. /* Return a newly allocated service intro point and fully initialized from the
  381. * given extend_info_t ei if non NULL.
  382. * If is_legacy is true, we also generate the legacy key.
  383. * If supports_ed25519_link_handshake_any is true, we add the relay's ed25519
  384. * key to the link specifiers.
  385. *
  386. * If ei is NULL, returns a hs_service_intro_point_t with an empty link
  387. * specifier list and no onion key. (This is used for testing.)
  388. * On any other error, NULL is returned.
  389. *
  390. * ei must be an extend_info_t containing an IPv4 address. (We will add supoort
  391. * for IPv6 in a later release.) When calling extend_info_from_node(), pass
  392. * 0 in for_direct_connection to make sure ei always has an IPv4 address. */
  393. STATIC hs_service_intro_point_t *
  394. service_intro_point_new(const extend_info_t *ei, unsigned int is_legacy,
  395. unsigned int supports_ed25519_link_handshake_any)
  396. {
  397. hs_desc_link_specifier_t *ls;
  398. hs_service_intro_point_t *ip;
  399. ip = tor_malloc_zero(sizeof(*ip));
  400. /* We'll create the key material. No need for extra strong, those are short
  401. * term keys. */
  402. ed25519_keypair_generate(&ip->auth_key_kp, 0);
  403. { /* Set introduce2 max cells limit */
  404. int32_t min_introduce2_cells = get_intro_point_min_introduce2();
  405. int32_t max_introduce2_cells = get_intro_point_max_introduce2();
  406. if (BUG(max_introduce2_cells < min_introduce2_cells)) {
  407. goto err;
  408. }
  409. ip->introduce2_max = crypto_rand_int_range(min_introduce2_cells,
  410. max_introduce2_cells);
  411. }
  412. { /* Set intro point lifetime */
  413. int32_t intro_point_min_lifetime = get_intro_point_min_lifetime();
  414. int32_t intro_point_max_lifetime = get_intro_point_max_lifetime();
  415. if (BUG(intro_point_max_lifetime < intro_point_min_lifetime)) {
  416. goto err;
  417. }
  418. ip->time_to_expire = approx_time() +
  419. crypto_rand_int_range(intro_point_min_lifetime,intro_point_max_lifetime);
  420. }
  421. ip->replay_cache = replaycache_new(0, 0);
  422. /* Initialize the base object. We don't need the certificate object. */
  423. ip->base.link_specifiers = smartlist_new();
  424. /* Generate the encryption key for this intro point. */
  425. curve25519_keypair_generate(&ip->enc_key_kp, 0);
  426. /* Figure out if this chosen node supports v3 or is legacy only. */
  427. if (is_legacy) {
  428. ip->base.is_only_legacy = 1;
  429. /* Legacy mode that is doesn't support v3+ with ed25519 auth key. */
  430. ip->legacy_key = crypto_pk_new();
  431. if (crypto_pk_generate_key(ip->legacy_key) < 0) {
  432. goto err;
  433. }
  434. if (crypto_pk_get_digest(ip->legacy_key,
  435. (char *) ip->legacy_key_digest) < 0) {
  436. goto err;
  437. }
  438. }
  439. if (ei == NULL) {
  440. goto done;
  441. }
  442. /* We'll try to add all link specifiers. Legacy is mandatory.
  443. * IPv4 or IPv6 is required, and we always send IPv4. */
  444. ls = hs_desc_link_specifier_new(ei, LS_IPV4);
  445. /* It is impossible to have an extend info object without a v4. */
  446. if (BUG(!ls)) {
  447. goto err;
  448. }
  449. smartlist_add(ip->base.link_specifiers, ls);
  450. ls = hs_desc_link_specifier_new(ei, LS_LEGACY_ID);
  451. /* It is impossible to have an extend info object without an identity
  452. * digest. */
  453. if (BUG(!ls)) {
  454. goto err;
  455. }
  456. smartlist_add(ip->base.link_specifiers, ls);
  457. /* ed25519 identity key is optional for intro points. If the node supports
  458. * ed25519 link authentication, we include it. */
  459. if (supports_ed25519_link_handshake_any) {
  460. ls = hs_desc_link_specifier_new(ei, LS_ED25519_ID);
  461. if (ls) {
  462. smartlist_add(ip->base.link_specifiers, ls);
  463. }
  464. }
  465. /* IPv6 is not supported in this release. */
  466. /* Finally, copy onion key from the extend_info_t object. */
  467. memcpy(&ip->onion_key, &ei->curve25519_onion_key, sizeof(ip->onion_key));
  468. done:
  469. return ip;
  470. err:
  471. service_intro_point_free(ip);
  472. return NULL;
  473. }
  474. /* Add the given intro point object to the given intro point map. The intro
  475. * point MUST have its RSA encryption key set if this is a legacy type or the
  476. * authentication key set otherwise. */
  477. STATIC void
  478. service_intro_point_add(digest256map_t *map, hs_service_intro_point_t *ip)
  479. {
  480. hs_service_intro_point_t *old_ip_entry;
  481. tor_assert(map);
  482. tor_assert(ip);
  483. old_ip_entry = digest256map_set(map, ip->auth_key_kp.pubkey.pubkey, ip);
  484. /* Make sure we didn't just try to double-add an intro point */
  485. tor_assert_nonfatal(!old_ip_entry);
  486. }
  487. /* For a given service, remove the intro point from that service's descriptors
  488. * (check both current and next descriptor) */
  489. STATIC void
  490. service_intro_point_remove(const hs_service_t *service,
  491. const hs_service_intro_point_t *ip)
  492. {
  493. tor_assert(service);
  494. tor_assert(ip);
  495. /* Trying all descriptors. */
  496. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  497. /* We'll try to remove the descriptor on both descriptors which is not
  498. * very expensive to do instead of doing loopup + remove. */
  499. digest256map_remove(desc->intro_points.map,
  500. ip->auth_key_kp.pubkey.pubkey);
  501. } FOR_EACH_DESCRIPTOR_END;
  502. }
  503. /* For a given service and authentication key, return the intro point or NULL
  504. * if not found. This will check both descriptors in the service. */
  505. STATIC hs_service_intro_point_t *
  506. service_intro_point_find(const hs_service_t *service,
  507. const ed25519_public_key_t *auth_key)
  508. {
  509. hs_service_intro_point_t *ip = NULL;
  510. tor_assert(service);
  511. tor_assert(auth_key);
  512. /* Trying all descriptors to find the right intro point.
  513. *
  514. * Even if we use the same node as intro point in both descriptors, the node
  515. * will have a different intro auth key for each descriptor since we generate
  516. * a new one everytime we pick an intro point.
  517. *
  518. * After #22893 gets implemented, intro points will be moved to be
  519. * per-service instead of per-descriptor so this function will need to
  520. * change.
  521. */
  522. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  523. if ((ip = digest256map_get(desc->intro_points.map,
  524. auth_key->pubkey)) != NULL) {
  525. break;
  526. }
  527. } FOR_EACH_DESCRIPTOR_END;
  528. return ip;
  529. }
  530. /* For a given service and intro point, return the descriptor for which the
  531. * intro point is assigned to. NULL is returned if not found. */
  532. STATIC hs_service_descriptor_t *
  533. service_desc_find_by_intro(const hs_service_t *service,
  534. const hs_service_intro_point_t *ip)
  535. {
  536. hs_service_descriptor_t *descp = NULL;
  537. tor_assert(service);
  538. tor_assert(ip);
  539. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  540. if (digest256map_get(desc->intro_points.map,
  541. ip->auth_key_kp.pubkey.pubkey)) {
  542. descp = desc;
  543. break;
  544. }
  545. } FOR_EACH_DESCRIPTOR_END;
  546. return descp;
  547. }
  548. /* From a circuit identifier, get all the possible objects associated with the
  549. * ident. If not NULL, service, ip or desc are set if the object can be found.
  550. * They are untouched if they can't be found.
  551. *
  552. * This is an helper function because we do those lookups often so it's more
  553. * convenient to simply call this functions to get all the things at once. */
  554. STATIC void
  555. get_objects_from_ident(const hs_ident_circuit_t *ident,
  556. hs_service_t **service, hs_service_intro_point_t **ip,
  557. hs_service_descriptor_t **desc)
  558. {
  559. hs_service_t *s;
  560. tor_assert(ident);
  561. /* Get service object from the circuit identifier. */
  562. s = find_service(hs_service_map, &ident->identity_pk);
  563. if (s && service) {
  564. *service = s;
  565. }
  566. /* From the service object, get the intro point object of that circuit. The
  567. * following will query both descriptors intro points list. */
  568. if (s && ip) {
  569. *ip = service_intro_point_find(s, &ident->intro_auth_pk);
  570. }
  571. /* Get the descriptor for this introduction point and service. */
  572. if (s && ip && *ip && desc) {
  573. *desc = service_desc_find_by_intro(s, *ip);
  574. }
  575. }
  576. /* From a given intro point, return the first link specifier of type
  577. * encountered in the link specifier list. Return NULL if it can't be found.
  578. *
  579. * The caller does NOT have ownership of the object, the intro point does. */
  580. static hs_desc_link_specifier_t *
  581. get_link_spec_by_type(const hs_service_intro_point_t *ip, uint8_t type)
  582. {
  583. hs_desc_link_specifier_t *lnk_spec = NULL;
  584. tor_assert(ip);
  585. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  586. hs_desc_link_specifier_t *, ls) {
  587. if (ls->type == type) {
  588. lnk_spec = ls;
  589. goto end;
  590. }
  591. } SMARTLIST_FOREACH_END(ls);
  592. end:
  593. return lnk_spec;
  594. }
  595. /* Given a service intro point, return the node_t associated to it. This can
  596. * return NULL if the given intro point has no legacy ID or if the node can't
  597. * be found in the consensus. */
  598. STATIC const node_t *
  599. get_node_from_intro_point(const hs_service_intro_point_t *ip)
  600. {
  601. const hs_desc_link_specifier_t *ls;
  602. tor_assert(ip);
  603. ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  604. if (BUG(!ls)) {
  605. return NULL;
  606. }
  607. /* XXX In the future, we want to only use the ed25519 ID (#22173). */
  608. return node_get_by_id((const char *) ls->u.legacy_id);
  609. }
  610. /* Given a service intro point, return the extend_info_t for it. This can
  611. * return NULL if the node can't be found for the intro point or the extend
  612. * info can't be created for the found node. If direct_conn is set, the extend
  613. * info is validated on if we can connect directly. */
  614. static extend_info_t *
  615. get_extend_info_from_intro_point(const hs_service_intro_point_t *ip,
  616. unsigned int direct_conn)
  617. {
  618. extend_info_t *info = NULL;
  619. const node_t *node;
  620. tor_assert(ip);
  621. node = get_node_from_intro_point(ip);
  622. if (node == NULL) {
  623. /* This can happen if the relay serving as intro point has been removed
  624. * from the consensus. In that case, the intro point will be removed from
  625. * the descriptor during the scheduled events. */
  626. goto end;
  627. }
  628. /* In the case of a direct connection (single onion service), it is possible
  629. * our firewall policy won't allow it so this can return a NULL value. */
  630. info = extend_info_from_node(node, direct_conn);
  631. end:
  632. return info;
  633. }
  634. /* Return the number of introduction points that are established for the
  635. * given descriptor. */
  636. static unsigned int
  637. count_desc_circuit_established(const hs_service_descriptor_t *desc)
  638. {
  639. unsigned int count = 0;
  640. tor_assert(desc);
  641. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  642. const hs_service_intro_point_t *, ip) {
  643. count += ip->circuit_established;
  644. } DIGEST256MAP_FOREACH_END;
  645. return count;
  646. }
  647. /* For a given service and descriptor of that service, close all active
  648. * directory connections. */
  649. static void
  650. close_directory_connections(const hs_service_t *service,
  651. const hs_service_descriptor_t *desc)
  652. {
  653. unsigned int count = 0;
  654. smartlist_t *dir_conns;
  655. tor_assert(service);
  656. tor_assert(desc);
  657. /* Close pending HS desc upload connections for the blinded key of 'desc'. */
  658. dir_conns = connection_list_by_type_purpose(CONN_TYPE_DIR,
  659. DIR_PURPOSE_UPLOAD_HSDESC);
  660. SMARTLIST_FOREACH_BEGIN(dir_conns, connection_t *, conn) {
  661. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  662. if (ed25519_pubkey_eq(&dir_conn->hs_ident->identity_pk,
  663. &service->keys.identity_pk) &&
  664. ed25519_pubkey_eq(&dir_conn->hs_ident->blinded_pk,
  665. &desc->blinded_kp.pubkey)) {
  666. connection_mark_for_close(conn);
  667. count++;
  668. continue;
  669. }
  670. } SMARTLIST_FOREACH_END(conn);
  671. log_info(LD_REND, "Closed %u active service directory connections for "
  672. "descriptor %s of service %s",
  673. count, safe_str_client(ed25519_fmt(&desc->blinded_kp.pubkey)),
  674. safe_str_client(service->onion_address));
  675. /* We don't have ownership of the objects in this list. */
  676. smartlist_free(dir_conns);
  677. }
  678. /* Close all rendezvous circuits for the given service. */
  679. static void
  680. close_service_rp_circuits(hs_service_t *service)
  681. {
  682. origin_circuit_t *ocirc = NULL;
  683. tor_assert(service);
  684. /* The reason we go over all circuit instead of using the circuitmap API is
  685. * because most hidden service circuits are rendezvous circuits so there is
  686. * no real improvement at getting all rendezvous circuits from the
  687. * circuitmap and then going over them all to find the right ones.
  688. * Furthermore, another option would have been to keep a list of RP cookies
  689. * for a service but it creates an engineering complexity since we don't
  690. * have a "RP circuit closed" event to clean it up properly so we avoid a
  691. * memory DoS possibility. */
  692. while ((ocirc = circuit_get_next_service_rp_circ(ocirc))) {
  693. /* Only close circuits that are v3 and for this service. */
  694. if (ocirc->hs_ident != NULL &&
  695. ed25519_pubkey_eq(&ocirc->hs_ident->identity_pk,
  696. &service->keys.identity_pk)) {
  697. /* Reason is FINISHED because service has been removed and thus the
  698. * circuit is considered old/uneeded. When freed, it is removed from the
  699. * hs circuitmap. */
  700. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  701. }
  702. }
  703. }
  704. /* Close the circuit(s) for the given map of introduction points. */
  705. static void
  706. close_intro_circuits(hs_service_intropoints_t *intro_points)
  707. {
  708. tor_assert(intro_points);
  709. DIGEST256MAP_FOREACH(intro_points->map, key,
  710. const hs_service_intro_point_t *, ip) {
  711. origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
  712. if (ocirc) {
  713. /* Reason is FINISHED because service has been removed and thus the
  714. * circuit is considered old/uneeded. When freed, the circuit is removed
  715. * from the HS circuitmap. */
  716. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  717. }
  718. } DIGEST256MAP_FOREACH_END;
  719. }
  720. /* Close all introduction circuits for the given service. */
  721. static void
  722. close_service_intro_circuits(hs_service_t *service)
  723. {
  724. tor_assert(service);
  725. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  726. close_intro_circuits(&desc->intro_points);
  727. } FOR_EACH_DESCRIPTOR_END;
  728. }
  729. /* Close any circuits related to the given service. */
  730. static void
  731. close_service_circuits(hs_service_t *service)
  732. {
  733. tor_assert(service);
  734. /* Only support for version >= 3. */
  735. if (BUG(service->config.version < HS_VERSION_THREE)) {
  736. return;
  737. }
  738. /* Close intro points. */
  739. close_service_intro_circuits(service);
  740. /* Close rendezvous points. */
  741. close_service_rp_circuits(service);
  742. }
  743. /* Move every ephemeral services from the src service map to the dst service
  744. * map. It is possible that a service can't be register to the dst map which
  745. * won't stop the process of moving them all but will trigger a log warn. */
  746. static void
  747. move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
  748. {
  749. hs_service_t **iter, **next;
  750. tor_assert(src);
  751. tor_assert(dst);
  752. /* Iterate over the map to find ephemeral service and move them to the other
  753. * map. We loop using this method to have a safe removal process. */
  754. for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
  755. hs_service_t *s = *iter;
  756. if (!s->config.is_ephemeral) {
  757. /* Yeah, we are in a very manual loop :). */
  758. next = HT_NEXT(hs_service_ht, src, iter);
  759. continue;
  760. }
  761. /* Remove service from map and then register to it to the other map.
  762. * Reminder that "*iter" and "s" are the same thing. */
  763. next = HT_NEXT_RMV(hs_service_ht, src, iter);
  764. if (register_service(dst, s) < 0) {
  765. log_warn(LD_BUG, "Ephemeral service key is already being used. "
  766. "Skipping.");
  767. }
  768. }
  769. }
  770. /* Return a const string of the directory path escaped. If this is an
  771. * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
  772. * the main thread because escaped() uses a static variable. */
  773. static const char *
  774. service_escaped_dir(const hs_service_t *s)
  775. {
  776. return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
  777. escaped(s->config.directory_path);
  778. }
  779. /** Move the hidden service state from <b>src</b> to <b>dst</b>. We do this
  780. * when we receive a SIGHUP: <b>dst</b> is the post-HUP service */
  781. static void
  782. move_hs_state(hs_service_t *src_service, hs_service_t *dst_service)
  783. {
  784. tor_assert(src_service);
  785. tor_assert(dst_service);
  786. hs_service_state_t *src = &src_service->state;
  787. hs_service_state_t *dst = &dst_service->state;
  788. /* Let's do a shallow copy */
  789. dst->intro_circ_retry_started_time = src->intro_circ_retry_started_time;
  790. dst->num_intro_circ_launched = src->num_intro_circ_launched;
  791. /* Freeing a NULL replaycache triggers an info LD_BUG. */
  792. if (dst->replay_cache_rend_cookie != NULL) {
  793. replaycache_free(dst->replay_cache_rend_cookie);
  794. }
  795. dst->replay_cache_rend_cookie = src->replay_cache_rend_cookie;
  796. dst->next_rotation_time = src->next_rotation_time;
  797. src->replay_cache_rend_cookie = NULL; /* steal pointer reference */
  798. }
  799. /* Register services that are in the staging list. Once this function returns,
  800. * the global service map will be set with the right content and all non
  801. * surviving services will be cleaned up. */
  802. static void
  803. register_all_services(void)
  804. {
  805. struct hs_service_ht *new_service_map;
  806. tor_assert(hs_service_staging_list);
  807. /* Allocate a new map that will replace the current one. */
  808. new_service_map = tor_malloc_zero(sizeof(*new_service_map));
  809. HT_INIT(hs_service_ht, new_service_map);
  810. /* First step is to transfer all ephemeral services from the current global
  811. * map to the new one we are constructing. We do not prune ephemeral
  812. * services as the only way to kill them is by deleting it from the control
  813. * port or stopping the tor daemon. */
  814. move_ephemeral_services(hs_service_map, new_service_map);
  815. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
  816. hs_service_t *s;
  817. /* Check if that service is already in our global map and if so, we'll
  818. * transfer the intro points to it. */
  819. s = find_service(hs_service_map, &snew->keys.identity_pk);
  820. if (s) {
  821. /* Pass ownership of the descriptors from s (the current service) to
  822. * snew (the newly configured one). */
  823. move_descriptors(s, snew);
  824. move_hs_state(s, snew);
  825. /* Remove the service from the global map because after this, we need to
  826. * go over the remaining service in that map that aren't surviving the
  827. * reload to close their circuits. */
  828. remove_service(hs_service_map, s);
  829. hs_service_free(s);
  830. }
  831. /* Great, this service is now ready to be added to our new map. */
  832. if (BUG(register_service(new_service_map, snew) < 0)) {
  833. /* This should never happen because prior to registration, we validate
  834. * every service against the entire set. Not being able to register a
  835. * service means we failed to validate correctly. In that case, don't
  836. * break tor and ignore the service but tell user. */
  837. log_warn(LD_BUG, "Unable to register service with directory %s",
  838. service_escaped_dir(snew));
  839. SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
  840. hs_service_free(snew);
  841. }
  842. } SMARTLIST_FOREACH_END(snew);
  843. /* Close any circuits associated with the non surviving services. Every
  844. * service in the current global map are roaming. */
  845. FOR_EACH_SERVICE_BEGIN(service) {
  846. close_service_circuits(service);
  847. } FOR_EACH_SERVICE_END;
  848. /* Time to make the switch. We'll clear the staging list because its content
  849. * has now changed ownership to the map. */
  850. smartlist_clear(hs_service_staging_list);
  851. service_free_all();
  852. hs_service_map = new_service_map;
  853. /* We've just register services into the new map and now we've replaced the
  854. * global map with it so we have to notify that the change happened. When
  855. * registering a service, the notify is only triggered if the destination
  856. * map is the global map for which in here it was not. */
  857. hs_service_map_has_changed();
  858. }
  859. /* Write the onion address of a given service to the given filename fname_ in
  860. * the service directory. Return 0 on success else -1 on error. */
  861. STATIC int
  862. write_address_to_file(const hs_service_t *service, const char *fname_)
  863. {
  864. int ret = -1;
  865. char *fname = NULL;
  866. char *addr_buf = NULL;
  867. tor_assert(service);
  868. tor_assert(fname_);
  869. /* Construct the full address with the onion tld and write the hostname file
  870. * to disk. */
  871. tor_asprintf(&addr_buf, "%s.%s\n", service->onion_address, address_tld);
  872. /* Notice here that we use the given "fname_". */
  873. fname = hs_path_from_filename(service->config.directory_path, fname_);
  874. if (write_str_to_file(fname, addr_buf, 0) < 0) {
  875. log_warn(LD_REND, "Could not write onion address to hostname file %s",
  876. escaped(fname));
  877. goto end;
  878. }
  879. #ifndef _WIN32
  880. if (service->config.dir_group_readable) {
  881. /* Mode to 0640. */
  882. if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
  883. log_warn(LD_FS, "Unable to make onion service hostname file %s "
  884. "group-readable.", escaped(fname));
  885. }
  886. }
  887. #endif /* !defined(_WIN32) */
  888. /* Success. */
  889. ret = 0;
  890. end:
  891. tor_free(fname);
  892. tor_free(addr_buf);
  893. return ret;
  894. }
  895. /* Load and/or generate private keys for the given service. On success, the
  896. * hostname file will be written to disk along with the master private key iff
  897. * the service is not configured for offline keys. Return 0 on success else -1
  898. * on failure. */
  899. static int
  900. load_service_keys(hs_service_t *service)
  901. {
  902. int ret = -1;
  903. char *fname = NULL;
  904. ed25519_keypair_t *kp;
  905. const hs_service_config_t *config;
  906. tor_assert(service);
  907. config = &service->config;
  908. /* Create and fix permission on service directory. We are about to write
  909. * files to that directory so make sure it exists and has the right
  910. * permissions. We do this here because at this stage we know that Tor is
  911. * actually running and the service we have has been validated. */
  912. if (hs_check_service_private_dir(get_options()->User,
  913. config->directory_path,
  914. config->dir_group_readable, 1) < 0) {
  915. goto end;
  916. }
  917. /* Try to load the keys from file or generate it if not found. */
  918. fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
  919. /* Don't ask for key creation, we want to know if we were able to load it or
  920. * we had to generate it. Better logging! */
  921. kp = ed_key_init_from_file(fname, INIT_ED_KEY_SPLIT, LOG_INFO, NULL, 0, 0,
  922. 0, NULL, NULL);
  923. if (!kp) {
  924. log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
  925. /* We'll now try to generate the keys and for it we want the strongest
  926. * randomness for it. The keypair will be written in different files. */
  927. uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
  928. INIT_ED_KEY_SPLIT;
  929. kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
  930. NULL, NULL);
  931. if (!kp) {
  932. log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
  933. goto end;
  934. }
  935. }
  936. /* Copy loaded or generated keys to service object. */
  937. ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
  938. memcpy(&service->keys.identity_sk, &kp->seckey,
  939. sizeof(service->keys.identity_sk));
  940. /* This does a proper memory wipe. */
  941. ed25519_keypair_free(kp);
  942. /* Build onion address from the newly loaded keys. */
  943. tor_assert(service->config.version <= UINT8_MAX);
  944. hs_build_address(&service->keys.identity_pk,
  945. (uint8_t) service->config.version,
  946. service->onion_address);
  947. /* Write onion address to hostname file. */
  948. if (write_address_to_file(service, fname_hostname) < 0) {
  949. goto end;
  950. }
  951. /* Load all client authorization keys in the service. */
  952. if (load_client_keys(service) < 0) {
  953. goto end;
  954. }
  955. /* Succes. */
  956. ret = 0;
  957. end:
  958. tor_free(fname);
  959. return ret;
  960. }
  961. /* Check if the client file name is valid or not. Return 1 if valid,
  962. * otherwise return 0. */
  963. STATIC int
  964. client_filename_is_valid(const char *filename)
  965. {
  966. int ret = 1;
  967. const char *valid_extension = ".auth";
  968. tor_assert(filename);
  969. /* The file extension must match and the total filename length can't be the
  970. * length of the extension else we do not have a filename. */
  971. if (!strcmpend(filename, valid_extension) &&
  972. strlen(filename) != strlen(valid_extension)) {
  973. ret = 1;
  974. } else {
  975. ret = 0;
  976. }
  977. return ret;
  978. }
  979. /* Parse an authorized client from a string. The format of a client string
  980. * looks like (see rend-spec-v3.txt):
  981. *
  982. * <auth-type>:<key-type>:<base32-encoded-public-key>
  983. *
  984. * The <auth-type> can only be "descriptor".
  985. * The <key-type> can only be "x25519".
  986. *
  987. * Return the key on success, return NULL, otherwise. */
  988. STATIC hs_service_authorized_client_t *
  989. parse_authorized_client(const char *client_key_str)
  990. {
  991. char *auth_type = NULL;
  992. char *key_type = NULL;
  993. char *pubkey_b32 = NULL;
  994. hs_service_authorized_client_t *client = NULL;
  995. smartlist_t *fields = smartlist_new();
  996. tor_assert(client_key_str);
  997. smartlist_split_string(fields, client_key_str, ":",
  998. SPLIT_SKIP_SPACE, 0);
  999. /* Wrong number of fields. */
  1000. if (smartlist_len(fields) != 3) {
  1001. log_warn(LD_REND, "Unknown format of client authorization file.");
  1002. goto err;
  1003. }
  1004. auth_type = smartlist_get(fields, 0);
  1005. key_type = smartlist_get(fields, 1);
  1006. pubkey_b32 = smartlist_get(fields, 2);
  1007. /* Currently, the only supported auth type is "descriptor". */
  1008. if (strcmp(auth_type, "descriptor")) {
  1009. log_warn(LD_REND, "Client authorization auth type '%s' not supported.",
  1010. auth_type);
  1011. goto err;
  1012. }
  1013. /* Currently, the only supported key type is "x25519". */
  1014. if (strcmp(key_type, "x25519")) {
  1015. log_warn(LD_REND, "Client authorization key type '%s' not supported.",
  1016. key_type);
  1017. goto err;
  1018. }
  1019. /* We expect a specific length of the base32 encoded key so make sure we
  1020. * have that so we don't successfully decode a value with a different length
  1021. * and end up in trouble when copying the decoded key into a fixed length
  1022. * buffer. */
  1023. if (strlen(pubkey_b32) != BASE32_NOPAD_LEN(CURVE25519_PUBKEY_LEN)) {
  1024. log_warn(LD_REND, "Client authorization encoded base32 public key "
  1025. "length is invalid: %s", pubkey_b32);
  1026. goto err;
  1027. }
  1028. client = tor_malloc_zero(sizeof(hs_service_authorized_client_t));
  1029. if (base32_decode((char *) client->client_pk.public_key,
  1030. sizeof(client->client_pk.public_key),
  1031. pubkey_b32, strlen(pubkey_b32)) < 0) {
  1032. log_warn(LD_REND, "Client authorization public key cannot be decoded: %s",
  1033. pubkey_b32);
  1034. goto err;
  1035. }
  1036. /* Success. */
  1037. goto done;
  1038. err:
  1039. service_authorized_client_free(client);
  1040. done:
  1041. /* It is also a good idea to wipe the public key. */
  1042. if (pubkey_b32) {
  1043. memwipe(pubkey_b32, 0, strlen(pubkey_b32));
  1044. }
  1045. tor_assert(fields);
  1046. SMARTLIST_FOREACH(fields, char *, s, tor_free(s));
  1047. smartlist_free(fields);
  1048. return client;
  1049. }
  1050. /* Load all the client public keys for the given service. Return 0 on
  1051. * success else -1 on failure. */
  1052. static int
  1053. load_client_keys(hs_service_t *service)
  1054. {
  1055. int ret = -1;
  1056. char *client_key_str = NULL;
  1057. char *client_key_file_path = NULL;
  1058. char *client_keys_dir_path = NULL;
  1059. hs_service_config_t *config;
  1060. smartlist_t *file_list = NULL;
  1061. tor_assert(service);
  1062. config = &service->config;
  1063. /* Before calling this function, we already call load_service_keys to make
  1064. * sure that the directory exists with the right permission. So, if we
  1065. * cannot create a client pubkey key directory, we consider it as a bug. */
  1066. client_keys_dir_path = hs_path_from_filename(config->directory_path,
  1067. dname_client_pubkeys);
  1068. if (BUG(hs_check_service_private_dir(get_options()->User,
  1069. client_keys_dir_path,
  1070. config->dir_group_readable, 1) < 0)) {
  1071. goto end;
  1072. }
  1073. /* If the list of clients already exists, we must clear it first. */
  1074. if (config->clients) {
  1075. SMARTLIST_FOREACH(config->clients, hs_service_authorized_client_t *, p,
  1076. service_authorized_client_free(p));
  1077. smartlist_free(config->clients);
  1078. }
  1079. config->clients = smartlist_new();
  1080. file_list = tor_listdir(client_keys_dir_path);
  1081. if (file_list == NULL) {
  1082. log_warn(LD_REND, "Client authorization directory %s can't be listed.",
  1083. client_keys_dir_path);
  1084. goto end;
  1085. }
  1086. SMARTLIST_FOREACH_BEGIN(file_list, const char *, filename) {
  1087. hs_service_authorized_client_t *client = NULL;
  1088. log_info(LD_REND, "Loading a client authorization key file %s...",
  1089. filename);
  1090. if (!client_filename_is_valid(filename)) {
  1091. log_warn(LD_REND, "Client authorization unrecognized filename %s. "
  1092. "File must end in .auth. Ignoring.", filename);
  1093. continue;
  1094. }
  1095. /* Create a full path for a file. */
  1096. client_key_file_path = hs_path_from_filename(client_keys_dir_path,
  1097. filename);
  1098. client_key_str = read_file_to_str(client_key_file_path, 0, NULL);
  1099. /* Free immediately after using it. */
  1100. tor_free(client_key_file_path);
  1101. /* If we cannot read the file, continue with the next file. */
  1102. if (!client_key_str) {
  1103. log_warn(LD_REND, "Client authorization file %s can't be read. "
  1104. "Corrupted or verify permission? Ignoring.",
  1105. client_key_file_path);
  1106. continue;
  1107. }
  1108. client = parse_authorized_client(client_key_str);
  1109. /* Wipe and free immediately after using it. */
  1110. memwipe(client_key_str, 0, strlen(client_key_str));
  1111. tor_free(client_key_str);
  1112. if (client) {
  1113. smartlist_add(config->clients, client);
  1114. log_info(LD_REND, "Loaded a client authorization key file %s.",
  1115. filename);
  1116. }
  1117. } SMARTLIST_FOREACH_END(filename);
  1118. /* If the number of clients is greater than zero, set the flag to be true. */
  1119. if (smartlist_len(config->clients) > 0) {
  1120. config->is_client_auth_enabled = 1;
  1121. }
  1122. /* Success. */
  1123. ret = 0;
  1124. end:
  1125. if (client_key_str) {
  1126. memwipe(client_key_str, 0, strlen(client_key_str));
  1127. }
  1128. if (file_list) {
  1129. SMARTLIST_FOREACH(file_list, char *, s, tor_free(s));
  1130. smartlist_free(file_list);
  1131. }
  1132. tor_free(client_key_str);
  1133. tor_free(client_key_file_path);
  1134. tor_free(client_keys_dir_path);
  1135. return ret;
  1136. }
  1137. STATIC void
  1138. service_authorized_client_free_(hs_service_authorized_client_t *client)
  1139. {
  1140. if (!client) {
  1141. return;
  1142. }
  1143. memwipe(&client->client_pk, 0, sizeof(client->client_pk));
  1144. tor_free(client);
  1145. }
  1146. /* Free a given service descriptor object and all key material is wiped. */
  1147. STATIC void
  1148. service_descriptor_free_(hs_service_descriptor_t *desc)
  1149. {
  1150. if (!desc) {
  1151. return;
  1152. }
  1153. hs_descriptor_free(desc->desc);
  1154. memwipe(&desc->signing_kp, 0, sizeof(desc->signing_kp));
  1155. memwipe(&desc->blinded_kp, 0, sizeof(desc->blinded_kp));
  1156. /* Cleanup all intro points. */
  1157. digest256map_free(desc->intro_points.map, service_intro_point_free_void);
  1158. digestmap_free(desc->intro_points.failed_id, tor_free_);
  1159. if (desc->previous_hsdirs) {
  1160. SMARTLIST_FOREACH(desc->previous_hsdirs, char *, s, tor_free(s));
  1161. smartlist_free(desc->previous_hsdirs);
  1162. }
  1163. crypto_ope_free(desc->ope_cipher);
  1164. tor_free(desc);
  1165. }
  1166. /* Return a newly allocated service descriptor object. */
  1167. STATIC hs_service_descriptor_t *
  1168. service_descriptor_new(void)
  1169. {
  1170. hs_service_descriptor_t *sdesc = tor_malloc_zero(sizeof(*sdesc));
  1171. sdesc->desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  1172. /* Initialize the intro points map. */
  1173. sdesc->intro_points.map = digest256map_new();
  1174. sdesc->intro_points.failed_id = digestmap_new();
  1175. sdesc->previous_hsdirs = smartlist_new();
  1176. return sdesc;
  1177. }
  1178. /* Allocate and return a deep copy of client. */
  1179. static hs_service_authorized_client_t *
  1180. service_authorized_client_dup(const hs_service_authorized_client_t *client)
  1181. {
  1182. hs_service_authorized_client_t *client_dup = NULL;
  1183. tor_assert(client);
  1184. client_dup = tor_malloc_zero(sizeof(hs_service_authorized_client_t));
  1185. /* Currently, the public key is the only component of
  1186. * hs_service_authorized_client_t. */
  1187. memcpy(client_dup->client_pk.public_key,
  1188. client->client_pk.public_key,
  1189. CURVE25519_PUBKEY_LEN);
  1190. return client_dup;
  1191. }
  1192. /* If two authorized clients are equal, return 0. If the first one should come
  1193. * before the second, return less than zero. If the first should come after
  1194. * the second, return greater than zero. */
  1195. static int
  1196. service_authorized_client_cmp(const hs_service_authorized_client_t *client1,
  1197. const hs_service_authorized_client_t *client2)
  1198. {
  1199. tor_assert(client1);
  1200. tor_assert(client2);
  1201. /* Currently, the public key is the only component of
  1202. * hs_service_authorized_client_t. */
  1203. return tor_memcmp(client1->client_pk.public_key,
  1204. client2->client_pk.public_key,
  1205. CURVE25519_PUBKEY_LEN);
  1206. }
  1207. /* Helper for sorting authorized clients. */
  1208. static int
  1209. compare_service_authorzized_client_(const void **_a, const void **_b)
  1210. {
  1211. const hs_service_authorized_client_t *a = *_a, *b = *_b;
  1212. return service_authorized_client_cmp(a, b);
  1213. }
  1214. /* If the list of hs_service_authorized_client_t's is different between
  1215. * src and dst, return 1. Otherwise, return 0. */
  1216. STATIC int
  1217. service_authorized_client_config_equal(const hs_service_config_t *config1,
  1218. const hs_service_config_t *config2)
  1219. {
  1220. int ret = 0;
  1221. int i;
  1222. smartlist_t *sl1 = smartlist_new();
  1223. smartlist_t *sl2 = smartlist_new();
  1224. tor_assert(config1);
  1225. tor_assert(config2);
  1226. tor_assert(config1->clients);
  1227. tor_assert(config2->clients);
  1228. /* If the number of clients is different, it is obvious that the list
  1229. * changes. */
  1230. if (smartlist_len(config1->clients) != smartlist_len(config2->clients)) {
  1231. goto done;
  1232. }
  1233. /* We do not want to mutate config1 and config2, so we will duplicate both
  1234. * entire client lists here. */
  1235. SMARTLIST_FOREACH(config1->clients,
  1236. hs_service_authorized_client_t *, client,
  1237. smartlist_add(sl1, service_authorized_client_dup(client)));
  1238. SMARTLIST_FOREACH(config2->clients,
  1239. hs_service_authorized_client_t *, client,
  1240. smartlist_add(sl2, service_authorized_client_dup(client)));
  1241. smartlist_sort(sl1, compare_service_authorzized_client_);
  1242. smartlist_sort(sl2, compare_service_authorzized_client_);
  1243. for (i = 0; i < smartlist_len(sl1); i++) {
  1244. /* If the clients at index i in both lists differ, the whole configs
  1245. * differ. */
  1246. if (service_authorized_client_cmp(smartlist_get(sl1, i),
  1247. smartlist_get(sl2, i))) {
  1248. goto done;
  1249. }
  1250. }
  1251. /* Success. */
  1252. ret = 1;
  1253. done:
  1254. if (sl1) {
  1255. SMARTLIST_FOREACH(sl1, hs_service_authorized_client_t *, p,
  1256. service_authorized_client_free(p));
  1257. smartlist_free(sl1);
  1258. }
  1259. if (sl2) {
  1260. SMARTLIST_FOREACH(sl2, hs_service_authorized_client_t *, p,
  1261. service_authorized_client_free(p));
  1262. smartlist_free(sl2);
  1263. }
  1264. return ret;
  1265. }
  1266. /* Move descriptor(s) from the src service to the dst service and modify their
  1267. * content if necessary. We do this during SIGHUP when we re-create our
  1268. * hidden services. */
  1269. static void
  1270. move_descriptors(hs_service_t *src, hs_service_t *dst)
  1271. {
  1272. tor_assert(src);
  1273. tor_assert(dst);
  1274. if (src->desc_current) {
  1275. /* Nothing should be there, but clean it up just in case */
  1276. if (BUG(dst->desc_current)) {
  1277. service_descriptor_free(dst->desc_current);
  1278. }
  1279. dst->desc_current = src->desc_current;
  1280. src->desc_current = NULL;
  1281. }
  1282. if (src->desc_next) {
  1283. /* Nothing should be there, but clean it up just in case */
  1284. if (BUG(dst->desc_next)) {
  1285. service_descriptor_free(dst->desc_next);
  1286. }
  1287. dst->desc_next = src->desc_next;
  1288. src->desc_next = NULL;
  1289. }
  1290. /* If the client authorization changes, we must rebuild the superencrypted
  1291. * section and republish the descriptors. */
  1292. int client_auth_changed =
  1293. !service_authorized_client_config_equal(&src->config, &dst->config);
  1294. if (client_auth_changed && dst->desc_current) {
  1295. /* We have to clear the superencrypted content first. */
  1296. hs_desc_superencrypted_data_free_contents(
  1297. &dst->desc_current->desc->superencrypted_data);
  1298. if (build_service_desc_superencrypted(dst, dst->desc_current) < 0) {
  1299. goto err;
  1300. }
  1301. service_desc_schedule_upload(dst->desc_current, time(NULL), 1);
  1302. }
  1303. if (client_auth_changed && dst->desc_next) {
  1304. /* We have to clear the superencrypted content first. */
  1305. hs_desc_superencrypted_data_free_contents(
  1306. &dst->desc_next->desc->superencrypted_data);
  1307. if (build_service_desc_superencrypted(dst, dst->desc_next) < 0) {
  1308. goto err;
  1309. }
  1310. service_desc_schedule_upload(dst->desc_next, time(NULL), 1);
  1311. }
  1312. return;
  1313. err:
  1314. /* If there is an error, free all descriptors to make it clean and generate
  1315. * them later. */
  1316. service_descriptor_free(dst->desc_current);
  1317. service_descriptor_free(dst->desc_next);
  1318. }
  1319. /* From the given service, remove all expired failing intro points for each
  1320. * descriptor. */
  1321. static void
  1322. remove_expired_failing_intro(hs_service_t *service, time_t now)
  1323. {
  1324. tor_assert(service);
  1325. /* For both descriptors, cleanup the failing intro points list. */
  1326. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1327. DIGESTMAP_FOREACH_MODIFY(desc->intro_points.failed_id, key, time_t *, t) {
  1328. time_t failure_time = *t;
  1329. if ((failure_time + INTRO_CIRC_RETRY_PERIOD) <= now) {
  1330. MAP_DEL_CURRENT(key);
  1331. tor_free(t);
  1332. }
  1333. } DIGESTMAP_FOREACH_END;
  1334. } FOR_EACH_DESCRIPTOR_END;
  1335. }
  1336. /* For the given descriptor desc, put all node_t object found from its failing
  1337. * intro point list and put them in the given node_list. */
  1338. static void
  1339. setup_intro_point_exclude_list(const hs_service_descriptor_t *desc,
  1340. smartlist_t *node_list)
  1341. {
  1342. tor_assert(desc);
  1343. tor_assert(node_list);
  1344. DIGESTMAP_FOREACH(desc->intro_points.failed_id, key, time_t *, t) {
  1345. (void) t; /* Make gcc happy. */
  1346. const node_t *node = node_get_by_id(key);
  1347. if (node) {
  1348. smartlist_add(node_list, (void *) node);
  1349. }
  1350. } DIGESTMAP_FOREACH_END;
  1351. }
  1352. /* For the given failing intro point ip, we add its time of failure to the
  1353. * failed map and index it by identity digest (legacy ID) in the descriptor
  1354. * desc failed id map. */
  1355. static void
  1356. remember_failing_intro_point(const hs_service_intro_point_t *ip,
  1357. hs_service_descriptor_t *desc, time_t now)
  1358. {
  1359. time_t *time_of_failure, *prev_ptr;
  1360. const hs_desc_link_specifier_t *legacy_ls;
  1361. tor_assert(ip);
  1362. tor_assert(desc);
  1363. time_of_failure = tor_malloc_zero(sizeof(time_t));
  1364. *time_of_failure = now;
  1365. legacy_ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  1366. tor_assert(legacy_ls);
  1367. prev_ptr = digestmap_set(desc->intro_points.failed_id,
  1368. (const char *) legacy_ls->u.legacy_id,
  1369. time_of_failure);
  1370. tor_free(prev_ptr);
  1371. }
  1372. /* Copy the descriptor link specifier object from src to dst. */
  1373. static void
  1374. link_specifier_copy(hs_desc_link_specifier_t *dst,
  1375. const hs_desc_link_specifier_t *src)
  1376. {
  1377. tor_assert(dst);
  1378. tor_assert(src);
  1379. memcpy(dst, src, sizeof(hs_desc_link_specifier_t));
  1380. }
  1381. /* Using a given descriptor signing keypair signing_kp, a service intro point
  1382. * object ip and the time now, setup the content of an already allocated
  1383. * descriptor intro desc_ip.
  1384. *
  1385. * Return 0 on success else a negative value. */
  1386. static int
  1387. setup_desc_intro_point(const ed25519_keypair_t *signing_kp,
  1388. const hs_service_intro_point_t *ip,
  1389. time_t now, hs_desc_intro_point_t *desc_ip)
  1390. {
  1391. int ret = -1;
  1392. time_t nearest_hour = now - (now % 3600);
  1393. tor_assert(signing_kp);
  1394. tor_assert(ip);
  1395. tor_assert(desc_ip);
  1396. /* Copy the onion key. */
  1397. memcpy(&desc_ip->onion_key, &ip->onion_key, sizeof(desc_ip->onion_key));
  1398. /* Key and certificate material. */
  1399. desc_ip->auth_key_cert = tor_cert_create(signing_kp,
  1400. CERT_TYPE_AUTH_HS_IP_KEY,
  1401. &ip->auth_key_kp.pubkey,
  1402. nearest_hour,
  1403. HS_DESC_CERT_LIFETIME,
  1404. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1405. if (desc_ip->auth_key_cert == NULL) {
  1406. log_warn(LD_REND, "Unable to create intro point auth-key certificate");
  1407. goto done;
  1408. }
  1409. /* Copy link specifier(s). */
  1410. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  1411. const hs_desc_link_specifier_t *, ls) {
  1412. hs_desc_link_specifier_t *copy = tor_malloc_zero(sizeof(*copy));
  1413. link_specifier_copy(copy, ls);
  1414. smartlist_add(desc_ip->link_specifiers, copy);
  1415. } SMARTLIST_FOREACH_END(ls);
  1416. /* For a legacy intro point, we'll use an RSA/ed cross certificate. */
  1417. if (ip->base.is_only_legacy) {
  1418. desc_ip->legacy.key = crypto_pk_dup_key(ip->legacy_key);
  1419. /* Create cross certification cert. */
  1420. ssize_t cert_len = tor_make_rsa_ed25519_crosscert(
  1421. &signing_kp->pubkey,
  1422. desc_ip->legacy.key,
  1423. nearest_hour + HS_DESC_CERT_LIFETIME,
  1424. &desc_ip->legacy.cert.encoded);
  1425. if (cert_len < 0) {
  1426. log_warn(LD_REND, "Unable to create enc key legacy cross cert.");
  1427. goto done;
  1428. }
  1429. desc_ip->legacy.cert.len = cert_len;
  1430. }
  1431. /* Encryption key and its cross certificate. */
  1432. {
  1433. ed25519_public_key_t ed25519_pubkey;
  1434. /* Use the public curve25519 key. */
  1435. memcpy(&desc_ip->enc_key, &ip->enc_key_kp.pubkey,
  1436. sizeof(desc_ip->enc_key));
  1437. /* The following can't fail. */
  1438. ed25519_public_key_from_curve25519_public_key(&ed25519_pubkey,
  1439. &ip->enc_key_kp.pubkey,
  1440. 0);
  1441. desc_ip->enc_key_cert = tor_cert_create(signing_kp,
  1442. CERT_TYPE_CROSS_HS_IP_KEYS,
  1443. &ed25519_pubkey, nearest_hour,
  1444. HS_DESC_CERT_LIFETIME,
  1445. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1446. if (desc_ip->enc_key_cert == NULL) {
  1447. log_warn(LD_REND, "Unable to create enc key curve25519 cross cert.");
  1448. goto done;
  1449. }
  1450. }
  1451. /* Success. */
  1452. ret = 0;
  1453. done:
  1454. return ret;
  1455. }
  1456. /* Using the given descriptor from the given service, build the descriptor
  1457. * intro point list so we can then encode the descriptor for publication. This
  1458. * function does not pick intro points, they have to be in the descriptor
  1459. * current map. Cryptographic material (keys) must be initialized in the
  1460. * descriptor for this function to make sense. */
  1461. static void
  1462. build_desc_intro_points(const hs_service_t *service,
  1463. hs_service_descriptor_t *desc, time_t now)
  1464. {
  1465. hs_desc_encrypted_data_t *encrypted;
  1466. tor_assert(service);
  1467. tor_assert(desc);
  1468. /* Ease our life. */
  1469. encrypted = &desc->desc->encrypted_data;
  1470. /* Cleanup intro points, we are about to set them from scratch. */
  1471. hs_descriptor_clear_intro_points(desc->desc);
  1472. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1473. const hs_service_intro_point_t *, ip) {
  1474. hs_desc_intro_point_t *desc_ip = hs_desc_intro_point_new();
  1475. if (setup_desc_intro_point(&desc->signing_kp, ip, now, desc_ip) < 0) {
  1476. hs_desc_intro_point_free(desc_ip);
  1477. continue;
  1478. }
  1479. /* We have a valid descriptor intro point. Add it to the list. */
  1480. smartlist_add(encrypted->intro_points, desc_ip);
  1481. } DIGEST256MAP_FOREACH_END;
  1482. }
  1483. /* Populate the descriptor encrypted section from the given service object.
  1484. * This will generate a valid list of introduction points that can be used
  1485. * after for circuit creation. Return 0 on success else -1 on error. */
  1486. static int
  1487. build_service_desc_encrypted(const hs_service_t *service,
  1488. hs_service_descriptor_t *desc)
  1489. {
  1490. hs_desc_encrypted_data_t *encrypted;
  1491. tor_assert(service);
  1492. tor_assert(desc);
  1493. encrypted = &desc->desc->encrypted_data;
  1494. encrypted->create2_ntor = 1;
  1495. encrypted->single_onion_service = service->config.is_single_onion;
  1496. /* Setup introduction points from what we have in the service. */
  1497. if (encrypted->intro_points == NULL) {
  1498. encrypted->intro_points = smartlist_new();
  1499. }
  1500. /* We do NOT build introduction point yet, we only do that once the circuit
  1501. * have been opened. Until we have the right number of introduction points,
  1502. * we do not encode anything in the descriptor. */
  1503. /* XXX: Support client authorization (#20700). */
  1504. encrypted->intro_auth_types = NULL;
  1505. return 0;
  1506. }
  1507. /* Populate the descriptor superencrypted section from the given service
  1508. * object. This will generate a valid list of hs_desc_authorized_client_t
  1509. * of clients that are authorized to use the service. Return 0 on success
  1510. * else -1 on error. */
  1511. static int
  1512. build_service_desc_superencrypted(const hs_service_t *service,
  1513. hs_service_descriptor_t *desc)
  1514. {
  1515. const hs_service_config_t *config;
  1516. int i;
  1517. hs_desc_superencrypted_data_t *superencrypted;
  1518. tor_assert(service);
  1519. tor_assert(desc);
  1520. superencrypted = &desc->desc->superencrypted_data;
  1521. config = &service->config;
  1522. /* The ephemeral key pair is already generated, so this should not give
  1523. * an error. */
  1524. if (BUG(!curve25519_public_key_is_ok(&desc->auth_ephemeral_kp.pubkey))) {
  1525. return -1;
  1526. }
  1527. memcpy(&superencrypted->auth_ephemeral_pubkey,
  1528. &desc->auth_ephemeral_kp.pubkey,
  1529. sizeof(curve25519_public_key_t));
  1530. /* Test that subcred is not zero because we might use it below */
  1531. if (BUG(tor_mem_is_zero((char*)desc->desc->subcredential, DIGEST256_LEN))) {
  1532. return -1;
  1533. }
  1534. /* Create a smartlist to store clients */
  1535. superencrypted->clients = smartlist_new();
  1536. /* We do not need to build the desc authorized client if the client
  1537. * authorization is disabled */
  1538. if (config->is_client_auth_enabled) {
  1539. SMARTLIST_FOREACH_BEGIN(config->clients,
  1540. hs_service_authorized_client_t *, client) {
  1541. hs_desc_authorized_client_t *desc_client;
  1542. desc_client = tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
  1543. /* Prepare the client for descriptor and then add to the list in the
  1544. * superencrypted part of the descriptor */
  1545. hs_desc_build_authorized_client(desc->desc->subcredential,
  1546. &client->client_pk,
  1547. &desc->auth_ephemeral_kp.seckey,
  1548. desc->descriptor_cookie, desc_client);
  1549. smartlist_add(superencrypted->clients, desc_client);
  1550. } SMARTLIST_FOREACH_END(client);
  1551. }
  1552. /* We cannot let the number of auth-clients to be zero, so we need to
  1553. * make it be 16. If it is already a multiple of 16, we do not need to
  1554. * do anything. Otherwise, add the additional ones to make it a
  1555. * multiple of 16. */
  1556. int num_clients = smartlist_len(superencrypted->clients);
  1557. int num_clients_to_add;
  1558. if (num_clients == 0) {
  1559. num_clients_to_add = HS_DESC_AUTH_CLIENT_MULTIPLE;
  1560. } else if (num_clients % HS_DESC_AUTH_CLIENT_MULTIPLE == 0) {
  1561. num_clients_to_add = 0;
  1562. } else {
  1563. num_clients_to_add =
  1564. HS_DESC_AUTH_CLIENT_MULTIPLE
  1565. - (num_clients % HS_DESC_AUTH_CLIENT_MULTIPLE);
  1566. }
  1567. for (i = 0; i < num_clients_to_add; i++) {
  1568. hs_desc_authorized_client_t *desc_client =
  1569. hs_desc_build_fake_authorized_client();
  1570. smartlist_add(superencrypted->clients, desc_client);
  1571. }
  1572. /* Shuffle the list to prevent the client know the position in the
  1573. * config. */
  1574. smartlist_shuffle(superencrypted->clients);
  1575. return 0;
  1576. }
  1577. /* Populate the descriptor plaintext section from the given service object.
  1578. * The caller must make sure that the keys in the descriptors are valid that
  1579. * is are non-zero. Return 0 on success else -1 on error. */
  1580. static int
  1581. build_service_desc_plaintext(const hs_service_t *service,
  1582. hs_service_descriptor_t *desc, time_t now)
  1583. {
  1584. int ret = -1;
  1585. hs_desc_plaintext_data_t *plaintext;
  1586. tor_assert(service);
  1587. tor_assert(desc);
  1588. /* XXX: Use a "assert_desc_ok()" ? */
  1589. tor_assert(!tor_mem_is_zero((char *) &desc->blinded_kp,
  1590. sizeof(desc->blinded_kp)));
  1591. tor_assert(!tor_mem_is_zero((char *) &desc->signing_kp,
  1592. sizeof(desc->signing_kp)));
  1593. /* Set the subcredential. */
  1594. hs_get_subcredential(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
  1595. desc->desc->subcredential);
  1596. plaintext = &desc->desc->plaintext_data;
  1597. plaintext->version = service->config.version;
  1598. plaintext->lifetime_sec = HS_DESC_DEFAULT_LIFETIME;
  1599. plaintext->signing_key_cert =
  1600. tor_cert_create(&desc->blinded_kp, CERT_TYPE_SIGNING_HS_DESC,
  1601. &desc->signing_kp.pubkey, now, HS_DESC_CERT_LIFETIME,
  1602. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1603. if (plaintext->signing_key_cert == NULL) {
  1604. log_warn(LD_REND, "Unable to create descriptor signing certificate for "
  1605. "service %s",
  1606. safe_str_client(service->onion_address));
  1607. goto end;
  1608. }
  1609. /* Copy public key material to go in the descriptor. */
  1610. ed25519_pubkey_copy(&plaintext->signing_pubkey, &desc->signing_kp.pubkey);
  1611. ed25519_pubkey_copy(&plaintext->blinded_pubkey, &desc->blinded_kp.pubkey);
  1612. /* Success. */
  1613. ret = 0;
  1614. end:
  1615. return ret;
  1616. }
  1617. /** Compute the descriptor's OPE cipher for encrypting revision counters. */
  1618. static crypto_ope_t *
  1619. generate_ope_cipher_for_desc(const hs_service_descriptor_t *hs_desc)
  1620. {
  1621. /* Compute OPE key as H("rev-counter-generation" | blinded privkey) */
  1622. uint8_t key[DIGEST256_LEN];
  1623. crypto_digest_t *digest = crypto_digest256_new(DIGEST_SHA3_256);
  1624. const char ope_key_prefix[] = "rev-counter-generation";
  1625. const ed25519_secret_key_t *eph_privkey = &hs_desc->blinded_kp.seckey;
  1626. crypto_digest_add_bytes(digest, ope_key_prefix, sizeof(ope_key_prefix));
  1627. crypto_digest_add_bytes(digest, (char*)eph_privkey->seckey,
  1628. sizeof(eph_privkey->seckey));
  1629. crypto_digest_get_digest(digest, (char *)key, sizeof(key));
  1630. crypto_digest_free(digest);
  1631. return crypto_ope_new(key);
  1632. }
  1633. /* For the given service and descriptor object, create the key material which
  1634. * is the blinded keypair, the descriptor signing keypair, the ephemeral
  1635. * keypair, and the descriptor cookie. Return 0 on success else -1 on error
  1636. * where the generated keys MUST be ignored. */
  1637. static int
  1638. build_service_desc_keys(const hs_service_t *service,
  1639. hs_service_descriptor_t *desc)
  1640. {
  1641. int ret = -1;
  1642. ed25519_keypair_t kp;
  1643. tor_assert(desc);
  1644. tor_assert(!tor_mem_is_zero((char *) &service->keys.identity_pk,
  1645. ED25519_PUBKEY_LEN));
  1646. /* XXX: Support offline key feature (#18098). */
  1647. /* Copy the identity keys to the keypair so we can use it to create the
  1648. * blinded key. */
  1649. memcpy(&kp.pubkey, &service->keys.identity_pk, sizeof(kp.pubkey));
  1650. memcpy(&kp.seckey, &service->keys.identity_sk, sizeof(kp.seckey));
  1651. /* Build blinded keypair for this time period. */
  1652. hs_build_blinded_keypair(&kp, NULL, 0, desc->time_period_num,
  1653. &desc->blinded_kp);
  1654. /* Let's not keep too much traces of our keys in memory. */
  1655. memwipe(&kp, 0, sizeof(kp));
  1656. /* Compute the OPE cipher struct (it's tied to the current blinded key) */
  1657. log_info(LD_GENERAL,
  1658. "Getting OPE for TP#%u", (unsigned) desc->time_period_num);
  1659. tor_assert_nonfatal(!desc->ope_cipher);
  1660. desc->ope_cipher = generate_ope_cipher_for_desc(desc);
  1661. /* No need for extra strong, this is a temporary key only for this
  1662. * descriptor. Nothing long term. */
  1663. if (ed25519_keypair_generate(&desc->signing_kp, 0) < 0) {
  1664. log_warn(LD_REND, "Can't generate descriptor signing keypair for "
  1665. "service %s",
  1666. safe_str_client(service->onion_address));
  1667. goto end;
  1668. }
  1669. /* No need for extra strong, this is a temporary key only for this
  1670. * descriptor. Nothing long term. */
  1671. if (curve25519_keypair_generate(&desc->auth_ephemeral_kp, 0) < 0) {
  1672. log_warn(LD_REND, "Can't generate auth ephemeral keypair for "
  1673. "service %s",
  1674. safe_str_client(service->onion_address));
  1675. goto end;
  1676. }
  1677. /* Random descriptor cookie to be used as a part of a key to encrypt the
  1678. * descriptor, only if the client auth is enabled will it be used. */
  1679. crypto_strongest_rand(desc->descriptor_cookie,
  1680. sizeof(desc->descriptor_cookie));
  1681. /* Success. */
  1682. ret = 0;
  1683. end:
  1684. return ret;
  1685. }
  1686. /* Given a service and the current time, build a descriptor for the service.
  1687. * This function does not pick introduction point, this needs to be done by
  1688. * the update function. On success, desc_out will point to the newly allocated
  1689. * descriptor object.
  1690. *
  1691. * This can error if we are unable to create keys or certificate. */
  1692. static void
  1693. build_service_descriptor(hs_service_t *service, time_t now,
  1694. uint64_t time_period_num,
  1695. hs_service_descriptor_t **desc_out)
  1696. {
  1697. char *encoded_desc;
  1698. hs_service_descriptor_t *desc;
  1699. tor_assert(service);
  1700. tor_assert(desc_out);
  1701. desc = service_descriptor_new();
  1702. /* Set current time period */
  1703. desc->time_period_num = time_period_num;
  1704. /* Create the needed keys so we can setup the descriptor content. */
  1705. if (build_service_desc_keys(service, desc) < 0) {
  1706. goto err;
  1707. }
  1708. /* Setup plaintext descriptor content. */
  1709. if (build_service_desc_plaintext(service, desc, now) < 0) {
  1710. goto err;
  1711. }
  1712. /* Setup superencrypted descriptor content. */
  1713. if (build_service_desc_superencrypted(service, desc) < 0) {
  1714. goto err;
  1715. }
  1716. /* Setup encrypted descriptor content. */
  1717. if (build_service_desc_encrypted(service, desc) < 0) {
  1718. goto err;
  1719. }
  1720. /* Let's make sure that we've created a descriptor that can actually be
  1721. * encoded properly. This function also checks if the encoded output is
  1722. * decodable after. */
  1723. if (BUG(service_encode_descriptor(service, desc, &desc->signing_kp,
  1724. &encoded_desc) < 0)) {
  1725. goto err;
  1726. }
  1727. tor_free(encoded_desc);
  1728. /* Assign newly built descriptor to the next slot. */
  1729. *desc_out = desc;
  1730. /* Fire a CREATED control port event. */
  1731. hs_control_desc_event_created(service->onion_address,
  1732. &desc->blinded_kp.pubkey);
  1733. return;
  1734. err:
  1735. service_descriptor_free(desc);
  1736. }
  1737. /* Build both descriptors for the given service that has just booted up.
  1738. * Because it's a special case, it deserves its special function ;). */
  1739. static void
  1740. build_descriptors_for_new_service(hs_service_t *service, time_t now)
  1741. {
  1742. uint64_t current_desc_tp, next_desc_tp;
  1743. tor_assert(service);
  1744. /* These are the conditions for a new service. */
  1745. tor_assert(!service->desc_current);
  1746. tor_assert(!service->desc_next);
  1747. /*
  1748. * +------------------------------------------------------------------+
  1749. * | |
  1750. * | 00:00 12:00 00:00 12:00 00:00 12:00 |
  1751. * | SRV#1 TP#1 SRV#2 TP#2 SRV#3 TP#3 |
  1752. * | |
  1753. * | $==========|-----------$===========|-----------$===========| |
  1754. * | ^ ^ |
  1755. * | A B |
  1756. * +------------------------------------------------------------------+
  1757. *
  1758. * Case A: The service boots up before a new time period, the current time
  1759. * period is thus TP#1 and the next is TP#2 which for both we have access to
  1760. * their SRVs.
  1761. *
  1762. * Case B: The service boots up inside TP#2, we can't use the TP#3 for the
  1763. * next descriptor because we don't have the SRV#3 so the current should be
  1764. * TP#1 and next TP#2.
  1765. */
  1766. if (hs_in_period_between_tp_and_srv(NULL, now)) {
  1767. /* Case B from the above, inside of the new time period. */
  1768. current_desc_tp = hs_get_previous_time_period_num(0); /* TP#1 */
  1769. next_desc_tp = hs_get_time_period_num(0); /* TP#2 */
  1770. } else {
  1771. /* Case A from the above, outside of the new time period. */
  1772. current_desc_tp = hs_get_time_period_num(0); /* TP#1 */
  1773. next_desc_tp = hs_get_next_time_period_num(0); /* TP#2 */
  1774. }
  1775. /* Build descriptors. */
  1776. build_service_descriptor(service, now, current_desc_tp,
  1777. &service->desc_current);
  1778. build_service_descriptor(service, now, next_desc_tp,
  1779. &service->desc_next);
  1780. log_info(LD_REND, "Hidden service %s has just started. Both descriptors "
  1781. "built. Now scheduled for upload.",
  1782. safe_str_client(service->onion_address));
  1783. }
  1784. /* Build descriptors for each service if needed. There are conditions to build
  1785. * a descriptor which are details in the function. */
  1786. STATIC void
  1787. build_all_descriptors(time_t now)
  1788. {
  1789. FOR_EACH_SERVICE_BEGIN(service) {
  1790. /* A service booting up will have both descriptors to NULL. No other cases
  1791. * makes both descriptor non existent. */
  1792. if (service->desc_current == NULL && service->desc_next == NULL) {
  1793. build_descriptors_for_new_service(service, now);
  1794. continue;
  1795. }
  1796. /* Reaching this point means we are pass bootup so at runtime. We should
  1797. * *never* have an empty current descriptor. If the next descriptor is
  1798. * empty, we'll try to build it for the next time period. This only
  1799. * happens when we rotate meaning that we are guaranteed to have a new SRV
  1800. * at that point for the next time period. */
  1801. if (BUG(service->desc_current == NULL)) {
  1802. continue;
  1803. }
  1804. if (service->desc_next == NULL) {
  1805. build_service_descriptor(service, now, hs_get_next_time_period_num(0),
  1806. &service->desc_next);
  1807. log_info(LD_REND, "Hidden service %s next descriptor successfully "
  1808. "built. Now scheduled for upload.",
  1809. safe_str_client(service->onion_address));
  1810. }
  1811. } FOR_EACH_DESCRIPTOR_END;
  1812. }
  1813. /* Randomly pick a node to become an introduction point but not present in the
  1814. * given exclude_nodes list. The chosen node is put in the exclude list
  1815. * regardless of success or not because in case of failure, the node is simply
  1816. * unsusable from that point on.
  1817. *
  1818. * If direct_conn is set, try to pick a node that our local firewall/policy
  1819. * allows us to connect to directly. If we can't find any, return NULL.
  1820. * This function supports selecting dual-stack nodes for direct single onion
  1821. * service IPv6 connections. But it does not send IPv6 addresses in link
  1822. * specifiers. (Current clients don't use IPv6 addresses to extend, and
  1823. * direct client connections to intro points are not supported.)
  1824. *
  1825. * Return a newly allocated service intro point ready to be used for encoding.
  1826. * Return NULL on error. */
  1827. static hs_service_intro_point_t *
  1828. pick_intro_point(unsigned int direct_conn, smartlist_t *exclude_nodes)
  1829. {
  1830. const node_t *node;
  1831. extend_info_t *info = NULL;
  1832. hs_service_intro_point_t *ip = NULL;
  1833. /* Normal 3-hop introduction point flags. */
  1834. router_crn_flags_t flags = CRN_NEED_UPTIME | CRN_NEED_DESC;
  1835. /* Single onion flags. */
  1836. router_crn_flags_t direct_flags = flags | CRN_PREF_ADDR | CRN_DIRECT_CONN;
  1837. node = router_choose_random_node(exclude_nodes, get_options()->ExcludeNodes,
  1838. direct_conn ? direct_flags : flags);
  1839. /* Unable to find a node. When looking for a node for a direct connection,
  1840. * we could try a 3-hop path instead. We'll add support for this in a later
  1841. * release. */
  1842. if (!node) {
  1843. goto err;
  1844. }
  1845. /* We have a suitable node, add it to the exclude list. We do this *before*
  1846. * we can validate the extend information because even in case of failure,
  1847. * we don't want to use that node anymore. */
  1848. smartlist_add(exclude_nodes, (void *) node);
  1849. /* We do this to ease our life but also this call makes appropriate checks
  1850. * of the node object such as validating ntor support for instance.
  1851. *
  1852. * We must provide an extend_info for clients to connect over a 3-hop path,
  1853. * so we don't pass direct_conn here. */
  1854. info = extend_info_from_node(node, 0);
  1855. if (BUG(info == NULL)) {
  1856. goto err;
  1857. }
  1858. /* Let's do a basic sanity check here so that we don't end up advertising the
  1859. * ed25519 identity key of relays that don't actually support the link
  1860. * protocol */
  1861. if (!node_supports_ed25519_link_authentication(node, 0)) {
  1862. tor_assert_nonfatal(ed25519_public_key_is_zero(&info->ed_identity));
  1863. } else {
  1864. /* Make sure we *do* have an ed key if we support the link authentication.
  1865. * Sending an empty key would result in a failure to extend. */
  1866. tor_assert_nonfatal(!ed25519_public_key_is_zero(&info->ed_identity));
  1867. }
  1868. /* Create our objects and populate them with the node information.
  1869. * We don't care if the intro's link auth is compatible with us, because
  1870. * we are sending the ed25519 key to a remote client via the descriptor. */
  1871. ip = service_intro_point_new(info, !node_supports_ed25519_hs_intro(node),
  1872. node_supports_ed25519_link_authentication(node,
  1873. 0));
  1874. if (ip == NULL) {
  1875. goto err;
  1876. }
  1877. log_info(LD_REND, "Picked intro point: %s", extend_info_describe(info));
  1878. extend_info_free(info);
  1879. return ip;
  1880. err:
  1881. service_intro_point_free(ip);
  1882. extend_info_free(info);
  1883. return NULL;
  1884. }
  1885. /* For a given descriptor from the given service, pick any needed intro points
  1886. * and update the current map with those newly picked intro points. Return the
  1887. * number node that might have been added to the descriptor current map. */
  1888. static unsigned int
  1889. pick_needed_intro_points(hs_service_t *service,
  1890. hs_service_descriptor_t *desc)
  1891. {
  1892. int i = 0, num_needed_ip;
  1893. smartlist_t *exclude_nodes = smartlist_new();
  1894. tor_assert(service);
  1895. tor_assert(desc);
  1896. /* Compute how many intro points we actually need to open. */
  1897. num_needed_ip = service->config.num_intro_points -
  1898. digest256map_size(desc->intro_points.map);
  1899. if (BUG(num_needed_ip < 0)) {
  1900. /* Let's not make tor freak out here and just skip this. */
  1901. goto done;
  1902. }
  1903. /* We want to end up with config.num_intro_points intro points, but if we
  1904. * have no intro points at all (chances are they all cycled or we are
  1905. * starting up), we launch get_intro_point_num_extra() extra circuits and
  1906. * use the first config.num_intro_points that complete. See proposal #155,
  1907. * section 4 for the rationale of this which is purely for performance.
  1908. *
  1909. * The ones after the first config.num_intro_points will be converted to
  1910. * 'General' internal circuits and then we'll drop them from the list of
  1911. * intro points. */
  1912. if (digest256map_size(desc->intro_points.map) == 0) {
  1913. num_needed_ip += get_intro_point_num_extra();
  1914. }
  1915. /* Build an exclude list of nodes of our intro point(s). The expiring intro
  1916. * points are OK to pick again because this is afterall a concept of round
  1917. * robin so they are considered valid nodes to pick again. */
  1918. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1919. hs_service_intro_point_t *, ip) {
  1920. const node_t *intro_node = get_node_from_intro_point(ip);
  1921. if (intro_node) {
  1922. smartlist_add(exclude_nodes, (void*)intro_node);
  1923. }
  1924. } DIGEST256MAP_FOREACH_END;
  1925. /* Also, add the failing intro points that our descriptor encounteered in
  1926. * the exclude node list. */
  1927. setup_intro_point_exclude_list(desc, exclude_nodes);
  1928. for (i = 0; i < num_needed_ip; i++) {
  1929. hs_service_intro_point_t *ip;
  1930. /* This function will add the picked intro point node to the exclude nodes
  1931. * list so we don't pick the same one at the next iteration. */
  1932. ip = pick_intro_point(service->config.is_single_onion, exclude_nodes);
  1933. if (ip == NULL) {
  1934. /* If we end up unable to pick an introduction point it is because we
  1935. * can't find suitable node and calling this again is highly unlikely to
  1936. * give us a valid node all of the sudden. */
  1937. log_info(LD_REND, "Unable to find a suitable node to be an "
  1938. "introduction point for service %s.",
  1939. safe_str_client(service->onion_address));
  1940. goto done;
  1941. }
  1942. /* Valid intro point object, add it to the descriptor current map. */
  1943. service_intro_point_add(desc->intro_points.map, ip);
  1944. }
  1945. /* We've successfully picked all our needed intro points thus none are
  1946. * missing which will tell our upload process to expect the number of
  1947. * circuits to be the number of configured intro points circuits and not the
  1948. * number of intro points object that we have. */
  1949. desc->missing_intro_points = 0;
  1950. /* Success. */
  1951. done:
  1952. /* We don't have ownership of the node_t object in this list. */
  1953. smartlist_free(exclude_nodes);
  1954. return i;
  1955. }
  1956. /** Clear previous cached HSDirs in <b>desc</b>. */
  1957. static void
  1958. service_desc_clear_previous_hsdirs(hs_service_descriptor_t *desc)
  1959. {
  1960. if (BUG(!desc->previous_hsdirs)) {
  1961. return;
  1962. }
  1963. SMARTLIST_FOREACH(desc->previous_hsdirs, char*, s, tor_free(s));
  1964. smartlist_clear(desc->previous_hsdirs);
  1965. }
  1966. /** Note that we attempted to upload <b>desc</b> to <b>hsdir</b>. */
  1967. static void
  1968. service_desc_note_upload(hs_service_descriptor_t *desc, const node_t *hsdir)
  1969. {
  1970. char b64_digest[BASE64_DIGEST_LEN+1] = {0};
  1971. digest_to_base64(b64_digest, hsdir->identity);
  1972. if (BUG(!desc->previous_hsdirs)) {
  1973. return;
  1974. }
  1975. if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
  1976. smartlist_add_strdup(desc->previous_hsdirs, b64_digest);
  1977. }
  1978. }
  1979. /** Schedule an upload of <b>desc</b>. If <b>descriptor_changed</b> is set, it
  1980. * means that this descriptor is dirty. */
  1981. STATIC void
  1982. service_desc_schedule_upload(hs_service_descriptor_t *desc,
  1983. time_t now,
  1984. int descriptor_changed)
  1985. {
  1986. desc->next_upload_time = now;
  1987. /* If the descriptor changed, clean up the old HSDirs list. We want to
  1988. * re-upload no matter what. */
  1989. if (descriptor_changed) {
  1990. service_desc_clear_previous_hsdirs(desc);
  1991. }
  1992. }
  1993. /* Update the given descriptor from the given service. The possible update
  1994. * actions includes:
  1995. * - Picking missing intro points if needed.
  1996. */
  1997. static void
  1998. update_service_descriptor(hs_service_t *service,
  1999. hs_service_descriptor_t *desc, time_t now)
  2000. {
  2001. unsigned int num_intro_points;
  2002. tor_assert(service);
  2003. tor_assert(desc);
  2004. tor_assert(desc->desc);
  2005. num_intro_points = digest256map_size(desc->intro_points.map);
  2006. /* Pick any missing introduction point(s). */
  2007. if (num_intro_points < service->config.num_intro_points) {
  2008. unsigned int num_new_intro_points = pick_needed_intro_points(service,
  2009. desc);
  2010. if (num_new_intro_points != 0) {
  2011. log_info(LD_REND, "Service %s just picked %u intro points and wanted "
  2012. "%u for %s descriptor. It currently has %d intro "
  2013. "points. Launching ESTABLISH_INTRO circuit shortly.",
  2014. safe_str_client(service->onion_address),
  2015. num_new_intro_points,
  2016. service->config.num_intro_points - num_intro_points,
  2017. (desc == service->desc_current) ? "current" : "next",
  2018. num_intro_points);
  2019. /* We'll build those introduction point into the descriptor once we have
  2020. * confirmation that the circuits are opened and ready. However,
  2021. * indicate that this descriptor should be uploaded from now on. */
  2022. service_desc_schedule_upload(desc, now, 1);
  2023. }
  2024. /* Were we able to pick all the intro points we needed? If not, we'll
  2025. * flag the descriptor that it's missing intro points because it
  2026. * couldn't pick enough which will trigger a descriptor upload. */
  2027. if ((num_new_intro_points + num_intro_points) <
  2028. service->config.num_intro_points) {
  2029. desc->missing_intro_points = 1;
  2030. }
  2031. }
  2032. }
  2033. /* Update descriptors for each service if needed. */
  2034. STATIC void
  2035. update_all_descriptors(time_t now)
  2036. {
  2037. FOR_EACH_SERVICE_BEGIN(service) {
  2038. /* We'll try to update each descriptor that is if certain conditions apply
  2039. * in order for the descriptor to be updated. */
  2040. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2041. update_service_descriptor(service, desc, now);
  2042. } FOR_EACH_DESCRIPTOR_END;
  2043. } FOR_EACH_SERVICE_END;
  2044. }
  2045. /* Return true iff the given intro point has expired that is it has been used
  2046. * for too long or we've reached our max seen INTRODUCE2 cell. */
  2047. STATIC int
  2048. intro_point_should_expire(const hs_service_intro_point_t *ip,
  2049. time_t now)
  2050. {
  2051. tor_assert(ip);
  2052. if (ip->introduce2_count >= ip->introduce2_max) {
  2053. goto expired;
  2054. }
  2055. if (ip->time_to_expire <= now) {
  2056. goto expired;
  2057. }
  2058. /* Not expiring. */
  2059. return 0;
  2060. expired:
  2061. return 1;
  2062. }
  2063. /* Go over the given set of intro points for each service and remove any
  2064. * invalid ones. The conditions for removal are:
  2065. *
  2066. * - The node doesn't exists anymore (not in consensus)
  2067. * OR
  2068. * - The intro point maximum circuit retry count has been reached and no
  2069. * circuit can be found associated with it.
  2070. * OR
  2071. * - The intro point has expired and we should pick a new one.
  2072. *
  2073. * If an intro point is removed, the circuit (if any) is immediately close.
  2074. * If a circuit can't be found, the intro point is kept if it hasn't reached
  2075. * its maximum circuit retry value and thus should be retried. */
  2076. static void
  2077. cleanup_intro_points(hs_service_t *service, time_t now)
  2078. {
  2079. /* List of intro points to close. We can't mark the intro circuits for close
  2080. * in the modify loop because doing so calls
  2081. * hs_service_intro_circ_has_closed() which does a digest256map_get() on the
  2082. * intro points map (that we are iterating over). This can't be done in a
  2083. * single iteration after a MAP_DEL_CURRENT, the object will still be
  2084. * returned leading to a use-after-free. So, we close the circuits and free
  2085. * the intro points after the loop if any. */
  2086. smartlist_t *ips_to_free = smartlist_new();
  2087. tor_assert(service);
  2088. /* For both descriptors, cleanup the intro points. */
  2089. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2090. /* Go over the current intro points we have, make sure they are still
  2091. * valid and remove any of them that aren't. */
  2092. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  2093. hs_service_intro_point_t *, ip) {
  2094. const node_t *node = get_node_from_intro_point(ip);
  2095. int has_expired = intro_point_should_expire(ip, now);
  2096. /* We cleanup an intro point if it has expired or if we do not know the
  2097. * node_t anymore (removed from our latest consensus) or if we've
  2098. * reached the maximum number of retry with a non existing circuit. */
  2099. if (has_expired || node == NULL ||
  2100. ip->circuit_retries > MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  2101. log_info(LD_REND, "Intro point %s%s (retried: %u times). "
  2102. "Removing it.",
  2103. describe_intro_point(ip),
  2104. has_expired ? " has expired" :
  2105. (node == NULL) ? " fell off the consensus" : "",
  2106. ip->circuit_retries);
  2107. /* We've retried too many times, remember it as a failed intro point
  2108. * so we don't pick it up again for INTRO_CIRC_RETRY_PERIOD sec. */
  2109. if (ip->circuit_retries > MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  2110. remember_failing_intro_point(ip, desc, approx_time());
  2111. }
  2112. /* Remove intro point from descriptor map and add it to the list of
  2113. * ips to free for which we'll also try to close the intro circuit. */
  2114. MAP_DEL_CURRENT(key);
  2115. smartlist_add(ips_to_free, ip);
  2116. }
  2117. } DIGEST256MAP_FOREACH_END;
  2118. } FOR_EACH_DESCRIPTOR_END;
  2119. /* Go over the intro points to free and close their circuit if any. */
  2120. SMARTLIST_FOREACH_BEGIN(ips_to_free, hs_service_intro_point_t *, ip) {
  2121. /* See if we need to close the intro point circuit as well */
  2122. /* XXX: Legacy code does NOT close circuits like this: it keeps the circuit
  2123. * open until a new descriptor is uploaded and then closed all expiring
  2124. * intro point circuit. Here, we close immediately and because we just
  2125. * discarded the intro point, a new one will be selected, a new descriptor
  2126. * created and uploaded. There is no difference to an attacker between the
  2127. * timing of a new consensus and intro point rotation (possibly?). */
  2128. origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
  2129. if (ocirc && !TO_CIRCUIT(ocirc)->marked_for_close) {
  2130. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  2131. }
  2132. /* Cleanup the intro point */
  2133. service_intro_point_free(ip);
  2134. } SMARTLIST_FOREACH_END(ip);
  2135. smartlist_free(ips_to_free);
  2136. }
  2137. /* Set the next rotation time of the descriptors for the given service for the
  2138. * time now. */
  2139. static void
  2140. set_rotation_time(hs_service_t *service)
  2141. {
  2142. tor_assert(service);
  2143. service->state.next_rotation_time =
  2144. sr_state_get_start_time_of_current_protocol_run() +
  2145. sr_state_get_protocol_run_duration();
  2146. {
  2147. char fmt_time[ISO_TIME_LEN + 1];
  2148. format_local_iso_time(fmt_time, service->state.next_rotation_time);
  2149. log_info(LD_REND, "Next descriptor rotation time set to %s for %s",
  2150. fmt_time, safe_str_client(service->onion_address));
  2151. }
  2152. }
  2153. /* Return true iff the service should rotate its descriptor. The time now is
  2154. * only used to fetch the live consensus and if none can be found, this
  2155. * returns false. */
  2156. static unsigned int
  2157. should_rotate_descriptors(hs_service_t *service, time_t now)
  2158. {
  2159. const networkstatus_t *ns;
  2160. tor_assert(service);
  2161. ns = networkstatus_get_live_consensus(now);
  2162. if (ns == NULL) {
  2163. goto no_rotation;
  2164. }
  2165. if (ns->valid_after >= service->state.next_rotation_time) {
  2166. /* In theory, we should never get here with no descriptors. We can never
  2167. * have a NULL current descriptor except when tor starts up. The next
  2168. * descriptor can be NULL after a rotation but we build a new one right
  2169. * after.
  2170. *
  2171. * So, when tor starts, the next rotation time is set to the start of the
  2172. * next SRV period using the consensus valid after time so it should
  2173. * always be set to a future time value. This means that we should never
  2174. * reach this point at bootup that is this check safeguards tor in never
  2175. * allowing a rotation if the valid after time is smaller than the next
  2176. * rotation time.
  2177. *
  2178. * This is all good in theory but we've had a NULL descriptor issue here
  2179. * so this is why we BUG() on both with extra logging to try to understand
  2180. * how this can possibly happens. We'll simply ignore and tor should
  2181. * recover from this by skipping rotation and building the missing
  2182. * descriptors just after this. */
  2183. if (BUG(service->desc_current == NULL || service->desc_next == NULL)) {
  2184. log_warn(LD_BUG, "Service descriptor is NULL (%p/%p). Next rotation "
  2185. "time is %ld (now: %ld). Valid after time from "
  2186. "consensus is %ld",
  2187. service->desc_current, service->desc_next,
  2188. (long)service->state.next_rotation_time,
  2189. (long)now,
  2190. (long)ns->valid_after);
  2191. goto no_rotation;
  2192. }
  2193. goto rotation;
  2194. }
  2195. no_rotation:
  2196. return 0;
  2197. rotation:
  2198. return 1;
  2199. }
  2200. /* Rotate the service descriptors of the given service. The current descriptor
  2201. * will be freed, the next one put in as the current and finally the next
  2202. * descriptor pointer is NULLified. */
  2203. static void
  2204. rotate_service_descriptors(hs_service_t *service)
  2205. {
  2206. if (service->desc_current) {
  2207. /* Close all IP circuits for the descriptor. */
  2208. close_intro_circuits(&service->desc_current->intro_points);
  2209. /* We don't need this one anymore, we won't serve any clients coming with
  2210. * this service descriptor. */
  2211. service_descriptor_free(service->desc_current);
  2212. }
  2213. /* The next one become the current one and emptying the next will trigger
  2214. * a descriptor creation for it. */
  2215. service->desc_current = service->desc_next;
  2216. service->desc_next = NULL;
  2217. /* We've just rotated, set the next time for the rotation. */
  2218. set_rotation_time(service);
  2219. }
  2220. /* Rotate descriptors for each service if needed. A non existing current
  2221. * descriptor will trigger a descriptor build for the next time period. */
  2222. STATIC void
  2223. rotate_all_descriptors(time_t now)
  2224. {
  2225. /* XXX We rotate all our service descriptors at once. In the future it might
  2226. * be wise, to rotate service descriptors independently to hide that all
  2227. * those descriptors are on the same tor instance */
  2228. FOR_EACH_SERVICE_BEGIN(service) {
  2229. /* Note for a service booting up: Both descriptors are NULL in that case
  2230. * so this function might return true if we are in the timeframe for a
  2231. * rotation leading to basically swapping two NULL pointers which is
  2232. * harmless. However, the side effect is that triggering a rotation will
  2233. * update the service state and avoid doing anymore rotations after the
  2234. * two descriptors have been built. */
  2235. if (!should_rotate_descriptors(service, now)) {
  2236. continue;
  2237. }
  2238. log_info(LD_REND, "Time to rotate our descriptors (%p / %p) for %s",
  2239. service->desc_current, service->desc_next,
  2240. safe_str_client(service->onion_address));
  2241. rotate_service_descriptors(service);
  2242. } FOR_EACH_SERVICE_END;
  2243. }
  2244. /* Scheduled event run from the main loop. Make sure all our services are up
  2245. * to date and ready for the other scheduled events. This includes looking at
  2246. * the introduction points status and descriptor rotation time. */
  2247. STATIC void
  2248. run_housekeeping_event(time_t now)
  2249. {
  2250. /* Note that nothing here opens circuit(s) nor uploads descriptor(s). We are
  2251. * simply moving things around or removing unneeded elements. */
  2252. FOR_EACH_SERVICE_BEGIN(service) {
  2253. /* If the service is starting off, set the rotation time. We can't do that
  2254. * at configure time because the get_options() needs to be set for setting
  2255. * that time that uses the voting interval. */
  2256. if (service->state.next_rotation_time == 0) {
  2257. /* Set the next rotation time of the descriptors. If it's Oct 25th
  2258. * 23:47:00, the next rotation time is when the next SRV is computed
  2259. * which is at Oct 26th 00:00:00 that is in 13 minutes. */
  2260. set_rotation_time(service);
  2261. }
  2262. /* Cleanup invalid intro points from the service descriptor. */
  2263. cleanup_intro_points(service, now);
  2264. /* Remove expired failing intro point from the descriptor failed list. We
  2265. * reset them at each INTRO_CIRC_RETRY_PERIOD. */
  2266. remove_expired_failing_intro(service, now);
  2267. /* At this point, the service is now ready to go through the scheduled
  2268. * events guaranteeing a valid state. Intro points might be missing from
  2269. * the descriptors after the cleanup but the update/build process will
  2270. * make sure we pick those missing ones. */
  2271. } FOR_EACH_SERVICE_END;
  2272. }
  2273. /* Scheduled event run from the main loop. Make sure all descriptors are up to
  2274. * date. Once this returns, each service descriptor needs to be considered for
  2275. * new introduction circuits and then for upload. */
  2276. static void
  2277. run_build_descriptor_event(time_t now)
  2278. {
  2279. /* For v2 services, this step happens in the upload event. */
  2280. /* Run v3+ events. */
  2281. /* We start by rotating the descriptors only if needed. */
  2282. rotate_all_descriptors(now);
  2283. /* Then, we'll try to build new descriptors that we might need. The
  2284. * condition is that the next descriptor is non existing because it has
  2285. * been rotated or we just started up. */
  2286. build_all_descriptors(now);
  2287. /* Finally, we'll check if we should update the descriptors. Missing
  2288. * introduction points will be picked in this function which is useful for
  2289. * newly built descriptors. */
  2290. update_all_descriptors(now);
  2291. }
  2292. /* For the given service, launch any intro point circuits that could be
  2293. * needed. This considers every descriptor of the service. */
  2294. static void
  2295. launch_intro_point_circuits(hs_service_t *service)
  2296. {
  2297. tor_assert(service);
  2298. /* For both descriptors, try to launch any missing introduction point
  2299. * circuits using the current map. */
  2300. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2301. /* Keep a ref on if we need a direct connection. We use this often. */
  2302. unsigned int direct_conn = service->config.is_single_onion;
  2303. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  2304. hs_service_intro_point_t *, ip) {
  2305. extend_info_t *ei;
  2306. /* Skip the intro point that already has an existing circuit
  2307. * (established or not). */
  2308. if (hs_circ_service_get_intro_circ(ip)) {
  2309. continue;
  2310. }
  2311. ei = get_extend_info_from_intro_point(ip, direct_conn);
  2312. if (ei == NULL) {
  2313. /* This is possible if we can get a node_t but not the extend info out
  2314. * of it. In this case, we remove the intro point and a new one will
  2315. * be picked at the next main loop callback. */
  2316. MAP_DEL_CURRENT(key);
  2317. service_intro_point_free(ip);
  2318. continue;
  2319. }
  2320. /* Launch a circuit to the intro point. */
  2321. ip->circuit_retries++;
  2322. if (hs_circ_launch_intro_point(service, ip, ei) < 0) {
  2323. log_info(LD_REND, "Unable to launch intro circuit to node %s "
  2324. "for service %s.",
  2325. safe_str_client(extend_info_describe(ei)),
  2326. safe_str_client(service->onion_address));
  2327. /* Intro point will be retried if possible after this. */
  2328. }
  2329. extend_info_free(ei);
  2330. } DIGEST256MAP_FOREACH_END;
  2331. } FOR_EACH_DESCRIPTOR_END;
  2332. }
  2333. /* Don't try to build more than this many circuits before giving up for a
  2334. * while. Dynamically calculated based on the configured number of intro
  2335. * points for the given service and how many descriptor exists. The default
  2336. * use case of 3 introduction points and two descriptors will allow 28
  2337. * circuits for a retry period (((3 + 2) + (3 * 3)) * 2). */
  2338. static unsigned int
  2339. get_max_intro_circ_per_period(const hs_service_t *service)
  2340. {
  2341. unsigned int count = 0;
  2342. unsigned int multiplier = 0;
  2343. unsigned int num_wanted_ip;
  2344. tor_assert(service);
  2345. tor_assert(service->config.num_intro_points <=
  2346. HS_CONFIG_V3_MAX_INTRO_POINTS);
  2347. /* For a testing network, allow to do it for the maximum amount so circuit
  2348. * creation and rotation and so on can actually be tested without limit. */
  2349. #define MAX_INTRO_POINT_CIRCUIT_RETRIES_TESTING -1
  2350. if (get_options()->TestingTorNetwork) {
  2351. return MAX_INTRO_POINT_CIRCUIT_RETRIES_TESTING;
  2352. }
  2353. num_wanted_ip = service->config.num_intro_points;
  2354. /* The calculation is as follow. We have a number of intro points that we
  2355. * want configured as a torrc option (num_intro_points). We then add an
  2356. * extra value so we can launch multiple circuits at once and pick the
  2357. * quickest ones. For instance, we want 3 intros, we add 2 extra so we'll
  2358. * pick 5 intros and launch 5 circuits. */
  2359. count += (num_wanted_ip + get_intro_point_num_extra());
  2360. /* Then we add the number of retries that is possible to do for each intro
  2361. * point. If we want 3 intros, we'll allow 3 times the number of possible
  2362. * retry. */
  2363. count += (num_wanted_ip * MAX_INTRO_POINT_CIRCUIT_RETRIES);
  2364. /* Then, we multiply by a factor of 2 if we have both descriptor or 0 if we
  2365. * have none. */
  2366. multiplier += (service->desc_current) ? 1 : 0;
  2367. multiplier += (service->desc_next) ? 1 : 0;
  2368. return (count * multiplier);
  2369. }
  2370. /* For the given service, return 1 if the service is allowed to launch more
  2371. * introduction circuits else 0 if the maximum has been reached for the retry
  2372. * period of INTRO_CIRC_RETRY_PERIOD. */
  2373. STATIC int
  2374. can_service_launch_intro_circuit(hs_service_t *service, time_t now)
  2375. {
  2376. tor_assert(service);
  2377. /* Consider the intro circuit retry period of the service. */
  2378. if (now > (service->state.intro_circ_retry_started_time +
  2379. INTRO_CIRC_RETRY_PERIOD)) {
  2380. service->state.intro_circ_retry_started_time = now;
  2381. service->state.num_intro_circ_launched = 0;
  2382. goto allow;
  2383. }
  2384. /* Check if we can still launch more circuits in this period. */
  2385. if (service->state.num_intro_circ_launched <=
  2386. get_max_intro_circ_per_period(service)) {
  2387. goto allow;
  2388. }
  2389. /* Rate limit log that we've reached our circuit creation limit. */
  2390. {
  2391. char *msg;
  2392. time_t elapsed_time = now - service->state.intro_circ_retry_started_time;
  2393. static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
  2394. if ((msg = rate_limit_log(&rlimit, now))) {
  2395. log_info(LD_REND, "Hidden service %s exceeded its circuit launch limit "
  2396. "of %u per %d seconds. It launched %u circuits in "
  2397. "the last %ld seconds. Will retry in %ld seconds.",
  2398. safe_str_client(service->onion_address),
  2399. get_max_intro_circ_per_period(service),
  2400. INTRO_CIRC_RETRY_PERIOD,
  2401. service->state.num_intro_circ_launched,
  2402. (long int) elapsed_time,
  2403. (long int) (INTRO_CIRC_RETRY_PERIOD - elapsed_time));
  2404. tor_free(msg);
  2405. }
  2406. }
  2407. /* Not allow. */
  2408. return 0;
  2409. allow:
  2410. return 1;
  2411. }
  2412. /* Scheduled event run from the main loop. Make sure we have all the circuits
  2413. * we need for each service. */
  2414. static void
  2415. run_build_circuit_event(time_t now)
  2416. {
  2417. /* Make sure we can actually have enough information or able to build
  2418. * internal circuits as required by services. */
  2419. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN ||
  2420. !have_completed_a_circuit()) {
  2421. return;
  2422. }
  2423. /* Run v2 check. */
  2424. if (rend_num_services() > 0) {
  2425. rend_consider_services_intro_points(now);
  2426. }
  2427. /* Run v3+ check. */
  2428. FOR_EACH_SERVICE_BEGIN(service) {
  2429. /* For introduction circuit, we need to make sure we don't stress too much
  2430. * circuit creation so make sure this service is respecting that limit. */
  2431. if (can_service_launch_intro_circuit(service, now)) {
  2432. /* Launch intro point circuits if needed. */
  2433. launch_intro_point_circuits(service);
  2434. /* Once the circuits have opened, we'll make sure to update the
  2435. * descriptor intro point list and cleanup any extraneous. */
  2436. }
  2437. } FOR_EACH_SERVICE_END;
  2438. }
  2439. /* Encode and sign the service descriptor desc and upload it to the given
  2440. * hidden service directory. This does nothing if PublishHidServDescriptors
  2441. * is false. */
  2442. static void
  2443. upload_descriptor_to_hsdir(const hs_service_t *service,
  2444. hs_service_descriptor_t *desc, const node_t *hsdir)
  2445. {
  2446. char *encoded_desc = NULL;
  2447. tor_assert(service);
  2448. tor_assert(desc);
  2449. tor_assert(hsdir);
  2450. /* Let's avoid doing that if tor is configured to not publish. */
  2451. if (!get_options()->PublishHidServDescriptors) {
  2452. log_info(LD_REND, "Service %s not publishing descriptor. "
  2453. "PublishHidServDescriptors is set to 1.",
  2454. safe_str_client(service->onion_address));
  2455. goto end;
  2456. }
  2457. /* First of all, we'll encode the descriptor. This should NEVER fail but
  2458. * just in case, let's make sure we have an actual usable descriptor. */
  2459. if (BUG(service_encode_descriptor(service, desc, &desc->signing_kp,
  2460. &encoded_desc) < 0)) {
  2461. goto end;
  2462. }
  2463. /* Time to upload the descriptor to the directory. */
  2464. hs_service_upload_desc_to_dir(encoded_desc, service->config.version,
  2465. &service->keys.identity_pk,
  2466. &desc->blinded_kp.pubkey, hsdir->rs);
  2467. /* Add this node to previous_hsdirs list */
  2468. service_desc_note_upload(desc, hsdir);
  2469. /* Logging so we know where it was sent. */
  2470. {
  2471. int is_next_desc = (service->desc_next == desc);
  2472. const uint8_t *idx = (is_next_desc) ? hsdir->hsdir_index.store_second:
  2473. hsdir->hsdir_index.store_first;
  2474. char *blinded_pubkey_log_str =
  2475. tor_strdup(hex_str((char*)&desc->blinded_kp.pubkey.pubkey, 32));
  2476. log_info(LD_REND, "Service %s %s descriptor of revision %" PRIu64
  2477. " initiated upload request to %s with index %s (%s)",
  2478. safe_str_client(service->onion_address),
  2479. (is_next_desc) ? "next" : "current",
  2480. desc->desc->plaintext_data.revision_counter,
  2481. safe_str_client(node_describe(hsdir)),
  2482. safe_str_client(hex_str((const char *) idx, 32)),
  2483. safe_str_client(blinded_pubkey_log_str));
  2484. tor_free(blinded_pubkey_log_str);
  2485. /* Fire a UPLOAD control port event. */
  2486. hs_control_desc_event_upload(service->onion_address, hsdir->identity,
  2487. &desc->blinded_kp.pubkey, idx);
  2488. }
  2489. end:
  2490. tor_free(encoded_desc);
  2491. return;
  2492. }
  2493. /** Set the revision counter in <b>hs_desc</b>. We do this by encrypting a
  2494. * timestamp using an OPE scheme and using the ciphertext as our revision
  2495. * counter.
  2496. *
  2497. * If <b>is_current</b> is true, then this is the current HS descriptor,
  2498. * otherwise it's the next one. */
  2499. static void
  2500. set_descriptor_revision_counter(hs_service_descriptor_t *hs_desc, time_t now,
  2501. bool is_current)
  2502. {
  2503. uint64_t rev_counter = 0;
  2504. /* Get current time */
  2505. time_t srv_start = 0;
  2506. /* As our revision counter plaintext value, we use the seconds since the
  2507. * start of the SR protocol run that is relevant to this descriptor. This is
  2508. * guaranteed to be a positive value since we need the SRV to start making a
  2509. * descriptor (so that we know where to upload it).
  2510. *
  2511. * Depending on whether we are building the current or the next descriptor,
  2512. * services use a different SRV value. See [SERVICEUPLOAD] in
  2513. * rend-spec-v3.txt:
  2514. *
  2515. * In particular, for the current descriptor (aka first descriptor), Tor
  2516. * always uses the previous SRV for uploading the descriptor, and hence we
  2517. * should use the start time of the previous protocol run here.
  2518. *
  2519. * Whereas for the next descriptor (aka second descriptor), Tor always uses
  2520. * the current SRV for uploading the descriptor. and hence we use the start
  2521. * time of the current protocol run.
  2522. */
  2523. if (is_current) {
  2524. srv_start = sr_state_get_start_time_of_previous_protocol_run();
  2525. } else {
  2526. srv_start = sr_state_get_start_time_of_current_protocol_run();
  2527. }
  2528. log_info(LD_REND, "Setting rev counter for TP #%u: "
  2529. "SRV started at %d, now %d (%s)",
  2530. (unsigned) hs_desc->time_period_num, (int)srv_start,
  2531. (int)now, is_current ? "current" : "next");
  2532. tor_assert_nonfatal(now >= srv_start);
  2533. /* Compute seconds elapsed since the start of the time period. That's the
  2534. * number of seconds of how long this blinded key has been active. */
  2535. time_t seconds_since_start_of_srv = now - srv_start;
  2536. /* Increment by one so that we are definitely sure this is strictly
  2537. * positive and not zero. */
  2538. seconds_since_start_of_srv++;
  2539. /* Check for too big inputs. */
  2540. if (BUG(seconds_since_start_of_srv > OPE_INPUT_MAX)) {
  2541. seconds_since_start_of_srv = OPE_INPUT_MAX;
  2542. }
  2543. /* Now we compute the final revision counter value by encrypting the
  2544. plaintext using our OPE cipher: */
  2545. tor_assert(hs_desc->ope_cipher);
  2546. rev_counter = crypto_ope_encrypt(hs_desc->ope_cipher,
  2547. (int) seconds_since_start_of_srv);
  2548. /* The OPE module returns CRYPTO_OPE_ERROR in case of errors. */
  2549. tor_assert_nonfatal(rev_counter < CRYPTO_OPE_ERROR);
  2550. log_info(LD_REND, "Encrypted revision counter %d to %ld",
  2551. (int) seconds_since_start_of_srv, (long int) rev_counter);
  2552. hs_desc->desc->plaintext_data.revision_counter = rev_counter;
  2553. }
  2554. /* Encode and sign the service descriptor desc and upload it to the
  2555. * responsible hidden service directories. If for_next_period is true, the set
  2556. * of directories are selected using the next hsdir_index. This does nothing
  2557. * if PublishHidServDescriptors is false. */
  2558. STATIC void
  2559. upload_descriptor_to_all(const hs_service_t *service,
  2560. hs_service_descriptor_t *desc)
  2561. {
  2562. smartlist_t *responsible_dirs = NULL;
  2563. tor_assert(service);
  2564. tor_assert(desc);
  2565. /* We'll first cancel any directory request that are ongoing for this
  2566. * descriptor. It is possible that we can trigger multiple uploads in a
  2567. * short time frame which can lead to a race where the second upload arrives
  2568. * before the first one leading to a 400 malformed descriptor response from
  2569. * the directory. Closing all pending requests avoids that. */
  2570. close_directory_connections(service, desc);
  2571. /* Get our list of responsible HSDir. */
  2572. responsible_dirs = smartlist_new();
  2573. /* The parameter 0 means that we aren't a client so tell the function to use
  2574. * the spread store consensus paremeter. */
  2575. hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
  2576. service->desc_next == desc, 0, responsible_dirs);
  2577. /** Clear list of previous hsdirs since we are about to upload to a new
  2578. * list. Let's keep it up to date. */
  2579. service_desc_clear_previous_hsdirs(desc);
  2580. /* For each responsible HSDir we have, initiate an upload command. */
  2581. SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *,
  2582. hsdir_rs) {
  2583. const node_t *hsdir_node = node_get_by_id(hsdir_rs->identity_digest);
  2584. /* Getting responsible hsdir implies that the node_t object exists for the
  2585. * routerstatus_t found in the consensus else we have a problem. */
  2586. tor_assert(hsdir_node);
  2587. /* Upload this descriptor to the chosen directory. */
  2588. upload_descriptor_to_hsdir(service, desc, hsdir_node);
  2589. } SMARTLIST_FOREACH_END(hsdir_rs);
  2590. /* Set the next upload time for this descriptor. Even if we are configured
  2591. * to not upload, we still want to follow the right cycle of life for this
  2592. * descriptor. */
  2593. desc->next_upload_time =
  2594. (time(NULL) + crypto_rand_int_range(HS_SERVICE_NEXT_UPLOAD_TIME_MIN,
  2595. HS_SERVICE_NEXT_UPLOAD_TIME_MAX));
  2596. {
  2597. char fmt_next_time[ISO_TIME_LEN+1];
  2598. format_local_iso_time(fmt_next_time, desc->next_upload_time);
  2599. log_debug(LD_REND, "Service %s set to upload a descriptor at %s",
  2600. safe_str_client(service->onion_address), fmt_next_time);
  2601. }
  2602. smartlist_free(responsible_dirs);
  2603. return;
  2604. }
  2605. /** The set of HSDirs have changed: check if the change affects our descriptor
  2606. * HSDir placement, and if it does, reupload the desc. */
  2607. STATIC int
  2608. service_desc_hsdirs_changed(const hs_service_t *service,
  2609. const hs_service_descriptor_t *desc)
  2610. {
  2611. int should_reupload = 0;
  2612. smartlist_t *responsible_dirs = smartlist_new();
  2613. /* No desc upload has happened yet: it will happen eventually */
  2614. if (!desc->previous_hsdirs || !smartlist_len(desc->previous_hsdirs)) {
  2615. goto done;
  2616. }
  2617. /* Get list of responsible hsdirs */
  2618. hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
  2619. service->desc_next == desc, 0, responsible_dirs);
  2620. /* Check if any new hsdirs have been added to the responsible hsdirs set:
  2621. * Iterate over the list of new hsdirs, and reupload if any of them is not
  2622. * present in the list of previous hsdirs.
  2623. */
  2624. SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *, hsdir_rs) {
  2625. char b64_digest[BASE64_DIGEST_LEN+1] = {0};
  2626. digest_to_base64(b64_digest, hsdir_rs->identity_digest);
  2627. if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
  2628. should_reupload = 1;
  2629. break;
  2630. }
  2631. } SMARTLIST_FOREACH_END(hsdir_rs);
  2632. done:
  2633. smartlist_free(responsible_dirs);
  2634. return should_reupload;
  2635. }
  2636. /* Return 1 if the given descriptor from the given service can be uploaded
  2637. * else return 0 if it can not. */
  2638. static int
  2639. should_service_upload_descriptor(const hs_service_t *service,
  2640. const hs_service_descriptor_t *desc, time_t now)
  2641. {
  2642. unsigned int num_intro_points;
  2643. tor_assert(service);
  2644. tor_assert(desc);
  2645. /* If this descriptors has missing intro points that is that it couldn't get
  2646. * them all when it was time to pick them, it means that we should upload
  2647. * instead of waiting an arbitrary amount of time breaking the service.
  2648. * Else, if we have no missing intro points, we use the value taken from the
  2649. * service configuration. */
  2650. if (desc->missing_intro_points) {
  2651. num_intro_points = digest256map_size(desc->intro_points.map);
  2652. } else {
  2653. num_intro_points = service->config.num_intro_points;
  2654. }
  2655. /* This means we tried to pick intro points but couldn't get any so do not
  2656. * upload descriptor in this case. We need at least one for the service to
  2657. * be reachable. */
  2658. if (desc->missing_intro_points && num_intro_points == 0) {
  2659. goto cannot;
  2660. }
  2661. /* Check if all our introduction circuit have been established for all the
  2662. * intro points we have selected. */
  2663. if (count_desc_circuit_established(desc) != num_intro_points) {
  2664. goto cannot;
  2665. }
  2666. /* Is it the right time to upload? */
  2667. if (desc->next_upload_time > now) {
  2668. goto cannot;
  2669. }
  2670. /* Don't upload desc if we don't have a live consensus */
  2671. if (!networkstatus_get_live_consensus(now)) {
  2672. goto cannot;
  2673. }
  2674. /* Do we know enough router descriptors to have adequate vision of the HSDir
  2675. hash ring? */
  2676. if (!router_have_minimum_dir_info()) {
  2677. goto cannot;
  2678. }
  2679. /* Can upload! */
  2680. return 1;
  2681. cannot:
  2682. return 0;
  2683. }
  2684. /* Scheduled event run from the main loop. Try to upload the descriptor for
  2685. * each service. */
  2686. STATIC void
  2687. run_upload_descriptor_event(time_t now)
  2688. {
  2689. /* v2 services use the same function for descriptor creation and upload so
  2690. * we do everything here because the intro circuits were checked before. */
  2691. if (rend_num_services() > 0) {
  2692. rend_consider_services_upload(now);
  2693. rend_consider_descriptor_republication();
  2694. }
  2695. /* Run v3+ check. */
  2696. FOR_EACH_SERVICE_BEGIN(service) {
  2697. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2698. /* If we were asked to re-examine the hash ring, and it changed, then
  2699. schedule an upload */
  2700. if (consider_republishing_hs_descriptors &&
  2701. service_desc_hsdirs_changed(service, desc)) {
  2702. service_desc_schedule_upload(desc, now, 0);
  2703. }
  2704. /* Can this descriptor be uploaded? */
  2705. if (!should_service_upload_descriptor(service, desc, now)) {
  2706. continue;
  2707. }
  2708. log_info(LD_REND, "Initiating upload for hidden service %s descriptor "
  2709. "for service %s with %u/%u introduction points%s.",
  2710. (desc == service->desc_current) ? "current" : "next",
  2711. safe_str_client(service->onion_address),
  2712. digest256map_size(desc->intro_points.map),
  2713. service->config.num_intro_points,
  2714. (desc->missing_intro_points) ? " (couldn't pick more)" : "");
  2715. /* At this point, we have to upload the descriptor so start by building
  2716. * the intro points descriptor section which we are now sure to be
  2717. * accurate because all circuits have been established. */
  2718. build_desc_intro_points(service, desc, now);
  2719. /* Set the desc revision counter right before uploading */
  2720. set_descriptor_revision_counter(desc, approx_time(),
  2721. service->desc_current == desc);
  2722. upload_descriptor_to_all(service, desc);
  2723. } FOR_EACH_DESCRIPTOR_END;
  2724. } FOR_EACH_SERVICE_END;
  2725. /* We are done considering whether to republish rend descriptors */
  2726. consider_republishing_hs_descriptors = 0;
  2727. }
  2728. /* Called when the introduction point circuit is done building and ready to be
  2729. * used. */
  2730. static void
  2731. service_intro_circ_has_opened(origin_circuit_t *circ)
  2732. {
  2733. hs_service_t *service = NULL;
  2734. hs_service_intro_point_t *ip = NULL;
  2735. hs_service_descriptor_t *desc = NULL;
  2736. tor_assert(circ);
  2737. /* Let's do some basic sanity checking of the circ state */
  2738. if (BUG(!circ->cpath)) {
  2739. return;
  2740. }
  2741. if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)) {
  2742. return;
  2743. }
  2744. if (BUG(!circ->hs_ident)) {
  2745. return;
  2746. }
  2747. /* Get the corresponding service and intro point. */
  2748. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  2749. if (service == NULL) {
  2750. log_warn(LD_REND, "Unknown service identity key %s on the introduction "
  2751. "circuit %u. Can't find onion service.",
  2752. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2753. TO_CIRCUIT(circ)->n_circ_id);
  2754. goto err;
  2755. }
  2756. if (ip == NULL) {
  2757. log_warn(LD_REND, "Unknown introduction point auth key on circuit %u "
  2758. "for service %s",
  2759. TO_CIRCUIT(circ)->n_circ_id,
  2760. safe_str_client(service->onion_address));
  2761. goto err;
  2762. }
  2763. /* We can't have an IP object without a descriptor. */
  2764. tor_assert(desc);
  2765. if (hs_circ_service_intro_has_opened(service, ip, desc, circ)) {
  2766. /* Getting here means that the circuit has been re-purposed because we
  2767. * have enough intro circuit opened. Remove the IP from the service. */
  2768. service_intro_point_remove(service, ip);
  2769. service_intro_point_free(ip);
  2770. }
  2771. goto done;
  2772. err:
  2773. /* Close circuit, we can't use it. */
  2774. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
  2775. done:
  2776. return;
  2777. }
  2778. /* Called when a rendezvous circuit is done building and ready to be used. */
  2779. static void
  2780. service_rendezvous_circ_has_opened(origin_circuit_t *circ)
  2781. {
  2782. hs_service_t *service = NULL;
  2783. tor_assert(circ);
  2784. tor_assert(circ->cpath);
  2785. /* Getting here means this is a v3 rendezvous circuit. */
  2786. tor_assert(circ->hs_ident);
  2787. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  2788. /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
  2789. * timestamp regardless of its content because that circuit could have been
  2790. * cannibalized so in any cases, we are about to use that circuit more. */
  2791. TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
  2792. pathbias_count_use_attempt(circ);
  2793. /* Get the corresponding service and intro point. */
  2794. get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
  2795. if (service == NULL) {
  2796. log_warn(LD_REND, "Unknown service identity key %s on the rendezvous "
  2797. "circuit %u with cookie %s. Can't find onion service.",
  2798. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2799. TO_CIRCUIT(circ)->n_circ_id,
  2800. hex_str((const char *) circ->hs_ident->rendezvous_cookie,
  2801. REND_COOKIE_LEN));
  2802. goto err;
  2803. }
  2804. /* If the cell can't be sent, the circuit will be closed within this
  2805. * function. */
  2806. hs_circ_service_rp_has_opened(service, circ);
  2807. goto done;
  2808. err:
  2809. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
  2810. done:
  2811. return;
  2812. }
  2813. /* We've been expecting an INTRO_ESTABLISHED cell on this circuit and it just
  2814. * arrived. Handle the INTRO_ESTABLISHED cell arriving on the given
  2815. * introduction circuit. Return 0 on success else a negative value. */
  2816. static int
  2817. service_handle_intro_established(origin_circuit_t *circ,
  2818. const uint8_t *payload,
  2819. size_t payload_len)
  2820. {
  2821. hs_service_t *service = NULL;
  2822. hs_service_intro_point_t *ip = NULL;
  2823. tor_assert(circ);
  2824. tor_assert(payload);
  2825. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  2826. /* We need the service and intro point for this cell. */
  2827. get_objects_from_ident(circ->hs_ident, &service, &ip, NULL);
  2828. /* Get service object from the circuit identifier. */
  2829. if (service == NULL) {
  2830. log_warn(LD_REND, "Unknown service identity key %s on the introduction "
  2831. "circuit %u. Can't find onion service.",
  2832. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2833. TO_CIRCUIT(circ)->n_circ_id);
  2834. goto err;
  2835. }
  2836. if (ip == NULL) {
  2837. /* We don't recognize the key. */
  2838. log_warn(LD_REND, "Introduction circuit established without an intro "
  2839. "point object on circuit %u for service %s",
  2840. TO_CIRCUIT(circ)->n_circ_id,
  2841. safe_str_client(service->onion_address));
  2842. goto err;
  2843. }
  2844. /* Try to parse the payload into a cell making sure we do actually have a
  2845. * valid cell. On success, the ip object and circuit purpose is updated to
  2846. * reflect the fact that the introduction circuit is established. */
  2847. if (hs_circ_handle_intro_established(service, ip, circ, payload,
  2848. payload_len) < 0) {
  2849. goto err;
  2850. }
  2851. /* Flag that we have an established circuit for this intro point. This value
  2852. * is what indicates the upload scheduled event if we are ready to build the
  2853. * intro point into the descriptor and upload. */
  2854. ip->circuit_established = 1;
  2855. log_info(LD_REND, "Successfully received an INTRO_ESTABLISHED cell "
  2856. "on circuit %u for service %s",
  2857. TO_CIRCUIT(circ)->n_circ_id,
  2858. safe_str_client(service->onion_address));
  2859. return 0;
  2860. err:
  2861. return -1;
  2862. }
  2863. /* We just received an INTRODUCE2 cell on the established introduction circuit
  2864. * circ. Handle the cell and return 0 on success else a negative value. */
  2865. static int
  2866. service_handle_introduce2(origin_circuit_t *circ, const uint8_t *payload,
  2867. size_t payload_len)
  2868. {
  2869. hs_service_t *service = NULL;
  2870. hs_service_intro_point_t *ip = NULL;
  2871. hs_service_descriptor_t *desc = NULL;
  2872. tor_assert(circ);
  2873. tor_assert(payload);
  2874. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  2875. /* We'll need every object associated with this circuit. */
  2876. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  2877. /* Get service object from the circuit identifier. */
  2878. if (service == NULL) {
  2879. log_warn(LD_BUG, "Unknown service identity key %s when handling "
  2880. "an INTRODUCE2 cell on circuit %u",
  2881. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2882. TO_CIRCUIT(circ)->n_circ_id);
  2883. goto err;
  2884. }
  2885. if (ip == NULL) {
  2886. /* We don't recognize the key. */
  2887. log_warn(LD_BUG, "Unknown introduction auth key when handling "
  2888. "an INTRODUCE2 cell on circuit %u for service %s",
  2889. TO_CIRCUIT(circ)->n_circ_id,
  2890. safe_str_client(service->onion_address));
  2891. goto err;
  2892. }
  2893. /* If we have an IP object, we MUST have a descriptor object. */
  2894. tor_assert(desc);
  2895. /* The following will parse, decode and launch the rendezvous point circuit.
  2896. * Both current and legacy cells are handled. */
  2897. if (hs_circ_handle_introduce2(service, circ, ip, desc->desc->subcredential,
  2898. payload, payload_len) < 0) {
  2899. goto err;
  2900. }
  2901. return 0;
  2902. err:
  2903. return -1;
  2904. }
  2905. /* Add to list every filename used by service. This is used by the sandbox
  2906. * subsystem. */
  2907. static void
  2908. service_add_fnames_to_list(const hs_service_t *service, smartlist_t *list)
  2909. {
  2910. const char *s_dir;
  2911. char fname[128] = {0};
  2912. tor_assert(service);
  2913. tor_assert(list);
  2914. /* Ease our life. */
  2915. s_dir = service->config.directory_path;
  2916. /* The hostname file. */
  2917. smartlist_add(list, hs_path_from_filename(s_dir, fname_hostname));
  2918. /* The key files splitted in two. */
  2919. tor_snprintf(fname, sizeof(fname), "%s_secret_key", fname_keyfile_prefix);
  2920. smartlist_add(list, hs_path_from_filename(s_dir, fname));
  2921. tor_snprintf(fname, sizeof(fname), "%s_public_key", fname_keyfile_prefix);
  2922. smartlist_add(list, hs_path_from_filename(s_dir, fname));
  2923. }
  2924. /* Return true iff the given service identity key is present on disk. */
  2925. static int
  2926. service_key_on_disk(const char *directory_path)
  2927. {
  2928. int ret = 0;
  2929. char *fname;
  2930. ed25519_keypair_t *kp = NULL;
  2931. tor_assert(directory_path);
  2932. /* Build the v3 key path name and then try to load it. */
  2933. fname = hs_path_from_filename(directory_path, fname_keyfile_prefix);
  2934. kp = ed_key_init_from_file(fname, INIT_ED_KEY_SPLIT,
  2935. LOG_DEBUG, NULL, 0, 0, 0, NULL, NULL);
  2936. if (kp) {
  2937. ret = 1;
  2938. }
  2939. ed25519_keypair_free(kp);
  2940. tor_free(fname);
  2941. return ret;
  2942. }
  2943. /* This is a proxy function before actually calling hs_desc_encode_descriptor
  2944. * because we need some preprocessing here */
  2945. static int
  2946. service_encode_descriptor(const hs_service_t *service,
  2947. const hs_service_descriptor_t *desc,
  2948. const ed25519_keypair_t *signing_kp,
  2949. char **encoded_out)
  2950. {
  2951. int ret;
  2952. const uint8_t *descriptor_cookie = NULL;
  2953. tor_assert(service);
  2954. tor_assert(desc);
  2955. tor_assert(encoded_out);
  2956. /* If the client authorization is enabled, send the descriptor cookie to
  2957. * hs_desc_encode_descriptor. Otherwise, send NULL */
  2958. if (service->config.is_client_auth_enabled) {
  2959. descriptor_cookie = desc->descriptor_cookie;
  2960. }
  2961. ret = hs_desc_encode_descriptor(desc->desc, signing_kp,
  2962. descriptor_cookie, encoded_out);
  2963. return ret;
  2964. }
  2965. /* ========== */
  2966. /* Public API */
  2967. /* ========== */
  2968. /* This is called everytime the service map (v2 or v3) changes that is if an
  2969. * element is added or removed. */
  2970. void
  2971. hs_service_map_has_changed(void)
  2972. {
  2973. /* If we now have services where previously we had not, we need to enable
  2974. * the HS service main loop event. If we changed to having no services, we
  2975. * need to disable the event. */
  2976. rescan_periodic_events(get_options());
  2977. }
  2978. /* Upload an encoded descriptor in encoded_desc of the given version. This
  2979. * descriptor is for the service identity_pk and blinded_pk used to setup the
  2980. * directory connection identifier. It is uploaded to the directory hsdir_rs
  2981. * routerstatus_t object.
  2982. *
  2983. * NOTE: This function does NOT check for PublishHidServDescriptors because it
  2984. * is only used by the control port command HSPOST outside of this subsystem.
  2985. * Inside this code, upload_descriptor_to_hsdir() should be used. */
  2986. void
  2987. hs_service_upload_desc_to_dir(const char *encoded_desc,
  2988. const uint8_t version,
  2989. const ed25519_public_key_t *identity_pk,
  2990. const ed25519_public_key_t *blinded_pk,
  2991. const routerstatus_t *hsdir_rs)
  2992. {
  2993. char version_str[4] = {0};
  2994. directory_request_t *dir_req;
  2995. hs_ident_dir_conn_t ident;
  2996. tor_assert(encoded_desc);
  2997. tor_assert(identity_pk);
  2998. tor_assert(blinded_pk);
  2999. tor_assert(hsdir_rs);
  3000. /* Setup the connection identifier. */
  3001. memset(&ident, 0, sizeof(ident));
  3002. hs_ident_dir_conn_init(identity_pk, blinded_pk, &ident);
  3003. /* This is our resource when uploading which is used to construct the URL
  3004. * with the version number: "/tor/hs/<version>/publish". */
  3005. tor_snprintf(version_str, sizeof(version_str), "%u", version);
  3006. /* Build the directory request for this HSDir. */
  3007. dir_req = directory_request_new(DIR_PURPOSE_UPLOAD_HSDESC);
  3008. directory_request_set_routerstatus(dir_req, hsdir_rs);
  3009. directory_request_set_indirection(dir_req, DIRIND_ANONYMOUS);
  3010. directory_request_set_resource(dir_req, version_str);
  3011. directory_request_set_payload(dir_req, encoded_desc,
  3012. strlen(encoded_desc));
  3013. /* The ident object is copied over the directory connection object once
  3014. * the directory request is initiated. */
  3015. directory_request_upload_set_hs_ident(dir_req, &ident);
  3016. /* Initiate the directory request to the hsdir.*/
  3017. directory_initiate_request(dir_req);
  3018. directory_request_free(dir_req);
  3019. }
  3020. /* Add the ephemeral service using the secret key sk and ports. Both max
  3021. * streams parameter will be set in the newly created service.
  3022. *
  3023. * Ownership of sk and ports is passed to this routine. Regardless of
  3024. * success/failure, callers should not touch these values after calling this
  3025. * routine, and may assume that correct cleanup has been done on failure.
  3026. *
  3027. * Return an appropriate hs_service_add_ephemeral_status_t. */
  3028. hs_service_add_ephemeral_status_t
  3029. hs_service_add_ephemeral(ed25519_secret_key_t *sk, smartlist_t *ports,
  3030. int max_streams_per_rdv_circuit,
  3031. int max_streams_close_circuit, char **address_out)
  3032. {
  3033. hs_service_add_ephemeral_status_t ret;
  3034. hs_service_t *service = NULL;
  3035. tor_assert(sk);
  3036. tor_assert(ports);
  3037. tor_assert(address_out);
  3038. service = hs_service_new(get_options());
  3039. /* Setup the service configuration with specifics. A default service is
  3040. * HS_VERSION_TWO so explicitly set it. */
  3041. service->config.version = HS_VERSION_THREE;
  3042. service->config.max_streams_per_rdv_circuit = max_streams_per_rdv_circuit;
  3043. service->config.max_streams_close_circuit = !!max_streams_close_circuit;
  3044. service->config.is_ephemeral = 1;
  3045. smartlist_free(service->config.ports);
  3046. service->config.ports = ports;
  3047. /* Handle the keys. */
  3048. memcpy(&service->keys.identity_sk, sk, sizeof(service->keys.identity_sk));
  3049. if (ed25519_public_key_generate(&service->keys.identity_pk,
  3050. &service->keys.identity_sk) < 0) {
  3051. log_warn(LD_CONFIG, "Unable to generate ed25519 public key"
  3052. "for v3 service.");
  3053. ret = RSAE_BADPRIVKEY;
  3054. goto err;
  3055. }
  3056. /* Make sure we have at least one port. */
  3057. if (smartlist_len(service->config.ports) == 0) {
  3058. log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified "
  3059. "for v3 service.");
  3060. ret = RSAE_BADVIRTPORT;
  3061. goto err;
  3062. }
  3063. /* Build the onion address for logging purposes but also the control port
  3064. * uses it for the HS_DESC event. */
  3065. hs_build_address(&service->keys.identity_pk,
  3066. (uint8_t) service->config.version,
  3067. service->onion_address);
  3068. /* The only way the registration can fail is if the service public key
  3069. * already exists. */
  3070. if (BUG(register_service(hs_service_map, service) < 0)) {
  3071. log_warn(LD_CONFIG, "Onion Service private key collides with an "
  3072. "existing v3 service.");
  3073. ret = RSAE_ADDREXISTS;
  3074. goto err;
  3075. }
  3076. log_info(LD_CONFIG, "Added ephemeral v3 onion service: %s",
  3077. safe_str_client(service->onion_address));
  3078. *address_out = tor_strdup(service->onion_address);
  3079. ret = RSAE_OKAY;
  3080. goto end;
  3081. err:
  3082. hs_service_free(service);
  3083. end:
  3084. memwipe(sk, 0, sizeof(ed25519_secret_key_t));
  3085. tor_free(sk);
  3086. return ret;
  3087. }
  3088. /* For the given onion address, delete the ephemeral service. Return 0 on
  3089. * success else -1 on error. */
  3090. int
  3091. hs_service_del_ephemeral(const char *address)
  3092. {
  3093. uint8_t version;
  3094. ed25519_public_key_t pk;
  3095. hs_service_t *service = NULL;
  3096. tor_assert(address);
  3097. if (hs_parse_address(address, &pk, NULL, &version) < 0) {
  3098. log_warn(LD_CONFIG, "Requested malformed v3 onion address for removal.");
  3099. goto err;
  3100. }
  3101. if (version != HS_VERSION_THREE) {
  3102. log_warn(LD_CONFIG, "Requested version of onion address for removal "
  3103. "is not supported.");
  3104. goto err;
  3105. }
  3106. service = find_service(hs_service_map, &pk);
  3107. if (service == NULL) {
  3108. log_warn(LD_CONFIG, "Requested non-existent v3 hidden service for "
  3109. "removal.");
  3110. goto err;
  3111. }
  3112. if (!service->config.is_ephemeral) {
  3113. log_warn(LD_CONFIG, "Requested non-ephemeral v3 hidden service for "
  3114. "removal.");
  3115. goto err;
  3116. }
  3117. /* Close circuits, remove from map and finally free. */
  3118. close_service_circuits(service);
  3119. remove_service(hs_service_map, service);
  3120. hs_service_free(service);
  3121. log_info(LD_CONFIG, "Removed ephemeral v3 hidden service: %s",
  3122. safe_str_client(address));
  3123. return 0;
  3124. err:
  3125. return -1;
  3126. }
  3127. /* Using the ed25519 public key pk, find a service for that key and return the
  3128. * current encoded descriptor as a newly allocated string or NULL if not
  3129. * found. This is used by the control port subsystem. */
  3130. char *
  3131. hs_service_lookup_current_desc(const ed25519_public_key_t *pk)
  3132. {
  3133. const hs_service_t *service;
  3134. tor_assert(pk);
  3135. service = find_service(hs_service_map, pk);
  3136. if (service && service->desc_current) {
  3137. char *encoded_desc = NULL;
  3138. /* No matter what is the result (which should never be a failure), return
  3139. * the encoded variable, if success it will contain the right thing else
  3140. * it will be NULL. */
  3141. service_encode_descriptor(service,
  3142. service->desc_current,
  3143. &service->desc_current->signing_kp,
  3144. &encoded_desc);
  3145. return encoded_desc;
  3146. }
  3147. return NULL;
  3148. }
  3149. /* Return the number of service we have configured and usable. */
  3150. unsigned int
  3151. hs_service_get_num_services(void)
  3152. {
  3153. if (hs_service_map == NULL) {
  3154. return 0;
  3155. }
  3156. return HT_SIZE(hs_service_map);
  3157. }
  3158. /* Called once an introduction circuit is closed. If the circuit doesn't have
  3159. * a v3 identifier, it is ignored. */
  3160. void
  3161. hs_service_intro_circ_has_closed(origin_circuit_t *circ)
  3162. {
  3163. hs_service_t *service = NULL;
  3164. hs_service_intro_point_t *ip = NULL;
  3165. hs_service_descriptor_t *desc = NULL;
  3166. tor_assert(circ);
  3167. if (circ->hs_ident == NULL) {
  3168. /* This is not a v3 circuit, ignore. */
  3169. goto end;
  3170. }
  3171. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  3172. if (service == NULL) {
  3173. /* This is possible if the circuits are closed and the service is
  3174. * immediately deleted. */
  3175. log_info(LD_REND, "Unable to find any hidden service associated "
  3176. "identity key %s on intro circuit %u.",
  3177. ed25519_fmt(&circ->hs_ident->identity_pk),
  3178. TO_CIRCUIT(circ)->n_circ_id);
  3179. goto end;
  3180. }
  3181. if (ip == NULL) {
  3182. /* The introduction point object has already been removed probably by our
  3183. * cleanup process so ignore. */
  3184. goto end;
  3185. }
  3186. /* Can't have an intro point object without a descriptor. */
  3187. tor_assert(desc);
  3188. /* Circuit disappeared so make sure the intro point is updated. By
  3189. * keeping the object in the descriptor, we'll be able to retry. */
  3190. ip->circuit_established = 0;
  3191. end:
  3192. return;
  3193. }
  3194. /* Given conn, a rendezvous edge connection acting as an exit stream, look up
  3195. * the hidden service for the circuit circ, and look up the port and address
  3196. * based on the connection port. Assign the actual connection address.
  3197. *
  3198. * Return 0 on success. Return -1 on failure and the caller should NOT close
  3199. * the circuit. Return -2 on failure and the caller MUST close the circuit for
  3200. * security reasons. */
  3201. int
  3202. hs_service_set_conn_addr_port(const origin_circuit_t *circ,
  3203. edge_connection_t *conn)
  3204. {
  3205. hs_service_t *service = NULL;
  3206. tor_assert(circ);
  3207. tor_assert(conn);
  3208. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3209. tor_assert(circ->hs_ident);
  3210. get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
  3211. if (service == NULL) {
  3212. log_warn(LD_REND, "Unable to find any hidden service associated "
  3213. "identity key %s on rendezvous circuit %u.",
  3214. ed25519_fmt(&circ->hs_ident->identity_pk),
  3215. TO_CIRCUIT(circ)->n_circ_id);
  3216. /* We want the caller to close the circuit because it's not a valid
  3217. * service so no danger. Attempting to bruteforce the entire key space by
  3218. * opening circuits to learn which service is being hosted here is
  3219. * impractical. */
  3220. goto err_close;
  3221. }
  3222. /* Enforce the streams-per-circuit limit, and refuse to provide a mapping if
  3223. * this circuit will exceed the limit. */
  3224. if (service->config.max_streams_per_rdv_circuit > 0 &&
  3225. (circ->hs_ident->num_rdv_streams >=
  3226. service->config.max_streams_per_rdv_circuit)) {
  3227. #define MAX_STREAM_WARN_INTERVAL 600
  3228. static struct ratelim_t stream_ratelim =
  3229. RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
  3230. log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
  3231. "Maximum streams per circuit limit reached on "
  3232. "rendezvous circuit %u for service %s. Circuit has "
  3233. "%" PRIu64 " out of %" PRIu64 " streams. %s.",
  3234. TO_CIRCUIT(circ)->n_circ_id,
  3235. service->onion_address,
  3236. circ->hs_ident->num_rdv_streams,
  3237. service->config.max_streams_per_rdv_circuit,
  3238. service->config.max_streams_close_circuit ?
  3239. "Closing circuit" : "Ignoring open stream request");
  3240. if (service->config.max_streams_close_circuit) {
  3241. /* Service explicitly configured to close immediately. */
  3242. goto err_close;
  3243. }
  3244. /* Exceeding the limit makes tor silently ignore the stream creation
  3245. * request and keep the circuit open. */
  3246. goto err_no_close;
  3247. }
  3248. /* Find a virtual port of that service mathcing the one in the connection if
  3249. * successful, set the address in the connection. */
  3250. if (hs_set_conn_addr_port(service->config.ports, conn) < 0) {
  3251. log_info(LD_REND, "No virtual port mapping exists for port %d for "
  3252. "hidden service %s.",
  3253. TO_CONN(conn)->port, service->onion_address);
  3254. if (service->config.allow_unknown_ports) {
  3255. /* Service explicitly allow connection to unknown ports so close right
  3256. * away because we do not care about port mapping. */
  3257. goto err_close;
  3258. }
  3259. /* If the service didn't explicitly allow it, we do NOT close the circuit
  3260. * here to raise the bar in terms of performance for port mapping. */
  3261. goto err_no_close;
  3262. }
  3263. /* Success. */
  3264. return 0;
  3265. err_close:
  3266. /* Indicate the caller that the circuit should be closed. */
  3267. return -2;
  3268. err_no_close:
  3269. /* Indicate the caller to NOT close the circuit. */
  3270. return -1;
  3271. }
  3272. /** Does the service with identity pubkey <b>pk</b> export the circuit IDs of
  3273. * its clients? */
  3274. hs_circuit_id_protocol_t
  3275. hs_service_exports_circuit_id(const ed25519_public_key_t *pk)
  3276. {
  3277. hs_service_t *service = find_service(hs_service_map, pk);
  3278. if (!service) {
  3279. return HS_CIRCUIT_ID_PROTOCOL_NONE;
  3280. }
  3281. return service->config.circuit_id_protocol;
  3282. }
  3283. /* Add to file_list every filename used by a configured hidden service, and to
  3284. * dir_list every directory path used by a configured hidden service. This is
  3285. * used by the sandbox subsystem to whitelist those. */
  3286. void
  3287. hs_service_lists_fnames_for_sandbox(smartlist_t *file_list,
  3288. smartlist_t *dir_list)
  3289. {
  3290. tor_assert(file_list);
  3291. tor_assert(dir_list);
  3292. /* Add files and dirs for legacy services. */
  3293. rend_services_add_filenames_to_lists(file_list, dir_list);
  3294. /* Add files and dirs for v3+. */
  3295. FOR_EACH_SERVICE_BEGIN(service) {
  3296. /* Skip ephemeral service, they don't touch the disk. */
  3297. if (service->config.is_ephemeral) {
  3298. continue;
  3299. }
  3300. service_add_fnames_to_list(service, file_list);
  3301. smartlist_add_strdup(dir_list, service->config.directory_path);
  3302. smartlist_add_strdup(dir_list, dname_client_pubkeys);
  3303. } FOR_EACH_DESCRIPTOR_END;
  3304. }
  3305. /* Called when our internal view of the directory has changed. We might have
  3306. * received a new batch of descriptors which might affect the shape of the
  3307. * HSDir hash ring. Signal that we should reexamine the hash ring and
  3308. * re-upload our HS descriptors if needed. */
  3309. void
  3310. hs_service_dir_info_changed(void)
  3311. {
  3312. if (hs_service_get_num_services() > 0) {
  3313. /* New directory information usually goes every consensus so rate limit
  3314. * every 30 minutes to not be too conservative. */
  3315. static struct ratelim_t dir_info_changed_ratelim = RATELIM_INIT(30 * 60);
  3316. log_fn_ratelim(&dir_info_changed_ratelim, LOG_INFO, LD_REND,
  3317. "New dirinfo arrived: consider reuploading descriptor");
  3318. consider_republishing_hs_descriptors = 1;
  3319. }
  3320. }
  3321. /* Called when we get an INTRODUCE2 cell on the circ. Respond to the cell and
  3322. * launch a circuit to the rendezvous point. */
  3323. int
  3324. hs_service_receive_introduce2(origin_circuit_t *circ, const uint8_t *payload,
  3325. size_t payload_len)
  3326. {
  3327. int ret = -1;
  3328. tor_assert(circ);
  3329. tor_assert(payload);
  3330. /* Do some initial validation and logging before we parse the cell */
  3331. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  3332. log_warn(LD_PROTOCOL, "Received an INTRODUCE2 cell on a "
  3333. "non introduction circuit of purpose %d",
  3334. TO_CIRCUIT(circ)->purpose);
  3335. goto done;
  3336. }
  3337. if (circ->hs_ident) {
  3338. ret = service_handle_introduce2(circ, payload, payload_len);
  3339. hs_stats_note_introduce2_cell(1);
  3340. } else {
  3341. ret = rend_service_receive_introduction(circ, payload, payload_len);
  3342. hs_stats_note_introduce2_cell(0);
  3343. }
  3344. done:
  3345. return ret;
  3346. }
  3347. /* Called when we get an INTRO_ESTABLISHED cell. Mark the circuit as an
  3348. * established introduction point. Return 0 on success else a negative value
  3349. * and the circuit is closed. */
  3350. int
  3351. hs_service_receive_intro_established(origin_circuit_t *circ,
  3352. const uint8_t *payload,
  3353. size_t payload_len)
  3354. {
  3355. int ret = -1;
  3356. tor_assert(circ);
  3357. tor_assert(payload);
  3358. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  3359. log_warn(LD_PROTOCOL, "Received an INTRO_ESTABLISHED cell on a "
  3360. "non introduction circuit of purpose %d",
  3361. TO_CIRCUIT(circ)->purpose);
  3362. goto err;
  3363. }
  3364. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  3365. * identifier hs_ident. Can't be both. */
  3366. if (circ->hs_ident) {
  3367. ret = service_handle_intro_established(circ, payload, payload_len);
  3368. } else {
  3369. ret = rend_service_intro_established(circ, payload, payload_len);
  3370. }
  3371. if (ret < 0) {
  3372. goto err;
  3373. }
  3374. return 0;
  3375. err:
  3376. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  3377. return -1;
  3378. }
  3379. /* Called when any kind of hidden service circuit is done building thus
  3380. * opened. This is the entry point from the circuit subsystem. */
  3381. void
  3382. hs_service_circuit_has_opened(origin_circuit_t *circ)
  3383. {
  3384. tor_assert(circ);
  3385. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  3386. * identifier hs_ident. Can't be both. */
  3387. switch (TO_CIRCUIT(circ)->purpose) {
  3388. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  3389. if (circ->hs_ident) {
  3390. service_intro_circ_has_opened(circ);
  3391. } else {
  3392. rend_service_intro_has_opened(circ);
  3393. }
  3394. break;
  3395. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  3396. if (circ->hs_ident) {
  3397. service_rendezvous_circ_has_opened(circ);
  3398. } else {
  3399. rend_service_rendezvous_has_opened(circ);
  3400. }
  3401. break;
  3402. default:
  3403. tor_assert(0);
  3404. }
  3405. }
  3406. /* Return the service version by looking at the key in the service directory.
  3407. * If the key is not found or unrecognized, -1 is returned. Else, the service
  3408. * version is returned. */
  3409. int
  3410. hs_service_get_version_from_key(const hs_service_t *service)
  3411. {
  3412. int version = -1; /* Unknown version. */
  3413. const char *directory_path;
  3414. tor_assert(service);
  3415. /* We'll try to load the key for version 3. If not found, we'll try version
  3416. * 2 and if not found, we'll send back an unknown version (-1). */
  3417. directory_path = service->config.directory_path;
  3418. /* Version 3 check. */
  3419. if (service_key_on_disk(directory_path)) {
  3420. version = HS_VERSION_THREE;
  3421. goto end;
  3422. }
  3423. /* Version 2 check. */
  3424. if (rend_service_key_on_disk(directory_path)) {
  3425. version = HS_VERSION_TWO;
  3426. goto end;
  3427. }
  3428. end:
  3429. return version;
  3430. }
  3431. /* Load and/or generate keys for all onion services including the client
  3432. * authorization if any. Return 0 on success, -1 on failure. */
  3433. int
  3434. hs_service_load_all_keys(void)
  3435. {
  3436. /* Load v2 service keys if we have v2. */
  3437. if (rend_num_services() != 0) {
  3438. if (rend_service_load_all_keys(NULL) < 0) {
  3439. goto err;
  3440. }
  3441. }
  3442. /* Load or/and generate them for v3+. */
  3443. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
  3444. /* Ignore ephemeral service, they already have their keys set. */
  3445. if (service->config.is_ephemeral) {
  3446. continue;
  3447. }
  3448. log_info(LD_REND, "Loading v3 onion service keys from %s",
  3449. service_escaped_dir(service));
  3450. if (load_service_keys(service) < 0) {
  3451. goto err;
  3452. }
  3453. } SMARTLIST_FOREACH_END(service);
  3454. /* Final step, the staging list contains service in a quiescent state that
  3455. * is ready to be used. Register them to the global map. Once this is over,
  3456. * the staging list will be cleaned up. */
  3457. register_all_services();
  3458. /* All keys have been loaded successfully. */
  3459. return 0;
  3460. err:
  3461. return -1;
  3462. }
  3463. /* Put all service object in the given service list. After this, the caller
  3464. * looses ownership of every elements in the list and responsible to free the
  3465. * list pointer. */
  3466. void
  3467. hs_service_stage_services(const smartlist_t *service_list)
  3468. {
  3469. tor_assert(service_list);
  3470. /* This list is freed at registration time but this function can be called
  3471. * multiple time. */
  3472. if (hs_service_staging_list == NULL) {
  3473. hs_service_staging_list = smartlist_new();
  3474. }
  3475. /* Add all service object to our staging list. Caller is responsible for
  3476. * freeing the service_list. */
  3477. smartlist_add_all(hs_service_staging_list, service_list);
  3478. }
  3479. /* Allocate and initilize a service object. The service configuration will
  3480. * contain the default values. Return the newly allocated object pointer. This
  3481. * function can't fail. */
  3482. hs_service_t *
  3483. hs_service_new(const or_options_t *options)
  3484. {
  3485. hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
  3486. /* Set default configuration value. */
  3487. set_service_default_config(&service->config, options);
  3488. /* Set the default service version. */
  3489. service->config.version = HS_SERVICE_DEFAULT_VERSION;
  3490. /* Allocate the CLIENT_PK replay cache in service state. */
  3491. service->state.replay_cache_rend_cookie =
  3492. replaycache_new(REND_REPLAY_TIME_INTERVAL, REND_REPLAY_TIME_INTERVAL);
  3493. return service;
  3494. }
  3495. /* Free the given <b>service</b> object and all its content. This function
  3496. * also takes care of wiping service keys from memory. It is safe to pass a
  3497. * NULL pointer. */
  3498. void
  3499. hs_service_free_(hs_service_t *service)
  3500. {
  3501. if (service == NULL) {
  3502. return;
  3503. }
  3504. /* Free descriptors. Go over both descriptor with this loop. */
  3505. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  3506. service_descriptor_free(desc);
  3507. } FOR_EACH_DESCRIPTOR_END;
  3508. /* Free service configuration. */
  3509. service_clear_config(&service->config);
  3510. /* Free replay cache from state. */
  3511. if (service->state.replay_cache_rend_cookie) {
  3512. replaycache_free(service->state.replay_cache_rend_cookie);
  3513. }
  3514. /* Wipe service keys. */
  3515. memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
  3516. tor_free(service);
  3517. }
  3518. /* Periodic callback. Entry point from the main loop to the HS service
  3519. * subsystem. This is call every second. This is skipped if tor can't build a
  3520. * circuit or the network is disabled. */
  3521. void
  3522. hs_service_run_scheduled_events(time_t now)
  3523. {
  3524. /* First thing we'll do here is to make sure our services are in a
  3525. * quiescent state for the scheduled events. */
  3526. run_housekeeping_event(now);
  3527. /* Order matters here. We first make sure the descriptor object for each
  3528. * service contains the latest data. Once done, we check if we need to open
  3529. * new introduction circuit. Finally, we try to upload the descriptor for
  3530. * each service. */
  3531. /* Make sure descriptors are up to date. */
  3532. run_build_descriptor_event(now);
  3533. /* Make sure services have enough circuits. */
  3534. run_build_circuit_event(now);
  3535. /* Upload the descriptors if needed/possible. */
  3536. run_upload_descriptor_event(now);
  3537. }
  3538. /* Initialize the service HS subsystem. */
  3539. void
  3540. hs_service_init(void)
  3541. {
  3542. /* Should never be called twice. */
  3543. tor_assert(!hs_service_map);
  3544. tor_assert(!hs_service_staging_list);
  3545. /* v2 specific. */
  3546. rend_service_init();
  3547. hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
  3548. HT_INIT(hs_service_ht, hs_service_map);
  3549. hs_service_staging_list = smartlist_new();
  3550. }
  3551. /* Release all global storage of the hidden service subsystem. */
  3552. void
  3553. hs_service_free_all(void)
  3554. {
  3555. rend_service_free_all();
  3556. service_free_all();
  3557. }
  3558. #ifdef TOR_UNIT_TESTS
  3559. /* Return the global service map size. Only used by unit test. */
  3560. STATIC unsigned int
  3561. get_hs_service_map_size(void)
  3562. {
  3563. return HT_SIZE(hs_service_map);
  3564. }
  3565. /* Return the staging list size. Only used by unit test. */
  3566. STATIC int
  3567. get_hs_service_staging_list_size(void)
  3568. {
  3569. return smartlist_len(hs_service_staging_list);
  3570. }
  3571. STATIC hs_service_ht *
  3572. get_hs_service_map(void)
  3573. {
  3574. return hs_service_map;
  3575. }
  3576. STATIC hs_service_t *
  3577. get_first_service(void)
  3578. {
  3579. hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
  3580. if (obj == NULL) {
  3581. return NULL;
  3582. }
  3583. return *obj;
  3584. }
  3585. #endif /* defined(TOR_UNIT_TESTS) */