rendservice.c 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2011, 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. #include "or.h"
  9. static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
  10. const char *pk_digest,
  11. int desc_version);
  12. /** Represents the mapping from a virtual port of a rendezvous service to
  13. * a real port on some IP.
  14. */
  15. typedef struct rend_service_port_config_t {
  16. uint16_t virtual_port;
  17. uint16_t real_port;
  18. tor_addr_t real_addr;
  19. } rend_service_port_config_t;
  20. /** Try to maintain this many intro points per service if possible. */
  21. #define NUM_INTRO_POINTS 3
  22. /** If we can't build our intro circuits, don't retry for this long. */
  23. #define INTRO_CIRC_RETRY_PERIOD (60*5)
  24. /** Don't try to build more than this many circuits before giving up
  25. * for a while.*/
  26. #define MAX_INTRO_CIRCS_PER_PERIOD 10
  27. /** How many times will a hidden service operator attempt to connect to
  28. * a requested rendezvous point before giving up? */
  29. #define MAX_REND_FAILURES 30
  30. /** How many seconds should we spend trying to connect to a requested
  31. * rendezvous point before giving up? */
  32. #define MAX_REND_TIMEOUT 30
  33. /** Represents a single hidden service running at this OP. */
  34. typedef struct rend_service_t {
  35. /* Fields specified in config file */
  36. char *directory; /**< where in the filesystem it stores it */
  37. smartlist_t *ports; /**< List of rend_service_port_config_t */
  38. int descriptor_version; /**< Rendezvous descriptor version that will be
  39. * published. */
  40. rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
  41. * authorization is performed. */
  42. smartlist_t *clients; /**< List of rend_authorized_client_t's of
  43. * clients that may access our service. Can be NULL
  44. * if no client authorization is performed. */
  45. /* Other fields */
  46. crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
  47. char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
  48. * '.onion' */
  49. char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
  50. smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
  51. * or are trying to establish. */
  52. time_t intro_period_started; /**< Start of the current period to build
  53. * introduction points. */
  54. int n_intro_circuits_launched; /**< count of intro circuits we have
  55. * established in this period. */
  56. rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  57. time_t desc_is_dirty; /**< Time at which changes to the hidden service
  58. * descriptor content occurred, or 0 if it's
  59. * up-to-date. */
  60. time_t next_upload_time; /**< Scheduled next hidden service descriptor
  61. * upload time. */
  62. /** Map from digests of Diffie-Hellman values INTRODUCE2 to time_t of when
  63. * they were received; used to prevent replays. */
  64. digestmap_t *accepted_intros;
  65. /** Time at which we last removed expired values from accepted_intros. */
  66. time_t last_cleaned_accepted_intros;
  67. } rend_service_t;
  68. /** A list of rend_service_t's for services run on this OP.
  69. */
  70. static smartlist_t *rend_service_list = NULL;
  71. /** Return the number of rendezvous services we have configured. */
  72. int
  73. num_rend_services(void)
  74. {
  75. if (!rend_service_list)
  76. return 0;
  77. return smartlist_len(rend_service_list);
  78. }
  79. /** Helper: free storage held by a single service authorized client entry. */
  80. static void
  81. rend_authorized_client_free(rend_authorized_client_t *client)
  82. {
  83. if (!client) return;
  84. if (client->client_key)
  85. crypto_free_pk_env(client->client_key);
  86. tor_free(client->client_name);
  87. tor_free(client);
  88. }
  89. /** Helper for strmap_free. */
  90. static void
  91. rend_authorized_client_strmap_item_free(void *authorized_client)
  92. {
  93. rend_authorized_client_free(authorized_client);
  94. }
  95. /** Release the storage held by <b>service</b>.
  96. */
  97. static void
  98. rend_service_free(rend_service_t *service)
  99. {
  100. if (!service) return;
  101. tor_free(service->directory);
  102. SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  103. smartlist_free(service->ports);
  104. if (service->private_key)
  105. crypto_free_pk_env(service->private_key);
  106. if (service->intro_nodes) {
  107. SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
  108. rend_intro_point_free(intro););
  109. smartlist_free(service->intro_nodes);
  110. }
  111. if (service->desc)
  112. rend_service_descriptor_free(service->desc);
  113. if (service->clients) {
  114. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
  115. rend_authorized_client_free(c););
  116. smartlist_free(service->clients);
  117. }
  118. if (service->accepted_intros)
  119. digestmap_free(service->accepted_intros, _tor_free);
  120. tor_free(service);
  121. }
  122. /** Release all the storage held in rend_service_list.
  123. */
  124. void
  125. rend_service_free_all(void)
  126. {
  127. if (!rend_service_list) {
  128. return;
  129. }
  130. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
  131. rend_service_free(ptr));
  132. smartlist_free(rend_service_list);
  133. rend_service_list = NULL;
  134. }
  135. /** Validate <b>service</b> and add it to rend_service_list if possible.
  136. */
  137. static void
  138. rend_add_service(rend_service_t *service)
  139. {
  140. int i;
  141. rend_service_port_config_t *p;
  142. service->intro_nodes = smartlist_create();
  143. /* If the service is configured to publish unversioned (v0) and versioned
  144. * descriptors (v2 or higher), split it up into two separate services
  145. * (unless it is configured to perform client authorization). */
  146. if (service->descriptor_version == -1) {
  147. if (service->auth_type == REND_NO_AUTH) {
  148. rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
  149. v0_service->directory = tor_strdup(service->directory);
  150. v0_service->ports = smartlist_create();
  151. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
  152. rend_service_port_config_t *copy =
  153. tor_malloc_zero(sizeof(rend_service_port_config_t));
  154. memcpy(copy, p, sizeof(rend_service_port_config_t));
  155. smartlist_add(v0_service->ports, copy);
  156. });
  157. v0_service->intro_period_started = service->intro_period_started;
  158. v0_service->descriptor_version = 0; /* Unversioned descriptor. */
  159. v0_service->auth_type = REND_NO_AUTH;
  160. rend_add_service(v0_service);
  161. }
  162. service->descriptor_version = 2; /* Versioned descriptor. */
  163. }
  164. if (service->auth_type != REND_NO_AUTH && !service->descriptor_version) {
  165. log_warn(LD_CONFIG, "Hidden service with client authorization and "
  166. "version 0 descriptors configured; ignoring.");
  167. rend_service_free(service);
  168. return;
  169. }
  170. if (service->auth_type != REND_NO_AUTH &&
  171. smartlist_len(service->clients) == 0) {
  172. log_warn(LD_CONFIG, "Hidden service with client authorization but no "
  173. "clients; ignoring.");
  174. rend_service_free(service);
  175. return;
  176. }
  177. if (!smartlist_len(service->ports)) {
  178. log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
  179. rend_service_free(service);
  180. } else {
  181. smartlist_add(rend_service_list, service);
  182. log_debug(LD_REND,"Configuring service with directory \"%s\"",
  183. service->directory);
  184. for (i = 0; i < smartlist_len(service->ports); ++i) {
  185. p = smartlist_get(service->ports, i);
  186. log_debug(LD_REND,"Service maps port %d to %s:%d",
  187. p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
  188. }
  189. }
  190. }
  191. /** Parses a real-port to virtual-port mapping and returns a new
  192. * rend_service_port_config_t.
  193. *
  194. * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
  195. *
  196. * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
  197. */
  198. static rend_service_port_config_t *
  199. parse_port_config(const char *string)
  200. {
  201. smartlist_t *sl;
  202. int virtport;
  203. int realport;
  204. uint16_t p;
  205. tor_addr_t addr;
  206. const char *addrport;
  207. rend_service_port_config_t *result = NULL;
  208. sl = smartlist_create();
  209. smartlist_split_string(sl, string, " ",
  210. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  211. if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
  212. log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
  213. goto err;
  214. }
  215. virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  216. if (!virtport) {
  217. log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
  218. "configuration", escaped(smartlist_get(sl,0)));
  219. goto err;
  220. }
  221. if (smartlist_len(sl) == 1) {
  222. /* No addr:port part; use default. */
  223. realport = virtport;
  224. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
  225. } else {
  226. addrport = smartlist_get(sl,1);
  227. if (strchr(addrport, ':') || strchr(addrport, '.')) {
  228. if (tor_addr_port_parse(addrport, &addr, &p)<0) {
  229. log_warn(LD_CONFIG,"Unparseable address in hidden service port "
  230. "configuration.");
  231. goto err;
  232. }
  233. realport = p?p:virtport;
  234. } else {
  235. /* No addr:port, no addr -- must be port. */
  236. realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
  237. if (!realport) {
  238. log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
  239. "service port configuration.", escaped(addrport));
  240. goto err;
  241. }
  242. tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
  243. }
  244. }
  245. result = tor_malloc(sizeof(rend_service_port_config_t));
  246. result->virtual_port = virtport;
  247. result->real_port = realport;
  248. tor_addr_copy(&result->real_addr, &addr);
  249. err:
  250. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  251. smartlist_free(sl);
  252. return result;
  253. }
  254. /** Set up rend_service_list, based on the values of HiddenServiceDir and
  255. * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
  256. * failure. (If <b>validate_only</b> is set, parse, warn and return as
  257. * normal, but don't actually change the configured services.)
  258. */
  259. int
  260. rend_config_services(or_options_t *options, int validate_only)
  261. {
  262. config_line_t *line;
  263. rend_service_t *service = NULL;
  264. rend_service_port_config_t *portcfg;
  265. smartlist_t *old_service_list = NULL;
  266. if (!validate_only) {
  267. old_service_list = rend_service_list;
  268. rend_service_list = smartlist_create();
  269. }
  270. for (line = options->RendConfigLines; line; line = line->next) {
  271. if (!strcasecmp(line->key, "HiddenServiceDir")) {
  272. if (service) {
  273. if (validate_only)
  274. rend_service_free(service);
  275. else
  276. rend_add_service(service);
  277. }
  278. service = tor_malloc_zero(sizeof(rend_service_t));
  279. service->directory = tor_strdup(line->value);
  280. service->ports = smartlist_create();
  281. service->intro_period_started = time(NULL);
  282. service->descriptor_version = -1; /**< All descriptor versions. */
  283. continue;
  284. }
  285. if (!service) {
  286. log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
  287. line->key);
  288. rend_service_free(service);
  289. return -1;
  290. }
  291. if (!strcasecmp(line->key, "HiddenServicePort")) {
  292. portcfg = parse_port_config(line->value);
  293. if (!portcfg) {
  294. rend_service_free(service);
  295. return -1;
  296. }
  297. smartlist_add(service->ports, portcfg);
  298. } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
  299. /* Parse auth type and comma-separated list of client names and add a
  300. * rend_authorized_client_t for each client to the service's list
  301. * of authorized clients. */
  302. smartlist_t *type_names_split, *clients;
  303. const char *authname;
  304. int num_clients;
  305. if (service->auth_type != REND_NO_AUTH) {
  306. log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
  307. "lines for a single service.");
  308. rend_service_free(service);
  309. return -1;
  310. }
  311. type_names_split = smartlist_create();
  312. smartlist_split_string(type_names_split, line->value, " ", 0, 2);
  313. if (smartlist_len(type_names_split) < 1) {
  314. log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
  315. "should have been prevented when parsing the "
  316. "configuration.");
  317. smartlist_free(type_names_split);
  318. rend_service_free(service);
  319. return -1;
  320. }
  321. authname = smartlist_get(type_names_split, 0);
  322. if (!strcasecmp(authname, "basic")) {
  323. service->auth_type = REND_BASIC_AUTH;
  324. } else if (!strcasecmp(authname, "stealth")) {
  325. service->auth_type = REND_STEALTH_AUTH;
  326. } else {
  327. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  328. "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
  329. "are recognized.",
  330. (char *) smartlist_get(type_names_split, 0));
  331. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  332. smartlist_free(type_names_split);
  333. rend_service_free(service);
  334. return -1;
  335. }
  336. service->clients = smartlist_create();
  337. if (smartlist_len(type_names_split) < 2) {
  338. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
  339. "auth-type '%s', but no client names.",
  340. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  341. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  342. smartlist_free(type_names_split);
  343. continue;
  344. }
  345. clients = smartlist_create();
  346. smartlist_split_string(clients, smartlist_get(type_names_split, 1),
  347. ",", SPLIT_SKIP_SPACE, 0);
  348. SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
  349. smartlist_free(type_names_split);
  350. /* Remove duplicate client names. */
  351. num_clients = smartlist_len(clients);
  352. smartlist_sort_strings(clients);
  353. smartlist_uniq_strings(clients);
  354. if (smartlist_len(clients) < num_clients) {
  355. log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  356. "duplicate client name(s); removing.",
  357. num_clients - smartlist_len(clients));
  358. num_clients = smartlist_len(clients);
  359. }
  360. SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
  361. {
  362. rend_authorized_client_t *client;
  363. size_t len = strlen(client_name);
  364. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  365. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  366. "illegal client name: '%s'. Length must be "
  367. "between 1 and %d characters.",
  368. client_name, REND_CLIENTNAME_MAX_LEN);
  369. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  370. smartlist_free(clients);
  371. rend_service_free(service);
  372. return -1;
  373. }
  374. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  375. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
  376. "illegal client name: '%s'. Valid "
  377. "characters are [A-Za-z0-9+-_].",
  378. client_name);
  379. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  380. smartlist_free(clients);
  381. rend_service_free(service);
  382. return -1;
  383. }
  384. client = tor_malloc_zero(sizeof(rend_authorized_client_t));
  385. client->client_name = tor_strdup(client_name);
  386. smartlist_add(service->clients, client);
  387. log_debug(LD_REND, "Adding client name '%s'", client_name);
  388. }
  389. SMARTLIST_FOREACH_END(client_name);
  390. SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
  391. smartlist_free(clients);
  392. /* Ensure maximum number of clients. */
  393. if ((service->auth_type == REND_BASIC_AUTH &&
  394. smartlist_len(service->clients) > 512) ||
  395. (service->auth_type == REND_STEALTH_AUTH &&
  396. smartlist_len(service->clients) > 16)) {
  397. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
  398. "client authorization entries, but only a "
  399. "maximum of %d entries is allowed for "
  400. "authorization type '%s'.",
  401. smartlist_len(service->clients),
  402. service->auth_type == REND_BASIC_AUTH ? 512 : 16,
  403. service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
  404. rend_service_free(service);
  405. return -1;
  406. }
  407. } else {
  408. smartlist_t *versions;
  409. char *version_str;
  410. int i, version, ver_ok=1, versions_bitmask = 0;
  411. tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
  412. versions = smartlist_create();
  413. smartlist_split_string(versions, line->value, ",",
  414. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  415. for (i = 0; i < smartlist_len(versions); i++) {
  416. version_str = smartlist_get(versions, i);
  417. if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
  418. log_warn(LD_CONFIG,
  419. "HiddenServiceVersion can only be 0 and/or 2.");
  420. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  421. smartlist_free(versions);
  422. rend_service_free(service);
  423. return -1;
  424. }
  425. version = (int)tor_parse_long(version_str, 10, 0, INT_MAX, &ver_ok,
  426. NULL);
  427. if (!ver_ok)
  428. continue;
  429. versions_bitmask |= 1 << version;
  430. }
  431. /* If exactly one version is set, change descriptor_version to that
  432. * value; otherwise leave it at -1. */
  433. if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
  434. if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
  435. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  436. smartlist_free(versions);
  437. }
  438. }
  439. if (service) {
  440. if (validate_only)
  441. rend_service_free(service);
  442. else
  443. rend_add_service(service);
  444. }
  445. /* If this is a reload and there were hidden services configured before,
  446. * keep the introduction points that are still needed and close the
  447. * other ones. */
  448. if (old_service_list && !validate_only) {
  449. smartlist_t *surviving_services = smartlist_create();
  450. circuit_t *circ;
  451. /* Copy introduction points to new services. */
  452. /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
  453. * probably ok? */
  454. SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
  455. SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
  456. if (!strcmp(old->directory, new->directory) &&
  457. old->descriptor_version == new->descriptor_version) {
  458. smartlist_add_all(new->intro_nodes, old->intro_nodes);
  459. smartlist_clear(old->intro_nodes);
  460. smartlist_add(surviving_services, old);
  461. break;
  462. }
  463. });
  464. });
  465. /* Close introduction circuits of services we don't serve anymore. */
  466. /* XXXX it would be nicer if we had a nicer abstraction to use here,
  467. * so we could just iterate over the list of services to close, but
  468. * once again, this isn't critical-path code. */
  469. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  470. if (!circ->marked_for_close &&
  471. circ->state == CIRCUIT_STATE_OPEN &&
  472. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  473. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  474. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  475. int keep_it = 0;
  476. tor_assert(oc->rend_data);
  477. SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
  478. if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
  479. DIGEST_LEN) &&
  480. ptr->descriptor_version == oc->rend_data->rend_desc_version) {
  481. keep_it = 1;
  482. break;
  483. }
  484. });
  485. if (keep_it)
  486. continue;
  487. log_info(LD_REND, "Closing intro point %s for service %s version %d.",
  488. safe_str(oc->build_state->chosen_exit->nickname),
  489. oc->rend_data->onion_address,
  490. oc->rend_data->rend_desc_version);
  491. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  492. /* XXXX Is there another reason we should use here? */
  493. }
  494. }
  495. smartlist_free(surviving_services);
  496. SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
  497. rend_service_free(ptr));
  498. smartlist_free(old_service_list);
  499. }
  500. return 0;
  501. }
  502. /** Replace the old value of <b>service</b>-\>desc with one that reflects
  503. * the other fields in service.
  504. */
  505. static void
  506. rend_service_update_descriptor(rend_service_t *service)
  507. {
  508. rend_service_descriptor_t *d;
  509. origin_circuit_t *circ;
  510. int i;
  511. if (service->desc) {
  512. rend_service_descriptor_free(service->desc);
  513. service->desc = NULL;
  514. }
  515. d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  516. d->pk = crypto_pk_dup_key(service->private_key);
  517. d->timestamp = time(NULL);
  518. d->version = service->descriptor_version;
  519. d->intro_nodes = smartlist_create();
  520. /* Support intro protocols 2 and 3. */
  521. d->protocols = (1 << 2) + (1 << 3);
  522. for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
  523. rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
  524. rend_intro_point_t *intro_desc;
  525. circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
  526. if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
  527. continue;
  528. /* We have an entirely established intro circuit. */
  529. intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
  530. intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
  531. if (intro_svc->intro_key)
  532. intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
  533. smartlist_add(d->intro_nodes, intro_desc);
  534. }
  535. }
  536. /** Load and/or generate private keys for all hidden services, possibly
  537. * including keys for client authorization. Return 0 on success, -1 on
  538. * failure.
  539. */
  540. int
  541. rend_service_load_keys(void)
  542. {
  543. int r = 0;
  544. char fname[512];
  545. char buf[1500];
  546. SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
  547. if (s->private_key)
  548. continue;
  549. log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
  550. s->directory);
  551. /* Check/create directory */
  552. if (check_private_dir(s->directory, CPD_CREATE) < 0)
  553. return -1;
  554. /* Load key */
  555. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  556. strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
  557. >= sizeof(fname)) {
  558. log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
  559. s->directory);
  560. return -1;
  561. }
  562. s->private_key = init_key_from_file(fname, 1, LOG_ERR);
  563. if (!s->private_key)
  564. return -1;
  565. /* Create service file */
  566. if (rend_get_service_id(s->private_key, s->service_id)<0) {
  567. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  568. return -1;
  569. }
  570. if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
  571. log_warn(LD_BUG, "Couldn't compute hash of public key.");
  572. return -1;
  573. }
  574. if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
  575. strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
  576. >= sizeof(fname)) {
  577. log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
  578. " \"%s\".", s->directory);
  579. return -1;
  580. }
  581. tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
  582. if (write_str_to_file(fname,buf,0)<0) {
  583. log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
  584. return -1;
  585. }
  586. /* If client authorization is configured, load or generate keys. */
  587. if (s->auth_type != REND_NO_AUTH) {
  588. char *client_keys_str = NULL;
  589. strmap_t *parsed_clients = strmap_new();
  590. char cfname[512];
  591. FILE *cfile, *hfile;
  592. open_file_t *open_cfile = NULL, *open_hfile = NULL;
  593. /* Load client keys and descriptor cookies, if available. */
  594. if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
  595. s->directory)<0) {
  596. log_warn(LD_CONFIG, "Directory name too long to store client keys "
  597. "file: \"%s\".", s->directory);
  598. goto err;
  599. }
  600. client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
  601. if (client_keys_str) {
  602. if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
  603. log_warn(LD_CONFIG, "Previously stored client_keys file could not "
  604. "be parsed.");
  605. goto err;
  606. } else {
  607. log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
  608. strmap_size(parsed_clients));
  609. tor_free(client_keys_str);
  610. }
  611. }
  612. /* Prepare client_keys and hostname files. */
  613. if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
  614. 0600, &open_cfile))) {
  615. log_warn(LD_CONFIG, "Could not open client_keys file %s",
  616. escaped(cfname));
  617. goto err;
  618. }
  619. if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
  620. 0600, &open_hfile))) {
  621. log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
  622. goto err;
  623. }
  624. /* Either use loaded keys for configured clients or generate new
  625. * ones if a client is new. */
  626. SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
  627. {
  628. char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
  629. char service_id[16+1];
  630. rend_authorized_client_t *parsed =
  631. strmap_get(parsed_clients, client->client_name);
  632. int written;
  633. size_t len;
  634. /* Copy descriptor cookie from parsed entry or create new one. */
  635. if (parsed) {
  636. memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
  637. REND_DESC_COOKIE_LEN);
  638. } else {
  639. crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  640. }
  641. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  642. client->descriptor_cookie,
  643. REND_DESC_COOKIE_LEN) < 0) {
  644. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  645. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  646. return -1;
  647. }
  648. /* Copy client key from parsed entry or create new one if required. */
  649. if (parsed && parsed->client_key) {
  650. client->client_key = crypto_pk_dup_key(parsed->client_key);
  651. } else if (s->auth_type == REND_STEALTH_AUTH) {
  652. /* Create private key for client. */
  653. crypto_pk_env_t *prkey = NULL;
  654. if (!(prkey = crypto_new_pk_env())) {
  655. log_warn(LD_BUG,"Error constructing client key");
  656. goto err;
  657. }
  658. if (crypto_pk_generate_key(prkey)) {
  659. log_warn(LD_BUG,"Error generating client key");
  660. crypto_free_pk_env(prkey);
  661. goto err;
  662. }
  663. if (crypto_pk_check_key(prkey) <= 0) {
  664. log_warn(LD_BUG,"Generated client key seems invalid");
  665. crypto_free_pk_env(prkey);
  666. goto err;
  667. }
  668. client->client_key = prkey;
  669. }
  670. /* Add entry to client_keys file. */
  671. desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
  672. written = tor_snprintf(buf, sizeof(buf),
  673. "client-name %s\ndescriptor-cookie %s\n",
  674. client->client_name, desc_cook_out);
  675. if (written < 0) {
  676. log_warn(LD_BUG, "Could not write client entry.");
  677. goto err;
  678. }
  679. if (client->client_key) {
  680. char *client_key_out = NULL;
  681. crypto_pk_write_private_key_to_string(client->client_key,
  682. &client_key_out, &len);
  683. if (rend_get_service_id(client->client_key, service_id)<0) {
  684. log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
  685. tor_free(client_key_out);
  686. goto err;
  687. }
  688. written = tor_snprintf(buf + written, sizeof(buf) - written,
  689. "client-key\n%s", client_key_out);
  690. tor_free(client_key_out);
  691. if (written < 0) {
  692. log_warn(LD_BUG, "Could not write client entry.");
  693. goto err;
  694. }
  695. }
  696. if (fputs(buf, cfile) < 0) {
  697. log_warn(LD_FS, "Could not append client entry to file: %s",
  698. strerror(errno));
  699. goto err;
  700. }
  701. /* Add line to hostname file. */
  702. if (s->auth_type == REND_BASIC_AUTH) {
  703. /* Remove == signs (newline has been removed above). */
  704. desc_cook_out[strlen(desc_cook_out)-2] = '\0';
  705. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  706. s->service_id, desc_cook_out, client->client_name);
  707. } else {
  708. char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
  709. memcpy(extended_desc_cookie, client->descriptor_cookie,
  710. REND_DESC_COOKIE_LEN);
  711. extended_desc_cookie[REND_DESC_COOKIE_LEN] =
  712. ((int)s->auth_type - 1) << 4;
  713. if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
  714. extended_desc_cookie,
  715. REND_DESC_COOKIE_LEN+1) < 0) {
  716. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  717. goto err;
  718. }
  719. desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
  720. newline. */
  721. tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
  722. service_id, desc_cook_out, client->client_name);
  723. }
  724. if (fputs(buf, hfile)<0) {
  725. log_warn(LD_FS, "Could not append host entry to file: %s",
  726. strerror(errno));
  727. goto err;
  728. }
  729. }
  730. SMARTLIST_FOREACH_END(client);
  731. goto done;
  732. err:
  733. r = -1;
  734. done:
  735. tor_free(client_keys_str);
  736. strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
  737. if (r<0) {
  738. if (open_cfile)
  739. abort_writing_to_file(open_cfile);
  740. if (open_hfile)
  741. abort_writing_to_file(open_hfile);
  742. return r;
  743. } else {
  744. finish_writing_to_file(open_cfile);
  745. finish_writing_to_file(open_hfile);
  746. }
  747. }
  748. } SMARTLIST_FOREACH_END(s);
  749. return r;
  750. }
  751. /** Return the service whose public key has a digest of <b>digest</b> and
  752. * which publishes the given descriptor <b>version</b>. Return NULL if no
  753. * such service exists.
  754. */
  755. static rend_service_t *
  756. rend_service_get_by_pk_digest_and_version(const char* digest,
  757. uint8_t version)
  758. {
  759. SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
  760. if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
  761. s->descriptor_version == version) return s);
  762. return NULL;
  763. }
  764. /** Return 1 if any virtual port in <b>service</b> wants a circuit
  765. * to have good uptime. Else return 0.
  766. */
  767. static int
  768. rend_service_requires_uptime(rend_service_t *service)
  769. {
  770. int i;
  771. rend_service_port_config_t *p;
  772. for (i=0; i < smartlist_len(service->ports); ++i) {
  773. p = smartlist_get(service->ports, i);
  774. if (smartlist_string_num_isin(get_options()->LongLivedPorts,
  775. p->virtual_port))
  776. return 1;
  777. }
  778. return 0;
  779. }
  780. /** Check client authorization of a given <b>descriptor_cookie</b> for
  781. * <b>service</b>. Return 1 for success and 0 for failure. */
  782. static int
  783. rend_check_authorization(rend_service_t *service,
  784. const char *descriptor_cookie)
  785. {
  786. rend_authorized_client_t *auth_client = NULL;
  787. tor_assert(service);
  788. tor_assert(descriptor_cookie);
  789. if (!service->clients) {
  790. log_warn(LD_BUG, "Can't check authorization for a service that has no "
  791. "authorized clients configured.");
  792. return 0;
  793. }
  794. /* Look up client authorization by descriptor cookie. */
  795. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
  796. if (!memcmp(client->descriptor_cookie, descriptor_cookie,
  797. REND_DESC_COOKIE_LEN)) {
  798. auth_client = client;
  799. break;
  800. }
  801. });
  802. if (!auth_client) {
  803. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  804. base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
  805. descriptor_cookie, REND_DESC_COOKIE_LEN);
  806. log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
  807. "Dropping cell!",
  808. descriptor_cookie_base64);
  809. return 0;
  810. }
  811. /* Allow the request. */
  812. log_debug(LD_REND, "Client %s authorized for service %s.",
  813. auth_client->client_name, service->service_id);
  814. return 1;
  815. }
  816. /** Remove elements from <b>service</b>'s replay cache that are old enough to
  817. * be noticed by timestamp checking. */
  818. static void
  819. clean_accepted_intros(rend_service_t *service, time_t now)
  820. {
  821. const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
  822. service->last_cleaned_accepted_intros = now;
  823. if (!service->accepted_intros)
  824. return;
  825. DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
  826. if (*t < cutoff) {
  827. tor_free(t);
  828. MAP_DEL_CURRENT(digest);
  829. }
  830. } DIGESTMAP_FOREACH_END;
  831. }
  832. /******
  833. * Handle cells
  834. ******/
  835. /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
  836. * rendezvous point.
  837. */
  838. int
  839. rend_service_introduce(origin_circuit_t *circuit, const uint8_t *request,
  840. size_t request_len)
  841. {
  842. char *ptr, *r_cookie;
  843. extend_info_t *extend_info = NULL;
  844. char buf[RELAY_PAYLOAD_SIZE];
  845. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
  846. rend_service_t *service;
  847. int r, i, v3_shift = 0;
  848. size_t len, keylen;
  849. crypto_dh_env_t *dh = NULL;
  850. origin_circuit_t *launched = NULL;
  851. crypt_path_t *cpath = NULL;
  852. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  853. char hexcookie[9];
  854. int circ_needs_uptime;
  855. int reason = END_CIRC_REASON_TORPROTOCOL;
  856. crypto_pk_env_t *intro_key;
  857. char intro_key_digest[DIGEST_LEN];
  858. int auth_type;
  859. size_t auth_len = 0;
  860. char auth_data[REND_DESC_COOKIE_LEN];
  861. crypto_digest_env_t *digest = NULL;
  862. time_t now = time(NULL);
  863. char diffie_hellman_hash[DIGEST_LEN];
  864. time_t *access_time;
  865. tor_assert(circuit->rend_data);
  866. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  867. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  868. log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
  869. escaped(serviceid), circuit->_base.n_circ_id);
  870. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
  871. log_warn(LD_PROTOCOL,
  872. "Got an INTRODUCE2 over a non-introduction circuit %d.",
  873. circuit->_base.n_circ_id);
  874. return -1;
  875. }
  876. /* min key length plus digest length plus nickname length */
  877. if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
  878. DH_KEY_LEN+42) {
  879. log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
  880. circuit->_base.n_circ_id);
  881. return -1;
  882. }
  883. /* look up service depending on circuit. */
  884. service = rend_service_get_by_pk_digest_and_version(
  885. circuit->rend_data->rend_pk_digest,
  886. circuit->rend_data->rend_desc_version);
  887. if (!service) {
  888. log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
  889. escaped(serviceid));
  890. return -1;
  891. }
  892. /* if descriptor version is 2, use intro key instead of service key. */
  893. if (circuit->rend_data->rend_desc_version == 0) {
  894. intro_key = service->private_key;
  895. } else {
  896. intro_key = circuit->intro_key;
  897. }
  898. /* first DIGEST_LEN bytes of request is intro or service pk digest */
  899. crypto_pk_get_digest(intro_key, intro_key_digest);
  900. if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
  901. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  902. (char*)request, REND_SERVICE_ID_LEN);
  903. log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
  904. escaped(serviceid));
  905. return -1;
  906. }
  907. keylen = crypto_pk_keysize(intro_key);
  908. if (request_len < keylen+DIGEST_LEN) {
  909. log_warn(LD_PROTOCOL,
  910. "PK-encrypted portion of INTRODUCE2 cell was truncated.");
  911. return -1;
  912. }
  913. /* Next N bytes is encrypted with service key */
  914. note_crypto_pk_op(REND_SERVER);
  915. r = crypto_pk_private_hybrid_decrypt(
  916. intro_key,buf,(char*)(request+DIGEST_LEN),request_len-DIGEST_LEN,
  917. PK_PKCS1_OAEP_PADDING,1);
  918. if (r<0) {
  919. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  920. return -1;
  921. }
  922. len = r;
  923. if (*buf == 3) {
  924. /* Version 3 INTRODUCE2 cell. */
  925. time_t ts = 0, now = time(NULL);
  926. v3_shift = 1;
  927. auth_type = buf[1];
  928. switch (auth_type) {
  929. case REND_BASIC_AUTH:
  930. /* fall through */
  931. case REND_STEALTH_AUTH:
  932. auth_len = ntohs(get_uint16(buf+2));
  933. if (auth_len != REND_DESC_COOKIE_LEN) {
  934. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  935. (int)auth_len, REND_DESC_COOKIE_LEN);
  936. return -1;
  937. }
  938. memcpy(auth_data, buf+4, sizeof(auth_data));
  939. v3_shift += 2+REND_DESC_COOKIE_LEN;
  940. break;
  941. case REND_NO_AUTH:
  942. break;
  943. default:
  944. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  945. }
  946. /* Check timestamp. */
  947. ts = ntohl(get_uint32(buf+1+v3_shift));
  948. v3_shift += 4;
  949. if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
  950. (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
  951. log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
  952. (now - ts) < 0 ? "old" : "new");
  953. return -1;
  954. }
  955. }
  956. if (*buf == 2 || *buf == 3) {
  957. /* Version 2 INTRODUCE2 cell. */
  958. int klen;
  959. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  960. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  961. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  962. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  963. DIGEST_LEN);
  964. extend_info->nickname[0] = '$';
  965. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  966. extend_info->identity_digest, DIGEST_LEN);
  967. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  968. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  969. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  970. (int)len, *buf);
  971. reason = END_CIRC_REASON_TORPROTOCOL;
  972. goto err;
  973. }
  974. extend_info->onion_key =
  975. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  976. if (!extend_info->onion_key) {
  977. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  978. "INTRODUCE2 cell.", *buf);
  979. reason = END_CIRC_REASON_TORPROTOCOL;
  980. goto err;
  981. }
  982. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  983. len -= v3_shift+7+DIGEST_LEN+2+klen;
  984. } else {
  985. char *rp_nickname;
  986. size_t nickname_field_len;
  987. routerinfo_t *router;
  988. int version;
  989. if (*buf == 1) {
  990. rp_nickname = buf+1;
  991. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  992. version = 1;
  993. } else {
  994. nickname_field_len = MAX_NICKNAME_LEN+1;
  995. rp_nickname = buf;
  996. version = 0;
  997. }
  998. ptr=memchr(rp_nickname,0,nickname_field_len);
  999. if (!ptr || ptr == rp_nickname) {
  1000. log_warn(LD_PROTOCOL,
  1001. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  1002. return -1;
  1003. }
  1004. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  1005. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  1006. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  1007. return -1;
  1008. }
  1009. /* Okay, now we know that a nickname is at the start of the buffer. */
  1010. ptr = rp_nickname+nickname_field_len;
  1011. len -= nickname_field_len;
  1012. len -= rp_nickname - buf; /* also remove header space used by version, if
  1013. * any */
  1014. router = router_get_by_nickname(rp_nickname, 0);
  1015. if (!router) {
  1016. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  1017. escaped_safe_str(rp_nickname));
  1018. /* XXXX Add a no-such-router reason? */
  1019. reason = END_CIRC_REASON_TORPROTOCOL;
  1020. goto err;
  1021. }
  1022. extend_info = extend_info_from_router(router);
  1023. }
  1024. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  1025. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  1026. reason = END_CIRC_REASON_TORPROTOCOL;
  1027. goto err;
  1028. }
  1029. r_cookie = ptr;
  1030. base16_encode(hexcookie,9,r_cookie,4);
  1031. /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
  1032. digest = crypto_new_digest_env();
  1033. crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
  1034. crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
  1035. crypto_free_digest_env(digest);
  1036. /* Check whether there is a past request with the same Diffie-Hellman,
  1037. * part 1. */
  1038. if (!service->accepted_intros)
  1039. service->accepted_intros = digestmap_new();
  1040. access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
  1041. if (access_time != NULL) {
  1042. log_warn(LD_REND, "Possible replay detected! We received an "
  1043. "INTRODUCE2 cell with same first part of "
  1044. "Diffie-Hellman handshake %d seconds ago. Dropping "
  1045. "cell.",
  1046. (int) (now - *access_time));
  1047. goto err;
  1048. }
  1049. /* Add request to access history, including time and hash of Diffie-Hellman,
  1050. * part 1, and possibly remove requests from the history that are older than
  1051. * one hour. */
  1052. access_time = tor_malloc(sizeof(time_t));
  1053. *access_time = now;
  1054. digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
  1055. if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
  1056. clean_accepted_intros(service, now);
  1057. /* If the service performs client authorization, check included auth data. */
  1058. if (service->clients) {
  1059. if (auth_len > 0) {
  1060. if (rend_check_authorization(service, auth_data)) {
  1061. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1062. } else {
  1063. log_info(LD_REND, "The authorization data that are contained in "
  1064. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1065. reason = END_CIRC_REASON_CONNECTFAILED;
  1066. goto err;
  1067. }
  1068. } else {
  1069. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1070. "data, but we require client authorization. Dropping cell.");
  1071. reason = END_CIRC_REASON_CONNECTFAILED;
  1072. goto err;
  1073. }
  1074. }
  1075. /* Try DH handshake... */
  1076. dh = crypto_dh_new();
  1077. if (!dh || crypto_dh_generate_public(dh)<0) {
  1078. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1079. "or generate public key.");
  1080. reason = END_CIRC_REASON_INTERNAL;
  1081. goto err;
  1082. }
  1083. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  1084. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1085. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1086. reason = END_CIRC_REASON_INTERNAL;
  1087. goto err;
  1088. }
  1089. circ_needs_uptime = rend_service_requires_uptime(service);
  1090. /* help predict this next time */
  1091. rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
  1092. /* Launch a circuit to alice's chosen rendezvous point.
  1093. */
  1094. for (i=0;i<MAX_REND_FAILURES;i++) {
  1095. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1096. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1097. launched = circuit_launch_by_extend_info(
  1098. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1099. if (launched)
  1100. break;
  1101. }
  1102. if (!launched) { /* give up */
  1103. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1104. "point %s for service %s.",
  1105. escaped_safe_str(extend_info->nickname), serviceid);
  1106. reason = END_CIRC_REASON_CONNECTFAILED;
  1107. goto err;
  1108. }
  1109. log_info(LD_REND,
  1110. "Accepted intro; launching circuit to %s "
  1111. "(cookie %s) for service %s.",
  1112. escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
  1113. tor_assert(launched->build_state);
  1114. /* Fill in the circuit's state. */
  1115. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1116. memcpy(launched->rend_data->rend_pk_digest,
  1117. circuit->rend_data->rend_pk_digest,
  1118. DIGEST_LEN);
  1119. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1120. strlcpy(launched->rend_data->onion_address, service->service_id,
  1121. sizeof(launched->rend_data->onion_address));
  1122. launched->rend_data->rend_desc_version = service->descriptor_version;
  1123. launched->build_state->pending_final_cpath = cpath =
  1124. tor_malloc_zero(sizeof(crypt_path_t));
  1125. cpath->magic = CRYPT_PATH_MAGIC;
  1126. launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
  1127. cpath->dh_handshake_state = dh;
  1128. dh = NULL;
  1129. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1130. goto err;
  1131. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1132. if (extend_info) extend_info_free(extend_info);
  1133. return 0;
  1134. err:
  1135. if (dh) crypto_dh_free(dh);
  1136. if (launched)
  1137. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1138. if (extend_info) extend_info_free(extend_info);
  1139. return -1;
  1140. }
  1141. /** Called when we fail building a rendezvous circuit at some point other
  1142. * than the last hop: launches a new circuit to the same rendezvous point.
  1143. */
  1144. void
  1145. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1146. {
  1147. origin_circuit_t *newcirc;
  1148. cpath_build_state_t *newstate, *oldstate;
  1149. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1150. if (!oldcirc->build_state ||
  1151. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1152. oldcirc->build_state->expiry_time < time(NULL)) {
  1153. log_info(LD_REND,
  1154. "Attempt to build circuit to %s for rendezvous has failed "
  1155. "too many times or expired; giving up.",
  1156. oldcirc->build_state ?
  1157. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  1158. return;
  1159. }
  1160. oldstate = oldcirc->build_state;
  1161. tor_assert(oldstate);
  1162. if (oldstate->pending_final_cpath == NULL) {
  1163. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1164. "Initiator will retry.");
  1165. return;
  1166. }
  1167. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1168. oldstate->chosen_exit->nickname);
  1169. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1170. oldstate->chosen_exit,
  1171. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1172. if (!newcirc) {
  1173. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1174. oldstate->chosen_exit->nickname);
  1175. return;
  1176. }
  1177. newstate = newcirc->build_state;
  1178. tor_assert(newstate);
  1179. newstate->failure_count = oldstate->failure_count+1;
  1180. newstate->expiry_time = oldstate->expiry_time;
  1181. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  1182. oldstate->pending_final_cpath = NULL;
  1183. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1184. }
  1185. /** Launch a circuit to serve as an introduction point for the service
  1186. * <b>service</b> at the introduction point <b>nickname</b>
  1187. */
  1188. static int
  1189. rend_service_launch_establish_intro(rend_service_t *service,
  1190. rend_intro_point_t *intro)
  1191. {
  1192. origin_circuit_t *launched;
  1193. log_info(LD_REND,
  1194. "Launching circuit to introduction point %s for service %s",
  1195. escaped_safe_str(intro->extend_info->nickname),
  1196. service->service_id);
  1197. rep_hist_note_used_internal(time(NULL), 1, 0);
  1198. ++service->n_intro_circuits_launched;
  1199. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1200. intro->extend_info,
  1201. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1202. if (!launched) {
  1203. log_info(LD_REND,
  1204. "Can't launch circuit to establish introduction at %s.",
  1205. escaped_safe_str(intro->extend_info->nickname));
  1206. return -1;
  1207. }
  1208. if (memcmp(intro->extend_info->identity_digest,
  1209. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1210. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1211. base16_encode(cann, sizeof(cann),
  1212. launched->build_state->chosen_exit->identity_digest,
  1213. DIGEST_LEN);
  1214. base16_encode(orig, sizeof(orig),
  1215. intro->extend_info->identity_digest, DIGEST_LEN);
  1216. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1217. "but we requested an intro circuit to $%s. Updating "
  1218. "our service.", cann, orig);
  1219. extend_info_free(intro->extend_info);
  1220. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1221. }
  1222. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1223. strlcpy(launched->rend_data->onion_address, service->service_id,
  1224. sizeof(launched->rend_data->onion_address));
  1225. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1226. launched->rend_data->rend_desc_version = service->descriptor_version;
  1227. if (service->descriptor_version == 2)
  1228. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1229. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1230. rend_service_intro_has_opened(launched);
  1231. return 0;
  1232. }
  1233. /** Return the number of introduction points that are or have been
  1234. * established for the given service address and rendezvous version. */
  1235. static int
  1236. count_established_intro_points(const char *query, int rend_version)
  1237. {
  1238. int num_ipos = 0;
  1239. circuit_t *circ;
  1240. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1241. if (!circ->marked_for_close &&
  1242. circ->state == CIRCUIT_STATE_OPEN &&
  1243. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1244. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1245. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1246. if (oc->rend_data &&
  1247. oc->rend_data->rend_desc_version == rend_version &&
  1248. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1249. num_ipos++;
  1250. }
  1251. }
  1252. return num_ipos;
  1253. }
  1254. /** Called when we're done building a circuit to an introduction point:
  1255. * sends a RELAY_ESTABLISH_INTRO cell.
  1256. */
  1257. void
  1258. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1259. {
  1260. rend_service_t *service;
  1261. size_t len;
  1262. int r;
  1263. char buf[RELAY_PAYLOAD_SIZE];
  1264. char auth[DIGEST_LEN + 9];
  1265. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1266. int reason = END_CIRC_REASON_TORPROTOCOL;
  1267. crypto_pk_env_t *intro_key;
  1268. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1269. tor_assert(circuit->cpath);
  1270. tor_assert(circuit->rend_data);
  1271. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1272. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1273. service = rend_service_get_by_pk_digest_and_version(
  1274. circuit->rend_data->rend_pk_digest,
  1275. circuit->rend_data->rend_desc_version);
  1276. if (!service) {
  1277. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1278. serviceid, circuit->_base.n_circ_id);
  1279. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1280. goto err;
  1281. }
  1282. /* If we already have enough introduction circuits for this service,
  1283. * redefine this one as a general circuit. */
  1284. if (count_established_intro_points(serviceid,
  1285. circuit->rend_data->rend_desc_version) > NUM_INTRO_POINTS) {
  1286. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1287. "circuit, but we already have enough. Redefining purpose to "
  1288. "general.");
  1289. TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1290. circuit_has_opened(circuit);
  1291. return;
  1292. }
  1293. log_info(LD_REND,
  1294. "Established circuit %d as introduction point for service %s",
  1295. circuit->_base.n_circ_id, serviceid);
  1296. /* If the introduction point will not be used in an unversioned
  1297. * descriptor, use the intro key instead of the service key in
  1298. * ESTABLISH_INTRO. */
  1299. if (service->descriptor_version == 0)
  1300. intro_key = service->private_key;
  1301. else
  1302. intro_key = circuit->intro_key;
  1303. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1304. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1305. RELAY_PAYLOAD_SIZE-2);
  1306. if (r < 0) {
  1307. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1308. reason = END_CIRC_REASON_INTERNAL;
  1309. goto err;
  1310. }
  1311. len = r;
  1312. set_uint16(buf, htons((uint16_t)len));
  1313. len += 2;
  1314. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1315. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1316. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1317. goto err;
  1318. len += 20;
  1319. note_crypto_pk_op(REND_SERVER);
  1320. r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
  1321. if (r<0) {
  1322. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1323. reason = END_CIRC_REASON_INTERNAL;
  1324. goto err;
  1325. }
  1326. len += r;
  1327. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1328. RELAY_COMMAND_ESTABLISH_INTRO,
  1329. buf, len, circuit->cpath->prev)<0) {
  1330. log_info(LD_GENERAL,
  1331. "Couldn't send introduction request for service %s on circuit %d",
  1332. serviceid, circuit->_base.n_circ_id);
  1333. reason = END_CIRC_REASON_INTERNAL;
  1334. goto err;
  1335. }
  1336. return;
  1337. err:
  1338. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1339. }
  1340. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1341. * live introduction point, and note that the service descriptor is
  1342. * now out-of-date.*/
  1343. int
  1344. rend_service_intro_established(origin_circuit_t *circuit,
  1345. const uint8_t *request,
  1346. size_t request_len)
  1347. {
  1348. rend_service_t *service;
  1349. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1350. (void) request;
  1351. (void) request_len;
  1352. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1353. log_warn(LD_PROTOCOL,
  1354. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1355. goto err;
  1356. }
  1357. tor_assert(circuit->rend_data);
  1358. service = rend_service_get_by_pk_digest_and_version(
  1359. circuit->rend_data->rend_pk_digest,
  1360. circuit->rend_data->rend_desc_version);
  1361. if (!service) {
  1362. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1363. circuit->_base.n_circ_id);
  1364. goto err;
  1365. }
  1366. service->desc_is_dirty = time(NULL);
  1367. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1368. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1369. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1370. log_info(LD_REND,
  1371. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1372. circuit->_base.n_circ_id, serviceid);
  1373. return 0;
  1374. err:
  1375. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1376. return -1;
  1377. }
  1378. /** Called once a circuit to a rendezvous point is established: sends a
  1379. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1380. */
  1381. void
  1382. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1383. {
  1384. rend_service_t *service;
  1385. char buf[RELAY_PAYLOAD_SIZE];
  1386. crypt_path_t *hop;
  1387. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1388. char hexcookie[9];
  1389. int reason;
  1390. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1391. tor_assert(circuit->cpath);
  1392. tor_assert(circuit->build_state);
  1393. tor_assert(circuit->rend_data);
  1394. hop = circuit->build_state->pending_final_cpath;
  1395. tor_assert(hop);
  1396. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1397. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1398. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1399. log_info(LD_REND,
  1400. "Done building circuit %d to rendezvous with "
  1401. "cookie %s for service %s",
  1402. circuit->_base.n_circ_id, hexcookie, serviceid);
  1403. service = rend_service_get_by_pk_digest_and_version(
  1404. circuit->rend_data->rend_pk_digest,
  1405. circuit->rend_data->rend_desc_version);
  1406. if (!service) {
  1407. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1408. "introduction circuit.");
  1409. reason = END_CIRC_REASON_INTERNAL;
  1410. goto err;
  1411. }
  1412. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1413. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1414. if (crypto_dh_get_public(hop->dh_handshake_state,
  1415. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1416. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1417. reason = END_CIRC_REASON_INTERNAL;
  1418. goto err;
  1419. }
  1420. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1421. DIGEST_LEN);
  1422. /* Send the cell */
  1423. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1424. RELAY_COMMAND_RENDEZVOUS1,
  1425. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1426. circuit->cpath->prev)<0) {
  1427. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1428. reason = END_CIRC_REASON_INTERNAL;
  1429. goto err;
  1430. }
  1431. crypto_dh_free(hop->dh_handshake_state);
  1432. hop->dh_handshake_state = NULL;
  1433. /* Append the cpath entry. */
  1434. hop->state = CPATH_STATE_OPEN;
  1435. /* set the windows to default. these are the windows
  1436. * that bob thinks alice has.
  1437. */
  1438. hop->package_window = circuit_initial_package_window();
  1439. hop->deliver_window = CIRCWINDOW_START;
  1440. onion_append_to_cpath(&circuit->cpath, hop);
  1441. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1442. /* Change the circuit purpose. */
  1443. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1444. return;
  1445. err:
  1446. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1447. }
  1448. /*
  1449. * Manage introduction points
  1450. */
  1451. /** Return the (possibly non-open) introduction circuit ending at
  1452. * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
  1453. * which publishes descriptor of version <b>desc_version</b>. Return
  1454. * NULL if no such service is found.
  1455. */
  1456. static origin_circuit_t *
  1457. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
  1458. int desc_version)
  1459. {
  1460. origin_circuit_t *circ = NULL;
  1461. tor_assert(intro);
  1462. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1463. CIRCUIT_PURPOSE_S_INTRO))) {
  1464. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1465. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1466. circ->rend_data &&
  1467. circ->rend_data->rend_desc_version == desc_version) {
  1468. return circ;
  1469. }
  1470. }
  1471. circ = NULL;
  1472. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1473. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1474. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1475. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1476. circ->rend_data &&
  1477. circ->rend_data->rend_desc_version == desc_version) {
  1478. return circ;
  1479. }
  1480. }
  1481. return NULL;
  1482. }
  1483. /** Determine the responsible hidden service directories for the
  1484. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1485. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1486. * purposes. */
  1487. static void
  1488. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1489. smartlist_t *descs, const char *service_id,
  1490. int seconds_valid)
  1491. {
  1492. int i, j, failed_upload = 0;
  1493. smartlist_t *responsible_dirs = smartlist_create();
  1494. smartlist_t *successful_uploads = smartlist_create();
  1495. routerstatus_t *hs_dir;
  1496. for (i = 0; i < smartlist_len(descs); i++) {
  1497. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1498. /* Determine responsible dirs. */
  1499. if (hid_serv_get_responsible_directories(responsible_dirs,
  1500. desc->desc_id) < 0) {
  1501. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1502. "directories to post descriptors to.");
  1503. smartlist_free(responsible_dirs);
  1504. smartlist_free(successful_uploads);
  1505. return;
  1506. }
  1507. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1508. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1509. hs_dir = smartlist_get(responsible_dirs, j);
  1510. if (smartlist_digest_isin(renddesc->successful_uploads,
  1511. hs_dir->identity_digest))
  1512. /* Don't upload descriptor if we succeeded in doing so last time. */
  1513. continue;
  1514. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1515. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1516. "hidden service directory '%s'; we don't have its "
  1517. "router descriptor. Queuing for later upload.",
  1518. hs_dir->nickname);
  1519. failed_upload = -1;
  1520. continue;
  1521. }
  1522. /* Send publish request. */
  1523. directory_initiate_command_routerstatus(hs_dir,
  1524. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1525. ROUTER_PURPOSE_GENERAL,
  1526. 1, NULL, desc->desc_str,
  1527. strlen(desc->desc_str), 0);
  1528. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1529. desc->desc_id, DIGEST_LEN);
  1530. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1531. "service '%s' with descriptor ID '%s' with validity "
  1532. "of %d seconds to hidden service directory '%s' on "
  1533. "port %d.",
  1534. safe_str(service_id),
  1535. safe_str(desc_id_base32),
  1536. seconds_valid,
  1537. hs_dir->nickname,
  1538. hs_dir->dir_port);
  1539. /* Remember successful upload to this router for next time. */
  1540. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1541. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1542. }
  1543. smartlist_clear(responsible_dirs);
  1544. }
  1545. if (!failed_upload) {
  1546. if (renddesc->successful_uploads) {
  1547. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1548. smartlist_free(renddesc->successful_uploads);
  1549. renddesc->successful_uploads = NULL;
  1550. }
  1551. renddesc->all_uploads_performed = 1;
  1552. } else {
  1553. /* Remember which routers worked this time, so that we don't upload the
  1554. * descriptor to them again. */
  1555. if (!renddesc->successful_uploads)
  1556. renddesc->successful_uploads = smartlist_create();
  1557. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1558. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1559. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1560. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1561. }
  1562. });
  1563. }
  1564. smartlist_free(responsible_dirs);
  1565. smartlist_free(successful_uploads);
  1566. }
  1567. /** Encode and sign up-to-date v0 and/or v2 service descriptors for
  1568. * <b>service</b>, and upload it/them to all the dirservers/to the
  1569. * responsible hidden service directories.
  1570. */
  1571. static void
  1572. upload_service_descriptor(rend_service_t *service)
  1573. {
  1574. time_t now = time(NULL);
  1575. int rendpostperiod;
  1576. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1577. int uploaded = 0;
  1578. rendpostperiod = get_options()->RendPostPeriod;
  1579. /* Upload unversioned (v0) descriptor? */
  1580. if (service->descriptor_version == 0 &&
  1581. get_options()->PublishHidServDescriptors) {
  1582. char *desc;
  1583. size_t desc_len;
  1584. /* Encode the descriptor. */
  1585. if (rend_encode_service_descriptor(service->desc,
  1586. service->private_key,
  1587. &desc, &desc_len)<0) {
  1588. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  1589. "not uploading.");
  1590. return;
  1591. }
  1592. /* Post it to the dirservers */
  1593. rend_get_service_id(service->desc->pk, serviceid);
  1594. log_info(LD_REND, "Sending publish request for hidden service %s",
  1595. serviceid);
  1596. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
  1597. ROUTER_PURPOSE_GENERAL,
  1598. HIDSERV_AUTHORITY, desc, desc_len, 0);
  1599. tor_free(desc);
  1600. service->next_upload_time = now + rendpostperiod;
  1601. uploaded = 1;
  1602. }
  1603. /* Upload v2 descriptor? */
  1604. if (service->descriptor_version == 2 &&
  1605. get_options()->PublishHidServDescriptors) {
  1606. networkstatus_t *c = networkstatus_get_latest_consensus();
  1607. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1608. int seconds_valid, i, j, num_descs;
  1609. smartlist_t *descs = smartlist_create();
  1610. smartlist_t *client_cookies = smartlist_create();
  1611. /* Either upload a single descriptor (including replicas) or one
  1612. * descriptor for each authorized client in case of authorization
  1613. * type 'stealth'. */
  1614. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1615. smartlist_len(service->clients) : 1;
  1616. for (j = 0; j < num_descs; j++) {
  1617. crypto_pk_env_t *client_key = NULL;
  1618. rend_authorized_client_t *client = NULL;
  1619. smartlist_clear(client_cookies);
  1620. switch (service->auth_type) {
  1621. case REND_NO_AUTH:
  1622. /* Do nothing here. */
  1623. break;
  1624. case REND_BASIC_AUTH:
  1625. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1626. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1627. break;
  1628. case REND_STEALTH_AUTH:
  1629. client = smartlist_get(service->clients, j);
  1630. client_key = client->client_key;
  1631. smartlist_add(client_cookies, client->descriptor_cookie);
  1632. break;
  1633. }
  1634. /* Encode the current descriptor. */
  1635. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1636. now, 0,
  1637. service->auth_type,
  1638. client_key,
  1639. client_cookies);
  1640. if (seconds_valid < 0) {
  1641. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1642. "descriptor; not uploading.");
  1643. smartlist_free(descs);
  1644. smartlist_free(client_cookies);
  1645. return;
  1646. }
  1647. /* Post the current descriptors to the hidden service directories. */
  1648. rend_get_service_id(service->desc->pk, serviceid);
  1649. log_info(LD_REND, "Sending publish request for hidden service %s",
  1650. serviceid);
  1651. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1652. seconds_valid);
  1653. /* Free memory for descriptors. */
  1654. for (i = 0; i < smartlist_len(descs); i++)
  1655. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1656. smartlist_clear(descs);
  1657. /* Update next upload time. */
  1658. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1659. > rendpostperiod)
  1660. service->next_upload_time = now + rendpostperiod;
  1661. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1662. service->next_upload_time = now + seconds_valid + 1;
  1663. else
  1664. service->next_upload_time = now + seconds_valid -
  1665. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1666. /* Post also the next descriptors, if necessary. */
  1667. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1668. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1669. now, 1,
  1670. service->auth_type,
  1671. client_key,
  1672. client_cookies);
  1673. if (seconds_valid < 0) {
  1674. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1675. "descriptor; not uploading.");
  1676. smartlist_free(descs);
  1677. smartlist_free(client_cookies);
  1678. return;
  1679. }
  1680. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1681. seconds_valid);
  1682. /* Free memory for descriptors. */
  1683. for (i = 0; i < smartlist_len(descs); i++)
  1684. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1685. smartlist_clear(descs);
  1686. }
  1687. }
  1688. smartlist_free(descs);
  1689. smartlist_free(client_cookies);
  1690. uploaded = 1;
  1691. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1692. }
  1693. }
  1694. /* If not uploaded, try again in one minute. */
  1695. if (!uploaded)
  1696. service->next_upload_time = now + 60;
  1697. /* Unmark dirty flag of this service. */
  1698. service->desc_is_dirty = 0;
  1699. }
  1700. /** For every service, check how many intro points it currently has, and:
  1701. * - Pick new intro points as necessary.
  1702. * - Launch circuits to any new intro points.
  1703. */
  1704. void
  1705. rend_services_introduce(void)
  1706. {
  1707. int i,j,r;
  1708. routerinfo_t *router;
  1709. rend_service_t *service;
  1710. rend_intro_point_t *intro;
  1711. int changed, prev_intro_nodes;
  1712. smartlist_t *intro_routers;
  1713. time_t now;
  1714. or_options_t *options = get_options();
  1715. intro_routers = smartlist_create();
  1716. now = time(NULL);
  1717. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1718. smartlist_clear(intro_routers);
  1719. service = smartlist_get(rend_service_list, i);
  1720. tor_assert(service);
  1721. changed = 0;
  1722. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1723. /* One period has elapsed; we can try building circuits again. */
  1724. service->intro_period_started = now;
  1725. service->n_intro_circuits_launched = 0;
  1726. } else if (service->n_intro_circuits_launched >=
  1727. MAX_INTRO_CIRCS_PER_PERIOD) {
  1728. /* We have failed too many times in this period; wait for the next
  1729. * one before we try again. */
  1730. continue;
  1731. }
  1732. /* Find out which introduction points we have in progress for this
  1733. service. */
  1734. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1735. intro = smartlist_get(service->intro_nodes, j);
  1736. router = router_get_by_digest(intro->extend_info->identity_digest);
  1737. if (!router || !find_intro_circuit(intro, service->pk_digest,
  1738. service->descriptor_version)) {
  1739. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1740. intro->extend_info->nickname, service->service_id);
  1741. if (service->desc) {
  1742. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1743. dintro, {
  1744. if (!memcmp(dintro->extend_info->identity_digest,
  1745. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1746. log_info(LD_REND, "The intro point we are giving up on was "
  1747. "included in the last published descriptor. "
  1748. "Marking current descriptor as dirty.");
  1749. service->desc_is_dirty = now;
  1750. }
  1751. });
  1752. }
  1753. rend_intro_point_free(intro);
  1754. smartlist_del(service->intro_nodes,j--);
  1755. changed = 1;
  1756. }
  1757. if (router)
  1758. smartlist_add(intro_routers, router);
  1759. }
  1760. /* We have enough intro points, and the intro points we thought we had were
  1761. * all connected.
  1762. */
  1763. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1764. /* We have all our intro points! Start a fresh period and reset the
  1765. * circuit count. */
  1766. service->intro_period_started = now;
  1767. service->n_intro_circuits_launched = 0;
  1768. continue;
  1769. }
  1770. /* Remember how many introduction circuits we started with. */
  1771. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1772. /* We have enough directory information to start establishing our
  1773. * intro points. We want to end up with three intro points, but if
  1774. * we're just starting, we launch five and pick the first three that
  1775. * complete.
  1776. *
  1777. * The ones after the first three will be converted to 'general'
  1778. * internal circuits in rend_service_intro_has_opened(), and then
  1779. * we'll drop them from the list of intro points next time we
  1780. * go through the above "find out which introduction points we have
  1781. * in progress" loop. */
  1782. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1783. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1784. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1785. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1786. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1787. flags |= CRN_ALLOW_INVALID;
  1788. router = router_choose_random_node(NULL, intro_routers,
  1789. options->ExcludeNodes, flags);
  1790. if (!router) {
  1791. log_warn(LD_REND,
  1792. "Could only establish %d introduction points for %s.",
  1793. smartlist_len(service->intro_nodes), service->service_id);
  1794. break;
  1795. }
  1796. changed = 1;
  1797. smartlist_add(intro_routers, router);
  1798. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1799. intro->extend_info = extend_info_from_router(router);
  1800. if (service->descriptor_version == 2) {
  1801. intro->intro_key = crypto_new_pk_env();
  1802. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1803. }
  1804. smartlist_add(service->intro_nodes, intro);
  1805. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1806. router->nickname, service->service_id);
  1807. }
  1808. /* If there's no need to launch new circuits, stop here. */
  1809. if (!changed)
  1810. continue;
  1811. /* Establish new introduction points. */
  1812. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1813. intro = smartlist_get(service->intro_nodes, j);
  1814. r = rend_service_launch_establish_intro(service, intro);
  1815. if (r<0) {
  1816. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1817. intro->extend_info->nickname, service->service_id);
  1818. }
  1819. }
  1820. }
  1821. smartlist_free(intro_routers);
  1822. }
  1823. /** Regenerate and upload rendezvous service descriptors for all
  1824. * services, if necessary. If the descriptor has been dirty enough
  1825. * for long enough, definitely upload; else only upload when the
  1826. * periodic timeout has expired.
  1827. *
  1828. * For the first upload, pick a random time between now and two periods
  1829. * from now, and pick it independently for each service.
  1830. */
  1831. void
  1832. rend_consider_services_upload(time_t now)
  1833. {
  1834. int i;
  1835. rend_service_t *service;
  1836. int rendpostperiod = get_options()->RendPostPeriod;
  1837. if (!get_options()->PublishHidServDescriptors)
  1838. return;
  1839. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1840. service = smartlist_get(rend_service_list, i);
  1841. if (!service->next_upload_time) { /* never been uploaded yet */
  1842. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1843. * is stable before being published. See comment below. */
  1844. service->next_upload_time =
  1845. now + 30 + crypto_rand_int(2*rendpostperiod);
  1846. }
  1847. if (service->next_upload_time < now ||
  1848. (service->desc_is_dirty &&
  1849. service->desc_is_dirty < now-30)) {
  1850. /* if it's time, or if the directory servers have a wrong service
  1851. * descriptor and ours has been stable for 30 seconds, upload a
  1852. * new one of each format. */
  1853. rend_service_update_descriptor(service);
  1854. upload_service_descriptor(service);
  1855. }
  1856. }
  1857. }
  1858. /** True if the list of available router descriptors might have changed so
  1859. * that we should have a look whether we can republish previously failed
  1860. * rendezvous service descriptors. */
  1861. static int consider_republishing_rend_descriptors = 1;
  1862. /** Called when our internal view of the directory has changed, so that we
  1863. * might have router descriptors of hidden service directories available that
  1864. * we did not have before. */
  1865. void
  1866. rend_hsdir_routers_changed(void)
  1867. {
  1868. consider_republishing_rend_descriptors = 1;
  1869. }
  1870. /** Consider republication of v2 rendezvous service descriptors that failed
  1871. * previously, but without regenerating descriptor contents.
  1872. */
  1873. void
  1874. rend_consider_descriptor_republication(void)
  1875. {
  1876. int i;
  1877. rend_service_t *service;
  1878. if (!consider_republishing_rend_descriptors)
  1879. return;
  1880. consider_republishing_rend_descriptors = 0;
  1881. if (!get_options()->PublishHidServDescriptors)
  1882. return;
  1883. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1884. service = smartlist_get(rend_service_list, i);
  1885. if (service->descriptor_version && service->desc &&
  1886. !service->desc->all_uploads_performed) {
  1887. /* If we failed in uploading a descriptor last time, try again *without*
  1888. * updating the descriptor's contents. */
  1889. upload_service_descriptor(service);
  1890. }
  1891. }
  1892. }
  1893. /** Log the status of introduction points for all rendezvous services
  1894. * at log severity <b>severity</b>.
  1895. */
  1896. void
  1897. rend_service_dump_stats(int severity)
  1898. {
  1899. int i,j;
  1900. rend_service_t *service;
  1901. rend_intro_point_t *intro;
  1902. const char *safe_name;
  1903. origin_circuit_t *circ;
  1904. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1905. service = smartlist_get(rend_service_list, i);
  1906. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1907. service->directory);
  1908. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1909. intro = smartlist_get(service->intro_nodes, j);
  1910. safe_name = safe_str(intro->extend_info->nickname);
  1911. circ = find_intro_circuit(intro, service->pk_digest,
  1912. service->descriptor_version);
  1913. if (!circ) {
  1914. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1915. j, safe_name);
  1916. continue;
  1917. }
  1918. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1919. j, safe_name, circuit_state_to_string(circ->_base.state));
  1920. }
  1921. }
  1922. }
  1923. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1924. * 'circ', and look up the port and address based on conn-\>port.
  1925. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1926. * or 0 for success.
  1927. */
  1928. int
  1929. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1930. origin_circuit_t *circ)
  1931. {
  1932. rend_service_t *service;
  1933. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1934. smartlist_t *matching_ports;
  1935. rend_service_port_config_t *chosen_port;
  1936. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1937. tor_assert(circ->rend_data);
  1938. log_debug(LD_REND,"beginning to hunt for addr/port");
  1939. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1940. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1941. service = rend_service_get_by_pk_digest_and_version(
  1942. circ->rend_data->rend_pk_digest,
  1943. circ->rend_data->rend_desc_version);
  1944. if (!service) {
  1945. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1946. "rendezvous circuit %d; closing.",
  1947. serviceid, circ->_base.n_circ_id);
  1948. return -1;
  1949. }
  1950. matching_ports = smartlist_create();
  1951. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1952. {
  1953. if (conn->_base.port == p->virtual_port) {
  1954. smartlist_add(matching_ports, p);
  1955. }
  1956. });
  1957. chosen_port = smartlist_choose(matching_ports);
  1958. smartlist_free(matching_ports);
  1959. if (chosen_port) {
  1960. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1961. conn->_base.port = chosen_port->real_port;
  1962. return 0;
  1963. }
  1964. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1965. conn->_base.port,serviceid);
  1966. return -1;
  1967. }