rendservice.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2010, 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 char *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. 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,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, const char *request,
  1345. size_t request_len)
  1346. {
  1347. rend_service_t *service;
  1348. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1349. (void) request;
  1350. (void) request_len;
  1351. if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
  1352. log_warn(LD_PROTOCOL,
  1353. "received INTRO_ESTABLISHED cell on non-intro circuit.");
  1354. goto err;
  1355. }
  1356. tor_assert(circuit->rend_data);
  1357. service = rend_service_get_by_pk_digest_and_version(
  1358. circuit->rend_data->rend_pk_digest,
  1359. circuit->rend_data->rend_desc_version);
  1360. if (!service) {
  1361. log_warn(LD_REND, "Unknown service on introduction circuit %d.",
  1362. circuit->_base.n_circ_id);
  1363. goto err;
  1364. }
  1365. service->desc_is_dirty = time(NULL);
  1366. circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
  1367. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
  1368. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1369. log_info(LD_REND,
  1370. "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
  1371. circuit->_base.n_circ_id, serviceid);
  1372. return 0;
  1373. err:
  1374. circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
  1375. return -1;
  1376. }
  1377. /** Called once a circuit to a rendezvous point is established: sends a
  1378. * RELAY_COMMAND_RENDEZVOUS1 cell.
  1379. */
  1380. void
  1381. rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
  1382. {
  1383. rend_service_t *service;
  1384. char buf[RELAY_PAYLOAD_SIZE];
  1385. crypt_path_t *hop;
  1386. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1387. char hexcookie[9];
  1388. int reason;
  1389. tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
  1390. tor_assert(circuit->cpath);
  1391. tor_assert(circuit->build_state);
  1392. tor_assert(circuit->rend_data);
  1393. hop = circuit->build_state->pending_final_cpath;
  1394. tor_assert(hop);
  1395. base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
  1396. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1397. circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1398. log_info(LD_REND,
  1399. "Done building circuit %d to rendezvous with "
  1400. "cookie %s for service %s",
  1401. circuit->_base.n_circ_id, hexcookie, serviceid);
  1402. service = rend_service_get_by_pk_digest_and_version(
  1403. circuit->rend_data->rend_pk_digest,
  1404. circuit->rend_data->rend_desc_version);
  1405. if (!service) {
  1406. log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
  1407. "introduction circuit.");
  1408. reason = END_CIRC_REASON_INTERNAL;
  1409. goto err;
  1410. }
  1411. /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
  1412. memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
  1413. if (crypto_dh_get_public(hop->dh_handshake_state,
  1414. buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
  1415. log_warn(LD_GENERAL,"Couldn't get DH public key.");
  1416. reason = END_CIRC_REASON_INTERNAL;
  1417. goto err;
  1418. }
  1419. memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
  1420. DIGEST_LEN);
  1421. /* Send the cell */
  1422. if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
  1423. RELAY_COMMAND_RENDEZVOUS1,
  1424. buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
  1425. circuit->cpath->prev)<0) {
  1426. log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
  1427. reason = END_CIRC_REASON_INTERNAL;
  1428. goto err;
  1429. }
  1430. crypto_dh_free(hop->dh_handshake_state);
  1431. hop->dh_handshake_state = NULL;
  1432. /* Append the cpath entry. */
  1433. hop->state = CPATH_STATE_OPEN;
  1434. /* set the windows to default. these are the windows
  1435. * that bob thinks alice has.
  1436. */
  1437. hop->package_window = circuit_initial_package_window();
  1438. hop->deliver_window = CIRCWINDOW_START;
  1439. onion_append_to_cpath(&circuit->cpath, hop);
  1440. circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
  1441. /* Change the circuit purpose. */
  1442. circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
  1443. return;
  1444. err:
  1445. circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
  1446. }
  1447. /*
  1448. * Manage introduction points
  1449. */
  1450. /** Return the (possibly non-open) introduction circuit ending at
  1451. * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
  1452. * which publishes descriptor of version <b>desc_version</b>. Return
  1453. * NULL if no such service is found.
  1454. */
  1455. static origin_circuit_t *
  1456. find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
  1457. int desc_version)
  1458. {
  1459. origin_circuit_t *circ = NULL;
  1460. tor_assert(intro);
  1461. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1462. CIRCUIT_PURPOSE_S_INTRO))) {
  1463. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1464. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1465. circ->rend_data &&
  1466. circ->rend_data->rend_desc_version == desc_version) {
  1467. return circ;
  1468. }
  1469. }
  1470. circ = NULL;
  1471. while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
  1472. CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
  1473. if (!memcmp(circ->build_state->chosen_exit->identity_digest,
  1474. intro->extend_info->identity_digest, DIGEST_LEN) &&
  1475. circ->rend_data &&
  1476. circ->rend_data->rend_desc_version == desc_version) {
  1477. return circ;
  1478. }
  1479. }
  1480. return NULL;
  1481. }
  1482. /** Determine the responsible hidden service directories for the
  1483. * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
  1484. * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
  1485. * purposes. */
  1486. static void
  1487. directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
  1488. smartlist_t *descs, const char *service_id,
  1489. int seconds_valid)
  1490. {
  1491. int i, j, failed_upload = 0;
  1492. smartlist_t *responsible_dirs = smartlist_create();
  1493. smartlist_t *successful_uploads = smartlist_create();
  1494. routerstatus_t *hs_dir;
  1495. for (i = 0; i < smartlist_len(descs); i++) {
  1496. rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
  1497. /* Determine responsible dirs. */
  1498. if (hid_serv_get_responsible_directories(responsible_dirs,
  1499. desc->desc_id) < 0) {
  1500. log_warn(LD_REND, "Could not determine the responsible hidden service "
  1501. "directories to post descriptors to.");
  1502. smartlist_free(responsible_dirs);
  1503. smartlist_free(successful_uploads);
  1504. return;
  1505. }
  1506. for (j = 0; j < smartlist_len(responsible_dirs); j++) {
  1507. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1508. hs_dir = smartlist_get(responsible_dirs, j);
  1509. if (smartlist_digest_isin(renddesc->successful_uploads,
  1510. hs_dir->identity_digest))
  1511. /* Don't upload descriptor if we succeeded in doing so last time. */
  1512. continue;
  1513. if (!router_get_by_digest(hs_dir->identity_digest)) {
  1514. log_info(LD_REND, "Not sending publish request for v2 descriptor to "
  1515. "hidden service directory '%s'; we don't have its "
  1516. "router descriptor. Queuing for later upload.",
  1517. hs_dir->nickname);
  1518. failed_upload = -1;
  1519. continue;
  1520. }
  1521. /* Send publish request. */
  1522. directory_initiate_command_routerstatus(hs_dir,
  1523. DIR_PURPOSE_UPLOAD_RENDDESC_V2,
  1524. ROUTER_PURPOSE_GENERAL,
  1525. 1, NULL, desc->desc_str,
  1526. strlen(desc->desc_str), 0);
  1527. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1528. desc->desc_id, DIGEST_LEN);
  1529. log_info(LD_REND, "Sending publish request for v2 descriptor for "
  1530. "service '%s' with descriptor ID '%s' with validity "
  1531. "of %d seconds to hidden service directory '%s' on "
  1532. "port %d.",
  1533. safe_str(service_id),
  1534. safe_str(desc_id_base32),
  1535. seconds_valid,
  1536. hs_dir->nickname,
  1537. hs_dir->dir_port);
  1538. /* Remember successful upload to this router for next time. */
  1539. if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
  1540. smartlist_add(successful_uploads, hs_dir->identity_digest);
  1541. }
  1542. smartlist_clear(responsible_dirs);
  1543. }
  1544. if (!failed_upload) {
  1545. if (renddesc->successful_uploads) {
  1546. SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
  1547. smartlist_free(renddesc->successful_uploads);
  1548. renddesc->successful_uploads = NULL;
  1549. }
  1550. renddesc->all_uploads_performed = 1;
  1551. } else {
  1552. /* Remember which routers worked this time, so that we don't upload the
  1553. * descriptor to them again. */
  1554. if (!renddesc->successful_uploads)
  1555. renddesc->successful_uploads = smartlist_create();
  1556. SMARTLIST_FOREACH(successful_uploads, const char *, c, {
  1557. if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
  1558. char *hsdir_id = tor_memdup(c, DIGEST_LEN);
  1559. smartlist_add(renddesc->successful_uploads, hsdir_id);
  1560. }
  1561. });
  1562. }
  1563. smartlist_free(responsible_dirs);
  1564. smartlist_free(successful_uploads);
  1565. }
  1566. /** Encode and sign up-to-date v0 and/or v2 service descriptors for
  1567. * <b>service</b>, and upload it/them to all the dirservers/to the
  1568. * responsible hidden service directories.
  1569. */
  1570. static void
  1571. upload_service_descriptor(rend_service_t *service)
  1572. {
  1573. time_t now = time(NULL);
  1574. int rendpostperiod;
  1575. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1576. int uploaded = 0;
  1577. rendpostperiod = get_options()->RendPostPeriod;
  1578. /* Upload unversioned (v0) descriptor? */
  1579. if (service->descriptor_version == 0 &&
  1580. get_options()->PublishHidServDescriptors) {
  1581. char *desc;
  1582. size_t desc_len;
  1583. /* Encode the descriptor. */
  1584. if (rend_encode_service_descriptor(service->desc,
  1585. service->private_key,
  1586. &desc, &desc_len)<0) {
  1587. log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
  1588. "not uploading.");
  1589. return;
  1590. }
  1591. /* Post it to the dirservers */
  1592. rend_get_service_id(service->desc->pk, serviceid);
  1593. log_info(LD_REND, "Sending publish request for hidden service %s",
  1594. serviceid);
  1595. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
  1596. ROUTER_PURPOSE_GENERAL,
  1597. HIDSERV_AUTHORITY, desc, desc_len, 0);
  1598. tor_free(desc);
  1599. service->next_upload_time = now + rendpostperiod;
  1600. uploaded = 1;
  1601. }
  1602. /* Upload v2 descriptor? */
  1603. if (service->descriptor_version == 2 &&
  1604. get_options()->PublishHidServDescriptors) {
  1605. networkstatus_t *c = networkstatus_get_latest_consensus();
  1606. if (c && smartlist_len(c->routerstatus_list) > 0) {
  1607. int seconds_valid, i, j, num_descs;
  1608. smartlist_t *descs = smartlist_create();
  1609. smartlist_t *client_cookies = smartlist_create();
  1610. /* Either upload a single descriptor (including replicas) or one
  1611. * descriptor for each authorized client in case of authorization
  1612. * type 'stealth'. */
  1613. num_descs = service->auth_type == REND_STEALTH_AUTH ?
  1614. smartlist_len(service->clients) : 1;
  1615. for (j = 0; j < num_descs; j++) {
  1616. crypto_pk_env_t *client_key = NULL;
  1617. rend_authorized_client_t *client = NULL;
  1618. smartlist_clear(client_cookies);
  1619. switch (service->auth_type) {
  1620. case REND_NO_AUTH:
  1621. /* Do nothing here. */
  1622. break;
  1623. case REND_BASIC_AUTH:
  1624. SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
  1625. cl, smartlist_add(client_cookies, cl->descriptor_cookie));
  1626. break;
  1627. case REND_STEALTH_AUTH:
  1628. client = smartlist_get(service->clients, j);
  1629. client_key = client->client_key;
  1630. smartlist_add(client_cookies, client->descriptor_cookie);
  1631. break;
  1632. }
  1633. /* Encode the current descriptor. */
  1634. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1635. now, 0,
  1636. service->auth_type,
  1637. client_key,
  1638. client_cookies);
  1639. if (seconds_valid < 0) {
  1640. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1641. "descriptor; not uploading.");
  1642. smartlist_free(descs);
  1643. smartlist_free(client_cookies);
  1644. return;
  1645. }
  1646. /* Post the current descriptors to the hidden service directories. */
  1647. rend_get_service_id(service->desc->pk, serviceid);
  1648. log_info(LD_REND, "Sending publish request for hidden service %s",
  1649. serviceid);
  1650. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1651. seconds_valid);
  1652. /* Free memory for descriptors. */
  1653. for (i = 0; i < smartlist_len(descs); i++)
  1654. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1655. smartlist_clear(descs);
  1656. /* Update next upload time. */
  1657. if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
  1658. > rendpostperiod)
  1659. service->next_upload_time = now + rendpostperiod;
  1660. else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
  1661. service->next_upload_time = now + seconds_valid + 1;
  1662. else
  1663. service->next_upload_time = now + seconds_valid -
  1664. REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
  1665. /* Post also the next descriptors, if necessary. */
  1666. if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
  1667. seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
  1668. now, 1,
  1669. service->auth_type,
  1670. client_key,
  1671. client_cookies);
  1672. if (seconds_valid < 0) {
  1673. log_warn(LD_BUG, "Internal error: couldn't encode service "
  1674. "descriptor; not uploading.");
  1675. smartlist_free(descs);
  1676. smartlist_free(client_cookies);
  1677. return;
  1678. }
  1679. directory_post_to_hs_dir(service->desc, descs, serviceid,
  1680. seconds_valid);
  1681. /* Free memory for descriptors. */
  1682. for (i = 0; i < smartlist_len(descs); i++)
  1683. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1684. smartlist_clear(descs);
  1685. }
  1686. }
  1687. smartlist_free(descs);
  1688. smartlist_free(client_cookies);
  1689. uploaded = 1;
  1690. log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
  1691. }
  1692. }
  1693. /* If not uploaded, try again in one minute. */
  1694. if (!uploaded)
  1695. service->next_upload_time = now + 60;
  1696. /* Unmark dirty flag of this service. */
  1697. service->desc_is_dirty = 0;
  1698. }
  1699. /** For every service, check how many intro points it currently has, and:
  1700. * - Pick new intro points as necessary.
  1701. * - Launch circuits to any new intro points.
  1702. */
  1703. void
  1704. rend_services_introduce(void)
  1705. {
  1706. int i,j,r;
  1707. routerinfo_t *router;
  1708. rend_service_t *service;
  1709. rend_intro_point_t *intro;
  1710. int changed, prev_intro_nodes;
  1711. smartlist_t *intro_routers;
  1712. time_t now;
  1713. or_options_t *options = get_options();
  1714. intro_routers = smartlist_create();
  1715. now = time(NULL);
  1716. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1717. smartlist_clear(intro_routers);
  1718. service = smartlist_get(rend_service_list, i);
  1719. tor_assert(service);
  1720. changed = 0;
  1721. if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
  1722. /* One period has elapsed; we can try building circuits again. */
  1723. service->intro_period_started = now;
  1724. service->n_intro_circuits_launched = 0;
  1725. } else if (service->n_intro_circuits_launched >=
  1726. MAX_INTRO_CIRCS_PER_PERIOD) {
  1727. /* We have failed too many times in this period; wait for the next
  1728. * one before we try again. */
  1729. continue;
  1730. }
  1731. /* Find out which introduction points we have in progress for this
  1732. service. */
  1733. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1734. intro = smartlist_get(service->intro_nodes, j);
  1735. router = router_get_by_digest(intro->extend_info->identity_digest);
  1736. if (!router || !find_intro_circuit(intro, service->pk_digest,
  1737. service->descriptor_version)) {
  1738. log_info(LD_REND,"Giving up on %s as intro point for %s.",
  1739. intro->extend_info->nickname, service->service_id);
  1740. if (service->desc) {
  1741. SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
  1742. dintro, {
  1743. if (!memcmp(dintro->extend_info->identity_digest,
  1744. intro->extend_info->identity_digest, DIGEST_LEN)) {
  1745. log_info(LD_REND, "The intro point we are giving up on was "
  1746. "included in the last published descriptor. "
  1747. "Marking current descriptor as dirty.");
  1748. service->desc_is_dirty = now;
  1749. }
  1750. });
  1751. }
  1752. rend_intro_point_free(intro);
  1753. smartlist_del(service->intro_nodes,j--);
  1754. changed = 1;
  1755. }
  1756. if (router)
  1757. smartlist_add(intro_routers, router);
  1758. }
  1759. /* We have enough intro points, and the intro points we thought we had were
  1760. * all connected.
  1761. */
  1762. if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
  1763. /* We have all our intro points! Start a fresh period and reset the
  1764. * circuit count. */
  1765. service->intro_period_started = now;
  1766. service->n_intro_circuits_launched = 0;
  1767. continue;
  1768. }
  1769. /* Remember how many introduction circuits we started with. */
  1770. prev_intro_nodes = smartlist_len(service->intro_nodes);
  1771. /* We have enough directory information to start establishing our
  1772. * intro points. We want to end up with three intro points, but if
  1773. * we're just starting, we launch five and pick the first three that
  1774. * complete.
  1775. *
  1776. * The ones after the first three will be converted to 'general'
  1777. * internal circuits in rend_service_intro_has_opened(), and then
  1778. * we'll drop them from the list of intro points next time we
  1779. * go through the above "find out which introduction points we have
  1780. * in progress" loop. */
  1781. #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
  1782. for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
  1783. NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
  1784. router_crn_flags_t flags = CRN_NEED_UPTIME;
  1785. if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
  1786. flags |= CRN_ALLOW_INVALID;
  1787. router = router_choose_random_node(NULL, intro_routers,
  1788. options->ExcludeNodes, flags);
  1789. if (!router) {
  1790. log_warn(LD_REND,
  1791. "Could only establish %d introduction points for %s.",
  1792. smartlist_len(service->intro_nodes), service->service_id);
  1793. break;
  1794. }
  1795. changed = 1;
  1796. smartlist_add(intro_routers, router);
  1797. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1798. intro->extend_info = extend_info_from_router(router);
  1799. if (service->descriptor_version == 2) {
  1800. intro->intro_key = crypto_new_pk_env();
  1801. tor_assert(!crypto_pk_generate_key(intro->intro_key));
  1802. }
  1803. smartlist_add(service->intro_nodes, intro);
  1804. log_info(LD_REND, "Picked router %s as an intro point for %s.",
  1805. router->nickname, service->service_id);
  1806. }
  1807. /* If there's no need to launch new circuits, stop here. */
  1808. if (!changed)
  1809. continue;
  1810. /* Establish new introduction points. */
  1811. for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
  1812. intro = smartlist_get(service->intro_nodes, j);
  1813. r = rend_service_launch_establish_intro(service, intro);
  1814. if (r<0) {
  1815. log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
  1816. intro->extend_info->nickname, service->service_id);
  1817. }
  1818. }
  1819. }
  1820. smartlist_free(intro_routers);
  1821. }
  1822. /** Regenerate and upload rendezvous service descriptors for all
  1823. * services, if necessary. If the descriptor has been dirty enough
  1824. * for long enough, definitely upload; else only upload when the
  1825. * periodic timeout has expired.
  1826. *
  1827. * For the first upload, pick a random time between now and two periods
  1828. * from now, and pick it independently for each service.
  1829. */
  1830. void
  1831. rend_consider_services_upload(time_t now)
  1832. {
  1833. int i;
  1834. rend_service_t *service;
  1835. int rendpostperiod = get_options()->RendPostPeriod;
  1836. if (!get_options()->PublishHidServDescriptors)
  1837. return;
  1838. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1839. service = smartlist_get(rend_service_list, i);
  1840. if (!service->next_upload_time) { /* never been uploaded yet */
  1841. /* The fixed lower bound of 30 seconds ensures that the descriptor
  1842. * is stable before being published. See comment below. */
  1843. service->next_upload_time =
  1844. now + 30 + crypto_rand_int(2*rendpostperiod);
  1845. }
  1846. if (service->next_upload_time < now ||
  1847. (service->desc_is_dirty &&
  1848. service->desc_is_dirty < now-30)) {
  1849. /* if it's time, or if the directory servers have a wrong service
  1850. * descriptor and ours has been stable for 30 seconds, upload a
  1851. * new one of each format. */
  1852. rend_service_update_descriptor(service);
  1853. upload_service_descriptor(service);
  1854. }
  1855. }
  1856. }
  1857. /** True if the list of available router descriptors might have changed so
  1858. * that we should have a look whether we can republish previously failed
  1859. * rendezvous service descriptors. */
  1860. static int consider_republishing_rend_descriptors = 1;
  1861. /** Called when our internal view of the directory has changed, so that we
  1862. * might have router descriptors of hidden service directories available that
  1863. * we did not have before. */
  1864. void
  1865. rend_hsdir_routers_changed(void)
  1866. {
  1867. consider_republishing_rend_descriptors = 1;
  1868. }
  1869. /** Consider republication of v2 rendezvous service descriptors that failed
  1870. * previously, but without regenerating descriptor contents.
  1871. */
  1872. void
  1873. rend_consider_descriptor_republication(void)
  1874. {
  1875. int i;
  1876. rend_service_t *service;
  1877. if (!consider_republishing_rend_descriptors)
  1878. return;
  1879. consider_republishing_rend_descriptors = 0;
  1880. if (!get_options()->PublishHidServDescriptors)
  1881. return;
  1882. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1883. service = smartlist_get(rend_service_list, i);
  1884. if (service->descriptor_version && service->desc &&
  1885. !service->desc->all_uploads_performed) {
  1886. /* If we failed in uploading a descriptor last time, try again *without*
  1887. * updating the descriptor's contents. */
  1888. upload_service_descriptor(service);
  1889. }
  1890. }
  1891. }
  1892. /** Log the status of introduction points for all rendezvous services
  1893. * at log severity <b>severity</b>.
  1894. */
  1895. void
  1896. rend_service_dump_stats(int severity)
  1897. {
  1898. int i,j;
  1899. rend_service_t *service;
  1900. rend_intro_point_t *intro;
  1901. const char *safe_name;
  1902. origin_circuit_t *circ;
  1903. for (i=0; i < smartlist_len(rend_service_list); ++i) {
  1904. service = smartlist_get(rend_service_list, i);
  1905. log(severity, LD_GENERAL, "Service configured in \"%s\":",
  1906. service->directory);
  1907. for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
  1908. intro = smartlist_get(service->intro_nodes, j);
  1909. safe_name = safe_str(intro->extend_info->nickname);
  1910. circ = find_intro_circuit(intro, service->pk_digest,
  1911. service->descriptor_version);
  1912. if (!circ) {
  1913. log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
  1914. j, safe_name);
  1915. continue;
  1916. }
  1917. log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
  1918. j, safe_name, circuit_state_to_string(circ->_base.state));
  1919. }
  1920. }
  1921. }
  1922. /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
  1923. * 'circ', and look up the port and address based on conn-\>port.
  1924. * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
  1925. * or 0 for success.
  1926. */
  1927. int
  1928. rend_service_set_connection_addr_port(edge_connection_t *conn,
  1929. origin_circuit_t *circ)
  1930. {
  1931. rend_service_t *service;
  1932. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1933. smartlist_t *matching_ports;
  1934. rend_service_port_config_t *chosen_port;
  1935. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
  1936. tor_assert(circ->rend_data);
  1937. log_debug(LD_REND,"beginning to hunt for addr/port");
  1938. base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
  1939. circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
  1940. service = rend_service_get_by_pk_digest_and_version(
  1941. circ->rend_data->rend_pk_digest,
  1942. circ->rend_data->rend_desc_version);
  1943. if (!service) {
  1944. log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
  1945. "rendezvous circuit %d; closing.",
  1946. serviceid, circ->_base.n_circ_id);
  1947. return -1;
  1948. }
  1949. matching_ports = smartlist_create();
  1950. SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
  1951. {
  1952. if (conn->_base.port == p->virtual_port) {
  1953. smartlist_add(matching_ports, p);
  1954. }
  1955. });
  1956. chosen_port = smartlist_choose(matching_ports);
  1957. smartlist_free(matching_ports);
  1958. if (chosen_port) {
  1959. tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
  1960. conn->_base.port = chosen_port->real_port;
  1961. return 0;
  1962. }
  1963. log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
  1964. conn->_base.port,serviceid);
  1965. return -1;
  1966. }