hs_service.c 127 KB

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