hs_service.c 144 KB

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