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