rendservice.c 129 KB

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