rendservice.c 116 KB

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