hs_service.c 106 KB

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