hs_service.c 98 KB

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