hs_service.c 101 KB

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