Next patch from Karsten: client-side configuration stuff for proposal 121.
[tor.git] / src / or / rendservice.c
blobb6b929f6f7065c481e9f653684a8ade22e248b13
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2008, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char rendservice_c_id[] =
6 "$Id$";
8 /**
9 * \file rendservice.c
10 * \brief The hidden-service side of rendezvous functionality.
11 **/
13 #include "or.h"
15 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
16 const char *pk_digest,
17 int desc_version);
19 /** Represents the mapping from a virtual port of a rendezvous service to
20 * a real port on some IP.
22 typedef struct rend_service_port_config_t {
23 uint16_t virtual_port;
24 uint16_t real_port;
25 tor_addr_t real_addr;
26 } rend_service_port_config_t;
28 /** Try to maintain this many intro points per service if possible. */
29 #define NUM_INTRO_POINTS 3
31 /** If we can't build our intro circuits, don't retry for this long. */
32 #define INTRO_CIRC_RETRY_PERIOD (60*5)
33 /** Don't try to build more than this many circuits before giving up
34 * for a while.*/
35 #define MAX_INTRO_CIRCS_PER_PERIOD 10
36 /** How many times will a hidden service operator attempt to connect to
37 * a requested rendezvous point before giving up? */
38 #define MAX_REND_FAILURES 30
39 /** How many seconds should we spend trying to connect to a requested
40 * rendezvous point before giving up? */
41 #define MAX_REND_TIMEOUT 30
43 /** Represents a single hidden service running at this OP. */
44 typedef struct rend_service_t {
45 /* Fields specified in config file */
46 char *directory; /**< where in the filesystem it stores it */
47 smartlist_t *ports; /**< List of rend_service_port_config_t */
48 int descriptor_version; /**< Rendezvous descriptor version that will be
49 * published. */
50 rend_auth_type_t auth_type; /**< Client authorization type or 0 if no client
51 * authorization is performed. */
52 smartlist_t *clients; /**< List of rend_authorized_client_t's of
53 * clients that may access our service. Can be NULL
54 * if no client authorization is peformed. */
55 /* Other fields */
56 crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
57 char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
58 * '.onion' */
59 char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
60 smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
61 * or are trying to establish. */
62 time_t intro_period_started; /**< Start of the current period to build
63 * introduction points. */
64 int n_intro_circuits_launched; /**< count of intro circuits we have
65 * established in this period. */
66 rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
67 time_t desc_is_dirty; /**< Time at which changes to the hidden service
68 * descriptor content occurred, or 0 if it's
69 * up-to-date. */
70 time_t next_upload_time; /**< Scheduled next hidden service descriptor
71 * upload time. */
72 } rend_service_t;
74 /** A list of rend_service_t's for services run on this OP.
76 static smartlist_t *rend_service_list = NULL;
78 /** Return the number of rendezvous services we have configured. */
79 int
80 num_rend_services(void)
82 if (!rend_service_list)
83 return 0;
84 return smartlist_len(rend_service_list);
87 /** Helper: free storage held by a single service authorized client entry. */
88 static void
89 rend_authorized_client_free(rend_authorized_client_t *client)
91 if (!client) 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) return;
111 tor_free(service->directory);
112 SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
113 smartlist_free(service->ports);
114 if (service->private_key)
115 crypto_free_pk_env(service->private_key);
116 if (service->intro_nodes) {
117 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
118 rend_intro_point_free(intro););
119 smartlist_free(service->intro_nodes);
121 if (service->desc)
122 rend_service_descriptor_free(service->desc);
123 if (service->clients) {
124 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
125 rend_authorized_client_free(c););
126 smartlist_free(service->clients);
128 tor_free(service);
131 /** Release all the storage held in rend_service_list.
133 void
134 rend_service_free_all(void)
136 if (!rend_service_list) {
137 return;
139 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
140 rend_service_free(ptr));
141 smartlist_free(rend_service_list);
142 rend_service_list = NULL;
145 /** Validate <b>service</b> and add it to rend_service_list if possible.
147 static void
148 rend_add_service(rend_service_t *service)
150 int i;
151 rend_service_port_config_t *p;
153 service->intro_nodes = smartlist_create();
155 /* If the service is configured to publish unversioned (v0) and versioned
156 * descriptors (v2 or higher), split it up into two separate services
157 * (unless it is configured to perform client authorization). */
158 if (service->descriptor_version == -1) {
159 if (service->auth_type == REND_NO_AUTH) {
160 rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
161 v0_service->directory = tor_strdup(service->directory);
162 v0_service->ports = smartlist_create();
163 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
164 rend_service_port_config_t *copy =
165 tor_malloc_zero(sizeof(rend_service_port_config_t));
166 memcpy(copy, p, sizeof(rend_service_port_config_t));
167 smartlist_add(v0_service->ports, copy);
169 v0_service->intro_period_started = service->intro_period_started;
170 v0_service->descriptor_version = 0; /* Unversioned descriptor. */
171 v0_service->auth_type = REND_NO_AUTH;
172 rend_add_service(v0_service);
175 service->descriptor_version = 2; /* Versioned descriptor. */
178 if (service->auth_type != REND_NO_AUTH && !service->descriptor_version) {
179 log_warn(LD_CONFIG, "Hidden service with client authorization and "
180 "version 0 descriptors configured; ignoring.");
181 rend_service_free(service);
182 return;
185 if (service->auth_type != REND_NO_AUTH &&
186 smartlist_len(service->clients) == 0) {
187 log_warn(LD_CONFIG, "Hidden service with client authorization but no "
188 "clients; ignoring.");
189 rend_service_free(service);
190 return;
193 if (!smartlist_len(service->ports)) {
194 log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
195 rend_service_free(service);
196 } else {
197 smartlist_add(rend_service_list, service);
198 log_debug(LD_REND,"Configuring service with directory \"%s\"",
199 service->directory);
200 for (i = 0; i < smartlist_len(service->ports); ++i) {
201 p = smartlist_get(service->ports, i);
202 log_debug(LD_REND,"Service maps port %d to %s:%d",
203 p->virtual_port, fmt_addr(&p->real_addr), p->real_port);
208 /** Parses a real-port to virtual-port mapping and returns a new
209 * rend_service_port_config_t.
211 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
213 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
215 static rend_service_port_config_t *
216 parse_port_config(const char *string)
218 smartlist_t *sl;
219 int virtport;
220 int realport;
221 uint16_t p;
222 tor_addr_t addr;
223 const char *addrport;
224 rend_service_port_config_t *result = NULL;
226 sl = smartlist_create();
227 smartlist_split_string(sl, string, " ",
228 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
229 if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
230 log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
231 goto err;
234 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
235 if (!virtport) {
236 log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
237 "configuration", escaped(smartlist_get(sl,0)));
238 goto err;
241 if (smartlist_len(sl) == 1) {
242 /* No addr:port part; use default. */
243 realport = virtport;
244 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
245 } else {
246 addrport = smartlist_get(sl,1);
247 if (strchr(addrport, ':') || strchr(addrport, '.')) {
248 if (tor_addr_port_parse(addrport, &addr, &p)<0) {
249 log_warn(LD_CONFIG,"Unparseable address in hidden service port "
250 "configuration.");
251 goto err;
253 realport = p?p:virtport;
254 } else {
255 /* No addr:port, no addr -- must be port. */
256 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
257 if (!realport) {
258 log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
259 "service port configuration.", escaped(addrport));
260 goto err;
262 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
266 result = tor_malloc(sizeof(rend_service_port_config_t));
267 result->virtual_port = virtport;
268 result->real_port = realport;
269 tor_addr_copy(&result->real_addr, &addr);
270 err:
271 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
272 smartlist_free(sl);
273 return result;
276 /** Set up rend_service_list, based on the values of HiddenServiceDir and
277 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
278 * failure. (If <b>validate_only</b> is set, parse, warn and return as
279 * normal, but don't actually change the configured services.)
282 rend_config_services(or_options_t *options, int validate_only)
284 config_line_t *line;
285 rend_service_t *service = NULL;
286 rend_service_port_config_t *portcfg;
288 if (!validate_only) {
289 rend_service_free_all();
290 rend_service_list = smartlist_create();
293 for (line = options->RendConfigLines; line; line = line->next) {
294 if (!strcasecmp(line->key, "HiddenServiceDir")) {
295 if (service) {
296 if (validate_only)
297 rend_service_free(service);
298 else
299 rend_add_service(service);
301 service = tor_malloc_zero(sizeof(rend_service_t));
302 service->directory = tor_strdup(line->value);
303 service->ports = smartlist_create();
304 service->intro_period_started = time(NULL);
305 service->descriptor_version = -1; /**< All descriptor versions. */
306 continue;
308 if (!service) {
309 log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
310 line->key);
311 rend_service_free(service);
312 return -1;
314 if (!strcasecmp(line->key, "HiddenServicePort")) {
315 portcfg = parse_port_config(line->value);
316 if (!portcfg) {
317 rend_service_free(service);
318 return -1;
320 smartlist_add(service->ports, portcfg);
321 } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
322 /* Parse auth type and comma-separated list of client names and add a
323 * rend_authorized_client_t for each client to the service's list
324 * of authorized clients. */
325 smartlist_t *type_names_split, *clients;
326 const char *authname;
327 int num_clients;
328 if (service->auth_type != REND_NO_AUTH) {
329 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
330 "lines for a single service.");
331 rend_service_free(service);
332 return -1;
334 type_names_split = smartlist_create();
335 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
336 if (smartlist_len(type_names_split) < 1) {
337 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
338 "should have been prevented when parsing the "
339 "configuration.");
340 smartlist_free(type_names_split);
341 rend_service_free(service);
342 return -1;
344 authname = smartlist_get(type_names_split, 0);
345 if (!strcasecmp(authname, "basic")) {
346 service->auth_type = REND_BASIC_AUTH;
347 } else if (!strcasecmp(authname, "stealth")) {
348 service->auth_type = REND_STEALTH_AUTH;
349 } else {
350 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
351 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
352 "are recognized.",
353 (char *) smartlist_get(type_names_split, 0));
354 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
355 smartlist_free(type_names_split);
356 rend_service_free(service);
357 return -1;
359 service->clients = smartlist_create();
360 if (smartlist_len(type_names_split) < 2) {
361 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
362 "auth-type '%s', but no client names.",
363 service->auth_type == 1 ? "basic" : "stealth");
364 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
365 smartlist_free(type_names_split);
366 continue;
368 clients = smartlist_create();
369 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
370 ",", SPLIT_SKIP_SPACE, 0);
371 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
372 smartlist_free(type_names_split);
373 /* Remove duplicate client names. */
374 num_clients = smartlist_len(clients);
375 smartlist_sort_strings(clients);
376 smartlist_uniq_strings(clients);
377 if (smartlist_len(clients) < num_clients) {
378 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
379 "duplicate client name(s); removing.",
380 num_clients - smartlist_len(clients));
381 num_clients = smartlist_len(clients);
383 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
385 rend_authorized_client_t *client;
386 size_t len = strlen(client_name);
387 if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
388 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
389 "illegal client name: '%s'. Length must be "
390 "between 1 and %d characters.",
391 client_name, REND_CLIENTNAME_MAX_LEN);
392 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
393 smartlist_free(clients);
394 rend_service_free(service);
395 return -1;
397 if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
398 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
399 "illegal client name: '%s'. Valid "
400 "characters are [A-Za-z0-9+-_].",
401 client_name);
402 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
403 smartlist_free(clients);
404 rend_service_free(service);
405 return -1;
407 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
408 client->client_name = tor_strdup(client_name);
409 smartlist_add(service->clients, client);
410 log_debug(LD_REND, "Adding client name '%s'", client_name);
412 SMARTLIST_FOREACH_END(client_name);
413 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
414 smartlist_free(clients);
415 /* Ensure maximum number of clients. */
416 if ((service->auth_type == REND_BASIC_AUTH &&
417 smartlist_len(service->clients) > 512) ||
418 (service->auth_type == REND_STEALTH_AUTH &&
419 smartlist_len(service->clients) > 16)) {
420 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
421 "client authorization entries, but only a "
422 "maximum of %d entries is allowed for "
423 "authorization type '%s'.",
424 smartlist_len(service->clients),
425 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
426 service->auth_type == 1 ? "basic" : "stealth");
427 rend_service_free(service);
428 return -1;
430 } else {
431 smartlist_t *versions;
432 char *version_str;
433 int i, version, ver_ok=1, versions_bitmask = 0;
434 tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
435 versions = smartlist_create();
436 smartlist_split_string(versions, line->value, ",",
437 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
438 for (i = 0; i < smartlist_len(versions); i++) {
439 version_str = smartlist_get(versions, i);
440 if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
441 log_warn(LD_CONFIG,
442 "HiddenServiceVersion can only be 0 and/or 2.");
443 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
444 smartlist_free(versions);
445 rend_service_free(service);
446 return -1;
448 version = (int)tor_parse_long(version_str, 10, 0, INT_MAX, &ver_ok,
449 NULL);
450 if (!ver_ok)
451 continue;
452 versions_bitmask |= 1 << version;
454 /* If exactly one version is set, change descriptor_version to that
455 * value; otherwise leave it at -1. */
456 if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
457 if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
458 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
459 smartlist_free(versions);
462 if (service) {
463 if (validate_only)
464 rend_service_free(service);
465 else
466 rend_add_service(service);
469 return 0;
472 /** Replace the old value of <b>service</b>-\>desc with one that reflects
473 * the other fields in service.
475 static void
476 rend_service_update_descriptor(rend_service_t *service)
478 rend_service_descriptor_t *d;
479 origin_circuit_t *circ;
480 int i;
481 if (service->desc) {
482 rend_service_descriptor_free(service->desc);
483 service->desc = NULL;
485 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
486 d->pk = crypto_pk_dup_key(service->private_key);
487 d->timestamp = time(NULL);
488 d->version = service->descriptor_version;
489 d->intro_nodes = smartlist_create();
490 /* Whoever understands descriptor version 2 also understands intro
491 * protocol 2. So we only support 2. */
492 d->protocols = 1 << 2;
494 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
495 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
496 rend_intro_point_t *intro_desc;
497 circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
498 if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
499 continue;
501 /* We have an entirely established intro circuit. */
502 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
503 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
504 if (intro_svc->intro_key)
505 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
506 smartlist_add(d->intro_nodes, intro_desc);
510 /** Load and/or generate private keys for all hidden services, possibly
511 * including keys for client authorization. Return 0 on success, -1 on
512 * failure.
515 rend_service_load_keys(void)
517 int r = 0;
518 char fname[512];
519 char buf[1500];
521 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
522 if (s->private_key)
523 continue;
524 log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
525 s->directory);
527 /* Check/create directory */
528 if (check_private_dir(s->directory, CPD_CREATE) < 0)
529 return -1;
531 /* Load key */
532 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
533 strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
534 >= sizeof(fname)) {
535 log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
536 s->directory);
537 return -1;
539 s->private_key = init_key_from_file(fname, 1, LOG_ERR);
540 if (!s->private_key)
541 return -1;
543 /* Create service file */
544 if (rend_get_service_id(s->private_key, s->service_id)<0) {
545 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
546 return -1;
548 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
549 log_warn(LD_BUG, "Couldn't compute hash of public key.");
550 return -1;
552 if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
553 strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
554 >= sizeof(fname)) {
555 log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
556 " \"%s\".", s->directory);
557 return -1;
559 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
560 if (write_str_to_file(fname,buf,0)<0) {
561 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
562 return -1;
565 /* If client authorization is configured, load or generate keys. */
566 if (s->auth_type != REND_NO_AUTH) {
567 char *client_keys_str = NULL;
568 strmap_t *parsed_clients = strmap_new();
569 char cfname[512];
570 FILE *cfile, *hfile;
571 open_file_t *open_cfile = NULL, *open_hfile = NULL;
573 /* Load client keys and descriptor cookies, if available. */
574 if (tor_snprintf(cfname, sizeof(cfname), "%s"PATH_SEPARATOR"client_keys",
575 s->directory)<0) {
576 log_warn(LD_CONFIG, "Directory name too long to store client keys "
577 "file: \"%s\".", s->directory);
578 goto err;
580 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
581 if (client_keys_str) {
582 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
583 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
584 "be parsed.");
585 goto err;
586 } else {
587 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
588 strmap_size(parsed_clients));
589 tor_free(client_keys_str);
593 /* Prepare client_keys and hostname files. */
594 if (!(cfile = start_writing_to_stdio_file(cfname, OPEN_FLAGS_REPLACE,
595 0600, &open_cfile))) {
596 log_warn(LD_CONFIG, "Could not open client_keys file %s",
597 escaped(cfname));
598 goto err;
600 if (!(hfile = start_writing_to_stdio_file(fname, OPEN_FLAGS_REPLACE,
601 0600, &open_hfile))) {
602 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(fname));
603 goto err;
606 /* Either use loaded keys for configured clients or generate new
607 * ones if a client is new. */
608 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client)
610 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
611 char service_id[16+1];
612 rend_authorized_client_t *parsed =
613 strmap_get(parsed_clients, client->client_name);
614 int written;
615 size_t len;
616 /* Copy descriptor cookie from parsed entry or create new one. */
617 if (parsed) {
618 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
619 REND_DESC_COOKIE_LEN);
620 } else {
621 crypto_rand(client->descriptor_cookie, REND_DESC_COOKIE_LEN);
623 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
624 client->descriptor_cookie,
625 REND_DESC_COOKIE_LEN) < 0) {
626 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
627 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
628 return -1;
630 /* Copy client key from parsed entry or create new one if required. */
631 if (parsed && parsed->client_key) {
632 client->client_key = crypto_pk_dup_key(parsed->client_key);
633 } else if (s->auth_type == REND_STEALTH_AUTH) {
634 /* Create private key for client. */
635 crypto_pk_env_t *prkey = NULL;
636 if (!(prkey = crypto_new_pk_env())) {
637 log_warn(LD_BUG,"Error constructing client key");
638 goto err;
640 if (crypto_pk_generate_key(prkey)) {
641 log_warn(LD_BUG,"Error generating client key");
642 goto err;
644 if (crypto_pk_check_key(prkey) <= 0) {
645 log_warn(LD_BUG,"Generated client key seems invalid");
646 crypto_free_pk_env(prkey);
647 goto err;
649 client->client_key = prkey;
651 /* Add entry to client_keys file. */
652 desc_cook_out[strlen(desc_cook_out)-1] = '\0'; /* Remove newline. */
653 written = tor_snprintf(buf, sizeof(buf),
654 "client-name %s\ndescriptor-cookie %s\n",
655 client->client_name, desc_cook_out);
656 if (written < 0) {
657 log_warn(LD_BUG, "Could not write client entry.");
658 goto err;
660 if (client->client_key) {
661 char *client_key_out;
662 crypto_pk_write_private_key_to_string(client->client_key,
663 &client_key_out, &len);
664 if (rend_get_service_id(client->client_key, service_id)<0) {
665 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
666 goto err;
668 written = tor_snprintf(buf + written, sizeof(buf) - written,
669 "client-key\n%s", client_key_out);
670 if (written < 0) {
671 log_warn(LD_BUG, "Could not write client entry.");
672 goto err;
676 if (fputs(buf, cfile) < 0) {
677 log_warn(LD_FS, "Could not append client entry to file: %s",
678 strerror(errno));
679 goto err;
682 /* Add line to hostname file. */
683 if (s->auth_type == REND_BASIC_AUTH) {
684 /* Remove == signs (newline has been removed above). */
685 desc_cook_out[strlen(desc_cook_out)-2] = '\0';
686 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
687 s->service_id, desc_cook_out, client->client_name);
688 } else {
689 char extended_desc_cookie[REND_DESC_COOKIE_LEN+1];
690 memcpy(extended_desc_cookie, client->descriptor_cookie,
691 REND_DESC_COOKIE_LEN);
692 extended_desc_cookie[REND_DESC_COOKIE_LEN] =
693 ((int)s->auth_type - 1) << 4;
694 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
695 extended_desc_cookie,
696 REND_DESC_COOKIE_LEN+1) < 0) {
697 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
698 goto err;
700 desc_cook_out[strlen(desc_cook_out)-3] = '\0'; /* Remove A= and
701 newline. */
702 tor_snprintf(buf, sizeof(buf),"%s.onion %s # client: %s\n",
703 service_id, desc_cook_out, client->client_name);
706 if (fputs(buf, hfile)<0) {
707 log_warn(LD_FS, "Could not append host entry to file: %s",
708 strerror(errno));
709 goto err;
712 SMARTLIST_FOREACH_END(client);
714 goto done;
715 err:
716 r = -1;
717 done:
718 tor_free(client_keys_str);
719 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
720 if (r<0) {
721 abort_writing_to_file(open_cfile);
722 abort_writing_to_file(open_hfile);
723 return r;
724 } else {
725 finish_writing_to_file(open_cfile);
726 finish_writing_to_file(open_hfile);
729 } SMARTLIST_FOREACH_END(s);
730 return r;
733 /** Return the service whose public key has a digest of <b>digest</b> and
734 * which publishes the given descriptor <b>version</b>. Return NULL if no
735 * such service exists.
737 static rend_service_t *
738 rend_service_get_by_pk_digest_and_version(const char* digest,
739 uint8_t version)
741 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
742 if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
743 s->descriptor_version == version) return s);
744 return NULL;
747 /** Return 1 if any virtual port in <b>service</b> wants a circuit
748 * to have good uptime. Else return 0.
750 static int
751 rend_service_requires_uptime(rend_service_t *service)
753 int i;
754 rend_service_port_config_t *p;
756 for (i=0; i < smartlist_len(service->ports); ++i) {
757 p = smartlist_get(service->ports, i);
758 if (smartlist_string_num_isin(get_options()->LongLivedPorts,
759 p->virtual_port))
760 return 1;
762 return 0;
765 /******
766 * Handle cells
767 ******/
769 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
770 * rendezvous point.
773 rend_service_introduce(origin_circuit_t *circuit, const char *request,
774 size_t request_len)
776 char *ptr, *r_cookie;
777 extend_info_t *extend_info = NULL;
778 char buf[RELAY_PAYLOAD_SIZE];
779 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
780 rend_service_t *service;
781 int r, i;
782 size_t len, keylen;
783 crypto_dh_env_t *dh = NULL;
784 origin_circuit_t *launched = NULL;
785 crypt_path_t *cpath = NULL;
786 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
787 char hexcookie[9];
788 int circ_needs_uptime;
789 int reason = END_CIRC_REASON_TORPROTOCOL;
790 crypto_pk_env_t *intro_key;
791 char intro_key_digest[DIGEST_LEN];
793 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
794 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
795 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
796 escaped(serviceid), circuit->_base.n_circ_id);
798 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
799 log_warn(LD_PROTOCOL,
800 "Got an INTRODUCE2 over a non-introduction circuit %d.",
801 circuit->_base.n_circ_id);
802 return -1;
805 /* min key length plus digest length plus nickname length */
806 if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
807 DH_KEY_LEN+42) {
808 log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
809 circuit->_base.n_circ_id);
810 return -1;
813 /* look up service depending on circuit. */
814 service = rend_service_get_by_pk_digest_and_version(
815 circuit->rend_pk_digest, circuit->rend_desc_version);
816 if (!service) {
817 log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
818 escaped(serviceid));
819 return -1;
822 /* if descriptor version is 2, use intro key instead of service key. */
823 if (circuit->rend_desc_version == 0) {
824 intro_key = service->private_key;
825 } else {
826 intro_key = circuit->intro_key;
829 /* first DIGEST_LEN bytes of request is intro or service pk digest */
830 crypto_pk_get_digest(intro_key, intro_key_digest);
831 if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
832 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
833 request, REND_SERVICE_ID_LEN);
834 log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
835 escaped(serviceid));
836 return -1;
839 keylen = crypto_pk_keysize(intro_key);
840 if (request_len < keylen+DIGEST_LEN) {
841 log_warn(LD_PROTOCOL,
842 "PK-encrypted portion of INTRODUCE2 cell was truncated.");
843 return -1;
845 /* Next N bytes is encrypted with service key */
846 note_crypto_pk_op(REND_SERVER);
847 r = crypto_pk_private_hybrid_decrypt(
848 intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
849 PK_PKCS1_OAEP_PADDING,1);
850 if (r<0) {
851 log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
852 return -1;
854 len = r;
855 if (*buf == 2) {
856 /* Version 2 INTRODUCE2 cell. */
857 int klen;
858 extend_info = tor_malloc_zero(sizeof(extend_info_t));
859 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf+1));
860 extend_info->port = ntohs(get_uint16(buf+5));
861 memcpy(extend_info->identity_digest, buf+7, DIGEST_LEN);
862 extend_info->nickname[0] = '$';
863 base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
864 extend_info->identity_digest, DIGEST_LEN);
866 klen = ntohs(get_uint16(buf+7+DIGEST_LEN));
867 if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
868 log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
869 (int)len);
870 reason = END_CIRC_REASON_TORPROTOCOL;
871 goto err;
873 extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
874 if (!extend_info->onion_key) {
875 log_warn(LD_PROTOCOL,
876 "Error decoding onion key in version 2 INTRODUCE2 cell.");
877 reason = END_CIRC_REASON_TORPROTOCOL;
878 goto err;
880 ptr = buf+7+DIGEST_LEN+2+klen;
881 len -= 7+DIGEST_LEN+2+klen;
882 } else {
883 char *rp_nickname;
884 size_t nickname_field_len;
885 routerinfo_t *router;
886 int version;
887 if (*buf == 1) {
888 rp_nickname = buf+1;
889 nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
890 version = 1;
891 } else {
892 nickname_field_len = MAX_NICKNAME_LEN+1;
893 rp_nickname = buf;
894 version = 0;
896 ptr=memchr(rp_nickname,0,nickname_field_len);
897 if (!ptr || ptr == rp_nickname) {
898 log_warn(LD_PROTOCOL,
899 "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
900 return -1;
902 if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
903 (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
904 log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
905 return -1;
907 /* Okay, now we know that a nickname is at the start of the buffer. */
908 ptr = rp_nickname+nickname_field_len;
909 len -= nickname_field_len;
910 len -= rp_nickname - buf; /* also remove header space used by version, if
911 * any */
912 router = router_get_by_nickname(rp_nickname, 0);
913 if (!router) {
914 log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
915 escaped_safe_str(rp_nickname));
916 /* XXXX Add a no-such-router reason? */
917 reason = END_CIRC_REASON_TORPROTOCOL;
918 goto err;
921 extend_info = extend_info_from_router(router);
924 if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
925 log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
926 reason = END_CIRC_REASON_TORPROTOCOL;
927 goto err;
930 r_cookie = ptr;
931 base16_encode(hexcookie,9,r_cookie,4);
933 /* Try DH handshake... */
934 dh = crypto_dh_new();
935 if (!dh || crypto_dh_generate_public(dh)<0) {
936 log_warn(LD_BUG,"Internal error: couldn't build DH state "
937 "or generate public key.");
938 reason = END_CIRC_REASON_INTERNAL;
939 goto err;
941 if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
942 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
943 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
944 reason = END_CIRC_REASON_INTERNAL;
945 goto err;
948 circ_needs_uptime = rend_service_requires_uptime(service);
950 /* help predict this next time */
951 rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
953 /* Launch a circuit to alice's chosen rendezvous point.
955 for (i=0;i<MAX_REND_FAILURES;i++) {
956 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
957 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
958 launched = circuit_launch_by_extend_info(
959 CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
961 if (launched)
962 break;
964 if (!launched) { /* give up */
965 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
966 "point %s for service %s.",
967 escaped_safe_str(extend_info->nickname), serviceid);
968 reason = END_CIRC_REASON_CONNECTFAILED;
969 goto err;
971 log_info(LD_REND,
972 "Accepted intro; launching circuit to %s "
973 "(cookie %s) for service %s.",
974 escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
975 tor_assert(launched->build_state);
976 /* Fill in the circuit's state. */
977 memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
978 DIGEST_LEN);
979 memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
980 strlcpy(launched->rend_query, service->service_id,
981 sizeof(launched->rend_query));
982 launched->rend_desc_version = service->descriptor_version;
983 launched->build_state->pending_final_cpath = cpath =
984 tor_malloc_zero(sizeof(crypt_path_t));
985 cpath->magic = CRYPT_PATH_MAGIC;
986 launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
988 cpath->dh_handshake_state = dh;
989 dh = NULL;
990 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
991 goto err;
992 memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
993 if (extend_info) extend_info_free(extend_info);
995 return 0;
996 err:
997 if (dh) crypto_dh_free(dh);
998 if (launched)
999 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
1000 if (extend_info) extend_info_free(extend_info);
1001 return -1;
1004 /** Called when we fail building a rendezvous circuit at some point other
1005 * than the last hop: launches a new circuit to the same rendezvous point.
1007 void
1008 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
1010 origin_circuit_t *newcirc;
1011 cpath_build_state_t *newstate, *oldstate;
1013 tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1015 if (!oldcirc->build_state ||
1016 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
1017 oldcirc->build_state->expiry_time < time(NULL)) {
1018 log_info(LD_REND,
1019 "Attempt to build circuit to %s for rendezvous has failed "
1020 "too many times or expired; giving up.",
1021 oldcirc->build_state ?
1022 oldcirc->build_state->chosen_exit->nickname : "*unknown*");
1023 return;
1026 oldstate = oldcirc->build_state;
1027 tor_assert(oldstate);
1029 if (oldstate->pending_final_cpath == NULL) {
1030 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
1031 "Initiator will retry.");
1032 return;
1035 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
1036 oldstate->chosen_exit->nickname);
1038 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
1039 oldstate->chosen_exit,
1040 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1042 if (!newcirc) {
1043 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
1044 oldstate->chosen_exit->nickname);
1045 return;
1047 newstate = newcirc->build_state;
1048 tor_assert(newstate);
1049 newstate->failure_count = oldstate->failure_count+1;
1050 newstate->expiry_time = oldstate->expiry_time;
1051 newstate->pending_final_cpath = oldstate->pending_final_cpath;
1052 oldstate->pending_final_cpath = NULL;
1054 memcpy(newcirc->rend_query, oldcirc->rend_query,
1055 REND_SERVICE_ID_LEN_BASE32+1);
1056 memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
1057 DIGEST_LEN);
1058 memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
1059 REND_COOKIE_LEN);
1060 newcirc->rend_desc_version = oldcirc->rend_desc_version;
1063 /** Launch a circuit to serve as an introduction point for the service
1064 * <b>service</b> at the introduction point <b>nickname</b>
1066 static int
1067 rend_service_launch_establish_intro(rend_service_t *service,
1068 rend_intro_point_t *intro)
1070 origin_circuit_t *launched;
1072 log_info(LD_REND,
1073 "Launching circuit to introduction point %s for service %s",
1074 escaped_safe_str(intro->extend_info->nickname),
1075 service->service_id);
1077 rep_hist_note_used_internal(time(NULL), 1, 0);
1079 ++service->n_intro_circuits_launched;
1080 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
1081 intro->extend_info,
1082 CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);
1084 if (!launched) {
1085 log_info(LD_REND,
1086 "Can't launch circuit to establish introduction at %s.",
1087 escaped_safe_str(intro->extend_info->nickname));
1088 return -1;
1091 if (memcmp(intro->extend_info->identity_digest,
1092 launched->build_state->chosen_exit->identity_digest, DIGEST_LEN)) {
1093 char cann[HEX_DIGEST_LEN+1], orig[HEX_DIGEST_LEN+1];
1094 base16_encode(cann, sizeof(cann),
1095 launched->build_state->chosen_exit->identity_digest,
1096 DIGEST_LEN);
1097 base16_encode(orig, sizeof(orig),
1098 intro->extend_info->identity_digest, DIGEST_LEN);
1099 log_info(LD_REND, "The intro circuit we just cannibalized ends at $%s, "
1100 "but we requested an intro circuit to $%s. Updating "
1101 "our service.", cann, orig);
1102 extend_info_free(intro->extend_info);
1103 intro->extend_info = extend_info_dup(launched->build_state->chosen_exit);
1106 strlcpy(launched->rend_query, service->service_id,
1107 sizeof(launched->rend_query));
1108 memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
1109 launched->rend_desc_version = service->descriptor_version;
1110 if (service->descriptor_version == 2)
1111 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
1112 if (launched->_base.state == CIRCUIT_STATE_OPEN)
1113 rend_service_intro_has_opened(launched);
1114 return 0;
1117 /** Called when we're done building a circuit to an introduction point:
1118 * sends a RELAY_ESTABLISH_INTRO cell.
1120 void
1121 rend_service_intro_has_opened(origin_circuit_t *circuit)
1123 rend_service_t *service;
1124 size_t len;
1125 int r;
1126 char buf[RELAY_PAYLOAD_SIZE];
1127 char auth[DIGEST_LEN + 9];
1128 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1129 int reason = END_CIRC_REASON_TORPROTOCOL;
1130 crypto_pk_env_t *intro_key;
1132 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
1133 tor_assert(circuit->cpath);
1135 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1136 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
1138 service = rend_service_get_by_pk_digest_and_version(
1139 circuit->rend_pk_digest, circuit->rend_desc_version);
1140 if (!service) {
1141 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
1142 serviceid, circuit->_base.n_circ_id);
1143 reason = END_CIRC_REASON_NOSUCHSERVICE;
1144 goto err;
1147 log_info(LD_REND,
1148 "Established circuit %d as introduction point for service %s",
1149 circuit->_base.n_circ_id, serviceid);
1151 /* If the introduction point will not be used in an unversioned
1152 * descriptor, use the intro key instead of the service key in
1153 * ESTABLISH_INTRO. */
1154 if (service->descriptor_version == 0)
1155 intro_key = service->private_key;
1156 else
1157 intro_key = circuit->intro_key;
1158 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
1159 r = crypto_pk_asn1_encode(intro_key, buf+2,
1160 RELAY_PAYLOAD_SIZE-2);
1161 if (r < 0) {
1162 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
1163 reason = END_CIRC_REASON_INTERNAL;
1164 goto err;
1166 len = r;
1167 set_uint16(buf, htons((uint16_t)len));
1168 len += 2;
1169 memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
1170 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
1171 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
1172 goto err;
1173 len += 20;
1174 note_crypto_pk_op(REND_SERVER);
1175 r = crypto_pk_private_sign_digest(intro_key, buf+len, buf, len);
1176 if (r<0) {
1177 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
1178 reason = END_CIRC_REASON_INTERNAL;
1179 goto err;
1181 len += r;
1183 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1184 RELAY_COMMAND_ESTABLISH_INTRO,
1185 buf, len, circuit->cpath->prev)<0) {
1186 log_info(LD_GENERAL,
1187 "Couldn't send introduction request for service %s on circuit %d",
1188 serviceid, circuit->_base.n_circ_id);
1189 reason = END_CIRC_REASON_INTERNAL;
1190 goto err;
1193 return;
1194 err:
1195 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1198 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
1199 * live introduction point, and note that the service descriptor is
1200 * now out-of-date.*/
1202 rend_service_intro_established(origin_circuit_t *circuit, const char *request,
1203 size_t request_len)
1205 rend_service_t *service;
1206 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1207 (void) request;
1208 (void) request_len;
1210 if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
1211 log_warn(LD_PROTOCOL,
1212 "received INTRO_ESTABLISHED cell on non-intro circuit.");
1213 goto err;
1215 service = rend_service_get_by_pk_digest_and_version(
1216 circuit->rend_pk_digest, circuit->rend_desc_version);
1217 if (!service) {
1218 log_warn(LD_REND, "Unknown service on introduction circuit %d.",
1219 circuit->_base.n_circ_id);
1220 goto err;
1222 service->desc_is_dirty = time(NULL);
1223 circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
1225 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
1226 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
1227 log_info(LD_REND,
1228 "Received INTRO_ESTABLISHED cell on circuit %d for service %s",
1229 circuit->_base.n_circ_id, serviceid);
1231 return 0;
1232 err:
1233 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
1234 return -1;
1237 /** Called once a circuit to a rendezvous point is established: sends a
1238 * RELAY_COMMAND_RENDEZVOUS1 cell.
1240 void
1241 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
1243 rend_service_t *service;
1244 char buf[RELAY_PAYLOAD_SIZE];
1245 crypt_path_t *hop;
1246 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1247 char hexcookie[9];
1248 int reason;
1250 tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
1251 tor_assert(circuit->cpath);
1252 tor_assert(circuit->build_state);
1253 hop = circuit->build_state->pending_final_cpath;
1254 tor_assert(hop);
1256 base16_encode(hexcookie,9,circuit->rend_cookie,4);
1257 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1258 circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
1260 log_info(LD_REND,
1261 "Done building circuit %d to rendezvous with "
1262 "cookie %s for service %s",
1263 circuit->_base.n_circ_id, hexcookie, serviceid);
1265 service = rend_service_get_by_pk_digest_and_version(
1266 circuit->rend_pk_digest, circuit->rend_desc_version);
1267 if (!service) {
1268 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
1269 "introduction circuit.");
1270 reason = END_CIRC_REASON_INTERNAL;
1271 goto err;
1274 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
1275 memcpy(buf, circuit->rend_cookie, REND_COOKIE_LEN);
1276 if (crypto_dh_get_public(hop->dh_handshake_state,
1277 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
1278 log_warn(LD_GENERAL,"Couldn't get DH public key.");
1279 reason = END_CIRC_REASON_INTERNAL;
1280 goto err;
1282 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->handshake_digest,
1283 DIGEST_LEN);
1285 /* Send the cell */
1286 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
1287 RELAY_COMMAND_RENDEZVOUS1,
1288 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
1289 circuit->cpath->prev)<0) {
1290 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
1291 reason = END_CIRC_REASON_INTERNAL;
1292 goto err;
1295 crypto_dh_free(hop->dh_handshake_state);
1296 hop->dh_handshake_state = NULL;
1298 /* Append the cpath entry. */
1299 hop->state = CPATH_STATE_OPEN;
1300 /* set the windows to default. these are the windows
1301 * that bob thinks alice has.
1303 hop->package_window = CIRCWINDOW_START;
1304 hop->deliver_window = CIRCWINDOW_START;
1306 onion_append_to_cpath(&circuit->cpath, hop);
1307 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
1309 /* Change the circuit purpose. */
1310 circuit->_base.purpose = CIRCUIT_PURPOSE_S_REND_JOINED;
1312 return;
1313 err:
1314 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
1318 * Manage introduction points
1321 /** Return the (possibly non-open) introduction circuit ending at
1322 * <b>intro</b> for the service whose public key is <b>pk_digest</b> and
1323 * which publishes descriptor of version <b>desc_version</b>. Return
1324 * NULL if no such service is found.
1326 static origin_circuit_t *
1327 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest,
1328 int desc_version)
1330 origin_circuit_t *circ = NULL;
1332 tor_assert(intro);
1333 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1334 CIRCUIT_PURPOSE_S_INTRO))) {
1335 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1336 intro->extend_info->identity_digest, DIGEST_LEN) &&
1337 circ->rend_desc_version == desc_version) {
1338 return circ;
1342 circ = NULL;
1343 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
1344 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
1345 if (!memcmp(circ->build_state->chosen_exit->identity_digest,
1346 intro->extend_info->identity_digest, DIGEST_LEN) &&
1347 circ->rend_desc_version == desc_version) {
1348 return circ;
1351 return NULL;
1354 /** Determine the responsible hidden service directories for the
1355 * rend_encoded_v2_service_descriptor_t's in <b>descs</b> and upload them;
1356 * <b>service_id</b> and <b>seconds_valid</b> are only passed for logging
1357 * purposes. */
1358 static void
1359 directory_post_to_hs_dir(smartlist_t *descs, const char *service_id,
1360 int seconds_valid)
1362 int i, j;
1363 smartlist_t *responsible_dirs = smartlist_create();
1364 routerstatus_t *hs_dir;
1365 for (i = 0; i < smartlist_len(descs); i++) {
1366 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
1367 /* Determine responsible dirs. */
1368 if (hid_serv_get_responsible_directories(responsible_dirs,
1369 desc->desc_id) < 0) {
1370 log_warn(LD_REND, "Could not determine the responsible hidden service "
1371 "directories to post descriptors to.");
1372 smartlist_free(responsible_dirs);
1373 return;
1375 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
1376 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
1377 hs_dir = smartlist_get(responsible_dirs, j);
1378 /* Send publish request. */
1379 directory_initiate_command_routerstatus(hs_dir,
1380 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
1381 ROUTER_PURPOSE_GENERAL,
1382 1, NULL, desc->desc_str,
1383 strlen(desc->desc_str), 0);
1384 base32_encode(desc_id_base32, sizeof(desc_id_base32),
1385 desc->desc_id, DIGEST_LEN);
1386 log_info(LD_REND, "Sending publish request for v2 descriptor for "
1387 "service '%s' with descriptor ID '%s' with validity "
1388 "of %d seconds to hidden service directory '%s' on "
1389 "port %d.",
1390 safe_str(service_id),
1391 safe_str(desc_id_base32),
1392 seconds_valid,
1393 hs_dir->nickname,
1394 hs_dir->dir_port);
1396 smartlist_clear(responsible_dirs);
1398 smartlist_free(responsible_dirs);
1401 /** Encode and sign up-to-date v0 and/or v2 service descriptors for
1402 * <b>service</b>, and upload it/them to all the dirservers/to the
1403 * responsible hidden service directories.
1405 static void
1406 upload_service_descriptor(rend_service_t *service)
1408 time_t now = time(NULL);
1409 int rendpostperiod;
1410 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1411 int uploaded = 0;
1413 /* Update the descriptor. */
1414 rend_service_update_descriptor(service);
1416 rendpostperiod = get_options()->RendPostPeriod;
1418 /* Upload unversioned (v0) descriptor? */
1419 if (service->descriptor_version == 0 &&
1420 get_options()->PublishHidServDescriptors) {
1421 char *desc;
1422 size_t desc_len;
1423 /* Encode the descriptor. */
1424 if (rend_encode_service_descriptor(service->desc,
1425 service->private_key,
1426 &desc, &desc_len)<0) {
1427 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1428 "not uploading.");
1429 return;
1432 /* Post it to the dirservers */
1433 rend_get_service_id(service->desc->pk, serviceid);
1434 log_info(LD_REND, "Sending publish request for hidden service %s",
1435 serviceid);
1436 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_RENDDESC,
1437 ROUTER_PURPOSE_GENERAL,
1438 HIDSERV_AUTHORITY, desc, desc_len, 0);
1439 tor_free(desc);
1440 service->next_upload_time = now + rendpostperiod;
1441 uploaded = 1;
1444 /* Upload v2 descriptor? */
1445 if (service->descriptor_version == 2 &&
1446 get_options()->PublishHidServDescriptors) {
1447 networkstatus_t *c = networkstatus_get_latest_consensus();
1448 if (c && smartlist_len(c->routerstatus_list) > 0) {
1449 int seconds_valid;
1450 smartlist_t *descs = smartlist_create();
1451 int i;
1452 /* Encode the current descriptor. */
1453 seconds_valid = rend_encode_v2_descriptors(descs, service->desc, now,
1454 NULL, 0);
1455 if (seconds_valid < 0) {
1456 log_warn(LD_BUG, "Internal error: couldn't encode service descriptor; "
1457 "not uploading.");
1458 smartlist_free(descs);
1459 return;
1461 /* Post the current descriptors to the hidden service directories. */
1462 rend_get_service_id(service->desc->pk, serviceid);
1463 log_info(LD_REND, "Sending publish request for hidden service %s",
1464 serviceid);
1465 directory_post_to_hs_dir(descs, serviceid, seconds_valid);
1466 /* Free memory for descriptors. */
1467 for (i = 0; i < smartlist_len(descs); i++)
1468 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1469 smartlist_clear(descs);
1470 /* Update next upload time. */
1471 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
1472 > rendpostperiod)
1473 service->next_upload_time = now + rendpostperiod;
1474 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
1475 service->next_upload_time = now + seconds_valid + 1;
1476 else
1477 service->next_upload_time = now + seconds_valid -
1478 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
1479 /* Post also the next descriptors, if necessary. */
1480 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
1481 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
1482 now, NULL, 1);
1483 if (seconds_valid < 0) {
1484 log_warn(LD_BUG, "Internal error: couldn't encode service "
1485 "descriptor; not uploading.");
1486 smartlist_free(descs);
1487 return;
1489 directory_post_to_hs_dir(descs, serviceid, seconds_valid);
1490 /* Free memory for descriptors. */
1491 for (i = 0; i < smartlist_len(descs); i++)
1492 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1494 smartlist_free(descs);
1495 uploaded = 1;
1496 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
1500 /* If not uploaded, try again in one minute. */
1501 if (!uploaded)
1502 service->next_upload_time = now + 60;
1504 /* Unmark dirty flag of this service. */
1505 service->desc_is_dirty = 0;
1508 /** For every service, check how many intro points it currently has, and:
1509 * - Pick new intro points as necessary.
1510 * - Launch circuits to any new intro points.
1512 void
1513 rend_services_introduce(void)
1515 int i,j,r;
1516 routerinfo_t *router;
1517 rend_service_t *service;
1518 rend_intro_point_t *intro;
1519 int changed, prev_intro_nodes;
1520 smartlist_t *intro_routers;
1521 time_t now;
1522 or_options_t *options = get_options();
1524 intro_routers = smartlist_create();
1525 now = time(NULL);
1527 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1528 smartlist_clear(intro_routers);
1529 service = smartlist_get(rend_service_list, i);
1531 tor_assert(service);
1532 changed = 0;
1533 if (now > service->intro_period_started+INTRO_CIRC_RETRY_PERIOD) {
1534 /* One period has elapsed; we can try building circuits again. */
1535 service->intro_period_started = now;
1536 service->n_intro_circuits_launched = 0;
1537 } else if (service->n_intro_circuits_launched >=
1538 MAX_INTRO_CIRCS_PER_PERIOD) {
1539 /* We have failed too many times in this period; wait for the next
1540 * one before we try again. */
1541 continue;
1544 /* Find out which introduction points we have in progress for this
1545 service. */
1546 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1547 intro = smartlist_get(service->intro_nodes, j);
1548 router = router_get_by_digest(intro->extend_info->identity_digest);
1549 if (!router || !find_intro_circuit(intro, service->pk_digest,
1550 service->descriptor_version)) {
1551 log_info(LD_REND,"Giving up on %s as intro point for %s.",
1552 intro->extend_info->nickname, service->service_id);
1553 if (service->desc) {
1554 SMARTLIST_FOREACH(service->desc->intro_nodes, rend_intro_point_t *,
1555 dintro, {
1556 if (!memcmp(dintro->extend_info->identity_digest,
1557 intro->extend_info->identity_digest, DIGEST_LEN)) {
1558 log_info(LD_REND, "The intro point we are giving up on was "
1559 "included in the last published descriptor. "
1560 "Marking current descriptor as dirty.");
1561 service->desc_is_dirty = now;
1565 rend_intro_point_free(intro);
1566 smartlist_del(service->intro_nodes,j--);
1567 changed = 1;
1569 if (router)
1570 smartlist_add(intro_routers, router);
1573 /* We have enough intro points, and the intro points we thought we had were
1574 * all connected.
1576 if (!changed && smartlist_len(service->intro_nodes) >= NUM_INTRO_POINTS) {
1577 /* We have all our intro points! Start a fresh period and reset the
1578 * circuit count. */
1579 service->intro_period_started = now;
1580 service->n_intro_circuits_launched = 0;
1581 continue;
1584 /* Remember how many introduction circuits we started with. */
1585 prev_intro_nodes = smartlist_len(service->intro_nodes);
1587 /* The directory is now here. Pick three ORs as intro points. */
1588 for (j=prev_intro_nodes; j < NUM_INTRO_POINTS; ++j) {
1589 router_crn_flags_t flags = CRN_NEED_UPTIME;
1590 if (get_options()->_AllowInvalid & ALLOW_INVALID_INTRODUCTION)
1591 flags |= CRN_ALLOW_INVALID;
1592 router = router_choose_random_node(NULL, intro_routers,
1593 options->ExcludeNodes, flags);
1594 if (!router) {
1595 log_warn(LD_REND,
1596 "Could only establish %d introduction points for %s.",
1597 smartlist_len(service->intro_nodes), service->service_id);
1598 break;
1600 changed = 1;
1601 smartlist_add(intro_routers, router);
1602 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
1603 intro->extend_info = extend_info_from_router(router);
1604 if (service->descriptor_version == 2) {
1605 intro->intro_key = crypto_new_pk_env();
1606 tor_assert(!crypto_pk_generate_key(intro->intro_key));
1608 smartlist_add(service->intro_nodes, intro);
1609 log_info(LD_REND, "Picked router %s as an intro point for %s.",
1610 router->nickname, service->service_id);
1613 /* If there's no need to launch new circuits, stop here. */
1614 if (!changed)
1615 continue;
1617 /* Establish new introduction points. */
1618 for (j=prev_intro_nodes; j < smartlist_len(service->intro_nodes); ++j) {
1619 intro = smartlist_get(service->intro_nodes, j);
1620 r = rend_service_launch_establish_intro(service, intro);
1621 if (r<0) {
1622 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
1623 intro->extend_info->nickname, service->service_id);
1627 smartlist_free(intro_routers);
1630 /** Regenerate and upload rendezvous service descriptors for all
1631 * services, if necessary. If the descriptor has been dirty enough
1632 * for long enough, definitely upload; else only upload when the
1633 * periodic timeout has expired.
1635 * For the first upload, pick a random time between now and two periods
1636 * from now, and pick it independently for each service.
1638 void
1639 rend_consider_services_upload(time_t now)
1641 int i;
1642 rend_service_t *service;
1643 int rendpostperiod = get_options()->RendPostPeriod;
1645 if (!get_options()->PublishHidServDescriptors)
1646 return;
1648 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1649 service = smartlist_get(rend_service_list, i);
1650 if (!service->next_upload_time) { /* never been uploaded yet */
1651 /* The fixed lower bound of 30 seconds ensures that the descriptor
1652 * is stable before being published. See comment below. */
1653 service->next_upload_time =
1654 now + 30 + crypto_rand_int(2*rendpostperiod);
1656 if (service->next_upload_time < now ||
1657 (service->desc_is_dirty &&
1658 service->desc_is_dirty < now-30)) {
1659 /* if it's time, or if the directory servers have a wrong service
1660 * descriptor and ours has been stable for 30 seconds, upload a
1661 * new one of each format. */
1662 upload_service_descriptor(service);
1667 /** Log the status of introduction points for all rendezvous services
1668 * at log severity <b>severity</b>.
1670 void
1671 rend_service_dump_stats(int severity)
1673 int i,j;
1674 rend_service_t *service;
1675 rend_intro_point_t *intro;
1676 const char *safe_name;
1677 origin_circuit_t *circ;
1679 for (i=0; i < smartlist_len(rend_service_list); ++i) {
1680 service = smartlist_get(rend_service_list, i);
1681 log(severity, LD_GENERAL, "Service configured in \"%s\":",
1682 service->directory);
1683 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
1684 intro = smartlist_get(service->intro_nodes, j);
1685 safe_name = safe_str(intro->extend_info->nickname);
1687 circ = find_intro_circuit(intro, service->pk_digest,
1688 service->descriptor_version);
1689 if (!circ) {
1690 log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
1691 j, safe_name);
1692 continue;
1694 log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
1695 j, safe_name, circuit_state_to_string(circ->_base.state));
1700 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
1701 * 'circ', and look up the port and address based on conn-\>port.
1702 * Assign the actual conn-\>addr and conn-\>port. Return -1 if failure,
1703 * or 0 for success.
1706 rend_service_set_connection_addr_port(edge_connection_t *conn,
1707 origin_circuit_t *circ)
1709 rend_service_t *service;
1710 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1711 smartlist_t *matching_ports;
1712 rend_service_port_config_t *chosen_port;
1714 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
1715 log_debug(LD_REND,"beginning to hunt for addr/port");
1716 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1717 circ->rend_pk_digest, REND_SERVICE_ID_LEN);
1718 service = rend_service_get_by_pk_digest_and_version(circ->rend_pk_digest,
1719 circ->rend_desc_version);
1720 if (!service) {
1721 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
1722 "rendezvous circuit %d; closing.",
1723 serviceid, circ->_base.n_circ_id);
1724 return -1;
1726 matching_ports = smartlist_create();
1727 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
1729 if (conn->_base.port == p->virtual_port) {
1730 smartlist_add(matching_ports, p);
1733 chosen_port = smartlist_choose(matching_ports);
1734 smartlist_free(matching_ports);
1735 if (chosen_port) {
1736 tor_addr_copy(&conn->_base.addr, &chosen_port->real_addr);
1737 conn->_base.port = chosen_port->real_port;
1738 return 0;
1740 log_info(LD_REND, "No virtual port mapping exists for port %d on service %s",
1741 conn->_base.port,serviceid);
1742 return -1;