rendservice.c 139 KB

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