rendservice.c 114 KB

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