Fix a heap overflow found by debuger, and make it harder to make that mistake again
[tor/rransom.git] / src / or / rendservice.c
blob07f01aead957180cdb790e0a235eaa8eaabc4d48
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2011, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendservice.c
7 * \brief The hidden-service side of rendezvous functionality.
8 **/
10 #include "or.h"
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 uint8_t *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 (char*)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,sizeof(buf),
983 (char*)(request+DIGEST_LEN),request_len-DIGEST_LEN,
984 PK_PKCS1_OAEP_PADDING,1);
985 if (r<0) {
986 log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
987 return -1;
989 len = r;
990 if (*buf == 3) {
991 /* Version 3 INTRODUCE2 cell. */
992 time_t ts = 0, now = time(NULL);
993 v3_shift = 1;
994 auth_type = buf[1];
995 switch (auth_type) {
996 case REND_BASIC_AUTH:
997 /* fall through */
998 case REND_STEALTH_AUTH:
999 auth_len = ntohs(get_uint16(buf+2));
1000 if (auth_len != REND_DESC_COOKIE_LEN) {
1001 log_info(LD_REND, "Wrong auth data size %d, should be %d.",
1002 (int)auth_len, REND_DESC_COOKIE_LEN);
1003 return -1;
1005 memcpy(auth_data, buf+4, sizeof(auth_data));
1006 v3_shift += 2+REND_DESC_COOKIE_LEN;
1007 break;
1008 case REND_NO_AUTH:
1009 break;
1010 default:
1011 log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
1014 /* Check timestamp. */
1015 ts = ntohl(get_uint32(buf+1+v3_shift));
1016 v3_shift += 4;
1017 if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
1018 (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
1019 log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
1020 (now - ts) < 0 ? "old" : "new");
1021 return -1;
1024 if (*buf == 2 || *buf == 3) {
1025 /* Version 2 INTRODUCE2 cell. */
1026 int klen;
1027 extend_info = tor_malloc_zero(sizeof(extend_info_t));
1028 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
1029 extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
1030 memcpy(extend_info->identity_digest, buf+v3_shift+7,
1031 DIGEST_LEN);
1032 extend_info->nickname[0] = '$';
1033 base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
1034 extend_info->identity_digest, DIGEST_LEN);
1036 klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
1037 if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
1038 log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
1039 (int)len, *buf);
1040 reason = END_CIRC_REASON_TORPROTOCOL;
1041 goto err;
1043 extend_info->onion_key =
1044 crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
1045 if (!extend_info->onion_key) {
1046 log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
1047 "INTRODUCE2 cell.", *buf);
1048 reason = END_CIRC_REASON_TORPROTOCOL;
1049 goto err;
1051 ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
1052 len -= v3_shift+7+DIGEST_LEN+2+klen;
1053 } else {
1054 char *rp_nickname;
1055 size_t nickname_field_len;
1056 routerinfo_t *router;
1057 int version;
1058 if (*buf == 1) {
1059 rp_nickname = buf+1;
1060 nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
1061 version = 1;
1062 } else {
1063 nickname_field_len = MAX_NICKNAME_LEN+1;
1064 rp_nickname = buf;
1065 version = 0;
1067 ptr=memchr(rp_nickname,0,nickname_field_len);
1068 if (!ptr || ptr == rp_nickname) {
1069 log_warn(LD_PROTOCOL,
1070 "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
1071 return -1;
1073 if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
1074 (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
1075 log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
1076 return -1;
1078 /* Okay, now we know that a nickname is at the start of the buffer. */
1079 ptr = rp_nickname+nickname_field_len;
1080 len -= nickname_field_len;
1081 len -= rp_nickname - buf; /* also remove header space used by version, if
1082 * any */
1083 router = router_get_by_nickname(rp_nickname, 0);
1084 if (!router) {
1085 log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
1086 escaped_safe_str(rp_nickname));
1087 /* XXXX Add a no-such-router reason? */
1088 reason = END_CIRC_REASON_TORPROTOCOL;
1089 goto err;
1092 extend_info = extend_info_from_router(router);
1095 if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
1096 log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
1097 reason = END_CIRC_REASON_TORPROTOCOL;
1098 goto err;
1101 r_cookie = ptr;
1102 base16_encode(hexcookie,9,r_cookie,4);
1104 /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
1105 digest = crypto_new_digest_env();
1106 crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
1107 crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
1108 crypto_free_digest_env(digest);
1110 /* Check whether there is a past request with the same Diffie-Hellman,
1111 * part 1. */
1112 if (!service->accepted_intros)
1113 service->accepted_intros = digestmap_new();
1115 access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
1116 if (access_time != NULL) {
1117 log_warn(LD_REND, "Possible replay detected! We received an "
1118 "INTRODUCE2 cell with same first part of "
1119 "Diffie-Hellman handshake %d seconds ago. Dropping "
1120 "cell.",
1121 (int) (now - *access_time));
1122 goto err;
1125 /* Add request to access history, including time and hash of Diffie-Hellman,
1126 * part 1, and possibly remove requests from the history that are older than
1127 * one hour. */
1128 access_time = tor_malloc(sizeof(time_t));
1129 *access_time = now;
1130 digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
1131 if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
1132 clean_accepted_intros(service, now);
1134 /* If the service performs client authorization, check included auth data. */
1135 if (service->clients) {
1136 if (auth_len > 0) {
1137 if (rend_check_authorization(service, auth_data)) {
1138 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
1139 } else {
1140 log_info(LD_REND, "The authorization data that are contained in "
1141 "the INTRODUCE2 cell are invalid. Dropping cell.");
1142 reason = END_CIRC_REASON_CONNECTFAILED;
1143 goto err;
1145 } else {
1146 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
1147 "data, but we require client authorization. Dropping cell.");
1148 reason = END_CIRC_REASON_CONNECTFAILED;
1149 goto err;
1153 /* Try DH handshake... */
1154 dh = crypto_dh_new();
1155 if (!dh || crypto_dh_generate_public(dh)<0) {
1156 log_warn(LD_BUG,"Internal error: couldn't build DH state "
1157 "or generate public key.");
1158 reason = END_CIRC_REASON_INTERNAL;
1159 goto err;
1161 if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
1162 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
1163 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
1164 reason = END_CIRC_REASON_INTERNAL;
1165 goto err;
1168 circ_needs_uptime = rend_service_requires_uptime(service);
1170 /* help predict this next time */
1171 rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
1173 /* Launch a circuit to alice's chosen rendezvous point.
1175 for (i=0;i<MAX_REND_FAILURES;i++) {
1176 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
1177 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1178 launched = circuit_launch_by_extend_info(
1179 CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
1181 if (launched)
1182 break;
1184 if (!launched) { /* give up */
1185 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
1186 "point %s for service %s.",
1187 escaped_safe_str(extend_info->nickname), serviceid);
1188 reason = END_CIRC_REASON_CONNECTFAILED;
1189 goto err;
1191 log_info(LD_REND,
1192 "Accepted intro; launching circuit to %s "
1193 "(cookie %s) for service %s.",
1194 escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
1195 tor_assert(launched->build_state);
1196 /* Fill in the circuit's state. */
1197 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1198 memcpy(launched->rend_data->rend_pk_digest,
1199 circuit->rend_data->rend_pk_digest,
1200 DIGEST_LEN);
1201 memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
1202 strlcpy(launched->rend_data->onion_address, service->service_id,
1203 sizeof(launched->rend_data->onion_address));
1204 launched->rend_data->rend_desc_version = service->descriptor_version;
1205 launched->build_state->pending_final_cpath = cpath =
1206 tor_malloc_zero(sizeof(crypt_path_t));
1207 cpath->magic = CRYPT_PATH_MAGIC;
1208 launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
1210 cpath->dh_handshake_state = dh;
1211 dh = NULL;
1212 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
1213 goto err;
1214 memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
1215 if (extend_info) extend_info_free(extend_info);
1217 return 0;
1218 err:
1219 if (dh) crypto_dh_free(dh);
1220 if (launched)
1221 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
1222 if (extend_info) extend_info_free(extend_info);
1223 return -1;
1226 /** Called when we fail building a rendezvous circuit at some point other
1227 * than the last hop: launches a new circuit to the same rendezvous point.
1229 void
1230 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
1232 origin_circuit_t *newcirc;
1233 cpath_build_state_t *newstate, *oldstate;
1235 tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1237 if (!oldcirc->build_state ||
1238 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
1239 oldcirc->build_state->expiry_time < time(NULL)) {
1240 log_info(LD_REND,
1241 "Attempt to build circuit to %s for rendezvous has failed "
1242 "too many times or expired; giving up.",
1243 oldcirc->build_state ?
1244 oldcirc->build_state->chosen_exit->nickname : "*unknown*");
1245 return;
1248 oldstate = oldcirc->build_state;
1249 tor_assert(oldstate);
1251 if (oldstate->pending_final_cpath == NULL) {
1252 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
1253 "Initiator will retry.");
1254 return;
1257 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
1258 oldstate->chosen_exit->nickname);
1260 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
1261 oldstate->chosen_exit,
1262 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1264 if (!newcirc) {
1265 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
1266 oldstate->chosen_exit->nickname);
1267 return;
1269 newstate = newcirc->build_state;
1270 tor_assert(newstate);
1271 newstate->failure_count = oldstate->failure_count+1;
1272 newstate->expiry_time = oldstate->expiry_time;
1273 newstate->pending_final_cpath = oldstate->pending_final_cpath;
1274 oldstate->pending_final_cpath = NULL;
1276 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
1279 /** Launch a circuit to serve as an introduction point for the service
1280 * <b>service</b> at the introduction point <b>nickname</b>
1282 static int
1283 rend_service_launch_establish_intro(rend_service_t *service,
1284 rend_intro_point_t *intro)
1286 origin_circuit_t *launched;
1288 log_info(LD_REND,
1289 "Launching circuit to introduction point %s for service %s",
1290 escaped_safe_str(intro->extend_info->nickname),
1291 service->service_id);
1293 rep_hist_note_used_internal(time(NULL), 1, 0);
1295 ++service->n_intro_circuits_launched;
1296 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
1297 intro->extend_info,
1298 CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
1300 if (!launched) {
1301 log_info(LD_REND,
1302 "Can't launch circuit to establish introduction at %s.",
1303 escaped_safe_str(intro->extend_info->nickname));
1304 return -1;
1307 if (memcmp(intro->extend_info->identity_digest,
1308 launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
1309 char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
1310 base16_encode(cann, sizeof(cann),
1311 launched->build_state->chosen_exit->identity_digest,
1312 DIGEST_LEN);
1313 base16_encode(orig, sizeof(orig),
1314 intro->extend_info->identity_digest, DIGEST_LEN);
1315 log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
1316 "but we requested an intro circuit to $%s. Updating "
1317 "our service.", cann, orig);
1318 extend_info_free(intro->extend_info);
1319 intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
1322 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1323 strlcpy(launched->rend_data->onion_address, service->service_id,
1324 sizeof(launched->rend_data->onion_address));
1325 memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
1326 launched->rend_data->rend_desc_version = service->descriptor_version;
1327 if (service->descriptor_version == 2)
1328 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
1329 if (launched->_base.state == CIRCUIT_STATE_OPEN)
1330 rend_service_intro_has_opened(launched);
1331 return 0;
1334 /** Return the number of introduction points that are or have been
1335 * established for the given service address and rendezvous version. */
1336 static int
1337 count_established_intro_points(const char *query, int rend_version)
1339 int num_ipos = 0;
1340 circuit_t *circ;
1341 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1342 if (!circ->marked_for_close &&
1343 circ->state == CIRCUIT_STATE_OPEN &&
1344 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1345 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
1346 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
1347 if (oc->rend_data &&
1348 oc->rend_data->rend_desc_version == rend_version &&
1349 !rend_cmp_service_ids(query, oc->rend_data->onion_address))
1350 num_ipos++;
1353 return num_ipos;
1356 /** Called when we're done building a circuit to an introduction point:
1357 * sends a RELAY_ESTABLISH_INTRO cell.
1359 void
1360 rend_service_intro_has_opened(origin_circuit_t *circuit)
1362 rend_service_t *service;
1363 size_t len;
1364 int r;
1365 char buf[RELAY_PAYLOAD_SIZE];
1366 char auth[DIGEST_LEN + 9];
1367 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1368 int reason = END_CIRC_REASON_TORPROTOCOL;
1369 crypto_pk_env_t *intro_key;
1371 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
1372 tor_assert(circuit->cpath);
1373 tor_assert(circuit->rend_data);
1375 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1376 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1378 service = rend_service_get_by_pk_digest_and_version(
1379 circuit->rend_data->rend_pk_digest,
1380 circuit->rend_data->rend_desc_version);
1381 if (!service) {
1382 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
1383 serviceid, circuit->_base.n_circ_id);
1384 reason = END_CIRC_REASON_NOSUCHSERVICE;
1385 goto err;
1388 /* If we already have enough introduction circuits for this service,
1389 * redefine this one as a general circuit. */
1390 if (count_established_intro_points(serviceid,
1391 circuit->rend_data->rend_desc_version) > NUM_INTRO_POINTS) {
1392 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
1393 "circuit, but we already have enough. Redefining purpose to "
1394 "general.");
1395 TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
1396 circuit_has_opened(circuit);
1397 return;
1400 log_info(LD_REND,
1401 "Established circuit %d as introduction point for service %s",
1402 circuit->_base.n_circ_id, serviceid);
1404 /* If the introduction point will not be used in an unversioned
1405 * descriptor, use the intro key instead of the service key in
1406 * ESTABLISH_INTRO. */
1407 if (service->descriptor_version == 0)
1408 intro_key = service->private_key;
1409 else
1410 intro_key = circuit->intro_key;
1411 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
1412 r = crypto_pk_asn1_encode(intro_key, buf+2,
1413 RELAY_PAYLOAD_SIZE-2);
1414 if (r < 0) {
1415 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
1416 reason = END_CIRC_REASON_INTERNAL;
1417 goto err;
1419 len = r;
1420 set_uint16(buf, htons((uint16_t)len));
1421 len += 2;
1422 memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
1423 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
1424 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
1425 goto err;
1426 len += 20;
1427 note_crypto_pk_op(REND_SERVER);
1428 r = crypto_pk_private_sign_digest(intro_key, buf+len, sizeof(buf)-len,
1429 buf, len);
1430 if (r<0) {
1431 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
1432 reason = END_CIRC_REASON_INTERNAL;
1433 goto err;
1435 len += r;
1437 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1438 RELAY_COMMAND_ESTABLISH_INTRO,
1439 buf, len, circuit->cpath->prev)<0) {
1440 log_info(LD_GENERAL,
1441 "Couldn't send introduction request for service %s on circuit %d",
1442 serviceid, circuit->_base.n_circ_id);
1443 reason = END_CIRC_REASON_INTERNAL;
1444 goto err;
1447 return;
1448 err:
1449 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1452 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
1453 * live introduction point, and note that the service descriptor is
1454 * now out-of-date.*/
1456 rend_service_intro_established(origin_circuit_t *circuit,
1457 const uint8_t *request,
1458 size_t request_len)
1460 rend_service_t *service;
1461 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1462 (void) request;
1463 (void) request_len;
1465 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
1466 log_warn(LD_PROTOCOL,
1467 "received INTRO_ESTABLISHED cell on non-intro circuit.");
1468 goto err;
1470 tor_assert(circuit->rend_data);
1471 service = rend_service_get_by_pk_digest_and_version(
1472 circuit->rend_data->rend_pk_digest,
1473 circuit->rend_data->rend_desc_version);
1474 if (!service) {
1475 log_warn(LD_REND, "Unknown service on introduction circuit %d.",
1476 circuit->_base.n_circ_id);
1477 goto err;
1479 service->desc_is_dirty = time(NULL);
1480 circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
1482 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
1483 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1484 log_info(LD_REND,
1485 "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
1486 circuit->_base.n_circ_id, serviceid);
1488 return 0;
1489 err:
1490 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
1491 return -1;
1494 /** Called once a circuit to a rendezvous point is established: sends a
1495 * RELAY_COMMAND_RENDEZVOUS1 cell.
1497 void
1498 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
1500 rend_service_t *service;
1501 char buf[RELAY_PAYLOAD_SIZE];
1502 crypt_path_t *hop;
1503 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1504 char hexcookie[9];
1505 int reason;
1507 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1508 tor_assert(circuit->cpath);
1509 tor_assert(circuit->build_state);
1510 tor_assert(circuit->rend_data);
1511 hop = circuit->build_state->pending_final_cpath;
1512 tor_assert(hop);
1514 base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
1515 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1516 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1518 log_info(LD_REND,
1519 "Done building circuit %d to rendezvous with "
1520 "cookie %s for service %s",
1521 circuit->_base.n_circ_id, hexcookie, serviceid);
1523 service = rend_service_get_by_pk_digest_and_version(
1524 circuit->rend_data->rend_pk_digest,
1525 circuit->rend_data->rend_desc_version);
1526 if (!service) {
1527 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
1528 "introduction circuit.");
1529 reason = END_CIRC_REASON_INTERNAL;
1530 goto err;
1533 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
1534 memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
1535 if (crypto_dh_get_public(hop->dh_handshake_state,
1536 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
1537 log_warn(LD_GENERAL,"Couldn't get DH public key.");
1538 reason = END_CIRC_REASON_INTERNAL;
1539 goto err;
1541 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
1542 DIGEST_LEN);
1544 /* Send the cell */
1545 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1546 RELAY_COMMAND_RENDEZVOUS1,
1547 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
1548 circuit->cpath->prev)<0) {
1549 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
1550 reason = END_CIRC_REASON_INTERNAL;
1551 goto err;
1554 crypto_dh_free(hop->dh_handshake_state);
1555 hop->dh_handshake_state = NULL;
1557 /* Append the cpath entry. */
1558 hop->state = CPATH_STATE_OPEN;
1559 /* set the windows to default. these are the windows
1560 * that bob thinks alice has.
1562 hop->package_window = circuit_initial_package_window();
1563 hop->deliver_window = CIRCWINDOW_START;
1565 onion_append_to_cpath(&circuit->cpath, hop);
1566 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
1568 /* Change the circuit purpose. */
1569 circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
1571 return;
1572 err:
1573 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1577 * Manage introduction points
1580 /** Return the (possibly non-open) introduction circuit ending at
1581 * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
1582 * which publishes descriptor of version <b>desc_version</b>. Return
1583 * NULL if no such service is found.
1585 static origin_circuit_t *
1586 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
1587 int desc_version)
1589 origin_circuit_t *circ = NULL;
1591 tor_assert(intro);
1592 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1593 CIRCUIT_PURPOSE_S_INTRO))) {
1594 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1595 intro->extend_info->identity_digest, DIGEST_LEN) &&
1596 circ->rend_data &&
1597 circ->rend_data->rend_desc_version == desc_version) {
1598 return circ;
1602 circ = NULL;
1603 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1604 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
1605 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1606 intro->extend_info->identity_digest, DIGEST_LEN) &&
1607 circ->rend_data &&
1608 circ->rend_data->rend_desc_version == desc_version) {
1609 return circ;
1612 return NULL;
1615 /** Determine the responsible hidden service directories for the
1616 * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
1617 * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
1618 * purposes. */
1619 static void
1620 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
1621 smartlist_t *descs, const char *service_id,
1622 int seconds_valid)
1624 int i, j, failed_upload = 0;
1625 smartlist_t *responsible_dirs = smartlist_create();
1626 smartlist_t *successful_uploads = smartlist_create();
1627 routerstatus_t *hs_dir;
1628 for (i = 0; i < smartlist_len(descs); i++) {
1629 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
1630 /* Determine responsible dirs. */
1631 if (hid_serv_get_responsible_directories(responsible_dirs,
1632 desc->desc_id) < 0) {
1633 log_warn(LD_REND, "Could not determine the responsible hidden service "
1634 "directories to post descriptors to.");
1635 smartlist_free(responsible_dirs);
1636 smartlist_free(successful_uploads);
1637 return;
1639 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
1640 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1641 hs_dir = smartlist_get(responsible_dirs, j);
1642 if (smartlist_digest_isin(renddesc->successful_uploads,
1643 hs_dir->identity_digest))
1644 /* Don't upload descriptor if we succeeded in doing so last time. */
1645 continue;
1646 if (!router_get_by_digest(hs_dir->identity_digest)) {
1647 log_info(LD_REND, "Not sending publish request for v2 descriptor to "
1648 "hidden service directory '%s'; we don't have its "
1649 "router descriptor. Queuing for later upload.",
1650 hs_dir->nickname);
1651 failed_upload = -1;
1652 continue;
1654 /* Send publish request. */
1655 directory_initiate_command_routerstatus(hs_dir,
1656 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
1657 ROUTER_PURPOSE_GENERAL,
1658 1, NULL, desc->desc_str,
1659 strlen(desc->desc_str), 0);
1660 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1661 desc->desc_id, DIGEST_LEN);
1662 log_info(LD_REND, "Sending publish request for v2 descriptor for "
1663 "service '%s' with descriptor ID '%s' with validity "
1664 "of %d seconds to hidden service directory '%s' on "
1665 "port %d.",
1666 safe_str(service_id),
1667 safe_str(desc_id_base32),
1668 seconds_valid,
1669 hs_dir->nickname,
1670 hs_dir->dir_port);
1671 /* Remember successful upload to this router for next time. */
1672 if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
1673 smartlist_add(successful_uploads, hs_dir->identity_digest);
1675 smartlist_clear(responsible_dirs);
1677 if (!failed_upload) {
1678 if (renddesc->successful_uploads) {
1679 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
1680 smartlist_free(renddesc->successful_uploads);
1681 renddesc->successful_uploads = NULL;
1683 renddesc->all_uploads_performed = 1;
1684 } else {
1685 /* Remember which routers worked this time, so that we don't upload the
1686 * descriptor to them again. */
1687 if (!renddesc->successful_uploads)
1688 renddesc->successful_uploads = smartlist_create();
1689 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
1690 if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
1691 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
1692 smartlist_add(renddesc->successful_uploads, hsdir_id);
1696 smartlist_free(responsible_dirs);
1697 smartlist_free(successful_uploads);
1700 /** Encode and sign up-to-date v0 and/or v2 service descriptors for
1701 * <b>service</b>, and upload it/them to all the dirservers/to the
1702 * responsible hidden service directories.
1704 static void
1705 upload_service_descriptor(rend_service_t *service)
1707 time_t now = time(NULL);
1708 int rendpostperiod;
1709 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1710 int uploaded = 0;
1712 rendpostperiod = get_options()->RendPostPeriod;
1714 /* Upload unversioned (v0) descriptor? */
1715 if (service->descriptor_version == 0 &&
1716 get_options()->PublishHidServDescriptors) {
1717 char *desc;
1718 size_t desc_len;
1719 /* Encode the descriptor. */
1720 if (rend_encode_service_descriptor(service->desc,
1721 service->private_key,
1722 &desc, &desc_len)<0) {
1723 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1724 "not uploading.");
1725 return;
1728 /* Post it to the dirservers */
1729 rend_get_service_id(service->desc->pk, serviceid);
1730 log_info(LD_REND, "Sending publish request for hidden service %s",
1731 serviceid);
1732 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
1733 ROUTER_PURPOSE_GENERAL,
1734 HIDSERV_AUTHORITY, desc, desc_len, 0);
1735 tor_free(desc);
1736 service->next_upload_time = now + rendpostperiod;
1737 uploaded = 1;
1740 /* Upload v2 descriptor? */
1741 if (service->descriptor_version == 2 &&
1742 get_options()->PublishHidServDescriptors) {
1743 networkstatus_t *c = networkstatus_get_latest_consensus();
1744 if (c && smartlist_len(c->routerstatus_list) > 0) {
1745 int seconds_valid, i, j, num_descs;
1746 smartlist_t *descs = smartlist_create();
1747 smartlist_t *client_cookies = smartlist_create();
1748 /* Either upload a single descriptor (including replicas) or one
1749 * descriptor for each authorized client in case of authorization
1750 * type 'stealth'. */
1751 num_descs = service->auth_type == REND_STEALTH_AUTH ?
1752 smartlist_len(service->clients) : 1;
1753 for (j = 0; j < num_descs; j++) {
1754 crypto_pk_env_t *client_key = NULL;
1755 rend_authorized_client_t *client = NULL;
1756 smartlist_clear(client_cookies);
1757 switch (service->auth_type) {
1758 case REND_NO_AUTH:
1759 /* Do nothing here. */
1760 break;
1761 case REND_BASIC_AUTH:
1762 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
1763 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
1764 break;
1765 case REND_STEALTH_AUTH:
1766 client = smartlist_get(service->clients, j);
1767 client_key = client->client_key;
1768 smartlist_add(client_cookies, client->descriptor_cookie);
1769 break;
1771 /* Encode the current descriptor. */
1772 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1773 now, 0,
1774 service->auth_type,
1775 client_key,
1776 client_cookies);
1777 if (seconds_valid < 0) {
1778 log_warn(LD_BUG, "Internal error: couldn't encode service "
1779 "descriptor; not uploading.");
1780 smartlist_free(descs);
1781 smartlist_free(client_cookies);
1782 return;
1784 /* Post the current descriptors to the hidden service directories. */
1785 rend_get_service_id(service->desc->pk, serviceid);
1786 log_info(LD_REND, "Sending publish request for hidden service %s",
1787 serviceid);
1788 directory_post_to_hs_dir(service->desc, descs, serviceid,
1789 seconds_valid);
1790 /* Free memory for descriptors. */
1791 for (i = 0; i < smartlist_len(descs); i++)
1792 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1793 smartlist_clear(descs);
1794 /* Update next upload time. */
1795 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
1796 > rendpostperiod)
1797 service->next_upload_time = now + rendpostperiod;
1798 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
1799 service->next_upload_time = now + seconds_valid + 1;
1800 else
1801 service->next_upload_time = now + seconds_valid -
1802 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
1803 /* Post also the next descriptors, if necessary. */
1804 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
1805 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1806 now, 1,
1807 service->auth_type,
1808 client_key,
1809 client_cookies);
1810 if (seconds_valid < 0) {
1811 log_warn(LD_BUG, "Internal error: couldn't encode service "
1812 "descriptor; not uploading.");
1813 smartlist_free(descs);
1814 smartlist_free(client_cookies);
1815 return;
1817 directory_post_to_hs_dir(service->desc, descs, serviceid,
1818 seconds_valid);
1819 /* Free memory for descriptors. */
1820 for (i = 0; i < smartlist_len(descs); i++)
1821 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1822 smartlist_clear(descs);
1825 smartlist_free(descs);
1826 smartlist_free(client_cookies);
1827 uploaded = 1;
1828 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
1832 /* If not uploaded, try again in one minute. */
1833 if (!uploaded)
1834 service->next_upload_time = now + 60;
1836 /* Unmark dirty flag of this service. */
1837 service->desc_is_dirty = 0;
1840 /** For every service, check how many intro points it currently has, and:
1841 * - Pick new intro points as necessary.
1842 * - Launch circuits to any new intro points.
1844 void
1845 rend_services_introduce(void)
1847 int i,j,r;
1848 routerinfo_t *router;
1849 rend_service_t *service;
1850 rend_intro_point_t *intro;
1851 int changed, prev_intro_nodes;
1852 smartlist_t *intro_routers;
1853 time_t now;
1854 or_options_t *options = get_options();
1856 intro_routers = smartlist_create();
1857 now = time(NULL);
1859 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1860 smartlist_clear(intro_routers);
1861 service = smartlist_get(rend_service_list, i);
1863 tor_assert(service);
1864 changed = 0;
1865 if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
1866 /* One period has elapsed; we can try building circuits again. */
1867 service->intro_period_started = now;
1868 service->n_intro_circuits_launched = 0;
1869 } else if (service->n_intro_circuits_launched >=
1870 MAX_INTRO_CIRCS_PER_PERIOD) {
1871 /* We have failed too many times in this period; wait for the next
1872 * one before we try again. */
1873 continue;
1876 /* Find out which introduction points we have in progress for this
1877 service. */
1878 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1879 intro = smartlist_get(service->intro_nodes, j);
1880 router = router_get_by_digest(intro->extend_info->identity_digest);
1881 if (!router || !find_intro_circuit(intro, service->pk_digest,
1882 service->descriptor_version)) {
1883 log_info(LD_REND,"Giving up on %s as intro point for %s.",
1884 intro->extend_info->nickname, service->service_id);
1885 if (service->desc) {
1886 SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
1887 dintro, {
1888 if (!memcmp(dintro->extend_info->identity_digest,
1889 intro->extend_info->identity_digest, DIGEST_LEN)) {
1890 log_info(LD_REND, "The intro point we are giving up on was "
1891 "included in the last published descriptor. "
1892 "Marking current descriptor as dirty.");
1893 service->desc_is_dirty = now;
1897 rend_intro_point_free(intro);
1898 smartlist_del(service->intro_nodes,j--);
1899 changed = 1;
1901 if (router)
1902 smartlist_add(intro_routers, router);
1905 /* We have enough intro points, and the intro points we thought we had were
1906 * all connected.
1908 if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
1909 /* We have all our intro points! Start a fresh period and reset the
1910 * circuit count. */
1911 service->intro_period_started = now;
1912 service->n_intro_circuits_launched = 0;
1913 continue;
1916 /* Remember how many introduction circuits we started with. */
1917 prev_intro_nodes = smartlist_len(service->intro_nodes);
1918 /* We have enough directory information to start establishing our
1919 * intro points. We want to end up with three intro points, but if
1920 * we're just starting, we launch five and pick the first three that
1921 * complete.
1923 * The ones after the first three will be converted to 'general'
1924 * internal circuits in rend_service_intro_has_opened(), and then
1925 * we'll drop them from the list of intro points next time we
1926 * go through the above "find out which introduction points we have
1927 * in progress" loop. */
1928 #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
1929 for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
1930 NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
1931 router_crn_flags_t flags = CRN_NEED_UPTIME;
1932 if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
1933 flags |= CRN_ALLOW_INVALID;
1934 router = router_choose_random_node(NULL, intro_routers,
1935 options->ExcludeNodes, flags);
1936 if (!router) {
1937 log_warn(LD_REND,
1938 "Could only establish %d introduction points for %s.",
1939 smartlist_len(service->intro_nodes), service->service_id);
1940 break;
1942 changed = 1;
1943 smartlist_add(intro_routers, router);
1944 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
1945 intro->extend_info = extend_info_from_router(router);
1946 if (service->descriptor_version == 2) {
1947 intro->intro_key = crypto_new_pk_env();
1948 tor_assert(!crypto_pk_generate_key(intro->intro_key));
1950 smartlist_add(service->intro_nodes, intro);
1951 log_info(LD_REND, "Picked router %s as an intro point for %s.",
1952 router->nickname, service->service_id);
1955 /* If there's no need to launch new circuits, stop here. */
1956 if (!changed)
1957 continue;
1959 /* Establish new introduction points. */
1960 for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
1961 intro = smartlist_get(service->intro_nodes, j);
1962 r = rend_service_launch_establish_intro(service, intro);
1963 if (r<0) {
1964 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
1965 intro->extend_info->nickname, service->service_id);
1969 smartlist_free(intro_routers);
1972 /** Regenerate and upload rendezvous service descriptors for all
1973 * services, if necessary. If the descriptor has been dirty enough
1974 * for long enough, definitely upload; else only upload when the
1975 * periodic timeout has expired.
1977 * For the first upload, pick a random time between now and two periods
1978 * from now, and pick it independently for each service.
1980 void
1981 rend_consider_services_upload(time_t now)
1983 int i;
1984 rend_service_t *service;
1985 int rendpostperiod = get_options()->RendPostPeriod;
1987 if (!get_options()->PublishHidServDescriptors)
1988 return;
1990 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1991 service = smartlist_get(rend_service_list, i);
1992 if (!service->next_upload_time) { /* never been uploaded yet */
1993 /* The fixed lower bound of 30 seconds ensures that the descriptor
1994 * is stable before being published. See comment below. */
1995 service->next_upload_time =
1996 now + 30 + crypto_rand_int(2*rendpostperiod);
1998 if (service->next_upload_time < now ||
1999 (service->desc_is_dirty &&
2000 service->desc_is_dirty < now-30)) {
2001 /* if it's time, or if the directory servers have a wrong service
2002 * descriptor and ours has been stable for 30 seconds, upload a
2003 * new one of each format. */
2004 rend_service_update_descriptor(service);
2005 upload_service_descriptor(service);
2010 /** True if the list of available router descriptors might have changed so
2011 * that we should have a look whether we can republish previously failed
2012 * rendezvous service descriptors. */
2013 static int consider_republishing_rend_descriptors = 1;
2015 /** Called when our internal view of the directory has changed, so that we
2016 * might have router descriptors of hidden service directories available that
2017 * we did not have before. */
2018 void
2019 rend_hsdir_routers_changed(void)
2021 consider_republishing_rend_descriptors = 1;
2024 /** Consider republication of v2 rendezvous service descriptors that failed
2025 * previously, but without regenerating descriptor contents.
2027 void
2028 rend_consider_descriptor_republication(void)
2030 int i;
2031 rend_service_t *service;
2033 if (!consider_republishing_rend_descriptors)
2034 return;
2035 consider_republishing_rend_descriptors = 0;
2037 if (!get_options()->PublishHidServDescriptors)
2038 return;
2040 for (i=0; i < smartlist_len(rend_service_list); ++i) {
2041 service = smartlist_get(rend_service_list, i);
2042 if (service->descriptor_version && service->desc &&
2043 !service->desc->all_uploads_performed) {
2044 /* If we failed in uploading a descriptor last time, try again *without*
2045 * updating the descriptor's contents. */
2046 upload_service_descriptor(service);
2051 /** Log the status of introduction points for all rendezvous services
2052 * at log severity <b>severity</b>.
2054 void
2055 rend_service_dump_stats(int severity)
2057 int i,j;
2058 rend_service_t *service;
2059 rend_intro_point_t *intro;
2060 const char *safe_name;
2061 origin_circuit_t *circ;
2063 for (i=0; i < smartlist_len(rend_service_list); ++i) {
2064 service = smartlist_get(rend_service_list, i);
2065 log(severity, LD_GENERAL, "Service configured in \"%s\":",
2066 service->directory);
2067 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
2068 intro = smartlist_get(service->intro_nodes, j);
2069 safe_name = safe_str(intro->extend_info->nickname);
2071 circ = find_intro_circuit(intro, service->pk_digest,
2072 service->descriptor_version);
2073 if (!circ) {
2074 log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
2075 j, safe_name);
2076 continue;
2078 log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
2079 j, safe_name, circuit_state_to_string(circ->_base.state));
2084 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
2085 * 'circ', and look up the port and address based on conn-\>port.
2086 * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
2087 * or 0 for success.
2090 rend_service_set_connection_addr_port(edge_connection_t *conn,
2091 origin_circuit_t *circ)
2093 rend_service_t *service;
2094 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
2095 smartlist_t *matching_ports;
2096 rend_service_port_config_t *chosen_port;
2098 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
2099 tor_assert(circ->rend_data);
2100 log_debug(LD_REND,"beginning to hunt for addr/port");
2101 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
2102 circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
2103 service = rend_service_get_by_pk_digest_and_version(
2104 circ->rend_data->rend_pk_digest,
2105 circ->rend_data->rend_desc_version);
2106 if (!service) {
2107 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
2108 "rendezvous circuit %d; closing.",
2109 serviceid, circ->_base.n_circ_id);
2110 return -1;
2112 matching_ports = smartlist_create();
2113 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
2115 if (conn->_base.port == p->virtual_port) {
2116 smartlist_add(matching_ports, p);
2119 chosen_port = smartlist_choose(matching_ports);
2120 smartlist_free(matching_ports);
2121 if (chosen_port) {
2122 tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
2123 conn->_base.port = chosen_port->real_port;
2124 return 0;
2126 log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
2127 conn->_base.port,serviceid);
2128 return -1;