hs_service.c 98 KB

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