hs_service.c 113 KB

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