hs_service.c 113 KB

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