rendservice.c 133 KB

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