rendservice.c 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendservice.c
  6. * \brief The hidden-service side of rendezvous functionality.
  7. **/
  8. #define RENDSERVICE_PRIVATE
  9. #include "or/or.h"
  10. #include "or/circpathbias.h"
  11. #include "or/circuitbuild.h"
  12. #include "or/circuitlist.h"
  13. #include "or/circuituse.h"
  14. #include "or/config.h"
  15. #include "or/control.h"
  16. #include "lib/crypt_ops/crypto_rand.h"
  17. #include "lib/crypt_ops/crypto_util.h"
  18. #include "or/directory.h"
  19. #include "or/hs_common.h"
  20. #include "or/hs_config.h"
  21. #include "or/main.h"
  22. #include "or/networkstatus.h"
  23. #include "or/nodelist.h"
  24. #include "or/policies.h"
  25. #include "or/rendclient.h"
  26. #include "or/rendcommon.h"
  27. #include "or/rendservice.h"
  28. #include "or/router.h"
  29. #include "or/relay.h"
  30. #include "or/rephist.h"
  31. #include "or/replaycache.h"
  32. #include "or/routerlist.h"
  33. #include "or/routerparse.h"
  34. #include "or/routerset.h"
  35. #include "lib/encoding/confline.h"
  36. #include "or/cpath_build_state_st.h"
  37. #include "or/crypt_path_st.h"
  38. #include "or/crypt_path_reference_st.h"
  39. #include "or/edge_connection_st.h"
  40. #include "or/extend_info_st.h"
  41. #include "or/networkstatus_st.h"
  42. #include "or/origin_circuit_st.h"
  43. #include "or/rend_authorized_client_st.h"
  44. #include "or/rend_encoded_v2_service_descriptor_st.h"
  45. #include "or/rend_intro_point_st.h"
  46. #include "or/rend_service_descriptor_st.h"
  47. #include "or/routerstatus_st.h"
  48. struct rend_service_t;
  49. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  50. const char *pk_digest);
  51. static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
  52. static rend_intro_point_t *find_expiring_intro_point(
  53. struct rend_service_t *service, origin_circuit_t *circ);
  54. static extend_info_t *find_rp_for_intro(
  55. const rend_intro_cell_t *intro,
  56. char **err_msg_out);
  57. static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
  58. static int intro_point_should_expire_now(rend_intro_point_t *intro,
  59. time_t now);
  60. static int rend_service_derive_key_digests(struct rend_service_t *s);
  61. static int rend_service_load_keys(struct rend_service_t *s);
  62. static int rend_service_load_auth_keys(struct rend_service_t *s,
  63. const char *hfname);
  64. static struct rend_service_t *rend_service_get_by_pk_digest(
  65. const char* digest);
  66. static struct rend_service_t *rend_service_get_by_service_id(const char *id);
  67. static const char *rend_service_escaped_dir(
  68. const struct rend_service_t *s);
  69. static ssize_t rend_service_parse_intro_for_v0_or_v1(
  70. rend_intro_cell_t *intro,
  71. const uint8_t *buf,
  72. size_t plaintext_len,
  73. char **err_msg_out);
  74. static ssize_t rend_service_parse_intro_for_v2(
  75. rend_intro_cell_t *intro,
  76. const uint8_t *buf,
  77. size_t plaintext_len,
  78. char **err_msg_out);
  79. static ssize_t rend_service_parse_intro_for_v3(
  80. rend_intro_cell_t *intro,
  81. const uint8_t *buf,
  82. size_t plaintext_len,
  83. char **err_msg_out);
  84. static int rend_service_check_private_dir(const or_options_t *options,
  85. const rend_service_t *s,
  86. int create);
  87. static const smartlist_t* rend_get_service_list(
  88. const smartlist_t* substitute_service_list);
  89. static smartlist_t* rend_get_service_list_mutable(
  90. smartlist_t* substitute_service_list);
  91. static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted);
  92. /* Hidden service directory file names:
  93. * new file names should be added to rend_service_add_filenames_to_list()
  94. * for sandboxing purposes. */
  95. static const char *private_key_fname = "private_key";
  96. static const char *hostname_fname = "hostname";
  97. static const char *client_keys_fname = "client_keys";
  98. static const char *sos_poison_fname = "onion_service_non_anonymous";
  99. /** A list of rend_service_t's for services run on this OP. */
  100. static smartlist_t *rend_service_list = NULL;
  101. /** A list of rend_service_t's for services run on this OP which is used as a
  102. * staging area before they are put in the main list in order to prune dying
  103. * service on config reload. */
  104. static smartlist_t *rend_service_staging_list = NULL;
  105. /* Like rend_get_service_list_mutable, but returns a read-only list. */
  106. static const smartlist_t*
  107. rend_get_service_list(const smartlist_t* substitute_service_list)
  108. {
  109. /* It is safe to cast away the const here, because
  110. * rend_get_service_list_mutable does not actually modify the list */
  111. return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
  112. }
  113. /* Return a mutable list of hidden services.
  114. * If substitute_service_list is not NULL, return it.
  115. * Otherwise, check if the global rend_service_list is non-NULL, and if so,
  116. * return it.
  117. * Otherwise, log a BUG message and return NULL.
  118. * */
  119. static smartlist_t*
  120. rend_get_service_list_mutable(smartlist_t* substitute_service_list)
  121. {
  122. if (substitute_service_list) {
  123. return substitute_service_list;
  124. }
  125. /* If no special service list is provided, then just use the global one. */
  126. if (BUG(!rend_service_list)) {
  127. /* No global HS list, which is a programmer error. */
  128. return NULL;
  129. }
  130. return rend_service_list;
  131. }
  132. /** Tells if onion service <b>s</b> is ephemeral.
  133. */
  134. static unsigned int
  135. rend_service_is_ephemeral(const struct rend_service_t *s)
  136. {
  137. return (s->directory == NULL);
  138. }
  139. /** Returns a escaped string representation of the service, <b>s</b>.
  140. */
  141. static const char *
  142. rend_service_escaped_dir(const struct rend_service_t *s)
  143. {
  144. return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
  145. }
  146. /** Return the number of rendezvous services we have configured. */
  147. int
  148. rend_num_services(void)
  149. {
  150. if (!rend_service_list)
  151. return 0;
  152. return smartlist_len(rend_service_list);
  153. }
  154. /** Helper: free storage held by a single service authorized client entry. */
  155. void
  156. rend_authorized_client_free_(rend_authorized_client_t *client)
  157. {
  158. if (!client)
  159. return;
  160. if (client->client_key)
  161. crypto_pk_free(client->client_key);
  162. if (client->client_name)
  163. memwipe(client->client_name, 0, strlen(client->client_name));
  164. tor_free(client->client_name);
  165. memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
  166. tor_free(client);
  167. }
  168. /** Helper for strmap_free. */
  169. static void
  170. rend_authorized_client_free_void(void *authorized_client)
  171. {
  172. rend_authorized_client_free_(authorized_client);
  173. }
  174. /** Release the storage held by <b>service</b>.
  175. */
  176. STATIC void
  177. rend_service_free_(rend_service_t *service)
  178. {
  179. if (!service)
  180. return;
  181. tor_free(service->directory);
  182. if (service->ports) {
  183. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
  184. rend_service_port_config_free(p));
  185. smartlist_free(service->ports);
  186. }
  187. if (service->private_key)
  188. crypto_pk_free(service->private_key);
  189. if (service->intro_nodes) {
  190. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  191. rend_intro_point_free(intro););
  192. smartlist_free(service->intro_nodes);
  193. }
  194. if (service->expiring_nodes) {
  195. SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
  196. rend_intro_point_free(intro););
  197. smartlist_free(service->expiring_nodes);
  198. }
  199. rend_service_descriptor_free(service->desc);
  200. if (service->clients) {
  201. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  202. rend_authorized_client_free(c););
  203. smartlist_free(service->clients);
  204. }
  205. if (service->accepted_intro_dh_parts) {
  206. replaycache_free(service->accepted_intro_dh_parts);
  207. }
  208. tor_free(service);
  209. }
  210. /* Release all the storage held in rend_service_staging_list. */
  211. void
  212. rend_service_free_staging_list(void)
  213. {
  214. if (rend_service_staging_list) {
  215. SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
  216. rend_service_free(ptr));
  217. smartlist_free(rend_service_staging_list);
  218. rend_service_staging_list = NULL;
  219. }
  220. }
  221. /** Release all the storage held in both rend_service_list and
  222. * rend_service_staging_list. */
  223. void
  224. rend_service_free_all(void)
  225. {
  226. if (rend_service_list) {
  227. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  228. rend_service_free(ptr));
  229. smartlist_free(rend_service_list);
  230. rend_service_list = NULL;
  231. }
  232. rend_service_free_staging_list();
  233. }
  234. /* Initialize the subsystem. */
  235. void
  236. rend_service_init(void)
  237. {
  238. tor_assert(!rend_service_list);
  239. tor_assert(!rend_service_staging_list);
  240. rend_service_list = smartlist_new();
  241. rend_service_staging_list = smartlist_new();
  242. }
  243. /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
  244. * is no duplicate entry for the given service object. Return 0 if valid else
  245. * -1 if not.*/
  246. static int
  247. rend_validate_service(const smartlist_t *service_list,
  248. const rend_service_t *service)
  249. {
  250. tor_assert(service_list);
  251. tor_assert(service);
  252. if (service->max_streams_per_circuit < 0) {
  253. log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
  254. "streams per circuit.",
  255. rend_service_escaped_dir(service));
  256. goto invalid;
  257. }
  258. if (service->max_streams_close_circuit < 0 ||
  259. service->max_streams_close_circuit > 1) {
  260. log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
  261. "max streams handling.",
  262. rend_service_escaped_dir(service));
  263. goto invalid;
  264. }
  265. if (service->auth_type != REND_NO_AUTH &&
  266. (!service->clients || smartlist_len(service->clients) == 0)) {
  267. log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
  268. "no clients.",
  269. rend_service_escaped_dir(service));
  270. goto invalid;
  271. }
  272. if (!service->ports || !smartlist_len(service->ports)) {
  273. log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
  274. rend_service_escaped_dir(service));
  275. goto invalid;
  276. }
  277. /* Valid. */
  278. return 0;
  279. invalid:
  280. return -1;
  281. }
  282. /** Add it to <b>service_list</b>, or to the global rend_service_list if
  283. * <b>service_list</b> is NULL. Return 0 on success. On failure, free
  284. * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
  285. static int
  286. rend_add_service(smartlist_t *service_list, rend_service_t *service)
  287. {
  288. int i;
  289. rend_service_port_config_t *p;
  290. tor_assert(service);
  291. smartlist_t *s_list = rend_get_service_list_mutable(service_list);
  292. /* We must have a service list, even if it's a temporary one, so we can
  293. * check for duplicate services */
  294. if (BUG(!s_list)) {
  295. rend_service_free(service);
  296. return -1;
  297. }
  298. service->intro_nodes = smartlist_new();
  299. service->expiring_nodes = smartlist_new();
  300. log_debug(LD_REND,"Configuring service with directory %s",
  301. rend_service_escaped_dir(service));
  302. for (i = 0; i < smartlist_len(service->ports); ++i) {
  303. p = smartlist_get(service->ports, i);
  304. if (!(p->is_unix_addr)) {
  305. log_debug(LD_REND,
  306. "Service maps port %d to %s",
  307. p->virtual_port,
  308. fmt_addrport(&p->real_addr, p->real_port));
  309. } else {
  310. #ifdef HAVE_SYS_UN_H
  311. log_debug(LD_REND,
  312. "Service maps port %d to socket at \"%s\"",
  313. p->virtual_port, p->unix_addr);
  314. #else
  315. log_warn(LD_BUG,
  316. "Service maps port %d to an AF_UNIX socket, but we "
  317. "have no AF_UNIX support on this platform. This is "
  318. "probably a bug.",
  319. p->virtual_port);
  320. rend_service_free(service);
  321. return -1;
  322. #endif /* defined(HAVE_SYS_UN_H) */
  323. }
  324. }
  325. /* The service passed all the checks */
  326. tor_assert(s_list);
  327. smartlist_add(s_list, service);
  328. /* Notify that our global service list has changed only if this new service
  329. * went into our global list. If not, when we move service from the staging
  330. * list to the new list, a notify is triggered. */
  331. if (s_list == rend_service_list) {
  332. hs_service_map_has_changed();
  333. }
  334. return 0;
  335. }
  336. /** Return a new rend_service_port_config_t with its path set to
  337. * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
  338. static rend_service_port_config_t *
  339. rend_service_port_config_new(const char *socket_path)
  340. {
  341. if (!socket_path)
  342. return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
  343. const size_t pathlen = strlen(socket_path) + 1;
  344. rend_service_port_config_t *conf =
  345. tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
  346. memcpy(conf->unix_addr, socket_path, pathlen);
  347. conf->is_unix_addr = 1;
  348. return conf;
  349. }
  350. /** Parses a virtual-port to real-port/socket mapping separated by
  351. * the provided separator and returns a new rend_service_port_config_t,
  352. * or NULL and an optional error string on failure.
  353. *
  354. * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
  355. *
  356. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  357. */
  358. rend_service_port_config_t *
  359. rend_service_parse_port_config(const char *string, const char *sep,
  360. char **err_msg_out)
  361. {
  362. smartlist_t *sl;
  363. int virtport;
  364. int realport = 0;
  365. uint16_t p;
  366. tor_addr_t addr;
  367. rend_service_port_config_t *result = NULL;
  368. unsigned int is_unix_addr = 0;
  369. const char *socket_path = NULL;
  370. char *err_msg = NULL;
  371. char *addrport = NULL;
  372. sl = smartlist_new();
  373. smartlist_split_string(sl, string, sep,
  374. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  375. if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
  376. err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
  377. goto err;
  378. }
  379. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  380. if (!virtport) {
  381. tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
  382. "port configuration", escaped(smartlist_get(sl,0)));
  383. goto err;
  384. }
  385. if (smartlist_len(sl) == 1) {
  386. /* No addr:port part; use default. */
  387. realport = virtport;
  388. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  389. } else {
  390. int ret;
  391. const char *addrport_element = smartlist_get(sl,1);
  392. const char *rest = NULL;
  393. int is_unix;
  394. ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
  395. &is_unix, &rest);
  396. if (ret < 0) {
  397. tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
  398. "service configuration", addrport_element);
  399. goto err;
  400. }
  401. if (is_unix) {
  402. socket_path = addrport;
  403. is_unix_addr = 1;
  404. } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
  405. /* else try it as an IP:port pair if it has a : or . in it */
  406. if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
  407. err_msg = tor_strdup("Unparseable address in hidden service port "
  408. "configuration.");
  409. goto err;
  410. }
  411. realport = p?p:virtport;
  412. } else {
  413. /* No addr:port, no addr -- must be port. */
  414. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  415. if (!realport) {
  416. tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
  417. "hidden service port configuration.",
  418. escaped(addrport));
  419. goto err;
  420. }
  421. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  422. }
  423. }
  424. /* Allow room for unix_addr */
  425. result = rend_service_port_config_new(socket_path);
  426. result->virtual_port = virtport;
  427. result->is_unix_addr = is_unix_addr;
  428. if (!is_unix_addr) {
  429. result->real_port = realport;
  430. tor_addr_copy(&result->real_addr, &addr);
  431. result->unix_addr[0] = '\0';
  432. }
  433. err:
  434. tor_free(addrport);
  435. if (err_msg_out != NULL) {
  436. *err_msg_out = err_msg;
  437. } else {
  438. tor_free(err_msg);
  439. }
  440. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  441. smartlist_free(sl);
  442. return result;
  443. }
  444. /** Release all storage held in a rend_service_port_config_t. */
  445. void
  446. rend_service_port_config_free_(rend_service_port_config_t *p)
  447. {
  448. tor_free(p);
  449. }
  450. /* Copy relevant data from service src to dst while pruning the service lists.
  451. * This should only be called during the pruning process which takes existing
  452. * services and copy their data to the newly configured services. The src
  453. * service replaycache will be set to NULL after this call. */
  454. static void
  455. copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
  456. {
  457. tor_assert(dst);
  458. tor_assert(src);
  459. /* Keep the timestamps for when the content changed and the next upload
  460. * time so we can properly upload the descriptor if needed for the new
  461. * service object. */
  462. dst->desc_is_dirty = src->desc_is_dirty;
  463. dst->next_upload_time = src->next_upload_time;
  464. /* Move the replaycache to the new object. */
  465. dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
  466. src->accepted_intro_dh_parts = NULL;
  467. /* Copy intro point information to destination service. */
  468. dst->intro_period_started = src->intro_period_started;
  469. dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
  470. dst->n_intro_points_wanted = src->n_intro_points_wanted;
  471. }
  472. /* Helper: Actual implementation of the pruning on reload which we've
  473. * decoupled in order to make the unit test workeable without ugly hacks.
  474. * Furthermore, this function does NOT free any memory but will nullify the
  475. * temporary list pointer whatever happens. */
  476. STATIC void
  477. rend_service_prune_list_impl_(void)
  478. {
  479. origin_circuit_t *ocirc = NULL;
  480. smartlist_t *surviving_services, *old_service_list, *new_service_list;
  481. /* When pruning our current service list, we must have a staging list that
  482. * contains what we want to check else it's a code flow error. */
  483. tor_assert(rend_service_staging_list);
  484. /* We are about to prune the current list of its dead service so set the
  485. * semantic for that list to be the "old" one. */
  486. old_service_list = rend_service_list;
  487. /* The staging list is now the "new" list so set this semantic. */
  488. new_service_list = rend_service_staging_list;
  489. /* After this, whatever happens, we'll use our new list. */
  490. rend_service_list = new_service_list;
  491. /* Finally, nullify the staging list pointer as we don't need it anymore
  492. * and it needs to be NULL before the next reload. */
  493. rend_service_staging_list = NULL;
  494. /* Nothing to prune if we have no service list so stop right away. */
  495. if (!old_service_list) {
  496. return;
  497. }
  498. /* This contains all _existing_ services that survives the relaod that is
  499. * that haven't been removed from the configuration. The difference between
  500. * this list and the new service list is that the new list can possibly
  501. * contain newly configured service that have no introduction points opened
  502. * yet nor key material loaded or generated. */
  503. surviving_services = smartlist_new();
  504. /* Preserve the existing ephemeral services.
  505. *
  506. * This is the ephemeral service equivalent of the "Copy introduction
  507. * points to new services" block, except there's no copy required since
  508. * the service structure isn't regenerated.
  509. *
  510. * After this is done, all ephemeral services will be:
  511. * * Removed from old_service_list, so the equivalent non-ephemeral code
  512. * will not attempt to preserve them.
  513. * * Added to the new_service_list (that previously only had the
  514. * services listed in the configuration).
  515. * * Added to surviving_services, which is the list of services that
  516. * will NOT have their intro point closed.
  517. */
  518. SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
  519. if (rend_service_is_ephemeral(old)) {
  520. SMARTLIST_DEL_CURRENT(old_service_list, old);
  521. smartlist_add(surviving_services, old);
  522. smartlist_add(new_service_list, old);
  523. }
  524. } SMARTLIST_FOREACH_END(old);
  525. /* Copy introduction points to new services. This is O(n^2), but it's only
  526. * called on reconfigure, so it's ok performance wise. */
  527. SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
  528. SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
  529. /* Skip ephemeral services as we only want to copy introduction points
  530. * from current services to newly configured one that already exists.
  531. * The same directory means it's the same service. */
  532. if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old) ||
  533. strcmp(old->directory, new->directory)) {
  534. continue;
  535. }
  536. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  537. smartlist_clear(old->intro_nodes);
  538. smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
  539. smartlist_clear(old->expiring_nodes);
  540. /* Copy needed information from old to new. */
  541. copy_service_on_prunning(new, old);
  542. /* This regular service will survive the closing IPs step after. */
  543. smartlist_add(surviving_services, old);
  544. break;
  545. } SMARTLIST_FOREACH_END(old);
  546. } SMARTLIST_FOREACH_END(new);
  547. /* For every service introduction circuit we can find, see if we have a
  548. * matching surviving configured service. If not, close the circuit. */
  549. while ((ocirc = circuit_get_next_service_intro_circ(ocirc))) {
  550. int keep_it = 0;
  551. if (ocirc->rend_data == NULL) {
  552. /* This is a v3 circuit, ignore it. */
  553. continue;
  554. }
  555. SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
  556. if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
  557. /* Keep this circuit as we have a matching configured service. */
  558. keep_it = 1;
  559. break;
  560. }
  561. } SMARTLIST_FOREACH_END(s);
  562. if (keep_it) {
  563. continue;
  564. }
  565. log_info(LD_REND, "Closing intro point %s for service %s.",
  566. safe_str_client(extend_info_describe(
  567. ocirc->build_state->chosen_exit)),
  568. safe_str_client(rend_data_get_address(ocirc->rend_data)));
  569. /* Reason is FINISHED because service has been removed and thus the
  570. * circuit is considered old/uneeded. */
  571. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  572. }
  573. smartlist_free(surviving_services);
  574. /* Notify that our global service list has changed. */
  575. hs_service_map_has_changed();
  576. }
  577. /* Try to prune our main service list using the temporary one that we just
  578. * loaded and parsed successfully. The pruning process decides which onion
  579. * services to keep and which to discard after a reload. */
  580. void
  581. rend_service_prune_list(void)
  582. {
  583. smartlist_t *old_service_list = rend_service_list;
  584. if (!rend_service_staging_list) {
  585. rend_service_staging_list = smartlist_new();
  586. }
  587. rend_service_prune_list_impl_();
  588. if (old_service_list) {
  589. /* Every remaining service in the old list have been removed from the
  590. * configuration so clean them up safely. */
  591. SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
  592. rend_service_free(s));
  593. smartlist_free(old_service_list);
  594. }
  595. }
  596. /* Copy all the relevant data that the hs_service object contains over to the
  597. * rend_service_t object. The reason to do so is because when configuring a
  598. * service, we go through a generic handler that creates an hs_service_t
  599. * object which so we have to copy the parsed values to a rend service object
  600. * which is version 2 specific. */
  601. static void
  602. service_config_shadow_copy(rend_service_t *service,
  603. hs_service_config_t *config)
  604. {
  605. tor_assert(service);
  606. tor_assert(config);
  607. service->directory = tor_strdup(config->directory_path);
  608. service->dir_group_readable = config->dir_group_readable;
  609. service->allow_unknown_ports = config->allow_unknown_ports;
  610. /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
  611. * if the code flow is right so this cast is safe. But just in case, we'll
  612. * check it. */
  613. service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
  614. if (BUG(config->max_streams_per_rdv_circuit >
  615. HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
  616. service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
  617. }
  618. service->max_streams_close_circuit = config->max_streams_close_circuit;
  619. service->n_intro_points_wanted = config->num_intro_points;
  620. /* Switching ownership of the ports to the rend service object. */
  621. smartlist_add_all(service->ports, config->ports);
  622. smartlist_free(config->ports);
  623. config->ports = NULL;
  624. }
  625. /* Parse the hidden service configuration starting at <b>line_</b> using the
  626. * already configured generic service configuration in <b>config</b>. This
  627. * function will translate the config object to a rend_service_t and add it to
  628. * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
  629. * and return as normal but don't actually add the service to the list. */
  630. int
  631. rend_config_service(const config_line_t *line_,
  632. const or_options_t *options,
  633. hs_service_config_t *config)
  634. {
  635. const config_line_t *line;
  636. rend_service_t *service = NULL;
  637. /* line_ can be NULL which would mean that the service configuration only
  638. * have one line that is the directory directive. */
  639. tor_assert(options);
  640. tor_assert(config);
  641. /* Use the staging service list so that we can check then do the pruning
  642. * process using the main list at the end. */
  643. if (rend_service_staging_list == NULL) {
  644. rend_service_staging_list = smartlist_new();
  645. }
  646. /* Initialize service. */
  647. service = tor_malloc_zero(sizeof(rend_service_t));
  648. service->intro_period_started = time(NULL);
  649. service->ports = smartlist_new();
  650. /* From the hs_service object which has been used to load the generic
  651. * options, we'll copy over the useful data to the rend_service_t object. */
  652. service_config_shadow_copy(service, config);
  653. for (line = line_; line; line = line->next) {
  654. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  655. /* We just hit the next hidden service, stop right now. */
  656. break;
  657. }
  658. /* Number of introduction points. */
  659. if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
  660. int ok = 0;
  661. /* Those are specific defaults for version 2. */
  662. service->n_intro_points_wanted =
  663. (unsigned int) tor_parse_long(line->value, 10,
  664. 0, NUM_INTRO_POINTS_MAX, &ok, NULL);
  665. if (!ok) {
  666. log_warn(LD_CONFIG,
  667. "HiddenServiceNumIntroductionPoints "
  668. "should be between %d and %d, not %s",
  669. 0, NUM_INTRO_POINTS_MAX, line->value);
  670. goto err;
  671. }
  672. log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
  673. service->n_intro_points_wanted, escaped(service->directory));
  674. continue;
  675. }
  676. if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  677. /* Parse auth type and comma-separated list of client names and add a
  678. * rend_authorized_client_t for each client to the service's list
  679. * of authorized clients. */
  680. smartlist_t *type_names_split, *clients;
  681. const char *authname;
  682. if (service->auth_type != REND_NO_AUTH) {
  683. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  684. "lines for a single service.");
  685. goto err;
  686. }
  687. type_names_split = smartlist_new();
  688. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  689. if (smartlist_len(type_names_split) < 1) {
  690. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  691. "should have been prevented when parsing the "
  692. "configuration.");
  693. smartlist_free(type_names_split);
  694. goto err;
  695. }
  696. authname = smartlist_get(type_names_split, 0);
  697. if (!strcasecmp(authname, "basic")) {
  698. service->auth_type = REND_BASIC_AUTH;
  699. } else if (!strcasecmp(authname, "stealth")) {
  700. service->auth_type = REND_STEALTH_AUTH;
  701. } else {
  702. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  703. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  704. "are recognized.",
  705. (char *) smartlist_get(type_names_split, 0));
  706. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  707. smartlist_free(type_names_split);
  708. goto err;
  709. }
  710. service->clients = smartlist_new();
  711. if (smartlist_len(type_names_split) < 2) {
  712. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  713. "auth-type '%s', but no client names.",
  714. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  715. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  716. smartlist_free(type_names_split);
  717. continue;
  718. }
  719. clients = smartlist_new();
  720. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  721. ",", SPLIT_SKIP_SPACE, 0);
  722. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  723. smartlist_free(type_names_split);
  724. /* Remove duplicate client names. */
  725. {
  726. int num_clients = smartlist_len(clients);
  727. smartlist_sort_strings(clients);
  728. smartlist_uniq_strings(clients);
  729. if (smartlist_len(clients) < num_clients) {
  730. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  731. "duplicate client name(s); removing.",
  732. num_clients - smartlist_len(clients));
  733. }
  734. }
  735. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  736. {
  737. rend_authorized_client_t *client;
  738. if (!rend_valid_client_name(client_name)) {
  739. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  740. "illegal client name: '%s'. Names must be "
  741. "between 1 and %d characters and contain "
  742. "only [A-Za-z0-9+_-].",
  743. client_name, REND_CLIENTNAME_MAX_LEN);
  744. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  745. smartlist_free(clients);
  746. goto err;
  747. }
  748. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  749. client->client_name = tor_strdup(client_name);
  750. smartlist_add(service->clients, client);
  751. log_debug(LD_REND, "Adding client name '%s'", client_name);
  752. }
  753. SMARTLIST_FOREACH_END(client_name);
  754. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  755. smartlist_free(clients);
  756. /* Ensure maximum number of clients. */
  757. if ((service->auth_type == REND_BASIC_AUTH &&
  758. smartlist_len(service->clients) > 512) ||
  759. (service->auth_type == REND_STEALTH_AUTH &&
  760. smartlist_len(service->clients) > 16)) {
  761. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  762. "client authorization entries, but only a "
  763. "maximum of %d entries is allowed for "
  764. "authorization type '%s'.",
  765. smartlist_len(service->clients),
  766. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  767. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  768. goto err;
  769. }
  770. continue;
  771. }
  772. }
  773. /* Validate the service just parsed. */
  774. if (rend_validate_service(rend_service_staging_list, service) < 0) {
  775. /* Service is in the staging list so don't try to free it. */
  776. goto err;
  777. }
  778. /* Add it to the temporary list which we will use to prune our current
  779. * list if any after configuring all services. */
  780. if (rend_add_service(rend_service_staging_list, service) < 0) {
  781. /* The object has been freed on error already. */
  782. service = NULL;
  783. goto err;
  784. }
  785. return 0;
  786. err:
  787. rend_service_free(service);
  788. return -1;
  789. }
  790. /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
  791. * client authorization <b>auth_type</b> and an optional list of
  792. * rend_authorized_client_t in <b>auth_clients</b>, with
  793. * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
  794. * and circuit closure on max streams being exceeded set by
  795. * <b>max_streams_close_circuit</b>.
  796. *
  797. * Ownership of pk, ports, and auth_clients is passed to this routine.
  798. * Regardless of success/failure, callers should not touch these values
  799. * after calling this routine, and may assume that correct cleanup has
  800. * been done on failure.
  801. *
  802. * Return an appropriate hs_service_add_ephemeral_status_t.
  803. */
  804. hs_service_add_ephemeral_status_t
  805. rend_service_add_ephemeral(crypto_pk_t *pk,
  806. smartlist_t *ports,
  807. int max_streams_per_circuit,
  808. int max_streams_close_circuit,
  809. rend_auth_type_t auth_type,
  810. smartlist_t *auth_clients,
  811. char **service_id_out)
  812. {
  813. *service_id_out = NULL;
  814. /* Allocate the service structure, and initialize the key, and key derived
  815. * parameters.
  816. */
  817. rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
  818. s->directory = NULL; /* This indicates the service is ephemeral. */
  819. s->private_key = pk;
  820. s->auth_type = auth_type;
  821. s->clients = auth_clients;
  822. s->ports = ports;
  823. s->intro_period_started = time(NULL);
  824. s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
  825. s->max_streams_per_circuit = max_streams_per_circuit;
  826. s->max_streams_close_circuit = max_streams_close_circuit;
  827. if (rend_service_derive_key_digests(s) < 0) {
  828. rend_service_free(s);
  829. return RSAE_BADPRIVKEY;
  830. }
  831. if (!s->ports || smartlist_len(s->ports) == 0) {
  832. log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
  833. rend_service_free(s);
  834. return RSAE_BADVIRTPORT;
  835. }
  836. if (s->auth_type != REND_NO_AUTH &&
  837. (!s->clients || smartlist_len(s->clients) == 0)) {
  838. log_warn(LD_CONFIG, "At least one authorized client must be specified.");
  839. rend_service_free(s);
  840. return RSAE_BADAUTH;
  841. }
  842. /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
  843. * it's not, see #14828.
  844. */
  845. if (rend_service_get_by_pk_digest(s->pk_digest)) {
  846. log_warn(LD_CONFIG, "Onion Service private key collides with an "
  847. "existing service.");
  848. rend_service_free(s);
  849. return RSAE_ADDREXISTS;
  850. }
  851. if (rend_service_get_by_service_id(s->service_id)) {
  852. log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
  853. rend_service_free(s);
  854. return RSAE_ADDREXISTS;
  855. }
  856. /* Initialize the service. */
  857. if (rend_add_service(NULL, s)) {
  858. return RSAE_INTERNAL;
  859. }
  860. *service_id_out = tor_strdup(s->service_id);
  861. log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
  862. return RSAE_OKAY;
  863. }
  864. /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
  865. * success, and -1 on failure.
  866. */
  867. int
  868. rend_service_del_ephemeral(const char *service_id)
  869. {
  870. rend_service_t *s;
  871. if (!rend_valid_v2_service_id(service_id)) {
  872. log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
  873. return -1;
  874. }
  875. if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
  876. log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
  877. "removal.");
  878. return -1;
  879. }
  880. if (!rend_service_is_ephemeral(s)) {
  881. log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
  882. return -1;
  883. }
  884. /* Kill the intro point circuit for the Onion Service, and remove it from
  885. * the list. Closing existing connections is the application's problem.
  886. *
  887. * XXX: As with the comment in rend_config_services(), a nice abstraction
  888. * would be ideal here, but for now just duplicate the code.
  889. */
  890. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  891. if (!circ->marked_for_close &&
  892. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  893. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  894. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  895. if (oc->rend_data == NULL ||
  896. !rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
  897. continue;
  898. }
  899. log_debug(LD_REND, "Closing intro point %s for service %s.",
  900. safe_str_client(extend_info_describe(
  901. oc->build_state->chosen_exit)),
  902. rend_data_get_address(oc->rend_data));
  903. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  904. }
  905. } SMARTLIST_FOREACH_END(circ);
  906. smartlist_remove(rend_service_list, s);
  907. /* Notify that we just removed a service from our global list. */
  908. hs_service_map_has_changed();
  909. rend_service_free(s);
  910. log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
  911. return 0;
  912. }
  913. /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
  914. * another few seconds due to blocking calls. */
  915. #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
  916. /** Log information about the intro point creation rate and current intro
  917. * points for service, upgrading the log level from min_severity to warn if
  918. * we have stopped launching new intro point circuits. */
  919. static void
  920. rend_log_intro_limit(const rend_service_t *service, int min_severity)
  921. {
  922. int exceeded_limit = (service->n_intro_circuits_launched >=
  923. rend_max_intro_circs_per_period(
  924. service->n_intro_points_wanted));
  925. int severity = min_severity;
  926. /* We stopped creating circuits */
  927. if (exceeded_limit) {
  928. severity = LOG_WARN;
  929. }
  930. time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
  931. tor_assert_nonfatal(intro_period_elapsed >= 0);
  932. {
  933. char *msg;
  934. static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
  935. if ((msg = rate_limit_log(&rlimit, approx_time()))) {
  936. log_fn(severity, LD_REND,
  937. "Hidden service %s %s %d intro points in the last %d seconds. "
  938. "Intro circuit launches are limited to %d per %d seconds.%s",
  939. service->service_id,
  940. exceeded_limit ? "exceeded launch limit with" : "launched",
  941. service->n_intro_circuits_launched,
  942. (int)intro_period_elapsed,
  943. rend_max_intro_circs_per_period(service->n_intro_points_wanted),
  944. INTRO_CIRC_RETRY_PERIOD, msg);
  945. rend_service_dump_stats(severity);
  946. tor_free(msg);
  947. }
  948. }
  949. }
  950. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  951. * the other fields in service.
  952. */
  953. static void
  954. rend_service_update_descriptor(rend_service_t *service)
  955. {
  956. rend_service_descriptor_t *d;
  957. int i;
  958. rend_service_descriptor_free(service->desc);
  959. service->desc = NULL;
  960. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  961. d->pk = crypto_pk_dup_key(service->private_key);
  962. d->timestamp = time(NULL);
  963. d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
  964. d->intro_nodes = smartlist_new();
  965. /* Support intro protocols 2 and 3. */
  966. d->protocols = (1 << 2) + (1 << 3);
  967. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  968. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  969. rend_intro_point_t *intro_desc;
  970. /* This intro point won't be listed in the descriptor... */
  971. intro_svc->listed_in_last_desc = 0;
  972. /* circuit_established is set in rend_service_intro_established(), and
  973. * checked every second in rend_consider_services_intro_points(), so it's
  974. * safe to use it here */
  975. if (!intro_svc->circuit_established) {
  976. continue;
  977. }
  978. /* ...unless this intro point is listed in the descriptor. */
  979. intro_svc->listed_in_last_desc = 1;
  980. /* We have an entirely established intro circuit. Publish it in
  981. * our descriptor. */
  982. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  983. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  984. if (intro_svc->intro_key)
  985. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  986. smartlist_add(d->intro_nodes, intro_desc);
  987. if (intro_svc->time_published == -1) {
  988. /* We are publishing this intro point in a descriptor for the
  989. * first time -- note the current time in the service's copy of
  990. * the intro point. */
  991. intro_svc->time_published = time(NULL);
  992. }
  993. }
  994. /* Check that we have the right number of intro points */
  995. unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
  996. if (have_intro != service->n_intro_points_wanted) {
  997. int severity;
  998. /* Getting less than we wanted or more than we're allowed is serious */
  999. if (have_intro < service->n_intro_points_wanted ||
  1000. have_intro > NUM_INTRO_POINTS_MAX) {
  1001. severity = LOG_WARN;
  1002. } else {
  1003. /* Getting more than we wanted is weird, but less of a problem */
  1004. severity = LOG_NOTICE;
  1005. }
  1006. log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
  1007. "descriptor was updated with %d instead.",
  1008. service->service_id,
  1009. service->n_intro_points_wanted, have_intro);
  1010. /* Now log an informative message about how we might have got here. */
  1011. rend_log_intro_limit(service, severity);
  1012. }
  1013. }
  1014. /* Allocate and return a string containing the path to file_name in
  1015. * service->directory. Asserts that service has a directory.
  1016. * This function will never return NULL.
  1017. * The caller must free this path. */
  1018. static char *
  1019. rend_service_path(const rend_service_t *service, const char *file_name)
  1020. {
  1021. tor_assert(service->directory);
  1022. return hs_path_from_filename(service->directory, file_name);
  1023. }
  1024. /* Allocate and return a string containing the path to the single onion
  1025. * service poison file in service->directory. Asserts that service has a
  1026. * directory.
  1027. * The caller must free this path. */
  1028. STATIC char *
  1029. rend_service_sos_poison_path(const rend_service_t *service)
  1030. {
  1031. return rend_service_path(service, sos_poison_fname);
  1032. }
  1033. /** Return True if hidden services <b>service</b> has been poisoned by single
  1034. * onion mode. */
  1035. static int
  1036. service_is_single_onion_poisoned(const rend_service_t *service)
  1037. {
  1038. char *poison_fname = NULL;
  1039. file_status_t fstatus;
  1040. /* Passing a NULL service is a bug */
  1041. if (BUG(!service)) {
  1042. return 0;
  1043. }
  1044. if (rend_service_is_ephemeral(service)) {
  1045. return 0;
  1046. }
  1047. poison_fname = rend_service_sos_poison_path(service);
  1048. fstatus = file_status(poison_fname);
  1049. tor_free(poison_fname);
  1050. /* If this fname is occupied, the hidden service has been poisoned.
  1051. * fstatus can be FN_ERROR if the service directory does not exist, in that
  1052. * case, there is obviously no private key. */
  1053. if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
  1054. return 1;
  1055. }
  1056. return 0;
  1057. }
  1058. /* Return 1 if the private key file for service exists and has a non-zero size,
  1059. * and 0 otherwise. */
  1060. static int
  1061. rend_service_private_key_exists(const rend_service_t *service)
  1062. {
  1063. char *private_key_path = rend_service_path(service, private_key_fname);
  1064. const file_status_t private_key_status = file_status(private_key_path);
  1065. tor_free(private_key_path);
  1066. /* Only non-empty regular private key files could have been used before.
  1067. * fstatus can be FN_ERROR if the service directory does not exist, in that
  1068. * case, there is obviously no private key. */
  1069. return private_key_status == FN_FILE;
  1070. }
  1071. /** Check the single onion service poison state of the directory for s:
  1072. * - If the service is poisoned, and we are in Single Onion Mode,
  1073. * return 0,
  1074. * - If the service is not poisoned, and we are not in Single Onion Mode,
  1075. * return 0,
  1076. * - Otherwise, the poison state is invalid: the service was created in one
  1077. * mode, and is being used in the other, return -1.
  1078. * Hidden service directories without keys are always considered consistent.
  1079. * They will be poisoned after their directory is created (if needed). */
  1080. STATIC int
  1081. rend_service_verify_single_onion_poison(const rend_service_t* s,
  1082. const or_options_t* options)
  1083. {
  1084. /* Passing a NULL service is a bug */
  1085. if (BUG(!s)) {
  1086. return -1;
  1087. }
  1088. /* Ephemeral services are checked at ADD_ONION time */
  1089. if (BUG(rend_service_is_ephemeral(s))) {
  1090. return -1;
  1091. }
  1092. /* Service is expected to have a directory */
  1093. if (BUG(!s->directory)) {
  1094. return -1;
  1095. }
  1096. /* Services without keys are always ok - their keys will only ever be used
  1097. * in the current mode */
  1098. if (!rend_service_private_key_exists(s)) {
  1099. return 0;
  1100. }
  1101. /* The key has been used before in a different mode */
  1102. if (service_is_single_onion_poisoned(s) !=
  1103. rend_service_non_anonymous_mode_enabled(options)) {
  1104. return -1;
  1105. }
  1106. /* The key exists and is consistent with the current mode */
  1107. return 0;
  1108. }
  1109. /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
  1110. * the hidden service directory for s that marks it as a single onion service.
  1111. * Tor must be in single onion mode before calling this function, and the
  1112. * service directory must already have been created.
  1113. * Returns 0 when a directory is successfully poisoned, or if it is already
  1114. * poisoned. Returns -1 on a failure to read the directory or write the poison
  1115. * file, or if there is an existing private key file in the directory. (The
  1116. * service should have been poisoned when the key was created.) */
  1117. static int
  1118. poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
  1119. const or_options_t* options)
  1120. {
  1121. /* Passing a NULL service is a bug */
  1122. if (BUG(!service)) {
  1123. return -1;
  1124. }
  1125. /* We must only poison directories if we're in Single Onion mode */
  1126. tor_assert(rend_service_non_anonymous_mode_enabled(options));
  1127. int fd;
  1128. int retval = -1;
  1129. char *poison_fname = NULL;
  1130. if (rend_service_is_ephemeral(service)) {
  1131. log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
  1132. return 0;
  1133. }
  1134. /* Make sure we're only poisoning new hidden service directories */
  1135. if (rend_service_private_key_exists(service)) {
  1136. log_warn(LD_BUG, "Tried to single onion poison a service directory after "
  1137. "the private key was created.");
  1138. return -1;
  1139. }
  1140. /* Make sure the directory was created before calling this function. */
  1141. if (BUG(hs_check_service_private_dir(options->User, service->directory,
  1142. service->dir_group_readable, 0) < 0))
  1143. return -1;
  1144. poison_fname = rend_service_sos_poison_path(service);
  1145. switch (file_status(poison_fname)) {
  1146. case FN_DIR:
  1147. case FN_ERROR:
  1148. log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
  1149. poison_fname);
  1150. goto done;
  1151. case FN_FILE: /* single onion poison file already exists. NOP. */
  1152. case FN_EMPTY: /* single onion poison file already exists. NOP. */
  1153. log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
  1154. poison_fname);
  1155. break;
  1156. case FN_NOENT:
  1157. fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
  1158. if (fd < 0) {
  1159. log_warn(LD_FS, "Could not create single onion poison file %s",
  1160. poison_fname);
  1161. goto done;
  1162. }
  1163. close(fd);
  1164. break;
  1165. default:
  1166. tor_assert(0);
  1167. }
  1168. retval = 0;
  1169. done:
  1170. tor_free(poison_fname);
  1171. return retval;
  1172. }
  1173. /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
  1174. * hidden services. If s is new, we should mark its hidden service
  1175. * directory appropriately so that it is never launched as a location-private
  1176. * hidden service. (New directories don't have private key files.)
  1177. * Return 0 on success, -1 on fail. */
  1178. STATIC int
  1179. rend_service_poison_new_single_onion_dir(const rend_service_t *s,
  1180. const or_options_t* options)
  1181. {
  1182. /* Passing a NULL service is a bug */
  1183. if (BUG(!s)) {
  1184. return -1;
  1185. }
  1186. /* We must only poison directories if we're in Single Onion mode */
  1187. tor_assert(rend_service_non_anonymous_mode_enabled(options));
  1188. /* Ephemeral services aren't allowed in non-anonymous mode */
  1189. if (BUG(rend_service_is_ephemeral(s))) {
  1190. return -1;
  1191. }
  1192. /* Service is expected to have a directory */
  1193. if (BUG(!s->directory)) {
  1194. return -1;
  1195. }
  1196. if (!rend_service_private_key_exists(s)) {
  1197. if (poison_new_single_onion_hidden_service_dir_impl(s, options)
  1198. < 0) {
  1199. return -1;
  1200. }
  1201. }
  1202. return 0;
  1203. }
  1204. /** Load and/or generate private keys for all hidden services, possibly
  1205. * including keys for client authorization.
  1206. * If a <b>service_list</b> is provided, treat it as the list of hidden
  1207. * services (used in unittests). Otherwise, require that rend_service_list is
  1208. * not NULL.
  1209. * Return 0 on success, -1 on failure. */
  1210. int
  1211. rend_service_load_all_keys(const smartlist_t *service_list)
  1212. {
  1213. /* Use service_list for unit tests */
  1214. const smartlist_t *s_list = rend_get_service_list(service_list);
  1215. if (BUG(!s_list)) {
  1216. return -1;
  1217. }
  1218. SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
  1219. if (s->private_key)
  1220. continue;
  1221. log_info(LD_REND, "Loading hidden-service keys from %s",
  1222. rend_service_escaped_dir(s));
  1223. if (rend_service_load_keys(s) < 0)
  1224. return -1;
  1225. } SMARTLIST_FOREACH_END(s);
  1226. return 0;
  1227. }
  1228. /** Add to <b>lst</b> every filename used by <b>s</b>. */
  1229. static void
  1230. rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
  1231. {
  1232. tor_assert(lst);
  1233. tor_assert(s);
  1234. tor_assert(s->directory);
  1235. smartlist_add(lst, rend_service_path(s, private_key_fname));
  1236. smartlist_add(lst, rend_service_path(s, hostname_fname));
  1237. smartlist_add(lst, rend_service_path(s, client_keys_fname));
  1238. smartlist_add(lst, rend_service_sos_poison_path(s));
  1239. }
  1240. /** Add to <b>open_lst</b> every filename used by a configured hidden service,
  1241. * and to <b>stat_lst</b> every directory used by a configured hidden
  1242. * service */
  1243. void
  1244. rend_services_add_filenames_to_lists(smartlist_t *open_lst,
  1245. smartlist_t *stat_lst)
  1246. {
  1247. if (!rend_service_list)
  1248. return;
  1249. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  1250. if (!rend_service_is_ephemeral(s)) {
  1251. rend_service_add_filenames_to_list(open_lst, s);
  1252. smartlist_add_strdup(stat_lst, s->directory);
  1253. }
  1254. } SMARTLIST_FOREACH_END(s);
  1255. }
  1256. /** Derive all rend_service_t internal material based on the service's key.
  1257. * Returns 0 on success, -1 on failure.
  1258. */
  1259. static int
  1260. rend_service_derive_key_digests(struct rend_service_t *s)
  1261. {
  1262. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  1263. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  1264. return -1;
  1265. }
  1266. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  1267. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  1268. return -1;
  1269. }
  1270. return 0;
  1271. }
  1272. /** Make sure that the directory for <b>s</b> is private, using the config in
  1273. * <b>options</b>.
  1274. * If <b>create</b> is true:
  1275. * - if the directory exists, change permissions if needed,
  1276. * - if the directory does not exist, create it with the correct permissions.
  1277. * If <b>create</b> is false:
  1278. * - if the directory exists, check permissions,
  1279. * - if the directory does not exist, check if we think we can create it.
  1280. * Return 0 on success, -1 on failure. */
  1281. static int
  1282. rend_service_check_private_dir(const or_options_t *options,
  1283. const rend_service_t *s,
  1284. int create)
  1285. {
  1286. /* Passing a NULL service is a bug */
  1287. if (BUG(!s)) {
  1288. return -1;
  1289. }
  1290. /* Check/create directory */
  1291. if (hs_check_service_private_dir(options->User, s->directory,
  1292. s->dir_group_readable, create) < 0) {
  1293. return -1;
  1294. }
  1295. /* Check if the hidden service key exists, and was created in a different
  1296. * single onion service mode, and refuse to launch if it has.
  1297. * This is safe to call even when create is false, as it ignores missing
  1298. * keys and directories: they are always valid.
  1299. */
  1300. if (rend_service_verify_single_onion_poison(s, options) < 0) {
  1301. /* We can't use s->service_id here, as the key may not have been loaded */
  1302. log_warn(LD_GENERAL, "We are configured with "
  1303. "HiddenServiceNonAnonymousMode %d, but the hidden "
  1304. "service key in directory %s was created in %s mode. "
  1305. "This is not allowed.",
  1306. rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
  1307. rend_service_escaped_dir(s),
  1308. rend_service_non_anonymous_mode_enabled(options) ?
  1309. "an anonymous" : "a non-anonymous"
  1310. );
  1311. return -1;
  1312. }
  1313. /* Poison new single onion directories immediately after they are created,
  1314. * so that we never accidentally launch non-anonymous hidden services
  1315. * thinking they are anonymous. Any keys created later will end up with the
  1316. * correct poisoning state.
  1317. */
  1318. if (create && rend_service_non_anonymous_mode_enabled(options)) {
  1319. static int logged_warning = 0;
  1320. if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
  1321. log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
  1322. ".");
  1323. return -1;
  1324. }
  1325. if (!logged_warning) {
  1326. /* The keys for these services are linked to the server IP address */
  1327. log_notice(LD_REND, "The configured onion service directories have been "
  1328. "used in single onion mode. They can not be used for "
  1329. "anonymous hidden services.");
  1330. logged_warning = 1;
  1331. }
  1332. }
  1333. return 0;
  1334. }
  1335. /** Load and/or generate private keys for the hidden service <b>s</b>,
  1336. * possibly including keys for client authorization. Return 0 on success, -1
  1337. * on failure. */
  1338. static int
  1339. rend_service_load_keys(rend_service_t *s)
  1340. {
  1341. char *fname = NULL;
  1342. char buf[128];
  1343. /* Create the directory if needed which will also poison it in case of
  1344. * single onion service. */
  1345. if (rend_service_check_private_dir(get_options(), s, 1) < 0)
  1346. goto err;
  1347. /* Load key */
  1348. fname = rend_service_path(s, private_key_fname);
  1349. s->private_key = init_key_from_file(fname, 1, LOG_ERR, 0);
  1350. if (!s->private_key)
  1351. goto err;
  1352. if (rend_service_derive_key_digests(s) < 0)
  1353. goto err;
  1354. tor_free(fname);
  1355. /* Create service file */
  1356. fname = rend_service_path(s, hostname_fname);
  1357. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  1358. if (write_str_to_file(fname,buf,0)<0) {
  1359. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  1360. goto err;
  1361. }
  1362. #ifndef _WIN32
  1363. if (s->dir_group_readable) {
  1364. /* Also verify hostname file created with group read. */
  1365. if (chmod(fname, 0640))
  1366. log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
  1367. fname);
  1368. }
  1369. #endif /* !defined(_WIN32) */
  1370. /* If client authorization is configured, load or generate keys. */
  1371. if (s->auth_type != REND_NO_AUTH) {
  1372. if (rend_service_load_auth_keys(s, fname) < 0) {
  1373. goto err;
  1374. }
  1375. }
  1376. int r = 0;
  1377. goto done;
  1378. err:
  1379. r = -1;
  1380. done:
  1381. memwipe(buf, 0, sizeof(buf));
  1382. tor_free(fname);
  1383. return r;
  1384. }
  1385. /** Load and/or generate client authorization keys for the hidden service
  1386. * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
  1387. * -1 on failure. */
  1388. static int
  1389. rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
  1390. {
  1391. int r = 0;
  1392. char *cfname = NULL;
  1393. char *client_keys_str = NULL;
  1394. strmap_t *parsed_clients = strmap_new();
  1395. FILE *cfile, *hfile;
  1396. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  1397. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  1398. char service_id[16+1];
  1399. char buf[1500];
  1400. /* Load client keys and descriptor cookies, if available. */
  1401. cfname = rend_service_path(s, client_keys_fname);
  1402. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  1403. if (client_keys_str) {
  1404. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  1405. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  1406. "be parsed.");
  1407. goto err;
  1408. } else {
  1409. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  1410. strmap_size(parsed_clients));
  1411. }
  1412. }
  1413. /* Prepare client_keys and hostname files. */
  1414. if (!(cfile = start_writing_to_stdio_file(cfname,
  1415. OPEN_FLAGS_REPLACE | O_TEXT,
  1416. 0600, &open_cfile))) {
  1417. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  1418. escaped(cfname));
  1419. goto err;
  1420. }
  1421. if (!(hfile = start_writing_to_stdio_file(hfname,
  1422. OPEN_FLAGS_REPLACE | O_TEXT,
  1423. 0600, &open_hfile))) {
  1424. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
  1425. goto err;
  1426. }
  1427. /* Either use loaded keys for configured clients or generate new
  1428. * ones if a client is new. */
  1429. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
  1430. rend_authorized_client_t *parsed =
  1431. strmap_get(parsed_clients, client->client_name);
  1432. int written;
  1433. size_t len;
  1434. /* Copy descriptor cookie from parsed entry or create new one. */
  1435. if (parsed) {
  1436. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  1437. REND_DESC_COOKIE_LEN);
  1438. } else {
  1439. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1440. }
  1441. /* For compatibility with older tor clients, this does not
  1442. * truncate the padding characters, unlike rend_auth_encode_cookie. */
  1443. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  1444. (char *) client->descriptor_cookie,
  1445. REND_DESC_COOKIE_LEN, 0) < 0) {
  1446. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  1447. goto err;
  1448. }
  1449. /* Copy client key from parsed entry or create new one if required. */
  1450. if (parsed && parsed->client_key) {
  1451. client->client_key = crypto_pk_dup_key(parsed->client_key);
  1452. } else if (s->auth_type == REND_STEALTH_AUTH) {
  1453. /* Create private key for client. */
  1454. crypto_pk_t *prkey = NULL;
  1455. if (!(prkey = crypto_pk_new())) {
  1456. log_warn(LD_BUG,"Error constructing client key");
  1457. goto err;
  1458. }
  1459. if (crypto_pk_generate_key(prkey)) {
  1460. log_warn(LD_BUG,"Error generating client key");
  1461. crypto_pk_free(prkey);
  1462. goto err;
  1463. }
  1464. if (crypto_pk_check_key(prkey) <= 0) {
  1465. log_warn(LD_BUG,"Generated client key seems invalid");
  1466. crypto_pk_free(prkey);
  1467. goto err;
  1468. }
  1469. client->client_key = prkey;
  1470. }
  1471. /* Add entry to client_keys file. */
  1472. written = tor_snprintf(buf, sizeof(buf),
  1473. "client-name %s\ndescriptor-cookie %s\n",
  1474. client->client_name, desc_cook_out);
  1475. if (written < 0) {
  1476. log_warn(LD_BUG, "Could not write client entry.");
  1477. goto err;
  1478. }
  1479. if (client->client_key) {
  1480. char *client_key_out = NULL;
  1481. if (crypto_pk_write_private_key_to_string(client->client_key,
  1482. &client_key_out, &len) != 0) {
  1483. log_warn(LD_BUG, "Internal error: "
  1484. "crypto_pk_write_private_key_to_string() failed.");
  1485. goto err;
  1486. }
  1487. if (rend_get_service_id(client->client_key, service_id)<0) {
  1488. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  1489. /*
  1490. * len is string length, not buffer length, but last byte is NUL
  1491. * anyway.
  1492. */
  1493. memwipe(client_key_out, 0, len);
  1494. tor_free(client_key_out);
  1495. goto err;
  1496. }
  1497. written = tor_snprintf(buf + written, sizeof(buf) - written,
  1498. "client-key\n%s", client_key_out);
  1499. memwipe(client_key_out, 0, len);
  1500. tor_free(client_key_out);
  1501. if (written < 0) {
  1502. log_warn(LD_BUG, "Could not write client entry.");
  1503. goto err;
  1504. }
  1505. } else {
  1506. strlcpy(service_id, s->service_id, sizeof(service_id));
  1507. }
  1508. if (fputs(buf, cfile) < 0) {
  1509. log_warn(LD_FS, "Could not append client entry to file: %s",
  1510. strerror(errno));
  1511. goto err;
  1512. }
  1513. /* Add line to hostname file. This is not the same encoding as in
  1514. * client_keys. */
  1515. char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
  1516. s->auth_type);
  1517. if (!encoded_cookie) {
  1518. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  1519. goto err;
  1520. }
  1521. tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
  1522. service_id, encoded_cookie, client->client_name);
  1523. memwipe(encoded_cookie, 0, strlen(encoded_cookie));
  1524. tor_free(encoded_cookie);
  1525. if (fputs(buf, hfile)<0) {
  1526. log_warn(LD_FS, "Could not append host entry to file: %s",
  1527. strerror(errno));
  1528. goto err;
  1529. }
  1530. } SMARTLIST_FOREACH_END(client);
  1531. finish_writing_to_file(open_cfile);
  1532. finish_writing_to_file(open_hfile);
  1533. goto done;
  1534. err:
  1535. r = -1;
  1536. if (open_cfile)
  1537. abort_writing_to_file(open_cfile);
  1538. if (open_hfile)
  1539. abort_writing_to_file(open_hfile);
  1540. done:
  1541. if (client_keys_str) {
  1542. memwipe(client_keys_str, 0, strlen(client_keys_str));
  1543. tor_free(client_keys_str);
  1544. }
  1545. strmap_free(parsed_clients, rend_authorized_client_free_void);
  1546. if (cfname) {
  1547. memwipe(cfname, 0, strlen(cfname));
  1548. tor_free(cfname);
  1549. }
  1550. /* Clear stack buffers that held key-derived material. */
  1551. memwipe(buf, 0, sizeof(buf));
  1552. memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
  1553. memwipe(service_id, 0, sizeof(service_id));
  1554. return r;
  1555. }
  1556. /** Return the service whose public key has a digest of <b>digest</b>, or
  1557. * NULL if no such service exists.
  1558. */
  1559. static rend_service_t *
  1560. rend_service_get_by_pk_digest(const char* digest)
  1561. {
  1562. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  1563. if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
  1564. return s);
  1565. return NULL;
  1566. }
  1567. /** Return the service whose service id is <b>id</b>, or NULL if no such
  1568. * service exists.
  1569. */
  1570. static struct rend_service_t *
  1571. rend_service_get_by_service_id(const char *id)
  1572. {
  1573. tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
  1574. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
  1575. if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
  1576. return s;
  1577. });
  1578. return NULL;
  1579. }
  1580. /** Check client authorization of a given <b>descriptor_cookie</b> of
  1581. * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
  1582. * and 0 for failure. */
  1583. static int
  1584. rend_check_authorization(rend_service_t *service,
  1585. const char *descriptor_cookie,
  1586. size_t cookie_len)
  1587. {
  1588. rend_authorized_client_t *auth_client = NULL;
  1589. tor_assert(service);
  1590. tor_assert(descriptor_cookie);
  1591. if (!service->clients) {
  1592. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  1593. "authorized clients configured.");
  1594. return 0;
  1595. }
  1596. if (cookie_len != REND_DESC_COOKIE_LEN) {
  1597. log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
  1598. "%lu bytes. Dropping cell.",
  1599. (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
  1600. return 0;
  1601. }
  1602. /* Look up client authorization by descriptor cookie. */
  1603. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  1604. if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
  1605. REND_DESC_COOKIE_LEN)) {
  1606. auth_client = client;
  1607. break;
  1608. }
  1609. });
  1610. if (!auth_client) {
  1611. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  1612. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  1613. descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
  1614. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  1615. "Dropping cell!",
  1616. descriptor_cookie_base64);
  1617. return 0;
  1618. }
  1619. /* Allow the request. */
  1620. log_info(LD_REND, "Client %s authorized for service %s.",
  1621. auth_client->client_name, service->service_id);
  1622. return 1;
  1623. }
  1624. /* Can this service make a direct connection to ei?
  1625. * It must be a single onion service, and the firewall rules must allow ei. */
  1626. static int
  1627. rend_service_use_direct_connection(const or_options_t* options,
  1628. const extend_info_t* ei)
  1629. {
  1630. /* We'll connect directly all reachable addresses, whether preferred or not.
  1631. * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
  1632. * ignored, because pref_only is 0. */
  1633. return (rend_service_allow_non_anonymous_connection(options) &&
  1634. fascist_firewall_allows_address_addr(&ei->addr, ei->port,
  1635. FIREWALL_OR_CONNECTION, 0, 0));
  1636. }
  1637. /* Like rend_service_use_direct_connection, but to a node. */
  1638. static int
  1639. rend_service_use_direct_connection_node(const or_options_t* options,
  1640. const node_t* node)
  1641. {
  1642. /* We'll connect directly all reachable addresses, whether preferred or not.
  1643. */
  1644. return (rend_service_allow_non_anonymous_connection(options) &&
  1645. fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
  1646. }
  1647. /******
  1648. * Handle cells
  1649. ******/
  1650. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  1651. * rendezvous point.
  1652. */
  1653. int
  1654. rend_service_receive_introduction(origin_circuit_t *circuit,
  1655. const uint8_t *request,
  1656. size_t request_len)
  1657. {
  1658. /* Global status stuff */
  1659. int status = 0, result;
  1660. const or_options_t *options = get_options();
  1661. char *err_msg = NULL;
  1662. int err_msg_severity = LOG_WARN;
  1663. const char *stage_descr = NULL, *rend_pk_digest;
  1664. int reason = END_CIRC_REASON_TORPROTOCOL;
  1665. /* Service/circuit/key stuff we can learn before parsing */
  1666. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1667. rend_service_t *service = NULL;
  1668. rend_intro_point_t *intro_point = NULL;
  1669. crypto_pk_t *intro_key = NULL;
  1670. /* Parsed cell */
  1671. rend_intro_cell_t *parsed_req = NULL;
  1672. /* Rendezvous point */
  1673. extend_info_t *rp = NULL;
  1674. /* XXX not handled yet */
  1675. char buf[RELAY_PAYLOAD_SIZE];
  1676. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  1677. int i;
  1678. crypto_dh_t *dh = NULL;
  1679. origin_circuit_t *launched = NULL;
  1680. crypt_path_t *cpath = NULL;
  1681. char hexcookie[9];
  1682. int circ_needs_uptime;
  1683. time_t now = time(NULL);
  1684. time_t elapsed;
  1685. int replay;
  1686. ssize_t keylen;
  1687. /* Do some initial validation and logging before we parse the cell */
  1688. if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1689. log_warn(LD_PROTOCOL,
  1690. "Got an INTRODUCE2 over a non-introduction circuit %u.",
  1691. (unsigned) circuit->base_.n_circ_id);
  1692. goto err;
  1693. }
  1694. assert_circ_anonymity_ok(circuit, options);
  1695. tor_assert(circuit->rend_data);
  1696. /* XXX: This is version 2 specific (only one supported). */
  1697. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  1698. /* We'll use this in a bazillion log messages */
  1699. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1700. rend_pk_digest, REND_SERVICE_ID_LEN);
  1701. /* look up service depending on circuit. */
  1702. service = rend_service_get_by_pk_digest(rend_pk_digest);
  1703. if (!service) {
  1704. log_warn(LD_BUG,
  1705. "Internal error: Got an INTRODUCE2 cell on an intro "
  1706. "circ for an unrecognized service %s.",
  1707. escaped(serviceid));
  1708. goto err;
  1709. }
  1710. intro_point = find_intro_point(circuit);
  1711. if (intro_point == NULL) {
  1712. intro_point = find_expiring_intro_point(service, circuit);
  1713. if (intro_point == NULL) {
  1714. log_warn(LD_BUG,
  1715. "Internal error: Got an INTRODUCE2 cell on an "
  1716. "intro circ (for service %s) with no corresponding "
  1717. "rend_intro_point_t.",
  1718. escaped(serviceid));
  1719. goto err;
  1720. }
  1721. }
  1722. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
  1723. escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
  1724. /* use intro key instead of service key. */
  1725. intro_key = circuit->intro_key;
  1726. tor_free(err_msg);
  1727. stage_descr = NULL;
  1728. stage_descr = "early parsing";
  1729. /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
  1730. parsed_req =
  1731. rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
  1732. if (!parsed_req) {
  1733. goto log_error;
  1734. } else if (err_msg) {
  1735. log_info(LD_REND, "%s on circ %u.", err_msg,
  1736. (unsigned)circuit->base_.n_circ_id);
  1737. tor_free(err_msg);
  1738. }
  1739. /* make sure service replay caches are present */
  1740. if (!service->accepted_intro_dh_parts) {
  1741. service->accepted_intro_dh_parts =
  1742. replaycache_new(REND_REPLAY_TIME_INTERVAL,
  1743. REND_REPLAY_TIME_INTERVAL);
  1744. }
  1745. if (!intro_point->accepted_intro_rsa_parts) {
  1746. intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
  1747. }
  1748. /* check for replay of PK-encrypted portion. */
  1749. keylen = crypto_pk_keysize(intro_key);
  1750. replay = replaycache_add_test_and_elapsed(
  1751. intro_point->accepted_intro_rsa_parts,
  1752. parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
  1753. &elapsed);
  1754. if (replay) {
  1755. log_warn(LD_REND,
  1756. "Possible replay detected! We received an "
  1757. "INTRODUCE2 cell with same PK-encrypted part %d "
  1758. "seconds ago. Dropping cell.",
  1759. (int)elapsed);
  1760. goto err;
  1761. }
  1762. stage_descr = "decryption";
  1763. /* Now try to decrypt it */
  1764. result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
  1765. if (result < 0) {
  1766. goto log_error;
  1767. } else if (err_msg) {
  1768. log_info(LD_REND, "%s on circ %u.", err_msg,
  1769. (unsigned)circuit->base_.n_circ_id);
  1770. tor_free(err_msg);
  1771. }
  1772. stage_descr = "late parsing";
  1773. /* Parse the plaintext */
  1774. result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
  1775. if (result < 0) {
  1776. goto log_error;
  1777. } else if (err_msg) {
  1778. log_info(LD_REND, "%s on circ %u.", err_msg,
  1779. (unsigned)circuit->base_.n_circ_id);
  1780. tor_free(err_msg);
  1781. }
  1782. stage_descr = "late validation";
  1783. /* Validate the parsed plaintext parts */
  1784. result = rend_service_validate_intro_late(parsed_req, &err_msg);
  1785. if (result < 0) {
  1786. goto log_error;
  1787. } else if (err_msg) {
  1788. log_info(LD_REND, "%s on circ %u.", err_msg,
  1789. (unsigned)circuit->base_.n_circ_id);
  1790. tor_free(err_msg);
  1791. }
  1792. stage_descr = NULL;
  1793. /* Increment INTRODUCE2 counter */
  1794. ++(intro_point->accepted_introduce2_count);
  1795. /* Find the rendezvous point */
  1796. rp = find_rp_for_intro(parsed_req, &err_msg);
  1797. if (!rp) {
  1798. err_msg_severity = LOG_PROTOCOL_WARN;
  1799. goto log_error;
  1800. }
  1801. /* Check if we'd refuse to talk to this router */
  1802. if (options->StrictNodes &&
  1803. routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
  1804. log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
  1805. "exclude, and StrictNodes is set. Refusing service.");
  1806. reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
  1807. goto err;
  1808. }
  1809. base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
  1810. /* Check whether there is a past request with the same Diffie-Hellman,
  1811. * part 1. */
  1812. replay = replaycache_add_test_and_elapsed(
  1813. service->accepted_intro_dh_parts,
  1814. parsed_req->dh, DH1024_KEY_LEN,
  1815. &elapsed);
  1816. if (replay) {
  1817. /* A Tor client will send a new INTRODUCE1 cell with the same rend
  1818. * cookie and DH public key as its previous one if its intro circ
  1819. * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
  1820. * If we received the first INTRODUCE1 cell (the intro-point relay
  1821. * converts it into an INTRODUCE2 cell), we are already trying to
  1822. * connect to that rend point (and may have already succeeded);
  1823. * drop this cell. */
  1824. log_info(LD_REND, "We received an "
  1825. "INTRODUCE2 cell with same first part of "
  1826. "Diffie-Hellman handshake %d seconds ago. Dropping "
  1827. "cell.",
  1828. (int) elapsed);
  1829. goto err;
  1830. }
  1831. /* If the service performs client authorization, check included auth data. */
  1832. if (service->clients) {
  1833. if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
  1834. if (rend_check_authorization(service,
  1835. (const char*)parsed_req->u.v3.auth_data,
  1836. parsed_req->u.v3.auth_len)) {
  1837. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1838. } else {
  1839. log_info(LD_REND, "The authorization data that are contained in "
  1840. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1841. reason = END_CIRC_REASON_CONNECTFAILED;
  1842. goto err;
  1843. }
  1844. } else {
  1845. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1846. "data, but we require client authorization. Dropping cell.");
  1847. reason = END_CIRC_REASON_CONNECTFAILED;
  1848. goto err;
  1849. }
  1850. }
  1851. /* Try DH handshake... */
  1852. dh = crypto_dh_new(DH_TYPE_REND);
  1853. if (!dh || crypto_dh_generate_public(dh)<0) {
  1854. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1855. "or generate public key.");
  1856. reason = END_CIRC_REASON_INTERNAL;
  1857. goto err;
  1858. }
  1859. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
  1860. (char *)(parsed_req->dh),
  1861. DH1024_KEY_LEN, keys,
  1862. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1863. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1864. reason = END_CIRC_REASON_INTERNAL;
  1865. goto err;
  1866. }
  1867. circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
  1868. /* help predict this next time */
  1869. rep_hist_note_used_internal(now, circ_needs_uptime, 1);
  1870. /* Launch a circuit to the client's chosen rendezvous point.
  1871. */
  1872. int max_rend_failures=hs_get_service_max_rend_failures();
  1873. for (i=0;i<max_rend_failures;i++) {
  1874. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1875. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1876. /* A Single Onion Service only uses a direct connection if its
  1877. * firewall rules permit direct connections to the address. */
  1878. if (rend_service_use_direct_connection(options, rp)) {
  1879. flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
  1880. }
  1881. launched = circuit_launch_by_extend_info(
  1882. CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
  1883. if (launched)
  1884. break;
  1885. }
  1886. if (!launched) { /* give up */
  1887. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1888. "point %s for service %s.",
  1889. safe_str_client(extend_info_describe(rp)),
  1890. serviceid);
  1891. reason = END_CIRC_REASON_CONNECTFAILED;
  1892. goto err;
  1893. }
  1894. log_info(LD_REND,
  1895. "Accepted intro; launching circuit to %s "
  1896. "(cookie %s) for service %s.",
  1897. safe_str_client(extend_info_describe(rp)),
  1898. hexcookie, serviceid);
  1899. tor_assert(launched->build_state);
  1900. /* Fill in the circuit's state. */
  1901. launched->rend_data =
  1902. rend_data_service_create(service->service_id, rend_pk_digest,
  1903. parsed_req->rc, service->auth_type);
  1904. launched->build_state->service_pending_final_cpath_ref =
  1905. tor_malloc_zero(sizeof(crypt_path_reference_t));
  1906. launched->build_state->service_pending_final_cpath_ref->refcount = 1;
  1907. launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
  1908. tor_malloc_zero(sizeof(crypt_path_t));
  1909. cpath->magic = CRYPT_PATH_MAGIC;
  1910. launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
  1911. cpath->rend_dh_handshake_state = dh;
  1912. dh = NULL;
  1913. if (circuit_init_cpath_crypto(cpath,
  1914. keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
  1915. 1, 0)<0)
  1916. goto err;
  1917. memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
  1918. goto done;
  1919. log_error:
  1920. if (!err_msg) {
  1921. if (stage_descr) {
  1922. tor_asprintf(&err_msg,
  1923. "unknown %s error for INTRODUCE2", stage_descr);
  1924. } else {
  1925. err_msg = tor_strdup("unknown error for INTRODUCE2");
  1926. }
  1927. }
  1928. log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
  1929. (unsigned)circuit->base_.n_circ_id);
  1930. err:
  1931. status = -1;
  1932. if (dh) crypto_dh_free(dh);
  1933. if (launched) {
  1934. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1935. }
  1936. tor_free(err_msg);
  1937. done:
  1938. memwipe(keys, 0, sizeof(keys));
  1939. memwipe(buf, 0, sizeof(buf));
  1940. memwipe(serviceid, 0, sizeof(serviceid));
  1941. memwipe(hexcookie, 0, sizeof(hexcookie));
  1942. /* Free the parsed cell */
  1943. rend_service_free_intro(parsed_req);
  1944. /* Free rp */
  1945. extend_info_free(rp);
  1946. return status;
  1947. }
  1948. /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
  1949. * return NULL and an error string if we can't. Return a newly allocated
  1950. * extend_info_t* for the rendezvous point. */
  1951. static extend_info_t *
  1952. find_rp_for_intro(const rend_intro_cell_t *intro,
  1953. char **err_msg_out)
  1954. {
  1955. extend_info_t *rp = NULL;
  1956. char *err_msg = NULL;
  1957. const char *rp_nickname = NULL;
  1958. const node_t *node = NULL;
  1959. if (!intro) {
  1960. if (err_msg_out)
  1961. err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
  1962. goto err;
  1963. }
  1964. if (intro->version == 0 || intro->version == 1) {
  1965. rp_nickname = (const char *)(intro->u.v0_v1.rp);
  1966. node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
  1967. if (!node) {
  1968. if (err_msg_out) {
  1969. tor_asprintf(&err_msg,
  1970. "Couldn't find router %s named in INTRODUCE2 cell",
  1971. escaped_safe_str_client(rp_nickname));
  1972. }
  1973. goto err;
  1974. }
  1975. /* Are we in single onion mode? */
  1976. const int allow_direct = rend_service_allow_non_anonymous_connection(
  1977. get_options());
  1978. rp = extend_info_from_node(node, allow_direct);
  1979. if (!rp) {
  1980. if (err_msg_out) {
  1981. tor_asprintf(&err_msg,
  1982. "Couldn't build extend_info_t for router %s named "
  1983. "in INTRODUCE2 cell",
  1984. escaped_safe_str_client(rp_nickname));
  1985. }
  1986. goto err;
  1987. }
  1988. } else if (intro->version == 2) {
  1989. rp = extend_info_dup(intro->u.v2.extend_info);
  1990. } else if (intro->version == 3) {
  1991. rp = extend_info_dup(intro->u.v3.extend_info);
  1992. } else {
  1993. if (err_msg_out) {
  1994. tor_asprintf(&err_msg,
  1995. "Unknown version %d in INTRODUCE2 cell",
  1996. (int)(intro->version));
  1997. }
  1998. goto err;
  1999. }
  2000. /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
  2001. * the other cases goto err. */
  2002. tor_assert(rp);
  2003. /* Make sure the RP we are being asked to connect to is _not_ a private
  2004. * address unless it's allowed. Let's avoid to build a circuit to our
  2005. * second middle node and fail right after when extending to the RP. */
  2006. if (!extend_info_addr_is_allowed(&rp->addr)) {
  2007. if (err_msg_out) {
  2008. tor_asprintf(&err_msg,
  2009. "Relay IP in INTRODUCE2 cell is private address.");
  2010. }
  2011. extend_info_free(rp);
  2012. rp = NULL;
  2013. goto err;
  2014. }
  2015. goto done;
  2016. err:
  2017. if (err_msg_out)
  2018. *err_msg_out = err_msg;
  2019. else
  2020. tor_free(err_msg);
  2021. done:
  2022. return rp;
  2023. }
  2024. /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
  2025. * rend_service_parse_intro().
  2026. */
  2027. void
  2028. rend_service_free_intro_(rend_intro_cell_t *request)
  2029. {
  2030. if (!request) {
  2031. return;
  2032. }
  2033. /* Free ciphertext */
  2034. tor_free(request->ciphertext);
  2035. request->ciphertext_len = 0;
  2036. /* Have plaintext? */
  2037. if (request->plaintext) {
  2038. /* Zero it out just to be safe */
  2039. memwipe(request->plaintext, 0, request->plaintext_len);
  2040. tor_free(request->plaintext);
  2041. request->plaintext_len = 0;
  2042. }
  2043. /* Have parsed plaintext? */
  2044. if (request->parsed) {
  2045. switch (request->version) {
  2046. case 0:
  2047. case 1:
  2048. /*
  2049. * Nothing more to do; these formats have no further pointers
  2050. * in them.
  2051. */
  2052. break;
  2053. case 2:
  2054. extend_info_free(request->u.v2.extend_info);
  2055. request->u.v2.extend_info = NULL;
  2056. break;
  2057. case 3:
  2058. if (request->u.v3.auth_data) {
  2059. memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
  2060. tor_free(request->u.v3.auth_data);
  2061. }
  2062. extend_info_free(request->u.v3.extend_info);
  2063. request->u.v3.extend_info = NULL;
  2064. break;
  2065. default:
  2066. log_info(LD_BUG,
  2067. "rend_service_free_intro() saw unknown protocol "
  2068. "version %d.",
  2069. request->version);
  2070. }
  2071. }
  2072. /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
  2073. memwipe(request, 0, sizeof(*request));
  2074. tor_free(request);
  2075. }
  2076. /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
  2077. * rend_intro_cell_t structure. Free it with rend_service_free_intro()
  2078. * when finished. The type parameter should be 1 or 2 to indicate whether
  2079. * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
  2080. * parts; after this, call rend_service_decrypt_intro() with a key, then
  2081. * rend_service_parse_intro_plaintext() to finish parsing. The optional
  2082. * err_msg_out parameter is set to a string suitable for log output
  2083. * if parsing fails. This function does some validation, but only
  2084. * that which depends solely on the contents of the cell and the
  2085. * key; it can be unit-tested. Further validation is done in
  2086. * rend_service_validate_intro().
  2087. */
  2088. rend_intro_cell_t *
  2089. rend_service_begin_parse_intro(const uint8_t *request,
  2090. size_t request_len,
  2091. uint8_t type,
  2092. char **err_msg_out)
  2093. {
  2094. rend_intro_cell_t *rv = NULL;
  2095. char *err_msg = NULL;
  2096. if (!request || request_len <= 0) goto err;
  2097. if (!(type == 1 || type == 2)) goto err;
  2098. /* First, check that the cell is long enough to be a sensible INTRODUCE */
  2099. /* min key length plus digest length plus nickname length */
  2100. if (request_len <
  2101. (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
  2102. DH1024_KEY_LEN + 42)) {
  2103. if (err_msg_out) {
  2104. tor_asprintf(&err_msg,
  2105. "got a truncated INTRODUCE%d cell",
  2106. (int)type);
  2107. }
  2108. goto err;
  2109. }
  2110. /* Allocate a new parsed cell structure */
  2111. rv = tor_malloc_zero(sizeof(*rv));
  2112. /* Set the type */
  2113. rv->type = type;
  2114. /* Copy in the ID */
  2115. memcpy(rv->pk, request, DIGEST_LEN);
  2116. /* Copy in the ciphertext */
  2117. rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
  2118. memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
  2119. rv->ciphertext_len = request_len - DIGEST_LEN;
  2120. goto done;
  2121. err:
  2122. rend_service_free_intro(rv);
  2123. rv = NULL;
  2124. if (err_msg_out && !err_msg) {
  2125. tor_asprintf(&err_msg,
  2126. "unknown INTRODUCE%d error",
  2127. (int)type);
  2128. }
  2129. done:
  2130. if (err_msg_out) *err_msg_out = err_msg;
  2131. else tor_free(err_msg);
  2132. return rv;
  2133. }
  2134. /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
  2135. * cell
  2136. */
  2137. static ssize_t
  2138. rend_service_parse_intro_for_v0_or_v1(
  2139. rend_intro_cell_t *intro,
  2140. const uint8_t *buf,
  2141. size_t plaintext_len,
  2142. char **err_msg_out)
  2143. {
  2144. const char *rp_nickname, *endptr;
  2145. size_t nickname_field_len, ver_specific_len;
  2146. if (intro->version == 1) {
  2147. ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
  2148. rp_nickname = ((const char *)buf) + 1;
  2149. nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
  2150. } else if (intro->version == 0) {
  2151. ver_specific_len = MAX_NICKNAME_LEN + 1;
  2152. rp_nickname = (const char *)buf;
  2153. nickname_field_len = MAX_NICKNAME_LEN + 1;
  2154. } else {
  2155. if (err_msg_out)
  2156. tor_asprintf(err_msg_out,
  2157. "rend_service_parse_intro_for_v0_or_v1() called with "
  2158. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2159. intro->version,
  2160. (int)(intro->type));
  2161. goto err;
  2162. }
  2163. if (plaintext_len < ver_specific_len) {
  2164. if (err_msg_out)
  2165. tor_asprintf(err_msg_out,
  2166. "short plaintext of encrypted part in v1 INTRODUCE%d "
  2167. "cell (%lu bytes, needed %lu)",
  2168. (int)(intro->type),
  2169. (unsigned long)plaintext_len,
  2170. (unsigned long)ver_specific_len);
  2171. goto err;
  2172. }
  2173. endptr = memchr(rp_nickname, 0, nickname_field_len);
  2174. if (!endptr || endptr == rp_nickname) {
  2175. if (err_msg_out) {
  2176. tor_asprintf(err_msg_out,
  2177. "couldn't find a nul-padded nickname in "
  2178. "INTRODUCE%d cell",
  2179. (int)(intro->type));
  2180. }
  2181. goto err;
  2182. }
  2183. if ((intro->version == 0 &&
  2184. !is_legal_nickname(rp_nickname)) ||
  2185. (intro->version == 1 &&
  2186. !is_legal_nickname_or_hexdigest(rp_nickname))) {
  2187. if (err_msg_out) {
  2188. tor_asprintf(err_msg_out,
  2189. "bad nickname in INTRODUCE%d cell",
  2190. (int)(intro->type));
  2191. }
  2192. goto err;
  2193. }
  2194. memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
  2195. return ver_specific_len;
  2196. err:
  2197. return -1;
  2198. }
  2199. /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
  2200. */
  2201. static ssize_t
  2202. rend_service_parse_intro_for_v2(
  2203. rend_intro_cell_t *intro,
  2204. const uint8_t *buf,
  2205. size_t plaintext_len,
  2206. char **err_msg_out)
  2207. {
  2208. unsigned int klen;
  2209. extend_info_t *extend_info = NULL;
  2210. ssize_t ver_specific_len;
  2211. /*
  2212. * We accept version 3 too so that the v3 parser can call this with
  2213. * an adjusted buffer for the latter part of a v3 cell, which is
  2214. * identical to a v2 cell.
  2215. */
  2216. if (!(intro->version == 2 ||
  2217. intro->version == 3)) {
  2218. if (err_msg_out)
  2219. tor_asprintf(err_msg_out,
  2220. "rend_service_parse_intro_for_v2() called with "
  2221. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2222. intro->version,
  2223. (int)(intro->type));
  2224. goto err;
  2225. }
  2226. /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
  2227. if (plaintext_len < 7 + DIGEST_LEN + 2) {
  2228. if (err_msg_out) {
  2229. tor_asprintf(err_msg_out,
  2230. "truncated plaintext of encrypted parted of "
  2231. "version %d INTRODUCE%d cell",
  2232. intro->version,
  2233. (int)(intro->type));
  2234. }
  2235. goto err;
  2236. }
  2237. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  2238. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
  2239. extend_info->port = ntohs(get_uint16(buf + 5));
  2240. memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
  2241. extend_info->nickname[0] = '$';
  2242. base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
  2243. extend_info->identity_digest, DIGEST_LEN);
  2244. klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
  2245. /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
  2246. if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
  2247. if (err_msg_out) {
  2248. tor_asprintf(err_msg_out,
  2249. "truncated plaintext of encrypted parted of "
  2250. "version %d INTRODUCE%d cell",
  2251. intro->version,
  2252. (int)(intro->type));
  2253. }
  2254. goto err;
  2255. }
  2256. extend_info->onion_key =
  2257. crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
  2258. if (!extend_info->onion_key) {
  2259. if (err_msg_out) {
  2260. tor_asprintf(err_msg_out,
  2261. "error decoding onion key in version %d "
  2262. "INTRODUCE%d cell",
  2263. intro->version,
  2264. (intro->type));
  2265. }
  2266. goto err;
  2267. }
  2268. if (128 != crypto_pk_keysize(extend_info->onion_key)) {
  2269. if (err_msg_out) {
  2270. tor_asprintf(err_msg_out,
  2271. "invalid onion key size in version %d INTRODUCE%d cell",
  2272. intro->version,
  2273. (intro->type));
  2274. }
  2275. goto err;
  2276. }
  2277. ver_specific_len = 7+DIGEST_LEN+2+klen;
  2278. if (intro->version == 2) intro->u.v2.extend_info = extend_info;
  2279. else intro->u.v3.extend_info = extend_info;
  2280. return ver_specific_len;
  2281. err:
  2282. extend_info_free(extend_info);
  2283. return -1;
  2284. }
  2285. /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
  2286. */
  2287. static ssize_t
  2288. rend_service_parse_intro_for_v3(
  2289. rend_intro_cell_t *intro,
  2290. const uint8_t *buf,
  2291. size_t plaintext_len,
  2292. char **err_msg_out)
  2293. {
  2294. ssize_t adjust, v2_ver_specific_len, ts_offset;
  2295. /* This should only be called on v3 cells */
  2296. if (intro->version != 3) {
  2297. if (err_msg_out)
  2298. tor_asprintf(err_msg_out,
  2299. "rend_service_parse_intro_for_v3() called with "
  2300. "bad version %d on INTRODUCE%d cell (this is a bug)",
  2301. intro->version,
  2302. (int)(intro->type));
  2303. goto err;
  2304. }
  2305. /*
  2306. * Check that we have at least enough to get auth_len:
  2307. *
  2308. * 1 octet for version, 1 for auth_type, 2 for auth_len
  2309. */
  2310. if (plaintext_len < 4) {
  2311. if (err_msg_out) {
  2312. tor_asprintf(err_msg_out,
  2313. "truncated plaintext of encrypted parted of "
  2314. "version %d INTRODUCE%d cell",
  2315. intro->version,
  2316. (int)(intro->type));
  2317. }
  2318. goto err;
  2319. }
  2320. /*
  2321. * The rend_client_send_introduction() function over in rendclient.c is
  2322. * broken (i.e., fails to match the spec) in such a way that we can't
  2323. * change it without breaking the protocol. Specifically, it doesn't
  2324. * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
  2325. * by two bytes after that. Calculate ts_offset and do everything from
  2326. * the timestamp on relative to that to handle this dain bramage.
  2327. */
  2328. intro->u.v3.auth_type = buf[1];
  2329. if (intro->u.v3.auth_type != REND_NO_AUTH) {
  2330. intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
  2331. ts_offset = 4 + intro->u.v3.auth_len;
  2332. } else {
  2333. intro->u.v3.auth_len = 0;
  2334. ts_offset = 2;
  2335. }
  2336. /* Check that auth len makes sense for this auth type */
  2337. if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
  2338. intro->u.v3.auth_type == REND_STEALTH_AUTH) {
  2339. if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
  2340. if (err_msg_out) {
  2341. tor_asprintf(err_msg_out,
  2342. "wrong auth data size %d for INTRODUCE%d cell, "
  2343. "should be %d",
  2344. (int)(intro->u.v3.auth_len),
  2345. (int)(intro->type),
  2346. REND_DESC_COOKIE_LEN);
  2347. }
  2348. goto err;
  2349. }
  2350. }
  2351. /* Check that we actually have everything up through the timestamp */
  2352. if (plaintext_len < (size_t)(ts_offset)+4) {
  2353. if (err_msg_out) {
  2354. tor_asprintf(err_msg_out,
  2355. "truncated plaintext of encrypted parted of "
  2356. "version %d INTRODUCE%d cell",
  2357. intro->version,
  2358. (int)(intro->type));
  2359. }
  2360. goto err;
  2361. }
  2362. if (intro->u.v3.auth_type != REND_NO_AUTH &&
  2363. intro->u.v3.auth_len > 0) {
  2364. /* Okay, we can go ahead and copy auth_data */
  2365. intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
  2366. /*
  2367. * We know we had an auth_len field in this case, so 4 is
  2368. * always right.
  2369. */
  2370. memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
  2371. }
  2372. /*
  2373. * From here on, the format is as in v2, so we call the v2 parser with
  2374. * adjusted buffer and length. We are 4 + ts_offset octets in, but the
  2375. * v2 parser expects to skip over a version byte at the start, so we
  2376. * adjust by 3 + ts_offset.
  2377. */
  2378. adjust = 3 + ts_offset;
  2379. v2_ver_specific_len =
  2380. rend_service_parse_intro_for_v2(intro,
  2381. buf + adjust, plaintext_len - adjust,
  2382. err_msg_out);
  2383. /* Success in v2 parser */
  2384. if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
  2385. /* Failure in v2 parser; it will have provided an err_msg */
  2386. else return v2_ver_specific_len;
  2387. err:
  2388. return -1;
  2389. }
  2390. /** Table of parser functions for version-specific parts of an INTRODUCE2
  2391. * cell.
  2392. */
  2393. static ssize_t
  2394. (*intro_version_handlers[])(
  2395. rend_intro_cell_t *,
  2396. const uint8_t *,
  2397. size_t,
  2398. char **) =
  2399. { rend_service_parse_intro_for_v0_or_v1,
  2400. rend_service_parse_intro_for_v0_or_v1,
  2401. rend_service_parse_intro_for_v2,
  2402. rend_service_parse_intro_for_v3 };
  2403. /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
  2404. * return 0 if successful, or < 0 and write an error message to
  2405. * *err_msg_out if provided.
  2406. */
  2407. int
  2408. rend_service_decrypt_intro(
  2409. rend_intro_cell_t *intro,
  2410. crypto_pk_t *key,
  2411. char **err_msg_out)
  2412. {
  2413. char *err_msg = NULL;
  2414. uint8_t key_digest[DIGEST_LEN];
  2415. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  2416. ssize_t key_len;
  2417. uint8_t buf[RELAY_PAYLOAD_SIZE];
  2418. int result, status = -1;
  2419. if (!intro || !key) {
  2420. if (err_msg_out) {
  2421. err_msg =
  2422. tor_strdup("rend_service_decrypt_intro() called with bad "
  2423. "parameters");
  2424. }
  2425. status = -2;
  2426. goto err;
  2427. }
  2428. /* Make sure we have ciphertext */
  2429. if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
  2430. if (err_msg_out) {
  2431. tor_asprintf(&err_msg,
  2432. "rend_intro_cell_t was missing ciphertext for "
  2433. "INTRODUCE%d cell",
  2434. (int)(intro->type));
  2435. }
  2436. status = -3;
  2437. goto err;
  2438. }
  2439. /* Check that this cell actually matches this service key */
  2440. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  2441. if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
  2442. if (err_msg_out)
  2443. *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
  2444. log_warn(LD_BUG, "Couldn't compute key digest.");
  2445. status = -7;
  2446. goto err;
  2447. }
  2448. if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
  2449. if (err_msg_out) {
  2450. base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
  2451. (char*)(intro->pk), REND_SERVICE_ID_LEN);
  2452. tor_asprintf(&err_msg,
  2453. "got an INTRODUCE%d cell for the wrong service (%s)",
  2454. (int)(intro->type),
  2455. escaped(service_id));
  2456. }
  2457. status = -4;
  2458. goto err;
  2459. }
  2460. /* Make sure the encrypted part is long enough to decrypt */
  2461. key_len = crypto_pk_keysize(key);
  2462. if (intro->ciphertext_len < key_len) {
  2463. if (err_msg_out) {
  2464. tor_asprintf(&err_msg,
  2465. "got an INTRODUCE%d cell with a truncated PK-encrypted "
  2466. "part",
  2467. (int)(intro->type));
  2468. }
  2469. status = -5;
  2470. goto err;
  2471. }
  2472. /* Decrypt the encrypted part */
  2473. result =
  2474. crypto_pk_obsolete_private_hybrid_decrypt(
  2475. key, (char *)buf, sizeof(buf),
  2476. (const char *)(intro->ciphertext), intro->ciphertext_len,
  2477. PK_PKCS1_OAEP_PADDING, 1);
  2478. if (result < 0) {
  2479. if (err_msg_out) {
  2480. tor_asprintf(&err_msg,
  2481. "couldn't decrypt INTRODUCE%d cell",
  2482. (int)(intro->type));
  2483. }
  2484. status = -6;
  2485. goto err;
  2486. }
  2487. intro->plaintext_len = result;
  2488. intro->plaintext = tor_malloc(intro->plaintext_len);
  2489. memcpy(intro->plaintext, buf, intro->plaintext_len);
  2490. status = 0;
  2491. goto done;
  2492. err:
  2493. if (err_msg_out && !err_msg) {
  2494. tor_asprintf(&err_msg,
  2495. "unknown INTRODUCE%d error decrypting encrypted part",
  2496. intro ? (int)(intro->type) : -1);
  2497. }
  2498. done:
  2499. if (err_msg_out) *err_msg_out = err_msg;
  2500. else tor_free(err_msg);
  2501. /* clean up potentially sensitive material */
  2502. memwipe(buf, 0, sizeof(buf));
  2503. memwipe(key_digest, 0, sizeof(key_digest));
  2504. memwipe(service_id, 0, sizeof(service_id));
  2505. return status;
  2506. }
  2507. /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
  2508. * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
  2509. * message to *err_msg_out if provided.
  2510. */
  2511. int
  2512. rend_service_parse_intro_plaintext(
  2513. rend_intro_cell_t *intro,
  2514. char **err_msg_out)
  2515. {
  2516. char *err_msg = NULL;
  2517. ssize_t ver_specific_len, ver_invariant_len;
  2518. uint8_t version;
  2519. int status = -1;
  2520. if (!intro) {
  2521. if (err_msg_out) {
  2522. err_msg =
  2523. tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
  2524. "rend_intro_cell_t");
  2525. }
  2526. status = -2;
  2527. goto err;
  2528. }
  2529. /* Check that we have plaintext */
  2530. if (!(intro->plaintext) || intro->plaintext_len <= 0) {
  2531. if (err_msg_out) {
  2532. err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
  2533. }
  2534. status = -3;
  2535. goto err;
  2536. }
  2537. /* In all formats except v0, the first byte is a version number */
  2538. version = intro->plaintext[0];
  2539. /* v0 has no version byte (stupid...), so handle it as a fallback */
  2540. if (version > 3) version = 0;
  2541. /* Copy the version into the parsed cell structure */
  2542. intro->version = version;
  2543. /* Call the version-specific parser from the table */
  2544. ver_specific_len =
  2545. intro_version_handlers[version](intro,
  2546. intro->plaintext, intro->plaintext_len,
  2547. &err_msg);
  2548. if (ver_specific_len < 0) {
  2549. status = -4;
  2550. goto err;
  2551. }
  2552. /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
  2553. * and at the end of the plaintext of the encrypted part of the cell.
  2554. */
  2555. ver_invariant_len = intro->plaintext_len - ver_specific_len;
  2556. if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
  2557. tor_asprintf(&err_msg,
  2558. "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
  2559. (int)(intro->type),
  2560. (long)(intro->plaintext_len));
  2561. status = -5;
  2562. goto err;
  2563. } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
  2564. tor_asprintf(&err_msg,
  2565. "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
  2566. (int)(intro->type),
  2567. (long)(intro->plaintext_len));
  2568. status = -6;
  2569. goto err;
  2570. } else {
  2571. memcpy(intro->rc,
  2572. intro->plaintext + ver_specific_len,
  2573. REND_COOKIE_LEN);
  2574. memcpy(intro->dh,
  2575. intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
  2576. DH1024_KEY_LEN);
  2577. }
  2578. /* Flag it as being fully parsed */
  2579. intro->parsed = 1;
  2580. status = 0;
  2581. goto done;
  2582. err:
  2583. if (err_msg_out && !err_msg) {
  2584. tor_asprintf(&err_msg,
  2585. "unknown INTRODUCE%d error parsing encrypted part",
  2586. intro ? (int)(intro->type) : -1);
  2587. }
  2588. done:
  2589. if (err_msg_out) *err_msg_out = err_msg;
  2590. else tor_free(err_msg);
  2591. return status;
  2592. }
  2593. /** Do validity checks on a parsed intro cell after decryption; some of
  2594. * these are not done in rend_service_parse_intro_plaintext() itself because
  2595. * they depend on a lot of other state and would make it hard to unit test.
  2596. * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
  2597. * optionally writes out an error message for logging. If an err_msg
  2598. * pointer is provided, it is the caller's responsibility to free any
  2599. * provided message.
  2600. */
  2601. int
  2602. rend_service_validate_intro_late(const rend_intro_cell_t *intro,
  2603. char **err_msg_out)
  2604. {
  2605. int status = 0;
  2606. if (!intro) {
  2607. if (err_msg_out)
  2608. *err_msg_out =
  2609. tor_strdup("NULL intro cell passed to "
  2610. "rend_service_validate_intro_late()");
  2611. status = -1;
  2612. goto err;
  2613. }
  2614. if (intro->version == 3 && intro->parsed) {
  2615. if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
  2616. intro->u.v3.auth_type == REND_BASIC_AUTH ||
  2617. intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
  2618. /* This is an informative message, not an error, as in the old code */
  2619. if (err_msg_out)
  2620. tor_asprintf(err_msg_out,
  2621. "unknown authorization type %d",
  2622. intro->u.v3.auth_type);
  2623. }
  2624. }
  2625. err:
  2626. return status;
  2627. }
  2628. /** Called when we fail building a rendezvous circuit at some point other
  2629. * than the last hop: launches a new circuit to the same rendezvous point.
  2630. */
  2631. void
  2632. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  2633. {
  2634. origin_circuit_t *newcirc;
  2635. cpath_build_state_t *newstate, *oldstate;
  2636. tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  2637. oldstate = oldcirc->build_state;
  2638. tor_assert(oldstate);
  2639. if (oldstate->service_pending_final_cpath_ref == NULL) {
  2640. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  2641. "Initiator will retry.");
  2642. return;
  2643. }
  2644. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  2645. safe_str(extend_info_describe(oldstate->chosen_exit)));
  2646. /* You'd think Single Onion Services would want to retry the rendezvous
  2647. * using a direct connection. But if it's blocked by a firewall, or the
  2648. * service is IPv6-only, or the rend point avoiding becoming a one-hop
  2649. * proxy, we need a 3-hop connection. */
  2650. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  2651. oldstate->chosen_exit,
  2652. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  2653. if (!newcirc) {
  2654. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  2655. safe_str(extend_info_describe(oldstate->chosen_exit)));
  2656. return;
  2657. }
  2658. newstate = newcirc->build_state;
  2659. tor_assert(newstate);
  2660. newstate->failure_count = oldstate->failure_count+1;
  2661. newstate->expiry_time = oldstate->expiry_time;
  2662. newstate->service_pending_final_cpath_ref =
  2663. oldstate->service_pending_final_cpath_ref;
  2664. ++(newstate->service_pending_final_cpath_ref->refcount);
  2665. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  2666. }
  2667. /** Launch a circuit to serve as an introduction point for the service
  2668. * <b>service</b> at the introduction point <b>nickname</b>
  2669. */
  2670. static int
  2671. rend_service_launch_establish_intro(rend_service_t *service,
  2672. rend_intro_point_t *intro)
  2673. {
  2674. origin_circuit_t *launched;
  2675. int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
  2676. const or_options_t *options = get_options();
  2677. extend_info_t *launch_ei = intro->extend_info;
  2678. extend_info_t *direct_ei = NULL;
  2679. /* Are we in single onion mode? */
  2680. if (rend_service_allow_non_anonymous_connection(options)) {
  2681. /* Do we have a descriptor for the node?
  2682. * We've either just chosen it from the consensus, or we've just reviewed
  2683. * our intro points to see which ones are still valid, and deleted the ones
  2684. * that aren't in the consensus any more. */
  2685. const node_t *node = node_get_by_id(launch_ei->identity_digest);
  2686. if (BUG(!node)) {
  2687. /* The service has kept an intro point after it went missing from the
  2688. * consensus. If we did anything else here, it would be a consensus
  2689. * distinguisher. Which are less of an issue for single onion services,
  2690. * but still a bug. */
  2691. return -1;
  2692. }
  2693. /* Can we connect to the node directly? If so, replace launch_ei
  2694. * (a multi-hop extend_info) with one suitable for direct connection. */
  2695. if (rend_service_use_direct_connection_node(options, node)) {
  2696. direct_ei = extend_info_from_node(node, 1);
  2697. if (BUG(!direct_ei)) {
  2698. /* rend_service_use_direct_connection_node and extend_info_from_node
  2699. * disagree about which addresses on this node are permitted. This
  2700. * should never happen. Avoiding the connection is a safe response. */
  2701. return -1;
  2702. }
  2703. flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
  2704. launch_ei = direct_ei;
  2705. }
  2706. }
  2707. /* launch_ei is either intro->extend_info, or has been replaced with a valid
  2708. * extend_info for single onion service direct connection. */
  2709. tor_assert(launch_ei);
  2710. /* We must have the same intro when making a direct connection. */
  2711. tor_assert(tor_memeq(intro->extend_info->identity_digest,
  2712. launch_ei->identity_digest,
  2713. DIGEST_LEN));
  2714. log_info(LD_REND,
  2715. "Launching circuit to introduction point %s%s%s for service %s",
  2716. safe_str_client(extend_info_describe(intro->extend_info)),
  2717. direct_ei ? " via direct address " : "",
  2718. direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
  2719. service->service_id);
  2720. rep_hist_note_used_internal(time(NULL), 1, 0);
  2721. ++service->n_intro_circuits_launched;
  2722. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  2723. launch_ei, flags);
  2724. if (!launched) {
  2725. log_info(LD_REND,
  2726. "Can't launch circuit to establish introduction at %s%s%s.",
  2727. safe_str_client(extend_info_describe(intro->extend_info)),
  2728. direct_ei ? " via direct address " : "",
  2729. direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
  2730. );
  2731. extend_info_free(direct_ei);
  2732. return -1;
  2733. }
  2734. /* We must have the same exit node even if cannibalized or direct connection.
  2735. */
  2736. tor_assert(tor_memeq(intro->extend_info->identity_digest,
  2737. launched->build_state->chosen_exit->identity_digest,
  2738. DIGEST_LEN));
  2739. launched->rend_data = rend_data_service_create(service->service_id,
  2740. service->pk_digest, NULL,
  2741. service->auth_type);
  2742. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  2743. if (launched->base_.state == CIRCUIT_STATE_OPEN)
  2744. rend_service_intro_has_opened(launched);
  2745. extend_info_free(direct_ei);
  2746. return 0;
  2747. }
  2748. /** Return the number of introduction points that are established for the
  2749. * given service. */
  2750. static unsigned int
  2751. count_established_intro_points(const rend_service_t *service)
  2752. {
  2753. unsigned int num = 0;
  2754. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  2755. num += intro->circuit_established
  2756. );
  2757. return num;
  2758. }
  2759. /** Return the number of introduction points that are or are being
  2760. * established for the given service. This function iterates over all
  2761. * circuit and count those that are linked to the service and are waiting
  2762. * for the intro point to respond. */
  2763. static unsigned int
  2764. count_intro_point_circuits(const rend_service_t *service)
  2765. {
  2766. unsigned int num_ipos = 0;
  2767. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  2768. if (!circ->marked_for_close &&
  2769. circ->state == CIRCUIT_STATE_OPEN &&
  2770. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  2771. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  2772. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  2773. if (oc->rend_data &&
  2774. rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
  2775. num_ipos++;
  2776. }
  2777. }
  2778. }
  2779. SMARTLIST_FOREACH_END(circ);
  2780. return num_ipos;
  2781. }
  2782. /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
  2783. write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
  2784. as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
  2785. crypto material. On success, fill <b>cell_body_out</b> and return the number
  2786. of bytes written. On fail, return -1.
  2787. */
  2788. ssize_t
  2789. rend_service_encode_establish_intro_cell(char *cell_body_out,
  2790. size_t cell_body_out_len,
  2791. crypto_pk_t *intro_key,
  2792. const char *rend_circ_nonce)
  2793. {
  2794. int retval = -1;
  2795. int r;
  2796. int len = 0;
  2797. char auth[DIGEST_LEN + 9];
  2798. tor_assert(intro_key);
  2799. tor_assert(rend_circ_nonce);
  2800. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  2801. r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
  2802. RELAY_PAYLOAD_SIZE-2);
  2803. if (r < 0) {
  2804. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  2805. goto err;
  2806. }
  2807. len = r;
  2808. set_uint16(cell_body_out, htons((uint16_t)len));
  2809. len += 2;
  2810. memcpy(auth, rend_circ_nonce, DIGEST_LEN);
  2811. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  2812. if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
  2813. goto err;
  2814. len += 20;
  2815. r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
  2816. cell_body_out_len - len,
  2817. cell_body_out, len);
  2818. if (r<0) {
  2819. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  2820. goto err;
  2821. }
  2822. len += r;
  2823. retval = len;
  2824. err:
  2825. memwipe(auth, 0, sizeof(auth));
  2826. return retval;
  2827. }
  2828. /** Called when we're done building a circuit to an introduction point:
  2829. * sends a RELAY_ESTABLISH_INTRO cell.
  2830. */
  2831. void
  2832. rend_service_intro_has_opened(origin_circuit_t *circuit)
  2833. {
  2834. rend_service_t *service;
  2835. char buf[RELAY_PAYLOAD_SIZE];
  2836. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  2837. unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
  2838. int reason = END_CIRC_REASON_TORPROTOCOL;
  2839. const char *rend_pk_digest;
  2840. tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  2841. assert_circ_anonymity_ok(circuit, get_options());
  2842. tor_assert(circuit->cpath);
  2843. tor_assert(circuit->rend_data);
  2844. /* XXX: This is version 2 specific (only on supported). */
  2845. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  2846. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  2847. rend_pk_digest, REND_SERVICE_ID_LEN);
  2848. service = rend_service_get_by_pk_digest(rend_pk_digest);
  2849. if (!service) {
  2850. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
  2851. safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
  2852. reason = END_CIRC_REASON_NOSUCHSERVICE;
  2853. goto err;
  2854. }
  2855. /* Take the current amount of expiring nodes and the current amount of IP
  2856. * circuits and compute how many valid IP circuits we have. */
  2857. expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
  2858. num_ip_circuits = count_intro_point_circuits(service);
  2859. /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
  2860. * case this condition turns out false because it means that all circuits
  2861. * are expiring so we need to keep this circuit. */
  2862. if (num_ip_circuits > expiring_nodes_len) {
  2863. valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
  2864. }
  2865. /* If we already have enough introduction circuits for this service,
  2866. * redefine this one as a general circuit or close it, depending.
  2867. * Subtract the amount of expiring nodes here because the circuits are
  2868. * still opened. */
  2869. if (valid_ip_circuits > service->n_intro_points_wanted) {
  2870. const or_options_t *options = get_options();
  2871. /* Remove the intro point associated with this circuit, it's being
  2872. * repurposed or closed thus cleanup memory. */
  2873. rend_intro_point_t *intro = find_intro_point(circuit);
  2874. if (intro != NULL) {
  2875. smartlist_remove(service->intro_nodes, intro);
  2876. rend_intro_point_free(intro);
  2877. }
  2878. if (options->ExcludeNodes) {
  2879. /* XXXX in some future version, we can test whether the transition is
  2880. allowed or not given the actual nodes in the circuit. But for now,
  2881. this case, we might as well close the thing. */
  2882. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  2883. "circuit, but we already have enough. Closing it.");
  2884. reason = END_CIRC_REASON_NONE;
  2885. goto err;
  2886. } else {
  2887. tor_assert(circuit->build_state->is_internal);
  2888. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  2889. "circuit, but we already have enough. Redefining purpose to "
  2890. "general; leaving as internal.");
  2891. if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
  2892. circuit_change_purpose(TO_CIRCUIT(circuit),
  2893. CIRCUIT_PURPOSE_HS_VANGUARDS);
  2894. } else {
  2895. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
  2896. }
  2897. {
  2898. rend_data_free(circuit->rend_data);
  2899. circuit->rend_data = NULL;
  2900. }
  2901. {
  2902. crypto_pk_t *intro_key = circuit->intro_key;
  2903. circuit->intro_key = NULL;
  2904. crypto_pk_free(intro_key);
  2905. }
  2906. circuit_has_opened(circuit);
  2907. goto done;
  2908. }
  2909. }
  2910. log_info(LD_REND,
  2911. "Established circuit %u as introduction point for service %s",
  2912. (unsigned)circuit->base_.n_circ_id, serviceid);
  2913. circuit_log_path(LOG_INFO, LD_REND, circuit);
  2914. /* Send the ESTABLISH_INTRO cell */
  2915. {
  2916. ssize_t len;
  2917. len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
  2918. circuit->intro_key,
  2919. circuit->cpath->prev->rend_circ_nonce);
  2920. if (len < 0) {
  2921. reason = END_CIRC_REASON_INTERNAL;
  2922. goto err;
  2923. }
  2924. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  2925. RELAY_COMMAND_ESTABLISH_INTRO,
  2926. buf, len, circuit->cpath->prev)<0) {
  2927. log_info(LD_GENERAL,
  2928. "Couldn't send introduction request for service %s on circuit %u",
  2929. serviceid, (unsigned)circuit->base_.n_circ_id);
  2930. goto done;
  2931. }
  2932. }
  2933. /* We've attempted to use this circuit */
  2934. pathbias_count_use_attempt(circuit);
  2935. goto done;
  2936. err:
  2937. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  2938. done:
  2939. memwipe(buf, 0, sizeof(buf));
  2940. memwipe(serviceid, 0, sizeof(serviceid));
  2941. return;
  2942. }
  2943. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  2944. * live introduction point, and note that the service descriptor is
  2945. * now out-of-date. */
  2946. int
  2947. rend_service_intro_established(origin_circuit_t *circuit,
  2948. const uint8_t *request,
  2949. size_t request_len)
  2950. {
  2951. rend_service_t *service;
  2952. rend_intro_point_t *intro;
  2953. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  2954. (void) request;
  2955. (void) request_len;
  2956. tor_assert(circuit->rend_data);
  2957. /* XXX: This is version 2 specific (only supported one for now). */
  2958. const char *rend_pk_digest =
  2959. (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
  2960. if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  2961. log_warn(LD_PROTOCOL,
  2962. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  2963. goto err;
  2964. }
  2965. service = rend_service_get_by_pk_digest(rend_pk_digest);
  2966. if (!service) {
  2967. log_warn(LD_REND, "Unknown service on introduction circuit %u.",
  2968. (unsigned)circuit->base_.n_circ_id);
  2969. goto err;
  2970. }
  2971. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  2972. rend_pk_digest, REND_SERVICE_ID_LEN);
  2973. /* We've just successfully established a intro circuit to one of our
  2974. * introduction point, account for it. */
  2975. intro = find_intro_point(circuit);
  2976. if (intro == NULL) {
  2977. log_warn(LD_REND,
  2978. "Introduction circuit established without a rend_intro_point_t "
  2979. "object for service %s on circuit %u",
  2980. safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
  2981. goto err;
  2982. }
  2983. intro->circuit_established = 1;
  2984. /* We might not have every introduction point ready but at this point we
  2985. * know that the descriptor needs to be uploaded. */
  2986. service->desc_is_dirty = time(NULL);
  2987. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
  2988. log_info(LD_REND,
  2989. "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
  2990. (unsigned)circuit->base_.n_circ_id, serviceid);
  2991. /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
  2992. * used the circ */
  2993. pathbias_mark_use_success(circuit);
  2994. return 0;
  2995. err:
  2996. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  2997. return -1;
  2998. }
  2999. /** Called once a circuit to a rendezvous point is established: sends a
  3000. * RELAY_COMMAND_RENDEZVOUS1 cell.
  3001. */
  3002. void
  3003. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  3004. {
  3005. rend_service_t *service;
  3006. char buf[RELAY_PAYLOAD_SIZE];
  3007. crypt_path_t *hop;
  3008. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3009. char hexcookie[9];
  3010. int reason;
  3011. const char *rend_cookie, *rend_pk_digest;
  3012. tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  3013. tor_assert(circuit->cpath);
  3014. tor_assert(circuit->build_state);
  3015. assert_circ_anonymity_ok(circuit, get_options());
  3016. tor_assert(circuit->rend_data);
  3017. /* XXX: This is version 2 specific (only one supported). */
  3018. rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
  3019. NULL);
  3020. rend_cookie = circuit->rend_data->rend_cookie;
  3021. /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
  3022. * timestamp regardless of its content because that circuit could have been
  3023. * cannibalized so in any cases, we are about to use that circuit more. */
  3024. circuit->base_.timestamp_dirty = time(NULL);
  3025. /* This may be redundant */
  3026. pathbias_count_use_attempt(circuit);
  3027. hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
  3028. base16_encode(hexcookie,9, rend_cookie,4);
  3029. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  3030. rend_pk_digest, REND_SERVICE_ID_LEN);
  3031. log_info(LD_REND,
  3032. "Done building circuit %u to rendezvous with "
  3033. "cookie %s for service %s",
  3034. (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
  3035. circuit_log_path(LOG_INFO, LD_REND, circuit);
  3036. /* Clear the 'in-progress HS circ has timed out' flag for
  3037. * consistency with what happens on the client side; this line has
  3038. * no effect on Tor's behaviour. */
  3039. circuit->hs_circ_has_timed_out = 0;
  3040. /* If hop is NULL, another rend circ has already connected to this
  3041. * rend point. Close this circ. */
  3042. if (hop == NULL) {
  3043. log_info(LD_REND, "Another rend circ has already reached this rend point; "
  3044. "closing this rend circ.");
  3045. reason = END_CIRC_REASON_NONE;
  3046. goto err;
  3047. }
  3048. /* Remove our final cpath element from the reference, so that no
  3049. * other circuit will try to use it. Store it in
  3050. * pending_final_cpath for now to ensure that it will be freed if
  3051. * our rendezvous attempt fails. */
  3052. circuit->build_state->pending_final_cpath = hop;
  3053. circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
  3054. service = rend_service_get_by_pk_digest(rend_pk_digest);
  3055. if (!service) {
  3056. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  3057. "rendezvous circuit.");
  3058. reason = END_CIRC_REASON_INTERNAL;
  3059. goto err;
  3060. }
  3061. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  3062. memcpy(buf, rend_cookie, REND_COOKIE_LEN);
  3063. if (crypto_dh_get_public(hop->rend_dh_handshake_state,
  3064. buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
  3065. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  3066. reason = END_CIRC_REASON_INTERNAL;
  3067. goto err;
  3068. }
  3069. memcpy(buf+REND_COOKIE_LEN+DH1024_KEY_LEN, hop->rend_circ_nonce,
  3070. DIGEST_LEN);
  3071. /* Send the cell */
  3072. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  3073. RELAY_COMMAND_RENDEZVOUS1,
  3074. buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
  3075. circuit->cpath->prev)<0) {
  3076. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  3077. goto done;
  3078. }
  3079. crypto_dh_free(hop->rend_dh_handshake_state);
  3080. hop->rend_dh_handshake_state = NULL;
  3081. /* Append the cpath entry. */
  3082. hop->state = CPATH_STATE_OPEN;
  3083. /* set the windows to default. these are the windows
  3084. * that the service thinks the client has.
  3085. */
  3086. hop->package_window = circuit_initial_package_window();
  3087. hop->deliver_window = CIRCWINDOW_START;
  3088. onion_append_to_cpath(&circuit->cpath, hop);
  3089. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  3090. /* Change the circuit purpose. */
  3091. circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
  3092. goto done;
  3093. err:
  3094. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  3095. done:
  3096. memwipe(buf, 0, sizeof(buf));
  3097. memwipe(serviceid, 0, sizeof(serviceid));
  3098. memwipe(hexcookie, 0, sizeof(hexcookie));
  3099. return;
  3100. }
  3101. /*
  3102. * Manage introduction points
  3103. */
  3104. /** Return the (possibly non-open) introduction circuit ending at
  3105. * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
  3106. * (<b>desc_version</b> is ignored). Return NULL if no such service is
  3107. * found.
  3108. */
  3109. static origin_circuit_t *
  3110. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
  3111. {
  3112. origin_circuit_t *circ = NULL;
  3113. tor_assert(intro);
  3114. while ((circ = circuit_get_next_by_pk_and_purpose(circ,
  3115. (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
  3116. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  3117. intro->extend_info->identity_digest, DIGEST_LEN) &&
  3118. circ->rend_data) {
  3119. return circ;
  3120. }
  3121. }
  3122. circ = NULL;
  3123. while ((circ = circuit_get_next_by_pk_and_purpose(circ,
  3124. (uint8_t *) pk_digest,
  3125. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  3126. if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
  3127. intro->extend_info->identity_digest, DIGEST_LEN) &&
  3128. circ->rend_data) {
  3129. return circ;
  3130. }
  3131. }
  3132. return NULL;
  3133. }
  3134. /** Return the corresponding introdution point using the circuit <b>circ</b>
  3135. * found in the <b>service</b>. NULL is returned if not found. */
  3136. static rend_intro_point_t *
  3137. find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
  3138. {
  3139. tor_assert(service);
  3140. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  3141. TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  3142. SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
  3143. intro_point,
  3144. if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
  3145. return intro_point;
  3146. });
  3147. return NULL;
  3148. }
  3149. /** Return a pointer to the rend_intro_point_t corresponding to the
  3150. * service-side introduction circuit <b>circ</b>. */
  3151. static rend_intro_point_t *
  3152. find_intro_point(origin_circuit_t *circ)
  3153. {
  3154. const char *serviceid;
  3155. rend_service_t *service = NULL;
  3156. tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  3157. TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
  3158. tor_assert(circ->rend_data);
  3159. serviceid = rend_data_get_address(circ->rend_data);
  3160. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
  3161. if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
  3162. service = s;
  3163. break;
  3164. });
  3165. if (service == NULL) return NULL;
  3166. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
  3167. if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
  3168. return intro_point;
  3169. });
  3170. return NULL;
  3171. }
  3172. /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
  3173. * associated with the rend_service_descriptor_t <b>renddesc</b> to
  3174. * the responsible hidden service directories OR the hidden service
  3175. * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
  3176. * <b>seconds_valid</b> are only passed for logging purposes.
  3177. */
  3178. void
  3179. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  3180. smartlist_t *descs, smartlist_t *hs_dirs,
  3181. const char *service_id, int seconds_valid)
  3182. {
  3183. int i, j, failed_upload = 0;
  3184. smartlist_t *responsible_dirs = smartlist_new();
  3185. smartlist_t *successful_uploads = smartlist_new();
  3186. routerstatus_t *hs_dir;
  3187. for (i = 0; i < smartlist_len(descs); i++) {
  3188. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  3189. /** If any HSDirs are specified, they should be used instead of
  3190. * the responsible directories */
  3191. if (hs_dirs && smartlist_len(hs_dirs) > 0) {
  3192. smartlist_add_all(responsible_dirs, hs_dirs);
  3193. } else {
  3194. /* Determine responsible dirs. */
  3195. if (hid_serv_get_responsible_directories(responsible_dirs,
  3196. desc->desc_id) < 0) {
  3197. log_warn(LD_REND, "Could not determine the responsible hidden service "
  3198. "directories to post descriptors to.");
  3199. control_event_hs_descriptor_upload(service_id,
  3200. "UNKNOWN",
  3201. "UNKNOWN", NULL);
  3202. goto done;
  3203. }
  3204. }
  3205. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  3206. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  3207. char *hs_dir_ip;
  3208. const node_t *node;
  3209. rend_data_t *rend_data;
  3210. hs_dir = smartlist_get(responsible_dirs, j);
  3211. if (smartlist_contains_digest(renddesc->successful_uploads,
  3212. hs_dir->identity_digest))
  3213. /* Don't upload descriptor if we succeeded in doing so last time. */
  3214. continue;
  3215. node = node_get_by_id(hs_dir->identity_digest);
  3216. if (!node || !node_has_preferred_descriptor(node,0)) {
  3217. log_info(LD_REND, "Not launching upload for for v2 descriptor to "
  3218. "hidden service directory %s; we don't have its "
  3219. "router descriptor. Queuing for later upload.",
  3220. safe_str_client(routerstatus_describe(hs_dir)));
  3221. failed_upload = -1;
  3222. continue;
  3223. }
  3224. /* Send publish request. */
  3225. /* We need the service ID to identify which service did the upload
  3226. * request. Lookup is made in rend_service_desc_has_uploaded(). */
  3227. rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
  3228. REND_NO_AUTH);
  3229. directory_request_t *req =
  3230. directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2);
  3231. directory_request_set_routerstatus(req, hs_dir);
  3232. directory_request_set_indirection(req, DIRIND_ANONYMOUS);
  3233. directory_request_set_payload(req,
  3234. desc->desc_str, strlen(desc->desc_str));
  3235. directory_request_set_rend_query(req, rend_data);
  3236. directory_initiate_request(req);
  3237. directory_request_free(req);
  3238. rend_data_free(rend_data);
  3239. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  3240. desc->desc_id, DIGEST_LEN);
  3241. hs_dir_ip = tor_dup_ip(hs_dir->addr);
  3242. log_info(LD_REND, "Launching upload for v2 descriptor for "
  3243. "service '%s' with descriptor ID '%s' with validity "
  3244. "of %d seconds to hidden service directory '%s' on "
  3245. "%s:%d.",
  3246. safe_str_client(service_id),
  3247. safe_str_client(desc_id_base32),
  3248. seconds_valid,
  3249. hs_dir->nickname,
  3250. hs_dir_ip,
  3251. hs_dir->or_port);
  3252. control_event_hs_descriptor_upload(service_id,
  3253. hs_dir->identity_digest,
  3254. desc_id_base32, NULL);
  3255. tor_free(hs_dir_ip);
  3256. /* Remember successful upload to this router for next time. */
  3257. if (!smartlist_contains_digest(successful_uploads,
  3258. hs_dir->identity_digest))
  3259. smartlist_add(successful_uploads, hs_dir->identity_digest);
  3260. }
  3261. smartlist_clear(responsible_dirs);
  3262. }
  3263. if (!failed_upload) {
  3264. if (renddesc->successful_uploads) {
  3265. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  3266. smartlist_free(renddesc->successful_uploads);
  3267. renddesc->successful_uploads = NULL;
  3268. }
  3269. renddesc->all_uploads_performed = 1;
  3270. } else {
  3271. /* Remember which routers worked this time, so that we don't upload the
  3272. * descriptor to them again. */
  3273. if (!renddesc->successful_uploads)
  3274. renddesc->successful_uploads = smartlist_new();
  3275. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  3276. if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
  3277. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  3278. smartlist_add(renddesc->successful_uploads, hsdir_id);
  3279. }
  3280. });
  3281. }
  3282. done:
  3283. smartlist_free(responsible_dirs);
  3284. smartlist_free(successful_uploads);
  3285. }
  3286. /** Encode and sign an up-to-date service descriptor for <b>service</b>,
  3287. * and upload it/them to the responsible hidden service directories.
  3288. */
  3289. static void
  3290. upload_service_descriptor(rend_service_t *service)
  3291. {
  3292. time_t now = time(NULL);
  3293. int rendpostperiod;
  3294. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3295. int uploaded = 0;
  3296. rendpostperiod = get_options()->RendPostPeriod;
  3297. networkstatus_t *c = networkstatus_get_latest_consensus();
  3298. if (c && smartlist_len(c->routerstatus_list) > 0) {
  3299. int seconds_valid, i, j, num_descs;
  3300. smartlist_t *descs = smartlist_new();
  3301. smartlist_t *client_cookies = smartlist_new();
  3302. /* Either upload a single descriptor (including replicas) or one
  3303. * descriptor for each authorized client in case of authorization
  3304. * type 'stealth'. */
  3305. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  3306. smartlist_len(service->clients) : 1;
  3307. for (j = 0; j < num_descs; j++) {
  3308. crypto_pk_t *client_key = NULL;
  3309. rend_authorized_client_t *client = NULL;
  3310. smartlist_clear(client_cookies);
  3311. switch (service->auth_type) {
  3312. case REND_NO_AUTH:
  3313. /* Do nothing here. */
  3314. break;
  3315. case REND_BASIC_AUTH:
  3316. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  3317. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  3318. break;
  3319. case REND_STEALTH_AUTH:
  3320. client = smartlist_get(service->clients, j);
  3321. client_key = client->client_key;
  3322. smartlist_add(client_cookies, client->descriptor_cookie);
  3323. break;
  3324. }
  3325. /* Encode the current descriptor. */
  3326. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  3327. now, 0,
  3328. service->auth_type,
  3329. client_key,
  3330. client_cookies);
  3331. if (seconds_valid < 0) {
  3332. log_warn(LD_BUG, "Internal error: couldn't encode service "
  3333. "descriptor; not uploading.");
  3334. smartlist_free(descs);
  3335. smartlist_free(client_cookies);
  3336. return;
  3337. }
  3338. rend_get_service_id(service->desc->pk, serviceid);
  3339. if (get_options()->PublishHidServDescriptors) {
  3340. /* Post the current descriptors to the hidden service directories. */
  3341. log_info(LD_REND, "Launching upload for hidden service %s",
  3342. serviceid);
  3343. directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
  3344. seconds_valid);
  3345. }
  3346. /* Free memory for descriptors. */
  3347. for (i = 0; i < smartlist_len(descs); i++)
  3348. rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
  3349. smartlist_clear(descs);
  3350. /* Update next upload time. */
  3351. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  3352. > rendpostperiod)
  3353. service->next_upload_time = now + rendpostperiod;
  3354. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  3355. service->next_upload_time = now + seconds_valid + 1;
  3356. else
  3357. service->next_upload_time = now + seconds_valid -
  3358. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  3359. /* Post also the next descriptors, if necessary. */
  3360. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  3361. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  3362. now, 1,
  3363. service->auth_type,
  3364. client_key,
  3365. client_cookies);
  3366. if (seconds_valid < 0) {
  3367. log_warn(LD_BUG, "Internal error: couldn't encode service "
  3368. "descriptor; not uploading.");
  3369. smartlist_free(descs);
  3370. smartlist_free(client_cookies);
  3371. return;
  3372. }
  3373. if (get_options()->PublishHidServDescriptors) {
  3374. directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
  3375. seconds_valid);
  3376. }
  3377. /* Free memory for descriptors. */
  3378. for (i = 0; i < smartlist_len(descs); i++)
  3379. rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
  3380. smartlist_clear(descs);
  3381. }
  3382. }
  3383. smartlist_free(descs);
  3384. smartlist_free(client_cookies);
  3385. uploaded = 1;
  3386. if (get_options()->PublishHidServDescriptors) {
  3387. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  3388. } else {
  3389. log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
  3390. }
  3391. }
  3392. /* If not uploaded, try again in one minute. */
  3393. if (!uploaded)
  3394. service->next_upload_time = now + 60;
  3395. /* Unmark dirty flag of this service. */
  3396. service->desc_is_dirty = 0;
  3397. }
  3398. /** Return the number of INTRODUCE2 cells this hidden service has received
  3399. * from this intro point. */
  3400. static int
  3401. intro_point_accepted_intro_count(rend_intro_point_t *intro)
  3402. {
  3403. return intro->accepted_introduce2_count;
  3404. }
  3405. /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
  3406. * should stop publishing it in new descriptors and eventually close
  3407. * it). */
  3408. static int
  3409. intro_point_should_expire_now(rend_intro_point_t *intro,
  3410. time_t now)
  3411. {
  3412. tor_assert(intro != NULL);
  3413. if (intro->time_published == -1) {
  3414. /* Don't expire an intro point if we haven't even published it yet. */
  3415. return 0;
  3416. }
  3417. if (intro_point_accepted_intro_count(intro) >=
  3418. intro->max_introductions) {
  3419. /* This intro point has been used too many times. Expire it now. */
  3420. return 1;
  3421. }
  3422. if (intro->time_to_expire == -1) {
  3423. /* This intro point has been published, but we haven't picked an
  3424. * expiration time for it. Pick one now. */
  3425. int intro_point_lifetime_seconds =
  3426. crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
  3427. INTRO_POINT_LIFETIME_MAX_SECONDS);
  3428. /* Start the expiration timer now, rather than when the intro
  3429. * point was first published. There shouldn't be much of a time
  3430. * difference. */
  3431. intro->time_to_expire = now + intro_point_lifetime_seconds;
  3432. return 0;
  3433. }
  3434. /* This intro point has a time to expire set already. Use it. */
  3435. return (now >= intro->time_to_expire);
  3436. }
  3437. /** Iterate over intro points in the given service and remove the invalid
  3438. * ones. For an intro point object to be considered invalid, the circuit
  3439. * _and_ node need to have disappeared.
  3440. *
  3441. * If the intro point should expire, it's placed into the expiring_nodes
  3442. * list of the service and removed from the active intro nodes list.
  3443. *
  3444. * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
  3445. *
  3446. * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
  3447. * circuit disappeared but the node is still in the consensus. */
  3448. static void
  3449. remove_invalid_intro_points(rend_service_t *service,
  3450. smartlist_t *exclude_nodes,
  3451. smartlist_t *retry_nodes, time_t now)
  3452. {
  3453. tor_assert(service);
  3454. /* Remove any expired nodes that doesn't have a circuit. */
  3455. SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
  3456. intro) {
  3457. origin_circuit_t *intro_circ =
  3458. find_intro_circuit(intro, service->pk_digest);
  3459. if (intro_circ) {
  3460. continue;
  3461. }
  3462. /* No more circuit, cleanup the into point object. */
  3463. SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
  3464. rend_intro_point_free(intro);
  3465. } SMARTLIST_FOREACH_END(intro);
  3466. SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
  3467. intro) {
  3468. /* Find the introduction point node object. */
  3469. const node_t *node =
  3470. node_get_by_id(intro->extend_info->identity_digest);
  3471. /* Find the intro circuit, this might be NULL. */
  3472. origin_circuit_t *intro_circ =
  3473. find_intro_circuit(intro, service->pk_digest);
  3474. /* Add the valid node to the exclusion list so we don't try to establish
  3475. * an introduction point to it again. */
  3476. if (node && exclude_nodes) {
  3477. smartlist_add(exclude_nodes, (void*) node);
  3478. }
  3479. /* First, make sure we still have a valid circuit for this intro point.
  3480. * If we dont, we'll give up on it and make a new one. */
  3481. if (intro_circ == NULL) {
  3482. log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
  3483. " (circuit disappeared).",
  3484. safe_str_client(extend_info_describe(intro->extend_info)),
  3485. safe_str_client(service->service_id));
  3486. /* We've lost the circuit for this intro point, flag it so it can be
  3487. * accounted for when considiring uploading a descriptor. */
  3488. intro->circuit_established = 0;
  3489. /* Node is gone or we've reached our maximum circuit creationg retry
  3490. * count, clean up everything, we'll find a new one. */
  3491. if (node == NULL ||
  3492. intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
  3493. rend_intro_point_free(intro);
  3494. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  3495. /* We've just killed the intro point, nothing left to do. */
  3496. continue;
  3497. }
  3498. /* The intro point is still alive so let's try to use it again because
  3499. * we have a published descriptor containing it. Keep the intro point
  3500. * in the intro_nodes list because it's still valid, we are rebuilding
  3501. * a circuit to it. */
  3502. if (retry_nodes) {
  3503. smartlist_add(retry_nodes, intro);
  3504. }
  3505. }
  3506. /* else, the circuit is valid so in both cases, node being alive or not,
  3507. * we leave the circuit and intro point object as is. Closing the
  3508. * circuit here would leak new consensus timing and freeing the intro
  3509. * point object would make the intro circuit unusable. */
  3510. /* Now, check if intro point should expire. If it does, queue it so
  3511. * it can be cleaned up once it has been replaced properly. */
  3512. if (intro_point_should_expire_now(intro, now)) {
  3513. log_info(LD_REND, "Expiring %s as intro point for %s.",
  3514. safe_str_client(extend_info_describe(intro->extend_info)),
  3515. safe_str_client(service->service_id));
  3516. /* We might have put it in the retry list if so, undo. */
  3517. if (retry_nodes) {
  3518. smartlist_remove(retry_nodes, intro);
  3519. }
  3520. smartlist_add(service->expiring_nodes, intro);
  3521. SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
  3522. /* Intro point is expired, we need a new one thus don't consider it
  3523. * anymore has a valid established intro point. */
  3524. intro->circuit_established = 0;
  3525. }
  3526. } SMARTLIST_FOREACH_END(intro);
  3527. }
  3528. /** A new descriptor has been successfully uploaded for the given
  3529. * <b>rend_data</b>. Remove and free the expiring nodes from the associated
  3530. * service. */
  3531. void
  3532. rend_service_desc_has_uploaded(const rend_data_t *rend_data)
  3533. {
  3534. rend_service_t *service;
  3535. const char *onion_address;
  3536. tor_assert(rend_data);
  3537. onion_address = rend_data_get_address(rend_data);
  3538. service = rend_service_get_by_service_id(onion_address);
  3539. if (service == NULL) {
  3540. return;
  3541. }
  3542. SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
  3543. intro) {
  3544. origin_circuit_t *intro_circ =
  3545. find_intro_circuit(intro, service->pk_digest);
  3546. if (intro_circ != NULL) {
  3547. circuit_mark_for_close(TO_CIRCUIT(intro_circ),
  3548. END_CIRC_REASON_FINISHED);
  3549. }
  3550. SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
  3551. rend_intro_point_free(intro);
  3552. } SMARTLIST_FOREACH_END(intro);
  3553. }
  3554. /** Don't try to build more than this many circuits before giving up
  3555. * for a while. Dynamically calculated based on the configured number of
  3556. * introduction points for the service, n_intro_points_wanted. */
  3557. static int
  3558. rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
  3559. {
  3560. /* Allow all but one of the initial connections to fail and be
  3561. * retried. (If all fail, we *want* to wait, because something is broken.) */
  3562. tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
  3563. /* For the normal use case, 3 intro points plus 2 extra for performance and
  3564. * allow that twice because once every 24h or so, we can do it twice for two
  3565. * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
  3566. * 12 allowed attempts for one period. */
  3567. return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
  3568. }
  3569. /** For every service, check how many intro points it currently has, and:
  3570. * - Invalidate introdution points based on specific criteria, see
  3571. * remove_invalid_intro_points comments.
  3572. * - Pick new intro points as necessary.
  3573. * - Launch circuits to any new intro points.
  3574. *
  3575. * This is called once a second by the main loop.
  3576. */
  3577. void
  3578. rend_consider_services_intro_points(time_t now)
  3579. {
  3580. int i;
  3581. const or_options_t *options = get_options();
  3582. /* Are we in single onion mode? */
  3583. const int allow_direct = rend_service_allow_non_anonymous_connection(
  3584. get_options());
  3585. /* List of nodes we need to _exclude_ when choosing a new node to
  3586. * establish an intro point to. */
  3587. smartlist_t *exclude_nodes;
  3588. /* List of nodes we need to retry to build a circuit on them because the
  3589. * node is valid but circuit died. */
  3590. smartlist_t *retry_nodes;
  3591. if (!have_completed_a_circuit())
  3592. return;
  3593. exclude_nodes = smartlist_new();
  3594. retry_nodes = smartlist_new();
  3595. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
  3596. int r;
  3597. /* Number of intro points we want to open and add to the intro nodes
  3598. * list of the service. */
  3599. unsigned int n_intro_points_to_open;
  3600. /* Have an unsigned len so we can use it to compare values else gcc is
  3601. * not happy with unmatching signed comparaison. */
  3602. unsigned int intro_nodes_len;
  3603. /* Different service are allowed to have the same introduction point as
  3604. * long as they are on different circuit thus why we clear this list. */
  3605. smartlist_clear(exclude_nodes);
  3606. smartlist_clear(retry_nodes);
  3607. /* Cleanup the invalid intro points and save the node objects, if any,
  3608. * in the exclude_nodes and retry_nodes lists. */
  3609. remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
  3610. /* This retry period is important here so we don't stress circuit
  3611. * creation. */
  3612. if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
  3613. /* One period has elapsed:
  3614. * - if we stopped, we can try building circuits again,
  3615. * - if we haven't, we reset the circuit creation counts. */
  3616. rend_log_intro_limit(service, LOG_INFO);
  3617. service->intro_period_started = now;
  3618. service->n_intro_circuits_launched = 0;
  3619. } else if (service->n_intro_circuits_launched >=
  3620. rend_max_intro_circs_per_period(
  3621. service->n_intro_points_wanted)) {
  3622. /* We have failed too many times in this period; wait for the next
  3623. * one before we try to initiate any more connections. */
  3624. rend_log_intro_limit(service, LOG_WARN);
  3625. continue;
  3626. }
  3627. /* Let's try to rebuild circuit on the nodes we want to retry on. */
  3628. SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
  3629. r = rend_service_launch_establish_intro(service, intro);
  3630. if (r < 0) {
  3631. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  3632. safe_str_client(extend_info_describe(intro->extend_info)),
  3633. safe_str_client(service->service_id));
  3634. /* Unable to launch a circuit to that intro point, remove it from
  3635. * the valid list so we can create a new one. */
  3636. smartlist_remove(service->intro_nodes, intro);
  3637. rend_intro_point_free(intro);
  3638. continue;
  3639. }
  3640. intro->circuit_retries++;
  3641. } SMARTLIST_FOREACH_END(intro);
  3642. /* Avoid mismatched signed comparaison below. */
  3643. intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
  3644. /* Quiescent state, we have more or the equal amount of wanted node for
  3645. * this service. Proceed to the next service. We can have more nodes
  3646. * because we launch extra preemptive circuits if our intro nodes list was
  3647. * originally empty for performance reasons. */
  3648. if (intro_nodes_len >= service->n_intro_points_wanted) {
  3649. continue;
  3650. }
  3651. /* Number of intro points we want to open which is the wanted amount minus
  3652. * the current amount of valid nodes. We know that this won't underflow
  3653. * because of the check above. */
  3654. n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
  3655. if (intro_nodes_len == 0) {
  3656. /* We want to end up with n_intro_points_wanted intro points, but if
  3657. * we have no intro points at all (chances are they all cycled or we
  3658. * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
  3659. * and use the first n_intro_points_wanted that complete. See proposal
  3660. * #155, section 4 for the rationale of this which is purely for
  3661. * performance.
  3662. *
  3663. * The ones after the first n_intro_points_to_open will be converted
  3664. * to 'general' internal circuits in rend_service_intro_has_opened(),
  3665. * and then we'll drop them from the list of intro points. */
  3666. n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
  3667. }
  3668. for (i = 0; i < (int) n_intro_points_to_open; i++) {
  3669. const node_t *node;
  3670. rend_intro_point_t *intro;
  3671. router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
  3672. router_crn_flags_t direct_flags = flags;
  3673. direct_flags |= CRN_PREF_ADDR;
  3674. direct_flags |= CRN_DIRECT_CONN;
  3675. node = router_choose_random_node(exclude_nodes,
  3676. options->ExcludeNodes,
  3677. allow_direct ? direct_flags : flags);
  3678. /* If we are in single onion mode, retry node selection for a 3-hop
  3679. * path */
  3680. if (allow_direct && !node) {
  3681. log_info(LD_REND,
  3682. "Unable to find an intro point that we can connect to "
  3683. "directly for %s, falling back to a 3-hop path.",
  3684. safe_str_client(service->service_id));
  3685. node = router_choose_random_node(exclude_nodes,
  3686. options->ExcludeNodes, flags);
  3687. }
  3688. if (!node) {
  3689. log_warn(LD_REND,
  3690. "We only have %d introduction points established for %s; "
  3691. "wanted %u.",
  3692. smartlist_len(service->intro_nodes),
  3693. safe_str_client(service->service_id),
  3694. n_intro_points_to_open);
  3695. break;
  3696. }
  3697. /* Add the chosen node to the exclusion list in order to avoid picking
  3698. * it again in the next iteration. */
  3699. smartlist_add(exclude_nodes, (void*)node);
  3700. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3701. /* extend_info is for clients, so we want the multi-hop primary ORPort,
  3702. * even if we are a single onion service and intend to connect to it
  3703. * directly ourselves. */
  3704. intro->extend_info = extend_info_from_node(node, 0);
  3705. if (BUG(intro->extend_info == NULL)) {
  3706. break;
  3707. }
  3708. intro->intro_key = crypto_pk_new();
  3709. const int fail = crypto_pk_generate_key(intro->intro_key);
  3710. tor_assert(!fail);
  3711. intro->time_published = -1;
  3712. intro->time_to_expire = -1;
  3713. intro->max_introductions =
  3714. crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  3715. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
  3716. smartlist_add(service->intro_nodes, intro);
  3717. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  3718. safe_str_client(node_describe(node)),
  3719. safe_str_client(service->service_id));
  3720. /* Establish new introduction circuit to our chosen intro point. */
  3721. r = rend_service_launch_establish_intro(service, intro);
  3722. if (r < 0) {
  3723. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  3724. safe_str_client(extend_info_describe(intro->extend_info)),
  3725. safe_str_client(service->service_id));
  3726. /* This funcion will be called again by the main loop so this intro
  3727. * point without a intro circuit will be retried on or removed after
  3728. * a maximum number of attempts. */
  3729. }
  3730. }
  3731. } SMARTLIST_FOREACH_END(service);
  3732. smartlist_free(exclude_nodes);
  3733. smartlist_free(retry_nodes);
  3734. }
  3735. #define MIN_REND_INITIAL_POST_DELAY (30)
  3736. #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
  3737. /** Regenerate and upload rendezvous service descriptors for all
  3738. * services, if necessary. If the descriptor has been dirty enough
  3739. * for long enough, definitely upload; else only upload when the
  3740. * periodic timeout has expired.
  3741. *
  3742. * For the first upload, pick a random time between now and two periods
  3743. * from now, and pick it independently for each service.
  3744. */
  3745. void
  3746. rend_consider_services_upload(time_t now)
  3747. {
  3748. int i;
  3749. rend_service_t *service;
  3750. const or_options_t *options = get_options();
  3751. int rendpostperiod = options->RendPostPeriod;
  3752. int rendinitialpostdelay = (options->TestingTorNetwork ?
  3753. MIN_REND_INITIAL_POST_DELAY_TESTING :
  3754. MIN_REND_INITIAL_POST_DELAY);
  3755. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3756. service = smartlist_get(rend_service_list, i);
  3757. if (!service->next_upload_time) { /* never been uploaded yet */
  3758. /* The fixed lower bound of rendinitialpostdelay seconds ensures that
  3759. * the descriptor is stable before being published. See comment below. */
  3760. service->next_upload_time =
  3761. now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
  3762. /* Single Onion Services prioritise availability over hiding their
  3763. * startup time, as their IP address is publicly discoverable anyway.
  3764. */
  3765. if (rend_service_reveal_startup_time(options)) {
  3766. service->next_upload_time = now + rendinitialpostdelay;
  3767. }
  3768. }
  3769. /* Does every introduction points have been established? */
  3770. unsigned int intro_points_ready =
  3771. count_established_intro_points(service) >=
  3772. service->n_intro_points_wanted;
  3773. if (intro_points_ready &&
  3774. (service->next_upload_time < now ||
  3775. (service->desc_is_dirty &&
  3776. service->desc_is_dirty < now-rendinitialpostdelay))) {
  3777. /* if it's time, or if the directory servers have a wrong service
  3778. * descriptor and ours has been stable for rendinitialpostdelay seconds,
  3779. * upload a new one of each format. */
  3780. rend_service_update_descriptor(service);
  3781. upload_service_descriptor(service);
  3782. }
  3783. }
  3784. }
  3785. /** True if the list of available router descriptors might have changed so
  3786. * that we should have a look whether we can republish previously failed
  3787. * rendezvous service descriptors. */
  3788. static int consider_republishing_rend_descriptors = 1;
  3789. /** Called when our internal view of the directory has changed, so that we
  3790. * might have router descriptors of hidden service directories available that
  3791. * we did not have before. */
  3792. void
  3793. rend_hsdir_routers_changed(void)
  3794. {
  3795. consider_republishing_rend_descriptors = 1;
  3796. }
  3797. /** Consider republication of v2 rendezvous service descriptors that failed
  3798. * previously, but without regenerating descriptor contents.
  3799. */
  3800. void
  3801. rend_consider_descriptor_republication(void)
  3802. {
  3803. int i;
  3804. rend_service_t *service;
  3805. if (!consider_republishing_rend_descriptors)
  3806. return;
  3807. consider_republishing_rend_descriptors = 0;
  3808. if (!get_options()->PublishHidServDescriptors)
  3809. return;
  3810. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3811. service = smartlist_get(rend_service_list, i);
  3812. if (service->desc && !service->desc->all_uploads_performed) {
  3813. /* If we failed in uploading a descriptor last time, try again *without*
  3814. * updating the descriptor's contents. */
  3815. upload_service_descriptor(service);
  3816. }
  3817. }
  3818. }
  3819. /** Log the status of introduction points for all rendezvous services
  3820. * at log severity <b>severity</b>.
  3821. */
  3822. void
  3823. rend_service_dump_stats(int severity)
  3824. {
  3825. int i,j;
  3826. rend_service_t *service;
  3827. rend_intro_point_t *intro;
  3828. const char *safe_name;
  3829. origin_circuit_t *circ;
  3830. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  3831. service = smartlist_get(rend_service_list, i);
  3832. tor_log(severity, LD_GENERAL, "Service configured in %s:",
  3833. rend_service_escaped_dir(service));
  3834. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  3835. intro = smartlist_get(service->intro_nodes, j);
  3836. safe_name = safe_str_client(intro->extend_info->nickname);
  3837. circ = find_intro_circuit(intro, service->pk_digest);
  3838. if (!circ) {
  3839. tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  3840. j, safe_name);
  3841. continue;
  3842. }
  3843. tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  3844. j, safe_name, circuit_state_to_string(circ->base_.state));
  3845. }
  3846. }
  3847. }
  3848. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  3849. * <b>circ</b>, and look up the port and address based on conn-\>port.
  3850. * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
  3851. * for which the circuit should be closed, -1 on other failure,
  3852. * or 0 for success.
  3853. */
  3854. int
  3855. rend_service_set_connection_addr_port(edge_connection_t *conn,
  3856. origin_circuit_t *circ)
  3857. {
  3858. rend_service_t *service;
  3859. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  3860. const char *rend_pk_digest;
  3861. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  3862. tor_assert(circ->rend_data);
  3863. log_debug(LD_REND,"beginning to hunt for addr/port");
  3864. rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
  3865. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  3866. rend_pk_digest, REND_SERVICE_ID_LEN);
  3867. service = rend_service_get_by_pk_digest(rend_pk_digest);
  3868. if (!service) {
  3869. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  3870. "rendezvous circuit %u; closing.",
  3871. serviceid, (unsigned)circ->base_.n_circ_id);
  3872. return -2;
  3873. }
  3874. if (service->max_streams_per_circuit > 0) {
  3875. /* Enforce the streams-per-circuit limit, and refuse to provide a
  3876. * mapping if this circuit will exceed the limit. */
  3877. #define MAX_STREAM_WARN_INTERVAL 600
  3878. static struct ratelim_t stream_ratelim =
  3879. RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
  3880. if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
  3881. log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
  3882. "Maximum streams per circuit limit reached on rendezvous "
  3883. "circuit %u; %s. Circuit has %d out of %d streams.",
  3884. (unsigned)circ->base_.n_circ_id,
  3885. service->max_streams_close_circuit ?
  3886. "closing circuit" :
  3887. "ignoring open stream request",
  3888. circ->rend_data->nr_streams,
  3889. service->max_streams_per_circuit);
  3890. return service->max_streams_close_circuit ? -2 : -1;
  3891. }
  3892. }
  3893. if (hs_set_conn_addr_port(service->ports, conn) == 0) {
  3894. /* Successfully set the port to the connection. We are done. */
  3895. return 0;
  3896. }
  3897. log_info(LD_REND,
  3898. "No virtual port mapping exists for port %d on service %s",
  3899. conn->base_.port, serviceid);
  3900. if (service->allow_unknown_ports)
  3901. return -1;
  3902. else
  3903. return -2;
  3904. }
  3905. /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
  3906. */
  3907. static int
  3908. rend_service_non_anonymous_mode_consistent(const or_options_t *options)
  3909. {
  3910. /* !! is used to make these options boolean */
  3911. return (!! options->HiddenServiceSingleHopMode ==
  3912. !! options->HiddenServiceNonAnonymousMode);
  3913. }
  3914. /* Do the options allow onion services to make direct (non-anonymous)
  3915. * connections to introduction or rendezvous points?
  3916. * Must only be called after options_validate_single_onion() has successfully
  3917. * checked onion service option consistency.
  3918. * Returns true if tor is in HiddenServiceSingleHopMode. */
  3919. int
  3920. rend_service_allow_non_anonymous_connection(const or_options_t *options)
  3921. {
  3922. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  3923. return options->HiddenServiceSingleHopMode ? 1 : 0;
  3924. }
  3925. /* Do the options allow us to reveal the exact startup time of the onion
  3926. * service?
  3927. * Single Onion Services prioritise availability over hiding their
  3928. * startup time, as their IP address is publicly discoverable anyway.
  3929. * Must only be called after options_validate_single_onion() has successfully
  3930. * checked onion service option consistency.
  3931. * Returns true if tor is in non-anonymous hidden service mode. */
  3932. int
  3933. rend_service_reveal_startup_time(const or_options_t *options)
  3934. {
  3935. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  3936. return rend_service_non_anonymous_mode_enabled(options);
  3937. }
  3938. /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
  3939. * config option?
  3940. * Must only be called after options_validate_single_onion() has successfully
  3941. * checked onion service option consistency.
  3942. */
  3943. int
  3944. rend_service_non_anonymous_mode_enabled(const or_options_t *options)
  3945. {
  3946. tor_assert(rend_service_non_anonymous_mode_consistent(options));
  3947. return options->HiddenServiceNonAnonymousMode ? 1 : 0;
  3948. }
  3949. #ifdef TOR_UNIT_TESTS
  3950. STATIC void
  3951. set_rend_service_list(smartlist_t *new_list)
  3952. {
  3953. rend_service_list = new_list;
  3954. }
  3955. STATIC void
  3956. set_rend_rend_service_staging_list(smartlist_t *new_list)
  3957. {
  3958. rend_service_staging_list = new_list;
  3959. }
  3960. #endif /* defined(TOR_UNIT_TESTS) */