rendservice.c 150 KB

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