hs_service.c 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  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 "main.h"
  15. #include "networkstatus.h"
  16. #include "nodelist.h"
  17. #include "relay.h"
  18. #include "rendservice.h"
  19. #include "router.h"
  20. #include "routerkeys.h"
  21. #include "routerlist.h"
  22. #include "hs_circuit.h"
  23. #include "hs_common.h"
  24. #include "hs_config.h"
  25. #include "hs_circuit.h"
  26. #include "hs_descriptor.h"
  27. #include "hs_ident.h"
  28. #include "hs_intropoint.h"
  29. #include "hs_service.h"
  30. /* Trunnel */
  31. #include "ed25519_cert.h"
  32. #include "hs/cell_establish_intro.h"
  33. #include "hs/cell_common.h"
  34. /* Helper macro. Iterate over every service in the global map. The var is the
  35. * name of the service pointer. */
  36. #define FOR_EACH_SERVICE_BEGIN(var) \
  37. STMT_BEGIN \
  38. hs_service_t **var##_iter, *var; \
  39. HT_FOREACH(var##_iter, hs_service_ht, hs_service_map) { \
  40. var = *var##_iter;
  41. #define FOR_EACH_SERVICE_END } STMT_END ;
  42. /* Helper macro. Iterate over both current and previous descriptor of a
  43. * service. The var is the name of the descriptor pointer. This macro skips
  44. * any descriptor object of the service that is NULL. */
  45. #define FOR_EACH_DESCRIPTOR_BEGIN(service, var) \
  46. STMT_BEGIN \
  47. hs_service_descriptor_t *var; \
  48. for (int var ## _loop_idx = 0; var ## _loop_idx < 2; \
  49. ++var ## _loop_idx) { \
  50. (var ## _loop_idx == 0) ? (var = service->desc_current) : \
  51. (var = service->desc_next); \
  52. if (var == NULL) continue;
  53. #define FOR_EACH_DESCRIPTOR_END } STMT_END ;
  54. /* Onion service directory file names. */
  55. static const char *fname_keyfile_prefix = "hs_ed25519";
  56. static const char *fname_hostname = "hostname";
  57. static const char *address_tld = "onion";
  58. /* Staging list of service object. When configuring service, we add them to
  59. * this list considered a staging area and they will get added to our global
  60. * map once the keys have been loaded. These two steps are seperated because
  61. * loading keys requires that we are an actual running tor process. */
  62. static smartlist_t *hs_service_staging_list;
  63. /* Helper: Function to compare two objects in the service map. Return 1 if the
  64. * two service have the same master public identity key. */
  65. static inline int
  66. hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
  67. {
  68. tor_assert(first);
  69. tor_assert(second);
  70. /* Simple key compare. */
  71. return ed25519_pubkey_eq(&first->keys.identity_pk,
  72. &second->keys.identity_pk);
  73. }
  74. /* Helper: Function for the service hash table code below. The key used is the
  75. * master public identity key which is ultimately the onion address. */
  76. static inline unsigned int
  77. hs_service_ht_hash(const hs_service_t *service)
  78. {
  79. tor_assert(service);
  80. return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
  81. sizeof(service->keys.identity_pk.pubkey));
  82. }
  83. /* This is _the_ global hash map of hidden services which indexed the service
  84. * contained in it by master public identity key which is roughly the onion
  85. * address of the service. */
  86. static struct hs_service_ht *hs_service_map;
  87. /* Register the service hash table. */
  88. HT_PROTOTYPE(hs_service_ht, /* Name of hashtable. */
  89. hs_service_t, /* Object contained in the map. */
  90. hs_service_node, /* The name of the HT_ENTRY member. */
  91. hs_service_ht_hash, /* Hashing function. */
  92. hs_service_ht_eq) /* Compare function for objects. */
  93. HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
  94. hs_service_ht_hash, hs_service_ht_eq,
  95. 0.6, tor_reallocarray, tor_free_)
  96. /* Query the given service map with a public key and return a service object
  97. * if found else NULL. It is also possible to set a directory path in the
  98. * search query. If pk is NULL, then it will be set to zero indicating the
  99. * hash table to compare the directory path instead. */
  100. STATIC hs_service_t *
  101. find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
  102. {
  103. hs_service_t dummy_service;
  104. tor_assert(map);
  105. tor_assert(pk);
  106. memset(&dummy_service, 0, sizeof(dummy_service));
  107. ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
  108. return HT_FIND(hs_service_ht, map, &dummy_service);
  109. }
  110. /* Register the given service in the given map. If the service already exists
  111. * in the map, -1 is returned. On success, 0 is returned and the service
  112. * ownership has been transfered to the global map. */
  113. STATIC int
  114. register_service(hs_service_ht *map, hs_service_t *service)
  115. {
  116. tor_assert(map);
  117. tor_assert(service);
  118. tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
  119. if (find_service(map, &service->keys.identity_pk)) {
  120. /* Existing service with the same key. Do not register it. */
  121. return -1;
  122. }
  123. /* Taking ownership of the object at this point. */
  124. HT_INSERT(hs_service_ht, map, service);
  125. return 0;
  126. }
  127. /* Remove a given service from the given map. If service is NULL or the
  128. * service key is unset, return gracefully. */
  129. STATIC void
  130. remove_service(hs_service_ht *map, hs_service_t *service)
  131. {
  132. hs_service_t *elm;
  133. tor_assert(map);
  134. /* Ignore if no service or key is zero. */
  135. if (BUG(service == NULL) ||
  136. BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
  137. return;
  138. }
  139. elm = HT_REMOVE(hs_service_ht, map, service);
  140. if (elm) {
  141. tor_assert(elm == service);
  142. } else {
  143. log_warn(LD_BUG, "Could not find service in the global map "
  144. "while removing service %s",
  145. escaped(service->config.directory_path));
  146. }
  147. }
  148. /* Set the default values for a service configuration object <b>c</b>. */
  149. static void
  150. set_service_default_config(hs_service_config_t *c,
  151. const or_options_t *options)
  152. {
  153. tor_assert(c);
  154. c->ports = smartlist_new();
  155. c->directory_path = NULL;
  156. c->descriptor_post_period = options->RendPostPeriod;
  157. c->max_streams_per_rdv_circuit = 0;
  158. c->max_streams_close_circuit = 0;
  159. c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
  160. c->allow_unknown_ports = 0;
  161. c->is_single_onion = 0;
  162. c->dir_group_readable = 0;
  163. c->is_ephemeral = 0;
  164. }
  165. /* From a service configuration object config, clear everything from it
  166. * meaning free allocated pointers and reset the values. */
  167. static void
  168. service_clear_config(hs_service_config_t *config)
  169. {
  170. if (config == NULL) {
  171. return;
  172. }
  173. tor_free(config->directory_path);
  174. if (config->ports) {
  175. SMARTLIST_FOREACH(config->ports, rend_service_port_config_t *, p,
  176. rend_service_port_config_free(p););
  177. smartlist_free(config->ports);
  178. }
  179. memset(config, 0, sizeof(*config));
  180. }
  181. /* Helper: Function that needs to return 1 for the HT for each loop which
  182. * frees every service in an hash map. */
  183. static int
  184. ht_free_service_(struct hs_service_t *service, void *data)
  185. {
  186. (void) data;
  187. hs_service_free(service);
  188. /* This function MUST return 1 so the given object is then removed from the
  189. * service map leading to this free of the object being safe. */
  190. return 1;
  191. }
  192. /* Free every service that can be found in the global map. Once done, clear
  193. * and free the global map. */
  194. static void
  195. service_free_all(void)
  196. {
  197. if (hs_service_map) {
  198. /* The free helper function returns 1 so this is safe. */
  199. hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
  200. HT_CLEAR(hs_service_ht, hs_service_map);
  201. tor_free(hs_service_map);
  202. hs_service_map = NULL;
  203. }
  204. if (hs_service_staging_list) {
  205. /* Cleanup staging list. */
  206. SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
  207. hs_service_free(s));
  208. smartlist_free(hs_service_staging_list);
  209. hs_service_staging_list = NULL;
  210. }
  211. }
  212. /* Free a given service intro point object. */
  213. static void
  214. service_intro_point_free(hs_service_intro_point_t *ip)
  215. {
  216. if (!ip) {
  217. return;
  218. }
  219. memwipe(&ip->auth_key_kp, 0, sizeof(ip->auth_key_kp));
  220. memwipe(&ip->enc_key_kp, 0, sizeof(ip->enc_key_kp));
  221. crypto_pk_free(ip->legacy_key);
  222. replaycache_free(ip->replay_cache);
  223. hs_intro_free_content(&ip->base);
  224. tor_free(ip);
  225. }
  226. /* Helper: free an hs_service_intro_point_t object. This function is used by
  227. * digest256map_free() which requires a void * pointer. */
  228. static void
  229. service_intro_point_free_(void *obj)
  230. {
  231. service_intro_point_free(obj);
  232. }
  233. /* Return a newly allocated service intro point and fully initialized from the
  234. * given extend_info_t ei if non NULL. If is_legacy is true, we also generate
  235. * the legacy key. On error, NULL is returned. */
  236. static hs_service_intro_point_t *
  237. service_intro_point_new(const extend_info_t *ei, unsigned int is_legacy)
  238. {
  239. hs_desc_link_specifier_t *ls;
  240. hs_service_intro_point_t *ip;
  241. ip = tor_malloc_zero(sizeof(*ip));
  242. /* We'll create the key material. No need for extra strong, those are short
  243. * term keys. */
  244. ed25519_keypair_generate(&ip->auth_key_kp, 0);
  245. /* XXX: These will be controlled by consensus params. (#20961) */
  246. ip->introduce2_max =
  247. crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  248. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
  249. ip->time_to_expire = time(NULL) +
  250. crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
  251. INTRO_POINT_LIFETIME_MAX_SECONDS);
  252. ip->replay_cache = replaycache_new(0, 0);
  253. /* Initialize the base object. We don't need the certificate object. */
  254. ip->base.link_specifiers = smartlist_new();
  255. /* Generate the encryption key for this intro point. */
  256. curve25519_keypair_generate(&ip->enc_key_kp, 0);
  257. /* Figure out if this chosen node supports v3 or is legacy only. */
  258. if (is_legacy) {
  259. ip->base.is_only_legacy = 1;
  260. /* Legacy mode that is doesn't support v3+ with ed25519 auth key. */
  261. ip->legacy_key = crypto_pk_new();
  262. if (crypto_pk_generate_key(ip->legacy_key) < 0) {
  263. goto err;
  264. }
  265. }
  266. if (ei == NULL) {
  267. goto done;
  268. }
  269. /* We'll try to add all link specifier. Legacy, IPv4 and ed25519 are
  270. * mandatory. */
  271. ls = hs_desc_link_specifier_new(ei, LS_IPV4);
  272. /* It is impossible to have an extend info object without a v4. */
  273. tor_assert(ls);
  274. smartlist_add(ip->base.link_specifiers, ls);
  275. ls = hs_desc_link_specifier_new(ei, LS_LEGACY_ID);
  276. /* It is impossible to have an extend info object without an identity
  277. * digest. */
  278. tor_assert(ls);
  279. smartlist_add(ip->base.link_specifiers, ls);
  280. ls = hs_desc_link_specifier_new(ei, LS_ED25519_ID);
  281. /* It is impossible to have an extend info object without an ed25519
  282. * identity key. */
  283. tor_assert(ls);
  284. smartlist_add(ip->base.link_specifiers, ls);
  285. /* IPv6 is optional. */
  286. ls = hs_desc_link_specifier_new(ei, LS_IPV6);
  287. if (ls) {
  288. smartlist_add(ip->base.link_specifiers, ls);
  289. }
  290. /* Finally, copy onion key from the extend_info_t object. */
  291. memcpy(&ip->onion_key, &ei->curve25519_onion_key, sizeof(ip->onion_key));
  292. done:
  293. return ip;
  294. err:
  295. service_intro_point_free(ip);
  296. return NULL;
  297. }
  298. /* Add the given intro point object to the given intro point map. The intro
  299. * point MUST have its RSA encryption key set if this is a legacy type or the
  300. * authentication key set otherwise. */
  301. static void
  302. service_intro_point_add(digest256map_t *map, hs_service_intro_point_t *ip)
  303. {
  304. tor_assert(map);
  305. tor_assert(ip);
  306. digest256map_set(map, ip->auth_key_kp.pubkey.pubkey, ip);
  307. }
  308. /* For a given service, remove the intro point from that service which will
  309. * look in both descriptors. */
  310. static void
  311. service_intro_point_remove(const hs_service_t *service,
  312. const hs_service_intro_point_t *ip)
  313. {
  314. tor_assert(service);
  315. tor_assert(ip);
  316. /* Trying all descriptors. */
  317. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  318. /* We'll try to remove the descriptor on both descriptors which is not
  319. * very expensive to do instead of doing loopup + remove. */
  320. digest256map_remove(desc->intro_points.map,
  321. ip->auth_key_kp.pubkey.pubkey);
  322. } FOR_EACH_DESCRIPTOR_END;
  323. }
  324. /* For a given service and authentication key, return the intro point or NULL
  325. * if not found. This will check both descriptors in the service. */
  326. static hs_service_intro_point_t *
  327. service_intro_point_find(const hs_service_t *service,
  328. const ed25519_public_key_t *auth_key)
  329. {
  330. hs_service_intro_point_t *ip = NULL;
  331. tor_assert(service);
  332. tor_assert(auth_key);
  333. /* Trying all descriptors. */
  334. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  335. if ((ip = digest256map_get(desc->intro_points.map,
  336. auth_key->pubkey)) != NULL) {
  337. break;
  338. }
  339. } FOR_EACH_DESCRIPTOR_END;
  340. return ip;
  341. }
  342. /* For a given service and intro point, return the descriptor for which the
  343. * intro point is assigned to. NULL is returned if not found. */
  344. static hs_service_descriptor_t *
  345. service_desc_find_by_intro(const hs_service_t *service,
  346. const hs_service_intro_point_t *ip)
  347. {
  348. hs_service_descriptor_t *descp = NULL;
  349. tor_assert(service);
  350. tor_assert(ip);
  351. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  352. if (digest256map_get(desc->intro_points.map,
  353. ip->auth_key_kp.pubkey.pubkey)) {
  354. descp = desc;
  355. break;
  356. }
  357. } FOR_EACH_DESCRIPTOR_END;
  358. return descp;
  359. }
  360. /* From a given intro point, return the first link specifier of type
  361. * encountered in the link specifier list. Return NULL if it can't be found.
  362. *
  363. * The caller does NOT have ownership of the object, the intro point does. */
  364. static hs_desc_link_specifier_t *
  365. get_link_spec_by_type(const hs_service_intro_point_t *ip, uint8_t type)
  366. {
  367. hs_desc_link_specifier_t *lnk_spec = NULL;
  368. tor_assert(ip);
  369. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  370. hs_desc_link_specifier_t *, ls) {
  371. if (ls->type == type) {
  372. lnk_spec = ls;
  373. goto end;
  374. }
  375. } SMARTLIST_FOREACH_END(ls);
  376. end:
  377. return lnk_spec;
  378. }
  379. /* Given a service intro point, return the node_t associated to it. This can
  380. * return NULL if the given intro point has no legacy ID or if the node can't
  381. * be found in the consensus. */
  382. static const node_t *
  383. get_node_from_intro_point(const hs_service_intro_point_t *ip)
  384. {
  385. const hs_desc_link_specifier_t *ls;
  386. tor_assert(ip);
  387. ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  388. /* Legacy ID is mandatory for an intro point object to have. */
  389. tor_assert(ls);
  390. /* XXX In the future, we want to only use the ed25519 ID (#22173). */
  391. return node_get_by_id((const char *) ls->u.legacy_id);
  392. }
  393. /* Given a service intro point, return the extend_info_t for it. This can
  394. * return NULL if the node can't be found for the intro point or the extend
  395. * info can't be created for the found node. If direct_conn is set, the extend
  396. * info is validated on if we can connect directly. */
  397. static extend_info_t *
  398. get_extend_info_from_intro_point(const hs_service_intro_point_t *ip,
  399. unsigned int direct_conn)
  400. {
  401. extend_info_t *info = NULL;
  402. const node_t *node;
  403. tor_assert(ip);
  404. node = get_node_from_intro_point(ip);
  405. if (node == NULL) {
  406. /* This can happen if the relay serving as intro point has been removed
  407. * from the consensus. In that case, the intro point will be removed from
  408. * the descriptor during the scheduled events. */
  409. goto end;
  410. }
  411. /* In the case of a direct connection (single onion service), it is possible
  412. * our firewall policy won't allow it so this can return a NULL value. */
  413. info = extend_info_from_node(node, direct_conn);
  414. end:
  415. return info;
  416. }
  417. /* Return an introduction point circuit matching the given intro point object.
  418. * NULL is returned is no such circuit can be found. */
  419. static origin_circuit_t *
  420. get_intro_circuit(const hs_service_intro_point_t *ip)
  421. {
  422. origin_circuit_t *circ = NULL;
  423. tor_assert(ip);
  424. if (ip->base.is_only_legacy) {
  425. uint8_t digest[DIGEST_LEN];
  426. if (BUG(crypto_pk_get_digest(ip->legacy_key, (char *) digest) < 0)) {
  427. goto end;
  428. }
  429. circ = hs_circuitmap_get_intro_circ_v2_service_side(digest);
  430. } else {
  431. circ = hs_circuitmap_get_intro_circ_v3_service_side(
  432. &ip->auth_key_kp.pubkey);
  433. }
  434. end:
  435. return circ;
  436. }
  437. /* Close all rendezvous circuits for the given service. */
  438. static void
  439. close_service_rp_circuits(hs_service_t *service)
  440. {
  441. origin_circuit_t *ocirc = NULL;
  442. tor_assert(service);
  443. /* The reason we go over all circuit instead of using the circuitmap API is
  444. * because most hidden service circuits are rendezvous circuits so there is
  445. * no real improvement at getting all rendezvous circuits from the
  446. * circuitmap and then going over them all to find the right ones.
  447. * Furthermore, another option would have been to keep a list of RP cookies
  448. * for a service but it creates an engineering complexity since we don't
  449. * have a "RP circuit closed" event to clean it up properly so we avoid a
  450. * memory DoS possibility. */
  451. while ((ocirc = circuit_get_next_service_rp_circ(ocirc))) {
  452. /* Only close circuits that are v3 and for this service. */
  453. if (ocirc->hs_ident != NULL &&
  454. ed25519_pubkey_eq(&ocirc->hs_ident->identity_pk,
  455. &service->keys.identity_pk)) {
  456. /* Reason is FINISHED because service has been removed and thus the
  457. * circuit is considered old/uneeded. When freed, it is removed from the
  458. * hs circuitmap. */
  459. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  460. }
  461. }
  462. }
  463. /* Close the circuit(s) for the given map of introduction points. */
  464. static void
  465. close_intro_circuits(hs_service_intropoints_t *intro_points)
  466. {
  467. tor_assert(intro_points);
  468. DIGEST256MAP_FOREACH(intro_points->map, key,
  469. const hs_service_intro_point_t *, ip) {
  470. origin_circuit_t *ocirc = get_intro_circuit(ip);
  471. if (ocirc) {
  472. /* Reason is FINISHED because service has been removed and thus the
  473. * circuit is considered old/uneeded. When freed, the circuit is removed
  474. * from the HS circuitmap. */
  475. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  476. }
  477. } DIGEST256MAP_FOREACH_END;
  478. }
  479. /* Close all introduction circuits for the given service. */
  480. static void
  481. close_service_intro_circuits(hs_service_t *service)
  482. {
  483. tor_assert(service);
  484. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  485. close_intro_circuits(&desc->intro_points);
  486. } FOR_EACH_DESCRIPTOR_END;
  487. }
  488. /* Close any circuits related to the given service. */
  489. static void
  490. close_service_circuits(hs_service_t *service)
  491. {
  492. tor_assert(service);
  493. /* Only support for version >= 3. */
  494. if (BUG(service->config.version < HS_VERSION_THREE)) {
  495. return;
  496. }
  497. /* Close intro points. */
  498. close_service_intro_circuits(service);
  499. /* Close rendezvous points. */
  500. close_service_rp_circuits(service);
  501. }
  502. /* Move introduction points from the src descriptor to the dst descriptor. The
  503. * destination service intropoints are wiped out if any before moving. */
  504. static void
  505. move_descriptor_intro_points(hs_service_descriptor_t *src,
  506. hs_service_descriptor_t *dst)
  507. {
  508. tor_assert(src);
  509. tor_assert(dst);
  510. digest256map_free(dst->intro_points.map, service_intro_point_free_);
  511. dst->intro_points.map = src->intro_points.map;
  512. /* Nullify the source. */
  513. src->intro_points.map = NULL;
  514. }
  515. /* Move introduction points from the src service to the dst service. The
  516. * destination service intropoints are wiped out if any before moving. */
  517. static void
  518. move_intro_points(hs_service_t *src, hs_service_t *dst)
  519. {
  520. tor_assert(src);
  521. tor_assert(dst);
  522. if (src->desc_current && dst->desc_current) {
  523. move_descriptor_intro_points(src->desc_current, dst->desc_current);
  524. }
  525. if (src->desc_next && dst->desc_next) {
  526. move_descriptor_intro_points(src->desc_next, dst->desc_next);
  527. }
  528. }
  529. /* Move every ephemeral services from the src service map to the dst service
  530. * map. It is possible that a service can't be register to the dst map which
  531. * won't stop the process of moving them all but will trigger a log warn. */
  532. static void
  533. move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
  534. {
  535. hs_service_t **iter, **next;
  536. tor_assert(src);
  537. tor_assert(dst);
  538. /* Iterate over the map to find ephemeral service and move them to the other
  539. * map. We loop using this method to have a safe removal process. */
  540. for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
  541. hs_service_t *s = *iter;
  542. if (!s->config.is_ephemeral) {
  543. /* Yeah, we are in a very manual loop :). */
  544. next = HT_NEXT(hs_service_ht, src, iter);
  545. continue;
  546. }
  547. /* Remove service from map and then register to it to the other map.
  548. * Reminder that "*iter" and "s" are the same thing. */
  549. next = HT_NEXT_RMV(hs_service_ht, src, iter);
  550. if (register_service(dst, s) < 0) {
  551. log_warn(LD_BUG, "Ephemeral service key is already being used. "
  552. "Skipping.");
  553. }
  554. }
  555. }
  556. /* Return a const string of the directory path escaped. If this is an
  557. * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
  558. * the main thread because escaped() uses a static variable. */
  559. static const char *
  560. service_escaped_dir(const hs_service_t *s)
  561. {
  562. return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
  563. escaped(s->config.directory_path);
  564. }
  565. /* Register services that are in the staging list. Once this function returns,
  566. * the global service map will be set with the right content and all non
  567. * surviving services will be cleaned up. */
  568. static void
  569. register_all_services(void)
  570. {
  571. struct hs_service_ht *new_service_map;
  572. tor_assert(hs_service_staging_list);
  573. /* We'll save us some allocation and computing time. */
  574. if (smartlist_len(hs_service_staging_list) == 0) {
  575. return;
  576. }
  577. /* Allocate a new map that will replace the current one. */
  578. new_service_map = tor_malloc_zero(sizeof(*new_service_map));
  579. HT_INIT(hs_service_ht, new_service_map);
  580. /* First step is to transfer all ephemeral services from the current global
  581. * map to the new one we are constructing. We do not prune ephemeral
  582. * services as the only way to kill them is by deleting it from the control
  583. * port or stopping the tor daemon. */
  584. move_ephemeral_services(hs_service_map, new_service_map);
  585. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
  586. hs_service_t *s;
  587. /* Check if that service is already in our global map and if so, we'll
  588. * transfer the intro points to it. */
  589. s = find_service(hs_service_map, &snew->keys.identity_pk);
  590. if (s) {
  591. /* Pass ownership of intro points from s (the current service) to snew
  592. * (the newly configured one). */
  593. move_intro_points(s, snew);
  594. /* Remove the service from the global map because after this, we need to
  595. * go over the remaining service in that map that aren't surviving the
  596. * reload to close their circuits. */
  597. remove_service(hs_service_map, s);
  598. }
  599. /* Great, this service is now ready to be added to our new map. */
  600. if (BUG(register_service(new_service_map, snew) < 0)) {
  601. /* This should never happen because prior to registration, we validate
  602. * every service against the entire set. Not being able to register a
  603. * service means we failed to validate correctly. In that case, don't
  604. * break tor and ignore the service but tell user. */
  605. log_warn(LD_BUG, "Unable to register service with directory %s",
  606. service_escaped_dir(snew));
  607. SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
  608. hs_service_free(snew);
  609. }
  610. } SMARTLIST_FOREACH_END(snew);
  611. /* Close any circuits associated with the non surviving services. Every
  612. * service in the current global map are roaming. */
  613. FOR_EACH_SERVICE_BEGIN(service) {
  614. close_service_circuits(service);
  615. } FOR_EACH_SERVICE_END;
  616. /* Time to make the switch. We'll clear the staging list because its content
  617. * has now changed ownership to the map. */
  618. smartlist_clear(hs_service_staging_list);
  619. service_free_all();
  620. hs_service_map = new_service_map;
  621. }
  622. /* Write the onion address of a given service to the given filename fname_ in
  623. * the service directory. Return 0 on success else -1 on error. */
  624. static int
  625. write_address_to_file(const hs_service_t *service, const char *fname_)
  626. {
  627. int ret = -1;
  628. char *fname = NULL;
  629. /* Length of an address plus the sizeof the address tld (onion) which counts
  630. * the NUL terminated byte so we keep it for the "." and the newline. */
  631. char buf[HS_SERVICE_ADDR_LEN_BASE32 + sizeof(address_tld) + 1];
  632. tor_assert(service);
  633. tor_assert(fname_);
  634. /* Construct the full address with the onion tld and write the hostname file
  635. * to disk. */
  636. tor_snprintf(buf, sizeof(buf), "%s.%s\n", service->onion_address,
  637. address_tld);
  638. /* Notice here that we use the given "fname_". */
  639. fname = hs_path_from_filename(service->config.directory_path, fname_);
  640. if (write_str_to_file(fname, buf, 0) < 0) {
  641. log_warn(LD_REND, "Could not write onion address to hostname file %s",
  642. escaped(fname));
  643. goto end;
  644. }
  645. #ifndef _WIN32
  646. if (service->config.dir_group_readable) {
  647. /* Mode to 0640. */
  648. if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
  649. log_warn(LD_FS, "Unable to make onion service hostname file %s "
  650. "group-readable.", escaped(fname));
  651. }
  652. }
  653. #endif /* _WIN32 */
  654. /* Success. */
  655. ret = 0;
  656. end:
  657. tor_free(fname);
  658. return ret;
  659. }
  660. /* Load and/or generate private keys for the given service. On success, the
  661. * hostname file will be written to disk along with the master private key iff
  662. * the service is not configured for offline keys. Return 0 on success else -1
  663. * on failure. */
  664. static int
  665. load_service_keys(hs_service_t *service)
  666. {
  667. int ret = -1;
  668. char *fname = NULL;
  669. ed25519_keypair_t *kp;
  670. const hs_service_config_t *config;
  671. tor_assert(service);
  672. config = &service->config;
  673. /* Create and fix permission on service directory. We are about to write
  674. * files to that directory so make sure it exists and has the right
  675. * permissions. We do this here because at this stage we know that Tor is
  676. * actually running and the service we have has been validated. */
  677. if (BUG(hs_check_service_private_dir(get_options()->User,
  678. config->directory_path,
  679. config->dir_group_readable, 1) < 0)) {
  680. goto end;
  681. }
  682. /* Try to load the keys from file or generate it if not found. */
  683. fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
  684. /* Don't ask for key creation, we want to know if we were able to load it or
  685. * we had to generate it. Better logging! */
  686. kp = ed_key_init_from_file(fname, 0, LOG_INFO, NULL, 0, 0, 0, NULL);
  687. if (!kp) {
  688. log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
  689. /* We'll now try to generate the keys and for it we want the strongest
  690. * randomness for it. The keypair will be written in different files. */
  691. uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
  692. INIT_ED_KEY_SPLIT;
  693. kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
  694. NULL);
  695. if (!kp) {
  696. log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
  697. goto end;
  698. }
  699. }
  700. /* Copy loaded or generated keys to service object. */
  701. ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
  702. memcpy(&service->keys.identity_sk, &kp->seckey,
  703. sizeof(service->keys.identity_sk));
  704. /* This does a proper memory wipe. */
  705. ed25519_keypair_free(kp);
  706. /* Build onion address from the newly loaded keys. */
  707. tor_assert(service->config.version <= UINT8_MAX);
  708. hs_build_address(&service->keys.identity_pk,
  709. (uint8_t) service->config.version,
  710. service->onion_address);
  711. /* Write onion address to hostname file. */
  712. if (write_address_to_file(service, fname_hostname) < 0) {
  713. goto end;
  714. }
  715. /* Succes. */
  716. ret = 0;
  717. end:
  718. tor_free(fname);
  719. return ret;
  720. }
  721. /* Free a given service descriptor object and all key material is wiped. */
  722. static void
  723. service_descriptor_free(hs_service_descriptor_t *desc)
  724. {
  725. if (!desc) {
  726. return;
  727. }
  728. hs_descriptor_free(desc->desc);
  729. memwipe(&desc->signing_kp, 0, sizeof(desc->signing_kp));
  730. memwipe(&desc->blinded_kp, 0, sizeof(desc->blinded_kp));
  731. /* Cleanup all intro points. */
  732. digest256map_free(desc->intro_points.map, service_intro_point_free_);
  733. tor_free(desc);
  734. }
  735. /* Return a newly allocated service descriptor object. */
  736. static hs_service_descriptor_t *
  737. service_descriptor_new(void)
  738. {
  739. hs_service_descriptor_t *sdesc = tor_malloc_zero(sizeof(*sdesc));
  740. sdesc->desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  741. /* Initialize the intro points map. */
  742. sdesc->intro_points.map = digest256map_new();
  743. return sdesc;
  744. }
  745. /* Copy the descriptor link specifier object from src to dst. */
  746. static void
  747. link_specifier_copy(hs_desc_link_specifier_t *dst,
  748. const hs_desc_link_specifier_t *src)
  749. {
  750. tor_assert(dst);
  751. tor_assert(src);
  752. memcpy(dst, src, sizeof(hs_desc_link_specifier_t));
  753. }
  754. /* Using a given descriptor signing keypair signing_kp, a service intro point
  755. * object ip and the time now, setup the content of an already allocated
  756. * descriptor intro desc_ip.
  757. *
  758. * Return 0 on success else a negative value. */
  759. static int
  760. setup_desc_intro_point(const ed25519_keypair_t *signing_kp,
  761. const hs_service_intro_point_t *ip,
  762. time_t now, hs_desc_intro_point_t *desc_ip)
  763. {
  764. int ret = -1;
  765. time_t nearest_hour = now - (now % 3600);
  766. tor_assert(signing_kp);
  767. tor_assert(ip);
  768. tor_assert(desc_ip);
  769. /* Copy the onion key. */
  770. memcpy(&desc_ip->onion_key, &ip->onion_key, sizeof(desc_ip->onion_key));
  771. /* Key and certificate material. */
  772. desc_ip->auth_key_cert = tor_cert_create(signing_kp,
  773. CERT_TYPE_AUTH_HS_IP_KEY,
  774. &ip->auth_key_kp.pubkey,
  775. nearest_hour,
  776. HS_DESC_CERT_LIFETIME,
  777. CERT_FLAG_INCLUDE_SIGNING_KEY);
  778. if (desc_ip->auth_key_cert == NULL) {
  779. log_warn(LD_REND, "Unable to create intro point auth-key certificate");
  780. goto done;
  781. }
  782. /* Copy link specifier(s). */
  783. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  784. const hs_desc_link_specifier_t *, ls) {
  785. hs_desc_link_specifier_t *dup = tor_malloc_zero(sizeof(*dup));
  786. link_specifier_copy(dup, ls);
  787. smartlist_add(desc_ip->link_specifiers, dup);
  788. } SMARTLIST_FOREACH_END(ls);
  789. /* For a legacy intro point, we'll use an RSA/ed cross certificate. */
  790. if (ip->base.is_only_legacy) {
  791. desc_ip->legacy.key = crypto_pk_dup_key(ip->legacy_key);
  792. /* Create cross certification cert. */
  793. ssize_t cert_len = tor_make_rsa_ed25519_crosscert(
  794. &signing_kp->pubkey,
  795. desc_ip->legacy.key,
  796. nearest_hour + HS_DESC_CERT_LIFETIME,
  797. &desc_ip->legacy.cert.encoded);
  798. if (cert_len < 0) {
  799. log_warn(LD_REND, "Unable to create enc key legacy cross cert.");
  800. goto done;
  801. }
  802. desc_ip->legacy.cert.len = cert_len;
  803. }
  804. /* Encryption key and its cross certificate. */
  805. {
  806. ed25519_public_key_t ed25519_pubkey;
  807. /* Use the public curve25519 key. */
  808. memcpy(&desc_ip->enc_key, &ip->enc_key_kp.pubkey,
  809. sizeof(desc_ip->enc_key));
  810. /* The following can't fail. */
  811. ed25519_public_key_from_curve25519_public_key(&ed25519_pubkey,
  812. &ip->enc_key_kp.pubkey,
  813. 0);
  814. desc_ip->enc_key_cert = tor_cert_create(signing_kp,
  815. CERT_TYPE_CROSS_HS_IP_KEYS,
  816. &ed25519_pubkey, nearest_hour,
  817. HS_DESC_CERT_LIFETIME,
  818. CERT_FLAG_INCLUDE_SIGNING_KEY);
  819. if (desc_ip->enc_key_cert == NULL) {
  820. log_warn(LD_REND, "Unable to create enc key curve25519 cross cert.");
  821. goto done;
  822. }
  823. }
  824. /* Success. */
  825. ret = 0;
  826. done:
  827. return ret;
  828. }
  829. /* Using the given descriptor from the given service, build the descriptor
  830. * intro point list so we can then encode the descriptor for publication. This
  831. * function does not pick intro points, they have to be in the descriptor
  832. * current map. Cryptographic material (keys) must be initialized in the
  833. * descriptor for this function to make sense. */
  834. static void
  835. build_desc_intro_points(const hs_service_t *service,
  836. hs_service_descriptor_t *desc, time_t now)
  837. {
  838. hs_desc_encrypted_data_t *encrypted;
  839. tor_assert(service);
  840. tor_assert(desc);
  841. /* Ease our life. */
  842. encrypted = &desc->desc->encrypted_data;
  843. /* Cleanup intro points, we are about to set them from scratch. */
  844. hs_descriptor_free_intro_points(desc->desc);
  845. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  846. const hs_service_intro_point_t *, ip) {
  847. hs_desc_intro_point_t *desc_ip = hs_desc_intro_point_new();
  848. if (setup_desc_intro_point(&desc->signing_kp, ip, now, desc_ip) < 0) {
  849. hs_desc_intro_point_free(desc_ip);
  850. continue;
  851. }
  852. /* We have a valid descriptor intro point. Add it to the list. */
  853. smartlist_add(encrypted->intro_points, desc_ip);
  854. } DIGEST256MAP_FOREACH_END;
  855. }
  856. /* Populate the descriptor encrypted section fomr the given service object.
  857. * This will generate a valid list of introduction points that can be used
  858. * after for circuit creation. Return 0 on success else -1 on error. */
  859. static int
  860. build_service_desc_encrypted(const hs_service_t *service,
  861. hs_service_descriptor_t *desc)
  862. {
  863. hs_desc_encrypted_data_t *encrypted;
  864. tor_assert(service);
  865. tor_assert(desc);
  866. encrypted = &desc->desc->encrypted_data;
  867. encrypted->create2_ntor = 1;
  868. encrypted->single_onion_service = service->config.is_single_onion;
  869. /* Setup introduction points from what we have in the service. */
  870. if (encrypted->intro_points == NULL) {
  871. encrypted->intro_points = smartlist_new();
  872. }
  873. /* We do NOT build introduction point yet, we only do that once the circuit
  874. * have been opened. Until we have the right number of introduction points,
  875. * we do not encode anything in the descriptor. */
  876. /* XXX: Support client authorization (#20700). */
  877. encrypted->intro_auth_types = NULL;
  878. return 0;
  879. }
  880. /* Populare the descriptor plaintext section from the given service object.
  881. * The caller must make sure that the keys in the descriptors are valid that
  882. * is are non-zero. Return 0 on success else -1 on error. */
  883. static int
  884. build_service_desc_plaintext(const hs_service_t *service,
  885. hs_service_descriptor_t *desc, time_t now)
  886. {
  887. int ret = -1;
  888. hs_desc_plaintext_data_t *plaintext;
  889. tor_assert(service);
  890. tor_assert(desc);
  891. /* XXX: Use a "assert_desc_ok()" ? */
  892. tor_assert(!tor_mem_is_zero((char *) &desc->blinded_kp,
  893. sizeof(desc->blinded_kp)));
  894. tor_assert(!tor_mem_is_zero((char *) &desc->signing_kp,
  895. sizeof(desc->signing_kp)));
  896. /* Set the subcredential. */
  897. hs_get_subcredential(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
  898. desc->desc->subcredential);
  899. plaintext = &desc->desc->plaintext_data;
  900. plaintext->version = service->config.version;
  901. plaintext->lifetime_sec = HS_DESC_DEFAULT_LIFETIME;
  902. plaintext->signing_key_cert =
  903. tor_cert_create(&desc->blinded_kp, CERT_TYPE_SIGNING_HS_DESC,
  904. &desc->signing_kp.pubkey, now, HS_DESC_CERT_LIFETIME,
  905. CERT_FLAG_INCLUDE_SIGNING_KEY);
  906. if (plaintext->signing_key_cert == NULL) {
  907. log_warn(LD_REND, "Unable to create descriptor signing certificate for "
  908. "service %s",
  909. safe_str_client(service->onion_address));
  910. goto end;
  911. }
  912. /* Copy public key material to go in the descriptor. */
  913. ed25519_pubkey_copy(&plaintext->signing_pubkey, &desc->signing_kp.pubkey);
  914. ed25519_pubkey_copy(&plaintext->blinded_pubkey, &desc->blinded_kp.pubkey);
  915. /* Success. */
  916. ret = 0;
  917. end:
  918. return ret;
  919. }
  920. /* For the given service and descriptor object, create the key material which
  921. * is the blinded keypair and the descriptor signing keypair. Return 0 on
  922. * success else -1 on error where the generated keys MUST be ignored. */
  923. static int
  924. build_service_desc_keys(const hs_service_t *service,
  925. hs_service_descriptor_t *desc,
  926. uint64_t time_period_num)
  927. {
  928. int ret = 0;
  929. ed25519_keypair_t kp;
  930. tor_assert(desc);
  931. tor_assert(!tor_mem_is_zero((char *) &service->keys.identity_pk,
  932. ED25519_PUBKEY_LEN));
  933. /* XXX: Support offline key feature (#18098). */
  934. /* Copy the identity keys to the keypair so we can use it to create the
  935. * blinded key. */
  936. memcpy(&kp.pubkey, &service->keys.identity_pk, sizeof(kp.pubkey));
  937. memcpy(&kp.seckey, &service->keys.identity_sk, sizeof(kp.seckey));
  938. /* Build blinded keypair for this time period. */
  939. hs_build_blinded_keypair(&kp, NULL, 0, time_period_num, &desc->blinded_kp);
  940. /* Let's not keep too much traces of our keys in memory. */
  941. memwipe(&kp, 0, sizeof(kp));
  942. /* No need for extra strong, this is a temporary key only for this
  943. * descriptor. Nothing long term. */
  944. if (ed25519_keypair_generate(&desc->signing_kp, 0) < 0) {
  945. log_warn(LD_REND, "Can't generate descriptor signing keypair for "
  946. "service %s",
  947. safe_str_client(service->onion_address));
  948. ret = -1;
  949. }
  950. return ret;
  951. }
  952. /* Given a service and the current time, build a descriptor for the service.
  953. * This function does not pick introduction point, this needs to be done by
  954. * the update function. On success, desc_out will point to the newly allocated
  955. * descriptor object.
  956. *
  957. * This can error if we are unable to create keys or certificate. */
  958. static void
  959. build_service_descriptor(hs_service_t *service, time_t now,
  960. uint64_t time_period_num,
  961. hs_service_descriptor_t **desc_out)
  962. {
  963. char *encoded_desc;
  964. hs_service_descriptor_t *desc;
  965. tor_assert(service);
  966. tor_assert(desc_out);
  967. desc = service_descriptor_new();
  968. /* Create the needed keys so we can setup the descriptor content. */
  969. if (build_service_desc_keys(service, desc, time_period_num) < 0) {
  970. goto err;
  971. }
  972. /* Setup plaintext descriptor content. */
  973. if (build_service_desc_plaintext(service, desc, now) < 0) {
  974. goto err;
  975. }
  976. /* Setup encrypted descriptor content. */
  977. if (build_service_desc_encrypted(service, desc) < 0) {
  978. goto err;
  979. }
  980. /* Let's make sure that we've created a descriptor that can actually be
  981. * encoded properly. This function also checks if the encoded output is
  982. * decodable after. */
  983. if (BUG(hs_desc_encode_descriptor(desc->desc, &desc->signing_kp,
  984. &encoded_desc) < 0)) {
  985. goto err;
  986. }
  987. tor_free(encoded_desc);
  988. /* Assign newly built descriptor to the next slot. */
  989. *desc_out = desc;
  990. return;
  991. err:
  992. service_descriptor_free(desc);
  993. }
  994. /* Build descriptors for each service if needed. There are conditions to build
  995. * a descriptor which are details in the function. */
  996. static void
  997. build_all_descriptors(time_t now)
  998. {
  999. FOR_EACH_SERVICE_BEGIN(service) {
  1000. if (service->desc_current == NULL) {
  1001. /* This means we just booted up because else this descriptor will never
  1002. * be NULL as it should always point to the descriptor that was in
  1003. * desc_next after rotation. */
  1004. build_service_descriptor(service, now, hs_get_time_period_num(now),
  1005. &service->desc_current);
  1006. log_info(LD_REND, "Hidden service %s current descriptor successfully "
  1007. "built. Now scheduled for upload.",
  1008. safe_str_client(service->onion_address));
  1009. }
  1010. /* A next descriptor to NULL indicate that we need to build a fresh one if
  1011. * we are in the overlap period for the _next_ time period since it means
  1012. * we either just booted or we just rotated our descriptors. */
  1013. if (hs_overlap_mode_is_active(NULL, now) && service->desc_next == NULL) {
  1014. build_service_descriptor(service, now, hs_get_next_time_period_num(now),
  1015. &service->desc_next);
  1016. log_info(LD_REND, "Hidden service %s next descriptor successfully "
  1017. "built. Now scheduled for upload.",
  1018. safe_str_client(service->onion_address));
  1019. }
  1020. } FOR_EACH_DESCRIPTOR_END;
  1021. }
  1022. /* Randomly pick a node to become an introduction point but not present in the
  1023. * given exclude_nodes list. The chosen node is put in the exclude list
  1024. * regardless of success or not because in case of failure, the node is simply
  1025. * unsusable from that point on. If direct_conn is set, try to pick a node
  1026. * that our local firewall/policy allows to directly connect to and if not,
  1027. * fallback to a normal 3-hop node. Return a newly allocated service intro
  1028. * point ready to be used for encoding. NULL on error. */
  1029. static hs_service_intro_point_t *
  1030. pick_intro_point(unsigned int direct_conn, smartlist_t *exclude_nodes)
  1031. {
  1032. const node_t *node;
  1033. extend_info_t *info = NULL;
  1034. hs_service_intro_point_t *ip = NULL;
  1035. /* Normal 3-hop introduction point flags. */
  1036. router_crn_flags_t flags = CRN_NEED_UPTIME | CRN_NEED_DESC;
  1037. /* Single onion flags. */
  1038. router_crn_flags_t direct_flags = flags | CRN_PREF_ADDR | CRN_DIRECT_CONN;
  1039. node = router_choose_random_node(exclude_nodes, get_options()->ExcludeNodes,
  1040. direct_conn ? direct_flags : flags);
  1041. if (node == NULL && direct_conn) {
  1042. /* Unable to find a node for direct connection, let's fall back to a
  1043. * normal 3-hop node. */
  1044. node = router_choose_random_node(exclude_nodes,
  1045. get_options()->ExcludeNodes, flags);
  1046. }
  1047. if (!node) {
  1048. goto err;
  1049. }
  1050. /* We have a suitable node, add it to the exclude list. We do this *before*
  1051. * we can validate the extend information because even in case of failure,
  1052. * we don't want to use that node anymore. */
  1053. smartlist_add(exclude_nodes, (void *) node);
  1054. /* We do this to ease our life but also this call makes appropriate checks
  1055. * of the node object such as validating ntor support for instance. */
  1056. info = extend_info_from_node(node, direct_conn);
  1057. if (BUG(info == NULL)) {
  1058. goto err;
  1059. }
  1060. /* Create our objects and populate them with the node information. */
  1061. ip = service_intro_point_new(info, !node_supports_ed25519_hs_intro(node));
  1062. if (ip == NULL) {
  1063. goto err;
  1064. }
  1065. extend_info_free(info);
  1066. return ip;
  1067. err:
  1068. service_intro_point_free(ip);
  1069. extend_info_free(info);
  1070. return NULL;
  1071. }
  1072. /* For a given descriptor from the given service, pick any needed intro points
  1073. * and update the current map with those newly picked intro points. Return the
  1074. * number node that might have been added to the descriptor current map. */
  1075. static unsigned int
  1076. pick_needed_intro_points(hs_service_t *service,
  1077. hs_service_descriptor_t *desc)
  1078. {
  1079. int i = 0, num_needed_ip;
  1080. smartlist_t *exclude_nodes = smartlist_new();
  1081. tor_assert(service);
  1082. tor_assert(desc);
  1083. /* Compute how many intro points we actually need to open. */
  1084. num_needed_ip = service->config.num_intro_points -
  1085. digest256map_size(desc->intro_points.map);
  1086. if (BUG(num_needed_ip < 0)) {
  1087. /* Let's not make tor freak out here and just skip this. */
  1088. goto done;
  1089. }
  1090. /* We want to end up with config.num_intro_points intro points, but if we
  1091. * have no intro points at all (chances are they all cycled or we are
  1092. * starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits and use the
  1093. * first config.num_intro_points that complete. See proposal #155, section 4
  1094. * for the rationale of this which is purely for performance.
  1095. *
  1096. * The ones after the first config.num_intro_points will be converted to
  1097. * 'General' internal circuits and then we'll drop them from the list of
  1098. * intro points. */
  1099. if (digest256map_size(desc->intro_points.map) == 0) {
  1100. /* XXX: Should a consensus param control that value? */
  1101. num_needed_ip += NUM_INTRO_POINTS_EXTRA;
  1102. }
  1103. /* Build an exclude list of nodes of our intro point(s). The expiring intro
  1104. * points are OK to pick again because this is afterall a concept of round
  1105. * robin so they are considered valid nodes to pick again. */
  1106. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1107. hs_service_intro_point_t *, ip) {
  1108. smartlist_add(exclude_nodes, (void *) get_node_from_intro_point(ip));
  1109. } DIGEST256MAP_FOREACH_END;
  1110. for (i = 0; i < num_needed_ip; i++) {
  1111. hs_service_intro_point_t *ip;
  1112. /* This function will add the picked intro point node to the exclude nodes
  1113. * list so we don't pick the same one at the next iteration. */
  1114. ip = pick_intro_point(service->config.is_single_onion, exclude_nodes);
  1115. if (ip == NULL) {
  1116. /* If we end up unable to pick an introduction point it is because we
  1117. * can't find suitable node and calling this again is highly unlikely to
  1118. * give us a valid node all of the sudden. */
  1119. log_info(LD_REND, "Unable to find a suitable node to be an "
  1120. "introduction point for service %s.",
  1121. safe_str_client(service->onion_address));
  1122. goto done;
  1123. }
  1124. /* Valid intro point object, add it to the descriptor current map. */
  1125. service_intro_point_add(desc->intro_points.map, ip);
  1126. }
  1127. /* Success. */
  1128. done:
  1129. /* We don't have ownership of the node_t object in this list. */
  1130. smartlist_free(exclude_nodes);
  1131. return i;
  1132. }
  1133. /* Update the given descriptor from the given service. The possible update
  1134. * actions includes:
  1135. * - Picking missing intro points if needed.
  1136. * - Incrementing the revision counter if needed.
  1137. */
  1138. static void
  1139. update_service_descriptor(hs_service_t *service,
  1140. hs_service_descriptor_t *desc, time_t now)
  1141. {
  1142. unsigned int num_intro_points;
  1143. tor_assert(service);
  1144. tor_assert(desc);
  1145. tor_assert(desc->desc);
  1146. num_intro_points = digest256map_size(desc->intro_points.map);
  1147. /* Pick any missing introduction point(s). */
  1148. if (num_intro_points < service->config.num_intro_points) {
  1149. unsigned int num_new_intro_points = pick_needed_intro_points(service,
  1150. desc);
  1151. if (num_new_intro_points != 0) {
  1152. log_info(LD_REND, "Service %s just picked %u intro points and wanted "
  1153. "%u. It currently has %d intro points. "
  1154. "Launching ESTABLISH_INTRO circuit shortly.",
  1155. safe_str_client(service->onion_address),
  1156. num_new_intro_points,
  1157. service->config.num_intro_points - num_intro_points,
  1158. num_intro_points);
  1159. /* We'll build those introduction point into the descriptor once we have
  1160. * confirmation that the circuits are opened and ready. However,
  1161. * indicate that this descriptor should be uploaded from now on. */
  1162. desc->next_upload_time = now;
  1163. }
  1164. }
  1165. }
  1166. /* Update descriptors for each service if needed. */
  1167. static void
  1168. update_all_descriptors(time_t now)
  1169. {
  1170. FOR_EACH_SERVICE_BEGIN(service) {
  1171. /* We'll try to update each descriptor that is if certain conditions apply
  1172. * in order for the descriptor to be updated. */
  1173. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1174. update_service_descriptor(service, desc, now);
  1175. } FOR_EACH_DESCRIPTOR_END;
  1176. } FOR_EACH_SERVICE_END;
  1177. }
  1178. /* Return true iff the given intro point has expired that is it has been used
  1179. * for too long or we've reached our max seen INTRODUCE2 cell. */
  1180. static int
  1181. intro_point_should_expire(const hs_service_intro_point_t *ip,
  1182. time_t now)
  1183. {
  1184. tor_assert(ip);
  1185. if (ip->introduce2_count >= ip->introduce2_max) {
  1186. goto expired;
  1187. }
  1188. if (ip->time_to_expire <= now) {
  1189. goto expired;
  1190. }
  1191. /* Not expiring. */
  1192. return 0;
  1193. expired:
  1194. return 1;
  1195. }
  1196. /* Go over the given set of intro points for each service and remove any
  1197. * invalid ones. The conditions for removal are:
  1198. *
  1199. * - The node doesn't exists anymore (not in consensus)
  1200. * OR
  1201. * - The intro point maximum circuit retry count has been reached and no
  1202. * circuit can be found associated with it.
  1203. * OR
  1204. * - The intro point has expired and we should pick a new one.
  1205. *
  1206. * If an intro point is removed, the circuit (if any) is immediately close.
  1207. * If a circuit can't be found, the intro point is kept if it hasn't reached
  1208. * its maximum circuit retry value and thus should be retried. */
  1209. static void
  1210. cleanup_intro_points(hs_service_t *service, time_t now)
  1211. {
  1212. tor_assert(service);
  1213. /* For both descriptors, cleanup the intro points. */
  1214. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1215. /* Go over the current intro points we have, make sure they are still
  1216. * valid and remove any of them that aren't. */
  1217. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1218. hs_service_intro_point_t *, ip) {
  1219. const node_t *node = get_node_from_intro_point(ip);
  1220. origin_circuit_t *ocirc = get_intro_circuit(ip);
  1221. int has_expired = intro_point_should_expire(ip, now);
  1222. /* We cleanup an intro point if it has expired or if we do not know the
  1223. * node_t anymore (removed from our latest consensus) or if we've
  1224. * reached the maximum number of retry with a non existing circuit. */
  1225. if (has_expired || node == NULL ||
  1226. (ocirc == NULL &&
  1227. ip->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES)) {
  1228. MAP_DEL_CURRENT(key);
  1229. service_intro_point_free(ip);
  1230. /* XXX: Legacy code does NOT do that, it keeps the circuit open until
  1231. * a new descriptor is uploaded and then closed all expiring intro
  1232. * point circuit. Here, we close immediately and because we just
  1233. * discarded the intro point, a new one will be selected, a new
  1234. * descriptor created and uploaded. There is no difference to an
  1235. * attacker between the timing of a new consensus and intro point
  1236. * rotation (possibly?). */
  1237. if (ocirc) {
  1238. /* After this, no new cells will be handled on the circuit. */
  1239. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  1240. }
  1241. continue;
  1242. }
  1243. if (ocirc == NULL) {
  1244. /* Circuit disappeared so make sure the intro point is updated. By
  1245. * keeping the object in the descriptor, we'll be able to retry. */
  1246. ip->circuit_established = 0;
  1247. }
  1248. } DIGEST256MAP_FOREACH_END;
  1249. } FOR_EACH_DESCRIPTOR_END;
  1250. }
  1251. /** We just entered overlap period and we need to rotate our <b>service</b>
  1252. * descriptors */
  1253. static void
  1254. rotate_service_descriptors(hs_service_t *service)
  1255. {
  1256. if (service->desc_current) {
  1257. /* Close all IP circuits for the descriptor. */
  1258. close_intro_circuits(&service->desc_current->intro_points);
  1259. /* We don't need this one anymore, we won't serve any clients coming with
  1260. * this service descriptor. */
  1261. service_descriptor_free(service->desc_current);
  1262. }
  1263. /* The next one become the current one and emptying the next will trigger
  1264. * a descriptor creation for it. */
  1265. service->desc_current = service->desc_next;
  1266. service->desc_next = NULL;
  1267. }
  1268. /* Rotate descriptors for each service if needed. If we are just entering
  1269. * the overlap period, rotate them that is point the previous descriptor to
  1270. * the current and cleanup the previous one. A non existing current
  1271. * descriptor will trigger a descriptor build for the next time period. */
  1272. static void
  1273. rotate_all_descriptors(time_t now)
  1274. {
  1275. FOR_EACH_SERVICE_BEGIN(service) {
  1276. /* We are _not_ in the overlap period so skip rotation. */
  1277. if (!hs_overlap_mode_is_active(NULL, now)) {
  1278. service->state.in_overlap_period = 0;
  1279. continue;
  1280. }
  1281. /* We've entered the overlap period already so skip rotation. */
  1282. if (service->state.in_overlap_period) {
  1283. continue;
  1284. }
  1285. /* It's the first time the service encounters the overlap period so flag
  1286. * it in order to make sure we don't rotate at next check. */
  1287. service->state.in_overlap_period = 1;
  1288. /* If we have a next descriptor lined up, rotate the descriptors so that it
  1289. * becomes current. */
  1290. if (service->desc_next) {
  1291. rotate_service_descriptors(service);
  1292. }
  1293. log_info(LD_REND, "We've just entered the overlap period. Service %s "
  1294. "descriptors have been rotated!",
  1295. safe_str_client(service->onion_address));
  1296. } FOR_EACH_SERVICE_END;
  1297. }
  1298. /* Scheduled event run from the main loop. Make sure all our services are up
  1299. * to date and ready for the other scheduled events. This includes looking at
  1300. * the introduction points status and descriptor rotation time. */
  1301. static void
  1302. run_housekeeping_event(time_t now)
  1303. {
  1304. /* Note that nothing here opens circuit(s) nor uploads descriptor(s). We are
  1305. * simply moving things around or removing uneeded elements. */
  1306. FOR_EACH_SERVICE_BEGIN(service) {
  1307. /* Cleanup invalid intro points from the service descriptor. */
  1308. cleanup_intro_points(service, now);
  1309. /* At this point, the service is now ready to go through the scheduled
  1310. * events guaranteeing a valid state. Intro points might be missing from
  1311. * the descriptors after the cleanup but the update/build process will
  1312. * make sure we pick those missing ones. */
  1313. } FOR_EACH_SERVICE_END;
  1314. }
  1315. /* Scheduled event run from the main loop. Make sure all descriptors are up to
  1316. * date. Once this returns, each service descriptor needs to be considered for
  1317. * new introduction circuits and then for upload. */
  1318. static void
  1319. run_build_descriptor_event(time_t now)
  1320. {
  1321. /* For v2 services, this step happens in the upload event. */
  1322. /* Run v3+ events. */
  1323. /* We start by rotating the descriptors only if needed. */
  1324. rotate_all_descriptors(now);
  1325. /* Then, we'll try to build new descriptors that we might need. The
  1326. * condition is that the next descriptor is non existing because it has
  1327. * been rotated or we just started up. */
  1328. build_all_descriptors(now);
  1329. /* Finally, we'll check if we should update the descriptors. Missing
  1330. * introduction points will be picked in this function which is useful for
  1331. * newly built descriptors. */
  1332. update_all_descriptors(now);
  1333. }
  1334. /* For the given service, launch any intro point circuits that could be
  1335. * needed. This considers every descriptor of the service. */
  1336. static void
  1337. launch_intro_point_circuits(hs_service_t *service, time_t now)
  1338. {
  1339. tor_assert(service);
  1340. /* For both descriptors, try to launch any missing introduction point
  1341. * circuits using the current map. */
  1342. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1343. /* Keep a ref on if we need a direct connection. We use this often. */
  1344. unsigned int direct_conn = service->config.is_single_onion;
  1345. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1346. hs_service_intro_point_t *, ip) {
  1347. extend_info_t *ei;
  1348. /* Skip the intro point that already has an existing circuit
  1349. * (established or not). */
  1350. if (get_intro_circuit(ip)) {
  1351. continue;
  1352. }
  1353. ei = get_extend_info_from_intro_point(ip, direct_conn);
  1354. if (ei == NULL) {
  1355. if (!direct_conn) {
  1356. /* In case of a multi-hop connection, it should never happen that we
  1357. * can't get the extend info from the node. Avoid connection and
  1358. * remove intro point from descriptor in order to recover from this
  1359. * potential bug. */
  1360. tor_assert_nonfatal(ei);
  1361. }
  1362. MAP_DEL_CURRENT(key);
  1363. service_intro_point_free(ip);
  1364. continue;
  1365. }
  1366. /* Launch a circuit to the intro point. */
  1367. ip->circuit_retries++;
  1368. if (hs_circ_launch_intro_point(service, ip, ei, now) < 0) {
  1369. log_warn(LD_REND, "Unable to launch intro circuit to node %s "
  1370. "for service %s.",
  1371. safe_str_client(extend_info_describe(ei)),
  1372. safe_str_client(service->onion_address));
  1373. /* Intro point will be retried if possible after this. */
  1374. }
  1375. extend_info_free(ei);
  1376. } DIGEST256MAP_FOREACH_END;
  1377. } FOR_EACH_DESCRIPTOR_END;
  1378. }
  1379. /* Don't try to build more than this many circuits before giving up for a
  1380. * while. Dynamically calculated based on the configured number of intro
  1381. * points for the given service and how many descriptor exists. The default
  1382. * use case of 3 introduction points and two descriptors will allow 28
  1383. * circuits for a retry period (((3 + 2) + (3 * 3)) * 2). */
  1384. static unsigned int
  1385. get_max_intro_circ_per_period(const hs_service_t *service)
  1386. {
  1387. unsigned int count = 0;
  1388. unsigned int multiplier = 0;
  1389. unsigned int num_wanted_ip;
  1390. tor_assert(service);
  1391. tor_assert(service->config.num_intro_points <=
  1392. HS_CONFIG_V3_MAX_INTRO_POINTS);
  1393. num_wanted_ip = service->config.num_intro_points;
  1394. /* The calculation is as follow. We have a number of intro points that we
  1395. * want configured as a torrc option (num_intro_points). We then add an
  1396. * extra value so we can launch multiple circuits at once and pick the
  1397. * quickest ones. For instance, we want 3 intros, we add 2 extra so we'll
  1398. * pick 5 intros and launch 5 circuits. */
  1399. count += (num_wanted_ip + NUM_INTRO_POINTS_EXTRA);
  1400. /* Then we add the number of retries that is possible to do for each intro
  1401. * point. If we want 3 intros, we'll allow 3 times the number of possible
  1402. * retry. */
  1403. count += (num_wanted_ip * MAX_INTRO_POINT_CIRCUIT_RETRIES);
  1404. /* Then, we multiply by a factor of 2 if we have both descriptor or 0 if we
  1405. * have none. */
  1406. multiplier += (service->desc_current) ? 1 : 0;
  1407. multiplier += (service->desc_next) ? 1 : 0;
  1408. return (count * multiplier);
  1409. }
  1410. /* For the given service, return 1 if the service is allowed to launch more
  1411. * introduction circuits else 0 if the maximum has been reached for the retry
  1412. * period of INTRO_CIRC_RETRY_PERIOD. */
  1413. static int
  1414. can_service_launch_intro_circuit(hs_service_t *service, time_t now)
  1415. {
  1416. tor_assert(service);
  1417. /* Consider the intro circuit retry period of the service. */
  1418. if (now > (service->state.intro_circ_retry_started_time +
  1419. INTRO_CIRC_RETRY_PERIOD)) {
  1420. service->state.intro_circ_retry_started_time = now;
  1421. service->state.num_intro_circ_launched = 0;
  1422. goto allow;
  1423. }
  1424. /* Check if we can still launch more circuits in this period. */
  1425. if (service->state.num_intro_circ_launched <=
  1426. get_max_intro_circ_per_period(service)) {
  1427. goto allow;
  1428. }
  1429. /* Rate limit log that we've reached our circuit creation limit. */
  1430. {
  1431. char *msg;
  1432. time_t elapsed_time = now - service->state.intro_circ_retry_started_time;
  1433. static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
  1434. if ((msg = rate_limit_log(&rlimit, now))) {
  1435. log_info(LD_REND, "Hidden service %s exceeded its circuit launch limit "
  1436. "of %u per %d seconds. It launched %u circuits in "
  1437. "the last %ld seconds. Will retry in %ld seconds.",
  1438. safe_str_client(service->onion_address),
  1439. get_max_intro_circ_per_period(service),
  1440. INTRO_CIRC_RETRY_PERIOD,
  1441. service->state.num_intro_circ_launched, elapsed_time,
  1442. INTRO_CIRC_RETRY_PERIOD - elapsed_time);
  1443. tor_free(msg);
  1444. }
  1445. }
  1446. /* Not allow. */
  1447. return 0;
  1448. allow:
  1449. return 1;
  1450. }
  1451. /* Scheduled event run from the main loop. Make sure we have all the circuits
  1452. * we need for each service. */
  1453. static void
  1454. run_build_circuit_event(time_t now)
  1455. {
  1456. /* Make sure we can actually have enough information or able to build
  1457. * internal circuits as required by services. */
  1458. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN ||
  1459. !have_completed_a_circuit()) {
  1460. return;
  1461. }
  1462. /* Run v2 check. */
  1463. if (num_rend_services() > 0) {
  1464. rend_consider_services_intro_points(now);
  1465. }
  1466. /* Run v3+ check. */
  1467. FOR_EACH_SERVICE_BEGIN(service) {
  1468. /* For introduction circuit, we need to make sure we don't stress too much
  1469. * circuit creation so make sure this service is respecting that limit. */
  1470. if (can_service_launch_intro_circuit(service, now)) {
  1471. /* Launch intro point circuits if needed. */
  1472. launch_intro_point_circuits(service, now);
  1473. /* Once the circuits have opened, we'll make sure to update the
  1474. * descriptor intro point list and cleanup any extraneous. */
  1475. }
  1476. } FOR_EACH_SERVICE_END;
  1477. }
  1478. /* Scheduled event run from the main loop. Try to upload the descriptor for
  1479. * each service. */
  1480. static void
  1481. run_upload_descriptor_event(time_t now)
  1482. {
  1483. /* v2 services use the same function for descriptor creation and upload so
  1484. * we do everything here because the intro circuits were checked before. */
  1485. if (num_rend_services() > 0) {
  1486. rend_consider_services_upload(now);
  1487. rend_consider_descriptor_republication();
  1488. }
  1489. /* Run v3+ check. */
  1490. FOR_EACH_SERVICE_BEGIN(service) {
  1491. /* XXX: Upload if needed the descriptor(s). Update next upload time. */
  1492. /* XXX: Build the descriptor intro points list with
  1493. * build_desc_intro_points() once we have enough circuit opened. */
  1494. build_desc_intro_points(service, NULL, now);
  1495. } FOR_EACH_SERVICE_END;
  1496. }
  1497. /* Called when the introduction point circuit is done building and ready to be
  1498. * used. */
  1499. static void
  1500. service_intro_circ_has_opened(origin_circuit_t *circ)
  1501. {
  1502. int close_reason;
  1503. hs_service_t *service;
  1504. hs_service_intro_point_t *ip;
  1505. hs_service_descriptor_t *desc = NULL;
  1506. tor_assert(circ);
  1507. tor_assert(circ->cpath);
  1508. /* Getting here means this is a v3 intro circuit. */
  1509. tor_assert(circ->hs_ident);
  1510. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1511. /* Get service object from the circuit identifier. */
  1512. service = find_service(hs_service_map, &circ->hs_ident->identity_pk);
  1513. if (service == NULL) {
  1514. log_warn(LD_REND, "Unknown service identity key %s on the introduction "
  1515. "circuit %u. Can't find onion service.",
  1516. safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
  1517. TO_CIRCUIT(circ)->n_circ_id);
  1518. close_reason = END_CIRC_REASON_NOSUCHSERVICE;
  1519. goto err;
  1520. }
  1521. /* From the service object, get the intro point object of that circuit. The
  1522. * following will query both descriptors intro points list. */
  1523. ip = service_intro_point_find(service, &circ->hs_ident->intro_auth_pk);
  1524. if (ip == NULL) {
  1525. log_warn(LD_REND, "Unknown authentication key on the introduction "
  1526. "circuit %u for service %s",
  1527. TO_CIRCUIT(circ)->n_circ_id,
  1528. safe_str_client(service->onion_address));
  1529. /* Closing this circuit because we don't recognize the key. */
  1530. close_reason = END_CIRC_REASON_NOSUCHSERVICE;
  1531. goto err;
  1532. }
  1533. /* We can't have an IP object without a descriptor. */
  1534. desc = service_desc_find_by_intro(service, ip);
  1535. tor_assert(desc);
  1536. if (hs_circ_service_intro_has_opened(service, ip, desc, circ)) {
  1537. /* Getting here means that the circuit has been re-purposed because we
  1538. * have enough intro circuit opened. Remove the IP from the service. */
  1539. service_intro_point_remove(service, ip);
  1540. service_intro_point_free(ip);
  1541. }
  1542. goto done;
  1543. err:
  1544. /* Close circuit, we can't use it. */
  1545. circuit_mark_for_close(TO_CIRCUIT(circ), close_reason);
  1546. done:
  1547. return;
  1548. }
  1549. static void
  1550. service_rendezvous_circ_has_opened(origin_circuit_t *circ)
  1551. {
  1552. tor_assert(circ);
  1553. /* XXX: Implement rendezvous support. */
  1554. }
  1555. /* ========== */
  1556. /* Public API */
  1557. /* ========== */
  1558. /* Called when any kind of hidden service circuit is done building thus
  1559. * opened. This is the entry point from the circuit subsystem. */
  1560. void
  1561. hs_service_circuit_has_opened(origin_circuit_t *circ)
  1562. {
  1563. tor_assert(circ);
  1564. /* Handle both version. v2 uses rend_data and v3 uses the hs circuit
  1565. * identifier hs_ident. Can't be both. */
  1566. switch (TO_CIRCUIT(circ)->purpose) {
  1567. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1568. (circ->hs_ident) ? service_intro_circ_has_opened(circ) :
  1569. rend_service_intro_has_opened(circ);
  1570. break;
  1571. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1572. (circ->hs_ident) ? service_rendezvous_circ_has_opened(circ) :
  1573. rend_service_rendezvous_has_opened(circ);
  1574. break;
  1575. default:
  1576. tor_assert(0);
  1577. }
  1578. }
  1579. /* Load and/or generate keys for all onion services including the client
  1580. * authorization if any. Return 0 on success, -1 on failure. */
  1581. int
  1582. hs_service_load_all_keys(void)
  1583. {
  1584. /* Load v2 service keys if we have v2. */
  1585. if (num_rend_services() != 0) {
  1586. if (rend_service_load_all_keys(NULL) < 0) {
  1587. goto err;
  1588. }
  1589. }
  1590. /* Load or/and generate them for v3+. */
  1591. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
  1592. /* Ignore ephemeral service, they already have their keys set. */
  1593. if (service->config.is_ephemeral) {
  1594. continue;
  1595. }
  1596. log_info(LD_REND, "Loading v3 onion service keys from %s",
  1597. service_escaped_dir(service));
  1598. if (load_service_keys(service) < 0) {
  1599. goto err;
  1600. }
  1601. /* XXX: Load/Generate client authorization keys. (#20700) */
  1602. } SMARTLIST_FOREACH_END(service);
  1603. /* Final step, the staging list contains service in a quiescent state that
  1604. * is ready to be used. Register them to the global map. Once this is over,
  1605. * the staging list will be cleaned up. */
  1606. register_all_services();
  1607. /* All keys have been loaded successfully. */
  1608. return 0;
  1609. err:
  1610. return -1;
  1611. }
  1612. /* Put all service object in the given service list. After this, the caller
  1613. * looses ownership of every elements in the list and responsible to free the
  1614. * list pointer. */
  1615. void
  1616. hs_service_stage_services(const smartlist_t *service_list)
  1617. {
  1618. tor_assert(service_list);
  1619. /* This list is freed at registration time but this function can be called
  1620. * multiple time. */
  1621. if (hs_service_staging_list == NULL) {
  1622. hs_service_staging_list = smartlist_new();
  1623. }
  1624. /* Add all service object to our staging list. Caller is responsible for
  1625. * freeing the service_list. */
  1626. smartlist_add_all(hs_service_staging_list, service_list);
  1627. }
  1628. /* Allocate and initilize a service object. The service configuration will
  1629. * contain the default values. Return the newly allocated object pointer. This
  1630. * function can't fail. */
  1631. hs_service_t *
  1632. hs_service_new(const or_options_t *options)
  1633. {
  1634. hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
  1635. /* Set default configuration value. */
  1636. set_service_default_config(&service->config, options);
  1637. /* Set the default service version. */
  1638. service->config.version = HS_SERVICE_DEFAULT_VERSION;
  1639. return service;
  1640. }
  1641. /* Free the given <b>service</b> object and all its content. This function
  1642. * also takes care of wiping service keys from memory. It is safe to pass a
  1643. * NULL pointer. */
  1644. void
  1645. hs_service_free(hs_service_t *service)
  1646. {
  1647. if (service == NULL) {
  1648. return;
  1649. }
  1650. /* Free descriptors. Go over both descriptor with this loop. */
  1651. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1652. service_descriptor_free(desc);
  1653. } FOR_EACH_DESCRIPTOR_END;
  1654. /* Free service configuration. */
  1655. service_clear_config(&service->config);
  1656. /* Wipe service keys. */
  1657. memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
  1658. tor_free(service);
  1659. }
  1660. /* Periodic callback. Entry point from the main loop to the HS service
  1661. * subsystem. This is call every second. This is skipped if tor can't build a
  1662. * circuit or the network is disabled. */
  1663. void
  1664. hs_service_run_scheduled_events(time_t now)
  1665. {
  1666. /* First thing we'll do here is to make sure our services are in a
  1667. * quiescent state for the scheduled events. */
  1668. run_housekeeping_event(now);
  1669. /* Order matters here. We first make sure the descriptor object for each
  1670. * service contains the latest data. Once done, we check if we need to open
  1671. * new introduction circuit. Finally, we try to upload the descriptor for
  1672. * each service. */
  1673. /* Make sure descriptors are up to date. */
  1674. run_build_descriptor_event(now);
  1675. /* Make sure services have enough circuits. */
  1676. run_build_circuit_event(now);
  1677. /* Upload the descriptors if needed/possible. */
  1678. run_upload_descriptor_event(now);
  1679. }
  1680. /* Initialize the service HS subsystem. */
  1681. void
  1682. hs_service_init(void)
  1683. {
  1684. /* Should never be called twice. */
  1685. tor_assert(!hs_service_map);
  1686. tor_assert(!hs_service_staging_list);
  1687. /* v2 specific. */
  1688. rend_service_init();
  1689. hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
  1690. HT_INIT(hs_service_ht, hs_service_map);
  1691. hs_service_staging_list = smartlist_new();
  1692. }
  1693. /* Release all global storage of the hidden service subsystem. */
  1694. void
  1695. hs_service_free_all(void)
  1696. {
  1697. rend_service_free_all();
  1698. service_free_all();
  1699. }
  1700. /* XXX We don't currently use these functions, apart from generating unittest
  1701. data. When we start implementing the service-side support for prop224 we
  1702. should revisit these functions and use them. */
  1703. /** Given an ESTABLISH_INTRO <b>cell</b>, encode it and place its payload in
  1704. * <b>buf_out</b> which has size <b>buf_out_len</b>. Return the number of
  1705. * bytes written, or a negative integer if there was an error. */
  1706. ssize_t
  1707. get_establish_intro_payload(uint8_t *buf_out, size_t buf_out_len,
  1708. const trn_cell_establish_intro_t *cell)
  1709. {
  1710. ssize_t bytes_used = 0;
  1711. if (buf_out_len < RELAY_PAYLOAD_SIZE) {
  1712. return -1;
  1713. }
  1714. bytes_used = trn_cell_establish_intro_encode(buf_out, buf_out_len,
  1715. cell);
  1716. return bytes_used;
  1717. }
  1718. /* Set the cell extensions of <b>cell</b>. */
  1719. static void
  1720. set_trn_cell_extensions(trn_cell_establish_intro_t *cell)
  1721. {
  1722. trn_cell_extension_t *trn_cell_extensions = trn_cell_extension_new();
  1723. /* For now, we don't use extensions at all. */
  1724. trn_cell_extensions->num = 0; /* It's already zeroed, but be explicit. */
  1725. trn_cell_establish_intro_set_extensions(cell, trn_cell_extensions);
  1726. }
  1727. /** Given the circuit handshake info in <b>circuit_key_material</b>, create and
  1728. * return an ESTABLISH_INTRO cell. Return NULL if something went wrong. The
  1729. * returned cell is allocated on the heap and it's the responsibility of the
  1730. * caller to free it. */
  1731. trn_cell_establish_intro_t *
  1732. generate_establish_intro_cell(const uint8_t *circuit_key_material,
  1733. size_t circuit_key_material_len)
  1734. {
  1735. trn_cell_establish_intro_t *cell = NULL;
  1736. ssize_t encoded_len;
  1737. log_warn(LD_GENERAL,
  1738. "Generating ESTABLISH_INTRO cell (key_material_len: %u)",
  1739. (unsigned) circuit_key_material_len);
  1740. /* Generate short-term keypair for use in ESTABLISH_INTRO */
  1741. ed25519_keypair_t key_struct;
  1742. if (ed25519_keypair_generate(&key_struct, 0) < 0) {
  1743. goto err;
  1744. }
  1745. cell = trn_cell_establish_intro_new();
  1746. /* Set AUTH_KEY_TYPE: 2 means ed25519 */
  1747. trn_cell_establish_intro_set_auth_key_type(cell,
  1748. HS_INTRO_AUTH_KEY_TYPE_ED25519);
  1749. /* Set AUTH_KEY_LEN field */
  1750. /* Must also set byte-length of AUTH_KEY to match */
  1751. int auth_key_len = ED25519_PUBKEY_LEN;
  1752. trn_cell_establish_intro_set_auth_key_len(cell, auth_key_len);
  1753. trn_cell_establish_intro_setlen_auth_key(cell, auth_key_len);
  1754. /* Set AUTH_KEY field */
  1755. uint8_t *auth_key_ptr = trn_cell_establish_intro_getarray_auth_key(cell);
  1756. memcpy(auth_key_ptr, key_struct.pubkey.pubkey, auth_key_len);
  1757. /* No cell extensions needed */
  1758. set_trn_cell_extensions(cell);
  1759. /* Set signature size.
  1760. We need to do this up here, because _encode() needs it and we need to call
  1761. _encode() to calculate the MAC and signature.
  1762. */
  1763. int sig_len = ED25519_SIG_LEN;
  1764. trn_cell_establish_intro_set_sig_len(cell, sig_len);
  1765. trn_cell_establish_intro_setlen_sig(cell, sig_len);
  1766. /* XXX How to make this process easier and nicer? */
  1767. /* Calculate the cell MAC (aka HANDSHAKE_AUTH). */
  1768. {
  1769. /* To calculate HANDSHAKE_AUTH, we dump the cell in bytes, and then derive
  1770. the MAC from it. */
  1771. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  1772. uint8_t mac[TRUNNEL_SHA3_256_LEN];
  1773. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  1774. sizeof(cell_bytes_tmp),
  1775. cell);
  1776. if (encoded_len < 0) {
  1777. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell.");
  1778. goto err;
  1779. }
  1780. /* sanity check */
  1781. tor_assert(encoded_len > ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN);
  1782. /* Calculate MAC of all fields before HANDSHAKE_AUTH */
  1783. crypto_mac_sha3_256(mac, sizeof(mac),
  1784. circuit_key_material, circuit_key_material_len,
  1785. cell_bytes_tmp,
  1786. encoded_len -
  1787. (ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN));
  1788. /* Write the MAC to the cell */
  1789. uint8_t *handshake_ptr =
  1790. trn_cell_establish_intro_getarray_handshake_mac(cell);
  1791. memcpy(handshake_ptr, mac, sizeof(mac));
  1792. }
  1793. /* Calculate the cell signature */
  1794. {
  1795. /* To calculate the sig we follow the same procedure as above. We first
  1796. dump the cell up to the sig, and then calculate the sig */
  1797. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  1798. ed25519_signature_t sig;
  1799. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  1800. sizeof(cell_bytes_tmp),
  1801. cell);
  1802. if (encoded_len < 0) {
  1803. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell (2).");
  1804. goto err;
  1805. }
  1806. tor_assert(encoded_len > ED25519_SIG_LEN);
  1807. if (ed25519_sign_prefixed(&sig,
  1808. cell_bytes_tmp,
  1809. encoded_len -
  1810. (ED25519_SIG_LEN + sizeof(cell->sig_len)),
  1811. ESTABLISH_INTRO_SIG_PREFIX,
  1812. &key_struct)) {
  1813. log_warn(LD_BUG, "Unable to gen signature for ESTABLISH_INTRO cell.");
  1814. goto err;
  1815. }
  1816. /* And write the signature to the cell */
  1817. uint8_t *sig_ptr = trn_cell_establish_intro_getarray_sig(cell);
  1818. memcpy(sig_ptr, sig.sig, sig_len);
  1819. }
  1820. /* We are done! Return the cell! */
  1821. return cell;
  1822. err:
  1823. trn_cell_establish_intro_free(cell);
  1824. return NULL;
  1825. }
  1826. #ifdef TOR_UNIT_TESTS
  1827. /* Return the global service map size. Only used by unit test. */
  1828. STATIC unsigned int
  1829. get_hs_service_map_size(void)
  1830. {
  1831. return HT_SIZE(hs_service_map);
  1832. }
  1833. /* Return the staging list size. Only used by unit test. */
  1834. STATIC int
  1835. get_hs_service_staging_list_size(void)
  1836. {
  1837. return smartlist_len(hs_service_staging_list);
  1838. }
  1839. STATIC hs_service_ht *
  1840. get_hs_service_map(void)
  1841. {
  1842. return hs_service_map;
  1843. }
  1844. STATIC hs_service_t *
  1845. get_first_service(void)
  1846. {
  1847. hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
  1848. if (obj == NULL) {
  1849. return NULL;
  1850. }
  1851. return *obj;
  1852. }
  1853. #endif /* TOR_UNIT_TESTS */