hs_service.c 127 KB

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