hs_service.c 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307
  1. /* Copyright (c) 2016-2017, 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 "or.h"
  9. #include "circpathbias.h"
  10. #include "circuitbuild.h"
  11. #include "circuitlist.h"
  12. #include "circuituse.h"
  13. #include "config.h"
  14. #include "connection.h"
  15. #include "directory.h"
  16. #include "main.h"
  17. #include "networkstatus.h"
  18. #include "nodelist.h"
  19. #include "relay.h"
  20. #include "rendservice.h"
  21. #include "router.h"
  22. #include "routerkeys.h"
  23. #include "routerlist.h"
  24. #include "shared_random_state.h"
  25. #include "statefile.h"
  26. #include "hs_circuit.h"
  27. #include "hs_common.h"
  28. #include "hs_config.h"
  29. #include "hs_circuit.h"
  30. #include "hs_descriptor.h"
  31. #include "hs_ident.h"
  32. #include "hs_intropoint.h"
  33. #include "hs_service.h"
  34. /* Trunnel */
  35. #include "ed25519_cert.h"
  36. #include "hs/cell_common.h"
  37. #include "hs/cell_establish_intro.h"
  38. /* Helper macro. Iterate over every service in the global map. The var is the
  39. * name of the service pointer. */
  40. #define FOR_EACH_SERVICE_BEGIN(var) \
  41. STMT_BEGIN \
  42. hs_service_t **var##_iter, *var; \
  43. HT_FOREACH(var##_iter, hs_service_ht, hs_service_map) { \
  44. var = *var##_iter;
  45. #define FOR_EACH_SERVICE_END } STMT_END ;
  46. /* Helper macro. Iterate over both current and previous descriptor of a
  47. * service. The var is the name of the descriptor pointer. This macro skips
  48. * any descriptor object of the service that is NULL. */
  49. #define FOR_EACH_DESCRIPTOR_BEGIN(service, var) \
  50. STMT_BEGIN \
  51. hs_service_descriptor_t *var; \
  52. for (int var ## _loop_idx = 0; var ## _loop_idx < 2; \
  53. ++var ## _loop_idx) { \
  54. (var ## _loop_idx == 0) ? (var = service->desc_current) : \
  55. (var = service->desc_next); \
  56. if (var == NULL) continue;
  57. #define FOR_EACH_DESCRIPTOR_END } STMT_END ;
  58. /* Onion service directory file names. */
  59. static const char fname_keyfile_prefix[] = "hs_ed25519";
  60. static const char fname_hostname[] = "hostname";
  61. static const char address_tld[] = "onion";
  62. /* Staging list of service object. When configuring service, we add them to
  63. * this list considered a staging area and they will get added to our global
  64. * map once the keys have been loaded. These two steps are seperated because
  65. * loading keys requires that we are an actual running tor process. */
  66. static smartlist_t *hs_service_staging_list;
  67. /** True if the list of available router descriptors might have changed which
  68. * might result in an altered hash ring. Check if the hash ring changed and
  69. * reupload if needed */
  70. static int consider_republishing_hs_descriptors = 0;
  71. static void set_descriptor_revision_counter(hs_descriptor_t *hs_desc);
  72. static void move_descriptors(hs_service_t *src, hs_service_t *dst);
  73. /* Helper: Function to compare two objects in the service map. Return 1 if the
  74. * two service have the same master public identity key. */
  75. static inline int
  76. hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
  77. {
  78. tor_assert(first);
  79. tor_assert(second);
  80. /* Simple key compare. */
  81. return ed25519_pubkey_eq(&first->keys.identity_pk,
  82. &second->keys.identity_pk);
  83. }
  84. /* Helper: Function for the service hash table code below. The key used is the
  85. * master public identity key which is ultimately the onion address. */
  86. static inline unsigned int
  87. hs_service_ht_hash(const hs_service_t *service)
  88. {
  89. tor_assert(service);
  90. return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
  91. sizeof(service->keys.identity_pk.pubkey));
  92. }
  93. /* This is _the_ global hash map of hidden services which indexed the service
  94. * contained in it by master public identity key which is roughly the onion
  95. * address of the service. */
  96. static struct hs_service_ht *hs_service_map;
  97. /* Register the service hash table. */
  98. HT_PROTOTYPE(hs_service_ht, /* Name of hashtable. */
  99. hs_service_t, /* Object contained in the map. */
  100. hs_service_node, /* The name of the HT_ENTRY member. */
  101. hs_service_ht_hash, /* Hashing function. */
  102. hs_service_ht_eq) /* Compare function for objects. */
  103. HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
  104. hs_service_ht_hash, hs_service_ht_eq,
  105. 0.6, tor_reallocarray, tor_free_)
  106. /* Query the given service map with a public key and return a service object
  107. * if found else NULL. It is also possible to set a directory path in the
  108. * search query. If pk is NULL, then it will be set to zero indicating the
  109. * hash table to compare the directory path instead. */
  110. STATIC hs_service_t *
  111. find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
  112. {
  113. hs_service_t dummy_service;
  114. tor_assert(map);
  115. tor_assert(pk);
  116. memset(&dummy_service, 0, sizeof(dummy_service));
  117. ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
  118. return HT_FIND(hs_service_ht, map, &dummy_service);
  119. }
  120. /* Register the given service in the given map. If the service already exists
  121. * in the map, -1 is returned. On success, 0 is returned and the service
  122. * ownership has been transfered to the global map. */
  123. STATIC int
  124. register_service(hs_service_ht *map, hs_service_t *service)
  125. {
  126. tor_assert(map);
  127. tor_assert(service);
  128. tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
  129. if (find_service(map, &service->keys.identity_pk)) {
  130. /* Existing service with the same key. Do not register it. */
  131. return -1;
  132. }
  133. /* Taking ownership of the object at this point. */
  134. HT_INSERT(hs_service_ht, map, service);
  135. return 0;
  136. }
  137. /* Remove a given service from the given map. If service is NULL or the
  138. * service key is unset, return gracefully. */
  139. STATIC void
  140. remove_service(hs_service_ht *map, hs_service_t *service)
  141. {
  142. hs_service_t *elm;
  143. tor_assert(map);
  144. /* Ignore if no service or key is zero. */
  145. if (BUG(service == NULL) ||
  146. BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
  147. return;
  148. }
  149. elm = HT_REMOVE(hs_service_ht, map, service);
  150. if (elm) {
  151. tor_assert(elm == service);
  152. } else {
  153. log_warn(LD_BUG, "Could not find service in the global map "
  154. "while removing service %s",
  155. escaped(service->config.directory_path));
  156. }
  157. }
  158. /* Set the default values for a service configuration object <b>c</b>. */
  159. static void
  160. set_service_default_config(hs_service_config_t *c,
  161. const or_options_t *options)
  162. {
  163. (void) options;
  164. tor_assert(c);
  165. c->ports = smartlist_new();
  166. c->directory_path = NULL;
  167. c->max_streams_per_rdv_circuit = 0;
  168. c->max_streams_close_circuit = 0;
  169. c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
  170. c->allow_unknown_ports = 0;
  171. c->is_single_onion = 0;
  172. c->dir_group_readable = 0;
  173. c->is_ephemeral = 0;
  174. }
  175. /* From a service configuration object config, clear everything from it
  176. * meaning free allocated pointers and reset the values. */
  177. static void
  178. service_clear_config(hs_service_config_t *config)
  179. {
  180. if (config == NULL) {
  181. return;
  182. }
  183. tor_free(config->directory_path);
  184. if (config->ports) {
  185. SMARTLIST_FOREACH(config->ports, rend_service_port_config_t *, p,
  186. rend_service_port_config_free(p););
  187. smartlist_free(config->ports);
  188. }
  189. memset(config, 0, sizeof(*config));
  190. }
  191. /* Return the lower bound of maximum INTRODUCE2 cells per circuit before we
  192. * rotate intro point (defined by a consensus parameter or the default
  193. * value). */
  194. static int32_t
  195. get_intro_point_min_introduce2(void)
  196. {
  197. /* The [0, 2147483647] range is quite large to accomodate anything we decide
  198. * in the future. */
  199. return networkstatus_get_param(NULL, "hs_intro_min_introduce2",
  200. INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  201. 0, INT32_MAX);
  202. }
  203. /* Return the upper bound of maximum INTRODUCE2 cells per circuit before we
  204. * rotate intro point (defined by a consensus parameter or the default
  205. * value). */
  206. static int32_t
  207. get_intro_point_max_introduce2(void)
  208. {
  209. /* The [0, 2147483647] range is quite large to accomodate anything we decide
  210. * in the future. */
  211. return networkstatus_get_param(NULL, "hs_intro_max_introduce2",
  212. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS,
  213. 0, INT32_MAX);
  214. }
  215. /* Return the minimum lifetime in seconds of an introduction point defined by a
  216. * consensus parameter or the default value. */
  217. static int32_t
  218. get_intro_point_min_lifetime(void)
  219. {
  220. #define MIN_INTRO_POINT_LIFETIME_TESTING 10
  221. if (get_options()->TestingTorNetwork) {
  222. return MIN_INTRO_POINT_LIFETIME_TESTING;
  223. }
  224. /* The [0, 2147483647] range is quite large to accomodate anything we decide
  225. * in the future. */
  226. return networkstatus_get_param(NULL, "hs_intro_min_lifetime",
  227. INTRO_POINT_LIFETIME_MIN_SECONDS,
  228. 0, INT32_MAX);
  229. }
  230. /* Return the maximum lifetime in seconds of an introduction point defined by a
  231. * consensus parameter or the default value. */
  232. static int32_t
  233. get_intro_point_max_lifetime(void)
  234. {
  235. #define MAX_INTRO_POINT_LIFETIME_TESTING 30
  236. if (get_options()->TestingTorNetwork) {
  237. return MAX_INTRO_POINT_LIFETIME_TESTING;
  238. }
  239. /* The [0, 2147483647] range is quite large to accomodate anything we decide
  240. * in the future. */
  241. return networkstatus_get_param(NULL, "hs_intro_max_lifetime",
  242. INTRO_POINT_LIFETIME_MAX_SECONDS,
  243. 0, INT32_MAX);
  244. }
  245. /* Return the number of extra introduction point defined by a consensus
  246. * parameter or the default value. */
  247. static int32_t
  248. get_intro_point_num_extra(void)
  249. {
  250. /* The [0, 128] range bounds the number of extra introduction point allowed.
  251. * Above 128 intro points, it's getting a bit crazy. */
  252. return networkstatus_get_param(NULL, "hs_intro_num_extra",
  253. NUM_INTRO_POINTS_EXTRA, 0, 128);
  254. }
  255. /* Helper: Function that needs to return 1 for the HT for each loop which
  256. * frees every service in an hash map. */
  257. static int
  258. ht_free_service_(struct hs_service_t *service, void *data)
  259. {
  260. (void) data;
  261. hs_service_free(service);
  262. /* This function MUST return 1 so the given object is then removed from the
  263. * service map leading to this free of the object being safe. */
  264. return 1;
  265. }
  266. /* Free every service that can be found in the global map. Once done, clear
  267. * and free the global map. */
  268. static void
  269. service_free_all(void)
  270. {
  271. if (hs_service_map) {
  272. /* The free helper function returns 1 so this is safe. */
  273. hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
  274. HT_CLEAR(hs_service_ht, hs_service_map);
  275. tor_free(hs_service_map);
  276. hs_service_map = NULL;
  277. }
  278. if (hs_service_staging_list) {
  279. /* Cleanup staging list. */
  280. SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
  281. hs_service_free(s));
  282. smartlist_free(hs_service_staging_list);
  283. hs_service_staging_list = NULL;
  284. }
  285. }
  286. /* Free a given service intro point object. */
  287. STATIC void
  288. service_intro_point_free(hs_service_intro_point_t *ip)
  289. {
  290. if (!ip) {
  291. return;
  292. }
  293. memwipe(&ip->auth_key_kp, 0, sizeof(ip->auth_key_kp));
  294. memwipe(&ip->enc_key_kp, 0, sizeof(ip->enc_key_kp));
  295. crypto_pk_free(ip->legacy_key);
  296. replaycache_free(ip->replay_cache);
  297. hs_intropoint_clear(&ip->base);
  298. tor_free(ip);
  299. }
  300. /* Helper: free an hs_service_intro_point_t object. This function is used by
  301. * digest256map_free() which requires a void * pointer. */
  302. static void
  303. service_intro_point_free_(void *obj)
  304. {
  305. service_intro_point_free(obj);
  306. }
  307. /* Return a newly allocated service intro point and fully initialized from the
  308. * given extend_info_t ei if non NULL. If is_legacy is true, we also generate
  309. * the legacy key. On error, NULL is returned. */
  310. STATIC hs_service_intro_point_t *
  311. service_intro_point_new(const extend_info_t *ei, unsigned int is_legacy)
  312. {
  313. hs_desc_link_specifier_t *ls;
  314. hs_service_intro_point_t *ip;
  315. ip = tor_malloc_zero(sizeof(*ip));
  316. /* We'll create the key material. No need for extra strong, those are short
  317. * term keys. */
  318. ed25519_keypair_generate(&ip->auth_key_kp, 0);
  319. { /* Set introduce2 max cells limit */
  320. int32_t min_introduce2_cells = get_intro_point_min_introduce2();
  321. int32_t max_introduce2_cells = get_intro_point_max_introduce2();
  322. if (BUG(max_introduce2_cells < min_introduce2_cells)) {
  323. goto err;
  324. }
  325. ip->introduce2_max = crypto_rand_int_range(min_introduce2_cells,
  326. max_introduce2_cells);
  327. }
  328. { /* Set intro point lifetime */
  329. int32_t intro_point_min_lifetime = get_intro_point_min_lifetime();
  330. int32_t intro_point_max_lifetime = get_intro_point_max_lifetime();
  331. if (BUG(intro_point_max_lifetime < intro_point_min_lifetime)) {
  332. goto err;
  333. }
  334. ip->time_to_expire = time(NULL) +
  335. crypto_rand_int_range(intro_point_min_lifetime,intro_point_max_lifetime);
  336. }
  337. ip->replay_cache = replaycache_new(0, 0);
  338. /* Initialize the base object. We don't need the certificate object. */
  339. ip->base.link_specifiers = smartlist_new();
  340. /* Generate the encryption key for this intro point. */
  341. curve25519_keypair_generate(&ip->enc_key_kp, 0);
  342. /* Figure out if this chosen node supports v3 or is legacy only. */
  343. if (is_legacy) {
  344. ip->base.is_only_legacy = 1;
  345. /* Legacy mode that is doesn't support v3+ with ed25519 auth key. */
  346. ip->legacy_key = crypto_pk_new();
  347. if (crypto_pk_generate_key(ip->legacy_key) < 0) {
  348. goto err;
  349. }
  350. }
  351. if (ei == NULL) {
  352. goto done;
  353. }
  354. /* We'll try to add all link specifier. Legacy, IPv4 and ed25519 are
  355. * mandatory. */
  356. ls = hs_desc_link_specifier_new(ei, LS_IPV4);
  357. /* It is impossible to have an extend info object without a v4. */
  358. if (BUG(!ls)) {
  359. goto err;
  360. }
  361. smartlist_add(ip->base.link_specifiers, ls);
  362. ls = hs_desc_link_specifier_new(ei, LS_LEGACY_ID);
  363. /* It is impossible to have an extend info object without an identity
  364. * digest. */
  365. if (BUG(!ls)) {
  366. goto err;
  367. }
  368. smartlist_add(ip->base.link_specifiers, ls);
  369. /* ed25519 identity key is optional for intro points */
  370. ls = hs_desc_link_specifier_new(ei, LS_ED25519_ID);
  371. if (ls) {
  372. smartlist_add(ip->base.link_specifiers, ls);
  373. }
  374. /* IPv6 is optional. */
  375. ls = hs_desc_link_specifier_new(ei, LS_IPV6);
  376. if (ls) {
  377. smartlist_add(ip->base.link_specifiers, ls);
  378. }
  379. /* Finally, copy onion key from the extend_info_t object. */
  380. memcpy(&ip->onion_key, &ei->curve25519_onion_key, sizeof(ip->onion_key));
  381. done:
  382. return ip;
  383. err:
  384. service_intro_point_free(ip);
  385. return NULL;
  386. }
  387. /* Add the given intro point object to the given intro point map. The intro
  388. * point MUST have its RSA encryption key set if this is a legacy type or the
  389. * authentication key set otherwise. */
  390. STATIC void
  391. service_intro_point_add(digest256map_t *map, hs_service_intro_point_t *ip)
  392. {
  393. hs_service_intro_point_t *old_ip_entry;
  394. tor_assert(map);
  395. tor_assert(ip);
  396. old_ip_entry = digest256map_set(map, ip->auth_key_kp.pubkey.pubkey, ip);
  397. /* Make sure we didn't just try to double-add an intro point */
  398. tor_assert_nonfatal(!old_ip_entry);
  399. }
  400. /* For a given service, remove the intro point from that service's descriptors
  401. * (check both current and next descriptor) */
  402. STATIC void
  403. service_intro_point_remove(const hs_service_t *service,
  404. const hs_service_intro_point_t *ip)
  405. {
  406. tor_assert(service);
  407. tor_assert(ip);
  408. /* Trying all descriptors. */
  409. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  410. /* We'll try to remove the descriptor on both descriptors which is not
  411. * very expensive to do instead of doing loopup + remove. */
  412. digest256map_remove(desc->intro_points.map,
  413. ip->auth_key_kp.pubkey.pubkey);
  414. } FOR_EACH_DESCRIPTOR_END;
  415. }
  416. /* For a given service and authentication key, return the intro point or NULL
  417. * if not found. This will check both descriptors in the service. */
  418. STATIC hs_service_intro_point_t *
  419. service_intro_point_find(const hs_service_t *service,
  420. const ed25519_public_key_t *auth_key)
  421. {
  422. hs_service_intro_point_t *ip = NULL;
  423. tor_assert(service);
  424. tor_assert(auth_key);
  425. /* Trying all descriptors to find the right intro point.
  426. *
  427. * Even if we use the same node as intro point in both descriptors, the node
  428. * will have a different intro auth key for each descriptor since we generate
  429. * a new one everytime we pick an intro point.
  430. *
  431. * After #22893 gets implemented, intro points will be moved to be
  432. * per-service instead of per-descriptor so this function will need to
  433. * change.
  434. */
  435. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  436. if ((ip = digest256map_get(desc->intro_points.map,
  437. auth_key->pubkey)) != NULL) {
  438. break;
  439. }
  440. } FOR_EACH_DESCRIPTOR_END;
  441. return ip;
  442. }
  443. /* For a given service and intro point, return the descriptor for which the
  444. * intro point is assigned to. NULL is returned if not found. */
  445. STATIC hs_service_descriptor_t *
  446. service_desc_find_by_intro(const hs_service_t *service,
  447. const hs_service_intro_point_t *ip)
  448. {
  449. hs_service_descriptor_t *descp = NULL;
  450. tor_assert(service);
  451. tor_assert(ip);
  452. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  453. if (digest256map_get(desc->intro_points.map,
  454. ip->auth_key_kp.pubkey.pubkey)) {
  455. descp = desc;
  456. break;
  457. }
  458. } FOR_EACH_DESCRIPTOR_END;
  459. return descp;
  460. }
  461. /* From a circuit identifier, get all the possible objects associated with the
  462. * ident. If not NULL, service, ip or desc are set if the object can be found.
  463. * They are untouched if they can't be found.
  464. *
  465. * This is an helper function because we do those lookups often so it's more
  466. * convenient to simply call this functions to get all the things at once. */
  467. STATIC void
  468. get_objects_from_ident(const hs_ident_circuit_t *ident,
  469. hs_service_t **service, hs_service_intro_point_t **ip,
  470. hs_service_descriptor_t **desc)
  471. {
  472. hs_service_t *s;
  473. tor_assert(ident);
  474. /* Get service object from the circuit identifier. */
  475. s = find_service(hs_service_map, &ident->identity_pk);
  476. if (s && service) {
  477. *service = s;
  478. }
  479. /* From the service object, get the intro point object of that circuit. The
  480. * following will query both descriptors intro points list. */
  481. if (s && ip) {
  482. *ip = service_intro_point_find(s, &ident->intro_auth_pk);
  483. }
  484. /* Get the descriptor for this introduction point and service. */
  485. if (s && ip && *ip && desc) {
  486. *desc = service_desc_find_by_intro(s, *ip);
  487. }
  488. }
  489. /* From a given intro point, return the first link specifier of type
  490. * encountered in the link specifier list. Return NULL if it can't be found.
  491. *
  492. * The caller does NOT have ownership of the object, the intro point does. */
  493. static hs_desc_link_specifier_t *
  494. get_link_spec_by_type(const hs_service_intro_point_t *ip, uint8_t type)
  495. {
  496. hs_desc_link_specifier_t *lnk_spec = NULL;
  497. tor_assert(ip);
  498. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  499. hs_desc_link_specifier_t *, ls) {
  500. if (ls->type == type) {
  501. lnk_spec = ls;
  502. goto end;
  503. }
  504. } SMARTLIST_FOREACH_END(ls);
  505. end:
  506. return lnk_spec;
  507. }
  508. /* Given a service intro point, return the node_t associated to it. This can
  509. * return NULL if the given intro point has no legacy ID or if the node can't
  510. * be found in the consensus. */
  511. STATIC const node_t *
  512. get_node_from_intro_point(const hs_service_intro_point_t *ip)
  513. {
  514. const hs_desc_link_specifier_t *ls;
  515. tor_assert(ip);
  516. ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  517. if (BUG(!ls)) {
  518. return NULL;
  519. }
  520. /* XXX In the future, we want to only use the ed25519 ID (#22173). */
  521. return node_get_by_id((const char *) ls->u.legacy_id);
  522. }
  523. /* Given a service intro point, return the extend_info_t for it. This can
  524. * return NULL if the node can't be found for the intro point or the extend
  525. * info can't be created for the found node. If direct_conn is set, the extend
  526. * info is validated on if we can connect directly. */
  527. static extend_info_t *
  528. get_extend_info_from_intro_point(const hs_service_intro_point_t *ip,
  529. unsigned int direct_conn)
  530. {
  531. extend_info_t *info = NULL;
  532. const node_t *node;
  533. tor_assert(ip);
  534. node = get_node_from_intro_point(ip);
  535. if (node == NULL) {
  536. /* This can happen if the relay serving as intro point has been removed
  537. * from the consensus. In that case, the intro point will be removed from
  538. * the descriptor during the scheduled events. */
  539. goto end;
  540. }
  541. /* In the case of a direct connection (single onion service), it is possible
  542. * our firewall policy won't allow it so this can return a NULL value. */
  543. info = extend_info_from_node(node, direct_conn);
  544. end:
  545. return info;
  546. }
  547. /* Return the number of introduction points that are established for the
  548. * given descriptor. */
  549. static unsigned int
  550. count_desc_circuit_established(const hs_service_descriptor_t *desc)
  551. {
  552. unsigned int count = 0;
  553. tor_assert(desc);
  554. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  555. const hs_service_intro_point_t *, ip) {
  556. count += ip->circuit_established;
  557. } DIGEST256MAP_FOREACH_END;
  558. return count;
  559. }
  560. /* For a given service and descriptor of that service, close all active
  561. * directory connections. */
  562. static void
  563. close_directory_connections(const hs_service_t *service,
  564. const hs_service_descriptor_t *desc)
  565. {
  566. unsigned int count = 0;
  567. smartlist_t *dir_conns;
  568. tor_assert(service);
  569. tor_assert(desc);
  570. /* Close pending HS desc upload connections for the blinded key of 'desc'. */
  571. dir_conns = connection_list_by_type_purpose(CONN_TYPE_DIR,
  572. DIR_PURPOSE_UPLOAD_HSDESC);
  573. SMARTLIST_FOREACH_BEGIN(dir_conns, connection_t *, conn) {
  574. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  575. if (ed25519_pubkey_eq(&dir_conn->hs_ident->identity_pk,
  576. &service->keys.identity_pk) &&
  577. ed25519_pubkey_eq(&dir_conn->hs_ident->blinded_pk,
  578. &desc->blinded_kp.pubkey)) {
  579. connection_mark_for_close(conn);
  580. count++;
  581. continue;
  582. }
  583. } SMARTLIST_FOREACH_END(conn);
  584. log_info(LD_REND, "Closed %u active service directory connections for "
  585. "descriptor %s of service %s",
  586. count, safe_str_client(ed25519_fmt(&desc->blinded_kp.pubkey)),
  587. safe_str_client(service->onion_address));
  588. /* We don't have ownership of the objects in this list. */
  589. smartlist_free(dir_conns);
  590. }
  591. /* Close all rendezvous circuits for the given service. */
  592. static void
  593. close_service_rp_circuits(hs_service_t *service)
  594. {
  595. origin_circuit_t *ocirc = NULL;
  596. tor_assert(service);
  597. /* The reason we go over all circuit instead of using the circuitmap API is
  598. * because most hidden service circuits are rendezvous circuits so there is
  599. * no real improvement at getting all rendezvous circuits from the
  600. * circuitmap and then going over them all to find the right ones.
  601. * Furthermore, another option would have been to keep a list of RP cookies
  602. * for a service but it creates an engineering complexity since we don't
  603. * have a "RP circuit closed" event to clean it up properly so we avoid a
  604. * memory DoS possibility. */
  605. while ((ocirc = circuit_get_next_service_rp_circ(ocirc))) {
  606. /* Only close circuits that are v3 and for this service. */
  607. if (ocirc->hs_ident != NULL &&
  608. ed25519_pubkey_eq(&ocirc->hs_ident->identity_pk,
  609. &service->keys.identity_pk)) {
  610. /* Reason is FINISHED because service has been removed and thus the
  611. * circuit is considered old/uneeded. When freed, it is removed from the
  612. * hs circuitmap. */
  613. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  614. }
  615. }
  616. }
  617. /* Close the circuit(s) for the given map of introduction points. */
  618. static void
  619. close_intro_circuits(hs_service_intropoints_t *intro_points)
  620. {
  621. tor_assert(intro_points);
  622. DIGEST256MAP_FOREACH(intro_points->map, key,
  623. const hs_service_intro_point_t *, ip) {
  624. origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
  625. if (ocirc) {
  626. /* Reason is FINISHED because service has been removed and thus the
  627. * circuit is considered old/uneeded. When freed, the circuit is removed
  628. * from the HS circuitmap. */
  629. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  630. }
  631. } DIGEST256MAP_FOREACH_END;
  632. }
  633. /* Close all introduction circuits for the given service. */
  634. static void
  635. close_service_intro_circuits(hs_service_t *service)
  636. {
  637. tor_assert(service);
  638. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  639. close_intro_circuits(&desc->intro_points);
  640. } FOR_EACH_DESCRIPTOR_END;
  641. }
  642. /* Close any circuits related to the given service. */
  643. static void
  644. close_service_circuits(hs_service_t *service)
  645. {
  646. tor_assert(service);
  647. /* Only support for version >= 3. */
  648. if (BUG(service->config.version < HS_VERSION_THREE)) {
  649. return;
  650. }
  651. /* Close intro points. */
  652. close_service_intro_circuits(service);
  653. /* Close rendezvous points. */
  654. close_service_rp_circuits(service);
  655. }
  656. /* Move every ephemeral services from the src service map to the dst service
  657. * map. It is possible that a service can't be register to the dst map which
  658. * won't stop the process of moving them all but will trigger a log warn. */
  659. static void
  660. move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
  661. {
  662. hs_service_t **iter, **next;
  663. tor_assert(src);
  664. tor_assert(dst);
  665. /* Iterate over the map to find ephemeral service and move them to the other
  666. * map. We loop using this method to have a safe removal process. */
  667. for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
  668. hs_service_t *s = *iter;
  669. if (!s->config.is_ephemeral) {
  670. /* Yeah, we are in a very manual loop :). */
  671. next = HT_NEXT(hs_service_ht, src, iter);
  672. continue;
  673. }
  674. /* Remove service from map and then register to it to the other map.
  675. * Reminder that "*iter" and "s" are the same thing. */
  676. next = HT_NEXT_RMV(hs_service_ht, src, iter);
  677. if (register_service(dst, s) < 0) {
  678. log_warn(LD_BUG, "Ephemeral service key is already being used. "
  679. "Skipping.");
  680. }
  681. }
  682. }
  683. /* Return a const string of the directory path escaped. If this is an
  684. * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
  685. * the main thread because escaped() uses a static variable. */
  686. static const char *
  687. service_escaped_dir(const hs_service_t *s)
  688. {
  689. return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
  690. escaped(s->config.directory_path);
  691. }
  692. /** Move the hidden service state from <b>src</b> to <b>dst</b>. We do this
  693. * when we receive a SIGHUP: <b>dst</b> is the post-HUP service */
  694. static void
  695. move_hs_state(hs_service_t *src_service, hs_service_t *dst_service)
  696. {
  697. tor_assert(src_service);
  698. tor_assert(dst_service);
  699. hs_service_state_t *src = &src_service->state;
  700. hs_service_state_t *dst = &dst_service->state;
  701. /* Let's do a shallow copy */
  702. dst->intro_circ_retry_started_time = src->intro_circ_retry_started_time;
  703. dst->num_intro_circ_launched = src->num_intro_circ_launched;
  704. dst->replay_cache_rend_cookie = src->replay_cache_rend_cookie;
  705. src->replay_cache_rend_cookie = NULL; /* steal pointer reference */
  706. }
  707. /* Register services that are in the staging list. Once this function returns,
  708. * the global service map will be set with the right content and all non
  709. * surviving services will be cleaned up. */
  710. static void
  711. register_all_services(void)
  712. {
  713. struct hs_service_ht *new_service_map;
  714. tor_assert(hs_service_staging_list);
  715. /* We'll save us some allocation and computing time. */
  716. if (smartlist_len(hs_service_staging_list) == 0) {
  717. return;
  718. }
  719. /* Allocate a new map that will replace the current one. */
  720. new_service_map = tor_malloc_zero(sizeof(*new_service_map));
  721. HT_INIT(hs_service_ht, new_service_map);
  722. /* First step is to transfer all ephemeral services from the current global
  723. * map to the new one we are constructing. We do not prune ephemeral
  724. * services as the only way to kill them is by deleting it from the control
  725. * port or stopping the tor daemon. */
  726. move_ephemeral_services(hs_service_map, new_service_map);
  727. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
  728. hs_service_t *s;
  729. /* Check if that service is already in our global map and if so, we'll
  730. * transfer the intro points to it. */
  731. s = find_service(hs_service_map, &snew->keys.identity_pk);
  732. if (s) {
  733. /* Pass ownership of the descriptors from s (the current service) to
  734. * snew (the newly configured one). */
  735. move_descriptors(s, snew);
  736. move_hs_state(s, snew);
  737. /* Remove the service from the global map because after this, we need to
  738. * go over the remaining service in that map that aren't surviving the
  739. * reload to close their circuits. */
  740. remove_service(hs_service_map, s);
  741. hs_service_free(s);
  742. }
  743. /* Great, this service is now ready to be added to our new map. */
  744. if (BUG(register_service(new_service_map, snew) < 0)) {
  745. /* This should never happen because prior to registration, we validate
  746. * every service against the entire set. Not being able to register a
  747. * service means we failed to validate correctly. In that case, don't
  748. * break tor and ignore the service but tell user. */
  749. log_warn(LD_BUG, "Unable to register service with directory %s",
  750. service_escaped_dir(snew));
  751. SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
  752. hs_service_free(snew);
  753. }
  754. } SMARTLIST_FOREACH_END(snew);
  755. /* Close any circuits associated with the non surviving services. Every
  756. * service in the current global map are roaming. */
  757. FOR_EACH_SERVICE_BEGIN(service) {
  758. close_service_circuits(service);
  759. } FOR_EACH_SERVICE_END;
  760. /* Time to make the switch. We'll clear the staging list because its content
  761. * has now changed ownership to the map. */
  762. smartlist_clear(hs_service_staging_list);
  763. service_free_all();
  764. hs_service_map = new_service_map;
  765. }
  766. /* Write the onion address of a given service to the given filename fname_ in
  767. * the service directory. Return 0 on success else -1 on error. */
  768. STATIC int
  769. write_address_to_file(const hs_service_t *service, const char *fname_)
  770. {
  771. int ret = -1;
  772. char *fname = NULL;
  773. char *addr_buf = NULL;
  774. tor_assert(service);
  775. tor_assert(fname_);
  776. /* Construct the full address with the onion tld and write the hostname file
  777. * to disk. */
  778. tor_asprintf(&addr_buf, "%s.%s\n", service->onion_address, address_tld);
  779. /* Notice here that we use the given "fname_". */
  780. fname = hs_path_from_filename(service->config.directory_path, fname_);
  781. if (write_str_to_file(fname, addr_buf, 0) < 0) {
  782. log_warn(LD_REND, "Could not write onion address to hostname file %s",
  783. escaped(fname));
  784. goto end;
  785. }
  786. #ifndef _WIN32
  787. if (service->config.dir_group_readable) {
  788. /* Mode to 0640. */
  789. if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
  790. log_warn(LD_FS, "Unable to make onion service hostname file %s "
  791. "group-readable.", escaped(fname));
  792. }
  793. }
  794. #endif /* _WIN32 */
  795. /* Success. */
  796. ret = 0;
  797. end:
  798. tor_free(fname);
  799. tor_free(addr_buf);
  800. return ret;
  801. }
  802. /* Load and/or generate private keys for the given service. On success, the
  803. * hostname file will be written to disk along with the master private key iff
  804. * the service is not configured for offline keys. Return 0 on success else -1
  805. * on failure. */
  806. static int
  807. load_service_keys(hs_service_t *service)
  808. {
  809. int ret = -1;
  810. char *fname = NULL;
  811. ed25519_keypair_t *kp;
  812. const hs_service_config_t *config;
  813. tor_assert(service);
  814. config = &service->config;
  815. /* Create and fix permission on service directory. We are about to write
  816. * files to that directory so make sure it exists and has the right
  817. * permissions. We do this here because at this stage we know that Tor is
  818. * actually running and the service we have has been validated. */
  819. if (BUG(hs_check_service_private_dir(get_options()->User,
  820. config->directory_path,
  821. config->dir_group_readable, 1) < 0)) {
  822. goto end;
  823. }
  824. /* Try to load the keys from file or generate it if not found. */
  825. fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
  826. /* Don't ask for key creation, we want to know if we were able to load it or
  827. * we had to generate it. Better logging! */
  828. kp = ed_key_init_from_file(fname, 0, LOG_INFO, NULL, 0, 0, 0, NULL);
  829. if (!kp) {
  830. log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
  831. /* We'll now try to generate the keys and for it we want the strongest
  832. * randomness for it. The keypair will be written in different files. */
  833. uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
  834. INIT_ED_KEY_SPLIT;
  835. kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
  836. NULL);
  837. if (!kp) {
  838. log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
  839. goto end;
  840. }
  841. }
  842. /* Copy loaded or generated keys to service object. */
  843. ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
  844. memcpy(&service->keys.identity_sk, &kp->seckey,
  845. sizeof(service->keys.identity_sk));
  846. /* This does a proper memory wipe. */
  847. ed25519_keypair_free(kp);
  848. /* Build onion address from the newly loaded keys. */
  849. tor_assert(service->config.version <= UINT8_MAX);
  850. hs_build_address(&service->keys.identity_pk,
  851. (uint8_t) service->config.version,
  852. service->onion_address);
  853. /* Write onion address to hostname file. */
  854. if (write_address_to_file(service, fname_hostname) < 0) {
  855. goto end;
  856. }
  857. /* Succes. */
  858. ret = 0;
  859. end:
  860. tor_free(fname);
  861. return ret;
  862. }
  863. /* Free a given service descriptor object and all key material is wiped. */
  864. STATIC void
  865. service_descriptor_free(hs_service_descriptor_t *desc)
  866. {
  867. if (!desc) {
  868. return;
  869. }
  870. hs_descriptor_free(desc->desc);
  871. memwipe(&desc->signing_kp, 0, sizeof(desc->signing_kp));
  872. memwipe(&desc->blinded_kp, 0, sizeof(desc->blinded_kp));
  873. /* Cleanup all intro points. */
  874. digest256map_free(desc->intro_points.map, service_intro_point_free_);
  875. digestmap_free(desc->intro_points.failed_id, tor_free_);
  876. if (desc->previous_hsdirs) {
  877. SMARTLIST_FOREACH(desc->previous_hsdirs, char *, s, tor_free(s));
  878. smartlist_free(desc->previous_hsdirs);
  879. }
  880. tor_free(desc);
  881. }
  882. /* Return a newly allocated service descriptor object. */
  883. STATIC hs_service_descriptor_t *
  884. service_descriptor_new(void)
  885. {
  886. hs_service_descriptor_t *sdesc = tor_malloc_zero(sizeof(*sdesc));
  887. sdesc->desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  888. /* Initialize the intro points map. */
  889. sdesc->intro_points.map = digest256map_new();
  890. sdesc->intro_points.failed_id = digestmap_new();
  891. sdesc->previous_hsdirs = smartlist_new();
  892. return sdesc;
  893. }
  894. /* Move descriptor(s) from the src service to the dst service. We do this
  895. * during SIGHUP when we re-create our hidden services. */
  896. static void
  897. move_descriptors(hs_service_t *src, hs_service_t *dst)
  898. {
  899. tor_assert(src);
  900. tor_assert(dst);
  901. if (src->desc_current) {
  902. /* Nothing should be there, but clean it up just in case */
  903. if (BUG(dst->desc_current)) {
  904. service_descriptor_free(dst->desc_current);
  905. }
  906. dst->desc_current = src->desc_current;
  907. src->desc_current = NULL;
  908. }
  909. if (src->desc_next) {
  910. /* Nothing should be there, but clean it up just in case */
  911. if (BUG(dst->desc_next)) {
  912. service_descriptor_free(dst->desc_next);
  913. }
  914. dst->desc_next = src->desc_next;
  915. src->desc_next = NULL;
  916. }
  917. }
  918. /* From the given service, remove all expired failing intro points for each
  919. * descriptor. */
  920. static void
  921. remove_expired_failing_intro(hs_service_t *service, time_t now)
  922. {
  923. tor_assert(service);
  924. /* For both descriptors, cleanup the failing intro points list. */
  925. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  926. DIGESTMAP_FOREACH_MODIFY(desc->intro_points.failed_id, key, time_t *, t) {
  927. time_t failure_time = *t;
  928. if ((failure_time + INTRO_CIRC_RETRY_PERIOD) <= now) {
  929. MAP_DEL_CURRENT(key);
  930. tor_free(t);
  931. }
  932. } DIGESTMAP_FOREACH_END;
  933. } FOR_EACH_DESCRIPTOR_END;
  934. }
  935. /* For the given descriptor desc, put all node_t object found from its failing
  936. * intro point list and put them in the given node_list. */
  937. static void
  938. setup_intro_point_exclude_list(const hs_service_descriptor_t *desc,
  939. smartlist_t *node_list)
  940. {
  941. tor_assert(desc);
  942. tor_assert(node_list);
  943. DIGESTMAP_FOREACH(desc->intro_points.failed_id, key, time_t *, t) {
  944. (void) t; /* Make gcc happy. */
  945. const node_t *node = node_get_by_id(key);
  946. if (node) {
  947. smartlist_add(node_list, (void *) node);
  948. }
  949. } DIGESTMAP_FOREACH_END;
  950. }
  951. /* For the given failing intro point ip, we add its time of failure to the
  952. * failed map and index it by identity digest (legacy ID) in the descriptor
  953. * desc failed id map. */
  954. static void
  955. remember_failing_intro_point(const hs_service_intro_point_t *ip,
  956. hs_service_descriptor_t *desc, time_t now)
  957. {
  958. time_t *time_of_failure, *prev_ptr;
  959. const hs_desc_link_specifier_t *legacy_ls;
  960. tor_assert(ip);
  961. tor_assert(desc);
  962. time_of_failure = tor_malloc_zero(sizeof(time_t));
  963. *time_of_failure = now;
  964. legacy_ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  965. tor_assert(legacy_ls);
  966. prev_ptr = digestmap_set(desc->intro_points.failed_id,
  967. (const char *) legacy_ls->u.legacy_id,
  968. time_of_failure);
  969. tor_free(prev_ptr);
  970. }
  971. /* Copy the descriptor link specifier object from src to dst. */
  972. static void
  973. link_specifier_copy(hs_desc_link_specifier_t *dst,
  974. const hs_desc_link_specifier_t *src)
  975. {
  976. tor_assert(dst);
  977. tor_assert(src);
  978. memcpy(dst, src, sizeof(hs_desc_link_specifier_t));
  979. }
  980. /* Using a given descriptor signing keypair signing_kp, a service intro point
  981. * object ip and the time now, setup the content of an already allocated
  982. * descriptor intro desc_ip.
  983. *
  984. * Return 0 on success else a negative value. */
  985. static int
  986. setup_desc_intro_point(const ed25519_keypair_t *signing_kp,
  987. const hs_service_intro_point_t *ip,
  988. time_t now, hs_desc_intro_point_t *desc_ip)
  989. {
  990. int ret = -1;
  991. time_t nearest_hour = now - (now % 3600);
  992. tor_assert(signing_kp);
  993. tor_assert(ip);
  994. tor_assert(desc_ip);
  995. /* Copy the onion key. */
  996. memcpy(&desc_ip->onion_key, &ip->onion_key, sizeof(desc_ip->onion_key));
  997. /* Key and certificate material. */
  998. desc_ip->auth_key_cert = tor_cert_create(signing_kp,
  999. CERT_TYPE_AUTH_HS_IP_KEY,
  1000. &ip->auth_key_kp.pubkey,
  1001. nearest_hour,
  1002. HS_DESC_CERT_LIFETIME,
  1003. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1004. if (desc_ip->auth_key_cert == NULL) {
  1005. log_warn(LD_REND, "Unable to create intro point auth-key certificate");
  1006. goto done;
  1007. }
  1008. /* Copy link specifier(s). */
  1009. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  1010. const hs_desc_link_specifier_t *, ls) {
  1011. hs_desc_link_specifier_t *dup = tor_malloc_zero(sizeof(*dup));
  1012. link_specifier_copy(dup, ls);
  1013. smartlist_add(desc_ip->link_specifiers, dup);
  1014. } SMARTLIST_FOREACH_END(ls);
  1015. /* For a legacy intro point, we'll use an RSA/ed cross certificate. */
  1016. if (ip->base.is_only_legacy) {
  1017. desc_ip->legacy.key = crypto_pk_dup_key(ip->legacy_key);
  1018. /* Create cross certification cert. */
  1019. ssize_t cert_len = tor_make_rsa_ed25519_crosscert(
  1020. &signing_kp->pubkey,
  1021. desc_ip->legacy.key,
  1022. nearest_hour + HS_DESC_CERT_LIFETIME,
  1023. &desc_ip->legacy.cert.encoded);
  1024. if (cert_len < 0) {
  1025. log_warn(LD_REND, "Unable to create enc key legacy cross cert.");
  1026. goto done;
  1027. }
  1028. desc_ip->legacy.cert.len = cert_len;
  1029. }
  1030. /* Encryption key and its cross certificate. */
  1031. {
  1032. ed25519_public_key_t ed25519_pubkey;
  1033. /* Use the public curve25519 key. */
  1034. memcpy(&desc_ip->enc_key, &ip->enc_key_kp.pubkey,
  1035. sizeof(desc_ip->enc_key));
  1036. /* The following can't fail. */
  1037. ed25519_public_key_from_curve25519_public_key(&ed25519_pubkey,
  1038. &ip->enc_key_kp.pubkey,
  1039. 0);
  1040. desc_ip->enc_key_cert = tor_cert_create(signing_kp,
  1041. CERT_TYPE_CROSS_HS_IP_KEYS,
  1042. &ed25519_pubkey, nearest_hour,
  1043. HS_DESC_CERT_LIFETIME,
  1044. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1045. if (desc_ip->enc_key_cert == NULL) {
  1046. log_warn(LD_REND, "Unable to create enc key curve25519 cross cert.");
  1047. goto done;
  1048. }
  1049. }
  1050. /* Success. */
  1051. ret = 0;
  1052. done:
  1053. return ret;
  1054. }
  1055. /* Using the given descriptor from the given service, build the descriptor
  1056. * intro point list so we can then encode the descriptor for publication. This
  1057. * function does not pick intro points, they have to be in the descriptor
  1058. * current map. Cryptographic material (keys) must be initialized in the
  1059. * descriptor for this function to make sense. */
  1060. static void
  1061. build_desc_intro_points(const hs_service_t *service,
  1062. hs_service_descriptor_t *desc, time_t now)
  1063. {
  1064. hs_desc_encrypted_data_t *encrypted;
  1065. tor_assert(service);
  1066. tor_assert(desc);
  1067. /* Ease our life. */
  1068. encrypted = &desc->desc->encrypted_data;
  1069. /* Cleanup intro points, we are about to set them from scratch. */
  1070. hs_descriptor_clear_intro_points(desc->desc);
  1071. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1072. const hs_service_intro_point_t *, ip) {
  1073. hs_desc_intro_point_t *desc_ip = hs_desc_intro_point_new();
  1074. if (setup_desc_intro_point(&desc->signing_kp, ip, now, desc_ip) < 0) {
  1075. hs_desc_intro_point_free(desc_ip);
  1076. continue;
  1077. }
  1078. /* We have a valid descriptor intro point. Add it to the list. */
  1079. smartlist_add(encrypted->intro_points, desc_ip);
  1080. } DIGEST256MAP_FOREACH_END;
  1081. }
  1082. /* Populate the descriptor encrypted section fomr the given service object.
  1083. * This will generate a valid list of introduction points that can be used
  1084. * after for circuit creation. Return 0 on success else -1 on error. */
  1085. static int
  1086. build_service_desc_encrypted(const hs_service_t *service,
  1087. hs_service_descriptor_t *desc)
  1088. {
  1089. hs_desc_encrypted_data_t *encrypted;
  1090. tor_assert(service);
  1091. tor_assert(desc);
  1092. encrypted = &desc->desc->encrypted_data;
  1093. encrypted->create2_ntor = 1;
  1094. encrypted->single_onion_service = service->config.is_single_onion;
  1095. /* Setup introduction points from what we have in the service. */
  1096. if (encrypted->intro_points == NULL) {
  1097. encrypted->intro_points = smartlist_new();
  1098. }
  1099. /* We do NOT build introduction point yet, we only do that once the circuit
  1100. * have been opened. Until we have the right number of introduction points,
  1101. * we do not encode anything in the descriptor. */
  1102. /* XXX: Support client authorization (#20700). */
  1103. encrypted->intro_auth_types = NULL;
  1104. return 0;
  1105. }
  1106. /* Populare the descriptor plaintext section from the given service object.
  1107. * The caller must make sure that the keys in the descriptors are valid that
  1108. * is are non-zero. Return 0 on success else -1 on error. */
  1109. static int
  1110. build_service_desc_plaintext(const hs_service_t *service,
  1111. hs_service_descriptor_t *desc, time_t now)
  1112. {
  1113. int ret = -1;
  1114. hs_desc_plaintext_data_t *plaintext;
  1115. tor_assert(service);
  1116. tor_assert(desc);
  1117. /* XXX: Use a "assert_desc_ok()" ? */
  1118. tor_assert(!tor_mem_is_zero((char *) &desc->blinded_kp,
  1119. sizeof(desc->blinded_kp)));
  1120. tor_assert(!tor_mem_is_zero((char *) &desc->signing_kp,
  1121. sizeof(desc->signing_kp)));
  1122. /* Set the subcredential. */
  1123. hs_get_subcredential(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
  1124. desc->desc->subcredential);
  1125. plaintext = &desc->desc->plaintext_data;
  1126. plaintext->version = service->config.version;
  1127. plaintext->lifetime_sec = HS_DESC_DEFAULT_LIFETIME;
  1128. plaintext->signing_key_cert =
  1129. tor_cert_create(&desc->blinded_kp, CERT_TYPE_SIGNING_HS_DESC,
  1130. &desc->signing_kp.pubkey, now, HS_DESC_CERT_LIFETIME,
  1131. CERT_FLAG_INCLUDE_SIGNING_KEY);
  1132. if (plaintext->signing_key_cert == NULL) {
  1133. log_warn(LD_REND, "Unable to create descriptor signing certificate for "
  1134. "service %s",
  1135. safe_str_client(service->onion_address));
  1136. goto end;
  1137. }
  1138. /* Copy public key material to go in the descriptor. */
  1139. ed25519_pubkey_copy(&plaintext->signing_pubkey, &desc->signing_kp.pubkey);
  1140. ed25519_pubkey_copy(&plaintext->blinded_pubkey, &desc->blinded_kp.pubkey);
  1141. /* Success. */
  1142. ret = 0;
  1143. end:
  1144. return ret;
  1145. }
  1146. /* For the given service and descriptor object, create the key material which
  1147. * is the blinded keypair and the descriptor signing keypair. Return 0 on
  1148. * success else -1 on error where the generated keys MUST be ignored. */
  1149. static int
  1150. build_service_desc_keys(const hs_service_t *service,
  1151. hs_service_descriptor_t *desc,
  1152. uint64_t time_period_num)
  1153. {
  1154. int ret = 0;
  1155. ed25519_keypair_t kp;
  1156. tor_assert(desc);
  1157. tor_assert(!tor_mem_is_zero((char *) &service->keys.identity_pk,
  1158. ED25519_PUBKEY_LEN));
  1159. /* XXX: Support offline key feature (#18098). */
  1160. /* Copy the identity keys to the keypair so we can use it to create the
  1161. * blinded key. */
  1162. memcpy(&kp.pubkey, &service->keys.identity_pk, sizeof(kp.pubkey));
  1163. memcpy(&kp.seckey, &service->keys.identity_sk, sizeof(kp.seckey));
  1164. /* Build blinded keypair for this time period. */
  1165. hs_build_blinded_keypair(&kp, NULL, 0, time_period_num, &desc->blinded_kp);
  1166. /* Let's not keep too much traces of our keys in memory. */
  1167. memwipe(&kp, 0, sizeof(kp));
  1168. /* No need for extra strong, this is a temporary key only for this
  1169. * descriptor. Nothing long term. */
  1170. if (ed25519_keypair_generate(&desc->signing_kp, 0) < 0) {
  1171. log_warn(LD_REND, "Can't generate descriptor signing keypair for "
  1172. "service %s",
  1173. safe_str_client(service->onion_address));
  1174. ret = -1;
  1175. }
  1176. return ret;
  1177. }
  1178. /* Given a service and the current time, build a descriptor for the service.
  1179. * This function does not pick introduction point, this needs to be done by
  1180. * the update function. On success, desc_out will point to the newly allocated
  1181. * descriptor object.
  1182. *
  1183. * This can error if we are unable to create keys or certificate. */
  1184. static void
  1185. build_service_descriptor(hs_service_t *service, time_t now,
  1186. uint64_t time_period_num,
  1187. hs_service_descriptor_t **desc_out)
  1188. {
  1189. char *encoded_desc;
  1190. hs_service_descriptor_t *desc;
  1191. tor_assert(service);
  1192. tor_assert(desc_out);
  1193. desc = service_descriptor_new();
  1194. desc->time_period_num = time_period_num;
  1195. /* Create the needed keys so we can setup the descriptor content. */
  1196. if (build_service_desc_keys(service, desc, time_period_num) < 0) {
  1197. goto err;
  1198. }
  1199. /* Setup plaintext descriptor content. */
  1200. if (build_service_desc_plaintext(service, desc, now) < 0) {
  1201. goto err;
  1202. }
  1203. /* Setup encrypted descriptor content. */
  1204. if (build_service_desc_encrypted(service, desc) < 0) {
  1205. goto err;
  1206. }
  1207. /* Set the revision counter for this descriptor */
  1208. set_descriptor_revision_counter(desc->desc);
  1209. /* Let's make sure that we've created a descriptor that can actually be
  1210. * encoded properly. This function also checks if the encoded output is
  1211. * decodable after. */
  1212. if (BUG(hs_desc_encode_descriptor(desc->desc, &desc->signing_kp,
  1213. &encoded_desc) < 0)) {
  1214. goto err;
  1215. }
  1216. tor_free(encoded_desc);
  1217. /* Assign newly built descriptor to the next slot. */
  1218. *desc_out = desc;
  1219. return;
  1220. err:
  1221. service_descriptor_free(desc);
  1222. }
  1223. /* Build both descriptors for the given service that has just booted up.
  1224. * Because it's a special case, it deserves its special function ;). */
  1225. static void
  1226. build_descriptors_for_new_service(hs_service_t *service, time_t now)
  1227. {
  1228. uint64_t current_desc_tp, next_desc_tp;
  1229. tor_assert(service);
  1230. /* These are the conditions for a new service. */
  1231. tor_assert(!service->desc_current);
  1232. tor_assert(!service->desc_next);
  1233. /*
  1234. * +------------------------------------------------------------------+
  1235. * | |
  1236. * | 00:00 12:00 00:00 12:00 00:00 12:00 |
  1237. * | SRV#1 TP#1 SRV#2 TP#2 SRV#3 TP#3 |
  1238. * | |
  1239. * | $==========|-----------$===========|-----------$===========| |
  1240. * | ^ ^ |
  1241. * | A B |
  1242. * +------------------------------------------------------------------+
  1243. *
  1244. * Case A: The service boots up before a new time period, the current time
  1245. * period is thus TP#1 and the next is TP#2 which for both we have access to
  1246. * their SRVs.
  1247. *
  1248. * Case B: The service boots up inside TP#2, we can't use the TP#3 for the
  1249. * next descriptor because we don't have the SRV#3 so the current should be
  1250. * TP#1 and next TP#2.
  1251. */
  1252. if (hs_in_period_between_tp_and_srv(NULL, now)) {
  1253. /* Case B from the above, inside of the new time period. */
  1254. current_desc_tp = hs_get_previous_time_period_num(0); /* TP#1 */
  1255. next_desc_tp = hs_get_time_period_num(0); /* TP#2 */
  1256. } else {
  1257. /* Case A from the above, outside of the new time period. */
  1258. current_desc_tp = hs_get_time_period_num(0); /* TP#1 */
  1259. next_desc_tp = hs_get_next_time_period_num(0); /* TP#2 */
  1260. }
  1261. /* Build descriptors. */
  1262. build_service_descriptor(service, now, current_desc_tp,
  1263. &service->desc_current);
  1264. build_service_descriptor(service, now, next_desc_tp,
  1265. &service->desc_next);
  1266. log_info(LD_REND, "Hidden service %s has just started. Both descriptors "
  1267. "built. Now scheduled for upload.",
  1268. safe_str_client(service->onion_address));
  1269. }
  1270. /* Build descriptors for each service if needed. There are conditions to build
  1271. * a descriptor which are details in the function. */
  1272. STATIC void
  1273. build_all_descriptors(time_t now)
  1274. {
  1275. FOR_EACH_SERVICE_BEGIN(service) {
  1276. /* A service booting up will have both descriptors to NULL. No other cases
  1277. * makes both descriptor non existent. */
  1278. if (service->desc_current == NULL && service->desc_next == NULL) {
  1279. build_descriptors_for_new_service(service, now);
  1280. continue;
  1281. }
  1282. /* Reaching this point means we are pass bootup so at runtime. We should
  1283. * *never* have an empty current descriptor. If the next descriptor is
  1284. * empty, we'll try to build it for the next time period. This only
  1285. * happens when we rotate meaning that we are guaranteed to have a new SRV
  1286. * at that point for the next time period. */
  1287. tor_assert(service->desc_current);
  1288. if (service->desc_next == NULL) {
  1289. build_service_descriptor(service, now, hs_get_next_time_period_num(0),
  1290. &service->desc_next);
  1291. log_info(LD_REND, "Hidden service %s next descriptor successfully "
  1292. "built. Now scheduled for upload.",
  1293. safe_str_client(service->onion_address));
  1294. }
  1295. } FOR_EACH_DESCRIPTOR_END;
  1296. }
  1297. /* Randomly pick a node to become an introduction point but not present in the
  1298. * given exclude_nodes list. The chosen node is put in the exclude list
  1299. * regardless of success or not because in case of failure, the node is simply
  1300. * unsusable from that point on. If direct_conn is set, try to pick a node
  1301. * that our local firewall/policy allows to directly connect to and if not,
  1302. * fallback to a normal 3-hop node. Return a newly allocated service intro
  1303. * point ready to be used for encoding. NULL on error. */
  1304. static hs_service_intro_point_t *
  1305. pick_intro_point(unsigned int direct_conn, smartlist_t *exclude_nodes)
  1306. {
  1307. const node_t *node;
  1308. extend_info_t *info = NULL;
  1309. hs_service_intro_point_t *ip = NULL;
  1310. /* Normal 3-hop introduction point flags. */
  1311. router_crn_flags_t flags = CRN_NEED_UPTIME | CRN_NEED_DESC;
  1312. /* Single onion flags. */
  1313. router_crn_flags_t direct_flags = flags | CRN_PREF_ADDR | CRN_DIRECT_CONN;
  1314. node = router_choose_random_node(exclude_nodes, get_options()->ExcludeNodes,
  1315. direct_conn ? direct_flags : flags);
  1316. if (node == NULL && direct_conn) {
  1317. /* Unable to find a node for direct connection, let's fall back to a
  1318. * normal 3-hop node. */
  1319. node = router_choose_random_node(exclude_nodes,
  1320. get_options()->ExcludeNodes, flags);
  1321. }
  1322. if (!node) {
  1323. goto err;
  1324. }
  1325. /* We have a suitable node, add it to the exclude list. We do this *before*
  1326. * we can validate the extend information because even in case of failure,
  1327. * we don't want to use that node anymore. */
  1328. smartlist_add(exclude_nodes, (void *) node);
  1329. /* We do this to ease our life but also this call makes appropriate checks
  1330. * of the node object such as validating ntor support for instance. */
  1331. info = extend_info_from_node(node, direct_conn);
  1332. if (BUG(info == NULL)) {
  1333. goto err;
  1334. }
  1335. /* Let's do a basic sanity check here so that we don't end up advertising the
  1336. * ed25519 identity key of relays that don't actually support the link
  1337. * protocol */
  1338. if (!node_supports_ed25519_link_authentication(node)) {
  1339. tor_assert_nonfatal(ed25519_public_key_is_zero(&info->ed_identity));
  1340. }
  1341. /* Create our objects and populate them with the node information. */
  1342. ip = service_intro_point_new(info, !node_supports_ed25519_hs_intro(node));
  1343. if (ip == NULL) {
  1344. goto err;
  1345. }
  1346. extend_info_free(info);
  1347. return ip;
  1348. err:
  1349. service_intro_point_free(ip);
  1350. extend_info_free(info);
  1351. return NULL;
  1352. }
  1353. /* For a given descriptor from the given service, pick any needed intro points
  1354. * and update the current map with those newly picked intro points. Return the
  1355. * number node that might have been added to the descriptor current map. */
  1356. static unsigned int
  1357. pick_needed_intro_points(hs_service_t *service,
  1358. hs_service_descriptor_t *desc)
  1359. {
  1360. int i = 0, num_needed_ip;
  1361. smartlist_t *exclude_nodes = smartlist_new();
  1362. tor_assert(service);
  1363. tor_assert(desc);
  1364. /* Compute how many intro points we actually need to open. */
  1365. num_needed_ip = service->config.num_intro_points -
  1366. digest256map_size(desc->intro_points.map);
  1367. if (BUG(num_needed_ip < 0)) {
  1368. /* Let's not make tor freak out here and just skip this. */
  1369. goto done;
  1370. }
  1371. /* We want to end up with config.num_intro_points intro points, but if we
  1372. * have no intro points at all (chances are they all cycled or we are
  1373. * starting up), we launch get_intro_point_num_extra() extra circuits and
  1374. * use the first config.num_intro_points that complete. See proposal #155,
  1375. * section 4 for the rationale of this which is purely for performance.
  1376. *
  1377. * The ones after the first config.num_intro_points will be converted to
  1378. * 'General' internal circuits and then we'll drop them from the list of
  1379. * intro points. */
  1380. if (digest256map_size(desc->intro_points.map) == 0) {
  1381. num_needed_ip += get_intro_point_num_extra();
  1382. }
  1383. /* Build an exclude list of nodes of our intro point(s). The expiring intro
  1384. * points are OK to pick again because this is afterall a concept of round
  1385. * robin so they are considered valid nodes to pick again. */
  1386. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1387. hs_service_intro_point_t *, ip) {
  1388. const node_t *intro_node = get_node_from_intro_point(ip);
  1389. if (intro_node) {
  1390. smartlist_add(exclude_nodes, (void*)intro_node);
  1391. }
  1392. } DIGEST256MAP_FOREACH_END;
  1393. /* Also, add the failing intro points that our descriptor encounteered in
  1394. * the exclude node list. */
  1395. setup_intro_point_exclude_list(desc, exclude_nodes);
  1396. for (i = 0; i < num_needed_ip; i++) {
  1397. hs_service_intro_point_t *ip;
  1398. /* This function will add the picked intro point node to the exclude nodes
  1399. * list so we don't pick the same one at the next iteration. */
  1400. ip = pick_intro_point(service->config.is_single_onion, exclude_nodes);
  1401. if (ip == NULL) {
  1402. /* If we end up unable to pick an introduction point it is because we
  1403. * can't find suitable node and calling this again is highly unlikely to
  1404. * give us a valid node all of the sudden. */
  1405. log_info(LD_REND, "Unable to find a suitable node to be an "
  1406. "introduction point for service %s.",
  1407. safe_str_client(service->onion_address));
  1408. goto done;
  1409. }
  1410. /* Valid intro point object, add it to the descriptor current map. */
  1411. service_intro_point_add(desc->intro_points.map, ip);
  1412. }
  1413. /* We've successfully picked all our needed intro points thus none are
  1414. * missing which will tell our upload process to expect the number of
  1415. * circuits to be the number of configured intro points circuits and not the
  1416. * number of intro points object that we have. */
  1417. desc->missing_intro_points = 0;
  1418. /* Success. */
  1419. done:
  1420. /* We don't have ownership of the node_t object in this list. */
  1421. smartlist_free(exclude_nodes);
  1422. return i;
  1423. }
  1424. /** Clear previous cached HSDirs in <b>desc</b>. */
  1425. static void
  1426. service_desc_clear_previous_hsdirs(hs_service_descriptor_t *desc)
  1427. {
  1428. if (BUG(!desc->previous_hsdirs)) {
  1429. return;
  1430. }
  1431. SMARTLIST_FOREACH(desc->previous_hsdirs, char*, s, tor_free(s));
  1432. smartlist_clear(desc->previous_hsdirs);
  1433. }
  1434. /** Note that we attempted to upload <b>desc</b> to <b>hsdir</b>. */
  1435. static void
  1436. service_desc_note_upload(hs_service_descriptor_t *desc, const node_t *hsdir)
  1437. {
  1438. char b64_digest[BASE64_DIGEST_LEN+1] = {0};
  1439. digest_to_base64(b64_digest, hsdir->identity);
  1440. if (BUG(!desc->previous_hsdirs)) {
  1441. return;
  1442. }
  1443. if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
  1444. smartlist_add_strdup(desc->previous_hsdirs, b64_digest);
  1445. }
  1446. }
  1447. /** Schedule an upload of <b>desc</b>. If <b>descriptor_changed</b> is set, it
  1448. * means that this descriptor is dirty. */
  1449. STATIC void
  1450. service_desc_schedule_upload(hs_service_descriptor_t *desc,
  1451. time_t now,
  1452. int descriptor_changed)
  1453. {
  1454. desc->next_upload_time = now;
  1455. /* If the descriptor changed, clean up the old HSDirs list. We want to
  1456. * re-upload no matter what. */
  1457. if (descriptor_changed) {
  1458. service_desc_clear_previous_hsdirs(desc);
  1459. }
  1460. }
  1461. /* Update the given descriptor from the given service. The possible update
  1462. * actions includes:
  1463. * - Picking missing intro points if needed.
  1464. * - Incrementing the revision counter if needed.
  1465. */
  1466. static void
  1467. update_service_descriptor(hs_service_t *service,
  1468. hs_service_descriptor_t *desc, time_t now)
  1469. {
  1470. unsigned int num_intro_points;
  1471. tor_assert(service);
  1472. tor_assert(desc);
  1473. tor_assert(desc->desc);
  1474. num_intro_points = digest256map_size(desc->intro_points.map);
  1475. /* Pick any missing introduction point(s). */
  1476. if (num_intro_points < service->config.num_intro_points) {
  1477. unsigned int num_new_intro_points = pick_needed_intro_points(service,
  1478. desc);
  1479. if (num_new_intro_points != 0) {
  1480. log_info(LD_REND, "Service %s just picked %u intro points and wanted "
  1481. "%u. It currently has %d intro points. "
  1482. "Launching ESTABLISH_INTRO circuit shortly.",
  1483. safe_str_client(service->onion_address),
  1484. num_new_intro_points,
  1485. service->config.num_intro_points - num_intro_points,
  1486. num_intro_points);
  1487. /* We'll build those introduction point into the descriptor once we have
  1488. * confirmation that the circuits are opened and ready. However,
  1489. * indicate that this descriptor should be uploaded from now on. */
  1490. service_desc_schedule_upload(desc, now, 1);
  1491. }
  1492. /* Were we able to pick all the intro points we needed? If not, we'll
  1493. * flag the descriptor that it's missing intro points because it
  1494. * couldn't pick enough which will trigger a descriptor upload. */
  1495. if ((num_new_intro_points + num_intro_points) <
  1496. service->config.num_intro_points) {
  1497. desc->missing_intro_points = 1;
  1498. }
  1499. }
  1500. }
  1501. /* Update descriptors for each service if needed. */
  1502. STATIC void
  1503. update_all_descriptors(time_t now)
  1504. {
  1505. FOR_EACH_SERVICE_BEGIN(service) {
  1506. /* We'll try to update each descriptor that is if certain conditions apply
  1507. * in order for the descriptor to be updated. */
  1508. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1509. update_service_descriptor(service, desc, now);
  1510. } FOR_EACH_DESCRIPTOR_END;
  1511. } FOR_EACH_SERVICE_END;
  1512. }
  1513. /* Return true iff the given intro point has expired that is it has been used
  1514. * for too long or we've reached our max seen INTRODUCE2 cell. */
  1515. STATIC int
  1516. intro_point_should_expire(const hs_service_intro_point_t *ip,
  1517. time_t now)
  1518. {
  1519. tor_assert(ip);
  1520. if (ip->introduce2_count >= ip->introduce2_max) {
  1521. goto expired;
  1522. }
  1523. if (ip->time_to_expire <= now) {
  1524. goto expired;
  1525. }
  1526. /* Not expiring. */
  1527. return 0;
  1528. expired:
  1529. return 1;
  1530. }
  1531. /* Go over the given set of intro points for each service and remove any
  1532. * invalid ones. The conditions for removal are:
  1533. *
  1534. * - The node doesn't exists anymore (not in consensus)
  1535. * OR
  1536. * - The intro point maximum circuit retry count has been reached and no
  1537. * circuit can be found associated with it.
  1538. * OR
  1539. * - The intro point has expired and we should pick a new one.
  1540. *
  1541. * If an intro point is removed, the circuit (if any) is immediately close.
  1542. * If a circuit can't be found, the intro point is kept if it hasn't reached
  1543. * its maximum circuit retry value and thus should be retried. */
  1544. static void
  1545. cleanup_intro_points(hs_service_t *service, time_t now)
  1546. {
  1547. tor_assert(service);
  1548. /* For both descriptors, cleanup the intro points. */
  1549. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1550. /* Go over the current intro points we have, make sure they are still
  1551. * valid and remove any of them that aren't. */
  1552. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1553. hs_service_intro_point_t *, ip) {
  1554. const node_t *node = get_node_from_intro_point(ip);
  1555. origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
  1556. int has_expired = intro_point_should_expire(ip, now);
  1557. /* We cleanup an intro point if it has expired or if we do not know the
  1558. * node_t anymore (removed from our latest consensus) or if we've
  1559. * reached the maximum number of retry with a non existing circuit. */
  1560. if (has_expired || node == NULL ||
  1561. ip->circuit_retries > MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  1562. /* Remove intro point from descriptor map. We'll add it to the failed
  1563. * map if we retried it too many times. */
  1564. MAP_DEL_CURRENT(key);
  1565. service_intro_point_free(ip);
  1566. /* XXX: Legacy code does NOT do that, it keeps the circuit open until
  1567. * a new descriptor is uploaded and then closed all expiring intro
  1568. * point circuit. Here, we close immediately and because we just
  1569. * discarded the intro point, a new one will be selected, a new
  1570. * descriptor created and uploaded. There is no difference to an
  1571. * attacker between the timing of a new consensus and intro point
  1572. * rotation (possibly?). */
  1573. if (ocirc && !TO_CIRCUIT(ocirc)->marked_for_close) {
  1574. /* After this, no new cells will be handled on the circuit. */
  1575. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  1576. }
  1577. continue;
  1578. }
  1579. } DIGEST256MAP_FOREACH_END;
  1580. } FOR_EACH_DESCRIPTOR_END;
  1581. }
  1582. /* Set the next rotation time of the descriptors for the given service for the
  1583. * time now. */
  1584. static void
  1585. set_rotation_time(hs_service_t *service, time_t now)
  1586. {
  1587. time_t valid_after;
  1588. const networkstatus_t *ns = networkstatus_get_live_consensus(now);
  1589. if (ns) {
  1590. valid_after = ns->valid_after;
  1591. } else {
  1592. valid_after = now;
  1593. }
  1594. tor_assert(service);
  1595. service->state.next_rotation_time =
  1596. sr_state_get_start_time_of_current_protocol_run(valid_after) +
  1597. sr_state_get_protocol_run_duration();
  1598. {
  1599. char fmt_time[ISO_TIME_LEN + 1];
  1600. format_local_iso_time(fmt_time, service->state.next_rotation_time);
  1601. log_info(LD_REND, "Next descriptor rotation time set to %s for %s",
  1602. fmt_time, safe_str_client(service->onion_address));
  1603. }
  1604. }
  1605. /* Return true iff the service should rotate its descriptor. The time now is
  1606. * only used to fetch the live consensus and if none can be found, this
  1607. * returns false. */
  1608. static unsigned int
  1609. should_rotate_descriptors(hs_service_t *service, time_t now)
  1610. {
  1611. const networkstatus_t *ns;
  1612. tor_assert(service);
  1613. ns = networkstatus_get_live_consensus(now);
  1614. if (ns == NULL) {
  1615. goto no_rotation;
  1616. }
  1617. if (ns->valid_after >= service->state.next_rotation_time) {
  1618. goto rotation;
  1619. }
  1620. no_rotation:
  1621. return 0;
  1622. rotation:
  1623. return 1;
  1624. }
  1625. /* Rotate the service descriptors of the given service. The current descriptor
  1626. * will be freed, the next one put in as the current and finally the next
  1627. * descriptor pointer is NULLified. */
  1628. static void
  1629. rotate_service_descriptors(hs_service_t *service, time_t now)
  1630. {
  1631. if (service->desc_current) {
  1632. /* Close all IP circuits for the descriptor. */
  1633. close_intro_circuits(&service->desc_current->intro_points);
  1634. /* We don't need this one anymore, we won't serve any clients coming with
  1635. * this service descriptor. */
  1636. service_descriptor_free(service->desc_current);
  1637. }
  1638. /* The next one become the current one and emptying the next will trigger
  1639. * a descriptor creation for it. */
  1640. service->desc_current = service->desc_next;
  1641. service->desc_next = NULL;
  1642. /* We've just rotated, set the next time for the rotation. */
  1643. set_rotation_time(service, now);
  1644. }
  1645. /* Rotate descriptors for each service if needed. A non existing current
  1646. * descriptor will trigger a descriptor build for the next time period. */
  1647. STATIC void
  1648. rotate_all_descriptors(time_t now)
  1649. {
  1650. /* XXX We rotate all our service descriptors at once. In the future it might
  1651. * be wise, to rotate service descriptors independently to hide that all
  1652. * those descriptors are on the same tor instance */
  1653. FOR_EACH_SERVICE_BEGIN(service) {
  1654. /* Note for a service booting up: Both descriptors are NULL in that case
  1655. * so this function might return true if we are in the timeframe for a
  1656. * rotation leading to basically swapping two NULL pointers which is
  1657. * harmless. However, the side effect is that triggering a rotation will
  1658. * update the service state and avoid doing anymore rotations after the
  1659. * two descriptors have been built. */
  1660. if (!should_rotate_descriptors(service, now)) {
  1661. continue;
  1662. }
  1663. tor_assert(service->desc_current);
  1664. tor_assert(service->desc_next);
  1665. log_info(LD_REND, "Time to rotate our descriptors (%p / %p) for %s",
  1666. service->desc_current, service->desc_next,
  1667. safe_str_client(service->onion_address));
  1668. rotate_service_descriptors(service, now);
  1669. } FOR_EACH_SERVICE_END;
  1670. }
  1671. /* Scheduled event run from the main loop. Make sure all our services are up
  1672. * to date and ready for the other scheduled events. This includes looking at
  1673. * the introduction points status and descriptor rotation time. */
  1674. STATIC void
  1675. run_housekeeping_event(time_t now)
  1676. {
  1677. /* Note that nothing here opens circuit(s) nor uploads descriptor(s). We are
  1678. * simply moving things around or removing uneeded elements. */
  1679. FOR_EACH_SERVICE_BEGIN(service) {
  1680. /* If the service is starting off, set the rotation time. We can't do that
  1681. * at configure time because the get_options() needs to be set for setting
  1682. * that time that uses the voting interval. */
  1683. if (service->state.next_rotation_time == 0) {
  1684. /* Set the next rotation time of the descriptors. If it's Oct 25th
  1685. * 23:47:00, the next rotation time is when the next SRV is computed
  1686. * which is at Oct 26th 00:00:00 that is in 13 minutes. */
  1687. set_rotation_time(service, now);
  1688. }
  1689. /* Cleanup invalid intro points from the service descriptor. */
  1690. cleanup_intro_points(service, now);
  1691. /* Remove expired failing intro point from the descriptor failed list. We
  1692. * reset them at each INTRO_CIRC_RETRY_PERIOD. */
  1693. remove_expired_failing_intro(service, now);
  1694. /* At this point, the service is now ready to go through the scheduled
  1695. * events guaranteeing a valid state. Intro points might be missing from
  1696. * the descriptors after the cleanup but the update/build process will
  1697. * make sure we pick those missing ones. */
  1698. } FOR_EACH_SERVICE_END;
  1699. }
  1700. /* Scheduled event run from the main loop. Make sure all descriptors are up to
  1701. * date. Once this returns, each service descriptor needs to be considered for
  1702. * new introduction circuits and then for upload. */
  1703. static void
  1704. run_build_descriptor_event(time_t now)
  1705. {
  1706. /* For v2 services, this step happens in the upload event. */
  1707. /* Run v3+ events. */
  1708. /* We start by rotating the descriptors only if needed. */
  1709. rotate_all_descriptors(now);
  1710. /* Then, we'll try to build new descriptors that we might need. The
  1711. * condition is that the next descriptor is non existing because it has
  1712. * been rotated or we just started up. */
  1713. build_all_descriptors(now);
  1714. /* Finally, we'll check if we should update the descriptors. Missing
  1715. * introduction points will be picked in this function which is useful for
  1716. * newly built descriptors. */
  1717. update_all_descriptors(now);
  1718. }
  1719. /* For the given service, launch any intro point circuits that could be
  1720. * needed. This considers every descriptor of the service. */
  1721. static void
  1722. launch_intro_point_circuits(hs_service_t *service)
  1723. {
  1724. tor_assert(service);
  1725. /* For both descriptors, try to launch any missing introduction point
  1726. * circuits using the current map. */
  1727. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1728. /* Keep a ref on if we need a direct connection. We use this often. */
  1729. unsigned int direct_conn = service->config.is_single_onion;
  1730. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1731. hs_service_intro_point_t *, ip) {
  1732. extend_info_t *ei;
  1733. /* Skip the intro point that already has an existing circuit
  1734. * (established or not). */
  1735. if (hs_circ_service_get_intro_circ(ip)) {
  1736. continue;
  1737. }
  1738. ei = get_extend_info_from_intro_point(ip, direct_conn);
  1739. if (ei == NULL) {
  1740. if (!direct_conn) {
  1741. /* In case of a multi-hop connection, it should never happen that we
  1742. * can't get the extend info from the node. Avoid connection and
  1743. * remove intro point from descriptor in order to recover from this
  1744. * potential bug. */
  1745. tor_assert_nonfatal(ei);
  1746. }
  1747. MAP_DEL_CURRENT(key);
  1748. service_intro_point_free(ip);
  1749. continue;
  1750. }
  1751. /* Launch a circuit to the intro point. */
  1752. ip->circuit_retries++;
  1753. if (hs_circ_launch_intro_point(service, ip, ei) < 0) {
  1754. log_warn(LD_REND, "Unable to launch intro circuit to node %s "
  1755. "for service %s.",
  1756. safe_str_client(extend_info_describe(ei)),
  1757. safe_str_client(service->onion_address));
  1758. /* Intro point will be retried if possible after this. */
  1759. }
  1760. extend_info_free(ei);
  1761. } DIGEST256MAP_FOREACH_END;
  1762. } FOR_EACH_DESCRIPTOR_END;
  1763. }
  1764. /* Don't try to build more than this many circuits before giving up for a
  1765. * while. Dynamically calculated based on the configured number of intro
  1766. * points for the given service and how many descriptor exists. The default
  1767. * use case of 3 introduction points and two descriptors will allow 28
  1768. * circuits for a retry period (((3 + 2) + (3 * 3)) * 2). */
  1769. static unsigned int
  1770. get_max_intro_circ_per_period(const hs_service_t *service)
  1771. {
  1772. unsigned int count = 0;
  1773. unsigned int multiplier = 0;
  1774. unsigned int num_wanted_ip;
  1775. tor_assert(service);
  1776. tor_assert(service->config.num_intro_points <=
  1777. HS_CONFIG_V3_MAX_INTRO_POINTS);
  1778. /* For a testing network, allow to do it for the maximum amount so circuit
  1779. * creation and rotation and so on can actually be tested without limit. */
  1780. #define MAX_INTRO_POINT_CIRCUIT_RETRIES_TESTING -1
  1781. if (get_options()->TestingTorNetwork) {
  1782. return MAX_INTRO_POINT_CIRCUIT_RETRIES_TESTING;
  1783. }
  1784. num_wanted_ip = service->config.num_intro_points;
  1785. /* The calculation is as follow. We have a number of intro points that we
  1786. * want configured as a torrc option (num_intro_points). We then add an
  1787. * extra value so we can launch multiple circuits at once and pick the
  1788. * quickest ones. For instance, we want 3 intros, we add 2 extra so we'll
  1789. * pick 5 intros and launch 5 circuits. */
  1790. count += (num_wanted_ip + get_intro_point_num_extra());
  1791. /* Then we add the number of retries that is possible to do for each intro
  1792. * point. If we want 3 intros, we'll allow 3 times the number of possible
  1793. * retry. */
  1794. count += (num_wanted_ip * MAX_INTRO_POINT_CIRCUIT_RETRIES);
  1795. /* Then, we multiply by a factor of 2 if we have both descriptor or 0 if we
  1796. * have none. */
  1797. multiplier += (service->desc_current) ? 1 : 0;
  1798. multiplier += (service->desc_next) ? 1 : 0;
  1799. return (count * multiplier);
  1800. }
  1801. /* For the given service, return 1 if the service is allowed to launch more
  1802. * introduction circuits else 0 if the maximum has been reached for the retry
  1803. * period of INTRO_CIRC_RETRY_PERIOD. */
  1804. STATIC int
  1805. can_service_launch_intro_circuit(hs_service_t *service, time_t now)
  1806. {
  1807. tor_assert(service);
  1808. /* Consider the intro circuit retry period of the service. */
  1809. if (now > (service->state.intro_circ_retry_started_time +
  1810. INTRO_CIRC_RETRY_PERIOD)) {
  1811. service->state.intro_circ_retry_started_time = now;
  1812. service->state.num_intro_circ_launched = 0;
  1813. goto allow;
  1814. }
  1815. /* Check if we can still launch more circuits in this period. */
  1816. if (service->state.num_intro_circ_launched <=
  1817. get_max_intro_circ_per_period(service)) {
  1818. goto allow;
  1819. }
  1820. /* Rate limit log that we've reached our circuit creation limit. */
  1821. {
  1822. char *msg;
  1823. time_t elapsed_time = now - service->state.intro_circ_retry_started_time;
  1824. static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
  1825. if ((msg = rate_limit_log(&rlimit, now))) {
  1826. log_info(LD_REND, "Hidden service %s exceeded its circuit launch limit "
  1827. "of %u per %d seconds. It launched %u circuits in "
  1828. "the last %ld seconds. Will retry in %ld seconds.",
  1829. safe_str_client(service->onion_address),
  1830. get_max_intro_circ_per_period(service),
  1831. INTRO_CIRC_RETRY_PERIOD,
  1832. service->state.num_intro_circ_launched,
  1833. (long int) elapsed_time,
  1834. (long int) (INTRO_CIRC_RETRY_PERIOD - elapsed_time));
  1835. tor_free(msg);
  1836. }
  1837. }
  1838. /* Not allow. */
  1839. return 0;
  1840. allow:
  1841. return 1;
  1842. }
  1843. /* Scheduled event run from the main loop. Make sure we have all the circuits
  1844. * we need for each service. */
  1845. static void
  1846. run_build_circuit_event(time_t now)
  1847. {
  1848. /* Make sure we can actually have enough information or able to build
  1849. * internal circuits as required by services. */
  1850. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN ||
  1851. !have_completed_a_circuit()) {
  1852. return;
  1853. }
  1854. /* Run v2 check. */
  1855. if (rend_num_services() > 0) {
  1856. rend_consider_services_intro_points(now);
  1857. }
  1858. /* Run v3+ check. */
  1859. FOR_EACH_SERVICE_BEGIN(service) {
  1860. /* For introduction circuit, we need to make sure we don't stress too much
  1861. * circuit creation so make sure this service is respecting that limit. */
  1862. if (can_service_launch_intro_circuit(service, now)) {
  1863. /* Launch intro point circuits if needed. */
  1864. launch_intro_point_circuits(service);
  1865. /* Once the circuits have opened, we'll make sure to update the
  1866. * descriptor intro point list and cleanup any extraneous. */
  1867. }
  1868. } FOR_EACH_SERVICE_END;
  1869. }
  1870. /* Encode and sign the service descriptor desc and upload it to the given
  1871. * hidden service directory. This does nothing if PublishHidServDescriptors
  1872. * is false. */
  1873. static void
  1874. upload_descriptor_to_hsdir(const hs_service_t *service,
  1875. hs_service_descriptor_t *desc, const node_t *hsdir)
  1876. {
  1877. char version_str[4] = {0}, *encoded_desc = NULL;
  1878. directory_request_t *dir_req;
  1879. hs_ident_dir_conn_t ident;
  1880. tor_assert(service);
  1881. tor_assert(desc);
  1882. tor_assert(hsdir);
  1883. memset(&ident, 0, sizeof(ident));
  1884. /* Let's avoid doing that if tor is configured to not publish. */
  1885. if (!get_options()->PublishHidServDescriptors) {
  1886. log_info(LD_REND, "Service %s not publishing descriptor. "
  1887. "PublishHidServDescriptors is set to 1.",
  1888. safe_str_client(service->onion_address));
  1889. goto end;
  1890. }
  1891. /* First of all, we'll encode the descriptor. This should NEVER fail but
  1892. * just in case, let's make sure we have an actual usable descriptor. */
  1893. if (BUG(hs_desc_encode_descriptor(desc->desc, &desc->signing_kp,
  1894. &encoded_desc) < 0)) {
  1895. goto end;
  1896. }
  1897. /* Setup the connection identifier. */
  1898. hs_ident_dir_conn_init(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
  1899. &ident);
  1900. /* This is our resource when uploading which is used to construct the URL
  1901. * with the version number: "/tor/hs/<version>/publish". */
  1902. tor_snprintf(version_str, sizeof(version_str), "%u",
  1903. service->config.version);
  1904. /* Build the directory request for this HSDir. */
  1905. dir_req = directory_request_new(DIR_PURPOSE_UPLOAD_HSDESC);
  1906. directory_request_set_routerstatus(dir_req, hsdir->rs);
  1907. directory_request_set_indirection(dir_req, DIRIND_ANONYMOUS);
  1908. directory_request_set_resource(dir_req, version_str);
  1909. directory_request_set_payload(dir_req, encoded_desc,
  1910. strlen(encoded_desc));
  1911. /* The ident object is copied over the directory connection object once
  1912. * the directory request is initiated. */
  1913. directory_request_upload_set_hs_ident(dir_req, &ident);
  1914. /* Initiate the directory request to the hsdir.*/
  1915. directory_initiate_request(dir_req);
  1916. directory_request_free(dir_req);
  1917. /* Add this node to previous_hsdirs list */
  1918. service_desc_note_upload(desc, hsdir);
  1919. /* Logging so we know where it was sent. */
  1920. {
  1921. int is_next_desc = (service->desc_next == desc);
  1922. const uint8_t *index = (is_next_desc) ? hsdir->hsdir_index->store_second:
  1923. hsdir->hsdir_index->store_first;
  1924. log_info(LD_REND, "Service %s %s descriptor of revision %" PRIu64
  1925. " initiated upload request to %s with index %s",
  1926. safe_str_client(service->onion_address),
  1927. (is_next_desc) ? "next" : "current",
  1928. desc->desc->plaintext_data.revision_counter,
  1929. safe_str_client(node_describe(hsdir)),
  1930. safe_str_client(hex_str((const char *) index, 32)));
  1931. }
  1932. /* XXX: Inform control port of the upload event (#20699). */
  1933. end:
  1934. tor_free(encoded_desc);
  1935. return;
  1936. }
  1937. /** Return a newly-allocated string for our state file which contains revision
  1938. * counter information for <b>desc</b>. The format is:
  1939. *
  1940. * HidServRevCounter <blinded_pubkey> <rev_counter>
  1941. */
  1942. STATIC char *
  1943. encode_desc_rev_counter_for_state(const hs_service_descriptor_t *desc)
  1944. {
  1945. char *state_str = NULL;
  1946. char blinded_pubkey_b64[ED25519_BASE64_LEN+1];
  1947. uint64_t rev_counter = desc->desc->plaintext_data.revision_counter;
  1948. const ed25519_public_key_t *blinded_pubkey = &desc->blinded_kp.pubkey;
  1949. /* Turn the blinded key into b64 so that we save it on state */
  1950. tor_assert(blinded_pubkey);
  1951. if (ed25519_public_to_base64(blinded_pubkey_b64, blinded_pubkey) < 0) {
  1952. goto done;
  1953. }
  1954. /* Format is: <blinded key> <rev counter> */
  1955. tor_asprintf(&state_str, "%s %" PRIu64, blinded_pubkey_b64, rev_counter);
  1956. log_info(LD_GENERAL, "[!] Adding rev counter %" PRIu64 " for %s!",
  1957. rev_counter, blinded_pubkey_b64);
  1958. done:
  1959. return state_str;
  1960. }
  1961. /** Update HS descriptor revision counters in our state by removing the old
  1962. * ones and writing down the ones that are currently active. */
  1963. static void
  1964. update_revision_counters_in_state(void)
  1965. {
  1966. config_line_t *lines = NULL;
  1967. config_line_t **nextline = &lines;
  1968. or_state_t *state = get_or_state();
  1969. /* Prepare our state structure with the rev counters */
  1970. FOR_EACH_SERVICE_BEGIN(service) {
  1971. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1972. /* We don't want to save zero counters */
  1973. if (desc->desc->plaintext_data.revision_counter == 0) {
  1974. continue;
  1975. }
  1976. *nextline = tor_malloc_zero(sizeof(config_line_t));
  1977. (*nextline)->key = tor_strdup("HidServRevCounter");
  1978. (*nextline)->value = encode_desc_rev_counter_for_state(desc);
  1979. nextline = &(*nextline)->next;
  1980. } FOR_EACH_DESCRIPTOR_END;
  1981. } FOR_EACH_SERVICE_END;
  1982. /* Remove the old rev counters, and replace them with the new ones */
  1983. config_free_lines(state->HidServRevCounter);
  1984. state->HidServRevCounter = lines;
  1985. /* Set the state as dirty since we just edited it */
  1986. if (!get_options()->AvoidDiskWrites) {
  1987. or_state_mark_dirty(state, 0);
  1988. }
  1989. }
  1990. /** Scan the string <b>state_line</b> for the revision counter of the service
  1991. * with <b>blinded_pubkey</b>. Set <b>service_found_out</b> to True if the
  1992. * line is relevant to this service, and return the cached revision
  1993. * counter. Else set <b>service_found_out</b> to False. */
  1994. STATIC uint64_t
  1995. check_state_line_for_service_rev_counter(const char *state_line,
  1996. const ed25519_public_key_t *blinded_pubkey,
  1997. int *service_found_out)
  1998. {
  1999. smartlist_t *items = NULL;
  2000. int ok;
  2001. ed25519_public_key_t pubkey_in_state;
  2002. uint64_t rev_counter = 0;
  2003. tor_assert(service_found_out);
  2004. tor_assert(state_line);
  2005. tor_assert(blinded_pubkey);
  2006. /* Assume that the line is not for this service */
  2007. *service_found_out = 0;
  2008. /* Start parsing the state line */
  2009. items = smartlist_new();
  2010. smartlist_split_string(items, state_line, NULL,
  2011. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  2012. if (smartlist_len(items) < 2) {
  2013. log_warn(LD_GENERAL, "Incomplete rev counter line. Ignoring.");
  2014. goto done;
  2015. }
  2016. char *b64_key_str = smartlist_get(items, 0);
  2017. char *saved_rev_counter_str = smartlist_get(items, 1);
  2018. /* Parse blinded key to check if it's for this hidden service */
  2019. if (ed25519_public_from_base64(&pubkey_in_state, b64_key_str) < 0) {
  2020. log_warn(LD_GENERAL, "Unable to base64 key in revcount line. Ignoring.");
  2021. goto done;
  2022. }
  2023. /* State line not for this hidden service */
  2024. if (!ed25519_pubkey_eq(&pubkey_in_state, blinded_pubkey)) {
  2025. goto done;
  2026. }
  2027. rev_counter = tor_parse_uint64(saved_rev_counter_str,
  2028. 10, 0, UINT64_MAX, &ok, NULL);
  2029. if (!ok) {
  2030. log_warn(LD_GENERAL, "Unable to parse rev counter. Ignoring.");
  2031. goto done;
  2032. }
  2033. /* Since we got this far, the line was for this service */
  2034. *service_found_out = 1;
  2035. log_info(LD_GENERAL, "Found rev counter for %s: %" PRIu64,
  2036. b64_key_str, rev_counter);
  2037. done:
  2038. tor_assert(items);
  2039. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  2040. smartlist_free(items);
  2041. return rev_counter;
  2042. }
  2043. /** Dig into our state file and find the current revision counter for the
  2044. * service with blinded key <b>blinded_pubkey</b>. If no revision counter is
  2045. * found, return 0. */
  2046. static uint64_t
  2047. get_rev_counter_for_service(const ed25519_public_key_t *blinded_pubkey)
  2048. {
  2049. or_state_t *state = get_or_state();
  2050. config_line_t *line;
  2051. /* Set default value for rev counters (if not found) to 0 */
  2052. uint64_t final_rev_counter = 0;
  2053. for (line = state->HidServRevCounter ; line ; line = line->next) {
  2054. int service_found = 0;
  2055. uint64_t rev_counter = 0;
  2056. tor_assert(!strcmp(line->key, "HidServRevCounter"));
  2057. /* Scan all the HidServRevCounter lines till we find the line for this
  2058. service: */
  2059. rev_counter = check_state_line_for_service_rev_counter(line->value,
  2060. blinded_pubkey,
  2061. &service_found);
  2062. if (service_found) {
  2063. final_rev_counter = rev_counter;
  2064. goto done;
  2065. }
  2066. }
  2067. done:
  2068. return final_rev_counter;
  2069. }
  2070. /** Update the value of the revision counter for <b>hs_desc</b> and save it on
  2071. our state file. */
  2072. static void
  2073. increment_descriptor_revision_counter(hs_descriptor_t *hs_desc)
  2074. {
  2075. /* Find stored rev counter if it exists */
  2076. uint64_t rev_counter =
  2077. get_rev_counter_for_service(&hs_desc->plaintext_data.blinded_pubkey);
  2078. /* Increment the revision counter of <b>hs_desc</b> so the next update (which
  2079. * will trigger an upload) will have the right value. We do this at this
  2080. * stage to only do it once because a descriptor can have many updates before
  2081. * being uploaded. By doing it at upload, we are sure to only increment by 1
  2082. * and thus avoid leaking how many operations we made on the descriptor from
  2083. * the previous one before uploading. */
  2084. rev_counter++;
  2085. hs_desc->plaintext_data.revision_counter = rev_counter;
  2086. update_revision_counters_in_state();
  2087. }
  2088. /** Set the revision counter in <b>hs_desc</b>, using the state file to find
  2089. * the current counter value if it exists. */
  2090. static void
  2091. set_descriptor_revision_counter(hs_descriptor_t *hs_desc)
  2092. {
  2093. /* Find stored rev counter if it exists */
  2094. uint64_t rev_counter =
  2095. get_rev_counter_for_service(&hs_desc->plaintext_data.blinded_pubkey);
  2096. hs_desc->plaintext_data.revision_counter = rev_counter;
  2097. }
  2098. /* Encode and sign the service descriptor desc and upload it to the
  2099. * responsible hidden service directories. If for_next_period is true, the set
  2100. * of directories are selected using the next hsdir_index. This does nothing
  2101. * if PublishHidServDescriptors is false. */
  2102. STATIC void
  2103. upload_descriptor_to_all(const hs_service_t *service,
  2104. hs_service_descriptor_t *desc)
  2105. {
  2106. smartlist_t *responsible_dirs = NULL;
  2107. tor_assert(service);
  2108. tor_assert(desc);
  2109. /* We'll first cancel any directory request that are ongoing for this
  2110. * descriptor. It is possible that we can trigger multiple uploads in a
  2111. * short time frame which can lead to a race where the second upload arrives
  2112. * before the first one leading to a 400 malformed descriptor response from
  2113. * the directory. Closing all pending requests avoids that. */
  2114. close_directory_connections(service, desc);
  2115. /* Get our list of responsible HSDir. */
  2116. responsible_dirs = smartlist_new();
  2117. /* The parameter 0 means that we aren't a client so tell the function to use
  2118. * the spread store consensus paremeter. */
  2119. hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
  2120. service->desc_next == desc, 0, responsible_dirs);
  2121. /** Clear list of previous hsdirs since we are about to upload to a new
  2122. * list. Let's keep it up to date. */
  2123. service_desc_clear_previous_hsdirs(desc);
  2124. /* For each responsible HSDir we have, initiate an upload command. */
  2125. SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *,
  2126. hsdir_rs) {
  2127. const node_t *hsdir_node = node_get_by_id(hsdir_rs->identity_digest);
  2128. /* Getting responsible hsdir implies that the node_t object exists for the
  2129. * routerstatus_t found in the consensus else we have a problem. */
  2130. tor_assert(hsdir_node);
  2131. /* Upload this descriptor to the chosen directory. */
  2132. upload_descriptor_to_hsdir(service, desc, hsdir_node);
  2133. } SMARTLIST_FOREACH_END(hsdir_rs);
  2134. /* Set the next upload time for this descriptor. Even if we are configured
  2135. * to not upload, we still want to follow the right cycle of life for this
  2136. * descriptor. */
  2137. desc->next_upload_time =
  2138. (time(NULL) + crypto_rand_int_range(HS_SERVICE_NEXT_UPLOAD_TIME_MIN,
  2139. HS_SERVICE_NEXT_UPLOAD_TIME_MAX));
  2140. {
  2141. char fmt_next_time[ISO_TIME_LEN+1];
  2142. format_local_iso_time(fmt_next_time, desc->next_upload_time);
  2143. log_debug(LD_REND, "Service %s set to upload a descriptor at %s",
  2144. safe_str_client(service->onion_address), fmt_next_time);
  2145. }
  2146. /* Update the revision counter of this descriptor */
  2147. increment_descriptor_revision_counter(desc->desc);
  2148. smartlist_free(responsible_dirs);
  2149. return;
  2150. }
  2151. /** The set of HSDirs have changed: check if the change affects our descriptor
  2152. * HSDir placement, and if it does, reupload the desc. */
  2153. STATIC int
  2154. service_desc_hsdirs_changed(const hs_service_t *service,
  2155. const hs_service_descriptor_t *desc)
  2156. {
  2157. int should_reupload = 0;
  2158. smartlist_t *responsible_dirs = smartlist_new();
  2159. /* No desc upload has happened yet: it will happen eventually */
  2160. if (!desc->previous_hsdirs || !smartlist_len(desc->previous_hsdirs)) {
  2161. goto done;
  2162. }
  2163. /* Get list of responsible hsdirs */
  2164. hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
  2165. service->desc_next == desc, 0, responsible_dirs);
  2166. /* Check if any new hsdirs have been added to the responsible hsdirs set:
  2167. * Iterate over the list of new hsdirs, and reupload if any of them is not
  2168. * present in the list of previous hsdirs.
  2169. */
  2170. SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *, hsdir_rs) {
  2171. char b64_digest[BASE64_DIGEST_LEN+1] = {0};
  2172. digest_to_base64(b64_digest, hsdir_rs->identity_digest);
  2173. if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
  2174. should_reupload = 1;
  2175. break;
  2176. }
  2177. } SMARTLIST_FOREACH_END(hsdir_rs);
  2178. done:
  2179. smartlist_free(responsible_dirs);
  2180. return should_reupload;
  2181. }
  2182. /* Return 1 if the given descriptor from the given service can be uploaded
  2183. * else return 0 if it can not. */
  2184. static int
  2185. should_service_upload_descriptor(const hs_service_t *service,
  2186. const hs_service_descriptor_t *desc, time_t now)
  2187. {
  2188. unsigned int num_intro_points;
  2189. tor_assert(service);
  2190. tor_assert(desc);
  2191. /* If this descriptors has missing intro points that is that it couldn't get
  2192. * them all when it was time to pick them, it means that we should upload
  2193. * instead of waiting an arbitrary amount of time breaking the service.
  2194. * Else, if we have no missing intro points, we use the value taken from the
  2195. * service configuration. */
  2196. if (desc->missing_intro_points) {
  2197. num_intro_points = digest256map_size(desc->intro_points.map);
  2198. } else {
  2199. num_intro_points = service->config.num_intro_points;
  2200. }
  2201. /* This means we tried to pick intro points but couldn't get any so do not
  2202. * upload descriptor in this case. We need at least one for the service to
  2203. * be reachable. */
  2204. if (desc->missing_intro_points && num_intro_points == 0) {
  2205. goto cannot;
  2206. }
  2207. /* Check if all our introduction circuit have been established for all the
  2208. * intro points we have selected. */
  2209. if (count_desc_circuit_established(desc) != num_intro_points) {
  2210. goto cannot;
  2211. }
  2212. /* Is it the right time to upload? */
  2213. if (desc->next_upload_time > now) {
  2214. goto cannot;
  2215. }
  2216. /* Don't upload desc if we don't have a live consensus */
  2217. if (!networkstatus_get_live_consensus(now)) {
  2218. goto cannot;
  2219. }
  2220. /* Do we know enough router descriptors to have adequate vision of the HSDir
  2221. hash ring? */
  2222. if (!router_have_minimum_dir_info()) {
  2223. goto cannot;
  2224. }
  2225. /* Can upload! */
  2226. return 1;
  2227. cannot:
  2228. return 0;
  2229. }
  2230. /* Scheduled event run from the main loop. Try to upload the descriptor for
  2231. * each service. */
  2232. STATIC void
  2233. run_upload_descriptor_event(time_t now)
  2234. {
  2235. /* v2 services use the same function for descriptor creation and upload so
  2236. * we do everything here because the intro circuits were checked before. */
  2237. if (rend_num_services() > 0) {
  2238. rend_consider_services_upload(now);
  2239. rend_consider_descriptor_republication();
  2240. }
  2241. /* Run v3+ check. */
  2242. FOR_EACH_SERVICE_BEGIN(service) {
  2243. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2244. /* If we were asked to re-examine the hash ring, and it changed, then
  2245. schedule an upload */
  2246. if (consider_republishing_hs_descriptors &&
  2247. service_desc_hsdirs_changed(service, desc)) {
  2248. service_desc_schedule_upload(desc, now, 0);
  2249. }
  2250. /* Can this descriptor be uploaded? */
  2251. if (!should_service_upload_descriptor(service, desc, now)) {
  2252. continue;
  2253. }
  2254. log_info(LD_REND, "Initiating upload for hidden service %s descriptor "
  2255. "for service %s with %u/%u introduction points%s.",
  2256. (desc == service->desc_current) ? "current" : "next",
  2257. safe_str_client(service->onion_address),
  2258. digest256map_size(desc->intro_points.map),
  2259. service->config.num_intro_points,
  2260. (desc->missing_intro_points) ? " (couldn't pick more)" : "");
  2261. /* At this point, we have to upload the descriptor so start by building
  2262. * the intro points descriptor section which we are now sure to be
  2263. * accurate because all circuits have been established. */
  2264. build_desc_intro_points(service, desc, now);
  2265. upload_descriptor_to_all(service, desc);
  2266. } FOR_EACH_DESCRIPTOR_END;
  2267. } FOR_EACH_SERVICE_END;
  2268. /* We are done considering whether to republish rend descriptors */
  2269. consider_republishing_hs_descriptors = 0;
  2270. }
  2271. /* Called when the introduction point circuit is done building and ready to be
  2272. * used. */
  2273. static void
  2274. service_intro_circ_has_opened(origin_circuit_t *circ)
  2275. {
  2276. hs_service_t *service = NULL;
  2277. hs_service_intro_point_t *ip = NULL;
  2278. hs_service_descriptor_t *desc = NULL;
  2279. tor_assert(circ);
  2280. /* Let's do some basic sanity checking of the circ state */
  2281. if (BUG(!circ->cpath)) {
  2282. return;
  2283. }
  2284. if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)) {
  2285. return;
  2286. }
  2287. if (BUG(!circ->hs_ident)) {
  2288. return;
  2289. }
  2290. /* Get the corresponding service and intro point. */
  2291. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  2292. if (service == NULL) {
  2293. log_warn(LD_REND, "Unknown service identity key %s on the introduction "
  2294. "circuit %u. Can't find onion service.",
  2295. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2296. TO_CIRCUIT(circ)->n_circ_id);
  2297. goto err;
  2298. }
  2299. if (ip == NULL) {
  2300. log_warn(LD_REND, "Unknown introduction point auth key on circuit %u "
  2301. "for service %s",
  2302. TO_CIRCUIT(circ)->n_circ_id,
  2303. safe_str_client(service->onion_address));
  2304. goto err;
  2305. }
  2306. /* We can't have an IP object without a descriptor. */
  2307. tor_assert(desc);
  2308. if (hs_circ_service_intro_has_opened(service, ip, desc, circ)) {
  2309. /* Getting here means that the circuit has been re-purposed because we
  2310. * have enough intro circuit opened. Remove the IP from the service. */
  2311. service_intro_point_remove(service, ip);
  2312. service_intro_point_free(ip);
  2313. }
  2314. goto done;
  2315. err:
  2316. /* Close circuit, we can't use it. */
  2317. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
  2318. done:
  2319. return;
  2320. }
  2321. /* Called when a rendezvous circuit is done building and ready to be used. */
  2322. static void
  2323. service_rendezvous_circ_has_opened(origin_circuit_t *circ)
  2324. {
  2325. hs_service_t *service = NULL;
  2326. tor_assert(circ);
  2327. tor_assert(circ->cpath);
  2328. /* Getting here means this is a v3 rendezvous circuit. */
  2329. tor_assert(circ->hs_ident);
  2330. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  2331. /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
  2332. * timestamp regardless of its content because that circuit could have been
  2333. * cannibalized so in any cases, we are about to use that circuit more. */
  2334. TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
  2335. pathbias_count_use_attempt(circ);
  2336. /* Get the corresponding service and intro point. */
  2337. get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
  2338. if (service == NULL) {
  2339. log_warn(LD_REND, "Unknown service identity key %s on the rendezvous "
  2340. "circuit %u with cookie %s. Can't find onion service.",
  2341. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2342. TO_CIRCUIT(circ)->n_circ_id,
  2343. hex_str((const char *) circ->hs_ident->rendezvous_cookie,
  2344. REND_COOKIE_LEN));
  2345. goto err;
  2346. }
  2347. /* If the cell can't be sent, the circuit will be closed within this
  2348. * function. */
  2349. hs_circ_service_rp_has_opened(service, circ);
  2350. goto done;
  2351. err:
  2352. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
  2353. done:
  2354. return;
  2355. }
  2356. /* We've been expecting an INTRO_ESTABLISHED cell on this circuit and it just
  2357. * arrived. Handle the INTRO_ESTABLISHED cell arriving on the given
  2358. * introduction circuit. Return 0 on success else a negative value. */
  2359. static int
  2360. service_handle_intro_established(origin_circuit_t *circ,
  2361. const uint8_t *payload,
  2362. size_t payload_len)
  2363. {
  2364. hs_service_t *service = NULL;
  2365. hs_service_intro_point_t *ip = NULL;
  2366. tor_assert(circ);
  2367. tor_assert(payload);
  2368. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  2369. /* We need the service and intro point for this cell. */
  2370. get_objects_from_ident(circ->hs_ident, &service, &ip, NULL);
  2371. /* Get service object from the circuit identifier. */
  2372. if (service == NULL) {
  2373. log_warn(LD_REND, "Unknown service identity key %s on the introduction "
  2374. "circuit %u. Can't find onion service.",
  2375. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2376. TO_CIRCUIT(circ)->n_circ_id);
  2377. goto err;
  2378. }
  2379. if (ip == NULL) {
  2380. /* We don't recognize the key. */
  2381. log_warn(LD_REND, "Introduction circuit established without an intro "
  2382. "point object on circuit %u for service %s",
  2383. TO_CIRCUIT(circ)->n_circ_id,
  2384. safe_str_client(service->onion_address));
  2385. goto err;
  2386. }
  2387. /* Try to parse the payload into a cell making sure we do actually have a
  2388. * valid cell. On success, the ip object and circuit purpose is updated to
  2389. * reflect the fact that the introduction circuit is established. */
  2390. if (hs_circ_handle_intro_established(service, ip, circ, payload,
  2391. payload_len) < 0) {
  2392. goto err;
  2393. }
  2394. /* Flag that we have an established circuit for this intro point. This value
  2395. * is what indicates the upload scheduled event if we are ready to build the
  2396. * intro point into the descriptor and upload. */
  2397. ip->circuit_established = 1;
  2398. log_info(LD_REND, "Successfully received an INTRO_ESTABLISHED cell "
  2399. "on circuit %u for service %s",
  2400. TO_CIRCUIT(circ)->n_circ_id,
  2401. safe_str_client(service->onion_address));
  2402. return 0;
  2403. err:
  2404. return -1;
  2405. }
  2406. /* We just received an INTRODUCE2 cell on the established introduction circuit
  2407. * circ. Handle the cell and return 0 on success else a negative value. */
  2408. static int
  2409. service_handle_introduce2(origin_circuit_t *circ, const uint8_t *payload,
  2410. size_t payload_len)
  2411. {
  2412. hs_service_t *service = NULL;
  2413. hs_service_intro_point_t *ip = NULL;
  2414. hs_service_descriptor_t *desc = NULL;
  2415. tor_assert(circ);
  2416. tor_assert(payload);
  2417. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  2418. /* We'll need every object associated with this circuit. */
  2419. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  2420. /* Get service object from the circuit identifier. */
  2421. if (service == NULL) {
  2422. log_warn(LD_BUG, "Unknown service identity key %s when handling "
  2423. "an INTRODUCE2 cell on circuit %u",
  2424. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  2425. TO_CIRCUIT(circ)->n_circ_id);
  2426. goto err;
  2427. }
  2428. if (ip == NULL) {
  2429. /* We don't recognize the key. */
  2430. log_warn(LD_BUG, "Unknown introduction auth key when handling "
  2431. "an INTRODUCE2 cell on circuit %u for service %s",
  2432. TO_CIRCUIT(circ)->n_circ_id,
  2433. safe_str_client(service->onion_address));
  2434. goto err;
  2435. }
  2436. /* If we have an IP object, we MUST have a descriptor object. */
  2437. tor_assert(desc);
  2438. /* The following will parse, decode and launch the rendezvous point circuit.
  2439. * Both current and legacy cells are handled. */
  2440. if (hs_circ_handle_introduce2(service, circ, ip, desc->desc->subcredential,
  2441. payload, payload_len) < 0) {
  2442. goto err;
  2443. }
  2444. return 0;
  2445. err:
  2446. return -1;
  2447. }
  2448. /* Add to list every filename used by service. This is used by the sandbox
  2449. * subsystem. */
  2450. static void
  2451. service_add_fnames_to_list(const hs_service_t *service, smartlist_t *list)
  2452. {
  2453. const char *s_dir;
  2454. char fname[128] = {0};
  2455. tor_assert(service);
  2456. tor_assert(list);
  2457. /* Ease our life. */
  2458. s_dir = service->config.directory_path;
  2459. /* The hostname file. */
  2460. smartlist_add(list, hs_path_from_filename(s_dir, fname_hostname));
  2461. /* The key files splitted in two. */
  2462. tor_snprintf(fname, sizeof(fname), "%s_secret_key", fname_keyfile_prefix);
  2463. smartlist_add(list, hs_path_from_filename(s_dir, fname));
  2464. tor_snprintf(fname, sizeof(fname), "%s_public_key", fname_keyfile_prefix);
  2465. smartlist_add(list, hs_path_from_filename(s_dir, fname));
  2466. }
  2467. /* ========== */
  2468. /* Public API */
  2469. /* ========== */
  2470. /* Return the number of service we have configured and usable. */
  2471. unsigned int
  2472. hs_service_get_num_services(void)
  2473. {
  2474. if (hs_service_map == NULL) {
  2475. return 0;
  2476. }
  2477. return HT_SIZE(hs_service_map);
  2478. }
  2479. /* Called once an introduction circuit is closed. If the circuit doesn't have
  2480. * a v3 identifier, it is ignored. */
  2481. void
  2482. hs_service_intro_circ_has_closed(origin_circuit_t *circ)
  2483. {
  2484. hs_service_t *service = NULL;
  2485. hs_service_intro_point_t *ip = NULL;
  2486. hs_service_descriptor_t *desc = NULL;
  2487. tor_assert(circ);
  2488. if (circ->hs_ident == NULL) {
  2489. /* This is not a v3 circuit, ignore. */
  2490. goto end;
  2491. }
  2492. get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
  2493. if (service == NULL) {
  2494. log_warn(LD_REND, "Unable to find any hidden service associated "
  2495. "identity key %s on intro circuit %u.",
  2496. ed25519_fmt(&circ->hs_ident->identity_pk),
  2497. TO_CIRCUIT(circ)->n_circ_id);
  2498. goto end;
  2499. }
  2500. if (ip == NULL) {
  2501. /* The introduction point object has already been removed probably by our
  2502. * cleanup process so ignore. */
  2503. goto end;
  2504. }
  2505. /* Can't have an intro point object without a descriptor. */
  2506. tor_assert(desc);
  2507. /* Circuit disappeared so make sure the intro point is updated. By
  2508. * keeping the object in the descriptor, we'll be able to retry. */
  2509. ip->circuit_established = 0;
  2510. /* We've retried too many times, remember it as a failed intro point so we
  2511. * don't pick it up again. It will be retried in INTRO_CIRC_RETRY_PERIOD
  2512. * seconds. */
  2513. if (ip->circuit_retries > MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  2514. remember_failing_intro_point(ip, desc, approx_time());
  2515. service_intro_point_remove(service, ip);
  2516. service_intro_point_free(ip);
  2517. }
  2518. end:
  2519. return;
  2520. }
  2521. /* Given conn, a rendezvous edge connection acting as an exit stream, look up
  2522. * the hidden service for the circuit circ, and look up the port and address
  2523. * based on the connection port. Assign the actual connection address.
  2524. *
  2525. * Return 0 on success. Return -1 on failure and the caller should NOT close
  2526. * the circuit. Return -2 on failure and the caller MUST close the circuit for
  2527. * security reasons. */
  2528. int
  2529. hs_service_set_conn_addr_port(const origin_circuit_t *circ,
  2530. edge_connection_t *conn)
  2531. {
  2532. hs_service_t *service = NULL;
  2533. tor_assert(circ);
  2534. tor_assert(conn);
  2535. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  2536. tor_assert(circ->hs_ident);
  2537. get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
  2538. if (service == NULL) {
  2539. log_warn(LD_REND, "Unable to find any hidden service associated "
  2540. "identity key %s on rendezvous circuit %u.",
  2541. ed25519_fmt(&circ->hs_ident->identity_pk),
  2542. TO_CIRCUIT(circ)->n_circ_id);
  2543. /* We want the caller to close the circuit because it's not a valid
  2544. * service so no danger. Attempting to bruteforce the entire key space by
  2545. * opening circuits to learn which service is being hosted here is
  2546. * impractical. */
  2547. goto err_close;
  2548. }
  2549. /* Enforce the streams-per-circuit limit, and refuse to provide a mapping if
  2550. * this circuit will exceed the limit. */
  2551. if (service->config.max_streams_per_rdv_circuit > 0 &&
  2552. (circ->hs_ident->num_rdv_streams >=
  2553. service->config.max_streams_per_rdv_circuit)) {
  2554. #define MAX_STREAM_WARN_INTERVAL 600
  2555. static struct ratelim_t stream_ratelim =
  2556. RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
  2557. log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
  2558. "Maximum streams per circuit limit reached on "
  2559. "rendezvous circuit %u for service %s. Circuit has "
  2560. "%" PRIu64 " out of %" PRIu64 " streams. %s.",
  2561. TO_CIRCUIT(circ)->n_circ_id,
  2562. service->onion_address,
  2563. circ->hs_ident->num_rdv_streams,
  2564. service->config.max_streams_per_rdv_circuit,
  2565. service->config.max_streams_close_circuit ?
  2566. "Closing circuit" : "Ignoring open stream request");
  2567. if (service->config.max_streams_close_circuit) {
  2568. /* Service explicitly configured to close immediately. */
  2569. goto err_close;
  2570. }
  2571. /* Exceeding the limit makes tor silently ignore the stream creation
  2572. * request and keep the circuit open. */
  2573. goto err_no_close;
  2574. }
  2575. /* Find a virtual port of that service mathcing the one in the connection if
  2576. * succesful, set the address in the connection. */
  2577. if (hs_set_conn_addr_port(service->config.ports, conn) < 0) {
  2578. log_info(LD_REND, "No virtual port mapping exists for port %d for "
  2579. "hidden service %s.",
  2580. TO_CONN(conn)->port, service->onion_address);
  2581. if (service->config.allow_unknown_ports) {
  2582. /* Service explicitly allow connection to unknown ports so close right
  2583. * away because we do not care about port mapping. */
  2584. goto err_close;
  2585. }
  2586. /* If the service didn't explicitly allow it, we do NOT close the circuit
  2587. * here to raise the bar in terms of performance for port mapping. */
  2588. goto err_no_close;
  2589. }
  2590. /* Success. */
  2591. return 0;
  2592. err_close:
  2593. /* Indicate the caller that the circuit should be closed. */
  2594. return -2;
  2595. err_no_close:
  2596. /* Indicate the caller to NOT close the circuit. */
  2597. return -1;
  2598. }
  2599. /* Add to file_list every filename used by a configured hidden service, and to
  2600. * dir_list every directory path used by a configured hidden service. This is
  2601. * used by the sandbox subsystem to whitelist those. */
  2602. void
  2603. hs_service_lists_fnames_for_sandbox(smartlist_t *file_list,
  2604. smartlist_t *dir_list)
  2605. {
  2606. tor_assert(file_list);
  2607. tor_assert(dir_list);
  2608. /* Add files and dirs for legacy services. */
  2609. rend_services_add_filenames_to_lists(file_list, dir_list);
  2610. /* Add files and dirs for v3+. */
  2611. FOR_EACH_SERVICE_BEGIN(service) {
  2612. /* Skip ephemeral service, they don't touch the disk. */
  2613. if (service->config.is_ephemeral) {
  2614. continue;
  2615. }
  2616. service_add_fnames_to_list(service, file_list);
  2617. smartlist_add_strdup(dir_list, service->config.directory_path);
  2618. } FOR_EACH_DESCRIPTOR_END;
  2619. }
  2620. /* Called when our internal view of the directory has changed. We might have
  2621. * received a new batch of descriptors which might affect the shape of the
  2622. * HSDir hash ring. Signal that we should reexamine the hash ring and
  2623. * re-upload our HS descriptors if needed. */
  2624. void
  2625. hs_service_dir_info_changed(void)
  2626. {
  2627. log_info(LD_REND, "New dirinfo arrived: consider reuploading descriptor");
  2628. consider_republishing_hs_descriptors = 1;
  2629. }
  2630. /* Called when we get an INTRODUCE2 cell on the circ. Respond to the cell and
  2631. * launch a circuit to the rendezvous point. */
  2632. int
  2633. hs_service_receive_introduce2(origin_circuit_t *circ, const uint8_t *payload,
  2634. size_t payload_len)
  2635. {
  2636. int ret = -1;
  2637. tor_assert(circ);
  2638. tor_assert(payload);
  2639. /* Do some initial validation and logging before we parse the cell */
  2640. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  2641. log_warn(LD_PROTOCOL, "Received an INTRODUCE2 cell on a "
  2642. "non introduction circuit of purpose %d",
  2643. TO_CIRCUIT(circ)->purpose);
  2644. goto done;
  2645. }
  2646. if (circ->hs_ident) {
  2647. ret = service_handle_introduce2(circ, payload, payload_len);
  2648. } else {
  2649. ret = rend_service_receive_introduction(circ, payload, payload_len);
  2650. }
  2651. done:
  2652. return ret;
  2653. }
  2654. /* Called when we get an INTRO_ESTABLISHED cell. Mark the circuit as an
  2655. * established introduction point. Return 0 on success else a negative value
  2656. * and the circuit is closed. */
  2657. int
  2658. hs_service_receive_intro_established(origin_circuit_t *circ,
  2659. const uint8_t *payload,
  2660. size_t payload_len)
  2661. {
  2662. int ret = -1;
  2663. tor_assert(circ);
  2664. tor_assert(payload);
  2665. if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  2666. log_warn(LD_PROTOCOL, "Received an INTRO_ESTABLISHED cell on a "
  2667. "non introduction circuit of purpose %d",
  2668. TO_CIRCUIT(circ)->purpose);
  2669. goto err;
  2670. }
  2671. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  2672. * identifier hs_ident. Can't be both. */
  2673. if (circ->hs_ident) {
  2674. ret = service_handle_intro_established(circ, payload, payload_len);
  2675. } else {
  2676. ret = rend_service_intro_established(circ, payload, payload_len);
  2677. }
  2678. if (ret < 0) {
  2679. goto err;
  2680. }
  2681. return 0;
  2682. err:
  2683. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  2684. return -1;
  2685. }
  2686. /* Called when any kind of hidden service circuit is done building thus
  2687. * opened. This is the entry point from the circuit subsystem. */
  2688. void
  2689. hs_service_circuit_has_opened(origin_circuit_t *circ)
  2690. {
  2691. tor_assert(circ);
  2692. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  2693. * identifier hs_ident. Can't be both. */
  2694. switch (TO_CIRCUIT(circ)->purpose) {
  2695. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2696. if (circ->hs_ident) {
  2697. service_intro_circ_has_opened(circ);
  2698. } else {
  2699. rend_service_intro_has_opened(circ);
  2700. }
  2701. break;
  2702. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2703. if (circ->hs_ident) {
  2704. service_rendezvous_circ_has_opened(circ);
  2705. } else {
  2706. rend_service_rendezvous_has_opened(circ);
  2707. }
  2708. break;
  2709. default:
  2710. tor_assert(0);
  2711. }
  2712. }
  2713. /* Load and/or generate keys for all onion services including the client
  2714. * authorization if any. Return 0 on success, -1 on failure. */
  2715. int
  2716. hs_service_load_all_keys(void)
  2717. {
  2718. /* Load v2 service keys if we have v2. */
  2719. if (rend_num_services() != 0) {
  2720. if (rend_service_load_all_keys(NULL) < 0) {
  2721. goto err;
  2722. }
  2723. }
  2724. /* Load or/and generate them for v3+. */
  2725. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
  2726. /* Ignore ephemeral service, they already have their keys set. */
  2727. if (service->config.is_ephemeral) {
  2728. continue;
  2729. }
  2730. log_info(LD_REND, "Loading v3 onion service keys from %s",
  2731. service_escaped_dir(service));
  2732. if (load_service_keys(service) < 0) {
  2733. goto err;
  2734. }
  2735. /* XXX: Load/Generate client authorization keys. (#20700) */
  2736. } SMARTLIST_FOREACH_END(service);
  2737. /* Final step, the staging list contains service in a quiescent state that
  2738. * is ready to be used. Register them to the global map. Once this is over,
  2739. * the staging list will be cleaned up. */
  2740. register_all_services();
  2741. /* All keys have been loaded successfully. */
  2742. return 0;
  2743. err:
  2744. return -1;
  2745. }
  2746. /* Put all service object in the given service list. After this, the caller
  2747. * looses ownership of every elements in the list and responsible to free the
  2748. * list pointer. */
  2749. void
  2750. hs_service_stage_services(const smartlist_t *service_list)
  2751. {
  2752. tor_assert(service_list);
  2753. /* This list is freed at registration time but this function can be called
  2754. * multiple time. */
  2755. if (hs_service_staging_list == NULL) {
  2756. hs_service_staging_list = smartlist_new();
  2757. }
  2758. /* Add all service object to our staging list. Caller is responsible for
  2759. * freeing the service_list. */
  2760. smartlist_add_all(hs_service_staging_list, service_list);
  2761. }
  2762. /* Allocate and initilize a service object. The service configuration will
  2763. * contain the default values. Return the newly allocated object pointer. This
  2764. * function can't fail. */
  2765. hs_service_t *
  2766. hs_service_new(const or_options_t *options)
  2767. {
  2768. hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
  2769. /* Set default configuration value. */
  2770. set_service_default_config(&service->config, options);
  2771. /* Set the default service version. */
  2772. service->config.version = HS_SERVICE_DEFAULT_VERSION;
  2773. /* Allocate the CLIENT_PK replay cache in service state. */
  2774. service->state.replay_cache_rend_cookie =
  2775. replaycache_new(REND_REPLAY_TIME_INTERVAL, REND_REPLAY_TIME_INTERVAL);
  2776. return service;
  2777. }
  2778. /* Free the given <b>service</b> object and all its content. This function
  2779. * also takes care of wiping service keys from memory. It is safe to pass a
  2780. * NULL pointer. */
  2781. void
  2782. hs_service_free(hs_service_t *service)
  2783. {
  2784. if (service == NULL) {
  2785. return;
  2786. }
  2787. /* Free descriptors. Go over both descriptor with this loop. */
  2788. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  2789. service_descriptor_free(desc);
  2790. } FOR_EACH_DESCRIPTOR_END;
  2791. /* Free service configuration. */
  2792. service_clear_config(&service->config);
  2793. /* Free replay cache from state. */
  2794. if (service->state.replay_cache_rend_cookie) {
  2795. replaycache_free(service->state.replay_cache_rend_cookie);
  2796. }
  2797. /* Wipe service keys. */
  2798. memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
  2799. tor_free(service);
  2800. }
  2801. /* Periodic callback. Entry point from the main loop to the HS service
  2802. * subsystem. This is call every second. This is skipped if tor can't build a
  2803. * circuit or the network is disabled. */
  2804. void
  2805. hs_service_run_scheduled_events(time_t now)
  2806. {
  2807. /* First thing we'll do here is to make sure our services are in a
  2808. * quiescent state for the scheduled events. */
  2809. run_housekeeping_event(now);
  2810. /* Order matters here. We first make sure the descriptor object for each
  2811. * service contains the latest data. Once done, we check if we need to open
  2812. * new introduction circuit. Finally, we try to upload the descriptor for
  2813. * each service. */
  2814. /* Make sure descriptors are up to date. */
  2815. run_build_descriptor_event(now);
  2816. /* Make sure services have enough circuits. */
  2817. run_build_circuit_event(now);
  2818. /* Upload the descriptors if needed/possible. */
  2819. run_upload_descriptor_event(now);
  2820. }
  2821. /* Initialize the service HS subsystem. */
  2822. void
  2823. hs_service_init(void)
  2824. {
  2825. /* Should never be called twice. */
  2826. tor_assert(!hs_service_map);
  2827. tor_assert(!hs_service_staging_list);
  2828. /* v2 specific. */
  2829. rend_service_init();
  2830. hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
  2831. HT_INIT(hs_service_ht, hs_service_map);
  2832. hs_service_staging_list = smartlist_new();
  2833. }
  2834. /* Release all global storage of the hidden service subsystem. */
  2835. void
  2836. hs_service_free_all(void)
  2837. {
  2838. rend_service_free_all();
  2839. service_free_all();
  2840. }
  2841. #ifdef TOR_UNIT_TESTS
  2842. /* Return the global service map size. Only used by unit test. */
  2843. STATIC unsigned int
  2844. get_hs_service_map_size(void)
  2845. {
  2846. return HT_SIZE(hs_service_map);
  2847. }
  2848. /* Return the staging list size. Only used by unit test. */
  2849. STATIC int
  2850. get_hs_service_staging_list_size(void)
  2851. {
  2852. return smartlist_len(hs_service_staging_list);
  2853. }
  2854. STATIC hs_service_ht *
  2855. get_hs_service_map(void)
  2856. {
  2857. return hs_service_map;
  2858. }
  2859. STATIC hs_service_t *
  2860. get_first_service(void)
  2861. {
  2862. hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
  2863. if (obj == NULL) {
  2864. return NULL;
  2865. }
  2866. return *obj;
  2867. }
  2868. #endif /* TOR_UNIT_TESTS */