hs_service.c 127 KB

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