hs_service.c 127 KB

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