rendservice.c 114 KB

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