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