naked constants are bad
[tor/rransom.git] / src / or / rendservice.c
blob7795db0d7024f74831a115f12e18bbe602bb8c01
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);
15 /** Represents the mapping from a virtual port of a rendezvous service to
16 * a real port on some IP.
18 typedef struct rend_service_port_config_t {
19 uint16_t virtual_port;
20 uint16_t real_port;
21 tor_addr_t real_addr;
22 } rend_service_port_config_t;
24 /** Try to maintain this many intro points per service if possible. */
25 #define NUM_INTRO_POINTS 3
27 /** If we can't build our intro circuits, don't retry for this long. */
28 #define INTRO_CIRC_RETRY_PERIOD (60*5)
29 /** Don't try to build more than this many circuits before giving up
30 * for a while.*/
31 #define MAX_INTRO_CIRCS_PER_PERIOD 10
32 /** How many times will a hidden service operator attempt to connect to
33 * a requested rendezvous point before giving up? */
34 #define MAX_REND_FAILURES 30
35 /** How many seconds should we spend trying to connect to a requested
36 * rendezvous point before giving up? */
37 #define MAX_REND_TIMEOUT 30
39 /** Represents a single hidden service running at this OP. */
40 typedef struct rend_service_t {
41 /* Fields specified in config file */
42 char *directory; /**< where in the filesystem it stores it */
43 smartlist_t *ports; /**< List of rend_service_port_config_t */
44 rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
45 * authorization is performed. */
46 smartlist_t *clients; /**< List of rend_authorized_client_t's of
47 * clients that may access our service. Can be NULL
48 * if no client authorization is performed. */
49 /* Other fields */
50 crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
51 char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
52 * '.onion' */
53 char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
54 smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
55 * or are trying to establish. */
56 time_t intro_period_started; /**< Start of the current period to build
57 * introduction points. */
58 int n_intro_circuits_launched; /**< Count of intro circuits we have
59 * established in this period. */
60 rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
61 time_t desc_is_dirty; /**< Time at which changes to the hidden service
62 * descriptor content occurred, or 0 if it's
63 * up-to-date. */
64 time_t next_upload_time; /**< Scheduled next hidden service descriptor
65 * upload time. */
66 /** Map from digests of Diffie-Hellman values INTRODUCE2 to time_t of when
67 * they were received; used to prevent replays. */
68 digestmap_t *accepted_intros;
69 /** Time at which we last removed expired values from accepted_intros. */
70 time_t last_cleaned_accepted_intros;
71 } rend_service_t;
73 /** A list of rend_service_t's for services run on this OP.
75 static smartlist_t *rend_service_list = NULL;
77 /** Return the number of rendezvous services we have configured. */
78 int
79 num_rend_services(void)
81 if (!rend_service_list)
82 return 0;
83 return smartlist_len(rend_service_list);
86 /** Helper: free storage held by a single service authorized client entry. */
87 static void
88 rend_authorized_client_free(rend_authorized_client_t *client)
90 if (!client)
91 return;
92 if (client->client_key)
93 crypto_free_pk_env(client->client_key);
94 tor_free(client->client_name);
95 tor_free(client);
98 /** Helper for strmap_free. */
99 static void
100 rend_authorized_client_strmap_item_free(void *authorized_client)
102 rend_authorized_client_free(authorized_client);
105 /** Release the storage held by <b>service</b>.
107 static void
108 rend_service_free(rend_service_t *service)
110 if (!service)
111 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);
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 digestmap_free(service->accepted_intros, _tor_free);
131 tor_free(service);
134 /** Release all the storage held in rend_service_list.
136 void
137 rend_service_free_all(void)
139 if (!rend_service_list)
140 return;
142 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
143 rend_service_free(ptr));
144 smartlist_free(rend_service_list);
145 rend_service_list = NULL;
148 /** Validate <b>service</b> and add it to rend_service_list if possible.
150 static void
151 rend_add_service(rend_service_t *service)
153 int i;
154 rend_service_port_config_t *p;
156 service->intro_nodes = smartlist_create();
158 if (service->auth_type != REND_NO_AUTH &&
159 smartlist_len(service->clients) == 0) {
160 log_warn(LD_CONFIG, "Hidden service with client authorization but no "
161 "clients; ignoring.");
162 rend_service_free(service);
163 return;
166 if (!smartlist_len(service->ports)) {
167 log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
168 rend_service_free(service);
169 } else {
170 smartlist_add(rend_service_list, service);
171 log_debug(LD_REND,"Configuring service with directory \"%s\"",
172 service->directory);
173 for (i = 0; i < smartlist_len(service->ports); ++i) {
174 p = smartlist_get(service->ports, i);
175 log_debug(LD_REND,"Service maps port %d to %s:%d",
176 p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
181 /** Parses a real-port to virtual-port mapping and returns a new
182 * rend_service_port_config_t.
184 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
186 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
188 static rend_service_port_config_t *
189 parse_port_config(const char *string)
191 smartlist_t *sl;
192 int virtport;
193 int realport;
194 uint16_t p;
195 tor_addr_t addr;
196 const char *addrport;
197 rend_service_port_config_t *result = NULL;
199 sl = smartlist_create();
200 smartlist_split_string(sl, string, " ",
201 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
202 if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
203 log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
204 goto err;
207 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
208 if (!virtport) {
209 log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
210 "configuration", escaped(smartlist_get(sl,0)));
211 goto err;
214 if (smartlist_len(sl) == 1) {
215 /* No addr:port part; use default. */
216 realport = virtport;
217 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
218 } else {
219 addrport = smartlist_get(sl,1);
220 if (strchr(addrport, ':') || strchr(addrport, '.')) {
221 if (tor_addr_port_parse(addrport, &addr, &p)<0) {
222 log_warn(LD_CONFIG,"Unparseable address in hidden service port "
223 "configuration.");
224 goto err;
226 realport = p?p:virtport;
227 } else {
228 /* No addr:port, no addr -- must be port. */
229 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
230 if (!realport) {
231 log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
232 "service port configuration.", escaped(addrport));
233 goto err;
235 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
239 result = tor_malloc(sizeof(rend_service_port_config_t));
240 result->virtual_port = virtport;
241 result->real_port = realport;
242 tor_addr_copy(&result->real_addr, &addr);
243 err:
244 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
245 smartlist_free(sl);
246 return result;
249 /** Set up rend_service_list, based on the values of HiddenServiceDir and
250 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
251 * failure. (If <b>validate_only</b> is set, parse, warn and return as
252 * normal, but don't actually change the configured services.)
255 rend_config_services(or_options_t *options, int validate_only)
257 config_line_t *line;
258 rend_service_t *service = NULL;
259 rend_service_port_config_t *portcfg;
260 smartlist_t *old_service_list = NULL;
262 if (!validate_only) {
263 old_service_list = rend_service_list;
264 rend_service_list = smartlist_create();
267 for (line = options->RendConfigLines; line; line = line->next) {
268 if (!strcasecmp(line->key, "HiddenServiceDir")) {
269 if (service) { /* register the one we just finished parsing */
270 if (validate_only)
271 rend_service_free(service);
272 else
273 rend_add_service(service);
275 service = tor_malloc_zero(sizeof(rend_service_t));
276 service->directory = tor_strdup(line->value);
277 service->ports = smartlist_create();
278 service->intro_period_started = time(NULL);
279 continue;
281 if (!service) {
282 log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
283 line->key);
284 rend_service_free(service);
285 return -1;
287 if (!strcasecmp(line->key, "HiddenServicePort")) {
288 portcfg = parse_port_config(line->value);
289 if (!portcfg) {
290 rend_service_free(service);
291 return -1;
293 smartlist_add(service->ports, portcfg);
294 } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
295 /* Parse auth type and comma-separated list of client names and add a
296 * rend_authorized_client_t for each client to the service's list
297 * of authorized clients. */
298 smartlist_t *type_names_split, *clients;
299 const char *authname;
300 int num_clients;
301 if (service->auth_type != REND_NO_AUTH) {
302 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
303 "lines for a single service.");
304 rend_service_free(service);
305 return -1;
307 type_names_split = smartlist_create();
308 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
309 if (smartlist_len(type_names_split) < 1) {
310 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
311 "should have been prevented when parsing the "
312 "configuration.");
313 smartlist_free(type_names_split);
314 rend_service_free(service);
315 return -1;
317 authname = smartlist_get(type_names_split, 0);
318 if (!strcasecmp(authname, "basic")) {
319 service->auth_type = REND_BASIC_AUTH;
320 } else if (!strcasecmp(authname, "stealth")) {
321 service->auth_type = REND_STEALTH_AUTH;
322 } else {
323 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
324 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
325 "are recognized.",
326 (char *) smartlist_get(type_names_split, 0));
327 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
328 smartlist_free(type_names_split);
329 rend_service_free(service);
330 return -1;
332 service->clients = smartlist_create();
333 if (smartlist_len(type_names_split) < 2) {
334 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
335 "auth-type '%s', but no client names.",
336 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
337 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
338 smartlist_free(type_names_split);
339 continue;
341 clients = smartlist_create();
342 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
343 ",", SPLIT_SKIP_SPACE, 0);
344 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
345 smartlist_free(type_names_split);
346 /* Remove duplicate client names. */
347 num_clients = smartlist_len(clients);
348 smartlist_sort_strings(clients);
349 smartlist_uniq_strings(clients);
350 if (smartlist_len(clients) < num_clients) {
351 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
352 "duplicate client name(s); removing.",
353 num_clients - smartlist_len(clients));
354 num_clients = smartlist_len(clients);
356 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
358 rend_authorized_client_t *client;
359 size_t len = strlen(client_name);
360 if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
361 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
362 "illegal client name: '%s'. Length must be "
363 "between 1 and %d characters.",
364 client_name, REND_CLIENTNAME_MAX_LEN);
365 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
366 smartlist_free(clients);
367 rend_service_free(service);
368 return -1;
370 if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
371 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
372 "illegal client name: '%s'. Valid "
373 "characters are [A-Za-z0-9+-_].",
374 client_name);
375 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
376 smartlist_free(clients);
377 rend_service_free(service);
378 return -1;
380 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
381 client->client_name = tor_strdup(client_name);
382 smartlist_add(service->clients, client);
383 log_debug(LD_REND, "Adding client name '%s'", client_name);
385 SMARTLIST_FOREACH_END(client_name);
386 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
387 smartlist_free(clients);
388 /* Ensure maximum number of clients. */
389 if ((service->auth_type == REND_BASIC_AUTH &&
390 smartlist_len(service->clients) > 512) ||
391 (service->auth_type == REND_STEALTH_AUTH &&
392 smartlist_len(service->clients) > 16)) {
393 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
394 "client authorization entries, but only a "
395 "maximum of %d entries is allowed for "
396 "authorization type '%s'.",
397 smartlist_len(service->clients),
398 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
399 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
400 rend_service_free(service);
401 return -1;
403 } else {
404 tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
405 if (strcmp(line->value, "2")) {
406 log_warn(LD_CONFIG,
407 "The only supported HiddenServiceVersion is 2.");
408 rend_service_free(service);
409 return -1;
413 if (service) {
414 if (validate_only)
415 rend_service_free(service);
416 else
417 rend_add_service(service);
420 /* If this is a reload and there were hidden services configured before,
421 * keep the introduction points that are still needed and close the
422 * other ones. */
423 if (old_service_list && !validate_only) {
424 smartlist_t *surviving_services = smartlist_create();
425 circuit_t *circ;
427 /* Copy introduction points to new services. */
428 /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
429 * probably ok? */
430 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, new, {
431 SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
432 if (!strcmp(old->directory, new->directory)) {
433 smartlist_add_all(new->intro_nodes, old->intro_nodes);
434 smartlist_clear(old->intro_nodes);
435 smartlist_add(surviving_services, old);
436 break;
441 /* Close introduction circuits of services we don't serve anymore. */
442 /* XXXX it would be nicer if we had a nicer abstraction to use here,
443 * so we could just iterate over the list of services to close, but
444 * once again, this isn't critical-path code. */
445 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
446 if (!circ->marked_for_close &&
447 circ->state == CIRCUIT_STATE_OPEN &&
448 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
449 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
450 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
451 int keep_it = 0;
452 tor_assert(oc->rend_data);
453 SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
454 if (!memcmp(ptr->pk_digest, oc->rend_data->rend_pk_digest,
455 DIGEST_LEN)) {
456 keep_it = 1;
457 break;
460 if (keep_it)
461 continue;
462 log_info(LD_REND, "Closing intro point %s for service %s.",
463 safe_str_client(oc->build_state->chosen_exit->nickname),
464 oc->rend_data->onion_address);
465 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
466 /* XXXX Is there another reason we should use here? */
469 smartlist_free(surviving_services);
470 SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
471 rend_service_free(ptr));
472 smartlist_free(old_service_list);
475 return 0;
478 /** Replace the old value of <b>service</b>-\>desc with one that reflects
479 * the other fields in service.
481 static void
482 rend_service_update_descriptor(rend_service_t *service)
484 rend_service_descriptor_t *d;
485 origin_circuit_t *circ;
486 int i;
488 rend_service_descriptor_free(service->desc);
489 service->desc = NULL;
491 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
492 d->pk = crypto_pk_dup_key(service->private_key);
493 d->timestamp = time(NULL);
494 d->intro_nodes = smartlist_create();
495 /* Support intro protocols 2 and 3. */
496 d->protocols = (1 << 2) + (1 << 3);
498 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
499 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
500 rend_intro_point_t *intro_desc;
501 circ = find_intro_circuit(intro_svc, service->pk_digest);
502 if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
503 continue;
505 /* We have an entirely established intro circuit. */
506 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
507 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
508 if (intro_svc->intro_key)
509 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
510 smartlist_add(d->intro_nodes, intro_desc);
514 /** Load and/or generate private keys for all hidden services, possibly
515 * including keys for client authorization. Return 0 on success, -1 on
516 * failure.
519 rend_service_load_keys(void)
521 int r = 0;
522 char fname[512];
523 char buf[1500];
525 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
526 if (s->private_key)
527 continue;
528 log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
529 s->directory);
531 /* Check/create directory */
532 if (check_private_dir(s->directory, CPD_CREATE) < 0)
533 return -1;
535 /* Load key */
536 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
537 strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
538 >= sizeof(fname)) {
539 log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
540 s->directory);
541 return -1;
543 s->private_key = init_key_from_file(fname, 1, LOG_ERR);
544 if (!s->private_key)
545 return -1;
547 /* Create service file */
548 if (rend_get_service_id(s->private_key, s->service_id)<0) {
549 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
550 return -1;
552 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
553 log_warn(LD_BUG, "Couldn't compute hash of public key.");
554 return -1;
556 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
557 strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
558 >= sizeof(fname)) {
559 log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
560 " \"%s\".", s->directory);
561 return -1;
563 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
564 if (write_str_to_file(fname,buf,0)<0) {
565 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
566 return -1;
569 /* If client authorization is configured, load or generate keys. */
570 if (s->auth_type != REND_NO_AUTH) {
571 char *client_keys_str = NULL;
572 strmap_t *parsed_clients = strmap_new();
573 char cfname[512];
574 FILE *cfile, *hfile;
575 open_file_t *open_cfile = NULL, *open_hfile = NULL;
577 /* Load client keys and descriptor cookies, if available. */
578 if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
579 s->directory)<0) {
580 log_warn(LD_CONFIG, "Directory name too long to store client keys "
581 "file: \"%s\".", s->directory);
582 goto err;
584 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
585 if (client_keys_str) {
586 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
587 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
588 "be parsed.");
589 goto err;
590 } else {
591 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
592 strmap_size(parsed_clients));
593 tor_free(client_keys_str);
597 /* Prepare client_keys and hostname files. */
598 if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
599 0600, &open_cfile))) {
600 log_warn(LD_CONFIG, "Could not open client_keys file %s",
601 escaped(cfname));
602 goto err;
604 if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
605 0600, &open_hfile))) {
606 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
607 goto err;
610 /* Either use loaded keys for configured clients or generate new
611 * ones if a client is new. */
612 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
614 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
615 char service_id[16+1];
616 rend_authorized_client_t *parsed =
617 strmap_get(parsed_clients, client->client_name);
618 int written;
619 size_t len;
620 /* Copy descriptor cookie from parsed entry or create new one. */
621 if (parsed) {
622 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
623 REND_DESC_COOKIE_LEN);
624 } else {
625 crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
627 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
628 client->descriptor_cookie,
629 REND_DESC_COOKIE_LEN) < 0) {
630 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
631 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
632 return -1;
634 /* Copy client key from parsed entry or create new one if required. */
635 if (parsed && parsed->client_key) {
636 client->client_key = crypto_pk_dup_key(parsed->client_key);
637 } else if (s->auth_type == REND_STEALTH_AUTH) {
638 /* Create private key for client. */
639 crypto_pk_env_t *prkey = NULL;
640 if (!(prkey = crypto_new_pk_env())) {
641 log_warn(LD_BUG,"Error constructing client key");
642 goto err;
644 if (crypto_pk_generate_key(prkey)) {
645 log_warn(LD_BUG,"Error generating client key");
646 crypto_free_pk_env(prkey);
647 goto err;
649 if (crypto_pk_check_key(prkey) <= 0) {
650 log_warn(LD_BUG,"Generated client key seems invalid");
651 crypto_free_pk_env(prkey);
652 goto err;
654 client->client_key = prkey;
656 /* Add entry to client_keys file. */
657 desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
658 written = tor_snprintf(buf, sizeof(buf),
659 "client-name %s\ndescriptor-cookie %s\n",
660 client->client_name, desc_cook_out);
661 if (written < 0) {
662 log_warn(LD_BUG, "Could not write client entry.");
663 goto err;
665 if (client->client_key) {
666 char *client_key_out = NULL;
667 crypto_pk_write_private_key_to_string(client->client_key,
668 &client_key_out, &len);
669 if (rend_get_service_id(client->client_key, service_id)<0) {
670 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
671 tor_free(client_key_out);
672 goto err;
674 written = tor_snprintf(buf + written, sizeof(buf) - written,
675 "client-key\n%s", client_key_out);
676 tor_free(client_key_out);
677 if (written < 0) {
678 log_warn(LD_BUG, "Could not write client entry.");
679 goto err;
683 if (fputs(buf, cfile) < 0) {
684 log_warn(LD_FS, "Could not append client entry to file: %s",
685 strerror(errno));
686 goto err;
689 /* Add line to hostname file. */
690 if (s->auth_type == REND_BASIC_AUTH) {
691 /* Remove == signs (newline has been removed above). */
692 desc_cook_out[strlen(desc_cook_out)-2] = '\0';
693 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
694 s->service_id, desc_cook_out, client->client_name);
695 } else {
696 char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
697 memcpy(extended_desc_cookie, client->descriptor_cookie,
698 REND_DESC_COOKIE_LEN);
699 extended_desc_cookie[REND_DESC_COOKIE_LEN] =
700 ((int)s->auth_type - 1) << 4;
701 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
702 extended_desc_cookie,
703 REND_DESC_COOKIE_LEN+1) < 0) {
704 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
705 goto err;
707 desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
708 newline. */
709 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
710 service_id, desc_cook_out, client->client_name);
713 if (fputs(buf, hfile)<0) {
714 log_warn(LD_FS, "Could not append host entry to file: %s",
715 strerror(errno));
716 goto err;
719 SMARTLIST_FOREACH_END(client);
721 goto done;
722 err:
723 r = -1;
724 done:
725 tor_free(client_keys_str);
726 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
727 if (r<0) {
728 if (open_cfile)
729 abort_writing_to_file(open_cfile);
730 if (open_hfile)
731 abort_writing_to_file(open_hfile);
732 return r;
733 } else {
734 finish_writing_to_file(open_cfile);
735 finish_writing_to_file(open_hfile);
738 } SMARTLIST_FOREACH_END(s);
739 return r;
742 /** Return the service whose public key has a digest of <b>digest</b>, or
743 * NULL if no such service exists.
745 static rend_service_t *
746 rend_service_get_by_pk_digest(const char* digest)
748 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
749 if (!memcmp(s->pk_digest,digest,DIGEST_LEN))
750 return s);
751 return NULL;
754 /** Return 1 if any virtual port in <b>service</b> wants a circuit
755 * to have good uptime. Else return 0.
757 static int
758 rend_service_requires_uptime(rend_service_t *service)
760 int i;
761 rend_service_port_config_t *p;
763 for (i=0; i < smartlist_len(service->ports); ++i) {
764 p = smartlist_get(service->ports, i);
765 if (smartlist_string_num_isin(get_options()->LongLivedPorts,
766 p->virtual_port))
767 return 1;
769 return 0;
772 /** Check client authorization of a given <b>descriptor_cookie</b> for
773 * <b>service</b>. Return 1 for success and 0 for failure. */
774 static int
775 rend_check_authorization(rend_service_t *service,
776 const char *descriptor_cookie)
778 rend_authorized_client_t *auth_client = NULL;
779 tor_assert(service);
780 tor_assert(descriptor_cookie);
781 if (!service->clients) {
782 log_warn(LD_BUG, "Can't check authorization for a service that has no "
783 "authorized clients configured.");
784 return 0;
787 /* Look up client authorization by descriptor cookie. */
788 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
789 if (!memcmp(client->descriptor_cookie, descriptor_cookie,
790 REND_DESC_COOKIE_LEN)) {
791 auth_client = client;
792 break;
795 if (!auth_client) {
796 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
797 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
798 descriptor_cookie, REND_DESC_COOKIE_LEN);
799 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
800 "Dropping cell!",
801 descriptor_cookie_base64);
802 return 0;
805 /* Allow the request. */
806 log_debug(LD_REND, "Client %s authorized for service %s.",
807 auth_client->client_name, service->service_id);
808 return 1;
811 /** Remove elements from <b>service</b>'s replay cache that are old enough to
812 * be noticed by timestamp checking. */
813 static void
814 clean_accepted_intros(rend_service_t *service, time_t now)
816 const time_t cutoff = now - REND_REPLAY_TIME_INTERVAL;
818 service->last_cleaned_accepted_intros = now;
819 if (!service->accepted_intros)
820 return;
822 DIGESTMAP_FOREACH_MODIFY(service->accepted_intros, digest, time_t *, t) {
823 if (*t < cutoff) {
824 tor_free(t);
825 MAP_DEL_CURRENT(digest);
827 } DIGESTMAP_FOREACH_END;
830 /******
831 * Handle cells
832 ******/
834 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
835 * rendezvous point.
838 rend_service_introduce(origin_circuit_t *circuit, const char *request,
839 size_t request_len)
841 char *ptr, *r_cookie;
842 extend_info_t *extend_info = NULL;
843 char buf[RELAY_PAYLOAD_SIZE];
844 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
845 rend_service_t *service;
846 int r, i, v3_shift = 0;
847 size_t len, keylen;
848 crypto_dh_env_t *dh = NULL;
849 origin_circuit_t *launched = NULL;
850 crypt_path_t *cpath = NULL;
851 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
852 char hexcookie[9];
853 int circ_needs_uptime;
854 int reason = END_CIRC_REASON_TORPROTOCOL;
855 crypto_pk_env_t *intro_key;
856 char intro_key_digest[DIGEST_LEN];
857 int auth_type;
858 size_t auth_len = 0;
859 char auth_data[REND_DESC_COOKIE_LEN];
860 crypto_digest_env_t *digest = NULL;
861 time_t now = time(NULL);
862 char diffie_hellman_hash[DIGEST_LEN];
863 time_t *access_time;
864 tor_assert(circuit->rend_data);
866 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
867 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
868 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
869 escaped(serviceid), circuit->_base.n_circ_id);
871 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
872 log_warn(LD_PROTOCOL,
873 "Got an INTRODUCE2 over a non-introduction circuit %d.",
874 circuit->_base.n_circ_id);
875 return -1;
878 /* min key length plus digest length plus nickname length */
879 if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
880 DH_KEY_LEN+42) {
881 log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
882 circuit->_base.n_circ_id);
883 return -1;
886 /* look up service depending on circuit. */
887 service = rend_service_get_by_pk_digest(
888 circuit->rend_data->rend_pk_digest);
889 if (!service) {
890 log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
891 escaped(serviceid));
892 return -1;
895 /* use intro key instead of service key. */
896 intro_key = circuit->intro_key;
898 /* first DIGEST_LEN bytes of request is intro or service pk digest */
899 crypto_pk_get_digest(intro_key, intro_key_digest);
900 if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
901 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
902 request, REND_SERVICE_ID_LEN);
903 log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
904 escaped(serviceid));
905 return -1;
908 keylen = crypto_pk_keysize(intro_key);
909 if (request_len < keylen+DIGEST_LEN) {
910 log_warn(LD_PROTOCOL,
911 "PK-encrypted portion of INTRODUCE2 cell was truncated.");
912 return -1;
914 /* Next N bytes is encrypted with service key */
915 note_crypto_pk_op(REND_SERVER);
916 r = crypto_pk_private_hybrid_decrypt(
917 intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
918 PK_PKCS1_OAEP_PADDING,1);
919 if (r<0) {
920 log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
921 return -1;
923 len = r;
924 if (*buf == 3) {
925 /* Version 3 INTRODUCE2 cell. */
926 time_t ts = 0;
927 v3_shift = 1;
928 auth_type = buf[1];
929 switch (auth_type) {
930 case REND_BASIC_AUTH:
931 /* fall through */
932 case REND_STEALTH_AUTH:
933 auth_len = ntohs(get_uint16(buf+2));
934 if (auth_len != REND_DESC_COOKIE_LEN) {
935 log_info(LD_REND, "Wrong auth data size %d, should be %d.",
936 (int)auth_len, REND_DESC_COOKIE_LEN);
937 return -1;
939 memcpy(auth_data, buf+4, sizeof(auth_data));
940 v3_shift += 2+REND_DESC_COOKIE_LEN;
941 break;
942 case REND_NO_AUTH:
943 break;
944 default:
945 log_info(LD_REND, "Unknown authorization type '%d'", auth_type);
948 /* Check timestamp. */
949 ts = ntohl(get_uint32(buf+1+v3_shift));
950 v3_shift += 4;
951 if ((now - ts) < -1 * REND_REPLAY_TIME_INTERVAL / 2 ||
952 (now - ts) > REND_REPLAY_TIME_INTERVAL / 2) {
953 log_warn(LD_REND, "INTRODUCE2 cell is too %s. Discarding.",
954 (now - ts) < 0 ? "old" : "new");
955 return -1;
958 if (*buf == 2 || *buf == 3) {
959 /* Version 2 INTRODUCE2 cell. */
960 int klen;
961 extend_info = tor_malloc_zero(sizeof(extend_info_t));
962 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+v3_shift+1));
963 extend_info->port = ntohs(get_uint16(buf+v3_shift+5));
964 memcpy(extend_info->identity_digest, buf+v3_shift+7,
965 DIGEST_LEN);
966 extend_info->nickname[0] = '$';
967 base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
968 extend_info->identity_digest, DIGEST_LEN);
970 klen = ntohs(get_uint16(buf+v3_shift+7+DIGEST_LEN));
971 if ((int)len != v3_shift+7+DIGEST_LEN+2+klen+20+128) {
972 log_warn(LD_PROTOCOL, "Bad length %u for version %d INTRODUCE2 cell.",
973 (int)len, *buf);
974 reason = END_CIRC_REASON_TORPROTOCOL;
975 goto err;
977 extend_info->onion_key =
978 crypto_pk_asn1_decode(buf+v3_shift+7+DIGEST_LEN+2, klen);
979 if (!extend_info->onion_key) {
980 log_warn(LD_PROTOCOL, "Error decoding onion key in version %d "
981 "INTRODUCE2 cell.", *buf);
982 reason = END_CIRC_REASON_TORPROTOCOL;
983 goto err;
985 ptr = buf+v3_shift+7+DIGEST_LEN+2+klen;
986 len -= v3_shift+7+DIGEST_LEN+2+klen;
987 } else {
988 char *rp_nickname;
989 size_t nickname_field_len;
990 routerinfo_t *router;
991 int version;
992 if (*buf == 1) {
993 rp_nickname = buf+1;
994 nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
995 version = 1;
996 } else {
997 nickname_field_len = MAX_NICKNAME_LEN+1;
998 rp_nickname = buf;
999 version = 0;
1001 ptr=memchr(rp_nickname,0,nickname_field_len);
1002 if (!ptr || ptr == rp_nickname) {
1003 log_warn(LD_PROTOCOL,
1004 "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
1005 return -1;
1007 if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
1008 (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
1009 log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
1010 return -1;
1012 /* Okay, now we know that a nickname is at the start of the buffer. */
1013 ptr = rp_nickname+nickname_field_len;
1014 len -= nickname_field_len;
1015 len -= rp_nickname - buf; /* also remove header space used by version, if
1016 * any */
1017 router = router_get_by_nickname(rp_nickname, 0);
1018 if (!router) {
1019 log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
1020 escaped_safe_str_client(rp_nickname));
1021 /* XXXX Add a no-such-router reason? */
1022 reason = END_CIRC_REASON_TORPROTOCOL;
1023 goto err;
1026 extend_info = extend_info_from_router(router);
1029 if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
1030 log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
1031 reason = END_CIRC_REASON_TORPROTOCOL;
1032 goto err;
1035 r_cookie = ptr;
1036 base16_encode(hexcookie,9,r_cookie,4);
1038 /* Determine hash of Diffie-Hellman, part 1 to detect replays. */
1039 digest = crypto_new_digest_env();
1040 crypto_digest_add_bytes(digest, ptr+REND_COOKIE_LEN, DH_KEY_LEN);
1041 crypto_digest_get_digest(digest, diffie_hellman_hash, DIGEST_LEN);
1042 crypto_free_digest_env(digest);
1044 /* Check whether there is a past request with the same Diffie-Hellman,
1045 * part 1. */
1046 if (!service->accepted_intros)
1047 service->accepted_intros = digestmap_new();
1049 access_time = digestmap_get(service->accepted_intros, diffie_hellman_hash);
1050 if (access_time != NULL) {
1051 log_warn(LD_REND, "Possible replay detected! We received an "
1052 "INTRODUCE2 cell with same first part of "
1053 "Diffie-Hellman handshake %d seconds ago. Dropping "
1054 "cell.",
1055 (int) (now - *access_time));
1056 goto err;
1059 /* Add request to access history, including time and hash of Diffie-Hellman,
1060 * part 1, and possibly remove requests from the history that are older than
1061 * one hour. */
1062 access_time = tor_malloc(sizeof(time_t));
1063 *access_time = now;
1064 digestmap_set(service->accepted_intros, diffie_hellman_hash, access_time);
1065 if (service->last_cleaned_accepted_intros + REND_REPLAY_TIME_INTERVAL < now)
1066 clean_accepted_intros(service, now);
1068 /* If the service performs client authorization, check included auth data. */
1069 if (service->clients) {
1070 if (auth_len > 0) {
1071 if (rend_check_authorization(service, auth_data)) {
1072 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
1073 } else {
1074 log_info(LD_REND, "The authorization data that are contained in "
1075 "the INTRODUCE2 cell are invalid. Dropping cell.");
1076 reason = END_CIRC_REASON_CONNECTFAILED;
1077 goto err;
1079 } else {
1080 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
1081 "data, but we require client authorization. Dropping cell.");
1082 reason = END_CIRC_REASON_CONNECTFAILED;
1083 goto err;
1087 /* Try DH handshake... */
1088 dh = crypto_dh_new();
1089 if (!dh || crypto_dh_generate_public(dh)<0) {
1090 log_warn(LD_BUG,"Internal error: couldn't build DH state "
1091 "or generate public key.");
1092 reason = END_CIRC_REASON_INTERNAL;
1093 goto err;
1095 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh, ptr+REND_COOKIE_LEN,
1096 DH_KEY_LEN, keys,
1097 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
1098 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
1099 reason = END_CIRC_REASON_INTERNAL;
1100 goto err;
1103 circ_needs_uptime = rend_service_requires_uptime(service);
1105 /* help predict this next time */
1106 rep_hist_note_used_internal(now, circ_needs_uptime, 1);
1108 /* Launch a circuit to alice's chosen rendezvous point.
1110 for (i=0;i<MAX_REND_FAILURES;i++) {
1111 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
1112 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1113 launched = circuit_launch_by_extend_info(
1114 CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
1116 if (launched)
1117 break;
1119 if (!launched) { /* give up */
1120 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
1121 "point %s for service %s.",
1122 escaped_safe_str_client(extend_info->nickname),
1123 serviceid);
1124 reason = END_CIRC_REASON_CONNECTFAILED;
1125 goto err;
1127 log_info(LD_REND,
1128 "Accepted intro; launching circuit to %s "
1129 "(cookie %s) for service %s.",
1130 escaped_safe_str_client(extend_info->nickname),
1131 hexcookie, serviceid);
1132 tor_assert(launched->build_state);
1133 /* Fill in the circuit's state. */
1134 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1135 memcpy(launched->rend_data->rend_pk_digest,
1136 circuit->rend_data->rend_pk_digest,
1137 DIGEST_LEN);
1138 memcpy(launched->rend_data->rend_cookie, r_cookie, REND_COOKIE_LEN);
1139 strlcpy(launched->rend_data->onion_address, service->service_id,
1140 sizeof(launched->rend_data->onion_address));
1141 launched->build_state->pending_final_cpath = cpath =
1142 tor_malloc_zero(sizeof(crypt_path_t));
1143 cpath->magic = CRYPT_PATH_MAGIC;
1144 launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
1146 cpath->dh_handshake_state = dh;
1147 dh = NULL;
1148 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
1149 goto err;
1150 memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
1151 if (extend_info) extend_info_free(extend_info);
1153 return 0;
1154 err:
1155 if (dh) crypto_dh_free(dh);
1156 if (launched)
1157 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
1158 if (extend_info) extend_info_free(extend_info);
1159 return -1;
1162 /** Called when we fail building a rendezvous circuit at some point other
1163 * than the last hop: launches a new circuit to the same rendezvous point.
1165 void
1166 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
1168 origin_circuit_t *newcirc;
1169 cpath_build_state_t *newstate, *oldstate;
1171 tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1173 if (!oldcirc->build_state ||
1174 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
1175 oldcirc->build_state->expiry_time < time(NULL)) {
1176 log_info(LD_REND,
1177 "Attempt to build circuit to %s for rendezvous has failed "
1178 "too many times or expired; giving up.",
1179 oldcirc->build_state ?
1180 oldcirc->build_state->chosen_exit->nickname : "*unknown*");
1181 return;
1184 oldstate = oldcirc->build_state;
1185 tor_assert(oldstate);
1187 if (oldstate->pending_final_cpath == NULL) {
1188 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
1189 "Initiator will retry.");
1190 return;
1193 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
1194 oldstate->chosen_exit->nickname);
1196 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
1197 oldstate->chosen_exit,
1198 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1200 if (!newcirc) {
1201 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
1202 oldstate->chosen_exit->nickname);
1203 return;
1205 newstate = newcirc->build_state;
1206 tor_assert(newstate);
1207 newstate->failure_count = oldstate->failure_count+1;
1208 newstate->expiry_time = oldstate->expiry_time;
1209 newstate->pending_final_cpath = oldstate->pending_final_cpath;
1210 oldstate->pending_final_cpath = NULL;
1212 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
1215 /** Launch a circuit to serve as an introduction point for the service
1216 * <b>service</b> at the introduction point <b>nickname</b>
1218 static int
1219 rend_service_launch_establish_intro(rend_service_t *service,
1220 rend_intro_point_t *intro)
1222 origin_circuit_t *launched;
1224 log_info(LD_REND,
1225 "Launching circuit to introduction point %s for service %s",
1226 escaped_safe_str_client(intro->extend_info->nickname),
1227 service->service_id);
1229 rep_hist_note_used_internal(time(NULL), 1, 0);
1231 ++service->n_intro_circuits_launched;
1232 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
1233 intro->extend_info,
1234 CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
1236 if (!launched) {
1237 log_info(LD_REND,
1238 "Can't launch circuit to establish introduction at %s.",
1239 escaped_safe_str_client(intro->extend_info->nickname));
1240 return -1;
1243 if (memcmp(intro->extend_info->identity_digest,
1244 launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
1245 char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
1246 base16_encode(cann, sizeof(cann),
1247 launched->build_state->chosen_exit->identity_digest,
1248 DIGEST_LEN);
1249 base16_encode(orig, sizeof(orig),
1250 intro->extend_info->identity_digest, DIGEST_LEN);
1251 log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
1252 "but we requested an intro circuit to $%s. Updating "
1253 "our service.", cann, orig);
1254 extend_info_free(intro->extend_info);
1255 intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
1258 launched->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1259 strlcpy(launched->rend_data->onion_address, service->service_id,
1260 sizeof(launched->rend_data->onion_address));
1261 memcpy(launched->rend_data->rend_pk_digest, service->pk_digest, DIGEST_LEN);
1262 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
1263 if (launched->_base.state == CIRCUIT_STATE_OPEN)
1264 rend_service_intro_has_opened(launched);
1265 return 0;
1268 /** Return the number of introduction points that are or have been
1269 * established for the given service address in <b>query</b>. */
1270 static int
1271 count_established_intro_points(const char *query)
1273 int num_ipos = 0;
1274 circuit_t *circ;
1275 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1276 if (!circ->marked_for_close &&
1277 circ->state == CIRCUIT_STATE_OPEN &&
1278 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1279 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
1280 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
1281 if (oc->rend_data &&
1282 !rend_cmp_service_ids(query, oc->rend_data->onion_address))
1283 num_ipos++;
1286 return num_ipos;
1289 /** Called when we're done building a circuit to an introduction point:
1290 * sends a RELAY_ESTABLISH_INTRO cell.
1292 void
1293 rend_service_intro_has_opened(origin_circuit_t *circuit)
1295 rend_service_t *service;
1296 size_t len;
1297 int r;
1298 char buf[RELAY_PAYLOAD_SIZE];
1299 char auth[DIGEST_LEN + 9];
1300 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1301 int reason = END_CIRC_REASON_TORPROTOCOL;
1302 crypto_pk_env_t *intro_key;
1304 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
1305 tor_assert(circuit->cpath);
1306 tor_assert(circuit->rend_data);
1308 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1309 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1311 service = rend_service_get_by_pk_digest(
1312 circuit->rend_data->rend_pk_digest);
1313 if (!service) {
1314 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
1315 serviceid, circuit->_base.n_circ_id);
1316 reason = END_CIRC_REASON_NOSUCHSERVICE;
1317 goto err;
1320 /* If we already have enough introduction circuits for this service,
1321 * redefine this one as a general circuit. */
1322 if (count_established_intro_points(serviceid) > NUM_INTRO_POINTS) {
1323 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
1324 "circuit, but we already have enough. Redefining purpose to "
1325 "general.");
1326 TO_CIRCUIT(circuit)->purpose = CIRCUIT_PURPOSE_C_GENERAL;
1327 circuit_has_opened(circuit);
1328 return;
1331 log_info(LD_REND,
1332 "Established circuit %d as introduction point for service %s",
1333 circuit->_base.n_circ_id, serviceid);
1335 /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
1336 intro_key = circuit->intro_key;
1337 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
1338 r = crypto_pk_asn1_encode(intro_key, buf+2,
1339 RELAY_PAYLOAD_SIZE-2);
1340 if (r < 0) {
1341 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
1342 reason = END_CIRC_REASON_INTERNAL;
1343 goto err;
1345 len = r;
1346 set_uint16(buf, htons((uint16_t)len));
1347 len += 2;
1348 memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
1349 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
1350 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
1351 goto err;
1352 len += 20;
1353 note_crypto_pk_op(REND_SERVER);
1354 r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
1355 if (r<0) {
1356 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
1357 reason = END_CIRC_REASON_INTERNAL;
1358 goto err;
1360 len += r;
1362 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1363 RELAY_COMMAND_ESTABLISH_INTRO,
1364 buf, len, circuit->cpath->prev)<0) {
1365 log_info(LD_GENERAL,
1366 "Couldn't send introduction request for service %s on circuit %d",
1367 serviceid, circuit->_base.n_circ_id);
1368 reason = END_CIRC_REASON_INTERNAL;
1369 goto err;
1372 return;
1373 err:
1374 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1377 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
1378 * live introduction point, and note that the service descriptor is
1379 * now out-of-date.*/
1381 rend_service_intro_established(origin_circuit_t *circuit, const char *request,
1382 size_t request_len)
1384 rend_service_t *service;
1385 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1386 (void) request;
1387 (void) request_len;
1389 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
1390 log_warn(LD_PROTOCOL,
1391 "received INTRO_ESTABLISHED cell on non-intro circuit.");
1392 goto err;
1394 tor_assert(circuit->rend_data);
1395 service = rend_service_get_by_pk_digest(
1396 circuit->rend_data->rend_pk_digest);
1397 if (!service) {
1398 log_warn(LD_REND, "Unknown service on introduction circuit %d.",
1399 circuit->_base.n_circ_id);
1400 goto err;
1402 service->desc_is_dirty = time(NULL);
1403 circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
1405 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
1406 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1407 log_info(LD_REND,
1408 "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
1409 circuit->_base.n_circ_id, serviceid);
1411 return 0;
1412 err:
1413 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
1414 return -1;
1417 /** Called once a circuit to a rendezvous point is established: sends a
1418 * RELAY_COMMAND_RENDEZVOUS1 cell.
1420 void
1421 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
1423 rend_service_t *service;
1424 char buf[RELAY_PAYLOAD_SIZE];
1425 crypt_path_t *hop;
1426 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1427 char hexcookie[9];
1428 int reason;
1430 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1431 tor_assert(circuit->cpath);
1432 tor_assert(circuit->build_state);
1433 tor_assert(circuit->rend_data);
1434 hop = circuit->build_state->pending_final_cpath;
1435 tor_assert(hop);
1437 base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
1438 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1439 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1441 log_info(LD_REND,
1442 "Done building circuit %d to rendezvous with "
1443 "cookie %s for service %s",
1444 circuit->_base.n_circ_id, hexcookie, serviceid);
1446 service = rend_service_get_by_pk_digest(
1447 circuit->rend_data->rend_pk_digest);
1448 if (!service) {
1449 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
1450 "introduction circuit.");
1451 reason = END_CIRC_REASON_INTERNAL;
1452 goto err;
1455 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
1456 memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
1457 if (crypto_dh_get_public(hop->dh_handshake_state,
1458 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
1459 log_warn(LD_GENERAL,"Couldn't get DH public key.");
1460 reason = END_CIRC_REASON_INTERNAL;
1461 goto err;
1463 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
1464 DIGEST_LEN);
1466 /* Send the cell */
1467 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1468 RELAY_COMMAND_RENDEZVOUS1,
1469 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
1470 circuit->cpath->prev)<0) {
1471 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
1472 reason = END_CIRC_REASON_INTERNAL;
1473 goto err;
1476 crypto_dh_free(hop->dh_handshake_state);
1477 hop->dh_handshake_state = NULL;
1479 /* Append the cpath entry. */
1480 hop->state = CPATH_STATE_OPEN;
1481 /* set the windows to default. these are the windows
1482 * that bob thinks alice has.
1484 hop->package_window = circuit_initial_package_window();
1485 hop->deliver_window = CIRCWINDOW_START;
1487 onion_append_to_cpath(&circuit->cpath, hop);
1488 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
1490 /* Change the circuit purpose. */
1491 circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
1493 return;
1494 err:
1495 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1499 * Manage introduction points
1502 /** Return the (possibly non-open) introduction circuit ending at
1503 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
1504 * (<b>desc_version</b> is ignored). Return NULL if no such service is
1505 * found.
1507 static origin_circuit_t *
1508 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
1510 origin_circuit_t *circ = NULL;
1512 tor_assert(intro);
1513 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1514 CIRCUIT_PURPOSE_S_INTRO))) {
1515 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1516 intro->extend_info->identity_digest, DIGEST_LEN) &&
1517 circ->rend_data) {
1518 return circ;
1522 circ = NULL;
1523 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1524 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
1525 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1526 intro->extend_info->identity_digest, DIGEST_LEN) &&
1527 circ->rend_data) {
1528 return circ;
1531 return NULL;
1534 /** Determine the responsible hidden service directories for the
1535 * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
1536 * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
1537 * purposes. */
1538 static void
1539 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
1540 smartlist_t *descs, const char *service_id,
1541 int seconds_valid)
1543 int i, j, failed_upload = 0;
1544 smartlist_t *responsible_dirs = smartlist_create();
1545 smartlist_t *successful_uploads = smartlist_create();
1546 routerstatus_t *hs_dir;
1547 for (i = 0; i < smartlist_len(descs); i++) {
1548 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
1549 /* Determine responsible dirs. */
1550 if (hid_serv_get_responsible_directories(responsible_dirs,
1551 desc->desc_id) < 0) {
1552 log_warn(LD_REND, "Could not determine the responsible hidden service "
1553 "directories to post descriptors to.");
1554 smartlist_free(responsible_dirs);
1555 smartlist_free(successful_uploads);
1556 return;
1558 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
1559 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1560 char *hs_dir_ip;
1561 hs_dir = smartlist_get(responsible_dirs, j);
1562 if (smartlist_digest_isin(renddesc->successful_uploads,
1563 hs_dir->identity_digest))
1564 /* Don't upload descriptor if we succeeded in doing so last time. */
1565 continue;
1566 if (!router_get_by_digest(hs_dir->identity_digest)) {
1567 log_info(LD_REND, "Not sending publish request for v2 descriptor to "
1568 "hidden service directory '%s'; we don't have its "
1569 "router descriptor. Queuing for later upload.",
1570 hs_dir->nickname);
1571 failed_upload = -1;
1572 continue;
1574 /* Send publish request. */
1575 directory_initiate_command_routerstatus(hs_dir,
1576 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
1577 ROUTER_PURPOSE_GENERAL,
1578 1, NULL, desc->desc_str,
1579 strlen(desc->desc_str), 0);
1580 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1581 desc->desc_id, DIGEST_LEN);
1582 hs_dir_ip = tor_dup_ip(hs_dir->addr);
1583 log_info(LD_REND, "Sending publish request for v2 descriptor for "
1584 "service '%s' with descriptor ID '%s' with validity "
1585 "of %d seconds to hidden service directory '%s' on "
1586 "%s:%d.",
1587 safe_str_client(service_id),
1588 safe_str_client(desc_id_base32),
1589 seconds_valid,
1590 hs_dir->nickname,
1591 hs_dir_ip,
1592 hs_dir->or_port);
1593 tor_free(hs_dir_ip);
1594 /* Remember successful upload to this router for next time. */
1595 if (!smartlist_digest_isin(successful_uploads, hs_dir->identity_digest))
1596 smartlist_add(successful_uploads, hs_dir->identity_digest);
1598 smartlist_clear(responsible_dirs);
1600 if (!failed_upload) {
1601 if (renddesc->successful_uploads) {
1602 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
1603 smartlist_free(renddesc->successful_uploads);
1604 renddesc->successful_uploads = NULL;
1606 renddesc->all_uploads_performed = 1;
1607 } else {
1608 /* Remember which routers worked this time, so that we don't upload the
1609 * descriptor to them again. */
1610 if (!renddesc->successful_uploads)
1611 renddesc->successful_uploads = smartlist_create();
1612 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
1613 if (!smartlist_digest_isin(renddesc->successful_uploads, c)) {
1614 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
1615 smartlist_add(renddesc->successful_uploads, hsdir_id);
1619 smartlist_free(responsible_dirs);
1620 smartlist_free(successful_uploads);
1623 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
1624 * and upload it/them to the responsible hidden service directories.
1626 static void
1627 upload_service_descriptor(rend_service_t *service)
1629 time_t now = time(NULL);
1630 int rendpostperiod;
1631 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1632 int uploaded = 0;
1634 rendpostperiod = get_options()->RendPostPeriod;
1636 /* Upload descriptor? */
1637 if (get_options()->PublishHidServDescriptors) {
1638 networkstatus_t *c = networkstatus_get_latest_consensus();
1639 if (c && smartlist_len(c->routerstatus_list) > 0) {
1640 int seconds_valid, i, j, num_descs;
1641 smartlist_t *descs = smartlist_create();
1642 smartlist_t *client_cookies = smartlist_create();
1643 /* Either upload a single descriptor (including replicas) or one
1644 * descriptor for each authorized client in case of authorization
1645 * type 'stealth'. */
1646 num_descs = service->auth_type == REND_STEALTH_AUTH ?
1647 smartlist_len(service->clients) : 1;
1648 for (j = 0; j < num_descs; j++) {
1649 crypto_pk_env_t *client_key = NULL;
1650 rend_authorized_client_t *client = NULL;
1651 smartlist_clear(client_cookies);
1652 switch (service->auth_type) {
1653 case REND_NO_AUTH:
1654 /* Do nothing here. */
1655 break;
1656 case REND_BASIC_AUTH:
1657 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
1658 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
1659 break;
1660 case REND_STEALTH_AUTH:
1661 client = smartlist_get(service->clients, j);
1662 client_key = client->client_key;
1663 smartlist_add(client_cookies, client->descriptor_cookie);
1664 break;
1666 /* Encode the current descriptor. */
1667 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1668 now, 0,
1669 service->auth_type,
1670 client_key,
1671 client_cookies);
1672 if (seconds_valid < 0) {
1673 log_warn(LD_BUG, "Internal error: couldn't encode service "
1674 "descriptor; not uploading.");
1675 smartlist_free(descs);
1676 smartlist_free(client_cookies);
1677 return;
1679 /* Post the current descriptors to the hidden service directories. */
1680 rend_get_service_id(service->desc->pk, serviceid);
1681 log_info(LD_REND, "Sending publish request for hidden service %s",
1682 serviceid);
1683 directory_post_to_hs_dir(service->desc, descs, serviceid,
1684 seconds_valid);
1685 /* Free memory for descriptors. */
1686 for (i = 0; i < smartlist_len(descs); i++)
1687 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1688 smartlist_clear(descs);
1689 /* Update next upload time. */
1690 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
1691 > rendpostperiod)
1692 service->next_upload_time = now + rendpostperiod;
1693 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
1694 service->next_upload_time = now + seconds_valid + 1;
1695 else
1696 service->next_upload_time = now + seconds_valid -
1697 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
1698 /* Post also the next descriptors, if necessary. */
1699 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
1700 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1701 now, 1,
1702 service->auth_type,
1703 client_key,
1704 client_cookies);
1705 if (seconds_valid < 0) {
1706 log_warn(LD_BUG, "Internal error: couldn't encode service "
1707 "descriptor; not uploading.");
1708 smartlist_free(descs);
1709 smartlist_free(client_cookies);
1710 return;
1712 directory_post_to_hs_dir(service->desc, descs, serviceid,
1713 seconds_valid);
1714 /* Free memory for descriptors. */
1715 for (i = 0; i < smartlist_len(descs); i++)
1716 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1717 smartlist_clear(descs);
1720 smartlist_free(descs);
1721 smartlist_free(client_cookies);
1722 uploaded = 1;
1723 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
1727 /* If not uploaded, try again in one minute. */
1728 if (!uploaded)
1729 service->next_upload_time = now + 60;
1731 /* Unmark dirty flag of this service. */
1732 service->desc_is_dirty = 0;
1735 /** For every service, check how many intro points it currently has, and:
1736 * - Pick new intro points as necessary.
1737 * - Launch circuits to any new intro points.
1739 void
1740 rend_services_introduce(void)
1742 int i,j,r;
1743 routerinfo_t *router;
1744 rend_service_t *service;
1745 rend_intro_point_t *intro;
1746 int changed, prev_intro_nodes;
1747 smartlist_t *intro_routers;
1748 time_t now;
1749 or_options_t *options = get_options();
1751 intro_routers = smartlist_create();
1752 now = time(NULL);
1754 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1755 smartlist_clear(intro_routers);
1756 service = smartlist_get(rend_service_list, i);
1758 tor_assert(service);
1759 changed = 0;
1760 if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
1761 /* One period has elapsed; we can try building circuits again. */
1762 service->intro_period_started = now;
1763 service->n_intro_circuits_launched = 0;
1764 } else if (service->n_intro_circuits_launched >=
1765 MAX_INTRO_CIRCS_PER_PERIOD) {
1766 /* We have failed too many times in this period; wait for the next
1767 * one before we try again. */
1768 continue;
1771 /* Find out which introduction points we have in progress for this
1772 service. */
1773 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1774 intro = smartlist_get(service->intro_nodes, j);
1775 router = router_get_by_digest(intro->extend_info->identity_digest);
1776 if (!router || !find_intro_circuit(intro, service->pk_digest)) {
1777 log_info(LD_REND,"Giving up on %s as intro point for %s.",
1778 intro->extend_info->nickname, service->service_id);
1779 if (service->desc) {
1780 SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
1781 dintro, {
1782 if (!memcmp(dintro->extend_info->identity_digest,
1783 intro->extend_info->identity_digest, DIGEST_LEN)) {
1784 log_info(LD_REND, "The intro point we are giving up on was "
1785 "included in the last published descriptor. "
1786 "Marking current descriptor as dirty.");
1787 service->desc_is_dirty = now;
1791 rend_intro_point_free(intro);
1792 smartlist_del(service->intro_nodes,j--);
1793 changed = 1;
1795 if (router)
1796 smartlist_add(intro_routers, router);
1799 /* We have enough intro points, and the intro points we thought we had were
1800 * all connected.
1802 if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
1803 /* We have all our intro points! Start a fresh period and reset the
1804 * circuit count. */
1805 service->intro_period_started = now;
1806 service->n_intro_circuits_launched = 0;
1807 continue;
1810 /* Remember how many introduction circuits we started with. */
1811 prev_intro_nodes = smartlist_len(service->intro_nodes);
1812 /* We have enough directory information to start establishing our
1813 * intro points. We want to end up with three intro points, but if
1814 * we're just starting, we launch five and pick the first three that
1815 * complete.
1817 * The ones after the first three will be converted to 'general'
1818 * internal circuits in rend_service_intro_has_opened(), and then
1819 * we'll drop them from the list of intro points next time we
1820 * go through the above "find out which introduction points we have
1821 * in progress" loop. */
1822 #define NUM_INTRO_POINTS_INIT (NUM_INTRO_POINTS + 2)
1823 for (j=prev_intro_nodes; j < (prev_intro_nodes == 0 ?
1824 NUM_INTRO_POINTS_INIT : NUM_INTRO_POINTS); ++j) {
1825 router_crn_flags_t flags = CRN_NEED_UPTIME;
1826 if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
1827 flags |= CRN_ALLOW_INVALID;
1828 router = router_choose_random_node(intro_routers,
1829 options->ExcludeNodes, flags);
1830 if (!router) {
1831 log_warn(LD_REND,
1832 "Could only establish %d introduction points for %s.",
1833 smartlist_len(service->intro_nodes), service->service_id);
1834 break;
1836 changed = 1;
1837 smartlist_add(intro_routers, router);
1838 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
1839 intro->extend_info = extend_info_from_router(router);
1840 intro->intro_key = crypto_new_pk_env();
1841 tor_assert(!crypto_pk_generate_key(intro->intro_key));
1842 smartlist_add(service->intro_nodes, intro);
1843 log_info(LD_REND, "Picked router %s as an intro point for %s.",
1844 router->nickname, service->service_id);
1847 /* If there's no need to launch new circuits, stop here. */
1848 if (!changed)
1849 continue;
1851 /* Establish new introduction points. */
1852 for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
1853 intro = smartlist_get(service->intro_nodes, j);
1854 r = rend_service_launch_establish_intro(service, intro);
1855 if (r<0) {
1856 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
1857 intro->extend_info->nickname, service->service_id);
1861 smartlist_free(intro_routers);
1864 /** Regenerate and upload rendezvous service descriptors for all
1865 * services, if necessary. If the descriptor has been dirty enough
1866 * for long enough, definitely upload; else only upload when the
1867 * periodic timeout has expired.
1869 * For the first upload, pick a random time between now and two periods
1870 * from now, and pick it independently for each service.
1872 void
1873 rend_consider_services_upload(time_t now)
1875 int i;
1876 rend_service_t *service;
1877 int rendpostperiod = get_options()->RendPostPeriod;
1879 if (!get_options()->PublishHidServDescriptors)
1880 return;
1882 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1883 service = smartlist_get(rend_service_list, i);
1884 if (!service->next_upload_time) { /* never been uploaded yet */
1885 /* The fixed lower bound of 30 seconds ensures that the descriptor
1886 * is stable before being published. See comment below. */
1887 service->next_upload_time =
1888 now + 30 + crypto_rand_int(2*rendpostperiod);
1890 if (service->next_upload_time < now ||
1891 (service->desc_is_dirty &&
1892 service->desc_is_dirty < now-30)) {
1893 /* if it's time, or if the directory servers have a wrong service
1894 * descriptor and ours has been stable for 30 seconds, upload a
1895 * new one of each format. */
1896 rend_service_update_descriptor(service);
1897 upload_service_descriptor(service);
1902 /** True if the list of available router descriptors might have changed so
1903 * that we should have a look whether we can republish previously failed
1904 * rendezvous service descriptors. */
1905 static int consider_republishing_rend_descriptors = 1;
1907 /** Called when our internal view of the directory has changed, so that we
1908 * might have router descriptors of hidden service directories available that
1909 * we did not have before. */
1910 void
1911 rend_hsdir_routers_changed(void)
1913 consider_republishing_rend_descriptors = 1;
1916 /** Consider republication of v2 rendezvous service descriptors that failed
1917 * previously, but without regenerating descriptor contents.
1919 void
1920 rend_consider_descriptor_republication(void)
1922 int i;
1923 rend_service_t *service;
1925 if (!consider_republishing_rend_descriptors)
1926 return;
1927 consider_republishing_rend_descriptors = 0;
1929 if (!get_options()->PublishHidServDescriptors)
1930 return;
1932 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1933 service = smartlist_get(rend_service_list, i);
1934 if (service->desc && !service->desc->all_uploads_performed) {
1935 /* If we failed in uploading a descriptor last time, try again *without*
1936 * updating the descriptor's contents. */
1937 upload_service_descriptor(service);
1942 /** Log the status of introduction points for all rendezvous services
1943 * at log severity <b>severity</b>.
1945 void
1946 rend_service_dump_stats(int severity)
1948 int i,j;
1949 rend_service_t *service;
1950 rend_intro_point_t *intro;
1951 const char *safe_name;
1952 origin_circuit_t *circ;
1954 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1955 service = smartlist_get(rend_service_list, i);
1956 log(severity, LD_GENERAL, "Service configured in \"%s\":",
1957 service->directory);
1958 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1959 intro = smartlist_get(service->intro_nodes, j);
1960 safe_name = safe_str_client(intro->extend_info->nickname);
1962 circ = find_intro_circuit(intro, service->pk_digest);
1963 if (!circ) {
1964 log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
1965 j, safe_name);
1966 continue;
1968 log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
1969 j, safe_name, circuit_state_to_string(circ->_base.state));
1974 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
1975 * 'circ', and look up the port and address based on conn-\>port.
1976 * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
1977 * or 0 for success.
1980 rend_service_set_connection_addr_port(edge_connection_t *conn,
1981 origin_circuit_t *circ)
1983 rend_service_t *service;
1984 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1985 smartlist_t *matching_ports;
1986 rend_service_port_config_t *chosen_port;
1988 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
1989 tor_assert(circ->rend_data);
1990 log_debug(LD_REND,"beginning to hunt for addr/port");
1991 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1992 circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1993 service = rend_service_get_by_pk_digest(
1994 circ->rend_data->rend_pk_digest);
1995 if (!service) {
1996 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
1997 "rendezvous circuit %d; closing.",
1998 serviceid, circ->_base.n_circ_id);
1999 return -1;
2001 matching_ports = smartlist_create();
2002 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
2004 if (conn->_base.port == p->virtual_port) {
2005 smartlist_add(matching_ports, p);
2008 chosen_port = smartlist_choose(matching_ports);
2009 smartlist_free(matching_ports);
2010 if (chosen_port) {
2011 tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
2012 conn->_base.port = chosen_port->real_port;
2013 return 0;
2015 log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
2016 conn->_base.port,serviceid);
2017 return -1;