rendservice.c 152 KB

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