rendservice.c 148 KB

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