Issues with router_get_by_nickname() (3)
[tor/rransom.git] / src / or / rendservice.c
blob289d64d399bb683232d2183418634be20abfb11f
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"
12 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
13 const char *pk_digest,
14 int desc_version);
16 /** Represents the mapping from a virtual port of a rendezvous service to
17 * a real port on some IP.
19 typedef struct rend_service_port_config_t {
20 uint16_t virtual_port;
21 uint16_t real_port;
22 tor_addr_t real_addr;
23 } rend_service_port_config_t;
25 /** Try to maintain this many intro points per service if possible. */
26 #define NUM_INTRO_POINTS 3
28 /** If we can't build our intro circuits, don't retry for this long. */
29 #define INTRO_CIRC_RETRY_PERIOD (60*5)
30 /** Don't try to build more than this many circuits before giving up
31 * for a while.*/
32 #define MAX_INTRO_CIRCS_PER_PERIOD 10
33 /** How many times will a hidden service operator attempt to connect to
34 * a requested rendezvous point before giving up? */
35 #define MAX_REND_FAILURES 30
36 /** How many seconds should we spend trying to connect to a requested
37 * rendezvous point before giving up? */
38 #define MAX_REND_TIMEOUT 30
40 /** Represents a single hidden service running at this OP. */
41 typedef struct rend_service_t {
42 /* Fields specified in config file */
43 char *directory; /**< where in the filesystem it stores it */
44 smartlist_t *ports; /**< List of rend_service_port_config_t */
45 int descriptor_version; /**< Rendezvous descriptor version that will be
46 * published. */
47 rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
48 * authorization is performed. */
49 smartlist_t *clients; /**< List of rend_authorized_client_t's of
50 * clients that may access our service. Can be NULL
51 * if no client authorization is performed. */
52 /* Other fields */
53 crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
54 char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
55 * '.onion' */
56 char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
57 smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
58 * or are trying to establish. */
59 time_t intro_period_started; /**< Start of the current period to build
60 * introduction points. */
61 int n_intro_circuits_launched; /**< count of intro circuits we have
62 * established in this period. */
63 rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
64 time_t desc_is_dirty; /**< Time at which changes to the hidden service
65 * descriptor content occurred, or 0 if it's
66 * up-to-date. */
67 time_t next_upload_time; /**< Scheduled next hidden service descriptor
68 * upload time. */
69 /** Map from digests of Diffie-Hellman values INTRODUCE2 to time_t of when
70 * they were received; used to prevent replays. */
71 digestmap_t *accepted_intros;
72 /** Time at which we last removed expired values from accepted_intros. */
73 time_t last_cleaned_accepted_intros;
74 } rend_service_t;
76 /** A list of rend_service_t's for services run on this OP.
78 static smartlist_t *rend_service_list = NULL;
80 /** Return the number of rendezvous services we have configured. */
81 int
82 num_rend_services(void)
84 if (!rend_service_list)
85 return 0;
86 return smartlist_len(rend_service_list);
89 /** Helper: free storage held by a single service authorized client entry. */
90 static void
91 rend_authorized_client_free(rend_authorized_client_t *client)
93 if (!client) return;
94 if (client->client_key)
95 crypto_free_pk_env(client->client_key);
96 tor_free(client->client_name);
97 tor_free(client);
100 /** Helper for strmap_free. */
101 static void
102 rend_authorized_client_strmap_item_free(void *authorized_client)
104 rend_authorized_client_free(authorized_client);
107 /** Release the storage held by <b>service</b>.
109 static void
110 rend_service_free(rend_service_t *service)
112 if (!service) return;
113 tor_free(service->directory);
114 SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
115 smartlist_free(service->ports);
116 if (service->private_key)
117 crypto_free_pk_env(service->private_key);
118 if (service->intro_nodes) {
119 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
120 rend_intro_point_free(intro););
121 smartlist_free(service->intro_nodes);
123 if (service->desc)
124 rend_service_descriptor_free(service->desc);
125 if (service->clients) {
126 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
127 rend_authorized_client_free(c););
128 smartlist_free(service->clients);
130 if (service->accepted_intros)
131 digestmap_free(service->accepted_intros, _tor_free);
132 tor_free(service);
135 /** Release all the storage held in rend_service_list.
137 void
138 rend_service_free_all(void)
140 if (!rend_service_list) {
141 return;
143 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
144 rend_service_free(ptr));
145 smartlist_free(rend_service_list);
146 rend_service_list = NULL;
149 /** Validate <b>service</b> and add it to rend_service_list if possible.
151 static void
152 rend_add_service(rend_service_t *service)
154 int i;
155 rend_service_port_config_t *p;
157 service->intro_nodes = smartlist_create();
159 /* If the service is configured to publish unversioned (v0) and versioned
160 * descriptors (v2 or higher), split it up into two separate services
161 * (unless it is configured to perform client authorization). */
162 if (service->descriptor_version == -1) {
163 if (service->auth_type == REND_NO_AUTH) {
164 rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
165 v0_service->directory = tor_strdup(service->directory);
166 v0_service->ports = smartlist_create();
167 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
168 rend_service_port_config_t *copy =
169 tor_malloc_zero(sizeof(rend_service_port_config_t));
170 memcpy(copy, p, sizeof(rend_service_port_config_t));
171 smartlist_add(v0_service->ports, copy);
173 v0_service->intro_period_started = service->intro_period_started;
174 v0_service->descriptor_version = 0; /* Unversioned descriptor. */
175 v0_service->auth_type = REND_NO_AUTH;
176 rend_add_service(v0_service);
179 service->descriptor_version = 2; /* Versioned descriptor. */
182 if (service->auth_type != REND_NO_AUTH && !service->descriptor_version) {
183 log_warn(LD_CONFIG, "Hidden service with client authorization and "
184 "version 0 descriptors configured; ignoring.");
185 rend_service_free(service);
186 return;
189 if (service->auth_type != REND_NO_AUTH &&
190 smartlist_len(service->clients) == 0) {
191 log_warn(LD_CONFIG, "Hidden service with client authorization but no "
192 "clients; ignoring.");
193 rend_service_free(service);
194 return;
197 if (!smartlist_len(service->ports)) {
198 log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
199 rend_service_free(service);
200 } else {
201 smartlist_add(rend_service_list, service);
202 log_debug(LD_REND,"Configuring service with directory \"%s\"",
203 service->directory);
204 for (i = 0; i < smartlist_len(service->ports); ++i) {
205 p = smartlist_get(service->ports, i);
206 log_debug(LD_REND,"Service maps port %d to %s:%d",
207 p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
212 /** Parses a real-port to virtual-port mapping and returns a new
213 * rend_service_port_config_t.
215 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
217 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
219 static rend_service_port_config_t *
220 parse_port_config(const char *string)
222 smartlist_t *sl;
223 int virtport;
224 int realport;
225 uint16_t p;
226 tor_addr_t addr;
227 const char *addrport;
228 rend_service_port_config_t *result = NULL;
230 sl = smartlist_create();
231 smartlist_split_string(sl, string, " ",
232 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
233 if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
234 log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
235 goto err;
238 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
239 if (!virtport) {
240 log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
241 "configuration", escaped(smartlist_get(sl,0)));
242 goto err;
245 if (smartlist_len(sl) == 1) {
246 /* No addr:port part; use default. */
247 realport = virtport;
248 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
249 } else {
250 addrport = smartlist_get(sl,1);
251 if (strchr(addrport, ':') || strchr(addrport, '.')) {
252 if (tor_addr_port_parse(addrport, &addr, &p)<0) {
253 log_warn(LD_CONFIG,"Unparseable address in hidden service port "
254 "configuration.");
255 goto err;
257 realport = p?p:virtport;
258 } else {
259 /* No addr:port, no addr -- must be port. */
260 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
261 if (!realport) {
262 log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
263 "service port configuration.", escaped(addrport));
264 goto err;
266 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
270 result = tor_malloc(sizeof(rend_service_port_config_t));
271 result->virtual_port = virtport;
272 result->real_port = realport;
273 tor_addr_copy(&result->real_addr, &addr);
274 err:
275 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
276 smartlist_free(sl);
277 return result;
280 /** Set up rend_service_list, based on the values of HiddenServiceDir and
281 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
282 * failure. (If <b>validate_only</b> is set, parse, warn and return as
283 * normal, but don't actually change the configured services.)
286 rend_config_services(or_options_t *options, int validate_only)
288 config_line_t *line;
289 rend_service_t *service = NULL;
290 rend_service_port_config_t *portcfg;
291 smartlist_t *old_service_list = NULL;
293 if (!validate_only) {
294 old_service_list = rend_service_list;
295 rend_service_list = smartlist_create();
298 for (line = options->RendConfigLines; line; line = line->next) {
299 if (!strcasecmp(line->key, "HiddenServiceDir")) {
300 if (service) {
301 if (validate_only)
302 rend_service_free(service);
303 else
304 rend_add_service(service);
306 service = tor_malloc_zero(sizeof(rend_service_t));
307 service->directory = tor_strdup(line->value);
308 service->ports = smartlist_create();
309 service->intro_period_started = time(NULL);
310 service->descriptor_version = -1; /**< All descriptor versions. */
311 continue;
313 if (!service) {
314 log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
315 line->key);
316 rend_service_free(service);
317 return -1;
319 if (!strcasecmp(line->key, "HiddenServicePort")) {
320 portcfg = parse_port_config(line->value);
321 if (!portcfg) {
322 rend_service_free(service);
323 return -1;
325 smartlist_add(service->ports, portcfg);
326 } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
327 /* Parse auth type and comma-separated list of client names and add a
328 * rend_authorized_client_t for each client to the service's list
329 * of authorized clients. */
330 smartlist_t *type_names_split, *clients;
331 const char *authname;
332 int num_clients;
333 if (service->auth_type != REND_NO_AUTH) {
334 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
335 "lines for a single service.");
336 rend_service_free(service);
337 return -1;
339 type_names_split = smartlist_create();
340 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
341 if (smartlist_len(type_names_split) < 1) {
342 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
343 "should have been prevented when parsing the "
344 "configuration.");
345 smartlist_free(type_names_split);
346 rend_service_free(service);
347 return -1;
349 authname = smartlist_get(type_names_split, 0);
350 if (!strcasecmp(authname, "basic")) {
351 service->auth_type = REND_BASIC_AUTH;
352 } else if (!strcasecmp(authname, "stealth")) {
353 service->auth_type = REND_STEALTH_AUTH;
354 } else {
355 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
356 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
357 "are recognized.",
358 (char *) smartlist_get(type_names_split, 0));
359 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
360 smartlist_free(type_names_split);
361 rend_service_free(service);
362 return -1;
364 service->clients = smartlist_create();
365 if (smartlist_len(type_names_split) < 2) {
366 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
367 "auth-type '%s', but no client names.",
368 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
369 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
370 smartlist_free(type_names_split);
371 continue;
373 clients = smartlist_create();
374 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
375 ",", SPLIT_SKIP_SPACE, 0);
376 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
377 smartlist_free(type_names_split);
378 /* Remove duplicate client names. */
379 num_clients = smartlist_len(clients);
380 smartlist_sort_strings(clients);
381 smartlist_uniq_strings(clients);
382 if (smartlist_len(clients) < num_clients) {
383 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
384 "duplicate client name(s); removing.",
385 num_clients - smartlist_len(clients));
386 num_clients = smartlist_len(clients);
388 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
390 rend_authorized_client_t *client;
391 size_t len = strlen(client_name);
392 if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
393 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
394 "illegal client name: '%s'. Length must be "
395 "between 1 and %d characters.",
396 client_name, REND_CLIENTNAME_MAX_LEN);
397 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
398 smartlist_free(clients);
399 rend_service_free(service);
400 return -1;
402 if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
403 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
404 "illegal client name: '%s'. Valid "
405 "characters are [A-Za-z0-9+-_].",
406 client_name);
407 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
408 smartlist_free(clients);
409 rend_service_free(service);
410 return -1;
412 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
413 client->client_name = tor_strdup(client_name);
414 smartlist_add(service->clients, client);
415 log_debug(LD_REND, "Adding client name '%s'", client_name);
417 SMARTLIST_FOREACH_END(client_name);
418 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
419 smartlist_free(clients);
420 /* Ensure maximum number of clients. */
421 if ((service->auth_type == REND_BASIC_AUTH &&
422 smartlist_len(service->clients) > 512) ||
423 (service->auth_type == REND_STEALTH_AUTH &&
424 smartlist_len(service->clients) > 16)) {
425 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
426 "client authorization entries, but only a "
427 "maximum of %d entries is allowed for "
428 "authorization type '%s'.",
429 smartlist_len(service->clients),
430 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
431 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
432 rend_service_free(service);
433 return -1;
435 } else {
436 smartlist_t *versions;
437 char *version_str;
438 int i, version, ver_ok=1, versions_bitmask = 0;
439 tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
440 versions = smartlist_create();
441 smartlist_split_string(versions, line->value, ",",
442 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
443 for (i = 0; i < smartlist_len(versions); i++) {
444 version_str = smartlist_get(versions, i);
445 if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
446 log_warn(LD_CONFIG,
447 "HiddenServiceVersion can only be 0 and/or 2.");
448 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
449 smartlist_free(versions);
450 rend_service_free(service);
451 return -1;
453 version = (int)tor_parse_long(version_str, 10, 0, INT_MAX, &ver_ok,
454 NULL);
455 if (!ver_ok)
456 continue;
457 versions_bitmask |= 1 << version;
459 /* If exactly one version is set, change descriptor_version to that
460 * value; otherwise leave it at -1. */
461 if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
462 if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
463 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
464 smartlist_free(versions);
467 if (service) {
468 if (validate_only)
469 rend_service_free(service);
470 else
471 rend_add_service(service);
474 /* If this is a reload and there were hidden services configured before,
475 * keep the introduction points that are still needed and close the
476 * other ones. */
477 if (old_service_list && !validate_only) {
478 smartlist_t *surviving_services = smartlist_create();
479 circuit_t *circ;
481 /* Copy introduction points to new services. */
482 /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
483 * probably ok? */
484 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
485 SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
486 if (!strcmp(old->directory, new->directory) &&
487 old->descriptor_version == new->descriptor_version) {
488 smartlist_add_all(new->intro_nodes, old->intro_nodes);
489 smartlist_clear(old->intro_nodes);
490 smartlist_add(surviving_services, old);
491 break;
496 /* Close introduction circuits of services we don't serve anymore. */
497 /* XXXX it would be nicer if we had a nicer abstraction to use here,
498 * so we could just iterate over the list of services to close, but
499 * once again, this isn't critical-path code. */
500 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
501 if (!circ->marked_for_close &&
502 circ->state == CIRCUIT_STATE_OPEN &&
503 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
504 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
505 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
506 int keep_it = 0;
507 tor_assert(oc->rend_data);
508 SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
509 if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
510 DIGEST_LEN) &&
511 ptr->descriptor_version == oc->rend_data->rend_desc_version) {
512 keep_it = 1;
513 break;
516 if (keep_it)
517 continue;
518 log_info(LD_REND, "Closing intro point %s for service %s version %d.",
519 safe_str(oc->build_state->chosen_exit->nickname),
520 oc->rend_data->onion_address,
521 oc->rend_data->rend_desc_version);
522 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
523 /* XXXX Is there another reason we should use here? */
526 smartlist_free(surviving_services);
527 SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
528 rend_service_free(ptr));
529 smartlist_free(old_service_list);
532 return 0;
535 /** Replace the old value of <b>service</b>-\>desc with one that reflects
536 * the other fields in service.
538 static void
539 rend_service_update_descriptor(rend_service_t *service)
541 rend_service_descriptor_t *d;
542 origin_circuit_t *circ;
543 int i;
544 if (service->desc) {
545 rend_service_descriptor_free(service->desc);
546 service->desc = NULL;
548 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
549 d->pk = crypto_pk_dup_key(service->private_key);
550 d->timestamp = time(NULL);
551 d->version = service->descriptor_version;
552 d->intro_nodes = smartlist_create();
553 /* Support intro protocols 2 and 3. */
554 d->protocols = (1 << 2) + (1 << 3);
556 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
557 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
558 rend_intro_point_t *intro_desc;
559 circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
560 if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
561 continue;
563 /* We have an entirely established intro circuit. */
564 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
565 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
566 if (intro_svc->intro_key)
567 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
568 smartlist_add(d->intro_nodes, intro_desc);
572 /** Load and/or generate private keys for all hidden services, possibly
573 * including keys for client authorization. Return 0 on success, -1 on
574 * failure.
577 rend_service_load_keys(void)
579 int r = 0;
580 char fname[512];
581 char buf[1500];
583 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
584 if (s->private_key)
585 continue;
586 log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
587 s->directory);
589 /* Check/create directory */
590 if (check_private_dir(s->directory, CPD_CREATE) < 0)
591 return -1;
593 /* Load key */
594 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
595 strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
596 >= sizeof(fname)) {
597 log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
598 s->directory);
599 return -1;
601 s->private_key = init_key_from_file(fname, 1, LOG_ERR);
602 if (!s->private_key)
603 return -1;
605 /* Create service file */
606 if (rend_get_service_id(s->private_key, s->service_id)<0) {
607 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
608 return -1;
610 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
611 log_warn(LD_BUG, "Couldn't compute hash of public key.");
612 return -1;
614 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
615 strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
616 >= sizeof(fname)) {
617 log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
618 " \"%s\".", s->directory);
619 return -1;
621 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
622 if (write_str_to_file(fname,buf,0)<0) {
623 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
624 return -1;
627 /* If client authorization is configured, load or generate keys. */
628 if (s->auth_type != REND_NO_AUTH) {
629 char *client_keys_str = NULL;
630 strmap_t *parsed_clients = strmap_new();
631 char cfname[512];
632 FILE *cfile, *hfile;
633 open_file_t *open_cfile = NULL, *open_hfile = NULL;
635 /* Load client keys and descriptor cookies, if available. */
636 if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
637 s->directory)<0) {
638 log_warn(LD_CONFIG, "Directory name too long to store client keys "
639 "file: \"%s\".", s->directory);
640 goto err;
642 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
643 if (client_keys_str) {
644 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
645 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
646 "be parsed.");
647 goto err;
648 } else {
649 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
650 strmap_size(parsed_clients));
651 tor_free(client_keys_str);
655 /* Prepare client_keys and hostname files. */
656 if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
657 0600, &open_cfile))) {
658 log_warn(LD_CONFIG, "Could not open client_keys file %s",
659 escaped(cfname));
660 goto err;
662 if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
663 0600, &open_hfile))) {
664 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
665 goto err;
668 /* Either use loaded keys for configured clients or generate new
669 * ones if a client is new. */
670 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
672 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
673 char service_id[16+1];
674 rend_authorized_client_t *parsed =
675 strmap_get(parsed_clients, client->client_name);
676 int written;
677 size_t len;
678 /* Copy descriptor cookie from parsed entry or create new one. */
679 if (parsed) {
680 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
681 REND_DESC_COOKIE_LEN);
682 } else {
683 crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
685 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
686 client->descriptor_cookie,
687 REND_DESC_COOKIE_LEN) < 0) {
688 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
689 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
690 return -1;
692 /* Copy client key from parsed entry or create new one if required. */
693 if (parsed && parsed->client_key) {
694 client->client_key = crypto_pk_dup_key(parsed->client_key);
695 } else if (s->auth_type == REND_STEALTH_AUTH) {
696 /* Create private key for client. */
697 crypto_pk_env_t *prkey = NULL;
698 if (!(prkey = crypto_new_pk_env())) {
699 log_warn(LD_BUG,"Error constructing client key");
700 goto err;
702 if (crypto_pk_generate_key(prkey)) {
703 log_warn(LD_BUG,"Error generating client key");
704 crypto_free_pk_env(prkey);
705 goto err;
707 if (crypto_pk_check_key(prkey) <= 0) {
708 log_warn(LD_BUG,"Generated client key seems invalid");
709 crypto_free_pk_env(prkey);
710 goto err;
712 client->client_key = prkey;
714 /* Add entry to client_keys file. */
715 desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
716 written = tor_snprintf(buf, sizeof(buf),
717 "client-name %s\ndescriptor-cookie %s\n",
718 client->client_name, desc_cook_out);
719 if (written < 0) {
720 log_warn(LD_BUG, "Could not write client entry.");
721 goto err;
723 if (client->client_key) {
724 char *client_key_out = NULL;
725 crypto_pk_write_private_key_to_string(client->client_key,
726 &client_key_out, &len);
727 if (rend_get_service_id(client->client_key, service_id)<0) {
728 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
729 tor_free(client_key_out);
730 goto err;
732 written = tor_snprintf(buf + written, sizeof(buf) - written,
733 "client-key\n%s", client_key_out);
734 tor_free(client_key_out);
735 if (written < 0) {
736 log_warn(LD_BUG, "Could not write client entry.");
737 goto err;
741 if (fputs(buf, cfile) < 0) {
742 log_warn(LD_FS, "Could not append client entry to file: %s",
743 strerror(errno));
744 goto err;
747 /* Add line to hostname file. */
748 if (s->auth_type == REND_BASIC_AUTH) {
749 /* Remove == signs (newline has been removed above). */
750 desc_cook_out[strlen(desc_cook_out)-2] = '\0';
751 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
752 s->service_id, desc_cook_out, client->client_name);
753 } else {
754 char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
755 memcpy(extended_desc_cookie, client->descriptor_cookie,
756 REND_DESC_COOKIE_LEN);
757 extended_desc_cookie[REND_DESC_COOKIE_LEN] =
758 ((int)s->auth_type - 1) << 4;
759 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
760 extended_desc_cookie,
761 REND_DESC_COOKIE_LEN+1) < 0) {
762 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
763 goto err;
765 desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
766 newline. */
767 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
768 service_id, desc_cook_out, client->client_name);
771 if (fputs(buf, hfile)<0) {
772 log_warn(LD_FS, "Could not append host entry to file: %s",
773 strerror(errno));
774 goto err;
777 SMARTLIST_FOREACH_END(client);
779 goto done;
780 err:
781 r = -1;
782 done:
783 tor_free(client_keys_str);
784 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
785 if (r<0) {
786 if (open_cfile)
787 abort_writing_to_file(open_cfile);
788 if (open_hfile)
789 abort_writing_to_file(open_hfile);
790 return r;
791 } else {
792 finish_writing_to_file(open_cfile);
793 finish_writing_to_file(open_hfile);
796 } SMARTLIST_FOREACH_END(s);
797 return r;
800 /** Return the service whose public key has a digest of <b>digest</b> and
801 * which publishes the given descriptor <b>version</b>. Return NULL if no
802 * such service exists.
804 static rend_service_t *
805 rend_service_get_by_pk_digest_and_version(const char* digest,
806 uint8_t version)
808 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
809 if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
810 s->descriptor_version == version) return s);
811 return NULL;
814 /** Return 1 if any virtual port in <b>service</b> wants a circuit
815 * to have good uptime. Else return 0.
817 static int
818 rend_service_requires_uptime(rend_service_t *service)
820 int i;
821 rend_service_port_config_t *p;
823 for (i=0; i < smartlist_len(service->ports); ++i) {
824 p = smartlist_get(service->ports, i);
825 if (smartlist_string_num_isin(get_options()->LongLivedPorts,
826 p->virtual_port))
827 return 1;
829 return 0;
832 /** Check client authorization of a given <b>descriptor_cookie</b> for
833 * <b>service</b>. Return 1 for success and 0 for failure. */
834 static int
835 rend_check_authorization(rend_service_t *service,
836 const char *descriptor_cookie)
838 rend_authorized_client_t *auth_client = NULL;
839 tor_assert(service);
840 tor_assert(descriptor_cookie);
841 if (!service->clients) {
842 log_warn(LD_BUG, "Can't check authorization for a service that has no "
843 "authorized clients configured.");
844 return 0;
847 /* Look up client authorization by descriptor cookie. */
848 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
849 if (!memcmp(client->descriptor_cookie, descriptor_cookie,
850 REND_DESC_COOKIE_LEN)) {
851 auth_client = client;
852 break;
855 if (!auth_client) {
856 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
857 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
858 descriptor_cookie, REND_DESC_COOKIE_LEN);
859 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
860 "Dropping cell!",
861 descriptor_cookie_base64);
862 return 0;
865 /* Allow the request. */
866 log_debug(LD_REND, "Client %s authorized for service %s.",
867 auth_client->client_name, service->service_id);
868 return 1;
871 /** Remove elements from <b>service</b>'s replay cache that are old enough to
872 * be noticed by timestamp checking. */
873 static void
874 clean_accepted_intros(rend_service_t *service, time_t now)
876 const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
878 service->last_cleaned_accepted_intros = now;
879 if (!service->accepted_intros)
880 return;
882 DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
883 if (*t < cutoff) {
884 tor_free(t);
885 MAP_DEL_CURRENT(digest);
887 } DIGESTMAP_FOREACH_END;
890 /******
891 * Handle cells
892 ******/
894 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
895 * rendezvous point.
898 rend_service_introduce(origin_circuit_t *circuit, const char *request,
899 size_t request_len)
901 char *ptr, *r_cookie;
902 extend_info_t *extend_info = NULL;
903 char buf[RELAY_PAYLOAD_SIZE];
904 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
905 rend_service_t *service;
906 int r, i, v3_shift = 0;
907 size_t len, keylen;
908 crypto_dh_env_t *dh = NULL;
909 origin_circuit_t *launched = NULL;
910 crypt_path_t *cpath = NULL;
911 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
912 char hexcookie[9];
913 int circ_needs_uptime;
914 int reason = END_CIRC_REASON_TORPROTOCOL;
915 crypto_pk_env_t *intro_key;
916 char intro_key_digest[DIGEST_LEN];
917 int auth_type;
918 size_t auth_len = 0;
919 char auth_data[REND_DESC_COOKIE_LEN];
920 crypto_digest_env_t *digest = NULL;
921 time_t now = time(NULL);
922 char diffie_hellman_hash[DIGEST_LEN];
923 time_t *access_time;
924 tor_assert(circuit->rend_data);
926 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
927 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
928 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
929 escaped(serviceid), circuit->_base.n_circ_id);
931 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
932 log_warn(LD_PROTOCOL,
933 "Got an INTRODUCE2 over a non-introduction circuit %d.",
934 circuit->_base.n_circ_id);
935 return -1;
938 /* min key length plus digest length plus nickname length */
939 if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
940 DH_KEY_LEN+42) {
941 log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
942 circuit->_base.n_circ_id);
943 return -1;
946 /* look up service depending on circuit. */
947 service = rend_service_get_by_pk_digest_and_version(
948 circuit->rend_data->rend_pk_digest,
949 circuit->rend_data->rend_desc_version);
950 if (!service) {
951 log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
952 escaped(serviceid));
953 return -1;
956 /* if descriptor version is 2, use intro key instead of service key. */
957 if (circuit->rend_data->rend_desc_version == 0) {
958 intro_key = service->private_key;
959 } else {
960 intro_key = circuit->intro_key;
963 /* first DIGEST_LEN bytes of request is intro or service pk digest */
964 crypto_pk_get_digest(intro_key, intro_key_digest);
965 if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
966 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
967 request, REND_SERVICE_ID_LEN);
968 log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
969 escaped(serviceid));
970 return -1;
973 keylen = crypto_pk_keysize(intro_key);
974 if (request_len < keylen+DIGEST_LEN) {
975 log_warn(LD_PROTOCOL,
976 "PK-encrypted portion of INTRODUCE2 cell was truncated.");
977 return -1;
979 /* Next N bytes is encrypted with service key */
980 note_crypto_pk_op(REND_SERVER);
981 r = crypto_pk_private_hybrid_decrypt(
982 intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
983 PK_PKCS1_OAEP_PADDING,1);
984 if (r<0) {
985 log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
986 return -1;
988 len = r;
989 if (*buf == 3) {
990 /* Version 3 INTRODUCE2 cell. */
991 time_t ts = 0, now = time(NULL);
992 v3_shift = 1;
993 auth_type = buf[1];
994 switch (auth_type) {
995 case REND_BASIC_AUTH:
996 /* fall through */
997 case REND_STEALTH_AUTH:
998 auth_len = ntohs(get_uint16(buf+2));
999 if (auth_len != REND_DESC_COOKIE_LEN) {
1000 log_info(LD_REND, "Wrong auth data size %d, should be %d.",
1001 (int)auth_len, REND_DESC_COOKIE_LEN);
1002 return -1;
1004 memcpy(auth_data, buf+4, sizeof(auth_data));
1005 v3_shift += 2+REND_DESC_COOKIE_LEN;
1006 break;
1007 case REND_NO_AUTH:
1008 break;
1009 default:
1010 log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
1013 /* Check timestamp. */
1014 ts = ntohl(get_uint32(buf+1+v3_shift));
1015 v3_shift += 4;
1016 if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
1017 (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
1018 log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
1019 (now - ts) < 0 ? "old" : "new");
1020 return -1;
1023 if (*buf == 2 || *buf == 3) {
1024 /* Version 2 INTRODUCE2 cell. */
1025 int klen;
1026 extend_info = tor_malloc_zero(sizeof(extend_info_t));
1027 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
1028 extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
1029 memcpy(extend_info->identity_digest, buf+v3_shift+7,
1030 DIGEST_LEN);
1031 extend_info->nickname[0] = '$';
1032 base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
1033 extend_info->identity_digest, DIGEST_LEN);
1035 klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
1036 if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
1037 log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
1038 (int)len, *buf);
1039 reason = END_CIRC_REASON_TORPROTOCOL;
1040 goto err;
1042 extend_info->onion_key =
1043 crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
1044 if (!extend_info->onion_key) {
1045 log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
1046 "INTRODUCE2 cell.", *buf);
1047 reason = END_CIRC_REASON_TORPROTOCOL;
1048 goto err;
1050 ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
1051 len -= v3_shift+7+DIGEST_LEN+2+klen;
1052 } else {
1053 char *rp_nickname;
1054 size_t nickname_field_len;
1055 routerinfo_t *router;
1056 int version;
1057 if (*buf == 1) {
1058 rp_nickname = buf+1;
1059 nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
1060 version = 1;
1061 } else {
1062 nickname_field_len = MAX_NICKNAME_LEN+1;
1063 rp_nickname = buf;
1064 version = 0;
1066 ptr=memchr(rp_nickname,0,nickname_field_len);
1067 if (!ptr || ptr == rp_nickname) {
1068 log_warn(LD_PROTOCOL,
1069 "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
1070 return -1;
1072 if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
1073 (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
1074 log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
1075 return -1;
1077 /* Okay, now we know that a nickname is at the start of the buffer. */
1078 ptr = rp_nickname+nickname_field_len;
1079 len -= nickname_field_len;
1080 len -= rp_nickname - buf; /* also remove header space used by version, if
1081 * any */
1082 router = router_get_by_nickname(rp_nickname, 0);
1083 if (!router) {
1084 log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
1085 escaped_safe_str(rp_nickname));
1086 /* XXXX Add a no-such-router reason? */
1087 reason = END_CIRC_REASON_TORPROTOCOL;
1088 goto err;
1091 extend_info = extend_info_from_router(router);
1094 if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
1095 log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
1096 reason = END_CIRC_REASON_TORPROTOCOL;
1097 goto err;
1100 r_cookie = ptr;
1101 base16_encode(hexcookie,9,r_cookie,4);
1103 /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
1104 digest = crypto_new_digest_env();
1105 crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
1106 crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
1107 crypto_free_digest_env(digest);
1109 /* Check whether there is a past request with the same Diffie-Hellman,
1110 * part 1. */
1111 if (!service->accepted_intros)
1112 service->accepted_intros = digestmap_new();
1114 access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
1115 if (access_time != NULL) {
1116 log_warn(LD_REND, "Possible replay detected! We received an "
1117 "INTRODUCE2 cell with same first part of "
1118 "Diffie-Hellman handshake %d seconds ago. Dropping "
1119 "cell.",
1120 (int) (now - *access_time));
1121 goto err;
1124 /* Add request to access history, including time and hash of Diffie-Hellman,
1125 * part 1, and possibly remove requests from the history that are older than
1126 * one hour. */
1127 access_time = tor_malloc(sizeof(time_t));
1128 *access_time = now;
1129 digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
1130 if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
1131 clean_accepted_intros(service, now);
1133 /* If the service performs client authorization, check included auth data. */
1134 if (service->clients) {
1135 if (auth_len > 0) {
1136 if (rend_check_authorization(service, auth_data)) {
1137 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
1138 } else {
1139 log_info(LD_REND, "The authorization data that are contained in "
1140 "the INTRODUCE2 cell are invalid. Dropping cell.");
1141 reason = END_CIRC_REASON_CONNECTFAILED;
1142 goto err;
1144 } else {
1145 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
1146 "data, but we require client authorization. Dropping cell.");
1147 reason = END_CIRC_REASON_CONNECTFAILED;
1148 goto err;
1152 /* Try DH handshake... */
1153 dh = crypto_dh_new();
1154 if (!dh || crypto_dh_generate_public(dh)<0) {
1155 log_warn(LD_BUG,"Internal error: couldn't build DH state "
1156 "or generate public key.");
1157 reason = END_CIRC_REASON_INTERNAL;
1158 goto err;
1160 if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
1161 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
1162 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
1163 reason = END_CIRC_REASON_INTERNAL;
1164 goto err;
1167 circ_needs_uptime = rend_service_requires_uptime(service);
1169 /* help predict this next time */
1170 rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
1172 /* Launch a circuit to alice's chosen rendezvous point.
1174 for (i=0;i<MAX_REND_FAILURES;i++) {
1175 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
1176 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1177 launched = circuit_launch_by_extend_info(
1178 CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
1180 if (launched)
1181 break;
1183 if (!launched) { /* give up */
1184 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
1185 "point %s for service %s.",
1186 escaped_safe_str(extend_info->nickname), serviceid);
1187 reason = END_CIRC_REASON_CONNECTFAILED;
1188 goto err;
1190 log_info(LD_REND,
1191 "Accepted intro; launching circuit to %s "
1192 "(cookie %s) for service %s.",
1193 escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
1194 tor_assert(launched->build_state);
1195 /* Fill in the circuit's state. */
1196 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1197 memcpy(launched->rend_data->rend_pk_digest,
1198 circuit->rend_data->rend_pk_digest,
1199 DIGEST_LEN);
1200 memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
1201 strlcpy(launched->rend_data->onion_address, service->service_id,
1202 sizeof(launched->rend_data->onion_address));
1203 launched->rend_data->rend_desc_version = service->descriptor_version;
1204 launched->build_state->pending_final_cpath = cpath =
1205 tor_malloc_zero(sizeof(crypt_path_t));
1206 cpath->magic = CRYPT_PATH_MAGIC;
1207 launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
1209 cpath->dh_handshake_state = dh;
1210 dh = NULL;
1211 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
1212 goto err;
1213 memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
1214 if (extend_info) extend_info_free(extend_info);
1216 return 0;
1217 err:
1218 if (dh) crypto_dh_free(dh);
1219 if (launched)
1220 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
1221 if (extend_info) extend_info_free(extend_info);
1222 return -1;
1225 /** Called when we fail building a rendezvous circuit at some point other
1226 * than the last hop: launches a new circuit to the same rendezvous point.
1228 void
1229 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
1231 origin_circuit_t *newcirc;
1232 cpath_build_state_t *newstate, *oldstate;
1234 tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1236 if (!oldcirc->build_state ||
1237 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
1238 oldcirc->build_state->expiry_time < time(NULL)) {
1239 log_info(LD_REND,
1240 "Attempt to build circuit to %s for rendezvous has failed "
1241 "too many times or expired; giving up.",
1242 oldcirc->build_state ?
1243 oldcirc->build_state->chosen_exit->nickname : "*unknown*");
1244 return;
1247 oldstate = oldcirc->build_state;
1248 tor_assert(oldstate);
1250 if (oldstate->pending_final_cpath == NULL) {
1251 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
1252 "Initiator will retry.");
1253 return;
1256 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
1257 oldstate->chosen_exit->nickname);
1259 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
1260 oldstate->chosen_exit,
1261 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1263 if (!newcirc) {
1264 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
1265 oldstate->chosen_exit->nickname);
1266 return;
1268 newstate = newcirc->build_state;
1269 tor_assert(newstate);
1270 newstate->failure_count = oldstate->failure_count+1;
1271 newstate->expiry_time = oldstate->expiry_time;
1272 newstate->pending_final_cpath = oldstate->pending_final_cpath;
1273 oldstate->pending_final_cpath = NULL;
1275 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
1278 /** Launch a circuit to serve as an introduction point for the service
1279 * <b>service</b> at the introduction point <b>nickname</b>
1281 static int
1282 rend_service_launch_establish_intro(rend_service_t *service,
1283 rend_intro_point_t *intro)
1285 origin_circuit_t *launched;
1287 log_info(LD_REND,
1288 "Launching circuit to introduction point %s for service %s",
1289 escaped_safe_str(intro->extend_info->nickname),
1290 service->service_id);
1292 rep_hist_note_used_internal(time(NULL), 1, 0);
1294 ++service->n_intro_circuits_launched;
1295 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
1296 intro->extend_info,
1297 CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
1299 if (!launched) {
1300 log_info(LD_REND,
1301 "Can't launch circuit to establish introduction at %s.",
1302 escaped_safe_str(intro->extend_info->nickname));
1303 return -1;
1306 if (memcmp(intro->extend_info->identity_digest,
1307 launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
1308 char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
1309 base16_encode(cann, sizeof(cann),
1310 launched->build_state->chosen_exit->identity_digest,
1311 DIGEST_LEN);
1312 base16_encode(orig, sizeof(orig),
1313 intro->extend_info->identity_digest, DIGEST_LEN);
1314 log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
1315 "but we requested an intro circuit to $%s. Updating "
1316 "our service.", cann, orig);
1317 extend_info_free(intro->extend_info);
1318 intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
1321 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1322 strlcpy(launched->rend_data->onion_address, service->service_id,
1323 sizeof(launched->rend_data->onion_address));
1324 memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
1325 launched->rend_data->rend_desc_version = service->descriptor_version;
1326 if (service->descriptor_version == 2)
1327 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
1328 if (launched->_base.state == CIRCUIT_STATE_OPEN)
1329 rend_service_intro_has_opened(launched);
1330 return 0;
1333 /** Return the number of introduction points that are or have been
1334 * established for the given service address and rendezvous version. */
1335 static int
1336 count_established_intro_points(const char *query, int rend_version)
1338 int num_ipos = 0;
1339 circuit_t *circ;
1340 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1341 if (!circ->marked_for_close &&
1342 circ->state == CIRCUIT_STATE_OPEN &&
1343 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1344 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
1345 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
1346 if (oc->rend_data &&
1347 oc->rend_data->rend_desc_version == rend_version &&
1348 !rend_cmp_service_ids(query, oc->rend_data->onion_address))
1349 num_ipos++;
1352 return num_ipos;
1355 /** Called when we're done building a circuit to an introduction point:
1356 * sends a RELAY_ESTABLISH_INTRO cell.
1358 void
1359 rend_service_intro_has_opened(origin_circuit_t *circuit)
1361 rend_service_t *service;
1362 size_t len;
1363 int r;
1364 char buf[RELAY_PAYLOAD_SIZE];
1365 char auth[DIGEST_LEN + 9];
1366 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1367 int reason = END_CIRC_REASON_TORPROTOCOL;
1368 crypto_pk_env_t *intro_key;
1370 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
1371 tor_assert(circuit->cpath);
1372 tor_assert(circuit->rend_data);
1374 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1375 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1377 service = rend_service_get_by_pk_digest_and_version(
1378 circuit->rend_data->rend_pk_digest,
1379 circuit->rend_data->rend_desc_version);
1380 if (!service) {
1381 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
1382 serviceid, circuit->_base.n_circ_id);
1383 reason = END_CIRC_REASON_NOSUCHSERVICE;
1384 goto err;
1387 /* If we already have enough introduction circuits for this service,
1388 * redefine this one as a general circuit. */
1389 if (count_established_intro_points(serviceid,
1390 circuit->rend_data->rend_desc_version) > NUM_INTRO_POINTS) {
1391 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
1392 "circuit, but we already have enough. Redefining purpose to "
1393 "general.");
1394 TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
1395 circuit_has_opened(circuit);
1396 return;
1399 log_info(LD_REND,
1400 "Established circuit %d as introduction point for service %s",
1401 circuit->_base.n_circ_id, serviceid);
1403 /* If the introduction point will not be used in an unversioned
1404 * descriptor, use the intro key instead of the service key in
1405 * ESTABLISH_INTRO. */
1406 if (service->descriptor_version == 0)
1407 intro_key = service->private_key;
1408 else
1409 intro_key = circuit->intro_key;
1410 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
1411 r = crypto_pk_asn1_encode(intro_key, buf+2,
1412 RELAY_PAYLOAD_SIZE-2);
1413 if (r < 0) {
1414 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
1415 reason = END_CIRC_REASON_INTERNAL;
1416 goto err;
1418 len = r;
1419 set_uint16(buf, htons((uint16_t)len));
1420 len += 2;
1421 memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
1422 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
1423 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
1424 goto err;
1425 len += 20;
1426 note_crypto_pk_op(REND_SERVER);
1427 r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
1428 if (r<0) {
1429 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
1430 reason = END_CIRC_REASON_INTERNAL;
1431 goto err;
1433 len += r;
1435 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1436 RELAY_COMMAND_ESTABLISH_INTRO,
1437 buf, len, circuit->cpath->prev)<0) {
1438 log_info(LD_GENERAL,
1439 "Couldn't send introduction request for service %s on circuit %d",
1440 serviceid, circuit->_base.n_circ_id);
1441 reason = END_CIRC_REASON_INTERNAL;
1442 goto err;
1445 return;
1446 err:
1447 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1450 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
1451 * live introduction point, and note that the service descriptor is
1452 * now out-of-date.*/
1454 rend_service_intro_established(origin_circuit_t *circuit, const char *request,
1455 size_t request_len)
1457 rend_service_t *service;
1458 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1459 (void) request;
1460 (void) request_len;
1462 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
1463 log_warn(LD_PROTOCOL,
1464 "received INTRO_ESTABLISHED cell on non-intro circuit.");
1465 goto err;
1467 tor_assert(circuit->rend_data);
1468 service = rend_service_get_by_pk_digest_and_version(
1469 circuit->rend_data->rend_pk_digest,
1470 circuit->rend_data->rend_desc_version);
1471 if (!service) {
1472 log_warn(LD_REND, "Unknown service on introduction circuit %d.",
1473 circuit->_base.n_circ_id);
1474 goto err;
1476 service->desc_is_dirty = time(NULL);
1477 circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
1479 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
1480 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1481 log_info(LD_REND,
1482 "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
1483 circuit->_base.n_circ_id, serviceid);
1485 return 0;
1486 err:
1487 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
1488 return -1;
1491 /** Called once a circuit to a rendezvous point is established: sends a
1492 * RELAY_COMMAND_RENDEZVOUS1 cell.
1494 void
1495 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
1497 rend_service_t *service;
1498 char buf[RELAY_PAYLOAD_SIZE];
1499 crypt_path_t *hop;
1500 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1501 char hexcookie[9];
1502 int reason;
1504 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1505 tor_assert(circuit->cpath);
1506 tor_assert(circuit->build_state);
1507 tor_assert(circuit->rend_data);
1508 hop = circuit->build_state->pending_final_cpath;
1509 tor_assert(hop);
1511 base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
1512 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1513 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1515 log_info(LD_REND,
1516 "Done building circuit %d to rendezvous with "
1517 "cookie %s for service %s",
1518 circuit->_base.n_circ_id, hexcookie, serviceid);
1520 service = rend_service_get_by_pk_digest_and_version(
1521 circuit->rend_data->rend_pk_digest,
1522 circuit->rend_data->rend_desc_version);
1523 if (!service) {
1524 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
1525 "introduction circuit.");
1526 reason = END_CIRC_REASON_INTERNAL;
1527 goto err;
1530 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
1531 memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
1532 if (crypto_dh_get_public(hop->dh_handshake_state,
1533 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
1534 log_warn(LD_GENERAL,"Couldn't get DH public key.");
1535 reason = END_CIRC_REASON_INTERNAL;
1536 goto err;
1538 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
1539 DIGEST_LEN);
1541 /* Send the cell */
1542 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1543 RELAY_COMMAND_RENDEZVOUS1,
1544 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
1545 circuit->cpath->prev)<0) {
1546 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
1547 reason = END_CIRC_REASON_INTERNAL;
1548 goto err;
1551 crypto_dh_free(hop->dh_handshake_state);
1552 hop->dh_handshake_state = NULL;
1554 /* Append the cpath entry. */
1555 hop->state = CPATH_STATE_OPEN;
1556 /* set the windows to default. these are the windows
1557 * that bob thinks alice has.
1559 hop->package_window = circuit_initial_package_window();
1560 hop->deliver_window = CIRCWINDOW_START;
1562 onion_append_to_cpath(&circuit->cpath, hop);
1563 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
1565 /* Change the circuit purpose. */
1566 circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
1568 return;
1569 err:
1570 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1574 * Manage introduction points
1577 /** Return the (possibly non-open) introduction circuit ending at
1578 * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
1579 * which publishes descriptor of version <b>desc_version</b>. Return
1580 * NULL if no such service is found.
1582 static origin_circuit_t *
1583 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
1584 int desc_version)
1586 origin_circuit_t *circ = NULL;
1588 tor_assert(intro);
1589 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1590 CIRCUIT_PURPOSE_S_INTRO))) {
1591 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1592 intro->extend_info->identity_digest, DIGEST_LEN) &&
1593 circ->rend_data &&
1594 circ->rend_data->rend_desc_version == desc_version) {
1595 return circ;
1599 circ = NULL;
1600 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1601 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
1602 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1603 intro->extend_info->identity_digest, DIGEST_LEN) &&
1604 circ->rend_data &&
1605 circ->rend_data->rend_desc_version == desc_version) {
1606 return circ;
1609 return NULL;
1612 /** Determine the responsible hidden service directories for the
1613 * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
1614 * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
1615 * purposes. */
1616 static void
1617 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
1618 smartlist_t *descs, const char *service_id,
1619 int seconds_valid)
1621 int i, j, failed_upload = 0;
1622 smartlist_t *responsible_dirs = smartlist_create();
1623 smartlist_t *successful_uploads = smartlist_create();
1624 routerstatus_t *hs_dir;
1625 for (i = 0; i < smartlist_len(descs); i++) {
1626 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
1627 /* Determine responsible dirs. */
1628 if (hid_serv_get_responsible_directories(responsible_dirs,
1629 desc->desc_id) < 0) {
1630 log_warn(LD_REND, "Could not determine the responsible hidden service "
1631 "directories to post descriptors to.");
1632 smartlist_free(responsible_dirs);
1633 smartlist_free(successful_uploads);
1634 return;
1636 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
1637 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1638 hs_dir = smartlist_get(responsible_dirs, j);
1639 if (smartlist_digest_isin(renddesc->successful_uploads,
1640 hs_dir->identity_digest))
1641 /* Don't upload descriptor if we succeeded in doing so last time. */
1642 continue;
1643 if (!router_get_by_digest(hs_dir->identity_digest)) {
1644 log_info(LD_REND, "Not sending publish request for v2 descriptor to "
1645 "hidden service directory '%s'; we don't have its "
1646 "router descriptor. Queuing for later upload.",
1647 hs_dir->nickname);
1648 failed_upload = -1;
1649 continue;
1651 /* Send publish request. */
1652 directory_initiate_command_routerstatus(hs_dir,
1653 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
1654 ROUTER_PURPOSE_GENERAL,
1655 1, NULL, desc->desc_str,
1656 strlen(desc->desc_str), 0);
1657 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1658 desc->desc_id, DIGEST_LEN);
1659 log_info(LD_REND, "Sending publish request for v2 descriptor for "
1660 "service '%s' with descriptor ID '%s' with validity "
1661 "of %d seconds to hidden service directory '%s' on "
1662 "port %d.",
1663 safe_str(service_id),
1664 safe_str(desc_id_base32),
1665 seconds_valid,
1666 hs_dir->nickname,
1667 hs_dir->dir_port);
1668 /* Remember successful upload to this router for next time. */
1669 if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
1670 smartlist_add(successful_uploads, hs_dir->identity_digest);
1672 smartlist_clear(responsible_dirs);
1674 if (!failed_upload) {
1675 if (renddesc->successful_uploads) {
1676 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
1677 smartlist_free(renddesc->successful_uploads);
1678 renddesc->successful_uploads = NULL;
1680 renddesc->all_uploads_performed = 1;
1681 } else {
1682 /* Remember which routers worked this time, so that we don't upload the
1683 * descriptor to them again. */
1684 if (!renddesc->successful_uploads)
1685 renddesc->successful_uploads = smartlist_create();
1686 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
1687 if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
1688 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
1689 smartlist_add(renddesc->successful_uploads, hsdir_id);
1693 smartlist_free(responsible_dirs);
1694 smartlist_free(successful_uploads);
1697 /** Encode and sign up-to-date v0 and/or v2 service descriptors for
1698 * <b>service</b>, and upload it/them to all the dirservers/to the
1699 * responsible hidden service directories.
1701 static void
1702 upload_service_descriptor(rend_service_t *service)
1704 time_t now = time(NULL);
1705 int rendpostperiod;
1706 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1707 int uploaded = 0;
1709 rendpostperiod = get_options()->RendPostPeriod;
1711 /* Upload unversioned (v0) descriptor? */
1712 if (service->descriptor_version == 0 &&
1713 get_options()->PublishHidServDescriptors) {
1714 char *desc;
1715 size_t desc_len;
1716 /* Encode the descriptor. */
1717 if (rend_encode_service_descriptor(service->desc,
1718 service->private_key,
1719 &desc, &desc_len)<0) {
1720 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1721 "not uploading.");
1722 return;
1725 /* Post it to the dirservers */
1726 rend_get_service_id(service->desc->pk, serviceid);
1727 log_info(LD_REND, "Sending publish request for hidden service %s",
1728 serviceid);
1729 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
1730 ROUTER_PURPOSE_GENERAL,
1731 HIDSERV_AUTHORITY, desc, desc_len, 0);
1732 tor_free(desc);
1733 service->next_upload_time = now + rendpostperiod;
1734 uploaded = 1;
1737 /* Upload v2 descriptor? */
1738 if (service->descriptor_version == 2 &&
1739 get_options()->PublishHidServDescriptors) {
1740 networkstatus_t *c = networkstatus_get_latest_consensus();
1741 if (c && smartlist_len(c->routerstatus_list) > 0) {
1742 int seconds_valid, i, j, num_descs;
1743 smartlist_t *descs = smartlist_create();
1744 smartlist_t *client_cookies = smartlist_create();
1745 /* Either upload a single descriptor (including replicas) or one
1746 * descriptor for each authorized client in case of authorization
1747 * type 'stealth'. */
1748 num_descs = service->auth_type == REND_STEALTH_AUTH ?
1749 smartlist_len(service->clients) : 1;
1750 for (j = 0; j < num_descs; j++) {
1751 crypto_pk_env_t *client_key = NULL;
1752 rend_authorized_client_t *client = NULL;
1753 smartlist_clear(client_cookies);
1754 switch (service->auth_type) {
1755 case REND_NO_AUTH:
1756 /* Do nothing here. */
1757 break;
1758 case REND_BASIC_AUTH:
1759 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
1760 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
1761 break;
1762 case REND_STEALTH_AUTH:
1763 client = smartlist_get(service->clients, j);
1764 client_key = client->client_key;
1765 smartlist_add(client_cookies, client->descriptor_cookie);
1766 break;
1768 /* Encode the current descriptor. */
1769 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1770 now, 0,
1771 service->auth_type,
1772 client_key,
1773 client_cookies);
1774 if (seconds_valid < 0) {
1775 log_warn(LD_BUG, "Internal error: couldn't encode service "
1776 "descriptor; not uploading.");
1777 smartlist_free(descs);
1778 smartlist_free(client_cookies);
1779 return;
1781 /* Post the current descriptors to the hidden service directories. */
1782 rend_get_service_id(service->desc->pk, serviceid);
1783 log_info(LD_REND, "Sending publish request for hidden service %s",
1784 serviceid);
1785 directory_post_to_hs_dir(service->desc, descs, serviceid,
1786 seconds_valid);
1787 /* Free memory for descriptors. */
1788 for (i = 0; i < smartlist_len(descs); i++)
1789 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1790 smartlist_clear(descs);
1791 /* Update next upload time. */
1792 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
1793 > rendpostperiod)
1794 service->next_upload_time = now + rendpostperiod;
1795 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
1796 service->next_upload_time = now + seconds_valid + 1;
1797 else
1798 service->next_upload_time = now + seconds_valid -
1799 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
1800 /* Post also the next descriptors, if necessary. */
1801 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
1802 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1803 now, 1,
1804 service->auth_type,
1805 client_key,
1806 client_cookies);
1807 if (seconds_valid < 0) {
1808 log_warn(LD_BUG, "Internal error: couldn't encode service "
1809 "descriptor; not uploading.");
1810 smartlist_free(descs);
1811 smartlist_free(client_cookies);
1812 return;
1814 directory_post_to_hs_dir(service->desc, descs, serviceid,
1815 seconds_valid);
1816 /* Free memory for descriptors. */
1817 for (i = 0; i < smartlist_len(descs); i++)
1818 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1819 smartlist_clear(descs);
1822 smartlist_free(descs);
1823 smartlist_free(client_cookies);
1824 uploaded = 1;
1825 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
1829 /* If not uploaded, try again in one minute. */
1830 if (!uploaded)
1831 service->next_upload_time = now + 60;
1833 /* Unmark dirty flag of this service. */
1834 service->desc_is_dirty = 0;
1837 /** For every service, check how many intro points it currently has, and:
1838 * - Pick new intro points as necessary.
1839 * - Launch circuits to any new intro points.
1841 void
1842 rend_services_introduce(void)
1844 int i,j,r;
1845 routerinfo_t *router;
1846 rend_service_t *service;
1847 rend_intro_point_t *intro;
1848 int changed, prev_intro_nodes;
1849 smartlist_t *intro_routers;
1850 time_t now;
1851 or_options_t *options = get_options();
1853 intro_routers = smartlist_create();
1854 now = time(NULL);
1856 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1857 smartlist_clear(intro_routers);
1858 service = smartlist_get(rend_service_list, i);
1860 tor_assert(service);
1861 changed = 0;
1862 if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
1863 /* One period has elapsed; we can try building circuits again. */
1864 service->intro_period_started = now;
1865 service->n_intro_circuits_launched = 0;
1866 } else if (service->n_intro_circuits_launched >=
1867 MAX_INTRO_CIRCS_PER_PERIOD) {
1868 /* We have failed too many times in this period; wait for the next
1869 * one before we try again. */
1870 continue;
1873 /* Find out which introduction points we have in progress for this
1874 service. */
1875 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1876 intro = smartlist_get(service->intro_nodes, j);
1877 router = router_get_by_digest(intro->extend_info->identity_digest);
1878 if (!router || !find_intro_circuit(intro, service->pk_digest,
1879 service->descriptor_version)) {
1880 log_info(LD_REND,"Giving up on %s as intro point for %s.",
1881 intro->extend_info->nickname, service->service_id);
1882 if (service->desc) {
1883 SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
1884 dintro, {
1885 if (!memcmp(dintro->extend_info->identity_digest,
1886 intro->extend_info->identity_digest, DIGEST_LEN)) {
1887 log_info(LD_REND, "The intro point we are giving up on was "
1888 "included in the last published descriptor. "
1889 "Marking current descriptor as dirty.");
1890 service->desc_is_dirty = now;
1894 rend_intro_point_free(intro);
1895 smartlist_del(service->intro_nodes,j--);
1896 changed = 1;
1898 if (router)
1899 smartlist_add(intro_routers, router);
1902 /* We have enough intro points, and the intro points we thought we had were
1903 * all connected.
1905 if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
1906 /* We have all our intro points! Start a fresh period and reset the
1907 * circuit count. */
1908 service->intro_period_started = now;
1909 service->n_intro_circuits_launched = 0;
1910 continue;
1913 /* Remember how many introduction circuits we started with. */
1914 prev_intro_nodes = smartlist_len(service->intro_nodes);
1915 /* We have enough directory information to start establishing our
1916 * intro points. We want to end up with three intro points, but if
1917 * we're just starting, we launch five and pick the first three that
1918 * complete.
1920 * The ones after the first three will be converted to 'general'
1921 * internal circuits in rend_service_intro_has_opened(), and then
1922 * we'll drop them from the list of intro points next time we
1923 * go through the above "find out which introduction points we have
1924 * in progress" loop. */
1925 #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
1926 for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
1927 NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
1928 router_crn_flags_t flags = CRN_NEED_UPTIME;
1929 if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
1930 flags |= CRN_ALLOW_INVALID;
1931 router = router_choose_random_node(NULL, intro_routers,
1932 options->ExcludeNodes, flags);
1933 if (!router) {
1934 log_warn(LD_REND,
1935 "Could only establish %d introduction points for %s.",
1936 smartlist_len(service->intro_nodes), service->service_id);
1937 break;
1939 changed = 1;
1940 smartlist_add(intro_routers, router);
1941 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
1942 intro->extend_info = extend_info_from_router(router);
1943 if (service->descriptor_version == 2) {
1944 intro->intro_key = crypto_new_pk_env();
1945 tor_assert(!crypto_pk_generate_key(intro->intro_key));
1947 smartlist_add(service->intro_nodes, intro);
1948 log_info(LD_REND, "Picked router %s as an intro point for %s.",
1949 router->nickname, service->service_id);
1952 /* If there's no need to launch new circuits, stop here. */
1953 if (!changed)
1954 continue;
1956 /* Establish new introduction points. */
1957 for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
1958 intro = smartlist_get(service->intro_nodes, j);
1959 r = rend_service_launch_establish_intro(service, intro);
1960 if (r<0) {
1961 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
1962 intro->extend_info->nickname, service->service_id);
1966 smartlist_free(intro_routers);
1969 /** Regenerate and upload rendezvous service descriptors for all
1970 * services, if necessary. If the descriptor has been dirty enough
1971 * for long enough, definitely upload; else only upload when the
1972 * periodic timeout has expired.
1974 * For the first upload, pick a random time between now and two periods
1975 * from now, and pick it independently for each service.
1977 void
1978 rend_consider_services_upload(time_t now)
1980 int i;
1981 rend_service_t *service;
1982 int rendpostperiod = get_options()->RendPostPeriod;
1984 if (!get_options()->PublishHidServDescriptors)
1985 return;
1987 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1988 service = smartlist_get(rend_service_list, i);
1989 if (!service->next_upload_time) { /* never been uploaded yet */
1990 /* The fixed lower bound of 30 seconds ensures that the descriptor
1991 * is stable before being published. See comment below. */
1992 service->next_upload_time =
1993 now + 30 + crypto_rand_int(2*rendpostperiod);
1995 if (service->next_upload_time < now ||
1996 (service->desc_is_dirty &&
1997 service->desc_is_dirty < now-30)) {
1998 /* if it's time, or if the directory servers have a wrong service
1999 * descriptor and ours has been stable for 30 seconds, upload a
2000 * new one of each format. */
2001 rend_service_update_descriptor(service);
2002 upload_service_descriptor(service);
2007 /** True if the list of available router descriptors might have changed so
2008 * that we should have a look whether we can republish previously failed
2009 * rendezvous service descriptors. */
2010 static int consider_republishing_rend_descriptors = 1;
2012 /** Called when our internal view of the directory has changed, so that we
2013 * might have router descriptors of hidden service directories available that
2014 * we did not have before. */
2015 void
2016 rend_hsdir_routers_changed(void)
2018 consider_republishing_rend_descriptors = 1;
2021 /** Consider republication of v2 rendezvous service descriptors that failed
2022 * previously, but without regenerating descriptor contents.
2024 void
2025 rend_consider_descriptor_republication(void)
2027 int i;
2028 rend_service_t *service;
2030 if (!consider_republishing_rend_descriptors)
2031 return;
2032 consider_republishing_rend_descriptors = 0;
2034 if (!get_options()->PublishHidServDescriptors)
2035 return;
2037 for (i=0; i < smartlist_len(rend_service_list); ++i) {
2038 service = smartlist_get(rend_service_list, i);
2039 if (service->descriptor_version && service->desc &&
2040 !service->desc->all_uploads_performed) {
2041 /* If we failed in uploading a descriptor last time, try again *without*
2042 * updating the descriptor's contents. */
2043 upload_service_descriptor(service);
2048 /** Log the status of introduction points for all rendezvous services
2049 * at log severity <b>severity</b>.
2051 void
2052 rend_service_dump_stats(int severity)
2054 int i,j;
2055 rend_service_t *service;
2056 rend_intro_point_t *intro;
2057 const char *safe_name;
2058 origin_circuit_t *circ;
2060 for (i=0; i < smartlist_len(rend_service_list); ++i) {
2061 service = smartlist_get(rend_service_list, i);
2062 log(severity, LD_GENERAL, "Service configured in \"%s\":",
2063 service->directory);
2064 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
2065 intro = smartlist_get(service->intro_nodes, j);
2066 safe_name = safe_str(intro->extend_info->nickname);
2068 circ = find_intro_circuit(intro, service->pk_digest,
2069 service->descriptor_version);
2070 if (!circ) {
2071 log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
2072 j, safe_name);
2073 continue;
2075 log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
2076 j, safe_name, circuit_state_to_string(circ->_base.state));
2081 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
2082 * 'circ', and look up the port and address based on conn-\>port.
2083 * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
2084 * or 0 for success.
2087 rend_service_set_connection_addr_port(edge_connection_t *conn,
2088 origin_circuit_t *circ)
2090 rend_service_t *service;
2091 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
2092 smartlist_t *matching_ports;
2093 rend_service_port_config_t *chosen_port;
2095 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
2096 tor_assert(circ->rend_data);
2097 log_debug(LD_REND,"beginning to hunt for addr/port");
2098 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
2099 circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
2100 service = rend_service_get_by_pk_digest_and_version(
2101 circ->rend_data->rend_pk_digest,
2102 circ->rend_data->rend_desc_version);
2103 if (!service) {
2104 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
2105 "rendezvous circuit %d; closing.",
2106 serviceid, circ->_base.n_circ_id);
2107 return -1;
2109 matching_ports = smartlist_create();
2110 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
2112 if (conn->_base.port == p->virtual_port) {
2113 smartlist_add(matching_ports, p);
2116 chosen_port = smartlist_choose(matching_ports);
2117 smartlist_free(matching_ports);
2118 if (chosen_port) {
2119 tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
2120 conn->_base.port = chosen_port->real_port;
2121 return 0;
2123 log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
2124 conn->_base.port,serviceid);
2125 return -1;