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