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