hs_service.c 111 KB

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