hs_service.c 145 KB

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