hs_service.c 126 KB

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