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