Tor  0.4.5.0-alpha-dev
rendservice.c
Go to the documentation of this file.
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2  * Copyright (c) 2007-2020, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 
5 /**
6  * \file rendservice.c
7  * \brief The hidden-service side of rendezvous functionality.
8  **/
9 
10 #define RENDSERVICE_PRIVATE
11 
12 #include "core/or/or.h"
13 
14 #include "app/config/config.h"
15 #include "core/mainloop/mainloop.h"
16 #include "core/or/circuitbuild.h"
17 #include "core/or/circuitlist.h"
18 #include "core/or/circuituse.h"
19 #include "core/or/extendinfo.h"
20 #include "core/or/policies.h"
21 #include "core/or/relay.h"
22 #include "core/or/crypt_path.h"
23 #include "feature/client/circpathbias.h"
27 #include "feature/hs/hs_common.h"
28 #include "feature/hs/hs_config.h"
30 #include "feature/keymgt/loadkey.h"
39 #include "feature/rend/rendparse.h"
45 #include "lib/encoding/confline.h"
46 #include "lib/net/resolve.h"
47 
49 #include "core/or/crypt_path_st.h"
52 #include "core/or/extend_info_st.h"
53 #include "feature/hs/hs_opts_st.h"
61 
62 #ifdef HAVE_FCNTL_H
63 #include <fcntl.h>
64 #endif
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif
68 #ifdef HAVE_SYS_STAT_H
69 #include <sys/stat.h>
70 #endif
71 
72 struct rend_service_t;
74  const char *pk_digest);
77  struct rend_service_t *service, origin_circuit_t *circ);
78 
80  const rend_intro_cell_t *intro,
81  char **err_msg_out);
82 
85  time_t now);
86 static int rend_service_derive_key_digests(struct rend_service_t *s);
87 static int rend_service_load_keys(struct rend_service_t *s);
88 static int rend_service_load_auth_keys(struct rend_service_t *s,
89  const char *hfname);
90 static struct rend_service_t *rend_service_get_by_pk_digest(
91  const char* digest);
92 static struct rend_service_t *rend_service_get_by_service_id(const char *id);
93 static const char *rend_service_escaped_dir(
94  const struct rend_service_t *s);
95 
97  rend_intro_cell_t *intro,
98  const uint8_t *buf,
99  size_t plaintext_len,
100  char **err_msg_out);
101 static ssize_t rend_service_parse_intro_for_v2(
102  rend_intro_cell_t *intro,
103  const uint8_t *buf,
104  size_t plaintext_len,
105  char **err_msg_out);
106 static ssize_t rend_service_parse_intro_for_v3(
107  rend_intro_cell_t *intro,
108  const uint8_t *buf,
109  size_t plaintext_len,
110  char **err_msg_out);
111 
112 static int rend_service_check_private_dir(const or_options_t *options,
113  const rend_service_t *s,
114  int create);
115 static const smartlist_t* rend_get_service_list(
116  const smartlist_t* substitute_service_list);
117 static smartlist_t* rend_get_service_list_mutable(
118  smartlist_t* substitute_service_list);
119 static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted);
120 
121 /* Hidden service directory file names:
122  * new file names should be added to rend_service_add_filenames_to_list()
123  * for sandboxing purposes. */
124 static const char *private_key_fname = "private_key";
125 static const char *hostname_fname = "hostname";
126 static const char *client_keys_fname = "client_keys";
127 static const char *sos_poison_fname = "onion_service_non_anonymous";
128 
129 /** A list of rend_service_t's for services run on this OP. */
131 /** A list of rend_service_t's for services run on this OP which is used as a
132  * staging area before they are put in the main list in order to prune dying
133  * service on config reload. */
135 
136 /** Helper: log the deprecation warning for version 2 only once. */
137 static void
139 {
140  static bool logged_once = false;
141  if (!logged_once) {
142  log_warn(LD_REND, "DEPRECATED: Onion service version 2 are deprecated. "
143  "Please use version 3 which is the default now. "
144  "Currently, version 2 is planned to be obsolete in "
145  "the Tor version 0.4.6 stable series.");
146  logged_once = true;
147  }
148 }
149 /** Macro to make it very explicit that we are warning about deprecation. */
150 #define WARN_ONCE_DEPRECATION() log_once_deprecation_warning()
151 
152 /* Like rend_get_service_list_mutable, but returns a read-only list. */
153 static const smartlist_t*
154 rend_get_service_list(const smartlist_t* substitute_service_list)
155 {
156  /* It is safe to cast away the const here, because
157  * rend_get_service_list_mutable does not actually modify the list */
158  return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
159 }
160 
161 /* Return a mutable list of hidden services.
162  * If substitute_service_list is not NULL, return it.
163  * Otherwise, check if the global rend_service_list is non-NULL, and if so,
164  * return it.
165  * Otherwise, log a BUG message and return NULL.
166  * */
167 static smartlist_t*
168 rend_get_service_list_mutable(smartlist_t* substitute_service_list)
169 {
170  if (substitute_service_list) {
171  return substitute_service_list;
172  }
173 
174  /* If no special service list is provided, then just use the global one. */
175 
176  if (BUG(!rend_service_list)) {
177  /* No global HS list, which is a programmer error. */
178  return NULL;
179  }
180 
181  return rend_service_list;
182 }
183 
184 /** Tells if onion service <b>s</b> is ephemeral.
185  */
186 static unsigned int
187 rend_service_is_ephemeral(const struct rend_service_t *s)
188 {
189  return (s->directory == NULL);
190 }
191 
192 /** Returns a escaped string representation of the service, <b>s</b>.
193  */
194 static const char *
195 rend_service_escaped_dir(const struct rend_service_t *s)
196 {
197  return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
198 }
199 
200 /** Return the number of rendezvous services we have configured. */
201 int
203 {
204  if (!rend_service_list)
205  return 0;
206  return smartlist_len(rend_service_list);
207 }
208 
209 /** Helper: free storage held by a single service authorized client entry. */
210 void
212 {
213  if (!client)
214  return;
215  if (client->client_key)
216  crypto_pk_free(client->client_key);
217  if (client->client_name)
218  memwipe(client->client_name, 0, strlen(client->client_name));
219  tor_free(client->client_name);
220  memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
221  tor_free(client);
222 }
223 
224 /** Helper for strmap_free. */
225 static void
226 rend_authorized_client_free_void(void *authorized_client)
227 {
228  rend_authorized_client_free_(authorized_client);
229 }
230 
231 /** Release the storage held by <b>service</b>.
232  */
233 STATIC void
234 rend_service_free_(rend_service_t *service)
235 {
236  if (!service)
237  return;
238 
239  tor_free(service->directory);
240  if (service->ports) {
241  SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
242  rend_service_port_config_free(p));
243  smartlist_free(service->ports);
244  }
245  if (service->private_key)
246  crypto_pk_free(service->private_key);
247  if (service->intro_nodes) {
248  SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
249  rend_intro_point_free(intro););
250  smartlist_free(service->intro_nodes);
251  }
252  if (service->expiring_nodes) {
253  SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
254  rend_intro_point_free(intro););
255  smartlist_free(service->expiring_nodes);
256  }
257 
258  rend_service_descriptor_free(service->desc);
259  if (service->clients) {
260  SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
261  rend_authorized_client_free(c););
262  smartlist_free(service->clients);
263  }
264  if (service->accepted_intro_dh_parts) {
265  replaycache_free(service->accepted_intro_dh_parts);
266  }
267  tor_free(service);
268 }
269 
270 /* Release all the storage held in rend_service_staging_list. */
271 void
272 rend_service_free_staging_list(void)
273 {
275  SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
276  rend_service_free(ptr));
277  smartlist_free(rend_service_staging_list);
279  }
280 }
281 
282 /** Release all the storage held in both rend_service_list and
283  * rend_service_staging_list. */
284 void
286 {
287  if (rend_service_list) {
288  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
289  rend_service_free(ptr));
290  smartlist_free(rend_service_list);
291  rend_service_list = NULL;
292  }
293  rend_service_free_staging_list();
294 }
295 
296 /* Initialize the subsystem. */
297 void
298 rend_service_init(void)
299 {
302 
305 }
306 
307 /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
308  * is no duplicate entry for the given service object. Return 0 if valid else
309  * -1 if not.*/
310 static int
311 rend_validate_service(const smartlist_t *service_list,
312  const rend_service_t *service)
313 {
314  tor_assert(service_list);
315  tor_assert(service);
316 
317  if (service->max_streams_per_circuit < 0) {
318  log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
319  "streams per circuit.",
320  rend_service_escaped_dir(service));
321  goto invalid;
322  }
323 
324  if (service->max_streams_close_circuit < 0 ||
325  service->max_streams_close_circuit > 1) {
326  log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
327  "max streams handling.",
328  rend_service_escaped_dir(service));
329  goto invalid;
330  }
331 
332  if (service->auth_type != REND_NO_AUTH &&
333  (!service->clients || smartlist_len(service->clients) == 0)) {
334  log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
335  "no clients.",
336  rend_service_escaped_dir(service));
337  goto invalid;
338  }
339 
340  if (!service->ports || !smartlist_len(service->ports)) {
341  log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
342  rend_service_escaped_dir(service));
343  goto invalid;
344  }
345 
346  /* Valid. */
347  return 0;
348  invalid:
349  return -1;
350 }
351 
352 /** Add it to <b>service_list</b>, or to the global rend_service_list if
353  * <b>service_list</b> is NULL. Return 0 on success. On failure, free
354  * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
355 static int
356 rend_add_service(smartlist_t *service_list, rend_service_t *service)
357 {
358  int i;
360 
361  tor_assert(service);
362 
363  smartlist_t *s_list = rend_get_service_list_mutable(service_list);
364  /* We must have a service list, even if it's a temporary one, so we can
365  * check for duplicate services */
366  if (BUG(!s_list)) {
367  rend_service_free(service);
368  return -1;
369  }
370 
371  service->intro_nodes = smartlist_new();
372  service->expiring_nodes = smartlist_new();
373 
374  log_debug(LD_REND,"Configuring service with directory %s",
375  rend_service_escaped_dir(service));
376  for (i = 0; i < smartlist_len(service->ports); ++i) {
377  p = smartlist_get(service->ports, i);
378  if (!(p->is_unix_addr)) {
379  log_debug(LD_REND,
380  "Service maps port %d to %s",
381  p->virtual_port,
382  fmt_addrport(&p->real_addr, p->real_port));
383  } else {
384 #ifdef HAVE_SYS_UN_H
385  log_debug(LD_REND,
386  "Service maps port %d to socket at \"%s\"",
387  p->virtual_port, p->unix_addr);
388 #else
389  log_warn(LD_BUG,
390  "Service maps port %d to an AF_UNIX socket, but we "
391  "have no AF_UNIX support on this platform. This is "
392  "probably a bug.",
393  p->virtual_port);
394  rend_service_free(service);
395  return -1;
396 #endif /* defined(HAVE_SYS_UN_H) */
397  }
398  }
399  /* The service passed all the checks */
400  tor_assert(s_list);
401  smartlist_add(s_list, service);
402 
403  /* Notify that our global service list has changed only if this new service
404  * went into our global list. If not, when we move service from the staging
405  * list to the new list, a notify is triggered. */
406  if (s_list == rend_service_list) {
408  }
409  return 0;
410 }
411 
412 /** Return a new rend_service_port_config_t with its path set to
413  * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
415 rend_service_port_config_new(const char *socket_path)
416 {
417  if (!socket_path)
418  return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
419 
420  const size_t pathlen = strlen(socket_path) + 1;
422  tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
423  memcpy(conf->unix_addr, socket_path, pathlen);
424  conf->is_unix_addr = 1;
425  return conf;
426 }
427 
428 /** Parses a virtual-port to real-port/socket mapping separated by
429  * the provided separator and returns a new rend_service_port_config_t,
430  * or NULL and an optional error string on failure.
431  *
432  * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
433  *
434  * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
435  */
437 rend_service_parse_port_config(const char *string, const char *sep,
438  char **err_msg_out)
439 {
440  smartlist_t *sl;
441  int virtport;
442  int realport = 0;
443  uint16_t p;
444  tor_addr_t addr;
445  rend_service_port_config_t *result = NULL;
446  unsigned int is_unix_addr = 0;
447  const char *socket_path = NULL;
448  char *err_msg = NULL;
449  char *addrport = NULL;
450 
451  sl = smartlist_new();
452  smartlist_split_string(sl, string, sep,
453  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
454  if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
455  err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
456  goto err;
457  }
458  virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
459  if (!virtport) {
460  tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
461  "port configuration", escaped(smartlist_get(sl,0)));
462 
463  goto err;
464  }
465  if (smartlist_len(sl) == 1) {
466  /* No addr:port part; use default. */
467  realport = virtport;
468  tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
469  } else {
470  int ret;
471 
472  const char *addrport_element = smartlist_get(sl,1);
473  const char *rest = NULL;
474  int is_unix;
475  ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
476  &is_unix, &rest);
477 
478  if (ret < 0) {
479  tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
480  "service configuration", addrport_element);
481  goto err;
482  }
483 
484  if (rest && strlen(rest)) {
485  err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
486  "mapping");
487  goto err;
488  }
489 
490  if (is_unix) {
491  socket_path = addrport;
492  is_unix_addr = 1;
493  } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
494  /* else try it as an IP:port pair if it has a : or . in it */
495  if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
496  err_msg = tor_strdup("Unparseable address in hidden service port "
497  "configuration.");
498  goto err;
499  }
500  realport = p?p:virtport;
501  } else {
502  /* No addr:port, no addr -- must be port. */
503  realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
504  if (!realport) {
505  tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
506  "hidden service port configuration.",
507  escaped(addrport));
508  goto err;
509  }
510  tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
511  }
512  }
513 
514  /* Allow room for unix_addr */
515  result = rend_service_port_config_new(socket_path);
516  result->virtual_port = virtport;
517  result->is_unix_addr = is_unix_addr;
518  if (!is_unix_addr) {
519  result->real_port = realport;
520  tor_addr_copy(&result->real_addr, &addr);
521  result->unix_addr[0] = '\0';
522  }
523 
524  err:
525  tor_free(addrport);
526  if (err_msg_out != NULL) {
527  *err_msg_out = err_msg;
528  } else {
529  tor_free(err_msg);
530  }
531  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
532  smartlist_free(sl);
533 
534  return result;
535 }
536 
537 /** Release all storage held in a rend_service_port_config_t. */
538 void
540 {
541  tor_free(p);
542 }
543 
544 /* Copy relevant data from service src to dst while pruning the service lists.
545  * This should only be called during the pruning process which takes existing
546  * services and copy their data to the newly configured services. The src
547  * service replaycache will be set to NULL after this call. */
548 static void
549 copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
550 {
551  tor_assert(dst);
552  tor_assert(src);
553 
554  /* Keep the timestamps for when the content changed and the next upload
555  * time so we can properly upload the descriptor if needed for the new
556  * service object. */
557  dst->desc_is_dirty = src->desc_is_dirty;
558  dst->next_upload_time = src->next_upload_time;
559  /* Move the replaycache to the new object. */
560  dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
561  src->accepted_intro_dh_parts = NULL;
562  /* Copy intro point information to destination service. */
563  dst->intro_period_started = src->intro_period_started;
564  dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
565  dst->n_intro_points_wanted = src->n_intro_points_wanted;
566 }
567 
568 /* Helper: Actual implementation of the pruning on reload which we've
569  * decoupled in order to make the unit test workeable without ugly hacks.
570  * Furthermore, this function does NOT free any memory but will nullify the
571  * temporary list pointer whatever happens. */
572 STATIC void
573 rend_service_prune_list_impl_(void)
574 {
575  origin_circuit_t *ocirc = NULL;
576  smartlist_t *surviving_services, *old_service_list, *new_service_list;
577 
578  /* When pruning our current service list, we must have a staging list that
579  * contains what we want to check else it's a code flow error. */
581 
582  /* We are about to prune the current list of its dead service so set the
583  * semantic for that list to be the "old" one. */
584  old_service_list = rend_service_list;
585  /* The staging list is now the "new" list so set this semantic. */
586  new_service_list = rend_service_staging_list;
587  /* After this, whatever happens, we'll use our new list. */
588  rend_service_list = new_service_list;
589  /* Finally, nullify the staging list pointer as we don't need it anymore
590  * and it needs to be NULL before the next reload. */
592  /* Nothing to prune if we have no service list so stop right away. */
593  if (!old_service_list) {
594  return;
595  }
596 
597  /* This contains all _existing_ services that survives the relaod that is
598  * that haven't been removed from the configuration. The difference between
599  * this list and the new service list is that the new list can possibly
600  * contain newly configured service that have no introduction points opened
601  * yet nor key material loaded or generated. */
602  surviving_services = smartlist_new();
603 
604  /* Preserve the existing ephemeral services.
605  *
606  * This is the ephemeral service equivalent of the "Copy introduction
607  * points to new services" block, except there's no copy required since
608  * the service structure isn't regenerated.
609  *
610  * After this is done, all ephemeral services will be:
611  * * Removed from old_service_list, so the equivalent non-ephemeral code
612  * will not attempt to preserve them.
613  * * Added to the new_service_list (that previously only had the
614  * services listed in the configuration).
615  * * Added to surviving_services, which is the list of services that
616  * will NOT have their intro point closed.
617  */
618  SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
619  if (rend_service_is_ephemeral(old)) {
620  SMARTLIST_DEL_CURRENT(old_service_list, old);
621  smartlist_add(surviving_services, old);
622  smartlist_add(new_service_list, old);
623  }
624  } SMARTLIST_FOREACH_END(old);
625 
626  /* Copy introduction points to new services. This is O(n^2), but it's only
627  * called on reconfigure, so it's ok performance wise. */
628  SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
629  SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
630  /* Skip ephemeral services as we only want to copy introduction points
631  * from current services to newly configured one that already exists.
632  * The same directory means it's the same service. */
634  strcmp(old->directory, new->directory)) {
635  continue;
636  }
637  smartlist_add_all(new->intro_nodes, old->intro_nodes);
638  smartlist_clear(old->intro_nodes);
639  smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
640  smartlist_clear(old->expiring_nodes);
641 
642  /* Copy needed information from old to new. */
643  copy_service_on_prunning(new, old);
644 
645  /* This regular service will survive the closing IPs step after. */
646  smartlist_add(surviving_services, old);
647  break;
648  } SMARTLIST_FOREACH_END(old);
649  } SMARTLIST_FOREACH_END(new);
650 
651  /* For every service introduction circuit we can find, see if we have a
652  * matching surviving configured service. If not, close the circuit. */
653  while ((ocirc = circuit_get_next_intro_circ(ocirc, false))) {
654  int keep_it = 0;
655  if (ocirc->rend_data == NULL) {
656  /* This is a v3 circuit, ignore it. */
657  continue;
658  }
659  SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
660  if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
661  /* Keep this circuit as we have a matching configured service. */
662  keep_it = 1;
663  break;
664  }
665  } SMARTLIST_FOREACH_END(s);
666  if (keep_it) {
667  continue;
668  }
669  log_info(LD_REND, "Closing intro point %s for service %s.",
670  safe_str_client(extend_info_describe(
671  ocirc->build_state->chosen_exit)),
672  safe_str_client(rend_data_get_address(ocirc->rend_data)));
673  /* Reason is FINISHED because service has been removed and thus the
674  * circuit is considered old/uneeded. */
675  circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
676  }
677  smartlist_free(surviving_services);
678  /* Notify that our global service list has changed. */
680 }
681 
682 /* Try to prune our main service list using the temporary one that we just
683  * loaded and parsed successfully. The pruning process decides which onion
684  * services to keep and which to discard after a reload. */
685 void
686 rend_service_prune_list(void)
687 {
688  smartlist_t *old_service_list = rend_service_list;
689 
692  }
693 
694  rend_service_prune_list_impl_();
695  if (old_service_list) {
696  /* Every remaining service in the old list have been removed from the
697  * configuration so clean them up safely. */
698  SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
699  rend_service_free(s));
700  smartlist_free(old_service_list);
701  }
702 }
703 
704 /* Copy all the relevant data that the hs_service object contains over to the
705  * rend_service_t object. The reason to do so is because when configuring a
706  * service, we go through a generic handler that creates an hs_service_t
707  * object which so we have to copy the parsed values to a rend service object
708  * which is version 2 specific. */
709 static void
710 service_config_shadow_copy(rend_service_t *service,
711  hs_service_config_t *config)
712 {
713  tor_assert(service);
714  tor_assert(config);
715 
716  service->directory = tor_strdup(config->directory_path);
717  service->dir_group_readable = config->dir_group_readable;
718  service->allow_unknown_ports = config->allow_unknown_ports;
719  /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
720  * if the code flow is right so this cast is safe. But just in case, we'll
721  * check it. */
722  service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
723  if (BUG(config->max_streams_per_rdv_circuit >
724  HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
725  service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
726  }
727  service->max_streams_close_circuit = config->max_streams_close_circuit;
728  service->n_intro_points_wanted = config->num_intro_points;
729  /* Switching ownership of the ports to the rend service object. */
730  smartlist_add_all(service->ports, config->ports);
731  smartlist_free(config->ports);
732  config->ports = NULL;
733 }
734 
735 /* Parse the hidden service configuration from <b>hs_opts</b> using the
736  * already configured generic service configuration in <b>config</b>. This
737  * function will translate the config object to a rend_service_t and add it to
738  * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
739  * and return as normal but don't actually add the service to the list. */
740 int
741 rend_config_service(const hs_opts_t *hs_opts,
742  const or_options_t *options,
743  hs_service_config_t *config)
744 {
745  rend_service_t *service = NULL;
746 
747  tor_assert(options);
748  tor_assert(hs_opts);
749  tor_assert(config);
750 
751  /* We are about to configure a version 2 service. Warn of deprecation. */
753 
754  /* Use the staging service list so that we can check then do the pruning
755  * process using the main list at the end. */
756  if (rend_service_staging_list == NULL) {
758  }
759 
760  /* Initialize service. */
761  service = tor_malloc_zero(sizeof(rend_service_t));
762  service->intro_period_started = time(NULL);
763  service->ports = smartlist_new();
764  /* From the hs_service object which has been used to load the generic
765  * options, we'll copy over the useful data to the rend_service_t object. */
766  service_config_shadow_copy(service, config);
767 
768  /* Number of introduction points. */
769  if (hs_opts->HiddenServiceNumIntroductionPoints > NUM_INTRO_POINTS_MAX) {
770  log_warn(LD_CONFIG, "HiddenServiceNumIntroductionPoints must be "
771  "between 0 and %d, not %d.",
773  hs_opts->HiddenServiceNumIntroductionPoints);
774  goto err;
775  }
776  service->n_intro_points_wanted = hs_opts->HiddenServiceNumIntroductionPoints;
777  log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
778  service->n_intro_points_wanted, escaped(service->directory));
779 
780  /* Client authorization */
781  if (hs_opts->HiddenServiceAuthorizeClient) {
782  /* Parse auth type and comma-separated list of client names and add a
783  * rend_authorized_client_t for each client to the service's list
784  * of authorized clients. */
785  smartlist_t *type_names_split, *clients;
786  const char *authname;
787  type_names_split = smartlist_new();
788  smartlist_split_string(type_names_split,
789  hs_opts->HiddenServiceAuthorizeClient, " ", 0, 2);
790  if (smartlist_len(type_names_split) < 1) {
791  log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
792  "should have been prevented when parsing the "
793  "configuration.");
794  smartlist_free(type_names_split);
795  goto err;
796  }
797  authname = smartlist_get(type_names_split, 0);
798  if (!strcasecmp(authname, "basic")) {
799  service->auth_type = REND_BASIC_AUTH;
800  } else if (!strcasecmp(authname, "stealth")) {
801  service->auth_type = REND_STEALTH_AUTH;
802  } else {
803  log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
804  "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
805  "are recognized.",
806  (char *) smartlist_get(type_names_split, 0));
807  SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
808  smartlist_free(type_names_split);
809  goto err;
810  }
811  service->clients = smartlist_new();
812  if (smartlist_len(type_names_split) < 2) {
813  log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
814  "auth-type '%s', but no client names.",
815  service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
816  SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
817  smartlist_free(type_names_split);
818  goto err;
819  }
820  clients = smartlist_new();
821  smartlist_split_string(clients, smartlist_get(type_names_split, 1),
822  ",", SPLIT_SKIP_SPACE, 0);
823  SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
824  smartlist_free(type_names_split);
825  /* Remove duplicate client names. */
826  {
827  int num_clients = smartlist_len(clients);
828  smartlist_sort_strings(clients);
829  smartlist_uniq_strings(clients);
830  if (smartlist_len(clients) < num_clients) {
831  log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
832  "duplicate client name(s); removing.",
833  num_clients - smartlist_len(clients));
834  }
835  }
836  SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name) {
837  rend_authorized_client_t *client;
838  if (!rend_valid_client_name(client_name)) {
839  log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
840  "illegal client name: '%s'. Names must be "
841  "between 1 and %d characters and contain "
842  "only [A-Za-z0-9+_-].",
843  client_name, REND_CLIENTNAME_MAX_LEN);
844  SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
845  smartlist_free(clients);
846  goto err;
847  }
848  client = tor_malloc_zero(sizeof(rend_authorized_client_t));
849  client->client_name = tor_strdup(client_name);
850  smartlist_add(service->clients, client);
851  log_debug(LD_REND, "Adding client name '%s'", client_name);
852  } SMARTLIST_FOREACH_END(client_name);
853  SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
854  smartlist_free(clients);
855  /* Ensure maximum number of clients. */
856  if ((service->auth_type == REND_BASIC_AUTH &&
857  smartlist_len(service->clients) > 512) ||
858  (service->auth_type == REND_STEALTH_AUTH &&
859  smartlist_len(service->clients) > 16)) {
860  log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
861  "client authorization entries, but only a "
862  "maximum of %d entries is allowed for "
863  "authorization type '%s'.",
864  smartlist_len(service->clients),
865  service->auth_type == REND_BASIC_AUTH ? 512 : 16,
866  service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
867  goto err;
868  }
869  }
870 
871  /* Validate the service just parsed. */
872  if (rend_validate_service(rend_service_staging_list, service) < 0) {
873  /* Service is in the staging list so don't try to free it. */
874  goto err;
875  }
876 
877  /* Add it to the temporary list which we will use to prune our current
878  * list if any after configuring all services. */
879  if (rend_add_service(rend_service_staging_list, service) < 0) {
880  /* The object has been freed on error already. */
881  service = NULL;
882  goto err;
883  }
884 
885  return 0;
886  err:
887  rend_service_free(service);
888  return -1;
889 }
890 
891 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
892  * client authorization <b>auth_type</b> and an optional list of
893  * rend_authorized_client_t in <b>auth_clients</b>, with
894  * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
895  * and circuit closure on max streams being exceeded set by
896  * <b>max_streams_close_circuit</b>.
897  *
898  * Ownership of pk, ports, and auth_clients is passed to this routine.
899  * Regardless of success/failure, callers should not touch these values
900  * after calling this routine, and may assume that correct cleanup has
901  * been done on failure.
902  *
903  * Return an appropriate hs_service_add_ephemeral_status_t.
904  */
907  smartlist_t *ports,
908  int max_streams_per_circuit,
909  int max_streams_close_circuit,
910  rend_auth_type_t auth_type,
911  smartlist_t *auth_clients,
912  char **service_id_out)
913 {
914  *service_id_out = NULL;
915  /* Allocate the service structure, and initialize the key, and key derived
916  * parameters.
917  */
918  rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
919  s->directory = NULL; /* This indicates the service is ephemeral. */
920  s->private_key = pk;
921  s->auth_type = auth_type;
922  s->clients = auth_clients;
923  s->ports = ports;
924  s->intro_period_started = time(NULL);
925  s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
926  s->max_streams_per_circuit = max_streams_per_circuit;
927  s->max_streams_close_circuit = max_streams_close_circuit;
928  if (rend_service_derive_key_digests(s) < 0) {
929  rend_service_free(s);
930  return RSAE_BADPRIVKEY;
931  }
932 
933  if (!s->ports || smartlist_len(s->ports) == 0) {
934  log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
935  rend_service_free(s);
936  return RSAE_BADVIRTPORT;
937  }
938  if (s->auth_type != REND_NO_AUTH &&
939  (!s->clients || smartlist_len(s->clients) == 0)) {
940  log_warn(LD_CONFIG, "At least one authorized client must be specified.");
941  rend_service_free(s);
942  return RSAE_BADAUTH;
943  }
944 
945  /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
946  * it's not, see #14828.
947  */
948  if (rend_service_get_by_pk_digest(s->pk_digest)) {
949  log_warn(LD_CONFIG, "Onion Service private key collides with an "
950  "existing service.");
951  rend_service_free(s);
952  return RSAE_ADDREXISTS;
953  }
954  if (rend_service_get_by_service_id(s->service_id)) {
955  log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
956  rend_service_free(s);
957  return RSAE_ADDREXISTS;
958  }
959 
960  /* Initialize the service. */
961  if (rend_add_service(NULL, s)) {
962  return RSAE_INTERNAL;
963  }
964  *service_id_out = tor_strdup(s->service_id);
965 
966  log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
967  return RSAE_OKAY;
968 }
969 
970 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
971  * success, and -1 on failure.
972  */
973 int
974 rend_service_del_ephemeral(const char *service_id)
975 {
976  rend_service_t *s;
977  if (!rend_valid_v2_service_id(service_id)) {
978  log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
979  return -1;
980  }
981  if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
982  log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
983  "removal.");
984  return -1;
985  }
986  if (!rend_service_is_ephemeral(s)) {
987  log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
988  return -1;
989  }
990 
991  /* Kill the intro point circuit for the Onion Service, and remove it from
992  * the list. Closing existing connections is the application's problem.
993  *
994  * XXX: As with the comment in rend_config_services(), a nice abstraction
995  * would be ideal here, but for now just duplicate the code.
996  */
998  if (!circ->marked_for_close &&
999  (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1000  circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
1001  origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
1002  if (oc->rend_data == NULL ||
1003  !rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
1004  continue;
1005  }
1006  log_debug(LD_REND, "Closing intro point %s for service %s.",
1007  safe_str_client(extend_info_describe(
1008  oc->build_state->chosen_exit)),
1010  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1011  }
1012  } SMARTLIST_FOREACH_END(circ);
1014  /* Notify that we just removed a service from our global list. */
1016  rend_service_free(s);
1017 
1018  log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
1019 
1020  return 0;
1021 }
1022 
1023 /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
1024  * another few seconds due to blocking calls. */
1025 #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
1026 
1027 /** Log information about the intro point creation rate and current intro
1028  * points for service, upgrading the log level from min_severity to warn if
1029  * we have stopped launching new intro point circuits. */
1030 static void
1031 rend_log_intro_limit(const rend_service_t *service, int min_severity)
1032 {
1033  int exceeded_limit = (service->n_intro_circuits_launched >=
1035  service->n_intro_points_wanted));
1036  int severity = min_severity;
1037  /* We stopped creating circuits */
1038  if (exceeded_limit) {
1039  severity = LOG_WARN;
1040  }
1041  time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
1042  tor_assert_nonfatal(intro_period_elapsed >= 0);
1043  {
1044  char *msg;
1045  static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
1046  if ((msg = rate_limit_log(&rlimit, approx_time()))) {
1047  log_fn(severity, LD_REND,
1048  "Hidden service %s %s %d intro points in the last %d seconds. "
1049  "Intro circuit launches are limited to %d per %d seconds.%s",
1050  service->service_id,
1051  exceeded_limit ? "exceeded launch limit with" : "launched",
1052  service->n_intro_circuits_launched,
1053  (int)intro_period_elapsed,
1054  rend_max_intro_circs_per_period(service->n_intro_points_wanted),
1056  rend_service_dump_stats(severity);
1057  tor_free(msg);
1058  }
1059  }
1060 }
1061 
1062 /** Replace the old value of <b>service</b>->desc with one that reflects
1063  * the other fields in service.
1064  */
1065 static void
1066 rend_service_update_descriptor(rend_service_t *service)
1067 {
1069  int i;
1070 
1071  rend_service_descriptor_free(service->desc);
1072  service->desc = NULL;
1073 
1074  d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
1075  d->pk = crypto_pk_dup_key(service->private_key);
1076  d->timestamp = time(NULL);
1077  d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
1078  d->intro_nodes = smartlist_new();
1079  /* Support intro protocols 2 and 3. */
1080  d->protocols = (1 << 2) + (1 << 3);
1081 
1082  for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
1083  rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
1084  rend_intro_point_t *intro_desc;
1085 
1086  /* This intro point won't be listed in the descriptor... */
1087  intro_svc->listed_in_last_desc = 0;
1088 
1089  /* circuit_established is set in rend_service_intro_established(), and
1090  * checked every second in rend_consider_services_intro_points(), so it's
1091  * safe to use it here */
1092  if (!intro_svc->circuit_established) {
1093  continue;
1094  }
1095 
1096  /* ...unless this intro point is listed in the descriptor. */
1097  intro_svc->listed_in_last_desc = 1;
1098 
1099  /* We have an entirely established intro circuit. Publish it in
1100  * our descriptor. */
1101  intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
1102  intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
1103  if (intro_svc->intro_key)
1104  intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
1105  smartlist_add(d->intro_nodes, intro_desc);
1106 
1107  if (intro_svc->time_published == -1) {
1108  /* We are publishing this intro point in a descriptor for the
1109  * first time -- note the current time in the service's copy of
1110  * the intro point. */
1111  intro_svc->time_published = time(NULL);
1112  }
1113  }
1114 
1115  /* Check that we have the right number of intro points */
1116  unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
1117  if (have_intro != service->n_intro_points_wanted) {
1118  int severity;
1119  /* Getting less than we wanted or more than we're allowed is serious */
1120  if (have_intro < service->n_intro_points_wanted ||
1121  have_intro > NUM_INTRO_POINTS_MAX) {
1122  severity = LOG_WARN;
1123  } else {
1124  /* Getting more than we wanted is weird, but less of a problem */
1125  severity = LOG_NOTICE;
1126  }
1127  log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
1128  "descriptor was updated with %d instead.",
1129  service->service_id,
1130  service->n_intro_points_wanted, have_intro);
1131  /* Now log an informative message about how we might have got here. */
1132  rend_log_intro_limit(service, severity);
1133  }
1134 }
1135 
1136 /* Allocate and return a string containing the path to file_name in
1137  * service->directory. Asserts that service has a directory.
1138  * This function will never return NULL.
1139  * The caller must free this path. */
1140 static char *
1141 rend_service_path(const rend_service_t *service, const char *file_name)
1142 {
1143  tor_assert(service->directory);
1144  return hs_path_from_filename(service->directory, file_name);
1145 }
1146 
1147 /* Allocate and return a string containing the path to the single onion
1148  * service poison file in service->directory. Asserts that service has a
1149  * directory.
1150  * The caller must free this path. */
1151 STATIC char *
1152 rend_service_sos_poison_path(const rend_service_t *service)
1153 {
1154  return rend_service_path(service, sos_poison_fname);
1155 }
1156 
1157 /** Return True if hidden services <b>service</b> has been poisoned by single
1158  * onion mode. */
1159 static int
1160 service_is_single_onion_poisoned(const rend_service_t *service)
1161 {
1162  char *poison_fname = NULL;
1163  file_status_t fstatus;
1164 
1165  /* Passing a NULL service is a bug */
1166  if (BUG(!service)) {
1167  return 0;
1168  }
1169 
1170  if (rend_service_is_ephemeral(service)) {
1171  return 0;
1172  }
1173 
1174  poison_fname = rend_service_sos_poison_path(service);
1175 
1176  fstatus = file_status(poison_fname);
1177  tor_free(poison_fname);
1178 
1179  /* If this fname is occupied, the hidden service has been poisoned.
1180  * fstatus can be FN_ERROR if the service directory does not exist, in that
1181  * case, there is obviously no private key. */
1182  if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
1183  return 1;
1184  }
1185 
1186  return 0;
1187 }
1188 
1189 /* Return 1 if the private key file for service exists and has a non-zero size,
1190  * and 0 otherwise. */
1191 static int
1192 rend_service_private_key_exists(const rend_service_t *service)
1193 {
1194  char *private_key_path = rend_service_path(service, private_key_fname);
1195  const file_status_t private_key_status = file_status(private_key_path);
1196  tor_free(private_key_path);
1197  /* Only non-empty regular private key files could have been used before.
1198  * fstatus can be FN_ERROR if the service directory does not exist, in that
1199  * case, there is obviously no private key. */
1200  return private_key_status == FN_FILE;
1201 }
1202 
1203 /** Check the single onion service poison state of the directory for s:
1204  * - If the service is poisoned, and we are in Single Onion Mode,
1205  * return 0,
1206  * - If the service is not poisoned, and we are not in Single Onion Mode,
1207  * return 0,
1208  * - Otherwise, the poison state is invalid: the service was created in one
1209  * mode, and is being used in the other, return -1.
1210  * Hidden service directories without keys are always considered consistent.
1211  * They will be poisoned after their directory is created (if needed). */
1212 STATIC int
1214  const or_options_t* options)
1215 {
1216  /* Passing a NULL service is a bug */
1217  if (BUG(!s)) {
1218  return -1;
1219  }
1220 
1221  /* Ephemeral services are checked at ADD_ONION time */
1222  if (BUG(rend_service_is_ephemeral(s))) {
1223  return -1;
1224  }
1225 
1226  /* Service is expected to have a directory */
1227  if (BUG(!s->directory)) {
1228  return -1;
1229  }
1230 
1231  /* Services without keys are always ok - their keys will only ever be used
1232  * in the current mode */
1233  if (!rend_service_private_key_exists(s)) {
1234  return 0;
1235  }
1236 
1237  /* The key has been used before in a different mode */
1239  rend_service_non_anonymous_mode_enabled(options)) {
1240  return -1;
1241  }
1242 
1243  /* The key exists and is consistent with the current mode */
1244  return 0;
1245 }
1246 
1247 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1248  * the hidden service directory for s that marks it as a single onion service.
1249  * Tor must be in single onion mode before calling this function, and the
1250  * service directory must already have been created.
1251  * Returns 0 when a directory is successfully poisoned, or if it is already
1252  * poisoned. Returns -1 on a failure to read the directory or write the poison
1253  * file, or if there is an existing private key file in the directory. (The
1254  * service should have been poisoned when the key was created.) */
1255 static int
1256 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
1257  const or_options_t* options)
1258 {
1259  /* Passing a NULL service is a bug */
1260  if (BUG(!service)) {
1261  return -1;
1262  }
1263 
1264  /* We must only poison directories if we're in Single Onion mode */
1265  tor_assert(rend_service_non_anonymous_mode_enabled(options));
1266 
1267  int fd;
1268  int retval = -1;
1269  char *poison_fname = NULL;
1270 
1271  if (rend_service_is_ephemeral(service)) {
1272  log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
1273  return 0;
1274  }
1275 
1276  /* Make sure we're only poisoning new hidden service directories */
1277  if (rend_service_private_key_exists(service)) {
1278  log_warn(LD_BUG, "Tried to single onion poison a service directory after "
1279  "the private key was created.");
1280  return -1;
1281  }
1282 
1283  /* Make sure the directory was created before calling this function. */
1284  if (BUG(hs_check_service_private_dir(options->User, service->directory,
1285  service->dir_group_readable, 0) < 0))
1286  return -1;
1287 
1288  poison_fname = rend_service_sos_poison_path(service);
1289 
1290  switch (file_status(poison_fname)) {
1291  case FN_DIR:
1292  case FN_ERROR:
1293  log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
1294  poison_fname);
1295  goto done;
1296  case FN_FILE: /* single onion poison file already exists. NOP. */
1297  case FN_EMPTY: /* single onion poison file already exists. NOP. */
1298  log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
1299  poison_fname);
1300  break;
1301  case FN_NOENT:
1302  fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
1303  if (fd < 0) {
1304  log_warn(LD_FS, "Could not create single onion poison file %s",
1305  poison_fname);
1306  goto done;
1307  }
1308  close(fd);
1309  break;
1310  default:
1311  tor_assert(0);
1312  }
1313 
1314  retval = 0;
1315 
1316  done:
1317  tor_free(poison_fname);
1318 
1319  return retval;
1320 }
1321 
1322 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1323  * hidden services. If s is new, we should mark its hidden service
1324  * directory appropriately so that it is never launched as a location-private
1325  * hidden service. (New directories don't have private key files.)
1326  * Return 0 on success, -1 on fail. */
1327 STATIC int
1329  const or_options_t* options)
1330 {
1331  /* Passing a NULL service is a bug */
1332  if (BUG(!s)) {
1333  return -1;
1334  }
1335 
1336  /* We must only poison directories if we're in Single Onion mode */
1337  tor_assert(rend_service_non_anonymous_mode_enabled(options));
1338 
1339  /* Ephemeral services aren't allowed in non-anonymous mode */
1340  if (BUG(rend_service_is_ephemeral(s))) {
1341  return -1;
1342  }
1343 
1344  /* Service is expected to have a directory */
1345  if (BUG(!s->directory)) {
1346  return -1;
1347  }
1348 
1349  if (!rend_service_private_key_exists(s)) {
1350  if (poison_new_single_onion_hidden_service_dir_impl(s, options)
1351  < 0) {
1352  return -1;
1353  }
1354  }
1355 
1356  return 0;
1357 }
1358 
1359 /* Return true iff the given service identity key is present on disk. This is
1360  * used to try to learn the service version during configuration time. */
1361 int
1362 rend_service_key_on_disk(const char *directory_path)
1363 {
1364  int ret = 0;
1365  char *fname;
1366  crypto_pk_t *pk = NULL;
1367 
1368  tor_assert(directory_path);
1369 
1370  /* Load key */
1371  fname = hs_path_from_filename(directory_path, private_key_fname);
1372  pk = init_key_from_file(fname, 0, LOG_DEBUG, NULL);
1373  if (pk) {
1374  ret = 1;
1375  }
1376 
1377  crypto_pk_free(pk);
1378  tor_free(fname);
1379  return ret;
1380 }
1381 
1382 /** Load and/or generate private keys for all hidden services, possibly
1383  * including keys for client authorization.
1384  * If a <b>service_list</b> is provided, treat it as the list of hidden
1385  * services (used in unittests). Otherwise, require that rend_service_list is
1386  * not NULL.
1387  * Return 0 on success, -1 on failure. */
1388 int
1390 {
1391  /* Use service_list for unit tests */
1392  const smartlist_t *s_list = rend_get_service_list(service_list);
1393  if (BUG(!s_list)) {
1394  return -1;
1395  }
1396 
1397  SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
1398  if (s->private_key)
1399  continue;
1400  log_info(LD_REND, "Loading hidden-service keys from %s",
1402 
1403  if (rend_service_load_keys(s) < 0)
1404  return -1;
1405  } SMARTLIST_FOREACH_END(s);
1406 
1407  return 0;
1408 }
1409 
1410 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1411 static void
1412 rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
1413 {
1414  tor_assert(lst);
1415  tor_assert(s);
1416  tor_assert(s->directory);
1417  smartlist_add(lst, rend_service_path(s, private_key_fname));
1418  smartlist_add(lst, rend_service_path(s, hostname_fname));
1419  smartlist_add(lst, rend_service_path(s, client_keys_fname));
1420  smartlist_add(lst, rend_service_sos_poison_path(s));
1421 }
1422 
1423 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1424  * and to <b>stat_lst</b> every directory used by a configured hidden
1425  * service */
1426 void
1428  smartlist_t *stat_lst)
1429 {
1430  if (!rend_service_list)
1431  return;
1432  SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
1433  if (!rend_service_is_ephemeral(s)) {
1435  smartlist_add_strdup(stat_lst, s->directory);
1436  }
1437  } SMARTLIST_FOREACH_END(s);
1438 }
1439 
1440 /** Derive all rend_service_t internal material based on the service's key.
1441  * Returns 0 on success, -1 on failure.
1442  */
1443 static int
1444 rend_service_derive_key_digests(struct rend_service_t *s)
1445 {
1446  if (rend_get_service_id(s->private_key, s->service_id)<0) {
1447  log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1448  return -1;
1449  }
1450  if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
1451  log_warn(LD_BUG, "Couldn't compute hash of public key.");
1452  return -1;
1453  }
1454 
1455  return 0;
1456 }
1457 
1458 /** Make sure that the directory for <b>s</b> is private, using the config in
1459  * <b>options</b>.
1460  * If <b>create</b> is true:
1461  * - if the directory exists, change permissions if needed,
1462  * - if the directory does not exist, create it with the correct permissions.
1463  * If <b>create</b> is false:
1464  * - if the directory exists, check permissions,
1465  * - if the directory does not exist, check if we think we can create it.
1466  * Return 0 on success, -1 on failure. */
1467 static int
1469  const rend_service_t *s,
1470  int create)
1471 {
1472  /* Passing a NULL service is a bug */
1473  if (BUG(!s)) {
1474  return -1;
1475  }
1476 
1477  /* Check/create directory */
1478  if (hs_check_service_private_dir(options->User, s->directory,
1479  s->dir_group_readable, create) < 0) {
1480  return -1;
1481  }
1482 
1483  /* Check if the hidden service key exists, and was created in a different
1484  * single onion service mode, and refuse to launch if it has.
1485  * This is safe to call even when create is false, as it ignores missing
1486  * keys and directories: they are always valid.
1487  */
1488  if (rend_service_verify_single_onion_poison(s, options) < 0) {
1489  /* We can't use s->service_id here, as the key may not have been loaded */
1490  log_warn(LD_GENERAL, "We are configured with "
1491  "HiddenServiceNonAnonymousMode %d, but the hidden "
1492  "service key in directory %s was created in %s mode. "
1493  "This is not allowed.",
1494  rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
1496  rend_service_non_anonymous_mode_enabled(options) ?
1497  "an anonymous" : "a non-anonymous"
1498  );
1499  return -1;
1500  }
1501 
1502  /* Poison new single onion directories immediately after they are created,
1503  * so that we never accidentally launch non-anonymous hidden services
1504  * thinking they are anonymous. Any keys created later will end up with the
1505  * correct poisoning state.
1506  */
1507  if (create && rend_service_non_anonymous_mode_enabled(options)) {
1508  static int logged_warning = 0;
1509 
1510  if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
1511  log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
1512  ".");
1513  return -1;
1514  }
1515 
1516  if (!logged_warning) {
1517  /* The keys for these services are linked to the server IP address */
1518  log_notice(LD_REND, "The configured onion service directories have been "
1519  "used in single onion mode. They can not be used for "
1520  "anonymous hidden services.");
1521  logged_warning = 1;
1522  }
1523  }
1524 
1525  return 0;
1526 }
1527 
1528 /** Load and/or generate private keys for the hidden service <b>s</b>,
1529  * possibly including keys for client authorization. Return 0 on success, -1
1530  * on failure. */
1531 static int
1532 rend_service_load_keys(rend_service_t *s)
1533 {
1534  char *fname = NULL;
1535  char buf[128];
1536 
1537  /* Create the directory if needed which will also poison it in case of
1538  * single onion service. */
1540  goto err;
1541 
1542  /* Load key */
1543  fname = rend_service_path(s, private_key_fname);
1544  s->private_key = init_key_from_file(fname, 1, LOG_ERR, NULL);
1545 
1546  if (!s->private_key)
1547  goto err;
1548 
1550  goto err;
1551 
1552  tor_free(fname);
1553  /* Create service file */
1554  fname = rend_service_path(s, hostname_fname);
1555 
1556  tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
1557  if (write_str_to_file_if_not_equal(fname, buf)) {
1558  log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
1559  goto err;
1560  }
1561 #ifndef _WIN32
1562  if (s->dir_group_readable) {
1563  /* Also verify hostname file created with group read. */
1564  if (chmod(fname, 0640))
1565  log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
1566  fname);
1567  }
1568 #endif /* !defined(_WIN32) */
1569 
1570  /* If client authorization is configured, load or generate keys. */
1571  if (s->auth_type != REND_NO_AUTH) {
1572  if (rend_service_load_auth_keys(s, fname) < 0) {
1573  goto err;
1574  }
1575  }
1576 
1577  int r = 0;
1578  goto done;
1579  err:
1580  r = -1;
1581  done:
1582  memwipe(buf, 0, sizeof(buf));
1583  tor_free(fname);
1584  return r;
1585 }
1586 
1587 /** Load and/or generate client authorization keys for the hidden service
1588  * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1589  * -1 on failure. */
1590 static int
1591 rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
1592 {
1593  int r = 0;
1594  char *cfname = NULL;
1595  char *client_keys_str = NULL;
1596  strmap_t *parsed_clients = strmap_new();
1597  FILE *cfile, *hfile;
1598  open_file_t *open_cfile = NULL, *open_hfile = NULL;
1599  char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
1600  char service_id[16+1];
1601  char buf[1500];
1602 
1603  /* Load client keys and descriptor cookies, if available. */
1604  cfname = rend_service_path(s, client_keys_fname);
1605  client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
1606  if (client_keys_str) {
1607  if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
1608  log_warn(LD_CONFIG, "Previously stored client_keys file could not "
1609  "be parsed.");
1610  goto err;
1611  } else {
1612  log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
1613  strmap_size(parsed_clients));
1614  }
1615  }
1616 
1617  /* Prepare client_keys and hostname files. */
1618  if (!(cfile = start_writing_to_stdio_file(cfname,
1619  OPEN_FLAGS_REPLACE | O_TEXT,
1620  0600, &open_cfile))) {
1621  log_warn(LD_CONFIG, "Could not open client_keys file %s",
1622  escaped(cfname));
1623  goto err;
1624  }
1625 
1626  if (!(hfile = start_writing_to_stdio_file(hfname,
1627  OPEN_FLAGS_REPLACE | O_TEXT,
1628  0600, &open_hfile))) {
1629  log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
1630  goto err;
1631  }
1632 
1633  /* Either use loaded keys for configured clients or generate new
1634  * ones if a client is new. */
1635  SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
1636  rend_authorized_client_t *parsed =
1637  strmap_get(parsed_clients, client->client_name);
1638  int written;
1639  size_t len;
1640  /* Copy descriptor cookie from parsed entry or create new one. */
1641  if (parsed) {
1642  memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
1644  } else {
1645  crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
1646  }
1647  /* For compatibility with older tor clients, this does not
1648  * truncate the padding characters, unlike rend_auth_encode_cookie. */
1649  if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
1650  (char *) client->descriptor_cookie,
1651  REND_DESC_COOKIE_LEN, 0) < 0) {
1652  log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1653  goto err;
1654  }
1655  /* Copy client key from parsed entry or create new one if required. */
1656  if (parsed && parsed->client_key) {
1657  client->client_key = crypto_pk_dup_key(parsed->client_key);
1658  } else if (s->auth_type == REND_STEALTH_AUTH) {
1659  /* Create private key for client. */
1660  crypto_pk_t *prkey = NULL;
1661  if (!(prkey = crypto_pk_new())) {
1662  log_warn(LD_BUG,"Error constructing client key");
1663  goto err;
1664  }
1665  if (crypto_pk_generate_key(prkey)) {
1666  log_warn(LD_BUG,"Error generating client key");
1667  crypto_pk_free(prkey);
1668  goto err;
1669  }
1670  if (! crypto_pk_is_valid_private_key(prkey)) {
1671  log_warn(LD_BUG,"Generated client key seems invalid");
1672  crypto_pk_free(prkey);
1673  goto err;
1674  }
1675  client->client_key = prkey;
1676  }
1677  /* Add entry to client_keys file. */
1678  written = tor_snprintf(buf, sizeof(buf),
1679  "client-name %s\ndescriptor-cookie %s\n",
1680  client->client_name, desc_cook_out);
1681  if (written < 0) {
1682  log_warn(LD_BUG, "Could not write client entry.");
1683  goto err;
1684  }
1685  if (client->client_key) {
1686  char *client_key_out = NULL;
1687  if (crypto_pk_write_private_key_to_string(client->client_key,
1688  &client_key_out, &len) != 0) {
1689  log_warn(LD_BUG, "Internal error: "
1690  "crypto_pk_write_private_key_to_string() failed.");
1691  goto err;
1692  }
1693  if (rend_get_service_id(client->client_key, service_id)<0) {
1694  log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1695  /*
1696  * len is string length, not buffer length, but last byte is NUL
1697  * anyway.
1698  */
1699  memwipe(client_key_out, 0, len);
1700  tor_free(client_key_out);
1701  goto err;
1702  }
1703  written = tor_snprintf(buf + written, sizeof(buf) - written,
1704  "client-key\n%s", client_key_out);
1705  memwipe(client_key_out, 0, len);
1706  tor_free(client_key_out);
1707  if (written < 0) {
1708  log_warn(LD_BUG, "Could not write client entry.");
1709  goto err;
1710  }
1711  } else {
1712  strlcpy(service_id, s->service_id, sizeof(service_id));
1713  }
1714 
1715  if (fputs(buf, cfile) < 0) {
1716  log_warn(LD_FS, "Could not append client entry to file: %s",
1717  strerror(errno));
1718  goto err;
1719  }
1720 
1721  /* Add line to hostname file. This is not the same encoding as in
1722  * client_keys. */
1723  char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
1724  s->auth_type);
1725  if (!encoded_cookie) {
1726  log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1727  goto err;
1728  }
1729  tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
1730  service_id, encoded_cookie, client->client_name);
1731  memwipe(encoded_cookie, 0, strlen(encoded_cookie));
1732  tor_free(encoded_cookie);
1733 
1734  if (fputs(buf, hfile)<0) {
1735  log_warn(LD_FS, "Could not append host entry to file: %s",
1736  strerror(errno));
1737  goto err;
1738  }
1739  } SMARTLIST_FOREACH_END(client);
1740 
1741  finish_writing_to_file(open_cfile);
1742  finish_writing_to_file(open_hfile);
1743 
1744  goto done;
1745  err:
1746  r = -1;
1747  if (open_cfile)
1748  abort_writing_to_file(open_cfile);
1749  if (open_hfile)
1750  abort_writing_to_file(open_hfile);
1751  done:
1752  if (client_keys_str) {
1753  memwipe(client_keys_str, 0, strlen(client_keys_str));
1754  tor_free(client_keys_str);
1755  }
1756  strmap_free(parsed_clients, rend_authorized_client_free_void);
1757 
1758  if (cfname) {
1759  memwipe(cfname, 0, strlen(cfname));
1760  tor_free(cfname);
1761  }
1762 
1763  /* Clear stack buffers that held key-derived material. */
1764  memwipe(buf, 0, sizeof(buf));
1765  memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
1766  memwipe(service_id, 0, sizeof(service_id));
1767 
1768  return r;
1769 }
1770 
1771 /** Return the service whose public key has a digest of <b>digest</b>, or
1772  * NULL if no such service exists.
1773  */
1774 static rend_service_t *
1776 {
1777  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
1778  if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
1779  return s);
1780  return NULL;
1781 }
1782 
1783 /** Return the service whose service id is <b>id</b>, or NULL if no such
1784  * service exists.
1785  */
1786 static struct rend_service_t *
1788 {
1789  tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
1790  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
1791  if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
1792  return s;
1793  });
1794  return NULL;
1795 }
1796 
1797 /** Check client authorization of a given <b>descriptor_cookie</b> of
1798  * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1799  * and 0 for failure. */
1800 static int
1801 rend_check_authorization(rend_service_t *service,
1802  const char *descriptor_cookie,
1803  size_t cookie_len)
1804 {
1805  rend_authorized_client_t *auth_client = NULL;
1806  tor_assert(service);
1807  tor_assert(descriptor_cookie);
1808  if (!service->clients) {
1809  log_warn(LD_BUG, "Can't check authorization for a service that has no "
1810  "authorized clients configured.");
1811  return 0;
1812  }
1813 
1814  if (cookie_len != REND_DESC_COOKIE_LEN) {
1815  log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
1816  "%lu bytes. Dropping cell.",
1817  (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
1818  return 0;
1819  }
1820 
1821  /* Look up client authorization by descriptor cookie. */
1822  SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
1823  if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
1824  REND_DESC_COOKIE_LEN)) {
1825  auth_client = client;
1826  break;
1827  }
1828  });
1829  if (!auth_client) {
1830  char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
1831  base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
1832  descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
1833  log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
1834  "Dropping cell!",
1835  descriptor_cookie_base64);
1836  return 0;
1837  }
1838 
1839  /* Allow the request. */
1840  log_info(LD_REND, "Client %s authorized for service %s.",
1841  auth_client->client_name, service->service_id);
1842  return 1;
1843 }
1844 
1845 /* Can this service make a direct connection to ei?
1846  * It must be a single onion service, and the firewall rules must allow ei. */
1847 static int
1848 rend_service_use_direct_connection(const or_options_t* options,
1849  const extend_info_t* ei)
1850 {
1851  /* We'll connect directly all reachable addresses, whether preferred or not.
1852  * The prefer_ipv6 argument to reachable_addr_allows_addr is
1853  * ignored, because pref_only is 0. */
1854  const tor_addr_port_t *ap = extend_info_get_orport(ei, AF_INET);
1855  if (!ap)
1856  return 0;
1857  return (rend_service_allow_non_anonymous_connection(options) &&
1858  reachable_addr_allows_addr(&ap->addr, ap->port,
1859  FIREWALL_OR_CONNECTION, 0, 0));
1860 }
1861 
1862 /* Like rend_service_use_direct_connection, but to a node. */
1863 static int
1864 rend_service_use_direct_connection_node(const or_options_t* options,
1865  const node_t* node)
1866 {
1867  /* We'll connect directly all reachable addresses, whether preferred or not.
1868  */
1869  return (rend_service_allow_non_anonymous_connection(options) &&
1870  reachable_addr_allows_node(node, FIREWALL_OR_CONNECTION, 0));
1871 }
1872 
1873 /******
1874  * Handle cells
1875  ******/
1876 
1877 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1878  * rendezvous point.
1879  */
1880 int
1882  const uint8_t *request,
1883  size_t request_len)
1884 {
1885  /* Global status stuff */
1886  int status = 0, result;
1887  const or_options_t *options = get_options();
1888  char *err_msg = NULL;
1889  int err_msg_severity = LOG_WARN;
1890  const char *stage_descr = NULL, *rend_pk_digest;
1891  int reason = END_CIRC_REASON_TORPROTOCOL;
1892  /* Service/circuit/key stuff we can learn before parsing */
1893  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1894  rend_service_t *service = NULL;
1895  rend_intro_point_t *intro_point = NULL;
1896  crypto_pk_t *intro_key = NULL;
1897  /* Parsed cell */
1898  rend_intro_cell_t *parsed_req = NULL;
1899  /* Rendezvous point */
1900  extend_info_t *rp = NULL;
1901  /* XXX not handled yet */
1902  char buf[RELAY_PAYLOAD_SIZE];
1903  char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
1904  int i;
1905  crypto_dh_t *dh = NULL;
1906  origin_circuit_t *launched = NULL;
1907  crypt_path_t *cpath = NULL;
1908  char hexcookie[9];
1909  int circ_needs_uptime;
1910  time_t now = time(NULL);
1911  time_t elapsed;
1912  int replay;
1913  ssize_t keylen;
1914 
1915  /* Do some initial validation and logging before we parse the cell */
1916  if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1917  log_warn(LD_PROTOCOL,
1918  "Got an INTRODUCE2 over a non-introduction circuit %u.",
1919  (unsigned) circuit->base_.n_circ_id);
1920  goto err;
1921  }
1922 
1923  assert_circ_anonymity_ok(circuit, options);
1924  tor_assert(circuit->rend_data);
1925  /* XXX: This is version 2 specific (only one supported). */
1926  rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
1927 
1928  /* We'll use this in a bazillion log messages */
1930  rend_pk_digest, REND_SERVICE_ID_LEN);
1931 
1932  /* look up service depending on circuit. */
1933  service = rend_service_get_by_pk_digest(rend_pk_digest);
1934  if (!service) {
1935  log_warn(LD_BUG,
1936  "Internal error: Got an INTRODUCE2 cell on an intro "
1937  "circ for an unrecognized service %s.",
1938  escaped(serviceid));
1939  goto err;
1940  }
1941 
1942  intro_point = find_intro_point(circuit);
1943  if (intro_point == NULL) {
1944  intro_point = find_expiring_intro_point(service, circuit);
1945  if (intro_point == NULL) {
1946  log_warn(LD_BUG,
1947  "Internal error: Got an INTRODUCE2 cell on an "
1948  "intro circ (for service %s) with no corresponding "
1949  "rend_intro_point_t.",
1950  escaped(serviceid));
1951  goto err;
1952  }
1953  }
1954 
1955  log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
1956  escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
1957 
1958  /* use intro key instead of service key. */
1959  intro_key = circuit->intro_key;
1960 
1961  tor_free(err_msg);
1962  stage_descr = NULL;
1963 
1964  stage_descr = "early parsing";
1965  /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1966  parsed_req =
1967  rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
1968  if (!parsed_req) {
1969  goto log_error;
1970  } else if (err_msg) {
1971  log_info(LD_REND, "%s on circ %u.", err_msg,
1972  (unsigned)circuit->base_.n_circ_id);
1973  tor_free(err_msg);
1974  }
1975 
1976  /* make sure service replay caches are present */
1977  if (!service->accepted_intro_dh_parts) {
1978  service->accepted_intro_dh_parts =
1981  }
1982 
1983  if (!intro_point->accepted_intro_rsa_parts) {
1984  intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
1985  }
1986 
1987  /* check for replay of PK-encrypted portion. */
1988  keylen = crypto_pk_keysize(intro_key);
1990  intro_point->accepted_intro_rsa_parts,
1991  parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
1992  &elapsed);
1993 
1994  if (replay) {
1995  log_warn(LD_REND,
1996  "Possible replay detected! We received an "
1997  "INTRODUCE2 cell with same PK-encrypted part %d "
1998  "seconds ago. Dropping cell.",
1999  (int)elapsed);
2000  goto err;
2001  }
2002 
2003  stage_descr = "decryption";
2004  /* Now try to decrypt it */
2005  result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
2006  if (result < 0) {
2007  goto log_error;
2008  } else if (err_msg) {
2009  log_info(LD_REND, "%s on circ %u.", err_msg,
2010  (unsigned)circuit->base_.n_circ_id);
2011  tor_free(err_msg);
2012  }
2013 
2014  stage_descr = "late parsing";
2015  /* Parse the plaintext */
2016  result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
2017  if (result < 0) {
2018  goto log_error;
2019  } else if (err_msg) {
2020  log_info(LD_REND, "%s on circ %u.", err_msg,
2021  (unsigned)circuit->base_.n_circ_id);
2022  tor_free(err_msg);
2023  }
2024 
2025  stage_descr = "late validation";
2026  /* Validate the parsed plaintext parts */
2027  result = rend_service_validate_intro_late(parsed_req, &err_msg);
2028  if (result < 0) {
2029  goto log_error;
2030  } else if (err_msg) {
2031  log_info(LD_REND, "%s on circ %u.", err_msg,
2032  (unsigned)circuit->base_.n_circ_id);
2033  tor_free(err_msg);
2034  }
2035  stage_descr = NULL;
2036 
2037  /* Increment INTRODUCE2 counter */
2038  ++(intro_point->accepted_introduce2_count);
2039 
2040  /* Find the rendezvous point */
2041  rp = find_rp_for_intro(parsed_req, &err_msg);
2042  if (!rp) {
2043  err_msg_severity = LOG_PROTOCOL_WARN;
2044  goto log_error;
2045  }
2046 
2047  /* Check if we'd refuse to talk to this router */
2048  if (options->StrictNodes &&
2050  log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
2051  "exclude, and StrictNodes is set. Refusing service.");
2052  reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
2053  goto err;
2054  }
2055 
2056  base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
2057 
2058  /* Check whether there is a past request with the same Diffie-Hellman,
2059  * part 1. */
2061  service->accepted_intro_dh_parts,
2062  parsed_req->dh, DH1024_KEY_LEN,
2063  &elapsed);
2064 
2065  if (replay) {
2066  /* A Tor client will send a new INTRODUCE1 cell with the same rend
2067  * cookie and DH public key as its previous one if its intro circ
2068  * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
2069  * If we received the first INTRODUCE1 cell (the intro-point relay
2070  * converts it into an INTRODUCE2 cell), we are already trying to
2071  * connect to that rend point (and may have already succeeded);
2072  * drop this cell. */
2073  log_info(LD_REND, "We received an "
2074  "INTRODUCE2 cell with same first part of "
2075  "Diffie-Hellman handshake %d seconds ago. Dropping "
2076  "cell.",
2077  (int) elapsed);
2078  goto err;
2079  }
2080 
2081  /* If the service performs client authorization, check included auth data. */
2082  if (service->clients) {
2083  if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
2084  if (rend_check_authorization(service,
2085  (const char*)parsed_req->u.v3.auth_data,
2086  parsed_req->u.v3.auth_len)) {
2087  log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
2088  } else {
2089  log_info(LD_REND, "The authorization data that are contained in "
2090  "the INTRODUCE2 cell are invalid. Dropping cell.");
2091  reason = END_CIRC_REASON_CONNECTFAILED;
2092  goto err;
2093  }
2094  } else {
2095  log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
2096  "data, but we require client authorization. Dropping cell.");
2097  reason = END_CIRC_REASON_CONNECTFAILED;
2098  goto err;
2099  }
2100  }
2101 
2102  /* Try DH handshake... */
2103  dh = crypto_dh_new(DH_TYPE_REND);
2104  if (!dh || crypto_dh_generate_public(dh)<0) {
2105  log_warn(LD_BUG,"Internal error: couldn't build DH state "
2106  "or generate public key.");
2107  reason = END_CIRC_REASON_INTERNAL;
2108  goto err;
2109  }
2110  if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
2111  (char *)(parsed_req->dh),
2112  DH1024_KEY_LEN, keys,
2113  DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
2114  log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
2115  reason = END_CIRC_REASON_INTERNAL;
2116  goto err;
2117  }
2118 
2119  circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
2120 
2121  /* help predict this next time */
2122  rep_hist_note_used_internal(now, circ_needs_uptime, 1);
2123 
2124  /* Launch a circuit to the client's chosen rendezvous point.
2125  */
2126  int max_rend_failures=hs_get_service_max_rend_failures();
2127  for (i=0;i<max_rend_failures;i++) {
2129  if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2130  /* A Single Onion Service only uses a direct connection if its
2131  * firewall rules permit direct connections to the address.
2132  *
2133  * We only use a one-hop path on the first attempt. If the first attempt
2134  * fails, we use a 3-hop path for reachability / reliability.
2135  * See the comment in rend_service_relaunch_rendezvous() for details. */
2136  if (rend_service_use_direct_connection(options, rp) && i == 0) {
2137  flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2138  }
2139  launched = circuit_launch_by_extend_info(
2140  CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2141 
2142  if (launched)
2143  break;
2144  }
2145  if (!launched) { /* give up */
2146  log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2147  "point %s for service %s.",
2148  safe_str_client(extend_info_describe(rp)),
2149  serviceid);
2150  reason = END_CIRC_REASON_CONNECTFAILED;
2151  goto err;
2152  }
2153  log_info(LD_REND,
2154  "Accepted intro; launching circuit to %s "
2155  "(cookie %s) for service %s.",
2156  safe_str_client(extend_info_describe(rp)),
2157  hexcookie, serviceid);
2158  tor_assert(launched->build_state);
2159  /* Fill in the circuit's state. */
2160 
2161  launched->rend_data =
2162  rend_data_service_create(service->service_id, rend_pk_digest,
2163  parsed_req->rc, service->auth_type);
2164 
2166  tor_malloc_zero(sizeof(crypt_path_reference_t));
2168 
2169  launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2170  tor_malloc_zero(sizeof(crypt_path_t));
2171  cpath->magic = CRYPT_PATH_MAGIC;
2172  launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2173 
2174  cpath->rend_dh_handshake_state = dh;
2175  dh = NULL;
2176  if (cpath_init_circuit_crypto(cpath,
2177  keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
2178  1, 0)<0)
2179  goto err;
2180  memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2181 
2182  goto done;
2183 
2184  log_error:
2185  if (!err_msg) {
2186  if (stage_descr) {
2187  tor_asprintf(&err_msg,
2188  "unknown %s error for INTRODUCE2", stage_descr);
2189  } else {
2190  err_msg = tor_strdup("unknown error for INTRODUCE2");
2191  }
2192  }
2193 
2194  log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2195  (unsigned)circuit->base_.n_circ_id);
2196  err:
2197  status = -1;
2198  if (dh) crypto_dh_free(dh);
2199  if (launched) {
2200  circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2201  }
2202  tor_free(err_msg);
2203 
2204  done:
2205  memwipe(keys, 0, sizeof(keys));
2206  memwipe(buf, 0, sizeof(buf));
2207  memwipe(serviceid, 0, sizeof(serviceid));
2208  memwipe(hexcookie, 0, sizeof(hexcookie));
2209 
2210  /* Free the parsed cell */
2211  rend_service_free_intro(parsed_req);
2212 
2213  /* Free rp */
2214  extend_info_free(rp);
2215 
2216  return status;
2217 }
2218 
2219 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2220  * return NULL and an error string if we can't. Return a newly allocated
2221  * extend_info_t* for the rendezvous point. */
2222 static extend_info_t *
2224  char **err_msg_out)
2225 {
2226  extend_info_t *rp = NULL;
2227  char *err_msg = NULL;
2228  const char *rp_nickname = NULL;
2229  const node_t *node = NULL;
2230 
2231  if (!intro) {
2232  if (err_msg_out)
2233  err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2234 
2235  goto err;
2236  }
2237 
2238  if (intro->version == 0 || intro->version == 1) {
2239  rp_nickname = (const char *)(intro->u.v0_v1.rp);
2240 
2241  node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
2242  if (!node) {
2243  if (err_msg_out) {
2244  tor_asprintf(&err_msg,
2245  "Couldn't find router %s named in INTRODUCE2 cell",
2246  escaped_safe_str_client(rp_nickname));
2247  }
2248 
2249  goto err;
2250  }
2251 
2252  /* Are we in single onion mode? */
2253  const int allow_direct = rend_service_allow_non_anonymous_connection(
2254  get_options());
2255  rp = extend_info_from_node(node, allow_direct);
2256  if (!rp) {
2257  if (err_msg_out) {
2258  tor_asprintf(&err_msg,
2259  "Couldn't build extend_info_t for router %s named "
2260  "in INTRODUCE2 cell",
2261  escaped_safe_str_client(rp_nickname));
2262  }
2263 
2264  goto err;
2265  }
2266  } else if (intro->version == 2) {
2267  rp = extend_info_dup(intro->u.v2.extend_info);
2268  } else if (intro->version == 3) {
2269  rp = extend_info_dup(intro->u.v3.extend_info);
2270  } else {
2271  if (err_msg_out) {
2272  tor_asprintf(&err_msg,
2273  "Unknown version %d in INTRODUCE2 cell",
2274  (int)(intro->version));
2275  }
2276 
2277  goto err;
2278  }
2279 
2280  /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2281  * the other cases goto err. */
2282  tor_assert(rp);
2283 
2284  /* Make sure the RP we are being asked to connect to is _not_ a private
2285  * address unless it's allowed. Let's avoid to build a circuit to our
2286  * second middle node and fail right after when extending to the RP. */
2287  const tor_addr_port_t *orport = extend_info_get_orport(rp, AF_INET);
2288  if (! orport || !extend_info_addr_is_allowed(&orport->addr)) {
2289  if (err_msg_out) {
2290  tor_asprintf(&err_msg,
2291  "Relay IP in INTRODUCE2 cell is private address.");
2292  }
2293  extend_info_free(rp);
2294  rp = NULL;
2295  goto err;
2296  }
2297  goto done;
2298 
2299  err:
2300  if (err_msg_out)
2301  *err_msg_out = err_msg;
2302  else
2303  tor_free(err_msg);
2304 
2305  done:
2306  return rp;
2307 }
2308 
2309 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2310  * rend_service_parse_intro().
2311  */
2312 void
2314 {
2315  if (!request) {
2316  return;
2317  }
2318 
2319  /* Free ciphertext */
2320  tor_free(request->ciphertext);
2321  request->ciphertext_len = 0;
2322 
2323  /* Have plaintext? */
2324  if (request->plaintext) {
2325  /* Zero it out just to be safe */
2326  memwipe(request->plaintext, 0, request->plaintext_len);
2327  tor_free(request->plaintext);
2328  request->plaintext_len = 0;
2329  }
2330 
2331  /* Have parsed plaintext? */
2332  if (request->parsed) {
2333  switch (request->version) {
2334  case 0:
2335  case 1:
2336  /*
2337  * Nothing more to do; these formats have no further pointers
2338  * in them.
2339  */
2340  break;
2341  case 2:
2342  extend_info_free(request->u.v2.extend_info);
2343  request->u.v2.extend_info = NULL;
2344  break;
2345  case 3:
2346  if (request->u.v3.auth_data) {
2347  memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2348  tor_free(request->u.v3.auth_data);
2349  }
2350 
2351  extend_info_free(request->u.v3.extend_info);
2352  request->u.v3.extend_info = NULL;
2353  break;
2354  default:
2355  log_info(LD_BUG,
2356  "rend_service_free_intro() saw unknown protocol "
2357  "version %d.",
2358  request->version);
2359  }
2360  }
2361 
2362  /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2363  memwipe(request, 0, sizeof(*request));
2364 
2365  tor_free(request);
2366 }
2367 
2368 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2369  * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2370  * when finished. The type parameter should be 1 or 2 to indicate whether
2371  * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2372  * parts; after this, call rend_service_decrypt_intro() with a key, then
2373  * rend_service_parse_intro_plaintext() to finish parsing. The optional
2374  * err_msg_out parameter is set to a string suitable for log output
2375  * if parsing fails. This function does some validation, but only
2376  * that which depends solely on the contents of the cell and the
2377  * key; it can be unit-tested. Further validation is done in
2378  * rend_service_validate_intro().
2379  */
2380 
2382 rend_service_begin_parse_intro(const uint8_t *request,
2383  size_t request_len,
2384  uint8_t type,
2385  char **err_msg_out)
2386 {
2387  rend_intro_cell_t *rv = NULL;
2388  char *err_msg = NULL;
2389 
2390  if (!request || request_len <= 0) goto err;
2391  if (!(type == 1 || type == 2)) goto err;
2392 
2393  /* First, check that the cell is long enough to be a sensible INTRODUCE */
2394 
2395  /* min key length plus digest length plus nickname length */
2396  if (request_len <
2398  DH1024_KEY_LEN + 42)) {
2399  if (err_msg_out) {
2400  tor_asprintf(&err_msg,
2401  "got a truncated INTRODUCE%d cell",
2402  (int)type);
2403  }
2404  goto err;
2405  }
2406 
2407  /* Allocate a new parsed cell structure */
2408  rv = tor_malloc_zero(sizeof(*rv));
2409 
2410  /* Set the type */
2411  rv->type = type;
2412 
2413  /* Copy in the ID */
2414  memcpy(rv->pk, request, DIGEST_LEN);
2415 
2416  /* Copy in the ciphertext */
2417  rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2418  memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2419  rv->ciphertext_len = request_len - DIGEST_LEN;
2420 
2421  goto done;
2422 
2423  err:
2424  rend_service_free_intro(rv);
2425  rv = NULL;
2426 
2427  if (err_msg_out && !err_msg) {
2428  tor_asprintf(&err_msg,
2429  "unknown INTRODUCE%d error",
2430  (int)type);
2431  }
2432 
2433  done:
2434  if (err_msg_out) *err_msg_out = err_msg;
2435  else tor_free(err_msg);
2436 
2437  return rv;
2438 }
2439 
2440 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2441  * cell
2442  */
2443 
2444 static ssize_t
2446  rend_intro_cell_t *intro,
2447  const uint8_t *buf,
2448  size_t plaintext_len,
2449  char **err_msg_out)
2450 {
2451  const char *rp_nickname, *endptr;
2452  size_t nickname_field_len, ver_specific_len;
2453 
2454  if (intro->version == 1) {
2455  ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2456  rp_nickname = ((const char *)buf) + 1;
2457  nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2458  } else if (intro->version == 0) {
2459  ver_specific_len = MAX_NICKNAME_LEN + 1;
2460  rp_nickname = (const char *)buf;
2461  nickname_field_len = MAX_NICKNAME_LEN + 1;
2462  } else {
2463  if (err_msg_out)
2464  tor_asprintf(err_msg_out,
2465  "rend_service_parse_intro_for_v0_or_v1() called with "
2466  "bad version %d on INTRODUCE%d cell (this is a bug)",
2467  intro->version,
2468  (int)(intro->type));
2469  goto err;
2470  }
2471 
2472  if (plaintext_len < ver_specific_len) {
2473  if (err_msg_out)
2474  tor_asprintf(err_msg_out,
2475  "short plaintext of encrypted part in v1 INTRODUCE%d "
2476  "cell (%lu bytes, needed %lu)",
2477  (int)(intro->type),
2478  (unsigned long)plaintext_len,
2479  (unsigned long)ver_specific_len);
2480  goto err;
2481  }
2482 
2483  endptr = memchr(rp_nickname, 0, nickname_field_len);
2484  if (!endptr || endptr == rp_nickname) {
2485  if (err_msg_out) {
2486  tor_asprintf(err_msg_out,
2487  "couldn't find a nul-padded nickname in "
2488  "INTRODUCE%d cell",
2489  (int)(intro->type));
2490  }
2491  goto err;
2492  }
2493 
2494  if ((intro->version == 0 &&
2495  !is_legal_nickname(rp_nickname)) ||
2496  (intro->version == 1 &&
2497  !is_legal_nickname_or_hexdigest(rp_nickname))) {
2498  if (err_msg_out) {
2499  tor_asprintf(err_msg_out,
2500  "bad nickname in INTRODUCE%d cell",
2501  (int)(intro->type));
2502  }
2503  goto err;
2504  }
2505 
2506  memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2507 
2508  return ver_specific_len;
2509 
2510  err:
2511  return -1;
2512 }
2513 
2514 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2515  */
2516 
2517 static ssize_t
2519  rend_intro_cell_t *intro,
2520  const uint8_t *buf,
2521  size_t plaintext_len,
2522  char **err_msg_out)
2523 {
2524  unsigned int klen;
2525  extend_info_t *extend_info = NULL;
2526  ssize_t ver_specific_len;
2527 
2528  /*
2529  * We accept version 3 too so that the v3 parser can call this with
2530  * an adjusted buffer for the latter part of a v3 cell, which is
2531  * identical to a v2 cell.
2532  */
2533  if (!(intro->version == 2 ||
2534  intro->version == 3)) {
2535  if (err_msg_out)
2536  tor_asprintf(err_msg_out,
2537  "rend_service_parse_intro_for_v2() called with "
2538  "bad version %d on INTRODUCE%d cell (this is a bug)",
2539  intro->version,
2540  (int)(intro->type));
2541  goto err;
2542  }
2543 
2544  /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2545  if (plaintext_len < 7 + DIGEST_LEN + 2) {
2546  if (err_msg_out) {
2547  tor_asprintf(err_msg_out,
2548  "truncated plaintext of encrypted parted of "
2549  "version %d INTRODUCE%d cell",
2550  intro->version,
2551  (int)(intro->type));
2552  }
2553 
2554  goto err;
2555  }
2556 
2557  extend_info = extend_info_new(NULL, NULL, NULL, NULL, NULL, NULL, 0);
2558  tor_addr_t addr;
2559  tor_addr_from_ipv4n(&addr, get_uint32(buf + 1));
2560  uint16_t port = ntohs(get_uint16(buf + 5));
2561  extend_info_add_orport(extend_info, &addr, port);
2562  memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2563  extend_info->nickname[0] = '$';
2564  base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2565  extend_info->identity_digest, DIGEST_LEN);
2566  klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2567 
2568  /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2569  if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2570  if (err_msg_out) {
2571  tor_asprintf(err_msg_out,
2572  "truncated plaintext of encrypted parted of "
2573  "version %d INTRODUCE%d cell",
2574  intro->version,
2575  (int)(intro->type));
2576  }
2577 
2578  goto err;
2579  }
2580 
2581  extend_info->onion_key =
2582  crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2583  if (!extend_info->onion_key) {
2584  if (err_msg_out) {
2585  tor_asprintf(err_msg_out,
2586  "error decoding onion key in version %d "
2587  "INTRODUCE%d cell",
2588  intro->version,
2589  (intro->type));
2590  }
2591 
2592  goto err;
2593  }
2594  if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2595  if (err_msg_out) {
2596  tor_asprintf(err_msg_out,
2597  "invalid onion key size in version %d INTRODUCE%d cell",
2598  intro->version,
2599  (intro->type));
2600  }
2601 
2602  goto err;
2603  }
2604 
2605  ver_specific_len = 7+DIGEST_LEN+2+klen;
2606 
2607  if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2608  else intro->u.v3.extend_info = extend_info;
2609 
2610  return ver_specific_len;
2611 
2612  err:
2613  extend_info_free(extend_info);
2614 
2615  return -1;
2616 }
2617 
2618 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2619  */
2620 
2621 static ssize_t
2623  rend_intro_cell_t *intro,
2624  const uint8_t *buf,
2625  size_t plaintext_len,
2626  char **err_msg_out)
2627 {
2628  ssize_t adjust, v2_ver_specific_len, ts_offset;
2629 
2630  /* This should only be called on v3 cells */
2631  if (intro->version != 3) {
2632  if (err_msg_out)
2633  tor_asprintf(err_msg_out,
2634  "rend_service_parse_intro_for_v3() called with "
2635  "bad version %d on INTRODUCE%d cell (this is a bug)",
2636  intro->version,
2637  (int)(intro->type));
2638  goto err;
2639  }
2640 
2641  /*
2642  * Check that we have at least enough to get auth_len:
2643  *
2644  * 1 octet for version, 1 for auth_type, 2 for auth_len
2645  */
2646  if (plaintext_len < 4) {
2647  if (err_msg_out) {
2648  tor_asprintf(err_msg_out,
2649  "truncated plaintext of encrypted parted of "
2650  "version %d INTRODUCE%d cell",
2651  intro->version,
2652  (int)(intro->type));
2653  }
2654 
2655  goto err;
2656  }
2657 
2658  /*
2659  * The rend_client_send_introduction() function over in rendclient.c is
2660  * broken (i.e., fails to match the spec) in such a way that we can't
2661  * change it without breaking the protocol. Specifically, it doesn't
2662  * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2663  * by two bytes after that. Calculate ts_offset and do everything from
2664  * the timestamp on relative to that to handle this dain bramage.
2665  */
2666 
2667  intro->u.v3.auth_type = buf[1];
2668  if (intro->u.v3.auth_type != REND_NO_AUTH) {
2669  intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2670  ts_offset = 4 + intro->u.v3.auth_len;
2671  } else {
2672  intro->u.v3.auth_len = 0;
2673  ts_offset = 2;
2674  }
2675 
2676  /* Check that auth len makes sense for this auth type */
2677  if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2678  intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2679  if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2680  if (err_msg_out) {
2681  tor_asprintf(err_msg_out,
2682  "wrong auth data size %d for INTRODUCE%d cell, "
2683  "should be %d",
2684  (int)(intro->u.v3.auth_len),
2685  (int)(intro->type),
2687  }
2688 
2689  goto err;
2690  }
2691  }
2692 
2693  /* Check that we actually have everything up through the timestamp */
2694  if (plaintext_len < (size_t)(ts_offset)+4) {
2695  if (err_msg_out) {
2696  tor_asprintf(err_msg_out,
2697  "truncated plaintext of encrypted parted of "
2698  "version %d INTRODUCE%d cell",
2699  intro->version,
2700  (int)(intro->type));
2701  }
2702 
2703  goto err;
2704  }
2705 
2706  if (intro->u.v3.auth_type != REND_NO_AUTH &&
2707  intro->u.v3.auth_len > 0) {
2708  /* Okay, we can go ahead and copy auth_data */
2709  intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2710  /*
2711  * We know we had an auth_len field in this case, so 4 is
2712  * always right.
2713  */
2714  memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2715  }
2716 
2717  /*
2718  * From here on, the format is as in v2, so we call the v2 parser with
2719  * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2720  * v2 parser expects to skip over a version byte at the start, so we
2721  * adjust by 3 + ts_offset.
2722  */
2723  adjust = 3 + ts_offset;
2724 
2725  v2_ver_specific_len =
2727  buf + adjust, plaintext_len - adjust,
2728  err_msg_out);
2729 
2730  /* Success in v2 parser */
2731  if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2732  /* Failure in v2 parser; it will have provided an err_msg */
2733  else return v2_ver_specific_len;
2734 
2735  err:
2736  return -1;
2737 }
2738 
2739 /** Table of parser functions for version-specific parts of an INTRODUCE2
2740  * cell.
2741  */
2742 
2743 static ssize_t
2746  const uint8_t *,
2747  size_t,
2748  char **) =
2753 
2754 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2755  * return 0 if successful, or < 0 and write an error message to
2756  * *err_msg_out if provided.
2757  */
2758 
2759 int
2761  rend_intro_cell_t *intro,
2762  crypto_pk_t *key,
2763  char **err_msg_out)
2764 {
2765  char *err_msg = NULL;
2766  uint8_t key_digest[DIGEST_LEN];
2767  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2768  ssize_t key_len;
2769  uint8_t buf[RELAY_PAYLOAD_SIZE];
2770  int result, status = -1;
2771 
2772  if (!intro || !key) {
2773  if (err_msg_out) {
2774  err_msg =
2775  tor_strdup("rend_service_decrypt_intro() called with bad "
2776  "parameters");
2777  }
2778 
2779  status = -2;
2780  goto err;
2781  }
2782 
2783  /* Make sure we have ciphertext */
2784  if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2785  if (err_msg_out) {
2786  tor_asprintf(&err_msg,
2787  "rend_intro_cell_t was missing ciphertext for "
2788  "INTRODUCE%d cell",
2789  (int)(intro->type));
2790  }
2791  status = -3;
2792  goto err;
2793  }
2794 
2795  /* Check that this cell actually matches this service key */
2796 
2797  /* first DIGEST_LEN bytes of request is intro or service pk digest */
2798  if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
2799  if (err_msg_out)
2800  *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
2801  log_warn(LD_BUG, "Couldn't compute key digest.");
2802  status = -7;
2803  goto err;
2804  }
2805 
2806  if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2807  if (err_msg_out) {
2808  base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2809  (char*)(intro->pk), REND_SERVICE_ID_LEN);
2810  tor_asprintf(&err_msg,
2811  "got an INTRODUCE%d cell for the wrong service (%s)",
2812  (int)(intro->type),
2813  escaped(service_id));
2814  }
2815 
2816  status = -4;
2817  goto err;
2818  }
2819 
2820  /* Make sure the encrypted part is long enough to decrypt */
2821 
2822  key_len = crypto_pk_keysize(key);
2823  if (intro->ciphertext_len < key_len) {
2824  if (err_msg_out) {
2825  tor_asprintf(&err_msg,
2826  "got an INTRODUCE%d cell with a truncated PK-encrypted "
2827  "part",
2828  (int)(intro->type));
2829  }
2830 
2831  status = -5;
2832  goto err;
2833  }
2834 
2835  /* Decrypt the encrypted part */
2836  result =
2838  key, (char *)buf, sizeof(buf),
2839  (const char *)(intro->ciphertext), intro->ciphertext_len,
2841  if (result < 0) {
2842  if (err_msg_out) {
2843  tor_asprintf(&err_msg,
2844  "couldn't decrypt INTRODUCE%d cell",
2845  (int)(intro->type));
2846  }
2847  status = -6;
2848  goto err;
2849  }
2850  intro->plaintext_len = result;
2851  intro->plaintext = tor_malloc(intro->plaintext_len);
2852  memcpy(intro->plaintext, buf, intro->plaintext_len);
2853 
2854  status = 0;
2855 
2856  goto done;
2857 
2858  err:
2859  if (err_msg_out && !err_msg) {
2860  tor_asprintf(&err_msg,
2861  "unknown INTRODUCE%d error decrypting encrypted part",
2862  intro ? (int)(intro->type) : -1);
2863  }
2864 
2865  done:
2866  if (err_msg_out) *err_msg_out = err_msg;
2867  else tor_free(err_msg);
2868 
2869  /* clean up potentially sensitive material */
2870  memwipe(buf, 0, sizeof(buf));
2871  memwipe(key_digest, 0, sizeof(key_digest));
2872  memwipe(service_id, 0, sizeof(service_id));
2873 
2874  return status;
2875 }
2876 
2877 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2878  * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2879  * message to *err_msg_out if provided.
2880  */
2881 
2882 int
2884  rend_intro_cell_t *intro,
2885  char **err_msg_out)
2886 {
2887  char *err_msg = NULL;
2888  ssize_t ver_specific_len, ver_invariant_len;
2889  uint8_t version;
2890  int status = -1;
2891 
2892  if (!intro) {
2893  if (err_msg_out) {
2894  err_msg =
2895  tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2896  "rend_intro_cell_t");
2897  }
2898 
2899  status = -2;
2900  goto err;
2901  }
2902 
2903  /* Check that we have plaintext */
2904  if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2905  if (err_msg_out) {
2906  err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2907  }
2908  status = -3;
2909  goto err;
2910  }
2911 
2912  /* In all formats except v0, the first byte is a version number */
2913  version = intro->plaintext[0];
2914 
2915  /* v0 has no version byte (stupid...), so handle it as a fallback */
2916  if (version > 3) version = 0;
2917 
2918  /* Copy the version into the parsed cell structure */
2919  intro->version = version;
2920 
2921  /* Call the version-specific parser from the table */
2922  ver_specific_len =
2923  intro_version_handlers[version](intro,
2924  intro->plaintext, intro->plaintext_len,
2925  &err_msg);
2926  if (ver_specific_len < 0) {
2927  status = -4;
2928  goto err;
2929  }
2930 
2931  /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2932  * and at the end of the plaintext of the encrypted part of the cell.
2933  */
2934 
2935  ver_invariant_len = intro->plaintext_len - ver_specific_len;
2936  if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
2937  tor_asprintf(&err_msg,
2938  "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2939  (int)(intro->type),
2940  (long)(intro->plaintext_len));
2941  status = -5;
2942  goto err;
2943  } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
2944  tor_asprintf(&err_msg,
2945  "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2946  (int)(intro->type),
2947  (long)(intro->plaintext_len));
2948  status = -6;
2949  goto err;
2950  } else {
2951  memcpy(intro->rc,
2952  intro->plaintext + ver_specific_len,
2953  REND_COOKIE_LEN);
2954  memcpy(intro->dh,
2955  intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2956  DH1024_KEY_LEN);
2957  }
2958 
2959  /* Flag it as being fully parsed */
2960  intro->parsed = 1;
2961 
2962  status = 0;
2963  goto done;
2964 
2965  err:
2966  if (err_msg_out && !err_msg) {
2967  tor_asprintf(&err_msg,
2968  "unknown INTRODUCE%d error parsing encrypted part",
2969  intro ? (int)(intro->type) : -1);
2970  }
2971 
2972  done:
2973  if (err_msg_out) *err_msg_out = err_msg;
2974  else tor_free(err_msg);
2975 
2976  return status;
2977 }
2978 
2979 /** Do validity checks on a parsed intro cell after decryption; some of
2980  * these are not done in rend_service_parse_intro_plaintext() itself because
2981  * they depend on a lot of other state and would make it hard to unit test.
2982  * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2983  * optionally writes out an error message for logging. If an err_msg
2984  * pointer is provided, it is the caller's responsibility to free any
2985  * provided message.
2986  */
2987 
2988 int
2990  char **err_msg_out)
2991 {
2992  int status = 0;
2993 
2994  if (!intro) {
2995  if (err_msg_out)
2996  *err_msg_out =
2997  tor_strdup("NULL intro cell passed to "
2998  "rend_service_validate_intro_late()");
2999 
3000  status = -1;
3001  goto err;
3002  }
3003 
3004  if (intro->version == 3 && intro->parsed) {
3005  if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
3006  intro->u.v3.auth_type == REND_BASIC_AUTH ||
3007  intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
3008  /* This is an informative message, not an error, as in the old code */
3009  if (err_msg_out)
3010  tor_asprintf(err_msg_out,
3011  "unknown authorization type %d",
3012  intro->u.v3.auth_type);
3013  }
3014  }
3015 
3016  err:
3017  return status;
3018 }
3019 
3020 /** Called when we fail building a rendezvous circuit at some point other
3021  * than the last hop: launches a new circuit to the same rendezvous point.
3022  */
3023 void
3025 {
3026  origin_circuit_t *newcirc;
3027  cpath_build_state_t *newstate, *oldstate;
3028  const char *rend_pk_digest;
3029  rend_service_t *service = NULL;
3030 
3032 
3034  oldstate = oldcirc->build_state;
3035  tor_assert(oldstate);
3036 
3037  if (oldstate->service_pending_final_cpath_ref == NULL) {
3038  log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
3039  "Initiator will retry.");
3040  return;
3041  }
3042 
3043  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
3044  safe_str(extend_info_describe(oldstate->chosen_exit)));
3045 
3046  /* Look up the service. */
3047  rend_pk_digest = (char *) rend_data_get_pk_digest(oldcirc->rend_data, NULL);
3048  service = rend_service_get_by_pk_digest(rend_pk_digest);
3049 
3050  if (!service) {
3051  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3053  rend_pk_digest, REND_SERVICE_ID_LEN);
3054 
3055  log_warn(LD_BUG, "Internal error: Trying to relaunch a rendezvous circ "
3056  "for an unrecognized service %s.",
3057  safe_str_client(serviceid));
3058  return;
3059  }
3060 
3061  if (hs_service_requires_uptime_circ(service->ports)) {
3062  flags |= CIRCLAUNCH_NEED_UPTIME;
3063  }
3064 
3065  /* You'd think Single Onion Services would want to retry the rendezvous
3066  * using a direct connection. But if it's blocked by a firewall, or the
3067  * service is IPv6-only, or the rend point avoiding becoming a one-hop
3068  * proxy, we need a 3-hop connection. */
3070  oldstate->chosen_exit, flags);
3071 
3072  if (!newcirc) {
3073  log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
3074  safe_str(extend_info_describe(oldstate->chosen_exit)));
3075  return;
3076  }
3077  newstate = newcirc->build_state;
3078  tor_assert(newstate);
3079  newstate->failure_count = oldstate->failure_count+1;
3080  newstate->expiry_time = oldstate->expiry_time;
3084 
3085  newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
3086 }
3087 
3088 /** Launch a circuit to serve as an introduction point for the service
3089  * <b>service</b> at the introduction point <b>nickname</b>
3090  */
3091 static int
3092 rend_service_launch_establish_intro(rend_service_t *service,
3093  rend_intro_point_t *intro)
3094 {
3095  origin_circuit_t *launched;
3097  const or_options_t *options = get_options();
3098  extend_info_t *launch_ei = intro->extend_info;
3099  extend_info_t *direct_ei = NULL;
3100 
3101  /* Are we in single onion mode?
3102  *
3103  * We only use a one-hop path on the first attempt. If the first attempt
3104  * fails, we use a 3-hop path for reachability / reliability.
3105  * (Unlike v3, retries is incremented by the caller after it calls this
3106  * function.)
3107  */
3108  if (rend_service_allow_non_anonymous_connection(options) &&
3109  intro->circuit_retries == 0) {
3110  /* Do we have a descriptor for the node?
3111  * We've either just chosen it from the consensus, or we've just reviewed
3112  * our intro points to see which ones are still valid, and deleted the ones
3113  * that aren't in the consensus any more. */
3114  const node_t *node = node_get_by_id(launch_ei->identity_digest);
3115  if (BUG(!node)) {
3116  /* The service has kept an intro point after it went missing from the
3117  * consensus. If we did anything else here, it would be a consensus
3118  * distinguisher. Which are less of an issue for single onion services,
3119  * but still a bug. */
3120  return -1;
3121  }
3122  /* Can we connect to the node directly? If so, replace launch_ei
3123  * (a multi-hop extend_info) with one suitable for direct connection. */
3124  if (rend_service_use_direct_connection_node(options, node)) {
3125  direct_ei = extend_info_from_node(node, 1);
3126  if (BUG(!direct_ei)) {
3127  /* rend_service_use_direct_connection_node and extend_info_from_node
3128  * disagree about which addresses on this node are permitted. This
3129  * should never happen. Avoiding the connection is a safe response. */
3130  return -1;
3131  }
3132  flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3133  launch_ei = direct_ei;
3134  }
3135  }
3136  /* launch_ei is either intro->extend_info, or has been replaced with a valid
3137  * extend_info for single onion service direct connection. */
3138  tor_assert(launch_ei);
3139  /* We must have the same intro when making a direct connection. */
3141  launch_ei->identity_digest,
3142  DIGEST_LEN));
3143 
3144  log_info(LD_REND,
3145  "Launching circuit to introduction point %s%s%s for service %s",
3146  safe_str_client(extend_info_describe(intro->extend_info)),
3147  direct_ei ? " via direct address " : "",
3148  direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3149  service->service_id);
3150 
3151  rep_hist_note_used_internal(time(NULL), 1, 0);
3152 
3153  ++service->n_intro_circuits_launched;
3155  launch_ei, flags);
3156 
3157  if (!launched) {
3158  log_info(LD_REND,
3159  "Can't launch circuit to establish introduction at %s%s%s.",
3160  safe_str_client(extend_info_describe(intro->extend_info)),
3161  direct_ei ? " via direct address " : "",
3162  direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3163  );
3164  extend_info_free(direct_ei);
3165  return -1;
3166  }
3167  /* We must have the same exit node even if cannibalized or direct connection.
3168  */
3171  DIGEST_LEN));
3172 
3173  launched->rend_data = rend_data_service_create(service->service_id,
3174  service->pk_digest, NULL,
3175  service->auth_type);
3176  launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3177  if (launched->base_.state == CIRCUIT_STATE_OPEN)
3179  extend_info_free(direct_ei);
3180  return 0;
3181 }
3182 
3183 /** Return the number of introduction points that are established for the
3184  * given service. */
3185 static unsigned int
3186 count_established_intro_points(const rend_service_t *service)
3187 {
3188  unsigned int num = 0;
3189 
3190  SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3191  num += intro->circuit_established
3192  );
3193  return num;
3194 }
3195 
3196 /** Return the number of introduction points that are or are being
3197  * established for the given service. This function iterates over all
3198  * circuit and count those that are linked to the service and are waiting
3199  * for the intro point to respond. */
3200 static unsigned int
3201 count_intro_point_circuits(const rend_service_t *service)
3202 {
3203  unsigned int num_ipos = 0;
3205  if (!circ->marked_for_close &&
3206  circ->state == CIRCUIT_STATE_OPEN &&
3207  (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3208  circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3209  origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3210  if (oc->rend_data &&
3211  rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
3212  num_ipos++;
3213  }
3214  }
3215  }
3216  SMARTLIST_FOREACH_END(circ);
3217  return num_ipos;
3218 }
3219 
3220 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3221  write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3222  as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3223  crypto material. On success, fill <b>cell_body_out</b> and return the number
3224  of bytes written. On fail, return -1.
3225  */
3226 ssize_t
3227 rend_service_encode_establish_intro_cell(char *cell_body_out,
3228  size_t cell_body_out_len,
3229  crypto_pk_t *intro_key,
3230  const char *rend_circ_nonce)
3231 {
3232  int retval = -1;
3233  int r;
3234  int len = 0;
3235  char auth[DIGEST_LEN + 9];
3236 
3237  tor_assert(intro_key);
3238  tor_assert(rend_circ_nonce);
3239 
3240  /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3241  r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
3242  RELAY_PAYLOAD_SIZE-2);
3243  if (r < 0) {
3244  log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3245  goto err;
3246  }
3247  len = r;
3248  set_uint16(cell_body_out, htons((uint16_t)len));
3249  len += 2;
3250  memcpy(auth, rend_circ_nonce, DIGEST_LEN);
3251  memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3252  if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
3253  goto err;
3254  len += 20;
3255  r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
3256  cell_body_out_len - len,
3257  cell_body_out, len);
3258  if (r<0) {
3259  log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3260  goto err;
3261  }
3262  len += r;
3263 
3264  retval = len;
3265 
3266  err:
3267  memwipe(auth, 0, sizeof(auth));
3268 
3269  return retval;
3270 }
3271 
3272 /** Called when we're done building a circuit to an introduction point:
3273  * sends a RELAY_ESTABLISH_INTRO cell.
3274  */
3275 void
3277 {
3278  rend_service_t *service;
3279  char buf[RELAY_PAYLOAD_SIZE];
3280  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3281  unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
3282  int reason = END_CIRC_REASON_TORPROTOCOL;
3283  const char *rend_pk_digest;
3284 
3286  assert_circ_anonymity_ok(circuit, get_options());
3287  tor_assert(circuit->cpath);
3288  tor_assert(circuit->rend_data);
3289  /* XXX: This is version 2 specific (only on supported). */
3290  rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3291 
3293  rend_pk_digest, REND_SERVICE_ID_LEN);
3294 
3295  service = rend_service_get_by_pk_digest(rend_pk_digest);
3296  if (!service) {
3297  log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3298  safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3299  reason = END_CIRC_REASON_NOSUCHSERVICE;
3300  goto err;
3301  }
3302 
3303  /* Take the current amount of expiring nodes and the current amount of IP
3304  * circuits and compute how many valid IP circuits we have. */
3305  expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
3306  num_ip_circuits = count_intro_point_circuits(service);
3307  /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3308  * case this condition turns out false because it means that all circuits
3309  * are expiring so we need to keep this circuit. */
3310  if (num_ip_circuits > expiring_nodes_len) {
3311  valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
3312  }
3313 
3314  /* If we already have enough introduction circuits for this service,
3315  * redefine this one as a general circuit or close it, depending.
3316  * Subtract the amount of expiring nodes here because the circuits are
3317  * still opened. */
3318  if (valid_ip_circuits > service->n_intro_points_wanted) {
3319  const or_options_t *options = get_options();
3320  /* Remove the intro point associated with this circuit, it's being
3321  * repurposed or closed thus cleanup memory. */
3322  rend_intro_point_t *intro = find_intro_point(circuit);
3323  if (intro != NULL) {
3324  smartlist_remove(service->intro_nodes, intro);
3325  rend_intro_point_free(intro);
3326  }
3327 
3328  if (options->ExcludeNodes) {
3329  /* XXXX in some future version, we can test whether the transition is
3330  allowed or not given the actual nodes in the circuit. But for now,
3331  this case, we might as well close the thing. */
3332  log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3333  "circuit, but we already have enough. Closing it.");
3334  reason = END_CIRC_REASON_NONE;
3335  goto err;
3336  } else {
3337  tor_assert(circuit->build_state->is_internal);
3338  log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3339  "circuit, but we already have enough. Redefining purpose to "
3340  "general; leaving as internal.");
3341 
3342  if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
3345  } else {
3347  }
3348 
3349  {
3350  rend_data_free(circuit->rend_data);
3351  circuit->rend_data = NULL;
3352  }
3353  {
3354  crypto_pk_t *intro_key = circuit->intro_key;
3355  circuit->intro_key = NULL;
3356  crypto_pk_free(intro_key);
3357  }
3358 
3359  circuit_has_opened(circuit);
3360  goto done;
3361  }
3362  }
3363 
3364  log_info(LD_REND,
3365  "Established circuit %u as introduction point for service %s",
3366  (unsigned)circuit->base_.n_circ_id, serviceid);
3367  circuit_log_path(LOG_INFO, LD_REND, circuit);
3368 
3369  /* Send the ESTABLISH_INTRO cell */
3370  {
3371  ssize_t len;
3372  len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
3373  circuit->intro_key,
3374  circuit->cpath->prev->rend_circ_nonce);
3375  if (len < 0) {
3376  reason = END_CIRC_REASON_INTERNAL;
3377  goto err;
3378  }
3379 
3380  if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3381  RELAY_COMMAND_ESTABLISH_INTRO,
3382  buf, len, circuit->cpath->prev)<0) {
3383  log_info(LD_GENERAL,
3384  "Couldn't send introduction request for service %s on circuit %u",
3385  serviceid, (unsigned)circuit->base_.n_circ_id);
3386  goto done;
3387  }
3388  }
3389 
3390  /* We've attempted to use this circuit */
3391  pathbias_count_use_attempt(circuit);
3392 
3393  goto done;
3394 
3395  err:
3396  circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3397  done:
3398  memwipe(buf, 0, sizeof(buf));
3399  memwipe(serviceid, 0, sizeof(serviceid));
3400 
3401  return;
3402 }
3403 
3404 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3405  * live introduction point, and note that the service descriptor is
3406  * now out-of-date. */
3407 int
3409  const uint8_t *request,
3410  size_t request_len)
3411 {
3412  rend_service_t *service;
3413  rend_intro_point_t *intro;
3414  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3415  (void) request;
3416  (void) request_len;
3417  tor_assert(circuit->rend_data);
3418  /* XXX: This is version 2 specific (only supported one for now). */
3419  const char *rend_pk_digest =
3420  (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3421 
3422  if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3423  log_warn(LD_PROTOCOL,
3424  "received INTRO_ESTABLISHED cell on non-intro circuit.");
3425  goto err;
3426  }
3427  service = rend_service_get_by_pk_digest(rend_pk_digest);
3428  if (!service) {
3429  log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3430  (unsigned)circuit->base_.n_circ_id);
3431  goto err;
3432  }
3434  rend_pk_digest, REND_SERVICE_ID_LEN);
3435  /* We've just successfully established a intro circuit to one of our
3436  * introduction point, account for it. */
3437  intro = find_intro_point(circuit);
3438  if (intro == NULL) {
3439  log_warn(LD_REND,
3440  "Introduction circuit established without a rend_intro_point_t "
3441  "object for service %s on circuit %u",
3442  safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3443  goto err;
3444  }
3445  intro->circuit_established = 1;
3446  /* We might not have every introduction point ready but at this point we
3447  * know that the descriptor needs to be uploaded. */
3448  service->desc_is_dirty = time(NULL);
3450 
3451  log_info(LD_REND,
3452  "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3453  (unsigned)circuit->base_.n_circ_id, serviceid);
3454 
3455  /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3456  * used the circ */
3457  pathbias_mark_use_success(circuit);
3458 
3459  return 0;
3460  err:
3461  circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3462  return -1;
3463 }
3464 
3465 /** Called once a circuit to a rendezvous point is established: sends a
3466  * RELAY_COMMAND_RENDEZVOUS1 cell.
3467  */
3468 void
3470 {
3471  rend_service_t *service;
3472  char buf[RELAY_PAYLOAD_SIZE];
3473  crypt_path_t *hop;
3474  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3475  char hexcookie[9];
3476  int reason;
3477  const char *rend_cookie, *rend_pk_digest;
3478 
3480  tor_assert(circuit->cpath);
3481  tor_assert(circuit->build_state);
3482  assert_circ_anonymity_ok(circuit, get_options());
3483  tor_assert(circuit->rend_data);
3484 
3485  /* XXX: This is version 2 specific (only one supported). */
3486  rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
3487  NULL);
3488  rend_cookie = circuit->rend_data->rend_cookie;
3489 
3490  /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3491  * timestamp regardless of its content because that circuit could have been
3492  * cannibalized so in any cases, we are about to use that circuit more. */
3493  circuit->base_.timestamp_dirty = time(NULL);
3494 
3495  /* This may be redundant */
3496  pathbias_count_use_attempt(circuit);
3497 
3499 
3500  base16_encode(hexcookie,9, rend_cookie,4);
3502  rend_pk_digest, REND_SERVICE_ID_LEN);
3503 
3504  log_info(LD_REND,
3505  "Done building circuit %u to rendezvous with "
3506  "cookie %s for service %s",
3507  (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3508  circuit_log_path(LOG_INFO, LD_REND, circuit);
3509 
3510  /* Clear the 'in-progress HS circ has timed out' flag for
3511  * consistency with what happens on the client side; this line has
3512  * no effect on Tor's behaviour. */
3513  circuit->hs_circ_has_timed_out = 0;
3514 
3515  /* If hop is NULL, another rend circ has already connected to this
3516  * rend point. Close this circ. */
3517  if (hop == NULL) {
3518  log_info(LD_REND, "Another rend circ has already reached this rend point; "
3519  "closing this rend circ.");
3520  reason = END_CIRC_REASON_NONE;
3521  goto err;
3522  }
3523 
3524  /* Remove our final cpath element from the reference, so that no
3525  * other circuit will try to use it. Store it in
3526  * pending_final_cpath for now to ensure that it will be freed if
3527  * our rendezvous attempt fails. */
3528  circuit->build_state->pending_final_cpath = hop;
3530 
3531  service = rend_service_get_by_pk_digest(rend_pk_digest);
3532  if (!service) {
3533  log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3534  "rendezvous circuit.");
3535  reason = END_CIRC_REASON_INTERNAL;
3536  goto err;
3537  }
3538 
3539  /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3540  memcpy(buf, rend_cookie, REND_COOKIE_LEN);
3542  buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
3543  log_warn(LD_GENERAL,"Couldn't get DH public key.");
3544  reason = END_CIRC_REASON_INTERNAL;
3545  goto err;
3546  }
3548  DIGEST_LEN);
3549 
3550  /* Send the cell */
3551  if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3552  RELAY_COMMAND_RENDEZVOUS1,
3554  circuit->cpath->prev)<0) {
3555  log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3556  goto done;
3557  }
3558 
3559  crypto_dh_free(hop->rend_dh_handshake_state);
3560  hop->rend_dh_handshake_state = NULL;
3561 
3562  /* Append the cpath entry. */
3563  hop->state = CPATH_STATE_OPEN;
3564  /* set the windows to default. these are the windows
3565  * that the service thinks the client has.
3566  */
3569 
3570  cpath_extend_linked_list(&circuit->cpath, hop);
3571  circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3572 
3573  /* Change the circuit purpose. */
3575 
3576  goto done;
3577 
3578  err:
3579  circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3580  done:
3581  memwipe(buf, 0, sizeof(buf));
3582  memwipe(serviceid, 0, sizeof(serviceid));
3583  memwipe(hexcookie, 0, sizeof(hexcookie));
3584 
3585  return;
3586 }
3587 
3588 /*
3589  * Manage introduction points
3590  */
3591 
3592 /** Return the (possibly non-open) introduction circuit ending at
3593  * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3594  * (<b>desc_version</b> is ignored). Return NULL if no such service is
3595  * found.
3596  */
3597 static origin_circuit_t *
3598 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3599 {
3600  origin_circuit_t *circ = NULL;
3601 
3602  tor_assert(intro);
3603  while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3604  (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
3607  circ->rend_data) {
3608  return circ;
3609  }
3610  }
3611 
3612  circ = NULL;
3613  while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3614  (uint8_t *) pk_digest,
3618  circ->rend_data) {
3619  return circ;
3620  }
3621  }
3622  return NULL;
3623 }
3624 
3625 /** Return the corresponding introdution point using the circuit <b>circ</b>
3626  * found in the <b>service</b>. NULL is returned if not found. */
3627 static rend_intro_point_t *
3628 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3629 {
3630  tor_assert(service);
3632  TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3633 
3634  SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3635  intro_point,
3636  if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3637  return intro_point;
3638  });
3639 
3640  return NULL;
3641 }
3642 
3643 /** Return a pointer to the rend_intro_point_t corresponding to the
3644  * service-side introduction circuit <b>circ</b>. */
3645 static rend_intro_point_t *
3647 {
3648  const char *serviceid;
3649  rend_service_t *service = NULL;
3650 
3652  TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3653  tor_assert(circ->rend_data);
3654  serviceid = rend_data_get_address(circ->rend_data);
3655 
3656  SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3657  if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3658  service = s;
3659  break;
3660  });
3661 
3662  if (service == NULL) return NULL;
3663 
3664  SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3665  if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3666  return intro_point;
3667  });
3668 
3669  return NULL;
3670 }
3671 
3672 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3673  * associated with the rend_service_descriptor_t <b>renddesc</b> to
3674  * the responsible hidden service directories OR the hidden service
3675  * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3676  * <b>seconds_valid</b> are only passed for logging purposes.
3677  */
3678 void
3680  smartlist_t *descs, smartlist_t *hs_dirs,
3681  const char *service_id, int seconds_valid)
3682 {
3683  int i, j, failed_upload = 0;
3684  smartlist_t *responsible_dirs = smartlist_new();
3685  smartlist_t *successful_uploads = smartlist_new();
3686  routerstatus_t *hs_dir;
3687  for (i = 0; i < smartlist_len(descs); i++) {
3688  rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3689  /** If any HSDirs are specified, they should be used instead of
3690  * the responsible directories */
3691  if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3692  smartlist_add_all(responsible_dirs, hs_dirs);
3693  } else {
3694  /* Determine responsible dirs. */
3695  if (hid_serv_get_responsible_directories(responsible_dirs,
3696  desc->desc_id) < 0) {
3697  log_warn(LD_REND, "Could not determine the responsible hidden service "
3698  "directories to post descriptors to.");
3700  "UNKNOWN",
3701  "UNKNOWN", NULL);
3702  goto done;
3703  }
3704  }
3705  for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3706  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3707  char *hs_dir_ip;
3708  const node_t *node;
3709  rend_data_t *rend_data;
3710  hs_dir = smartlist_get(responsible_dirs, j);
3712  hs_dir->identity_digest))
3713  /* Don't upload descriptor if we succeeded in doing so last time. */
3714  continue;
3715  node = node_get_by_id(hs_dir->identity_digest);
3716  if (!node || !node_has_preferred_descriptor(node,0)) {
3717  log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3718  "hidden service directory %s; we don't have its "
3719  "router descriptor. Queuing for later upload.",
3720  safe_str_client(routerstatus_describe(hs_dir)));
3721  failed_upload = -1;
3722  continue;
3723  }
3724  /* Send publish request. */
3725 
3726  /* We need the service ID to identify which service did the upload
3727  * request. Lookup is made in rend_service_desc_has_uploaded(). */
3728  rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3729  REND_NO_AUTH);
3730  directory_request_t *req =
3735  desc->desc_str, strlen(desc->desc_str));
3736  directory_request_set_rend_query(req, rend_data);
3738  directory_request_free(req);
3739 
3740  rend_data_free(rend_data);
3741  base32_encode(desc_id_base32, sizeof(desc_id_base32),
3742  desc->desc_id, DIGEST_LEN);
3743  hs_dir_ip = tor_addr_to_str_dup(&hs_dir->ipv4_addr);
3744  if (hs_dir_ip) {
3745  log_info(LD_REND, "Launching upload for v2 descriptor for "
3746  "service '%s' with descriptor ID '%s' with validity "
3747  "of %d seconds to hidden service directory '%s' on "
3748  "%s:%d.",
3749  safe_str_client(service_id),
3750  safe_str_client(desc_id_base32),
3751  seconds_valid,
3752  hs_dir->nickname,
3753  hs_dir_ip,
3754  hs_dir->ipv4_orport);
3755  tor_free(hs_dir_ip);
3756  }
3757 
3759  hs_dir->identity_digest,
3760  desc_id_base32, NULL);
3761  /* Remember successful upload to this router for next time. */
3762  if (!smartlist_contains_digest(successful_uploads,
3763  hs_dir->identity_digest))
3764  smartlist_add(successful_uploads, hs_dir->identity_digest);
3765  }
3766  smartlist_clear(responsible_dirs);
3767  }
3768  if (!failed_upload) {
3769  if (renddesc->successful_uploads) {
3770  SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3771  smartlist_free(renddesc->successful_uploads);
3772  renddesc->successful_uploads = NULL;
3773  }
3774  renddesc->all_uploads_performed = 1;
3775  } else {
3776  /* Remember which routers worked this time, so that we don't upload the
3777  * descriptor to them again. */
3778  if (!renddesc->successful_uploads)
3779  renddesc->successful_uploads = smartlist_new();
3780  SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3781  if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3782  char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3783  smartlist_add(renddesc->successful_uploads, hsdir_id);
3784  }
3785  });
3786  }
3787  done:
3788  smartlist_free(responsible_dirs);
3789  smartlist_free(successful_uploads);
3790 }
3791 
3792 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3793  * and upload it/them to the responsible hidden service directories.
3794  */
3795 static void
3796 upload_service_descriptor(rend_service_t *service)
3797 {
3798  time_t now = time(NULL);
3799  int rendpostperiod;
3800  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3801  int uploaded = 0;
3802 
3803  rendpostperiod = get_options()->RendPostPeriod;
3804 
3806  if (c && smartlist_len(c->routerstatus_list) > 0) {
3807  int seconds_valid, i, j, num_descs;
3808  smartlist_t *descs = smartlist_new();
3809  smartlist_t *client_cookies = smartlist_new();
3810  /* Either upload a single descriptor (including replicas) or one
3811  * descriptor for each authorized client in case of authorization
3812  * type 'stealth'. */
3813  num_descs = service->auth_type == REND_STEALTH_AUTH ?
3814  smartlist_len(service->clients) : 1;
3815  for (j = 0; j < num_descs; j++) {
3816  crypto_pk_t *client_key = NULL;
3817  rend_authorized_client_t *client = NULL;
3818  smartlist_clear(client_cookies);
3819  switch (service->auth_type) {
3820  case REND_NO_AUTH:
3821  /* Do nothing here. */
3822  break;
3823  case REND_BASIC_AUTH:
3824  SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3825  cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3826  break;
3827  case REND_STEALTH_AUTH:
3828  client = smartlist_get(service->clients, j);
3829  client_key = client->client_key;
3830  smartlist_add(client_cookies, client->descriptor_cookie);
3831  break;
3832  }
3833  /* Encode the current descriptor. */
3834  seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3835  now, 0,
3836  service->auth_type,
3837  client_key,
3838  client_cookies);
3839  if (seconds_valid < 0) {
3840  log_warn(LD_BUG, "Internal error: couldn't encode service "
3841  "descriptor; not uploading.");
3842  smartlist_free(descs);
3843  smartlist_free(client_cookies);
3844  return;
3845  }
3846  rend_get_service_id(service->desc->pk, serviceid);
3847  if (get_options()->PublishHidServDescriptors) {
3848  /* Post the current descriptors to the hidden service directories. */
3849  /* This log message is used by Chutney as part of its bootstrap
3850  * detection mechanism. Please don't change without first checking
3851  * Chutney. */
3852  log_info(LD_REND, "Launching upload for hidden service %s",
3853  serviceid);
3854  directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3855  seconds_valid);
3856  }
3857  /* Free memory for descriptors. */
3858  for (i = 0; i < smartlist_len(descs); i++)
3859  rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3860  smartlist_clear(descs);
3861  /* Update next upload time. */
3862  if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3863  > rendpostperiod)
3864  service->next_upload_time = now + rendpostperiod;
3865  else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3866  service->next_upload_time = now + seconds_valid + 1;
3867  else
3868  service->next_upload_time = now + seconds_valid -
3870  /* Post also the next descriptors, if necessary. */
3871  if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3872  seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3873  now, 1,
3874  service->auth_type,
3875  client_key,
3876  client_cookies);
3877  if (seconds_valid < 0) {
3878  log_warn(LD_BUG, "Internal error: couldn't encode service "
3879  "descriptor; not uploading.");
3880  smartlist_free(descs);
3881  smartlist_free(client_cookies);
3882  return;
3883  }
3884  if (get_options()->PublishHidServDescriptors) {
3885  directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3886  seconds_valid);
3887  }
3888  /* Free memory for descriptors. */
3889  for (i = 0; i < smartlist_len(descs); i++)
3890  rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3891  smartlist_clear(descs);
3892  }
3893  }
3894  smartlist_free(descs);
3895  smartlist_free(client_cookies);
3896  uploaded = 1;
3897  if (get_options()->PublishHidServDescriptors) {
3898  log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3899  } else {
3900  log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3901  }
3902  }
3903 
3904  /* If not uploaded, try again in one minute. */
3905  if (!uploaded)
3906  service->next_upload_time = now + 60;
3907 
3908  /* Unmark dirty flag of this service. */
3909  service->desc_is_dirty = 0;
3910 }
3911 
3912 /** Return the number of INTRODUCE2 cells this hidden service has received
3913  * from this intro point. */
3914 static int
3916 {
3917  return intro->accepted_introduce2_count;
3918 }
3919 
3920 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3921  * should stop publishing it in new descriptors and eventually close
3922  * it). */
3923 static int
3925  time_t now)
3926 {
3927  tor_assert(intro != NULL);
3928 
3929  if (intro->time_published == -1) {
3930  /* Don't expire an intro point if we haven't even published it yet. */
3931  return 0;
3932  }
3933 
3934  if (intro_point_accepted_intro_count(intro) >=
3935  intro->max_introductions) {
3936  /* This intro point has been used too many times. Expire it now. */
3937  return 1;
3938  }
3939 
3940  if (intro->time_to_expire == -1) {
3941  /* This intro point has been published, but we haven't picked an
3942  * expiration time for it. Pick one now. */
3943  int intro_point_lifetime_seconds =
3946 
3947  /* Start the expiration timer now, rather than when the intro
3948  * point was first published. There shouldn't be much of a time
3949  * difference. */
3950  intro->time_to_expire = now + intro_point_lifetime_seconds;
3951 
3952  return 0;
3953  }
3954 
3955  /* This intro point has a time to expire set already. Use it. */
3956  return (now >= intro->time_to_expire);
3957 }
3958 
3959 /** Iterate over intro points in the given service and remove the invalid
3960  * ones. For an intro point object to be considered invalid, the circuit
3961  * _and_ node need to have disappeared.
3962  *
3963  * If the intro point should expire, it's placed into the expiring_nodes
3964  * list of the service and removed from the active intro nodes list.
3965  *
3966  * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3967  *
3968  * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3969  * circuit disappeared but the node is still in the consensus. */
3970 static void
3971 remove_invalid_intro_points(rend_service_t *service,
3972  smartlist_t *exclude_nodes,
3973  smartlist_t *retry_nodes, time_t now)
3974 {
3975  tor_assert(service);
3976 
3977  /* Remove any expired nodes that doesn't have a circuit. */
3978  SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3979  intro) {
3980  origin_circuit_t *intro_circ =
3981  find_intro_circuit(intro, service->pk_digest);
3982  if (intro_circ) {
3983  continue;
3984  }
3985  /* No more circuit, cleanup the into point object. */
3986  SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3987  rend_intro_point_free(intro);
3988  } SMARTLIST_FOREACH_END(intro);
3989 
3990  SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3991  intro) {
3992  /* Find the introduction point node object. */
3993  const node_t *node =
3994  node_get_by_id(intro->extend_info->identity_digest);
3995  /* Find the intro circuit, this might be NULL. */
3996  origin_circuit_t *intro_circ =
3997  find_intro_circuit(intro, service->pk_digest);
3998 
3999  /* Add the valid node to the exclusion list so we don't try to establish
4000  * an introduction point to it again. */
4001  if (node && exclude_nodes) {
4002  smartlist_add(exclude_nodes, (void*) node);
4003  }
4004 
4005  /* First, make sure we still have a valid circuit for this intro point.
4006  * If we dont, we'll give up on it and make a new one. */
4007  if (intro_circ == NULL) {
4008  log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
4009  " (circuit disappeared).",
4010  safe_str_client(extend_info_describe(intro->extend_info)),
4011  safe_str_client(service->service_id));
4012  /* We've lost the circuit for this intro point, flag it so it can be
4013  * accounted for when considiring uploading a descriptor. */
4014  intro->circuit_established = 0;
4015 
4016  /* Node is gone or we've reached our maximum circuit creation retry
4017  * count, clean up everything, we'll find a new one. */
4018  if (node == NULL ||
4019  intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
4020  rend_intro_point_free(intro);
4021  SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4022  /* We've just killed the intro point, nothing left to do. */
4023  continue;
4024  }
4025 
4026  /* The intro point is still alive so let's try to use it again because
4027  * we have a published descriptor containing it. Keep the intro point
4028  * in the intro_nodes list because it's still valid, we are rebuilding
4029  * a circuit to it. */
4030  if (retry_nodes) {
4031  smartlist_add(retry_nodes, intro);
4032  }
4033  }
4034  /* else, the circuit is valid so in both cases, node being alive or not,
4035  * we leave the circuit and intro point object as is. Closing the
4036  * circuit here would leak new consensus timing and freeing the intro
4037  * point object would make the intro circuit unusable. */
4038 
4039  /* Now, check if intro point should expire. If it does, queue it so
4040  * it can be cleaned up once it has been replaced properly. */
4041  if (intro_point_should_expire_now(intro, now)) {
4042  log_info(LD_REND, "Expiring %s as intro point for %s.",
4043  safe_str_client(extend_info_describe(intro->extend_info)),
4044  safe_str_client(service->service_id));
4045  /* We might have put it in the retry list if so, undo. */
4046  if (retry_nodes) {
4047  smartlist_remove(retry_nodes, intro);
4048  }
4049  smartlist_add(service->expiring_nodes, intro);
4050  SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4051  /* Intro point is expired, we need a new one thus don't consider it
4052  * anymore has a valid established intro point. */
4053  intro->circuit_established = 0;
4054  }
4055  } SMARTLIST_FOREACH_END(intro);
4056 }
4057 
4058 /** A new descriptor has been successfully uploaded for the given
4059  * <b>rend_data</b>. Remove and free the expiring nodes from the associated
4060  * service. */
4061 void
4063 {
4064  rend_service_t *service;
4065  const char *onion_address;
4066 
4067  tor_assert(rend_data);
4068 
4069  onion_address = rend_data_get_address(rend_data);
4070 
4071  service = rend_service_get_by_service_id(onion_address);
4072  if (service == NULL) {
4073  return;
4074  }
4075 
4076  SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
4077  intro) {
4078  origin_circuit_t *intro_circ =
4079  find_intro_circuit(intro, service->pk_digest);
4080  if (intro_circ != NULL) {
4081  circuit_mark_for_close(TO_CIRCUIT(intro_circ),
4082  END_CIRC_REASON_FINISHED);
4083  }
4084  SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
4085  rend_intro_point_free(intro);
4086  } SMARTLIST_FOREACH_END(intro);
4087 }
4088 
4089 /** Don't try to build more than this many circuits before giving up
4090  * for a while. Dynamically calculated based on the configured number of
4091  * introduction points for the service, n_intro_points_wanted. */
4092 static int
4093 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
4094 {
4095  /* Allow all but one of the initial connections to fail and be
4096  * retried. (If all fail, we *want* to wait, because something is broken.) */
4097  tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
4098 
4099  /* For the normal use case, 3 intro points plus 2 extra for performance and
4100  * allow that twice because once every 24h or so, we can do it twice for two
4101  * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
4102  * 12 allowed attempts for one period. */
4103  return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
4104 }
4105 
4106 /** For every service, check how many intro points it currently has, and:
4107  * - Invalidate introdution points based on specific criteria, see
4108  * remove_invalid_intro_points comments.
4109  * - Pick new intro points as necessary.
4110  * - Launch circuits to any new intro points.
4111  *
4112  * This is called once a second by the main loop.
4113  */
4114 void
4116 {
4117  int i;
4118  const or_options_t *options = get_options();
4119  /* Are we in single onion mode? */
4120  const int allow_direct = rend_service_allow_non_anonymous_connection(
4121  get_options());
4122  /* List of nodes we need to _exclude_ when choosing a new node to
4123  * establish an intro point to. */
4124  smartlist_t *exclude_nodes;
4125  /* List of nodes we need to retry to build a circuit on them because the
4126  * node is valid but circuit died. */
4127  smartlist_t *retry_nodes;
4128 
4129  if (!have_completed_a_circuit())
4130  return;
4131 
4132  exclude_nodes = smartlist_new();
4133  retry_nodes = smartlist_new();
4134 
4135  SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
4136  int r;
4137  /* Number of intro points we want to open and add to the intro nodes
4138  * list of the service. */
4139  unsigned int n_intro_points_to_open;
4140  /* Have an unsigned len so we can use it to compare values else gcc is
4141  * not happy with unmatching signed comparaison. */
4142  unsigned int intro_nodes_len;
4143  /* Different service are allowed to have the same introduction point as
4144  * long as they are on different circuit thus why we clear this list. */
4145  smartlist_clear(exclude_nodes);
4146  smartlist_clear(retry_nodes);
4147 
4148  /* Cleanup the invalid intro points and save the node objects, if any,
4149  * in the exclude_nodes and retry_nodes lists. */
4150  remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
4151 
4152  /* This retry period is important here so we don't stress circuit
4153  * creation. */
4154 
4155  if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
4156  /* One period has elapsed:
4157  * - if we stopped, we can try building circuits again,
4158  * - if we haven't, we reset the circuit creation counts. */
4159  rend_log_intro_limit(service, LOG_INFO);
4160  service->intro_period_started = now;
4161  service->n_intro_circuits_launched = 0;
4162  } else if (service->n_intro_circuits_launched >=
4164  service->n_intro_points_wanted)) {
4165  /* We have failed too many times in this period; wait for the next
4166  * one before we try to initiate any more connections. */
4167  rend_log_intro_limit(service, LOG_WARN);
4168  continue;
4169  }
4170 
4171  /* Let's try to rebuild circuit on the nodes we want to retry on. */
4172  SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
4173  r = rend_service_launch_establish_intro(service, intro);
4174  if (r < 0) {
4175  log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4176  safe_str_client(extend_info_describe(intro->extend_info)),
4177  safe_str_client(service->service_id));
4178  /* Unable to launch a circuit to that intro point, remove it from
4179  * the valid list so we can create a new one. */
4180  smartlist_remove(service->intro_nodes, intro);
4181  rend_intro_point_free(intro);
4182  continue;
4183  }
4184  intro->circuit_retries++;
4185  } SMARTLIST_FOREACH_END(intro);
4186 
4187  /* Avoid mismatched signed comparaison below. */
4188  intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
4189 
4190  /* Quiescent state, we have more or the equal amount of wanted node for
4191  * this service. Proceed to the next service. We can have more nodes
4192  * because we launch extra preemptive circuits if our intro nodes list was
4193  * originally empty for performance reasons. */
4194  if (intro_nodes_len >= service->n_intro_points_wanted) {
4195  continue;
4196  }
4197 
4198  /* Number of intro points we want to open which is the wanted amount minus
4199  * the current amount of valid nodes. We know that this won't underflow
4200  * because of the check above. */
4201  n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
4202  if (intro_nodes_len == 0) {
4203  /* We want to end up with n_intro_points_wanted intro points, but if
4204  * we have no intro points at all (chances are they all cycled or we
4205  * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4206  * and use the first n_intro_points_wanted that complete. See proposal
4207  * #155, section 4 for the rationale of this which is purely for
4208  * performance.
4209  *
4210  * The ones after the first n_intro_points_to_open will be converted
4211  * to 'general' internal circuits in rend_service_intro_has_opened(),
4212  * and then we'll drop them from the list of intro points. */
4213  n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4214  }
4215 
4216  for (i = 0; i < (int) n_intro_points_to_open; i++) {
4217  const node_t *node;
4218  rend_intro_point_t *intro;
4219  router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4220  router_crn_flags_t direct_flags = flags;
4221  direct_flags |= CRN_PREF_ADDR;
4222  direct_flags |= CRN_DIRECT_CONN;
4223 
4224  node = router_choose_random_node(exclude_nodes,
4225  options->ExcludeNodes,
4226  allow_direct ? direct_flags : flags);
4227  /* If we are in single onion mode, retry node selection for a 3-hop
4228  * path */
4229  if (allow_direct && !node) {
4230  log_info(LD_REND,
4231  "Unable to find an intro point that we can connect to "
4232  "directly for %s, falling back to a 3-hop path.",
4233  safe_str_client(service->service_id));
4234  node = router_choose_random_node(exclude_nodes,
4235  options->ExcludeNodes, flags);
4236  }
4237 
4238  if (!node) {
4239  log_warn(LD_REND,
4240  "We only have %d introduction points established for %s; "
4241  "wanted %u.",
4242  smartlist_len(service->intro_nodes),
4243  safe_str_client(service->service_id),
4244  n_intro_points_to_open);
4245  break;
4246  }
4247  /* Add the chosen node to the exclusion list in order to avoid picking
4248  * it again in the next iteration. */
4249  smartlist_add(exclude_nodes, (void*)node);
4250  intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4251  /* extend_info is for clients, so we want the multi-hop primary ORPort,
4252  * even if we are a single onion service and intend to connect to it
4253  * directly ourselves. */
4254  intro->extend_info = extend_info_from_node(node, 0);
4255  if (BUG(intro->extend_info == NULL)) {
4256  tor_free(intro);
4257  break;
4258  }
4259  intro->intro_key = crypto_pk_new();
4260  const int fail = crypto_pk_generate_key(intro->intro_key);
4261  tor_assert(!fail);
4262  intro->time_published = -1;
4263  intro->time_to_expire = -1;
4264  intro->max_introductions =
4266  INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4267  smartlist_add(service->intro_nodes, intro);
4268  log_info(LD_REND, "Picked router %s as an intro point for %s.",
4269  safe_str_client(node_describe(node)),
4270  safe_str_client(service->service_id));
4271  /* Establish new introduction circuit to our chosen intro point. */
4272  r = rend_service_launch_establish_intro(service, intro);
4273  if (r < 0) {
4274  log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4275  safe_str_client(extend_info_describe(intro->extend_info)),
4276  safe_str_client(service->service_id));
4277  /* This funcion will be called again by the main loop so this intro
4278  * point without a intro circuit will be retried on or removed after
4279  * a maximum number of attempts. */
4280  }
4281  }
4282  } SMARTLIST_FOREACH_END(service);
4283  smartlist_free(exclude_nodes);
4284  smartlist_free(retry_nodes);
4285 }
4286 
4287 #define MIN_REND_INITIAL_POST_DELAY (30)
4288 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4289 
4290 /** Regenerate and upload rendezvous service descriptors for all
4291  * services, if necessary. If the descriptor has been dirty enough
4292  * for long enough, definitely upload; else only upload when the
4293  * periodic timeout has expired.
4294  *
4295  * For the first upload, pick a random time between now and two periods
4296  * from now, and pick it independently for each service.
4297  */
4298 void
4300 {
4301  int i;
4302  rend_service_t *service;
4303  const or_options_t *options = get_options();
4304  int rendpostperiod = options->RendPostPeriod;
4305  int rendinitialpostdelay = (options->TestingTorNetwork ?
4306  MIN_REND_INITIAL_POST_DELAY_TESTING :
4307  MIN_REND_INITIAL_POST_DELAY);
4308 
4309  for (i=0; i < smartlist_len(rend_service_list); ++i) {
4310  service = smartlist_get(rend_service_list, i);
4311  if (!service->next_upload_time) { /* never been uploaded yet */
4312  /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4313  * the descriptor is stable before being published. See comment below. */
4314  service->next_upload_time =
4315  now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4316  /* Single Onion Services prioritise availability over hiding their
4317  * startup time, as their IP address is publicly discoverable anyway.
4318  */
4319  if (rend_service_reveal_startup_time(options)) {
4320  service->next_upload_time = now + rendinitialpostdelay;
4321  }
4322  }
4323  /* Does every introduction points have been established? */
4324  unsigned int intro_points_ready =
4325  count_established_intro_points(service) >=
4326  service->n_intro_points_wanted;
4327  if (intro_points_ready &&
4328  (service->next_upload_time < now ||
4329  (service->desc_is_dirty &&
4330  service->desc_is_dirty < now-rendinitialpostdelay))) {
4331  /* if it's time, or if the directory servers have a wrong service
4332  * descriptor and ours has been stable for rendinitialpostdelay seconds,
4333  * upload a new one of each format. */
4335  upload_service_descriptor(service);
4336  }
4337  }
4338 }
4339 
4340 /** True if the list of available router descriptors might have changed so
4341  * that we should have a look whether we can republish previously failed
4342  * rendezvous service descriptors. */
4344 
4345 /** Called when our internal view of the directory has changed, so that we
4346  * might have router descriptors of hidden service directories available that
4347  * we did not have before. */
4348 void
4350 {
4352 }
4353 
4354 /** Consider republication of v2 rendezvous service descriptors that failed
4355  * previously, but without regenerating descriptor contents.
4356  */
4357 void
4359 {
4360  int i;
4361  rend_service_t *service;
4362 
4364  return;
4366 
4367  if (!get_options()->PublishHidServDescriptors)
4368  return;
4369 
4370  for (i=0; i < smartlist_len(rend_service_list); ++i) {
4371  service = smartlist_get(rend_service_list, i);
4372  if (service->desc && !service->desc->all_uploads_performed) {
4373  /* If we failed in uploading a descriptor last time, try again *without*
4374  * updating the descriptor's contents. */
4375  upload_service_descriptor(service);
4376  }
4377  }
4378 }
4379 
4380 /** Log the status of introduction points for all rendezvous services
4381  * at log severity <b>severity</b>.
4382  */
4383 void
4385 {
4386  rend_service_t *service;
4387  rend_intro_point_t *intro;
4388  const char *safe_name;
4389  origin_circuit_t *circ;
4390 
4391  for (int i = 0; i < smartlist_len(rend_service_list); ++i) {
4392  service = smartlist_get(rend_service_list, i);
4393  tor_log(severity, LD_GENERAL, "Service configured in %s:",
4394  rend_service_escaped_dir(service));
4395  for (int j = 0; j < smartlist_len(service->intro_nodes); ++j) {
4396  intro = smartlist_get(service->intro_nodes, j);
4397  safe_name = safe_str_client(intro->extend_info->nickname);
4398 
4399  circ = find_intro_circuit(intro, service->pk_digest);
4400  if (!circ) {
4401  tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4402  j, safe_name);
4403  continue;
4404  }
4405  tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4406  j, safe_name, circuit_state_to_string(circ->base_.state));
4407  }
4408  }
4409 }
4410 
4411 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4412  * <b>circ</b>, and look up the port and address based on conn->port.
4413  * Assign the actual conn->addr and conn->port. Return -2 on failure
4414  * for which the circuit should be closed, -1 on other failure,
4415  * or 0 for success.
4416  */
4417 int
4419  origin_circuit_t *circ)
4420 {
4421  rend_service_t *service;
4422  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4423  const char *rend_pk_digest;
4424 
4426  tor_assert(circ->rend_data);
4427  log_debug(LD_REND,"beginning to hunt for addr/port");
4428  rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
4430  rend_pk_digest, REND_SERVICE_ID_LEN);
4431  service = rend_service_get_by_pk_digest(rend_pk_digest);
4432  if (!service) {
4433  log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4434  "rendezvous circuit %u; closing.",
4435  serviceid, (unsigned)circ->base_.n_circ_id);
4436  return -2;
4437  }
4438  if (service->max_streams_per_circuit > 0) {
4439  /* Enforce the streams-per-circuit limit, and refuse to provide a
4440  * mapping if this circuit will exceed the limit. */
4441 #define MAX_STREAM_WARN_INTERVAL 600
4442  static struct ratelim_t stream_ratelim =
4443  RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4444  if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4445  log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4446  "Maximum streams per circuit limit reached on rendezvous "
4447  "circuit %u; %s. Circuit has %d out of %d streams.",
4448  (unsigned)circ->base_.n_circ_id,
4449  service->max_streams_close_circuit ?
4450  "closing circuit" :
4451  "ignoring open stream request",
4452  circ->rend_data->nr_streams,
4453  service->max_streams_per_circuit);
4454  return service->max_streams_close_circuit ? -2 : -1;
4455  }
4456  }
4457 
4458  if (hs_set_conn_addr_port(service->ports, conn) == 0) {
4459  /* Successfully set the port to the connection. We are done. */
4460  return 0;
4461  }
4462 
4463  log_info(LD_REND,
4464  "No virtual port mapping exists for port %d on service %s",
4465  conn->base_.port, serviceid);
4466 
4467  if (service->allow_unknown_ports)
4468  return -1;
4469  else
4470  return -2;
4471 }
4472 
4473 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4474  */
4475 static int
4476 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4477 {
4478  /* !! is used to make these options boolean */
4479  return (!! options->HiddenServiceSingleHopMode ==
4480  !! options->HiddenServiceNonAnonymousMode);
4481 }
4482 
4483 /* Do the options allow onion services to make direct (non-anonymous)
4484  * connections to introduction or rendezvous points?
4485  * Must only be called after options_validate_single_onion() has successfully
4486  * checked onion service option consistency.
4487  * Returns true if tor is in HiddenServiceSingleHopMode. */
4488 int
4489 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4490 {
4491  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4492  return options->HiddenServiceSingleHopMode ? 1 : 0;
4493 }
4494 
4495 /* Do the options allow us to reveal the exact startup time of the onion
4496  * service?
4497  * Single Onion Services prioritise availability over hiding their
4498  * startup time, as their IP address is publicly discoverable anyway.
4499  * Must only be called after options_validate_single_onion() has successfully
4500  * checked onion service option consistency.
4501  * Returns true if tor is in non-anonymous hidden service mode. */
4502 int
4503 rend_service_reveal_startup_time(const or_options_t *options)
4504 {
4505  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4506  return rend_service_non_anonymous_mode_enabled(options);
4507 }
4508 
4509 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4510  * config option?
4511  * Must only be called after options_validate_single_onion() has successfully
4512  * checked onion service option consistency.
4513  */
4514 int
4515 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4516 {
4517  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4518  return options->HiddenServiceNonAnonymousMode ? 1 : 0;
4519 }
4520 
4521 #ifdef TOR_UNIT_TESTS
4522 
4523 STATIC void
4524 set_rend_service_list(smartlist_t *new_list)
4525 {
4526  rend_service_list = new_list;
4527 }
4528 
4529 STATIC void
4530 set_rend_rend_service_staging_list(smartlist_t *new_list)
4531 {
4532  rend_service_staging_list = new_list;
4533 }
4534 
4535 #endif /* defined(TOR_UNIT_TESTS) */
log_fn
#define log_fn(severity, domain, args,...)
Definition: log.h:287
finish_writing_to_file
int finish_writing_to_file(open_file_t *file_data)
Definition: files.c:465
crypt_path_reference_t
Definition: crypt_path_reference_st.h:19
crypto_rand_int_range
int crypto_rand_int_range(unsigned int min, unsigned int max)
Definition: crypto_rand_numeric.c:71
file_status_t
file_status_t
Definition: files.h:55
tor_free
#define tor_free(p)
Definition: malloc.h:52
rend_intro_point_t::intro_key
struct crypto_pk_t * intro_key
Definition: rend_intro_point_st.h:24
rend_service_desc_has_uploaded
void rend_service_desc_has_uploaded(const rend_data_t *rend_data)
Definition: rendservice.c:4062
rend_service_load_keys
static int rend_service_load_keys(struct rend_service_t *s)
Definition: rendservice.c:1532
rend_service_staging_list
static smartlist_t * rend_service_staging_list
Definition: rendservice.c:134
LOG_DEBUG
#define LOG_DEBUG
Definition: log.h:42
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
rend_service_derive_key_digests
static int rend_service_derive_key_digests(struct rend_service_t *s)
Definition: rendservice.c:1444
rend_service_decrypt_intro
int rend_service_decrypt_intro(rend_intro_cell_t *intro, crypto_pk_t *key, char **err_msg_out)
Definition: rendservice.c:2760
rend_service_port_config_t::is_unix_addr
unsigned int is_unix_addr
Definition: hs_common.h:157
CIRCUIT_STATE_OPEN
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
rend_encoded_v2_service_descriptor_t::desc_str
char * desc_str
Definition: rend_encoded_v2_service_descriptor_st.h:18
rend_service_del_ephemeral
int rend_service_del_ephemeral(const char *service_id)
Definition: rendservice.c:974
circuit_t::purpose
uint8_t purpose
Definition: circuit_st.h:111
find_intro_circuit
static origin_circuit_t * find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
Definition: rendservice.c:3598
circuit_t::timestamp_dirty
time_t timestamp_dirty
Definition: circuit_st.h:187
crypt_path_reference_st.h
reference-counting structure for crypt_path_t
INTRO_CIRC_RETRY_PERIOD
#define INTRO_CIRC_RETRY_PERIOD
Definition: hs_common.h:41
rend_service_begin_parse_intro
rend_intro_cell_t * rend_service_begin_parse_intro(const uint8_t *request, size_t request_len, uint8_t type, char **err_msg_out)
Definition: rendservice.c:2382
routerstatus_describe
const char * routerstatus_describe(const routerstatus_t *rs)
Definition: describe.c:182
memwipe
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
count_intro_point_circuits
static unsigned int count_intro_point_circuits(const rend_service_t *service)
Definition: rendservice.c:3201
rend_log_intro_limit
static void rend_log_intro_limit(const rend_service_t *service, int min_severity)
Definition: rendservice.c:1031
tor_addr_t
Definition: address.h:69
CIRCUIT_PURPOSE_C_GENERAL
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:72
DIR_PURPOSE_UPLOAD_RENDDESC_V2
#define DIR_PURPOSE_UPLOAD_RENDDESC_V2
Definition: directory.h:66
circuit_get_next_intro_circ
origin_circuit_t * circuit_get_next_intro_circ(const origin_circuit_t *start, bool want_client_circ)
Definition: circuitlist.c:1734
smartlist_add_strdup
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
Definition: smartlist_core.c:137
INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS
#define INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS
Definition: or.h:1082
directory_initiate_request
void directory_initiate_request(directory_request_t *request)
Definition: dirclient.c:1235
approx_time
time_t approx_time(void)
Definition: approx_time.c:32
LOG_NOTICE
#define LOG_NOTICE
Definition: log.h:50
extend_info_t::onion_key
crypto_pk_t * onion_key
Definition: extend_info_st.h:38
circuit_get_global_list
smartlist_t * circuit_get_global_list(void)
Definition: circuitlist.c:696
rend_service_parse_intro_plaintext
int rend_service_parse_intro_plaintext(rend_intro_cell_t *intro, char **err_msg_out)
Definition: rendservice.c:2883
rend_service_free_intro_
void rend_service_free_intro_(rend_intro_cell_t *request)
Definition: rendservice.c:2313
crypt_path_t::package_window
int package_window
Definition: crypt_path_st.h:78
extend_info_add_orport
int extend_info_add_orport(extend_info_t *ei, const tor_addr_t *addr, uint16_t port)
Definition: extendinfo.c:67
rend_valid_client_name
int rend_valid_client_name(const char *client_name)
Definition: rendcommon.c:757
rend_intro_point_t::circuit_retries
unsigned int circuit_retries
Definition: rend_intro_point_st.h:74
rend_service_load_all_keys
int rend_service_load_all_keys(const smartlist_t *service_list)
Definition: rendservice.c:1389
or_options_t::User
char * User
Definition: or_options_st.h:142
hs_set_conn_addr_port
int hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
Definition: hs_common.c:857
crypt_path_t::rend_circ_nonce
char rend_circ_nonce[DIGEST_LEN]
Definition: crypt_path_st.h:58
routerset_contains_extendinfo
int routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
Definition: routerset.c:307
rend_service_descriptor_st.h
Parsed v2 HS descriptor structure.
CIRCLAUNCH_NEED_CAPACITY
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
rendparse.h
Header file for rendparse.c.
find_expiring_intro_point
static rend_intro_point_t * find_expiring_intro_point(struct rend_service_t *service, origin_circuit_t *circ)
Definition: rendservice.c:3628
crypto_pk_new
crypto_pk_t * crypto_pk_new(void)
Definition: crypto_rsa_nss.c:165
LD_BUG
#define LD_BUG
Definition: log.h:86
cpath_build_state_st.h
Circuit-build-stse structure.
rend_service_port_config_t
Definition: hs_common.h:153
circuituse.h
Header file for circuituse.c.
rend_service_poison_new_single_onion_dir
STATIC int rend_service_poison_new_single_onion_dir(const rend_service_t *s, const or_options_t *options)
Definition: rendservice.c:1328
MAX_INTRO_POINT_CIRCUIT_RETRIES
#define MAX_INTRO_POINT_CIRCUIT_RETRIES
Definition: or.h:1103
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
rend_service_port_config_t::virtual_port
uint16_t virtual_port
Definition: hs_common.h:155
INTRO_POINT_LIFETIME_MAX_SECONDS
#define INTRO_POINT_LIFETIME_MAX_SECONDS
Definition: or.h:1098
count_established_intro_points
static unsigned int count_established_intro_points(const rend_service_t *service)
Definition: rendservice.c:3186
base16_encode
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
RELAY_PAYLOAD_SIZE
#define RELAY_PAYLOAD_SIZE
Definition: or.h:606
or_options_t::RendPostPeriod
int RendPostPeriod
Definition: or_options_st.h:369
crypt_path_t::state
uint8_t state
Definition: crypt_path_st.h:68
rend_auth_type_t
rend_auth_type_t
Definition: or.h:403
loadkey.h
Header file for loadkey.c.
crypto_pk_dup_key
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
Definition: crypto_rsa_nss.c:351
describe.h
Header file for describe.c.
find_rp_for_intro
static extend_info_t * find_rp_for_intro(const rend_intro_cell_t *intro, char **err_msg_out)
Definition: rendservice.c:2223
rend_service_relaunch_rendezvous
void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
Definition: rendservice.c:3024
crypto_pk_asn1_encode
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
Definition: crypto_rsa_nss.c:595
smartlist_add_all
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
Definition: smartlist_core.c:125
rend_authorized_client_free_void
static void rend_authorized_client_free_void(void *authorized_client)
Definition: rendservice.c:226
node_get_by_nickname
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1004
cpath_build_state_t::is_internal
unsigned int is_internal
Definition: cpath_build_state_st.h:26
REND_SERVICE_ID_LEN_BASE32
#define REND_SERVICE_ID_LEN_BASE32
Definition: or.h:332
pathbias_count_use_attempt
void pathbias_count_use_attempt(origin_circuit_t *circ)
Definition: circpathbias.c:604
rend_service_list
static smartlist_t * rend_service_list
Definition: rendservice.c:130
node_get_by_id
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:223
rend_service_check_private_dir
static int rend_service_check_private_dir(const or_options_t *options, const rend_service_t *s, int create)
Definition: rendservice.c:1468
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
rend_service_launch_establish_intro
static int rend_service_launch_establish_intro(rend_service_t *service, rend_intro_point_t *intro)
Definition: rendservice.c:3092
tor_open_cloexec
int tor_open_cloexec(const char *path, int flags, unsigned mode)
Definition: files.c:54
replaycache_add_test_and_elapsed
int replaycache_add_test_and_elapsed(replaycache_t *r, const void *data, size_t len, time_t *elapsed)
Definition: replaycache.c:195
hs_service_map_has_changed
void hs_service_map_has_changed(void)
Definition: hs_service.c:3580
rend_encoded_v2_service_descriptor_st.h
Encoded v2 HS descriptor structure.
replaycache_new
replaycache_t * replaycache_new(time_t horizon, time_t interval)
Definition: replaycache.c:47
circuit_get_next_by_pk_and_purpose
origin_circuit_t * circuit_get_next_by_pk_and_purpose(origin_circuit_t *start, const uint8_t *digest, uint8_t purpose)
Definition: circuitlist.c:1820
crypto_pk_eq_keys
int crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
Definition: crypto_rsa.c:71
rend_service_parse_intro_for_v3
static ssize_t rend_service_parse_intro_for_v3(rend_intro_cell_t *intro, const uint8_t *buf, size_t plaintext_len, char **err_msg_out)
Definition: rendservice.c:2622
REND_CLIENTNAME_MAX_LEN
#define REND_CLIENTNAME_MAX_LEN
Definition: or.h:396
routerstatus_t
Definition: routerstatus_st.h:19
rend_intro_point_t::circuit_established
unsigned int circuit_established
Definition: rend_intro_point_st.h:78
rend_auth_encode_cookie
char * rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
Definition: rendcommon.c:894
smartlist_contains_digest
int smartlist_contains_digest(const smartlist_t *sl, const char *element)
Definition: smartlist.c:223
directory_request_set_rend_query
void directory_request_set_rend_query(directory_request_t *req, const rend_data_t *query)
Definition: dirclient.c:1096
rend_service_get_by_service_id
static struct rend_service_t * rend_service_get_by_service_id(const char *id)
Definition: rendservice.c:1787
is_legal_nickname
int is_legal_nickname(const char *s)
Definition: nickname.c:19
routerstatus_t::nickname
char nickname[MAX_NICKNAME_LEN+1]
Definition: routerstatus_st.h:25
rend_add_service
static int rend_add_service(smartlist_t *service_list, rend_service_t *service)
Definition: rendservice.c:356
rend_service_descriptor_t
Definition: rend_service_descriptor_st.h:19
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
rend_data_t::nr_streams
int nr_streams
Definition: or.h:431
crypto_pk_asn1_decode
crypto_pk_t * crypto_pk_asn1_decode(const char *str, size_t len)
Definition: crypto_rsa_nss.c:619
base64_encode
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
crypt_path.h
Header file for crypt_path.c.
crypto_digest
int crypto_digest(char *digest, const char *m, size_t len)
Definition: crypto_digest_nss.c:110
hs_service_config_t::dir_group_readable
unsigned int dir_group_readable
Definition: hs_service.h:243
tor_snprintf
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
rend_intro_point_st.h
v2 hidden service introduction point structure.
tor_parse_long
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
crypt_path_t
Definition: crypt_path_st.h:47
connection_t::port
uint16_t port
Definition: connection_st.h:146
crypto_pk_private_sign_digest
int crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
Definition: crypto_rsa.c:339
open_file_t
Definition: files.c:289
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
rend_consider_descriptor_republication
void rend_consider_descriptor_republication(void)
Definition: rendservice.c:4358
rend_data_dup
rend_data_t * rend_data_dup(const rend_data_t *data)
Definition: hs_common.c:387
crypto_rand_int
int crypto_rand_int(unsigned int max)
Definition: crypto_rand_numeric.c:52
extend_info_describe
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:202
networkstatus.h
Header file for networkstatus.c.
remove_invalid_intro_points
static void remove_invalid_intro_points(rend_service_t *service, smartlist_t *exclude_nodes, smartlist_t *retry_nodes, time_t now)
Definition: rendservice.c:3971
origin_circuit_t::hs_circ_has_timed_out
unsigned int hs_circ_has_timed_out
Definition: origin_circuit_st.h:207
replaycache_free
#define replaycache_free(r)
Definition: replaycache.h:42
tor_memeq
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
base32_encode
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:60
escaped_safe_str_client
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1119
crypto_util.h
Common functions for cryptographic routines.
hs_service_add_ephemeral_status_t
hs_service_add_ephemeral_status_t
Definition: hs_common.h:142
rend_intro_point_t::accepted_intro_rsa_parts
struct replaycache_t * accepted_intro_rsa_parts
Definition: rend_intro_point_st.h:46
rend_service_intro_established
int rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len)
Definition: rendservice.c:3408
REND_DESC_ID_V2_LEN_BASE32
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:355
hs_service_config_t::directory_path
char * directory_path
Definition: hs_service.h:211
LD_CIRC
#define LD_CIRC
Definition: log.h:82
cpath_build_state_t::failure_count
int failure_count
Definition: cpath_build_state_st.h:39
rend_intro_point_t::extend_info
extend_info_t * extend_info
Definition: rend_intro_point_st.h:22
extend_info_new
extend_info_t * extend_info_new(const char *nickname, const char *rsa_id_digest, const ed25519_public_key_t *ed_id, crypto_pk_t *onion_key, const curve25519_public_key_t *ntor_key, const tor_addr_t *addr, uint16_t port)
Definition: extendinfo.c:33
circuitlist.h
Header file for circuitlist.c.
mainloop.h
Header file for mainloop.c.
crypt_path_st.h
Path structures for origin circuits.
circuit_log_path
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
Definition: circuitbuild.c:352
DIGEST_LEN
#define DIGEST_LEN
Definition: digest_sizes.h:20
MAX_REND_TIMEOUT
#define MAX_REND_TIMEOUT
Definition: hs_common.h:50
intro_point_should_expire_now
static int intro_point_should_expire_now(rend_intro_point_t *intro, time_t now)
Definition: rendservice.c:3924
rate_limit_log
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:42
tor_addr_port_lookup
int tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
Definition: resolve.c:252
reachable_addr_allows_addr
int reachable_addr_allows_addr(const tor_addr_t *addr, uint16_t port, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:531
rend_service_descriptor_t::all_uploads_performed
int all_uploads_performed
Definition: rend_service_descriptor_st.h:30
resolve.h
Header for resolve.c.
RSAE_BADVIRTPORT
@ RSAE_BADVIRTPORT
Definition: hs_common.h:144
cpath_build_state_t::chosen_exit
extend_info_t * chosen_exit
Definition: cpath_build_state_st.h:20
RSAE_BADAUTH
@ RSAE_BADAUTH
Definition: hs_common.h:143
rend_service_parse_intro_for_v0_or_v1
static ssize_t rend_service_parse_intro_for_v0_or_v1(rend_intro_cell_t *intro, const uint8_t *buf, size_t plaintext_len, char **err_msg_out)
Definition: rendservice.c:2445
crypt_path_t::deliver_window
int deliver_window
Definition: crypt_path_st.h:80
rend_service_port_config_t::real_port
uint16_t real_port
Definition: hs_common.h:159
intro_version_handlers
static ssize_t(* intro_version_handlers[])(rend_intro_cell_t *, const uint8_t *, size_t, char **)
Definition: rendservice.c:2744
replaycache.h
Header file for replaycache.c.
crypt_path_reference_t::refcount
unsigned int refcount
Definition: crypt_path_reference_st.h:21
tor_addr_from_ipv4h
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:327
DH1024_KEY_LEN
#define DH1024_KEY_LEN
Definition: dh_sizes.h:20
rend_service_dump_stats
void rend_service_dump_stats(int severity)
Definition: rendservice.c:4384
rend_service_free_all
void rend_service_free_all(void)
Definition: rendservice.c:285
LD_FS
#define LD_FS
Definition: log.h:70
tor_addr_port_t
Definition: address.h:81
routerstatus_t::ipv4_orport
uint16_t ipv4_orport
Definition: routerstatus_st.h:33
tor_memneq
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
hs_path_from_filename
char * hs_path_from_filename(const char *directory, const char *filename)
Definition: hs_common.c:179
rend_service_receive_introduction
int rend_service_receive_introduction(origin_circuit_t *circuit, const uint8_t *request, size_t request_len)
Definition: rendservice.c:1881
networkstatus_get_latest_consensus
networkstatus_t * networkstatus_get_latest_consensus(void)
Definition: networkstatus.c:1390
rend_consider_services_intro_points
void rend_consider_services_intro_points(time_t now)
Definition: rendservice.c:4115
node_t
Definition: node_st.h:34
origin_circuit_t
Definition: origin_circuit_st.h:79
directory_request_set_routerstatus
void directory_request_set_routerstatus(directory_request_t *req, const routerstatus_t *status)
Definition: dirclient.c:1162
directory_request_set_payload
void directory_request_set_payload(directory_request_t *req, const char *payload, size_t payload_len)
Definition: dirclient.c:1056
RFTS_IGNORE_MISSING
#define RFTS_IGNORE_MISSING
Definition: files.h:101
rend_service_parse_intro_for_v2
static ssize_t rend_service_parse_intro_for_v2(rend_intro_cell_t *intro, const uint8_t *buf, size_t plaintext_len, char **err_msg_out)
Definition: rendservice.c:2518
rend_intro_point_t::time_published
time_t time_published
Definition: rend_intro_point_st.h:62
crypto_dh.h
Headers for crypto_dh.c.
CIRCLAUNCH_ONEHOP_TUNNEL
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition: circuituse.h:39
NUM_INTRO_POINTS_DEFAULT
#define NUM_INTRO_POINTS_DEFAULT
Definition: hs_common.h:33
directory.h
Header file for directory.c.
crypto_pk_get_digest
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:356
extend_info_from_node
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
Definition: extendinfo.c:92
rend_service_update_descriptor
static void rend_service_update_descriptor(rend_service_t *service)
Definition: rendservice.c:1066
directory_post_to_hs_dir
void directory_post_to_hs_dir(rend_service_descriptor_t *renddesc, smartlist_t *descs, smartlist_t *hs_dirs, const char *service_id, int seconds_valid)
Definition: rendservice.c:3679
rend_service_port_config_t::real_addr
tor_addr_t real_addr
Definition: hs_common.h:161
CIRCUIT_PURPOSE_HS_VANGUARDS
#define CIRCUIT_PURPOSE_HS_VANGUARDS
Definition: circuitlist.h:130
or_options_t::ExcludeNodes
struct routerset_t * ExcludeNodes
Definition: or_options_st.h:102
crypt_path_t::rend_dh_handshake_state
struct crypto_dh_t * rend_dh_handshake_state
Definition: crypt_path_st.h:55
crypto_pk_obsolete_private_hybrid_decrypt
int crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen, int padding, int warnOnFailure)
Definition: crypto_rsa.c:163
crypto_dh_get_public
int crypto_dh_get_public(crypto_dh_t *dh, char *pubkey_out, size_t pubkey_out_len)
Definition: crypto_dh_nss.c:116
REND_COOKIE_LEN
#define REND_COOKIE_LEN
Definition: or.h:400
rend_service_descriptor_t::pk
crypto_pk_t * pk
Definition: rend_service_descriptor_st.h:20
hs_check_service_private_dir
int hs_check_service_private_dir(const char *username, const char *path, unsigned int dir_group_readable, unsigned int create)
Definition: hs_common.c:201
LD_REND
#define LD_REND
Definition: log.h:84
RSAE_INTERNAL
@ RSAE_INTERNAL
Definition: hs_common.h:147
escaped
const char * escaped(const char *s)
Definition: escape.c:126
or_options_t::StrictNodes
int StrictNodes
Definition: or_options_st.h:99
hs_service_config_t
Definition: hs_service.h:198
circuit_change_purpose
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3117
circuit_has_opened
void circuit_has_opened(origin_circuit_t *circ)
Definition: circuituse.c:1693
find_intro_point
static rend_intro_point_t * find_intro_point(origin_circuit_t *circ)
Definition: rendservice.c:3646
circuit_t
Definition: circuit_st.h:61
nodelist.h
Header file for nodelist.c.
rend_valid_v2_service_id
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:725
upload_service_descriptor
static void upload_service_descriptor(rend_service_t *service)
Definition: rendservice.c:3796
cpath_extend_linked_list
void cpath_extend_linked_list(crypt_path_t **head_ptr, crypt_path_t *new_hop)
Definition: crypt_path.c:45
rend_data_service_create
rend_data_t * rend_data_service_create(const char *onion_address, const char *pk_digest, const uint8_t *cookie, rend_auth_type_t auth_type)
Definition: hs_common.c:462
rend_encoded_v2_service_descriptor_free_
void rend_encoded_v2_service_descriptor_free_(rend_encoded_v2_service_descriptor_t *desc)
Definition: rendcommon.c:445
rend_service_parse_port_config
rend_service_port_config_t * rend_service_parse_port_config(const char *string, const char *sep, char **err_msg_out)
Definition: rendservice.c:437
have_completed_a_circuit
int have_completed_a_circuit(void)
Definition: mainloop.c:220
routerset.h
Header file for routerset.c.
predict_ports.h
Header file for predict_ports.c.
extend_info_addr_is_allowed
int extend_info_addr_is_allowed(const tor_addr_t *addr)
Definition: extendinfo.c:224
crypto_dh_t
Definition: crypto_dh_nss.c:66
rendservice.h
Header file for rendservice.c.
LD_CONFIG
#define LD_CONFIG
Definition: log.h:68
abort_writing_to_file
int abort_writing_to_file(open_file_t *file_data)
Definition: files.c:473
node_select.h
Header file for node_select.c.
extendinfo.h
Header for core/or/extendinfo.c.
tor_addr_to_str_dup
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
networkstatus_t::routerstatus_list
smartlist_t * routerstatus_list
Definition: networkstatus_st.h:96
hs_service_config_t::allow_unknown_ports
unsigned int allow_unknown_ports
Definition: hs_service.h:235
rend_max_intro_circs_per_period
static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
Definition: rendservice.c:4093
file_status
file_status_t file_status(const char *filename)
Definition: files.c:212
crypto_dh_generate_public
int crypto_dh_generate_public(crypto_dh_t *dh)
Definition: crypto_dh_nss.c:100
REND_DESC_COOKIE_LEN_BASE64
#define REND_DESC_COOKIE_LEN_BASE64
Definition: or.h:371
rend_data_t::rend_cookie
char rend_cookie[REND_COOKIE_LEN]
Definition: or.h:428
log_once_deprecation_warning
static void log_once_deprecation_warning(void)
Definition: rendservice.c:138
write_str_to_file_if_not_equal
int write_str_to_file_if_not_equal(const char *fname, const char *str)
Definition: files.c:743
rep_hist_note_used_internal
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
Definition: predict_ports.c:206
RSAE_BADPRIVKEY
@ RSAE_BADPRIVKEY
Definition: hs_common.h:146
hs_service_config_t::num_intro_points
unsigned int num_intro_points
Definition: hs_service.h:224
pathbias_mark_use_success
void pathbias_mark_use_success(origin_circuit_t *circ)
Definition: circpathbias.c:661
circuit_t::n_circ_id
circid_t n_circ_id
Definition: circuit_st.h:78
crypto_pk_is_valid_private_key
int crypto_pk_is_valid_private_key(const crypto_pk_t *env)
Definition: crypto_rsa_nss.c:250
CIRCWINDOW_START
#define CIRCWINDOW_START
Definition: or.h:502
hs_service_config_t::max_streams_close_circuit
unsigned int max_streams_close_circuit
Definition: hs_service.h:220
rend_service_free_
STATIC void rend_service_free_(rend_service_t *service)
Definition: rendservice.c:234
smartlist_uniq_strings
void smartlist_uniq_strings(smartlist_t *sl)
Definition: smartlist.c:574
LOG_INFO
#define LOG_INFO
Definition: log.h:45
crypto_rand.h
Common functions for using (pseudo-)random number generators.
HS_LEGACY_RENDEZVOUS_CELL_SIZE
#define HS_LEGACY_RENDEZVOUS_CELL_SIZE
Definition: hs_common.h:131
hs_get_service_max_rend_failures
int hs_get_service_max_rend_failures(void)
Definition: hs_common.c:234
control_events.h
Header file for control_events.c.
get_options
const or_options_t * get_options(void)
Definition: config.c:928
crypto_pk_keysize
size_t crypto_pk_keysize(const crypto_pk_t *env)
Definition: crypto_rsa_nss.c:331
origin_circuit_t::build_state
cpath_build_state_t * build_state
Definition: origin_circuit_st.h:123
rend_service_set_connection_addr_port
int rend_service_set_connection_addr_port(edge_connection_t *conn, origin_circuit_t *circ)
Definition: rendservice.c:4418
rend_intro_point_t
Definition: rend_intro_point_st.h:21
circuitbuild.h
Header file for circuitbuild.c.
fmt_addrport
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1199
CIRCUIT_PURPOSE_S_REND_JOINED
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:112
WARN_ONCE_DEPRECATION
#define WARN_ONCE_DEPRECATION()
Definition: rendservice.c:150
get_uint32
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
MAX_NICKNAME_LEN
#define MAX_NICKNAME_LEN
Definition: or.h:112
rend_service_get_by_pk_digest
static struct rend_service_t * rend_service_get_by_pk_digest(const char *digest)
Definition: rendservice.c:1775
crypto_dh_compute_secret
ssize_t crypto_dh_compute_secret(int severity, crypto_dh_t *dh, const char *pubkey, size_t pubkey_len, char *secret_out, size_t secret_bytes_out)
Definition: crypto_dh.c:79
rend_service_descriptor_t::intro_nodes
smartlist_t * intro_nodes
Definition: rend_service_descriptor_st.h:28
smartlist_clear
void smartlist_clear(smartlist_t *sl)
Definition: smartlist_core.c:50
rend_encoded_v2_service_descriptor_t
Definition: rend_encoded_v2_service_descriptor_st.h:16
CIRCLAUNCH_IS_INTERNAL
#define CIRCLAUNCH_IS_INTERNAL
Definition: circuituse.h:46
rend_service_descriptor_t::timestamp
time_t timestamp
Definition: rend_service_descriptor_st.h:22
rend_service_validate_intro_late
int rend_service_validate_intro_late(const rend_intro_cell_t *intro, char **err_msg_out)
Definition: rendservice.c:2989
REND_SERVICE_ID_LEN
#define REND_SERVICE_ID_LEN
Definition: or.h:338
extend_info_st.h
Extend-info structure.
routerstatus_st.h
Routerstatus (consensus entry) structure.
node_describe
const char * node_describe(const node_t *node)
Definition: describe.c:142
smartlist_sort_strings
void smartlist_sort_strings(smartlist_t *sl)
Definition: smartlist.c:549
hs_common.h
Header file containing common data for the whole HS subsytem.
cpath_init_circuit_crypto
int cpath_init_circuit_crypto(crypt_path_t *cpath, const char *key_data, size_t key_data_len, int reverse, int is_hs_v3)
Definition: crypt_path.c:151
edge_connection_st.h
Edge-connection structure.
service_is_single_onion_poisoned
static int service_is_single_onion_poisoned(const rend_service_t *service)
Definition: rendservice.c:1160
CIRCLAUNCH_NEED_UPTIME
#define CIRCLAUNCH_NEED_UPTIME
Definition: circuituse.h:41
origin_circuit_t::cpath
crypt_path_t * cpath
Definition: origin_circuit_st.h:129
or_options_t::HiddenServiceSingleHopMode
int HiddenServiceSingleHopMode
Definition: or_options_st.h:312
is_legal_nickname_or_hexdigest
int is_legal_nickname_or_hexdigest(const char *s)
Definition: nickname.c:31
PK_PKCS1_OAEP_PADDING
#define PK_PKCS1_OAEP_PADDING
Definition: crypto_rsa.h:27
rend_check_authorization
static int rend_check_authorization(rend_service_t *service, const char *descriptor_cookie, size_t cookie_len)
Definition: rendservice.c:1801
TO_ORIGIN_CIRCUIT
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:168
rend_intro_point_t::accepted_introduce2_count
int accepted_introduce2_count
Definition: rend_intro_point_st.h:51
rend_service_add_filenames_to_list
static void rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
Definition: rendservice.c:1412
relay.h
Header file for relay.c.
RSAE_ADDREXISTS
@ RSAE_ADDREXISTS
Definition: hs_common.h:145
rend_service_port_config_free_
void rend_service_port_config_free_(rend_service_port_config_t *p)
Definition: rendservice.c:539
extend_info_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: extend_info_st.h:31
hs_opts_t
Definition: hs_options.inc:18
confline.h
Header for confline.c.
CIRCUIT_PURPOSE_S_CONNECT_REND
#define CIRCUIT_PURPOSE_S_CONNECT_REND
Definition: circuitlist.h:109
directory_request_new
directory_request_t * directory_request_new(uint8_t dir_purpose)
Definition: dirclient.c:948
crypt_path_t::prev
struct crypt_path_t * prev
Definition: crypt_path_st.h:75
NUM_INTRO_POINTS_MAX
#define NUM_INTRO_POINTS_MAX
Definition: hs_common.h:35
nickname.h
Header file for nickname.c.
hs_config.h
Header file containing configuration ABI/API for the HS subsytem.
rend_intro_point_t::listed_in_last_desc
unsigned int listed_in_last_desc
Definition: rend_intro_point_st.h:41
hs_service_requires_uptime_circ
int hs_service_requires_uptime_circ(const smartlist_t *ports)
Definition: hs_common.c:1133
dirclient.h
Header file for dirclient.c.
circuit_should_use_vanguards
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:2044
CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
#define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
Definition: circuitlist.h:103
REND_DESC_COOKIE_LEN
#define REND_DESC_COOKIE_LEN
Definition: or.h:367
control_event_hs_descriptor_upload
void control_event_hs_descriptor_upload(const char *onion_address, const char *id_digest, const char *desc_id, const char *hsdir_index)
Definition: control_events.c:2012
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
rend_authorized_client_st.h
Hidden-service authorized client structure.
rend_service_add_ephemeral
hs_service_add_ephemeral_status_t rend_service_add_ephemeral(crypto_pk_t *pk, smartlist_t *ports, int max_streams_per_circuit, int max_streams_close_circuit, rend_auth_type_t auth_type, smartlist_t *auth_clients, char **service_id_out)
Definition: rendservice.c:906
rend_encode_v2_descriptors
int rend_encode_v2_descriptors(smartlist_t *descs_out, rend_service_descriptor_t *desc, time_t now, uint8_t period, rend_auth_type_t auth_type, crypto_pk_t *client_key, smartlist_t *client_cookies)
Definition: rendcommon.c:480
origin_circuit_t::rend_data
rend_data_t * rend_data
Definition: origin_circuit_st.h:132
crypto_dh_new
crypto_dh_t * crypto_dh_new(int dh_type)
Definition: crypto_dh_nss.c:73
CIRCUIT_PURPOSE_S_INTRO
#define CIRCUIT_PURPOSE_S_INTRO
Definition: circuitlist.h:106
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
rend_consider_services_upload
void rend_consider_services_upload(time_t now)
Definition: rendservice.c:4299
rend_service_escaped_dir
static const char * rend_service_escaped_dir(const struct rend_service_t *s)
Definition: rendservice.c:195
log_fn_ratelim
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:292
crypto_pk_t
Definition: crypto_rsa_nss.c:37
or_options_t::TestingTorNetwork
int TestingTorNetwork
Definition: or_options_st.h:791
SMARTLIST_DEL_CURRENT
#define SMARTLIST_DEL_CURRENT(sl, var)
Definition: smartlist_foreach.h:120
rend_data_client_create
rend_data_t * rend_data_client_create(const char *onion_address, const char *desc_id, const char *cookie, rend_auth_type_t auth_type)
Definition: hs_common.c:494
rend_hsdir_routers_changed
void rend_hsdir_routers_changed(void)
Definition: rendservice.c:4349
rend_num_services
int rend_num_services(void)
Definition: rendservice.c:202
LOG_WARN
#define LOG_WARN
Definition: log.h:53
hs_service_config_t::ports
smartlist_t * ports
Definition: hs_service.h:207
edge_connection_t
Definition: edge_connection_st.h:21
port_cfg_line_extract_addrport
int port_cfg_line_extract_addrport(const char *line, char **addrport_out, int *is_unix_out, const char **rest_out)
Definition: config.c:5815
LOG_ERR
#define LOG_ERR
Definition: log.h:56
rend_data_t
Definition: or.h:419
rend_intro_point_t::time_to_expire
time_t time_to_expire
Definition: rend_intro_point_st.h:67
policies.h
Header file for policies.c.
NUM_INTRO_POINTS_EXTRA
#define NUM_INTRO_POINTS_EXTRA
Definition: hs_common.h:38
rend_intro_point_t::max_introductions
int max_introductions
Definition: rend_intro_point_st.h:57
rend_service_port_config_t::unix_addr
char unix_addr[FLEXIBLE_ARRAY_MEMBER]
Definition: hs_common.h:163
extend_info_dup
extend_info_t * extend_info_dup(extend_info_t *info)
Definition: extendinfo.c:180
rend_data_get_address
const char * rend_data_get_address(const rend_data_t *rend_data)
Definition: hs_common.c:529
rend_encoded_v2_service_descriptor_t::desc_id
char desc_id[DIGEST_LEN]
Definition: rend_encoded_v2_service_descriptor_st.h:17
config.h
Header file for config.c.
cpath_build_state_t
Definition: cpath_build_state_st.h:16
router_choose_random_node
const node_t * router_choose_random_node(smartlist_t *excludedsmartlist, routerset_t *excludedset, router_crn_flags_t flags)
Definition: node_select.c:979
extend_info_t::nickname
char nickname[MAX_HEX_NICKNAME_LEN+1]
Definition: extend_info_st.h:28
MAX_HEX_NICKNAME_LEN
#define MAX_HEX_NICKNAME_LEN
Definition: or.h:115
cpath_build_state_t::expiry_time
time_t expiry_time
Definition: cpath_build_state_st.h:41
crypt_path_reference_t::cpath
crypt_path_t * cpath
Definition: crypt_path_reference_st.h:24
get_uint16
static uint16_t get_uint16(const void *cp)
Definition: bytes.h:42
init_key_from_file
crypto_pk_t * init_key_from_file(const char *fname, int generate, int severity, bool *created_out)
Definition: loadkey.c:40
circuit_state_to_string
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:764
reachable_addr_allows_node
int reachable_addr_allows_node(const node_t *node, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:688
intro_point_accepted_intro_count
static int intro_point_accepted_intro_count(rend_intro_point_t *intro)
Definition: rendservice.c:3915
tor_log
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
hid_serv_get_responsible_directories
int hid_serv_get_responsible_directories(smartlist_t *responsible_dirs, const char *id)
Definition: rendcommon.c:848
rend_service_verify_single_onion_poison
STATIC int rend_service_verify_single_onion_poison(const rend_service_t *s, const or_options_t *options)
Definition: rendservice.c:1213
tor_addr_from_ipv4n
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:889
extend_info_get_orport
const tor_addr_port_t * extend_info_get_orport(const extend_info_t *ei, int family)
Definition: extendinfo.c:263
TO_CIRCUIT
#define TO_CIRCUIT(x)
Definition: or.h:965
or_options_t
Definition: or_options_st.h:45
crypto_rand
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:477
set_uint16
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:78
STATIC
#define STATIC
Definition: testsupport.h:32
router_crn_flags_t
router_crn_flags_t
Definition: node_select.h:16
cpath_build_state_t::pending_final_cpath
crypt_path_t * pending_final_cpath
Definition: cpath_build_state_st.h:34
INTRO_POINT_LIFETIME_MIN_SECONDS
#define INTRO_POINT_LIFETIME_MIN_SECONDS
Definition: or.h:1093
rend_service_descriptor_t::successful_uploads
smartlist_t * successful_uploads
Definition: rend_service_descriptor_st.h:35
networkstatus_st.h
Networkstatus consensus/vote structure.
start_writing_to_stdio_file
FILE * start_writing_to_stdio_file(const char *fname, int open_flags, int mode, open_file_t **data_out)
Definition: files.c:398
rend_services_add_filenames_to_lists
void rend_services_add_filenames_to_lists(smartlist_t *open_lst, smartlist_t *stat_lst)
Definition: rendservice.c:1427
DIRIND_ANONYMOUS
@ DIRIND_ANONYMOUS
Definition: dirclient.h:39
directory_request_t
struct directory_request_t directory_request_t
Definition: dirclient.h:52
routerstatus_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: routerstatus_st.h:27
rend_service_is_ephemeral
static unsigned int rend_service_is_ephemeral(const struct rend_service_t *s)
Definition: rendservice.c:187
networkstatus_t
Definition: networkstatus_st.h:26
origin_circuit_st.h
Origin circuit structure.
circuit_launch_by_extend_info
origin_circuit_t * circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info, int flags)
Definition: circuituse.c:2121
node_has_preferred_descriptor
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1419
smartlist_t
Definition: smartlist_core.h:26
smartlist_remove
void smartlist_remove(smartlist_t *sl, const void *element)
Definition: smartlist_core.c:151
rend_service_port_config_new
static rend_service_port_config_t * rend_service_port_config_new(const char *socket_path)
Definition: rendservice.c:415
rendclient.h
Header file for rendclient.c.
circuit_t::state
uint8_t state
Definition: circuit_st.h:110
circuit_initial_package_window
int32_t circuit_initial_package_window(void)
Definition: circuitlist.c:977
hs_service_config_t::max_streams_per_rdv_circuit
uint64_t max_streams_per_rdv_circuit
Definition: hs_service.h:216
REND_REPLAY_TIME_INTERVAL
#define REND_REPLAY_TIME_INTERVAL
Definition: or.h:480
rendcommon.h
Header file for rendcommon.c.
directory_request_set_indirection
void directory_request_set_indirection(directory_request_t *req, dir_indirection_t indirection)
Definition: dirclient.c:1032
rend_data_get_pk_digest
const uint8_t * rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
Definition: hs_common.c:569
RSAE_OKAY
@ RSAE_OKAY
Definition: hs_common.h:148
rend_authorized_client_free_
void rend_authorized_client_free_(rend_authorized_client_t *client)
Definition: rendservice.c:211
rend_authorized_client_t
Definition: rend_authorized_client_st.h:16
cpath_build_state_t::service_pending_final_cpath_ref
crypt_path_reference_t * service_pending_final_cpath_ref
Definition: cpath_build_state_st.h:37
rend_service_descriptor_t::protocols
unsigned protocols
Definition: rend_service_descriptor_st.h:25
tor_addr_copy
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
extend_info_t
Definition: extend_info_st.h:27
rend_service_rendezvous_has_opened
void rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
Definition: rendservice.c:3469
rend_service_intro_has_opened
void rend_service_intro_has_opened(origin_circuit_t *circuit)
Definition: rendservice.c:3276
rend_get_service_id
int rend_get_service_id(crypto_pk_t *pk, char *out)
Definition: rendcommon.c:712
rend_intro_cell_t
Definition: rendservice.h:23
rend_parse_client_keys
int rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
Definition: rendparse.c:523
consider_republishing_rend_descriptors
static int consider_republishing_rend_descriptors
Definition: rendservice.c:4343
ratelim_t
Definition: ratelim.h:42
REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
#define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
Definition: or.h:345
or.h
Master header file for Tor-specific functionality.
rend_service_load_auth_keys
static int rend_service_load_auth_keys(struct rend_service_t *s, const char *hfname)
Definition: rendservice.c:1591
crypto_pk_write_private_key_to_string
int crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:478
LD_PROTOCOL
#define LD_PROTOCOL
Definition: log.h:72