rendservice.c 144 KB

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