rendservice.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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,sizeof(buf),
  917. (char*)(request+DIGEST_LEN),request_len-DIGEST_LEN,
  918. PK_PKCS1_OAEP_PADDING,1);
  919. if (r<0) {
  920. log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
  921. return -1;
  922. }
  923. len = r;
  924. if (*buf == 3) {
  925. /* Version 3 INTRODUCE2 cell. */
  926. time_t ts = 0, now = time(NULL);
  927. v3_shift = 1;
  928. auth_type = buf[1];
  929. switch (auth_type) {
  930. case REND_BASIC_AUTH:
  931. /* fall through */
  932. case REND_STEALTH_AUTH:
  933. auth_len = ntohs(get_uint16(buf+2));
  934. if (auth_len != REND_DESC_COOKIE_LEN) {
  935. log_info(LD_REND, "Wrong auth data size %d, should be %d.",
  936. (int)auth_len, REND_DESC_COOKIE_LEN);
  937. return -1;
  938. }
  939. memcpy(auth_data, buf+4, sizeof(auth_data));
  940. v3_shift += 2+REND_DESC_COOKIE_LEN;
  941. break;
  942. case REND_NO_AUTH:
  943. break;
  944. default:
  945. log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
  946. }
  947. /* Check timestamp. */
  948. ts = ntohl(get_uint32(buf+1+v3_shift));
  949. v3_shift += 4;
  950. if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
  951. (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
  952. log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
  953. (now - ts) < 0 ? "old" : "new");
  954. return -1;
  955. }
  956. }
  957. if (*buf == 2 || *buf == 3) {
  958. /* Version 2 INTRODUCE2 cell. */
  959. int klen;
  960. extend_info = tor_malloc_zero(sizeof(extend_info_t));
  961. tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
  962. extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
  963. memcpy(extend_info->identity_digest, buf+v3_shift+7,
  964. DIGEST_LEN);
  965. extend_info->nickname[0] = '$';
  966. base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
  967. extend_info->identity_digest, DIGEST_LEN);
  968. klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
  969. if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
  970. log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
  971. (int)len, *buf);
  972. reason = END_CIRC_REASON_TORPROTOCOL;
  973. goto err;
  974. }
  975. extend_info->onion_key =
  976. crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
  977. if (!extend_info->onion_key) {
  978. log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
  979. "INTRODUCE2 cell.", *buf);
  980. reason = END_CIRC_REASON_TORPROTOCOL;
  981. goto err;
  982. }
  983. ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
  984. len -= v3_shift+7+DIGEST_LEN+2+klen;
  985. } else {
  986. char *rp_nickname;
  987. size_t nickname_field_len;
  988. routerinfo_t *router;
  989. int version;
  990. if (*buf == 1) {
  991. rp_nickname = buf+1;
  992. nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
  993. version = 1;
  994. } else {
  995. nickname_field_len = MAX_NICKNAME_LEN+1;
  996. rp_nickname = buf;
  997. version = 0;
  998. }
  999. ptr=memchr(rp_nickname,0,nickname_field_len);
  1000. if (!ptr || ptr == rp_nickname) {
  1001. log_warn(LD_PROTOCOL,
  1002. "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
  1003. return -1;
  1004. }
  1005. if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
  1006. (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
  1007. log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
  1008. return -1;
  1009. }
  1010. /* Okay, now we know that a nickname is at the start of the buffer. */
  1011. ptr = rp_nickname+nickname_field_len;
  1012. len -= nickname_field_len;
  1013. len -= rp_nickname - buf; /* also remove header space used by version, if
  1014. * any */
  1015. router = router_get_by_nickname(rp_nickname, 0);
  1016. if (!router) {
  1017. log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
  1018. escaped_safe_str(rp_nickname));
  1019. /* XXXX Add a no-such-router reason? */
  1020. reason = END_CIRC_REASON_TORPROTOCOL;
  1021. goto err;
  1022. }
  1023. extend_info = extend_info_from_router(router);
  1024. }
  1025. if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
  1026. log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
  1027. reason = END_CIRC_REASON_TORPROTOCOL;
  1028. goto err;
  1029. }
  1030. r_cookie = ptr;
  1031. base16_encode(hexcookie,9,r_cookie,4);
  1032. /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
  1033. digest = crypto_new_digest_env();
  1034. crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
  1035. crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
  1036. crypto_free_digest_env(digest);
  1037. /* Check whether there is a past request with the same Diffie-Hellman,
  1038. * part 1. */
  1039. if (!service->accepted_intros)
  1040. service->accepted_intros = digestmap_new();
  1041. access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
  1042. if (access_time != NULL) {
  1043. log_warn(LD_REND, "Possible replay detected! We received an "
  1044. "INTRODUCE2 cell with same first part of "
  1045. "Diffie-Hellman handshake %d seconds ago. Dropping "
  1046. "cell.",
  1047. (int) (now - *access_time));
  1048. goto err;
  1049. }
  1050. /* Add request to access history, including time and hash of Diffie-Hellman,
  1051. * part 1, and possibly remove requests from the history that are older than
  1052. * one hour. */
  1053. access_time = tor_malloc(sizeof(time_t));
  1054. *access_time = now;
  1055. digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
  1056. if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
  1057. clean_accepted_intros(service, now);
  1058. /* If the service performs client authorization, check included auth data. */
  1059. if (service->clients) {
  1060. if (auth_len > 0) {
  1061. if (rend_check_authorization(service, auth_data)) {
  1062. log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
  1063. } else {
  1064. log_info(LD_REND, "The authorization data that are contained in "
  1065. "the INTRODUCE2 cell are invalid. Dropping cell.");
  1066. reason = END_CIRC_REASON_CONNECTFAILED;
  1067. goto err;
  1068. }
  1069. } else {
  1070. log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
  1071. "data, but we require client authorization. Dropping cell.");
  1072. reason = END_CIRC_REASON_CONNECTFAILED;
  1073. goto err;
  1074. }
  1075. }
  1076. /* Try DH handshake... */
  1077. dh = crypto_dh_new();
  1078. if (!dh || crypto_dh_generate_public(dh)<0) {
  1079. log_warn(LD_BUG,"Internal error: couldn't build DH state "
  1080. "or generate public key.");
  1081. reason = END_CIRC_REASON_INTERNAL;
  1082. goto err;
  1083. }
  1084. if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
  1085. DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  1086. log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
  1087. reason = END_CIRC_REASON_INTERNAL;
  1088. goto err;
  1089. }
  1090. circ_needs_uptime = rend_service_requires_uptime(service);
  1091. /* help predict this next time */
  1092. rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
  1093. /* Launch a circuit to alice's chosen rendezvous point.
  1094. */
  1095. for (i=0;i<MAX_REND_FAILURES;i++) {
  1096. int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
  1097. if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1098. launched = circuit_launch_by_extend_info(
  1099. CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
  1100. if (launched)
  1101. break;
  1102. }
  1103. if (!launched) { /* give up */
  1104. log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
  1105. "point %s for service %s.",
  1106. escaped_safe_str(extend_info->nickname), serviceid);
  1107. reason = END_CIRC_REASON_CONNECTFAILED;
  1108. goto err;
  1109. }
  1110. log_info(LD_REND,
  1111. "Accepted intro; launching circuit to %s "
  1112. "(cookie %s) for service %s.",
  1113. escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
  1114. tor_assert(launched->build_state);
  1115. /* Fill in the circuit's state. */
  1116. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1117. memcpy(launched->rend_data->rend_pk_digest,
  1118. circuit->rend_data->rend_pk_digest,
  1119. DIGEST_LEN);
  1120. memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
  1121. strlcpy(launched->rend_data->onion_address, service->service_id,
  1122. sizeof(launched->rend_data->onion_address));
  1123. launched->rend_data->rend_desc_version = service->descriptor_version;
  1124. launched->build_state->pending_final_cpath = cpath =
  1125. tor_malloc_zero(sizeof(crypt_path_t));
  1126. cpath->magic = CRYPT_PATH_MAGIC;
  1127. launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
  1128. cpath->dh_handshake_state = dh;
  1129. dh = NULL;
  1130. if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
  1131. goto err;
  1132. memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
  1133. if (extend_info) extend_info_free(extend_info);
  1134. memset(keys, 0, sizeof(keys));
  1135. return 0;
  1136. err:
  1137. memset(keys, 0, sizeof(keys));
  1138. if (dh) crypto_dh_free(dh);
  1139. if (launched)
  1140. circuit_mark_for_close(TO_CIRCUIT(launched), reason);
  1141. if (extend_info) extend_info_free(extend_info);
  1142. return -1;
  1143. }
  1144. /** Called when we fail building a rendezvous circuit at some point other
  1145. * than the last hop: launches a new circuit to the same rendezvous point.
  1146. */
  1147. void
  1148. rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
  1149. {
  1150. origin_circuit_t *newcirc;
  1151. cpath_build_state_t *newstate, *oldstate;
  1152. tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1153. if (!oldcirc->build_state ||
  1154. oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
  1155. oldcirc->build_state->expiry_time < time(NULL)) {
  1156. log_info(LD_REND,
  1157. "Attempt to build circuit to %s for rendezvous has failed "
  1158. "too many times or expired; giving up.",
  1159. oldcirc->build_state ?
  1160. oldcirc->build_state->chosen_exit->nickname : "*unknown*");
  1161. return;
  1162. }
  1163. oldstate = oldcirc->build_state;
  1164. tor_assert(oldstate);
  1165. if (oldstate->pending_final_cpath == NULL) {
  1166. log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
  1167. "Initiator will retry.");
  1168. return;
  1169. }
  1170. log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
  1171. oldstate->chosen_exit->nickname);
  1172. newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
  1173. oldstate->chosen_exit,
  1174. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  1175. if (!newcirc) {
  1176. log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
  1177. oldstate->chosen_exit->nickname);
  1178. return;
  1179. }
  1180. newstate = newcirc->build_state;
  1181. tor_assert(newstate);
  1182. newstate->failure_count = oldstate->failure_count+1;
  1183. newstate->expiry_time = oldstate->expiry_time;
  1184. newstate->pending_final_cpath = oldstate->pending_final_cpath;
  1185. oldstate->pending_final_cpath = NULL;
  1186. newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
  1187. }
  1188. /** Launch a circuit to serve as an introduction point for the service
  1189. * <b>service</b> at the introduction point <b>nickname</b>
  1190. */
  1191. static int
  1192. rend_service_launch_establish_intro(rend_service_t *service,
  1193. rend_intro_point_t *intro)
  1194. {
  1195. origin_circuit_t *launched;
  1196. log_info(LD_REND,
  1197. "Launching circuit to introduction point %s for service %s",
  1198. escaped_safe_str(intro->extend_info->nickname),
  1199. service->service_id);
  1200. rep_hist_note_used_internal(time(NULL), 1, 0);
  1201. ++service->n_intro_circuits_launched;
  1202. launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
  1203. intro->extend_info,
  1204. CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
  1205. if (!launched) {
  1206. log_info(LD_REND,
  1207. "Can't launch circuit to establish introduction at %s.",
  1208. escaped_safe_str(intro->extend_info->nickname));
  1209. return -1;
  1210. }
  1211. if (memcmp(intro->extend_info->identity_digest,
  1212. launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
  1213. char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
  1214. base16_encode(cann, sizeof(cann),
  1215. launched->build_state->chosen_exit->identity_digest,
  1216. DIGEST_LEN);
  1217. base16_encode(orig, sizeof(orig),
  1218. intro->extend_info->identity_digest, DIGEST_LEN);
  1219. log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
  1220. "but we requested an intro circuit to $%s. Updating "
  1221. "our service.", cann, orig);
  1222. extend_info_free(intro->extend_info);
  1223. intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
  1224. }
  1225. launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
  1226. strlcpy(launched->rend_data->onion_address, service->service_id,
  1227. sizeof(launched->rend_data->onion_address));
  1228. memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
  1229. launched->rend_data->rend_desc_version = service->descriptor_version;
  1230. if (service->descriptor_version == 2)
  1231. launched->intro_key = crypto_pk_dup_key(intro->intro_key);
  1232. if (launched->_base.state == CIRCUIT_STATE_OPEN)
  1233. rend_service_intro_has_opened(launched);
  1234. return 0;
  1235. }
  1236. /** Return the number of introduction points that are or have been
  1237. * established for the given service address and rendezvous version. */
  1238. static int
  1239. count_established_intro_points(const char *query, int rend_version)
  1240. {
  1241. int num_ipos = 0;
  1242. circuit_t *circ;
  1243. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1244. if (!circ->marked_for_close &&
  1245. circ->state == CIRCUIT_STATE_OPEN &&
  1246. (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1247. circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
  1248. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
  1249. if (oc->rend_data &&
  1250. oc->rend_data->rend_desc_version == rend_version &&
  1251. !rend_cmp_service_ids(query, oc->rend_data->onion_address))
  1252. num_ipos++;
  1253. }
  1254. }
  1255. return num_ipos;
  1256. }
  1257. /** Called when we're done building a circuit to an introduction point:
  1258. * sends a RELAY_ESTABLISH_INTRO cell.
  1259. */
  1260. void
  1261. rend_service_intro_has_opened(origin_circuit_t *circuit)
  1262. {
  1263. rend_service_t *service;
  1264. size_t len;
  1265. int r;
  1266. char buf[RELAY_PAYLOAD_SIZE];
  1267. char auth[DIGEST_LEN + 9];
  1268. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1269. int reason = END_CIRC_REASON_TORPROTOCOL;
  1270. crypto_pk_env_t *intro_key;
  1271. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
  1272. tor_assert(circuit->cpath);
  1273. tor_assert(circuit->rend_data);
  1274. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1275. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1276. service = rend_service_get_by_pk_digest_and_version(
  1277. circuit->rend_data->rend_pk_digest,
  1278. circuit->rend_data->rend_desc_version);
  1279. if (!service) {
  1280. log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
  1281. serviceid, circuit->_base.n_circ_id);
  1282. reason = END_CIRC_REASON_NOSUCHSERVICE;
  1283. goto err;
  1284. }
  1285. /* If we already have enough introduction circuits for this service,
  1286. * redefine this one as a general circuit. */
  1287. if (count_established_intro_points(serviceid,
  1288. circuit->rend_data->rend_desc_version) > NUM_INTRO_POINTS) {
  1289. log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
  1290. "circuit, but we already have enough. Redefining purpose to "
  1291. "general.");
  1292. TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1293. circuit_has_opened(circuit);
  1294. return;
  1295. }
  1296. log_info(LD_REND,
  1297. "Established circuit %d as introduction point for service %s",
  1298. circuit->_base.n_circ_id, serviceid);
  1299. /* If the introduction point will not be used in an unversioned
  1300. * descriptor, use the intro key instead of the service key in
  1301. * ESTABLISH_INTRO. */
  1302. if (service->descriptor_version == 0)
  1303. intro_key = service->private_key;
  1304. else
  1305. intro_key = circuit->intro_key;
  1306. /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  1307. r = crypto_pk_asn1_encode(intro_key, buf+2,
  1308. RELAY_PAYLOAD_SIZE-2);
  1309. if (r < 0) {
  1310. log_warn(LD_BUG, "Internal error; failed to establish intro point.");
  1311. reason = END_CIRC_REASON_INTERNAL;
  1312. goto err;
  1313. }
  1314. len = r;
  1315. set_uint16(buf, htons((uint16_t)len));
  1316. len += 2;
  1317. memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  1318. memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
  1319. if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
  1320. goto err;
  1321. len += 20;
  1322. note_crypto_pk_op(REND_SERVER);
  1323. r = crypto_pk_private_sign_digest(intro_key, buf+len, sizeof(buf)-len,
  1324. buf, len);
  1325. if (r<0) {
  1326. log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
  1327. reason = END_CIRC_REASON_INTERNAL;
  1328. goto err;
  1329. }
  1330. len += r;
  1331. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1332. RELAY_COMMAND_ESTABLISH_INTRO,
  1333. buf, len, circuit->cpath->prev)<0) {
  1334. log_info(LD_GENERAL,
  1335. "Couldn't send introduction request for service %s on circuit %d",
  1336. serviceid, circuit->_base.n_circ_id);
  1337. reason = END_CIRC_REASON_INTERNAL;
  1338. goto err;
  1339. }
  1340. return;
  1341. err:
  1342. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1343. }
  1344. /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
  1345. * live introduction point, and note that the service descriptor is
  1346. * now out-of-date.*/
  1347. int
  1348. rend_service_intro_established(origin_circuit_t *circuit,
  1349. const uint8_t *request,
  1350. size_t request_len)
  1351. {
  1352. rend_service_t *service;
  1353. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1354. (void) request;
  1355. (void) request_len;
  1356. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1357. log_warn(LD_PROTOCOL,
  1358. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1359. goto err;
  1360. }
  1361. tor_assert(circuit->rend_data);
  1362. service = rend_service_get_by_pk_digest_and_version(
  1363. circuit->rend_data->rend_pk_digest,
  1364. circuit->rend_data->rend_desc_version);
  1365. if (!service) {
  1366. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1367. circuit->_base.n_circ_id);
  1368. goto err;
  1369. }
  1370. service->desc_is_dirty = time(NULL);
  1371. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1372. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1373. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1374. log_info(LD_REND,
  1375. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1376. circuit->_base.n_circ_id, serviceid);
  1377. return 0;
  1378. err:
  1379. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1380. return -1;
  1381. }
  1382. /** Called once a circuit to a rendezvous point is established: sends a
  1383. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1384. */
  1385. void
  1386. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1387. {
  1388. rend_service_t *service;
  1389. char buf[RELAY_PAYLOAD_SIZE];
  1390. crypt_path_t *hop;
  1391. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1392. char hexcookie[9];
  1393. int reason;
  1394. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1395. tor_assert(circuit->cpath);
  1396. tor_assert(circuit->build_state);
  1397. tor_assert(circuit->rend_data);
  1398. hop = circuit->build_state->pending_final_cpath;
  1399. tor_assert(hop);
  1400. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1401. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1402. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1403. log_info(LD_REND,
  1404. "Done building circuit %d to rendezvous with "
  1405. "cookie %s for service %s",
  1406. circuit->_base.n_circ_id, hexcookie, serviceid);
  1407. service = rend_service_get_by_pk_digest_and_version(
  1408. circuit->rend_data->rend_pk_digest,
  1409. circuit->rend_data->rend_desc_version);
  1410. if (!service) {
  1411. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1412. "introduction circuit.");
  1413. reason = END_CIRC_REASON_INTERNAL;
  1414. goto err;
  1415. }
  1416. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1417. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1418. if (crypto_dh_get_public(hop->dh_handshake_state,
  1419. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1420. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1421. reason = END_CIRC_REASON_INTERNAL;
  1422. goto err;
  1423. }
  1424. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1425. DIGEST_LEN);
  1426. /* Send the cell */
  1427. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1428. RELAY_COMMAND_RENDEZVOUS1,
  1429. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1430. circuit->cpath->prev)<0) {
  1431. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1432. reason = END_CIRC_REASON_INTERNAL;
  1433. goto err;
  1434. }
  1435. crypto_dh_free(hop->dh_handshake_state);
  1436. hop->dh_handshake_state = NULL;
  1437. /* Append the cpath entry. */
  1438. hop->state = CPATH_STATE_OPEN;
  1439. /* set the windows to default. these are the windows
  1440. * that bob thinks alice has.
  1441. */
  1442. hop->package_window = circuit_initial_package_window();
  1443. hop->deliver_window = CIRCWINDOW_START;
  1444. onion_append_to_cpath(&circuit->cpath, hop);
  1445. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1446. /* Change the circuit purpose. */
  1447. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1448. return;
  1449. err:
  1450. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1451. }
  1452. /*
  1453. * Manage introduction points
  1454. */
  1455. /** Return the (possibly non-open) introduction circuit ending at
  1456. * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
  1457. * which publishes descriptor of version <b>desc_version</b>. Return
  1458. * NULL if no such service is found.
  1459. */
  1460. static origin_circuit_t *
  1461. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
  1462. int desc_version)
  1463. {
  1464. origin_circuit_t *circ = NULL;
  1465. tor_assert(intro);
  1466. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1467. CIRCUIT_PURPOSE_S_INTRO))) {
  1468. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1469. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1470. circ->rend_data &&
  1471. circ->rend_data->rend_desc_version == desc_version) {
  1472. return circ;
  1473. }
  1474. }
  1475. circ = NULL;
  1476. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1477. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1478. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1479. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1480. circ->rend_data &&
  1481. circ->rend_data->rend_desc_version == desc_version) {
  1482. return circ;
  1483. }
  1484. }
  1485. return NULL;
  1486. }
  1487. /** Determine the responsible hidden service directories for the
  1488. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1489. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1490. * purposes. */
  1491. static void
  1492. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1493. smartlist_t *descs, const char *service_id,
  1494. int seconds_valid)
  1495. {
  1496. int i, j, failed_upload = 0;
  1497. smartlist_t *responsible_dirs = smartlist_create();
  1498. smartlist_t *successful_uploads = smartlist_create();
  1499. routerstatus_t *hs_dir;
  1500. for (i = 0; i < smartlist_len(descs); i++) {
  1501. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1502. /* Determine responsible dirs. */
  1503. if (hid_serv_get_responsible_directories(responsible_dirs,
  1504. desc->desc_id) < 0) {
  1505. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1506. "directories to post descriptors to.");
  1507. smartlist_free(responsible_dirs);
  1508. smartlist_free(successful_uploads);
  1509. return;
  1510. }
  1511. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1512. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1513. hs_dir = smartlist_get(responsible_dirs, j);
  1514. if (smartlist_digest_isin(renddesc->successful_uploads,
  1515. hs_dir->identity_digest))
  1516. /* Don't upload descriptor if we succeeded in doing so last time. */
  1517. continue;
  1518. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1519. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1520. "hidden service directory '%s'; we don't have its "
  1521. "router descriptor. Queuing for later upload.",
  1522. hs_dir->nickname);
  1523. failed_upload = -1;
  1524. continue;
  1525. }
  1526. /* Send publish request. */
  1527. directory_initiate_command_routerstatus(hs_dir,
  1528. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1529. ROUTER_PURPOSE_GENERAL,
  1530. 1, NULL, desc->desc_str,
  1531. strlen(desc->desc_str), 0);
  1532. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1533. desc->desc_id, DIGEST_LEN);
  1534. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1535. "service '%s' with descriptor ID '%s' with validity "
  1536. "of %d seconds to hidden service directory '%s' on "
  1537. "port %d.",
  1538. safe_str(service_id),
  1539. safe_str(desc_id_base32),
  1540. seconds_valid,
  1541. hs_dir->nickname,
  1542. hs_dir->dir_port);
  1543. /* Remember successful upload to this router for next time. */
  1544. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1545. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1546. }
  1547. smartlist_clear(responsible_dirs);
  1548. }
  1549. if (!failed_upload) {
  1550. if (renddesc->successful_uploads) {
  1551. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1552. smartlist_free(renddesc->successful_uploads);
  1553. renddesc->successful_uploads = NULL;
  1554. }
  1555. renddesc->all_uploads_performed = 1;
  1556. } else {
  1557. /* Remember which routers worked this time, so that we don't upload the
  1558. * descriptor to them again. */
  1559. if (!renddesc->successful_uploads)
  1560. renddesc->successful_uploads = smartlist_create();
  1561. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1562. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1563. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1564. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1565. }
  1566. });
  1567. }
  1568. smartlist_free(responsible_dirs);
  1569. smartlist_free(successful_uploads);
  1570. }
  1571. /** Encode and sign up-to-date v0 and/or v2 service descriptors for
  1572. * <b>service</b>, and upload it/them to all the dirservers/to the
  1573. * responsible hidden service directories.
  1574. */
  1575. static void
  1576. upload_service_descriptor(rend_service_t *service)
  1577. {
  1578. time_t now = time(NULL);
  1579. int rendpostperiod;
  1580. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1581. int uploaded = 0;
  1582. rendpostperiod = get_options()->RendPostPeriod;
  1583. /* Upload unversioned (v0) descriptor? */
  1584. if (service->descriptor_version == 0 &&
  1585. get_options()->PublishHidServDescriptors) {
  1586. char *desc;
  1587. size_t desc_len;
  1588. /* Encode the descriptor. */
  1589. if (rend_encode_service_descriptor(service->desc,
  1590. service->private_key,
  1591. &desc, &desc_len)<0) {
  1592. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  1593. "not uploading.");
  1594. return;
  1595. }
  1596. /* Post it to the dirservers */
  1597. rend_get_service_id(service->desc->pk, serviceid);
  1598. log_info(LD_REND, "Sending publish request for hidden service %s",
  1599. serviceid);
  1600. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
  1601. ROUTER_PURPOSE_GENERAL,
  1602. HIDSERV_AUTHORITY, desc, desc_len, 0);
  1603. tor_free(desc);
  1604. service->next_upload_time = now + rendpostperiod;
  1605. uploaded = 1;
  1606. }
  1607. /* Upload v2 descriptor? */
  1608. if (service->descriptor_version == 2 &&
  1609. get_options()->PublishHidServDescriptors) {
  1610. networkstatus_t *c = networkstatus_get_latest_consensus();
  1611. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1612. int seconds_valid, i, j, num_descs;
  1613. smartlist_t *descs = smartlist_create();
  1614. smartlist_t *client_cookies = smartlist_create();
  1615. /* Either upload a single descriptor (including replicas) or one
  1616. * descriptor for each authorized client in case of authorization
  1617. * type 'stealth'. */
  1618. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1619. smartlist_len(service->clients) : 1;
  1620. for (j = 0; j < num_descs; j++) {
  1621. crypto_pk_env_t *client_key = NULL;
  1622. rend_authorized_client_t *client = NULL;
  1623. smartlist_clear(client_cookies);
  1624. switch (service->auth_type) {
  1625. case REND_NO_AUTH:
  1626. /* Do nothing here. */
  1627. break;
  1628. case REND_BASIC_AUTH:
  1629. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1630. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1631. break;
  1632. case REND_STEALTH_AUTH:
  1633. client = smartlist_get(service->clients, j);
  1634. client_key = client->client_key;
  1635. smartlist_add(client_cookies, client->descriptor_cookie);
  1636. break;
  1637. }
  1638. /* Encode the current descriptor. */
  1639. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1640. now, 0,
  1641. service->auth_type,
  1642. client_key,
  1643. client_cookies);
  1644. if (seconds_valid < 0) {
  1645. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1646. "descriptor; not uploading.");
  1647. smartlist_free(descs);
  1648. smartlist_free(client_cookies);
  1649. return;
  1650. }
  1651. /* Post the current descriptors to the hidden service directories. */
  1652. rend_get_service_id(service->desc->pk, serviceid);
  1653. log_info(LD_REND, "Sending publish request for hidden service %s",
  1654. serviceid);
  1655. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1656. seconds_valid);
  1657. /* Free memory for descriptors. */
  1658. for (i = 0; i < smartlist_len(descs); i++)
  1659. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1660. smartlist_clear(descs);
  1661. /* Update next upload time. */
  1662. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1663. > rendpostperiod)
  1664. service->next_upload_time = now + rendpostperiod;
  1665. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1666. service->next_upload_time = now + seconds_valid + 1;
  1667. else
  1668. service->next_upload_time = now + seconds_valid -
  1669. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1670. /* Post also the next descriptors, if necessary. */
  1671. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1672. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1673. now, 1,
  1674. service->auth_type,
  1675. client_key,
  1676. client_cookies);
  1677. if (seconds_valid < 0) {
  1678. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1679. "descriptor; not uploading.");
  1680. smartlist_free(descs);
  1681. smartlist_free(client_cookies);
  1682. return;
  1683. }
  1684. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1685. seconds_valid);
  1686. /* Free memory for descriptors. */
  1687. for (i = 0; i < smartlist_len(descs); i++)
  1688. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1689. smartlist_clear(descs);
  1690. }
  1691. }
  1692. smartlist_free(descs);
  1693. smartlist_free(client_cookies);
  1694. uploaded = 1;
  1695. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1696. }
  1697. }
  1698. /* If not uploaded, try again in one minute. */
  1699. if (!uploaded)
  1700. service->next_upload_time = now + 60;
  1701. /* Unmark dirty flag of this service. */
  1702. service->desc_is_dirty = 0;
  1703. }
  1704. /** For every service, check how many intro points it currently has, and:
  1705. * - Pick new intro points as necessary.
  1706. * - Launch circuits to any new intro points.
  1707. */
  1708. void
  1709. rend_services_introduce(void)
  1710. {
  1711. int i,j,r;
  1712. routerinfo_t *router;
  1713. rend_service_t *service;
  1714. rend_intro_point_t *intro;
  1715. int changed, prev_intro_nodes;
  1716. smartlist_t *intro_routers;
  1717. time_t now;
  1718. or_options_t *options = get_options();
  1719. intro_routers = smartlist_create();
  1720. now = time(NULL);
  1721. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1722. smartlist_clear(intro_routers);
  1723. service = smartlist_get(rend_service_list, i);
  1724. tor_assert(service);
  1725. changed = 0;
  1726. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1727. /* One period has elapsed; we can try building circuits again. */
  1728. service->intro_period_started = now;
  1729. service->n_intro_circuits_launched = 0;
  1730. } else if (service->n_intro_circuits_launched >=
  1731. MAX_INTRO_CIRCS_PER_PERIOD) {
  1732. /* We have failed too many times in this period; wait for the next
  1733. * one before we try again. */
  1734. continue;
  1735. }
  1736. /* Find out which introduction points we have in progress for this
  1737. service. */
  1738. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1739. intro = smartlist_get(service->intro_nodes, j);
  1740. router = router_get_by_digest(intro->extend_info->identity_digest);
  1741. if (!router || !find_intro_circuit(intro, service->pk_digest,
  1742. service->descriptor_version)) {
  1743. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1744. intro->extend_info->nickname, service->service_id);
  1745. if (service->desc) {
  1746. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1747. dintro, {
  1748. if (!memcmp(dintro->extend_info->identity_digest,
  1749. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1750. log_info(LD_REND, "The intro point we are giving up on was "
  1751. "included in the last published descriptor. "
  1752. "Marking current descriptor as dirty.");
  1753. service->desc_is_dirty = now;
  1754. }
  1755. });
  1756. }
  1757. rend_intro_point_free(intro);
  1758. smartlist_del(service->intro_nodes,j--);
  1759. changed = 1;
  1760. }
  1761. if (router)
  1762. smartlist_add(intro_routers, router);
  1763. }
  1764. /* We have enough intro points, and the intro points we thought we had were
  1765. * all connected.
  1766. */
  1767. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1768. /* We have all our intro points! Start a fresh period and reset the
  1769. * circuit count. */
  1770. service->intro_period_started = now;
  1771. service->n_intro_circuits_launched = 0;
  1772. continue;
  1773. }
  1774. /* Remember how many introduction circuits we started with. */
  1775. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1776. /* We have enough directory information to start establishing our
  1777. * intro points. We want to end up with three intro points, but if
  1778. * we're just starting, we launch five and pick the first three that
  1779. * complete.
  1780. *
  1781. * The ones after the first three will be converted to 'general'
  1782. * internal circuits in rend_service_intro_has_opened(), and then
  1783. * we'll drop them from the list of intro points next time we
  1784. * go through the above "find out which introduction points we have
  1785. * in progress" loop. */
  1786. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1787. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1788. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1789. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1790. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1791. flags |= CRN_ALLOW_INVALID;
  1792. router = router_choose_random_node(NULL, intro_routers,
  1793. options->ExcludeNodes, flags);
  1794. if (!router) {
  1795. log_warn(LD_REND,
  1796. "Could only establish %d introduction points for %s.",
  1797. smartlist_len(service->intro_nodes), service->service_id);
  1798. break;
  1799. }
  1800. changed = 1;
  1801. smartlist_add(intro_routers, router);
  1802. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1803. intro->extend_info = extend_info_from_router(router);
  1804. if (service->descriptor_version == 2) {
  1805. intro->intro_key = crypto_new_pk_env();
  1806. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1807. }
  1808. smartlist_add(service->intro_nodes, intro);
  1809. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1810. router->nickname, service->service_id);
  1811. }
  1812. /* If there's no need to launch new circuits, stop here. */
  1813. if (!changed)
  1814. continue;
  1815. /* Establish new introduction points. */
  1816. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1817. intro = smartlist_get(service->intro_nodes, j);
  1818. r = rend_service_launch_establish_intro(service, intro);
  1819. if (r<0) {
  1820. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1821. intro->extend_info->nickname, service->service_id);
  1822. }
  1823. }
  1824. }
  1825. smartlist_free(intro_routers);
  1826. }
  1827. /** Regenerate and upload rendezvous service descriptors for all
  1828. * services, if necessary. If the descriptor has been dirty enough
  1829. * for long enough, definitely upload; else only upload when the
  1830. * periodic timeout has expired.
  1831. *
  1832. * For the first upload, pick a random time between now and two periods
  1833. * from now, and pick it independently for each service.
  1834. */
  1835. void
  1836. rend_consider_services_upload(time_t now)
  1837. {
  1838. int i;
  1839. rend_service_t *service;
  1840. int rendpostperiod = get_options()->RendPostPeriod;
  1841. if (!get_options()->PublishHidServDescriptors)
  1842. return;
  1843. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1844. service = smartlist_get(rend_service_list, i);
  1845. if (!service->next_upload_time) { /* never been uploaded yet */
  1846. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1847. * is stable before being published. See comment below. */
  1848. service->next_upload_time =
  1849. now + 30 + crypto_rand_int(2*rendpostperiod);
  1850. }
  1851. if (service->next_upload_time < now ||
  1852. (service->desc_is_dirty &&
  1853. service->desc_is_dirty < now-30)) {
  1854. /* if it's time, or if the directory servers have a wrong service
  1855. * descriptor and ours has been stable for 30 seconds, upload a
  1856. * new one of each format. */
  1857. rend_service_update_descriptor(service);
  1858. upload_service_descriptor(service);
  1859. }
  1860. }
  1861. }
  1862. /** True if the list of available router descriptors might have changed so
  1863. * that we should have a look whether we can republish previously failed
  1864. * rendezvous service descriptors. */
  1865. static int consider_republishing_rend_descriptors = 1;
  1866. /** Called when our internal view of the directory has changed, so that we
  1867. * might have router descriptors of hidden service directories available that
  1868. * we did not have before. */
  1869. void
  1870. rend_hsdir_routers_changed(void)
  1871. {
  1872. consider_republishing_rend_descriptors = 1;
  1873. }
  1874. /** Consider republication of v2 rendezvous service descriptors that failed
  1875. * previously, but without regenerating descriptor contents.
  1876. */
  1877. void
  1878. rend_consider_descriptor_republication(void)
  1879. {
  1880. int i;
  1881. rend_service_t *service;
  1882. if (!consider_republishing_rend_descriptors)
  1883. return;
  1884. consider_republishing_rend_descriptors = 0;
  1885. if (!get_options()->PublishHidServDescriptors)
  1886. return;
  1887. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1888. service = smartlist_get(rend_service_list, i);
  1889. if (service->descriptor_version && service->desc &&
  1890. !service->desc->all_uploads_performed) {
  1891. /* If we failed in uploading a descriptor last time, try again *without*
  1892. * updating the descriptor's contents. */
  1893. upload_service_descriptor(service);
  1894. }
  1895. }
  1896. }
  1897. /** Log the status of introduction points for all rendezvous services
  1898. * at log severity <b>severity</b>.
  1899. */
  1900. void
  1901. rend_service_dump_stats(int severity)
  1902. {
  1903. int i,j;
  1904. rend_service_t *service;
  1905. rend_intro_point_t *intro;
  1906. const char *safe_name;
  1907. origin_circuit_t *circ;
  1908. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1909. service = smartlist_get(rend_service_list, i);
  1910. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1911. service->directory);
  1912. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1913. intro = smartlist_get(service->intro_nodes, j);
  1914. safe_name = safe_str(intro->extend_info->nickname);
  1915. circ = find_intro_circuit(intro, service->pk_digest,
  1916. service->descriptor_version);
  1917. if (!circ) {
  1918. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1919. j, safe_name);
  1920. continue;
  1921. }
  1922. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1923. j, safe_name, circuit_state_to_string(circ->_base.state));
  1924. }
  1925. }
  1926. }
  1927. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1928. * 'circ', and look up the port and address based on conn-\>port.
  1929. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1930. * or 0 for success.
  1931. */
  1932. int
  1933. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1934. origin_circuit_t *circ)
  1935. {
  1936. rend_service_t *service;
  1937. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1938. smartlist_t *matching_ports;
  1939. rend_service_port_config_t *chosen_port;
  1940. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1941. tor_assert(circ->rend_data);
  1942. log_debug(LD_REND,"beginning to hunt for addr/port");
  1943. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1944. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1945. service = rend_service_get_by_pk_digest_and_version(
  1946. circ->rend_data->rend_pk_digest,
  1947. circ->rend_data->rend_desc_version);
  1948. if (!service) {
  1949. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1950. "rendezvous circuit %d; closing.",
  1951. serviceid, circ->_base.n_circ_id);
  1952. return -1;
  1953. }
  1954. matching_ports = smartlist_create();
  1955. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1956. {
  1957. if (conn->_base.port == p->virtual_port) {
  1958. smartlist_add(matching_ports, p);
  1959. }
  1960. });
  1961. chosen_port = smartlist_choose(matching_ports);
  1962. smartlist_free(matching_ports);
  1963. if (chosen_port) {
  1964. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1965. conn->_base.port = chosen_port->real_port;
  1966. return 0;
  1967. }
  1968. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1969. conn->_base.port,serviceid);
  1970. return -1;
  1971. }