tor  0.4.2.0-alpha-dev
rendservice.c
Go to the documentation of this file.
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2  * Copyright (c) 2007-2019, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 
10 #define RENDSERVICE_PRIVATE
11 
12 #include "core/or/or.h"
13 
14 #include "app/config/config.h"
15 #include "core/mainloop/mainloop.h"
16 #include "core/or/circuitbuild.h"
17 #include "core/or/circuitlist.h"
18 #include "core/or/circuituse.h"
19 #include "core/or/policies.h"
20 #include "core/or/relay.h"
21 #include "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  if (rend_service_use_direct_connection(options, rp)) {
2128  flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2129  }
2130  launched = circuit_launch_by_extend_info(
2131  CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2132 
2133  if (launched)
2134  break;
2135  }
2136  if (!launched) { /* give up */
2137  log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2138  "point %s for service %s.",
2139  safe_str_client(extend_info_describe(rp)),
2140  serviceid);
2141  reason = END_CIRC_REASON_CONNECTFAILED;
2142  goto err;
2143  }
2144  log_info(LD_REND,
2145  "Accepted intro; launching circuit to %s "
2146  "(cookie %s) for service %s.",
2147  safe_str_client(extend_info_describe(rp)),
2148  hexcookie, serviceid);
2149  tor_assert(launched->build_state);
2150  /* Fill in the circuit's state. */
2151 
2152  launched->rend_data =
2153  rend_data_service_create(service->service_id, rend_pk_digest,
2154  parsed_req->rc, service->auth_type);
2155 
2157  tor_malloc_zero(sizeof(crypt_path_reference_t));
2159 
2160  launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2161  tor_malloc_zero(sizeof(crypt_path_t));
2162  cpath->magic = CRYPT_PATH_MAGIC;
2163  launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2164 
2165  cpath->rend_dh_handshake_state = dh;
2166  dh = NULL;
2167  if (cpath_init_circuit_crypto(cpath,
2168  keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
2169  1, 0)<0)
2170  goto err;
2171  memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2172 
2173  goto done;
2174 
2175  log_error:
2176  if (!err_msg) {
2177  if (stage_descr) {
2178  tor_asprintf(&err_msg,
2179  "unknown %s error for INTRODUCE2", stage_descr);
2180  } else {
2181  err_msg = tor_strdup("unknown error for INTRODUCE2");
2182  }
2183  }
2184 
2185  log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2186  (unsigned)circuit->base_.n_circ_id);
2187  err:
2188  status = -1;
2189  if (dh) crypto_dh_free(dh);
2190  if (launched) {
2191  circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2192  }
2193  tor_free(err_msg);
2194 
2195  done:
2196  memwipe(keys, 0, sizeof(keys));
2197  memwipe(buf, 0, sizeof(buf));
2198  memwipe(serviceid, 0, sizeof(serviceid));
2199  memwipe(hexcookie, 0, sizeof(hexcookie));
2200 
2201  /* Free the parsed cell */
2202  rend_service_free_intro(parsed_req);
2203 
2204  /* Free rp */
2205  extend_info_free(rp);
2206 
2207  return status;
2208 }
2209 
2213 static extend_info_t *
2215  char **err_msg_out)
2216 {
2217  extend_info_t *rp = NULL;
2218  char *err_msg = NULL;
2219  const char *rp_nickname = NULL;
2220  const node_t *node = NULL;
2221 
2222  if (!intro) {
2223  if (err_msg_out)
2224  err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2225 
2226  goto err;
2227  }
2228 
2229  if (intro->version == 0 || intro->version == 1) {
2230  rp_nickname = (const char *)(intro->u.v0_v1.rp);
2231 
2232  node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
2233  if (!node) {
2234  if (err_msg_out) {
2235  tor_asprintf(&err_msg,
2236  "Couldn't find router %s named in INTRODUCE2 cell",
2237  escaped_safe_str_client(rp_nickname));
2238  }
2239 
2240  goto err;
2241  }
2242 
2243  /* Are we in single onion mode? */
2244  const int allow_direct = rend_service_allow_non_anonymous_connection(
2245  get_options());
2246  rp = extend_info_from_node(node, allow_direct);
2247  if (!rp) {
2248  if (err_msg_out) {
2249  tor_asprintf(&err_msg,
2250  "Couldn't build extend_info_t for router %s named "
2251  "in INTRODUCE2 cell",
2252  escaped_safe_str_client(rp_nickname));
2253  }
2254 
2255  goto err;
2256  }
2257  } else if (intro->version == 2) {
2258  rp = extend_info_dup(intro->u.v2.extend_info);
2259  } else if (intro->version == 3) {
2260  rp = extend_info_dup(intro->u.v3.extend_info);
2261  } else {
2262  if (err_msg_out) {
2263  tor_asprintf(&err_msg,
2264  "Unknown version %d in INTRODUCE2 cell",
2265  (int)(intro->version));
2266  }
2267 
2268  goto err;
2269  }
2270 
2271  /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2272  * the other cases goto err. */
2273  tor_assert(rp);
2274 
2275  /* Make sure the RP we are being asked to connect to is _not_ a private
2276  * address unless it's allowed. Let's avoid to build a circuit to our
2277  * second middle node and fail right after when extending to the RP. */
2278  if (!extend_info_addr_is_allowed(&rp->addr)) {
2279  if (err_msg_out) {
2280  tor_asprintf(&err_msg,
2281  "Relay IP in INTRODUCE2 cell is private address.");
2282  }
2283  extend_info_free(rp);
2284  rp = NULL;
2285  goto err;
2286  }
2287  goto done;
2288 
2289  err:
2290  if (err_msg_out)
2291  *err_msg_out = err_msg;
2292  else
2293  tor_free(err_msg);
2294 
2295  done:
2296  return rp;
2297 }
2298 
2302 void
2304 {
2305  if (!request) {
2306  return;
2307  }
2308 
2309  /* Free ciphertext */
2310  tor_free(request->ciphertext);
2311  request->ciphertext_len = 0;
2312 
2313  /* Have plaintext? */
2314  if (request->plaintext) {
2315  /* Zero it out just to be safe */
2316  memwipe(request->plaintext, 0, request->plaintext_len);
2317  tor_free(request->plaintext);
2318  request->plaintext_len = 0;
2319  }
2320 
2321  /* Have parsed plaintext? */
2322  if (request->parsed) {
2323  switch (request->version) {
2324  case 0:
2325  case 1:
2326  /*
2327  * Nothing more to do; these formats have no further pointers
2328  * in them.
2329  */
2330  break;
2331  case 2:
2332  extend_info_free(request->u.v2.extend_info);
2333  request->u.v2.extend_info = NULL;
2334  break;
2335  case 3:
2336  if (request->u.v3.auth_data) {
2337  memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2338  tor_free(request->u.v3.auth_data);
2339  }
2340 
2341  extend_info_free(request->u.v3.extend_info);
2342  request->u.v3.extend_info = NULL;
2343  break;
2344  default:
2345  log_info(LD_BUG,
2346  "rend_service_free_intro() saw unknown protocol "
2347  "version %d.",
2348  request->version);
2349  }
2350  }
2351 
2352  /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2353  memwipe(request, 0, sizeof(*request));
2354 
2355  tor_free(request);
2356 }
2357 
2372 rend_service_begin_parse_intro(const uint8_t *request,
2373  size_t request_len,
2374  uint8_t type,
2375  char **err_msg_out)
2376 {
2377  rend_intro_cell_t *rv = NULL;
2378  char *err_msg = NULL;
2379 
2380  if (!request || request_len <= 0) goto err;
2381  if (!(type == 1 || type == 2)) goto err;
2382 
2383  /* First, check that the cell is long enough to be a sensible INTRODUCE */
2384 
2385  /* min key length plus digest length plus nickname length */
2386  if (request_len <
2388  DH1024_KEY_LEN + 42)) {
2389  if (err_msg_out) {
2390  tor_asprintf(&err_msg,
2391  "got a truncated INTRODUCE%d cell",
2392  (int)type);
2393  }
2394  goto err;
2395  }
2396 
2397  /* Allocate a new parsed cell structure */
2398  rv = tor_malloc_zero(sizeof(*rv));
2399 
2400  /* Set the type */
2401  rv->type = type;
2402 
2403  /* Copy in the ID */
2404  memcpy(rv->pk, request, DIGEST_LEN);
2405 
2406  /* Copy in the ciphertext */
2407  rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2408  memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2409  rv->ciphertext_len = request_len - DIGEST_LEN;
2410 
2411  goto done;
2412 
2413  err:
2414  rend_service_free_intro(rv);
2415  rv = NULL;
2416 
2417  if (err_msg_out && !err_msg) {
2418  tor_asprintf(&err_msg,
2419  "unknown INTRODUCE%d error",
2420  (int)type);
2421  }
2422 
2423  done:
2424  if (err_msg_out) *err_msg_out = err_msg;
2425  else tor_free(err_msg);
2426 
2427  return rv;
2428 }
2429 
2434 static ssize_t
2436  rend_intro_cell_t *intro,
2437  const uint8_t *buf,
2438  size_t plaintext_len,
2439  char **err_msg_out)
2440 {
2441  const char *rp_nickname, *endptr;
2442  size_t nickname_field_len, ver_specific_len;
2443 
2444  if (intro->version == 1) {
2445  ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2446  rp_nickname = ((const char *)buf) + 1;
2447  nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2448  } else if (intro->version == 0) {
2449  ver_specific_len = MAX_NICKNAME_LEN + 1;
2450  rp_nickname = (const char *)buf;
2451  nickname_field_len = MAX_NICKNAME_LEN + 1;
2452  } else {
2453  if (err_msg_out)
2454  tor_asprintf(err_msg_out,
2455  "rend_service_parse_intro_for_v0_or_v1() called with "
2456  "bad version %d on INTRODUCE%d cell (this is a bug)",
2457  intro->version,
2458  (int)(intro->type));
2459  goto err;
2460  }
2461 
2462  if (plaintext_len < ver_specific_len) {
2463  if (err_msg_out)
2464  tor_asprintf(err_msg_out,
2465  "short plaintext of encrypted part in v1 INTRODUCE%d "
2466  "cell (%lu bytes, needed %lu)",
2467  (int)(intro->type),
2468  (unsigned long)plaintext_len,
2469  (unsigned long)ver_specific_len);
2470  goto err;
2471  }
2472 
2473  endptr = memchr(rp_nickname, 0, nickname_field_len);
2474  if (!endptr || endptr == rp_nickname) {
2475  if (err_msg_out) {
2476  tor_asprintf(err_msg_out,
2477  "couldn't find a nul-padded nickname in "
2478  "INTRODUCE%d cell",
2479  (int)(intro->type));
2480  }
2481  goto err;
2482  }
2483 
2484  if ((intro->version == 0 &&
2485  !is_legal_nickname(rp_nickname)) ||
2486  (intro->version == 1 &&
2487  !is_legal_nickname_or_hexdigest(rp_nickname))) {
2488  if (err_msg_out) {
2489  tor_asprintf(err_msg_out,
2490  "bad nickname in INTRODUCE%d cell",
2491  (int)(intro->type));
2492  }
2493  goto err;
2494  }
2495 
2496  memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2497 
2498  return ver_specific_len;
2499 
2500  err:
2501  return -1;
2502 }
2503 
2507 static ssize_t
2509  rend_intro_cell_t *intro,
2510  const uint8_t *buf,
2511  size_t plaintext_len,
2512  char **err_msg_out)
2513 {
2514  unsigned int klen;
2515  extend_info_t *extend_info = NULL;
2516  ssize_t ver_specific_len;
2517 
2518  /*
2519  * We accept version 3 too so that the v3 parser can call this with
2520  * an adjusted buffer for the latter part of a v3 cell, which is
2521  * identical to a v2 cell.
2522  */
2523  if (!(intro->version == 2 ||
2524  intro->version == 3)) {
2525  if (err_msg_out)
2526  tor_asprintf(err_msg_out,
2527  "rend_service_parse_intro_for_v2() called with "
2528  "bad version %d on INTRODUCE%d cell (this is a bug)",
2529  intro->version,
2530  (int)(intro->type));
2531  goto err;
2532  }
2533 
2534  /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2535  if (plaintext_len < 7 + DIGEST_LEN + 2) {
2536  if (err_msg_out) {
2537  tor_asprintf(err_msg_out,
2538  "truncated plaintext of encrypted parted of "
2539  "version %d INTRODUCE%d cell",
2540  intro->version,
2541  (int)(intro->type));
2542  }
2543 
2544  goto err;
2545  }
2546 
2547  extend_info = tor_malloc_zero(sizeof(extend_info_t));
2548  tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
2549  extend_info->port = ntohs(get_uint16(buf + 5));
2550  memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2551  extend_info->nickname[0] = '$';
2552  base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2553  extend_info->identity_digest, DIGEST_LEN);
2554  klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2555 
2556  /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2557  if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2558  if (err_msg_out) {
2559  tor_asprintf(err_msg_out,
2560  "truncated plaintext of encrypted parted of "
2561  "version %d INTRODUCE%d cell",
2562  intro->version,
2563  (int)(intro->type));
2564  }
2565 
2566  goto err;
2567  }
2568 
2569  extend_info->onion_key =
2570  crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2571  if (!extend_info->onion_key) {
2572  if (err_msg_out) {
2573  tor_asprintf(err_msg_out,
2574  "error decoding onion key in version %d "
2575  "INTRODUCE%d cell",
2576  intro->version,
2577  (intro->type));
2578  }
2579 
2580  goto err;
2581  }
2582  if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2583  if (err_msg_out) {
2584  tor_asprintf(err_msg_out,
2585  "invalid onion key size in version %d INTRODUCE%d cell",
2586  intro->version,
2587  (intro->type));
2588  }
2589 
2590  goto err;
2591  }
2592 
2593  ver_specific_len = 7+DIGEST_LEN+2+klen;
2594 
2595  if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2596  else intro->u.v3.extend_info = extend_info;
2597 
2598  return ver_specific_len;
2599 
2600  err:
2601  extend_info_free(extend_info);
2602 
2603  return -1;
2604 }
2605 
2609 static ssize_t
2611  rend_intro_cell_t *intro,
2612  const uint8_t *buf,
2613  size_t plaintext_len,
2614  char **err_msg_out)
2615 {
2616  ssize_t adjust, v2_ver_specific_len, ts_offset;
2617 
2618  /* This should only be called on v3 cells */
2619  if (intro->version != 3) {
2620  if (err_msg_out)
2621  tor_asprintf(err_msg_out,
2622  "rend_service_parse_intro_for_v3() called with "
2623  "bad version %d on INTRODUCE%d cell (this is a bug)",
2624  intro->version,
2625  (int)(intro->type));
2626  goto err;
2627  }
2628 
2629  /*
2630  * Check that we have at least enough to get auth_len:
2631  *
2632  * 1 octet for version, 1 for auth_type, 2 for auth_len
2633  */
2634  if (plaintext_len < 4) {
2635  if (err_msg_out) {
2636  tor_asprintf(err_msg_out,
2637  "truncated plaintext of encrypted parted of "
2638  "version %d INTRODUCE%d cell",
2639  intro->version,
2640  (int)(intro->type));
2641  }
2642 
2643  goto err;
2644  }
2645 
2646  /*
2647  * The rend_client_send_introduction() function over in rendclient.c is
2648  * broken (i.e., fails to match the spec) in such a way that we can't
2649  * change it without breaking the protocol. Specifically, it doesn't
2650  * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2651  * by two bytes after that. Calculate ts_offset and do everything from
2652  * the timestamp on relative to that to handle this dain bramage.
2653  */
2654 
2655  intro->u.v3.auth_type = buf[1];
2656  if (intro->u.v3.auth_type != REND_NO_AUTH) {
2657  intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2658  ts_offset = 4 + intro->u.v3.auth_len;
2659  } else {
2660  intro->u.v3.auth_len = 0;
2661  ts_offset = 2;
2662  }
2663 
2664  /* Check that auth len makes sense for this auth type */
2665  if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2666  intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2667  if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2668  if (err_msg_out) {
2669  tor_asprintf(err_msg_out,
2670  "wrong auth data size %d for INTRODUCE%d cell, "
2671  "should be %d",
2672  (int)(intro->u.v3.auth_len),
2673  (int)(intro->type),
2675  }
2676 
2677  goto err;
2678  }
2679  }
2680 
2681  /* Check that we actually have everything up through the timestamp */
2682  if (plaintext_len < (size_t)(ts_offset)+4) {
2683  if (err_msg_out) {
2684  tor_asprintf(err_msg_out,
2685  "truncated plaintext of encrypted parted of "
2686  "version %d INTRODUCE%d cell",
2687  intro->version,
2688  (int)(intro->type));
2689  }
2690 
2691  goto err;
2692  }
2693 
2694  if (intro->u.v3.auth_type != REND_NO_AUTH &&
2695  intro->u.v3.auth_len > 0) {
2696  /* Okay, we can go ahead and copy auth_data */
2697  intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2698  /*
2699  * We know we had an auth_len field in this case, so 4 is
2700  * always right.
2701  */
2702  memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2703  }
2704 
2705  /*
2706  * From here on, the format is as in v2, so we call the v2 parser with
2707  * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2708  * v2 parser expects to skip over a version byte at the start, so we
2709  * adjust by 3 + ts_offset.
2710  */
2711  adjust = 3 + ts_offset;
2712 
2713  v2_ver_specific_len =
2715  buf + adjust, plaintext_len - adjust,
2716  err_msg_out);
2717 
2718  /* Success in v2 parser */
2719  if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2720  /* Failure in v2 parser; it will have provided an err_msg */
2721  else return v2_ver_specific_len;
2722 
2723  err:
2724  return -1;
2725 }
2726 
2731 static ssize_t
2734  const uint8_t *,
2735  size_t,
2736  char **) =
2741 
2747 int
2749  rend_intro_cell_t *intro,
2750  crypto_pk_t *key,
2751  char **err_msg_out)
2752 {
2753  char *err_msg = NULL;
2754  uint8_t key_digest[DIGEST_LEN];
2755  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2756  ssize_t key_len;
2757  uint8_t buf[RELAY_PAYLOAD_SIZE];
2758  int result, status = -1;
2759 
2760  if (!intro || !key) {
2761  if (err_msg_out) {
2762  err_msg =
2763  tor_strdup("rend_service_decrypt_intro() called with bad "
2764  "parameters");
2765  }
2766 
2767  status = -2;
2768  goto err;
2769  }
2770 
2771  /* Make sure we have ciphertext */
2772  if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2773  if (err_msg_out) {
2774  tor_asprintf(&err_msg,
2775  "rend_intro_cell_t was missing ciphertext for "
2776  "INTRODUCE%d cell",
2777  (int)(intro->type));
2778  }
2779  status = -3;
2780  goto err;
2781  }
2782 
2783  /* Check that this cell actually matches this service key */
2784 
2785  /* first DIGEST_LEN bytes of request is intro or service pk digest */
2786  if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
2787  if (err_msg_out)
2788  *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
2789  log_warn(LD_BUG, "Couldn't compute key digest.");
2790  status = -7;
2791  goto err;
2792  }
2793 
2794  if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2795  if (err_msg_out) {
2796  base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2797  (char*)(intro->pk), REND_SERVICE_ID_LEN);
2798  tor_asprintf(&err_msg,
2799  "got an INTRODUCE%d cell for the wrong service (%s)",
2800  (int)(intro->type),
2801  escaped(service_id));
2802  }
2803 
2804  status = -4;
2805  goto err;
2806  }
2807 
2808  /* Make sure the encrypted part is long enough to decrypt */
2809 
2810  key_len = crypto_pk_keysize(key);
2811  if (intro->ciphertext_len < key_len) {
2812  if (err_msg_out) {
2813  tor_asprintf(&err_msg,
2814  "got an INTRODUCE%d cell with a truncated PK-encrypted "
2815  "part",
2816  (int)(intro->type));
2817  }
2818 
2819  status = -5;
2820  goto err;
2821  }
2822 
2823  /* Decrypt the encrypted part */
2824  result =
2826  key, (char *)buf, sizeof(buf),
2827  (const char *)(intro->ciphertext), intro->ciphertext_len,
2829  if (result < 0) {
2830  if (err_msg_out) {
2831  tor_asprintf(&err_msg,
2832  "couldn't decrypt INTRODUCE%d cell",
2833  (int)(intro->type));
2834  }
2835  status = -6;
2836  goto err;
2837  }
2838  intro->plaintext_len = result;
2839  intro->plaintext = tor_malloc(intro->plaintext_len);
2840  memcpy(intro->plaintext, buf, intro->plaintext_len);
2841 
2842  status = 0;
2843 
2844  goto done;
2845 
2846  err:
2847  if (err_msg_out && !err_msg) {
2848  tor_asprintf(&err_msg,
2849  "unknown INTRODUCE%d error decrypting encrypted part",
2850  intro ? (int)(intro->type) : -1);
2851  }
2852 
2853  done:
2854  if (err_msg_out) *err_msg_out = err_msg;
2855  else tor_free(err_msg);
2856 
2857  /* clean up potentially sensitive material */
2858  memwipe(buf, 0, sizeof(buf));
2859  memwipe(key_digest, 0, sizeof(key_digest));
2860  memwipe(service_id, 0, sizeof(service_id));
2861 
2862  return status;
2863 }
2864 
2870 int
2872  rend_intro_cell_t *intro,
2873  char **err_msg_out)
2874 {
2875  char *err_msg = NULL;
2876  ssize_t ver_specific_len, ver_invariant_len;
2877  uint8_t version;
2878  int status = -1;
2879 
2880  if (!intro) {
2881  if (err_msg_out) {
2882  err_msg =
2883  tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2884  "rend_intro_cell_t");
2885  }
2886 
2887  status = -2;
2888  goto err;
2889  }
2890 
2891  /* Check that we have plaintext */
2892  if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2893  if (err_msg_out) {
2894  err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2895  }
2896  status = -3;
2897  goto err;
2898  }
2899 
2900  /* In all formats except v0, the first byte is a version number */
2901  version = intro->plaintext[0];
2902 
2903  /* v0 has no version byte (stupid...), so handle it as a fallback */
2904  if (version > 3) version = 0;
2905 
2906  /* Copy the version into the parsed cell structure */
2907  intro->version = version;
2908 
2909  /* Call the version-specific parser from the table */
2910  ver_specific_len =
2911  intro_version_handlers[version](intro,
2912  intro->plaintext, intro->plaintext_len,
2913  &err_msg);
2914  if (ver_specific_len < 0) {
2915  status = -4;
2916  goto err;
2917  }
2918 
2923  ver_invariant_len = intro->plaintext_len - ver_specific_len;
2924  if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
2925  tor_asprintf(&err_msg,
2926  "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2927  (int)(intro->type),
2928  (long)(intro->plaintext_len));
2929  status = -5;
2930  goto err;
2931  } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
2932  tor_asprintf(&err_msg,
2933  "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2934  (int)(intro->type),
2935  (long)(intro->plaintext_len));
2936  status = -6;
2937  goto err;
2938  } else {
2939  memcpy(intro->rc,
2940  intro->plaintext + ver_specific_len,
2941  REND_COOKIE_LEN);
2942  memcpy(intro->dh,
2943  intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2944  DH1024_KEY_LEN);
2945  }
2946 
2947  /* Flag it as being fully parsed */
2948  intro->parsed = 1;
2949 
2950  status = 0;
2951  goto done;
2952 
2953  err:
2954  if (err_msg_out && !err_msg) {
2955  tor_asprintf(&err_msg,
2956  "unknown INTRODUCE%d error parsing encrypted part",
2957  intro ? (int)(intro->type) : -1);
2958  }
2959 
2960  done:
2961  if (err_msg_out) *err_msg_out = err_msg;
2962  else tor_free(err_msg);
2963 
2964  return status;
2965 }
2966 
2976 int
2978  char **err_msg_out)
2979 {
2980  int status = 0;
2981 
2982  if (!intro) {
2983  if (err_msg_out)
2984  *err_msg_out =
2985  tor_strdup("NULL intro cell passed to "
2986  "rend_service_validate_intro_late()");
2987 
2988  status = -1;
2989  goto err;
2990  }
2991 
2992  if (intro->version == 3 && intro->parsed) {
2993  if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
2994  intro->u.v3.auth_type == REND_BASIC_AUTH ||
2995  intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
2996  /* This is an informative message, not an error, as in the old code */
2997  if (err_msg_out)
2998  tor_asprintf(err_msg_out,
2999  "unknown authorization type %d",
3000  intro->u.v3.auth_type);
3001  }
3002  }
3003 
3004  err:
3005  return status;
3006 }
3007 
3011 void
3013 {
3014  origin_circuit_t *newcirc;
3015  cpath_build_state_t *newstate, *oldstate;
3016  const char *rend_pk_digest;
3017  rend_service_t *service = NULL;
3018 
3020 
3022  oldstate = oldcirc->build_state;
3023  tor_assert(oldstate);
3024 
3025  if (oldstate->service_pending_final_cpath_ref == NULL) {
3026  log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
3027  "Initiator will retry.");
3028  return;
3029  }
3030 
3031  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
3032  safe_str(extend_info_describe(oldstate->chosen_exit)));
3033 
3034  /* Look up the service. */
3035  rend_pk_digest = (char *) rend_data_get_pk_digest(oldcirc->rend_data, NULL);
3036  service = rend_service_get_by_pk_digest(rend_pk_digest);
3037 
3038  if (!service) {
3039  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3041  rend_pk_digest, REND_SERVICE_ID_LEN);
3042 
3043  log_warn(LD_BUG, "Internal error: Trying to relaunch a rendezvous circ "
3044  "for an unrecognized service %s.",
3045  safe_str_client(serviceid));
3046  return;
3047  }
3048 
3049  if (hs_service_requires_uptime_circ(service->ports)) {
3050  flags |= CIRCLAUNCH_NEED_UPTIME;
3051  }
3052 
3053  /* You'd think Single Onion Services would want to retry the rendezvous
3054  * using a direct connection. But if it's blocked by a firewall, or the
3055  * service is IPv6-only, or the rend point avoiding becoming a one-hop
3056  * proxy, we need a 3-hop connection. */
3058  oldstate->chosen_exit, flags);
3059 
3060  if (!newcirc) {
3061  log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
3062  safe_str(extend_info_describe(oldstate->chosen_exit)));
3063  return;
3064  }
3065  newstate = newcirc->build_state;
3066  tor_assert(newstate);
3067  newstate->failure_count = oldstate->failure_count+1;
3068  newstate->expiry_time = oldstate->expiry_time;
3072 
3073  newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
3074 }
3075 
3079 static int
3080 rend_service_launch_establish_intro(rend_service_t *service,
3081  rend_intro_point_t *intro)
3082 {
3083  origin_circuit_t *launched;
3085  const or_options_t *options = get_options();
3086  extend_info_t *launch_ei = intro->extend_info;
3087  extend_info_t *direct_ei = NULL;
3088 
3089  /* Are we in single onion mode? */
3090  if (rend_service_allow_non_anonymous_connection(options)) {
3091  /* Do we have a descriptor for the node?
3092  * We've either just chosen it from the consensus, or we've just reviewed
3093  * our intro points to see which ones are still valid, and deleted the ones
3094  * that aren't in the consensus any more. */
3095  const node_t *node = node_get_by_id(launch_ei->identity_digest);
3096  if (BUG(!node)) {
3097  /* The service has kept an intro point after it went missing from the
3098  * consensus. If we did anything else here, it would be a consensus
3099  * distinguisher. Which are less of an issue for single onion services,
3100  * but still a bug. */
3101  return -1;
3102  }
3103  /* Can we connect to the node directly? If so, replace launch_ei
3104  * (a multi-hop extend_info) with one suitable for direct connection. */
3105  if (rend_service_use_direct_connection_node(options, node)) {
3106  direct_ei = extend_info_from_node(node, 1);
3107  if (BUG(!direct_ei)) {
3108  /* rend_service_use_direct_connection_node and extend_info_from_node
3109  * disagree about which addresses on this node are permitted. This
3110  * should never happen. Avoiding the connection is a safe response. */
3111  return -1;
3112  }
3113  flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3114  launch_ei = direct_ei;
3115  }
3116  }
3117  /* launch_ei is either intro->extend_info, or has been replaced with a valid
3118  * extend_info for single onion service direct connection. */
3119  tor_assert(launch_ei);
3120  /* We must have the same intro when making a direct connection. */
3122  launch_ei->identity_digest,
3123  DIGEST_LEN));
3124 
3125  log_info(LD_REND,
3126  "Launching circuit to introduction point %s%s%s for service %s",
3127  safe_str_client(extend_info_describe(intro->extend_info)),
3128  direct_ei ? " via direct address " : "",
3129  direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3130  service->service_id);
3131 
3132  rep_hist_note_used_internal(time(NULL), 1, 0);
3133 
3134  ++service->n_intro_circuits_launched;
3136  launch_ei, flags);
3137 
3138  if (!launched) {
3139  log_info(LD_REND,
3140  "Can't launch circuit to establish introduction at %s%s%s.",
3141  safe_str_client(extend_info_describe(intro->extend_info)),
3142  direct_ei ? " via direct address " : "",
3143  direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3144  );
3145  extend_info_free(direct_ei);
3146  return -1;
3147  }
3148  /* We must have the same exit node even if cannibalized or direct connection.
3149  */
3152  DIGEST_LEN));
3153 
3154  launched->rend_data = rend_data_service_create(service->service_id,
3155  service->pk_digest, NULL,
3156  service->auth_type);
3157  launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3158  if (launched->base_.state == CIRCUIT_STATE_OPEN)
3160  extend_info_free(direct_ei);
3161  return 0;
3162 }
3163 
3166 static unsigned int
3167 count_established_intro_points(const rend_service_t *service)
3168 {
3169  unsigned int num = 0;
3170 
3171  SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3172  num += intro->circuit_established
3173  );
3174  return num;
3175 }
3176 
3181 static unsigned int
3182 count_intro_point_circuits(const rend_service_t *service)
3183 {
3184  unsigned int num_ipos = 0;
3185  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
3186  if (!circ->marked_for_close &&
3187  circ->state == CIRCUIT_STATE_OPEN &&
3188  (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3189  circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3190  origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3191  if (oc->rend_data &&
3192  rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
3193  num_ipos++;
3194  }
3195  }
3196  }
3197  SMARTLIST_FOREACH_END(circ);
3198  return num_ipos;
3199 }
3200 
3201 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3202  write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3203  as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3204  crypto material. On success, fill <b>cell_body_out</b> and return the number
3205  of bytes written. On fail, return -1.
3206  */
3207 ssize_t
3208 rend_service_encode_establish_intro_cell(char *cell_body_out,
3209  size_t cell_body_out_len,
3210  crypto_pk_t *intro_key,
3211  const char *rend_circ_nonce)
3212 {
3213  int retval = -1;
3214  int r;
3215  int len = 0;
3216  char auth[DIGEST_LEN + 9];
3217 
3218  tor_assert(intro_key);
3219  tor_assert(rend_circ_nonce);
3220 
3221  /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3222  r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
3223  RELAY_PAYLOAD_SIZE-2);
3224  if (r < 0) {
3225  log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3226  goto err;
3227  }
3228  len = r;
3229  set_uint16(cell_body_out, htons((uint16_t)len));
3230  len += 2;
3231  memcpy(auth, rend_circ_nonce, DIGEST_LEN);
3232  memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3233  if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
3234  goto err;
3235  len += 20;
3236  r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
3237  cell_body_out_len - len,
3238  cell_body_out, len);
3239  if (r<0) {
3240  log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3241  goto err;
3242  }
3243  len += r;
3244 
3245  retval = len;
3246 
3247  err:
3248  memwipe(auth, 0, sizeof(auth));
3249 
3250  return retval;
3251 }
3252 
3256 void
3258 {
3259  rend_service_t *service;
3260  char buf[RELAY_PAYLOAD_SIZE];
3261  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3262  unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
3263  int reason = END_CIRC_REASON_TORPROTOCOL;
3264  const char *rend_pk_digest;
3265 
3267  assert_circ_anonymity_ok(circuit, get_options());
3268  tor_assert(circuit->cpath);
3269  tor_assert(circuit->rend_data);
3270  /* XXX: This is version 2 specific (only on supported). */
3271  rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3272 
3274  rend_pk_digest, REND_SERVICE_ID_LEN);
3275 
3276  service = rend_service_get_by_pk_digest(rend_pk_digest);
3277  if (!service) {
3278  log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3279  safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3280  reason = END_CIRC_REASON_NOSUCHSERVICE;
3281  goto err;
3282  }
3283 
3284  /* Take the current amount of expiring nodes and the current amount of IP
3285  * circuits and compute how many valid IP circuits we have. */
3286  expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
3287  num_ip_circuits = count_intro_point_circuits(service);
3288  /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3289  * case this condition turns out false because it means that all circuits
3290  * are expiring so we need to keep this circuit. */
3291  if (num_ip_circuits > expiring_nodes_len) {
3292  valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
3293  }
3294 
3295  /* If we already have enough introduction circuits for this service,
3296  * redefine this one as a general circuit or close it, depending.
3297  * Subtract the amount of expiring nodes here because the circuits are
3298  * still opened. */
3299  if (valid_ip_circuits > service->n_intro_points_wanted) {
3300  const or_options_t *options = get_options();
3301  /* Remove the intro point associated with this circuit, it's being
3302  * repurposed or closed thus cleanup memory. */
3303  rend_intro_point_t *intro = find_intro_point(circuit);
3304  if (intro != NULL) {
3305  smartlist_remove(service->intro_nodes, intro);
3306  rend_intro_point_free(intro);
3307  }
3308 
3309  if (options->ExcludeNodes) {
3310  /* XXXX in some future version, we can test whether the transition is
3311  allowed or not given the actual nodes in the circuit. But for now,
3312  this case, we might as well close the thing. */
3313  log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3314  "circuit, but we already have enough. Closing it.");
3315  reason = END_CIRC_REASON_NONE;
3316  goto err;
3317  } else {
3318  tor_assert(circuit->build_state->is_internal);
3319  log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3320  "circuit, but we already have enough. Redefining purpose to "
3321  "general; leaving as internal.");
3322 
3323  if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
3326  } else {
3328  }
3329 
3330  {
3331  rend_data_free(circuit->rend_data);
3332  circuit->rend_data = NULL;
3333  }
3334  {
3335  crypto_pk_t *intro_key = circuit->intro_key;
3336  circuit->intro_key = NULL;
3337  crypto_pk_free(intro_key);
3338  }
3339 
3340  circuit_has_opened(circuit);
3341  goto done;
3342  }
3343  }
3344 
3345  log_info(LD_REND,
3346  "Established circuit %u as introduction point for service %s",
3347  (unsigned)circuit->base_.n_circ_id, serviceid);
3348  circuit_log_path(LOG_INFO, LD_REND, circuit);
3349 
3350  /* Send the ESTABLISH_INTRO cell */
3351  {
3352  ssize_t len;
3353  len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
3354  circuit->intro_key,
3355  circuit->cpath->prev->rend_circ_nonce);
3356  if (len < 0) {
3357  reason = END_CIRC_REASON_INTERNAL;
3358  goto err;
3359  }
3360 
3361  if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3362  RELAY_COMMAND_ESTABLISH_INTRO,
3363  buf, len, circuit->cpath->prev)<0) {
3364  log_info(LD_GENERAL,
3365  "Couldn't send introduction request for service %s on circuit %u",
3366  serviceid, (unsigned)circuit->base_.n_circ_id);
3367  goto done;
3368  }
3369  }
3370 
3371  /* We've attempted to use this circuit */
3372  pathbias_count_use_attempt(circuit);
3373 
3374  goto done;
3375 
3376  err:
3377  circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3378  done:
3379  memwipe(buf, 0, sizeof(buf));
3380  memwipe(serviceid, 0, sizeof(serviceid));
3381 
3382  return;
3383 }
3384 
3388 int
3390  const uint8_t *request,
3391  size_t request_len)
3392 {
3393  rend_service_t *service;
3394  rend_intro_point_t *intro;
3395  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3396  (void) request;
3397  (void) request_len;
3398  tor_assert(circuit->rend_data);
3399  /* XXX: This is version 2 specific (only supported one for now). */
3400  const char *rend_pk_digest =
3401  (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3402 
3403  if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3404  log_warn(LD_PROTOCOL,
3405  "received INTRO_ESTABLISHED cell on non-intro circuit.");
3406  goto err;
3407  }
3408  service = rend_service_get_by_pk_digest(rend_pk_digest);
3409  if (!service) {
3410  log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3411  (unsigned)circuit->base_.n_circ_id);
3412  goto err;
3413  }
3415  rend_pk_digest, REND_SERVICE_ID_LEN);
3416  /* We've just successfully established a intro circuit to one of our
3417  * introduction point, account for it. */
3418  intro = find_intro_point(circuit);
3419  if (intro == NULL) {
3420  log_warn(LD_REND,
3421  "Introduction circuit established without a rend_intro_point_t "
3422  "object for service %s on circuit %u",
3423  safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3424  goto err;
3425  }
3426  intro->circuit_established = 1;
3427  /* We might not have every introduction point ready but at this point we
3428  * know that the descriptor needs to be uploaded. */
3429  service->desc_is_dirty = time(NULL);
3431 
3432  log_info(LD_REND,
3433  "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3434  (unsigned)circuit->base_.n_circ_id, serviceid);
3435 
3436  /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3437  * used the circ */
3438  pathbias_mark_use_success(circuit);
3439 
3440  return 0;
3441  err:
3442  circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3443  return -1;
3444 }
3445 
3449 void
3451 {
3452  rend_service_t *service;
3453  char buf[RELAY_PAYLOAD_SIZE];
3454  crypt_path_t *hop;
3455  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3456  char hexcookie[9];
3457  int reason;
3458  const char *rend_cookie, *rend_pk_digest;
3459 
3461  tor_assert(circuit->cpath);
3462  tor_assert(circuit->build_state);
3463  assert_circ_anonymity_ok(circuit, get_options());
3464  tor_assert(circuit->rend_data);
3465 
3466  /* XXX: This is version 2 specific (only one supported). */
3467  rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
3468  NULL);
3469  rend_cookie = circuit->rend_data->rend_cookie;
3470 
3471  /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3472  * timestamp regardless of its content because that circuit could have been
3473  * cannibalized so in any cases, we are about to use that circuit more. */
3474  circuit->base_.timestamp_dirty = time(NULL);
3475 
3476  /* This may be redundant */
3477  pathbias_count_use_attempt(circuit);
3478 
3480 
3481  base16_encode(hexcookie,9, rend_cookie,4);
3483  rend_pk_digest, REND_SERVICE_ID_LEN);
3484 
3485  log_info(LD_REND,
3486  "Done building circuit %u to rendezvous with "
3487  "cookie %s for service %s",
3488  (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3489  circuit_log_path(LOG_INFO, LD_REND, circuit);
3490 
3491  /* Clear the 'in-progress HS circ has timed out' flag for
3492  * consistency with what happens on the client side; this line has
3493  * no effect on Tor's behaviour. */
3494  circuit->hs_circ_has_timed_out = 0;
3495 
3496  /* If hop is NULL, another rend circ has already connected to this
3497  * rend point. Close this circ. */
3498  if (hop == NULL) {
3499  log_info(LD_REND, "Another rend circ has already reached this rend point; "
3500  "closing this rend circ.");
3501  reason = END_CIRC_REASON_NONE;
3502  goto err;
3503  }
3504 
3505  /* Remove our final cpath element from the reference, so that no
3506  * other circuit will try to use it. Store it in
3507  * pending_final_cpath for now to ensure that it will be freed if
3508  * our rendezvous attempt fails. */
3509  circuit->build_state->pending_final_cpath = hop;
3511 
3512  service = rend_service_get_by_pk_digest(rend_pk_digest);
3513  if (!service) {
3514  log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3515  "rendezvous circuit.");
3516  reason = END_CIRC_REASON_INTERNAL;
3517  goto err;
3518  }
3519 
3520  /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3521  memcpy(buf, rend_cookie, REND_COOKIE_LEN);
3523  buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
3524  log_warn(LD_GENERAL,"Couldn't get DH public key.");
3525  reason = END_CIRC_REASON_INTERNAL;
3526  goto err;
3527  }
3529  DIGEST_LEN);
3530 
3531  /* Send the cell */
3532  if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3533  RELAY_COMMAND_RENDEZVOUS1,
3534  buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
3535  circuit->cpath->prev)<0) {
3536  log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3537  goto done;
3538  }
3539 
3540  crypto_dh_free(hop->rend_dh_handshake_state);
3541  hop->rend_dh_handshake_state = NULL;
3542 
3543  /* Append the cpath entry. */
3544  hop->state = CPATH_STATE_OPEN;
3545  /* set the windows to default. these are the windows
3546  * that the service thinks the client has.
3547  */
3550 
3551  cpath_extend_linked_list(&circuit->cpath, hop);
3552  circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3553 
3554  /* Change the circuit purpose. */
3556 
3557  goto done;
3558 
3559  err:
3560  circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3561  done:
3562  memwipe(buf, 0, sizeof(buf));
3563  memwipe(serviceid, 0, sizeof(serviceid));
3564  memwipe(hexcookie, 0, sizeof(hexcookie));
3565 
3566  return;
3567 }
3568 
3569 /*
3570  * Manage introduction points
3571  */
3572 
3578 static origin_circuit_t *
3579 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3580 {
3581  origin_circuit_t *circ = NULL;
3582 
3583  tor_assert(intro);
3584  while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3585  (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
3588  circ->rend_data) {
3589  return circ;
3590  }
3591  }
3592 
3593  circ = NULL;
3594  while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3595  (uint8_t *) pk_digest,
3599  circ->rend_data) {
3600  return circ;
3601  }
3602  }
3603  return NULL;
3604 }
3605 
3608 static rend_intro_point_t *
3609 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3610 {
3611  tor_assert(service);
3613  TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3614 
3615  SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3616  intro_point,
3617  if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3618  return intro_point;
3619  });
3620 
3621  return NULL;
3622 }
3623 
3626 static rend_intro_point_t *
3628 {
3629  const char *serviceid;
3630  rend_service_t *service = NULL;
3631 
3633  TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3634  tor_assert(circ->rend_data);
3635  serviceid = rend_data_get_address(circ->rend_data);
3636 
3637  SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3638  if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3639  service = s;
3640  break;
3641  });
3642 
3643  if (service == NULL) return NULL;
3644 
3645  SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3646  if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3647  return intro_point;
3648  });
3649 
3650  return NULL;
3651 }
3652 
3659 void
3661  smartlist_t *descs, smartlist_t *hs_dirs,
3662  const char *service_id, int seconds_valid)
3663 {
3664  int i, j, failed_upload = 0;
3665  smartlist_t *responsible_dirs = smartlist_new();
3666  smartlist_t *successful_uploads = smartlist_new();
3667  routerstatus_t *hs_dir;
3668  for (i = 0; i < smartlist_len(descs); i++) {
3669  rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3672  if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3673  smartlist_add_all(responsible_dirs, hs_dirs);
3674  } else {
3675  /* Determine responsible dirs. */
3676  if (hid_serv_get_responsible_directories(responsible_dirs,
3677  desc->desc_id) < 0) {
3678  log_warn(LD_REND, "Could not determine the responsible hidden service "
3679  "directories to post descriptors to.");
3681  "UNKNOWN",
3682  "UNKNOWN", NULL);
3683  goto done;
3684  }
3685  }
3686  for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3687  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3688  char *hs_dir_ip;
3689  const node_t *node;
3690  rend_data_t *rend_data;
3691  hs_dir = smartlist_get(responsible_dirs, j);
3693  hs_dir->identity_digest))
3694  /* Don't upload descriptor if we succeeded in doing so last time. */
3695  continue;
3696  node = node_get_by_id(hs_dir->identity_digest);
3697  if (!node || !node_has_preferred_descriptor(node,0)) {
3698  log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3699  "hidden service directory %s; we don't have its "
3700  "router descriptor. Queuing for later upload.",
3701  safe_str_client(routerstatus_describe(hs_dir)));
3702  failed_upload = -1;
3703  continue;
3704  }
3705  /* Send publish request. */
3706 
3707  /* We need the service ID to identify which service did the upload
3708  * request. Lookup is made in rend_service_desc_has_uploaded(). */
3709  rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3710  REND_NO_AUTH);
3711  directory_request_t *req =
3716  desc->desc_str, strlen(desc->desc_str));
3717  directory_request_set_rend_query(req, rend_data);
3718  directory_initiate_request(req);
3719  directory_request_free(req);
3720 
3721  rend_data_free(rend_data);
3722  base32_encode(desc_id_base32, sizeof(desc_id_base32),
3723  desc->desc_id, DIGEST_LEN);
3724  hs_dir_ip = tor_dup_ip(hs_dir->addr);
3725  log_info(LD_REND, "Launching upload for v2 descriptor for "
3726  "service '%s' with descriptor ID '%s' with validity "
3727  "of %d seconds to hidden service directory '%s' on "
3728  "%s:%d.",
3729  safe_str_client(service_id),
3730  safe_str_client(desc_id_base32),
3731  seconds_valid,
3732  hs_dir->nickname,
3733  hs_dir_ip,
3734  hs_dir->or_port);
3736  hs_dir->identity_digest,
3737  desc_id_base32, NULL);
3738  tor_free(hs_dir_ip);
3739  /* Remember successful upload to this router for next time. */
3740  if (!smartlist_contains_digest(successful_uploads,
3741  hs_dir->identity_digest))
3742  smartlist_add(successful_uploads, hs_dir->identity_digest);
3743  }
3744  smartlist_clear(responsible_dirs);
3745  }
3746  if (!failed_upload) {
3747  if (renddesc->successful_uploads) {
3748  SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3749  smartlist_free(renddesc->successful_uploads);
3750  renddesc->successful_uploads = NULL;
3751  }
3752  renddesc->all_uploads_performed = 1;
3753  } else {
3754  /* Remember which routers worked this time, so that we don't upload the
3755  * descriptor to them again. */
3756  if (!renddesc->successful_uploads)
3757  renddesc->successful_uploads = smartlist_new();
3758  SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3759  if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3760  char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3761  smartlist_add(renddesc->successful_uploads, hsdir_id);
3762  }
3763  });
3764  }
3765  done:
3766  smartlist_free(responsible_dirs);
3767  smartlist_free(successful_uploads);
3768 }
3769 
3773 static void
3774 upload_service_descriptor(rend_service_t *service)
3775 {
3776  time_t now = time(NULL);
3777  int rendpostperiod;
3778  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3779  int uploaded = 0;
3780 
3781  rendpostperiod = get_options()->RendPostPeriod;
3782 
3783  networkstatus_t *c = networkstatus_get_latest_consensus();
3784  if (c && smartlist_len(c->routerstatus_list) > 0) {
3785  int seconds_valid, i, j, num_descs;
3786  smartlist_t *descs = smartlist_new();
3787  smartlist_t *client_cookies = smartlist_new();
3788  /* Either upload a single descriptor (including replicas) or one
3789  * descriptor for each authorized client in case of authorization
3790  * type 'stealth'. */
3791  num_descs = service->auth_type == REND_STEALTH_AUTH ?
3792  smartlist_len(service->clients) : 1;
3793  for (j = 0; j < num_descs; j++) {
3794  crypto_pk_t *client_key = NULL;
3795  rend_authorized_client_t *client = NULL;
3796  smartlist_clear(client_cookies);
3797  switch (service->auth_type) {
3798  case REND_NO_AUTH:
3799  /* Do nothing here. */
3800  break;
3801  case REND_BASIC_AUTH:
3802  SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3803  cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3804  break;
3805  case REND_STEALTH_AUTH:
3806  client = smartlist_get(service->clients, j);
3807  client_key = client->client_key;
3808  smartlist_add(client_cookies, client->descriptor_cookie);
3809  break;
3810  }
3811  /* Encode the current descriptor. */
3812  seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3813  now, 0,
3814  service->auth_type,
3815  client_key,
3816  client_cookies);
3817  if (seconds_valid < 0) {
3818  log_warn(LD_BUG, "Internal error: couldn't encode service "
3819  "descriptor; not uploading.");
3820  smartlist_free(descs);
3821  smartlist_free(client_cookies);
3822  return;
3823  }
3824  rend_get_service_id(service->desc->pk, serviceid);
3825  if (get_options()->PublishHidServDescriptors) {
3826  /* Post the current descriptors to the hidden service directories. */
3827  log_info(LD_REND, "Launching upload for hidden service %s",
3828  serviceid);
3829  directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3830  seconds_valid);
3831  }
3832  /* Free memory for descriptors. */
3833  for (i = 0; i < smartlist_len(descs); i++)
3834  rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3835  smartlist_clear(descs);
3836  /* Update next upload time. */
3837  if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3838  > rendpostperiod)
3839  service->next_upload_time = now + rendpostperiod;
3840  else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3841  service->next_upload_time = now + seconds_valid + 1;
3842  else
3843  service->next_upload_time = now + seconds_valid -
3845  /* Post also the next descriptors, if necessary. */
3846  if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3847  seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3848  now, 1,
3849  service->auth_type,
3850  client_key,
3851  client_cookies);
3852  if (seconds_valid < 0) {
3853  log_warn(LD_BUG, "Internal error: couldn't encode service "
3854  "descriptor; not uploading.");
3855  smartlist_free(descs);
3856  smartlist_free(client_cookies);
3857  return;
3858  }
3859  if (get_options()->PublishHidServDescriptors) {
3860  directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3861  seconds_valid);
3862  }
3863  /* Free memory for descriptors. */
3864  for (i = 0; i < smartlist_len(descs); i++)
3865  rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3866  smartlist_clear(descs);
3867  }
3868  }
3869  smartlist_free(descs);
3870  smartlist_free(client_cookies);
3871  uploaded = 1;
3872  if (get_options()->PublishHidServDescriptors) {
3873  log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3874  } else {
3875  log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3876  }
3877  }
3878 
3879  /* If not uploaded, try again in one minute. */
3880  if (!uploaded)
3881  service->next_upload_time = now + 60;
3882 
3883  /* Unmark dirty flag of this service. */
3884  service->desc_is_dirty = 0;
3885 }
3886 
3889 static int
3891 {
3892  return intro->accepted_introduce2_count;
3893 }
3894 
3898 static int
3900  time_t now)
3901 {
3902  tor_assert(intro != NULL);
3903 
3904  if (intro->time_published == -1) {
3905  /* Don't expire an intro point if we haven't even published it yet. */
3906  return 0;
3907  }
3908 
3909  if (intro_point_accepted_intro_count(intro) >=
3910  intro->max_introductions) {
3911  /* This intro point has been used too many times. Expire it now. */
3912  return 1;
3913  }
3914 
3915  if (intro->time_to_expire == -1) {
3916  /* This intro point has been published, but we haven't picked an
3917  * expiration time for it. Pick one now. */
3918  int intro_point_lifetime_seconds =
3921 
3922  /* Start the expiration timer now, rather than when the intro
3923  * point was first published. There shouldn't be much of a time
3924  * difference. */
3925  intro->time_to_expire = now + intro_point_lifetime_seconds;
3926 
3927  return 0;
3928  }
3929 
3930  /* This intro point has a time to expire set already. Use it. */
3931  return (now >= intro->time_to_expire);
3932 }
3933 
3945 static void
3946 remove_invalid_intro_points(rend_service_t *service,
3947  smartlist_t *exclude_nodes,
3948  smartlist_t *retry_nodes, time_t now)
3949 {
3950  tor_assert(service);
3951 
3952  /* Remove any expired nodes that doesn't have a circuit. */
3953  SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3954  intro) {
3955  origin_circuit_t *intro_circ =
3956  find_intro_circuit(intro, service->pk_digest);
3957  if (intro_circ) {
3958  continue;
3959  }
3960  /* No more circuit, cleanup the into point object. */
3961  SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3962  rend_intro_point_free(intro);
3963  } SMARTLIST_FOREACH_END(intro);
3964 
3965  SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3966  intro) {
3967  /* Find the introduction point node object. */
3968  const node_t *node =
3969  node_get_by_id(intro->extend_info->identity_digest);
3970  /* Find the intro circuit, this might be NULL. */
3971  origin_circuit_t *intro_circ =
3972  find_intro_circuit(intro, service->pk_digest);
3973 
3974  /* Add the valid node to the exclusion list so we don't try to establish
3975  * an introduction point to it again. */
3976  if (node && exclude_nodes) {
3977  smartlist_add(exclude_nodes, (void*) node);
3978  }
3979 
3980  /* First, make sure we still have a valid circuit for this intro point.
3981  * If we dont, we'll give up on it and make a new one. */
3982  if (intro_circ == NULL) {
3983  log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
3984  " (circuit disappeared).",
3985  safe_str_client(extend_info_describe(intro->extend_info)),
3986  safe_str_client(service->service_id));
3987  /* We've lost the circuit for this intro point, flag it so it can be
3988  * accounted for when considiring uploading a descriptor. */
3989  intro->circuit_established = 0;
3990 
3991  /* Node is gone or we've reached our maximum circuit creationg retry
3992  * count, clean up everything, we'll find a new one. */
3993  if (node == NULL ||
3994  intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
3995  rend_intro_point_free(intro);
3996  SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3997  /* We've just killed the intro point, nothing left to do. */
3998  continue;
3999  }
4000 
4001  /* The intro point is still alive so let's try to use it again because
4002  * we have a published descriptor containing it. Keep the intro point
4003  * in the intro_nodes list because it's still valid, we are rebuilding
4004  * a circuit to it. */
4005  if (retry_nodes) {
4006  smartlist_add(retry_nodes, intro);
4007  }
4008  }
4009  /* else, the circuit is valid so in both cases, node being alive or not,
4010  * we leave the circuit and intro point object as is. Closing the
4011  * circuit here would leak new consensus timing and freeing the intro
4012  * point object would make the intro circuit unusable. */
4013 
4014  /* Now, check if intro point should expire. If it does, queue it so
4015  * it can be cleaned up once it has been replaced properly. */
4016  if (intro_point_should_expire_now(intro, now)) {
4017  log_info(LD_REND, "Expiring %s as intro point for %s.",
4018  safe_str_client(extend_info_describe(intro->extend_info)),
4019  safe_str_client(service->service_id));
4020  /* We might have put it in the retry list if so, undo. */
4021  if (retry_nodes) {
4022  smartlist_remove(retry_nodes, intro);
4023  }
4024  smartlist_add(service->expiring_nodes, intro);
4025  SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4026  /* Intro point is expired, we need a new one thus don't consider it
4027  * anymore has a valid established intro point. */
4028  intro->circuit_established = 0;
4029  }
4030  } SMARTLIST_FOREACH_END(intro);
4031 }
4032 
4036 void
4038 {
4039  rend_service_t *service;
4040  const char *onion_address;
4041 
4042  tor_assert(rend_data);
4043 
4044  onion_address = rend_data_get_address(rend_data);
4045 
4046  service = rend_service_get_by_service_id(onion_address);
4047  if (service == NULL) {
4048  return;
4049  }
4050 
4051  SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
4052  intro) {
4053  origin_circuit_t *intro_circ =
4054  find_intro_circuit(intro, service->pk_digest);
4055  if (intro_circ != NULL) {
4056  circuit_mark_for_close(TO_CIRCUIT(intro_circ),
4057  END_CIRC_REASON_FINISHED);
4058  }
4059  SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
4060  rend_intro_point_free(intro);
4061  } SMARTLIST_FOREACH_END(intro);
4062 }
4063 
4067 static int
4068 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
4069 {
4070  /* Allow all but one of the initial connections to fail and be
4071  * retried. (If all fail, we *want* to wait, because something is broken.) */
4072  tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
4073 
4074  /* For the normal use case, 3 intro points plus 2 extra for performance and
4075  * allow that twice because once every 24h or so, we can do it twice for two
4076  * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
4077  * 12 allowed attempts for one period. */
4078  return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
4079 }
4080 
4089 void
4091 {
4092  int i;
4093  const or_options_t *options = get_options();
4094  /* Are we in single onion mode? */
4095  const int allow_direct = rend_service_allow_non_anonymous_connection(
4096  get_options());
4097  /* List of nodes we need to _exclude_ when choosing a new node to
4098  * establish an intro point to. */
4099  smartlist_t *exclude_nodes;
4100  /* List of nodes we need to retry to build a circuit on them because the
4101  * node is valid but circuit died. */
4102  smartlist_t *retry_nodes;
4103 
4104  if (!have_completed_a_circuit())
4105  return;
4106 
4107  exclude_nodes = smartlist_new();
4108  retry_nodes = smartlist_new();
4109 
4110  SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
4111  int r;
4112  /* Number of intro points we want to open and add to the intro nodes
4113  * list of the service. */
4114  unsigned int n_intro_points_to_open;
4115  /* Have an unsigned len so we can use it to compare values else gcc is
4116  * not happy with unmatching signed comparaison. */
4117  unsigned int intro_nodes_len;
4118  /* Different service are allowed to have the same introduction point as
4119  * long as they are on different circuit thus why we clear this list. */
4120  smartlist_clear(exclude_nodes);
4121  smartlist_clear(retry_nodes);
4122 
4123  /* Cleanup the invalid intro points and save the node objects, if any,
4124  * in the exclude_nodes and retry_nodes lists. */
4125  remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
4126 
4127  /* This retry period is important here so we don't stress circuit
4128  * creation. */
4129 
4130  if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
4131  /* One period has elapsed:
4132  * - if we stopped, we can try building circuits again,
4133  * - if we haven't, we reset the circuit creation counts. */
4134  rend_log_intro_limit(service, LOG_INFO);
4135  service->intro_period_started = now;
4136  service->n_intro_circuits_launched = 0;
4137  } else if (service->n_intro_circuits_launched >=
4139  service->n_intro_points_wanted)) {
4140  /* We have failed too many times in this period; wait for the next
4141  * one before we try to initiate any more connections. */
4142  rend_log_intro_limit(service, LOG_WARN);
4143  continue;
4144  }
4145 
4146  /* Let's try to rebuild circuit on the nodes we want to retry on. */
4147  SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
4148  r = rend_service_launch_establish_intro(service, intro);
4149  if (r < 0) {
4150  log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4151  safe_str_client(extend_info_describe(intro->extend_info)),
4152  safe_str_client(service->service_id));
4153  /* Unable to launch a circuit to that intro point, remove it from
4154  * the valid list so we can create a new one. */
4155  smartlist_remove(service->intro_nodes, intro);
4156  rend_intro_point_free(intro);
4157  continue;
4158  }
4159  intro->circuit_retries++;
4160  } SMARTLIST_FOREACH_END(intro);
4161 
4162  /* Avoid mismatched signed comparaison below. */
4163  intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
4164 
4165  /* Quiescent state, we have more or the equal amount of wanted node for
4166  * this service. Proceed to the next service. We can have more nodes
4167  * because we launch extra preemptive circuits if our intro nodes list was
4168  * originally empty for performance reasons. */
4169  if (intro_nodes_len >= service->n_intro_points_wanted) {
4170  continue;
4171  }
4172 
4173  /* Number of intro points we want to open which is the wanted amount minus
4174  * the current amount of valid nodes. We know that this won't underflow
4175  * because of the check above. */
4176  n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
4177  if (intro_nodes_len == 0) {
4178  /* We want to end up with n_intro_points_wanted intro points, but if
4179  * we have no intro points at all (chances are they all cycled or we
4180  * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4181  * and use the first n_intro_points_wanted that complete. See proposal
4182  * #155, section 4 for the rationale of this which is purely for
4183  * performance.
4184  *
4185  * The ones after the first n_intro_points_to_open will be converted
4186  * to 'general' internal circuits in rend_service_intro_has_opened(),
4187  * and then we'll drop them from the list of intro points. */
4188  n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4189  }
4190 
4191  for (i = 0; i < (int) n_intro_points_to_open; i++) {
4192  const node_t *node;
4193  rend_intro_point_t *intro;
4194  router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4195  router_crn_flags_t direct_flags = flags;
4196  direct_flags |= CRN_PREF_ADDR;
4197  direct_flags |= CRN_DIRECT_CONN;
4198 
4199  node = router_choose_random_node(exclude_nodes,
4200  options->ExcludeNodes,
4201  allow_direct ? direct_flags : flags);
4202  /* If we are in single onion mode, retry node selection for a 3-hop
4203  * path */
4204  if (allow_direct && !node) {
4205  log_info(LD_REND,
4206  "Unable to find an intro point that we can connect to "
4207  "directly for %s, falling back to a 3-hop path.",
4208  safe_str_client(service->service_id));
4209  node = router_choose_random_node(exclude_nodes,
4210  options->ExcludeNodes, flags);
4211  }
4212 
4213  if (!node) {
4214  log_warn(LD_REND,
4215  "We only have %d introduction points established for %s; "
4216  "wanted %u.",
4217  smartlist_len(service->intro_nodes),
4218  safe_str_client(service->service_id),
4219  n_intro_points_to_open);
4220  break;
4221  }
4222  /* Add the chosen node to the exclusion list in order to avoid picking
4223  * it again in the next iteration. */
4224  smartlist_add(exclude_nodes, (void*)node);
4225  intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4226  /* extend_info is for clients, so we want the multi-hop primary ORPort,
4227  * even if we are a single onion service and intend to connect to it
4228  * directly ourselves. */
4229  intro->extend_info = extend_info_from_node(node, 0);
4230  if (BUG(intro->extend_info == NULL)) {
4231  tor_free(intro);
4232  break;
4233  }
4234  intro->intro_key = crypto_pk_new();
4235  const int fail = crypto_pk_generate_key(intro->intro_key);
4236  tor_assert(!fail);
4237  intro->time_published = -1;
4238  intro->time_to_expire = -1;
4239  intro->max_introductions =
4241  INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4242  smartlist_add(service->intro_nodes, intro);
4243  log_info(LD_REND, "Picked router %s as an intro point for %s.",
4244  safe_str_client(node_describe(node)),
4245  safe_str_client(service->service_id));
4246  /* Establish new introduction circuit to our chosen intro point. */
4247  r = rend_service_launch_establish_intro(service, intro);
4248  if (r < 0) {
4249  log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4250  safe_str_client(extend_info_describe(intro->extend_info)),
4251  safe_str_client(service->service_id));
4252  /* This funcion will be called again by the main loop so this intro
4253  * point without a intro circuit will be retried on or removed after
4254  * a maximum number of attempts. */
4255  }
4256  }
4257  } SMARTLIST_FOREACH_END(service);
4258  smartlist_free(exclude_nodes);
4259  smartlist_free(retry_nodes);
4260 }
4261 
4262 #define MIN_REND_INITIAL_POST_DELAY (30)
4263 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4264 
4273 void
4275 {
4276  int i;
4277  rend_service_t *service;
4278  const or_options_t *options = get_options();
4279  int rendpostperiod = options->RendPostPeriod;
4280  int rendinitialpostdelay = (options->TestingTorNetwork ?
4281  MIN_REND_INITIAL_POST_DELAY_TESTING :
4282  MIN_REND_INITIAL_POST_DELAY);
4283 
4284  for (i=0; i < smartlist_len(rend_service_list); ++i) {
4285  service = smartlist_get(rend_service_list, i);
4286  if (!service->next_upload_time) { /* never been uploaded yet */
4287  /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4288  * the descriptor is stable before being published. See comment below. */
4289  service->next_upload_time =
4290  now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4291  /* Single Onion Services prioritise availability over hiding their
4292  * startup time, as their IP address is publicly discoverable anyway.
4293  */
4294  if (rend_service_reveal_startup_time(options)) {
4295  service->next_upload_time = now + rendinitialpostdelay;
4296  }
4297  }
4298  /* Does every introduction points have been established? */
4299  unsigned int intro_points_ready =
4300  count_established_intro_points(service) >=
4301  service->n_intro_points_wanted;
4302  if (intro_points_ready &&
4303  (service->next_upload_time < now ||
4304  (service->desc_is_dirty &&
4305  service->desc_is_dirty < now-rendinitialpostdelay))) {
4306  /* if it's time, or if the directory servers have a wrong service
4307  * descriptor and ours has been stable for rendinitialpostdelay seconds,
4308  * upload a new one of each format. */
4310  upload_service_descriptor(service);
4311  }
4312  }
4313 }
4314 
4319 
4323 void
4325 {
4327 }
4328 
4332 void
4334 {
4335  int i;
4336  rend_service_t *service;
4337 
4339  return;
4341 
4342  if (!get_options()->PublishHidServDescriptors)
4343  return;
4344 
4345  for (i=0; i < smartlist_len(rend_service_list); ++i) {
4346  service = smartlist_get(rend_service_list, i);
4347  if (service->desc && !service->desc->all_uploads_performed) {
4348  /* If we failed in uploading a descriptor last time, try again *without*
4349  * updating the descriptor's contents. */
4350  upload_service_descriptor(service);
4351  }
4352  }
4353 }
4354 
4358 void
4360 {
4361  int i,j;
4362  rend_service_t *service;
4363  rend_intro_point_t *intro;
4364  const char *safe_name;
4365  origin_circuit_t *circ;
4366 
4367  for (i=0; i < smartlist_len(rend_service_list); ++i) {
4368  service = smartlist_get(rend_service_list, i);
4369  tor_log(severity, LD_GENERAL, "Service configured in %s:",
4370  rend_service_escaped_dir(service));
4371  for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
4372  intro = smartlist_get(service->intro_nodes, j);
4373  safe_name = safe_str_client(intro->extend_info->nickname);
4374 
4375  circ = find_intro_circuit(intro, service->pk_digest);
4376  if (!circ) {
4377  tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4378  j, safe_name);
4379  continue;
4380  }
4381  tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4382  j, safe_name, circuit_state_to_string(circ->base_.state));
4383  }
4384  }
4385 }
4386 
4393 int
4395  origin_circuit_t *circ)
4396 {
4397  rend_service_t *service;
4398  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4399  const char *rend_pk_digest;
4400 
4402  tor_assert(circ->rend_data);
4403  log_debug(LD_REND,"beginning to hunt for addr/port");
4404  rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
4406  rend_pk_digest, REND_SERVICE_ID_LEN);
4407  service = rend_service_get_by_pk_digest(rend_pk_digest);
4408  if (!service) {
4409  log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4410  "rendezvous circuit %u; closing.",
4411  serviceid, (unsigned)circ->base_.n_circ_id);
4412  return -2;
4413  }
4414  if (service->max_streams_per_circuit > 0) {
4415  /* Enforce the streams-per-circuit limit, and refuse to provide a
4416  * mapping if this circuit will exceed the limit. */
4417 #define MAX_STREAM_WARN_INTERVAL 600
4418  static struct ratelim_t stream_ratelim =
4419  RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4420  if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4421  log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4422  "Maximum streams per circuit limit reached on rendezvous "
4423  "circuit %u; %s. Circuit has %d out of %d streams.",
4424  (unsigned)circ->base_.n_circ_id,
4425  service->max_streams_close_circuit ?
4426  "closing circuit" :
4427  "ignoring open stream request",
4428  circ->rend_data->nr_streams,
4429  service->max_streams_per_circuit);
4430  return service->max_streams_close_circuit ? -2 : -1;
4431  }
4432  }
4433 
4434  if (hs_set_conn_addr_port(service->ports, conn) == 0) {
4435  /* Successfully set the port to the connection. We are done. */
4436  return 0;
4437  }
4438 
4439  log_info(LD_REND,
4440  "No virtual port mapping exists for port %d on service %s",
4441  conn->base_.port, serviceid);
4442 
4443  if (service->allow_unknown_ports)
4444  return -1;
4445  else
4446  return -2;
4447 }
4448 
4449 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4450  */
4451 static int
4452 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4453 {
4454  /* !! is used to make these options boolean */
4455  return (!! options->HiddenServiceSingleHopMode ==
4456  !! options->HiddenServiceNonAnonymousMode);
4457 }
4458 
4459 /* Do the options allow onion services to make direct (non-anonymous)
4460  * connections to introduction or rendezvous points?
4461  * Must only be called after options_validate_single_onion() has successfully
4462  * checked onion service option consistency.
4463  * Returns true if tor is in HiddenServiceSingleHopMode. */
4464 int
4465 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4466 {
4467  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4468  return options->HiddenServiceSingleHopMode ? 1 : 0;
4469 }
4470 
4471 /* Do the options allow us to reveal the exact startup time of the onion
4472  * service?
4473  * Single Onion Services prioritise availability over hiding their
4474  * startup time, as their IP address is publicly discoverable anyway.
4475  * Must only be called after options_validate_single_onion() has successfully
4476  * checked onion service option consistency.
4477  * Returns true if tor is in non-anonymous hidden service mode. */
4478 int
4479 rend_service_reveal_startup_time(const or_options_t *options)
4480 {
4481  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4482  return rend_service_non_anonymous_mode_enabled(options);
4483 }
4484 
4485 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4486  * config option?
4487  * Must only be called after options_validate_single_onion() has successfully
4488  * checked onion service option consistency.
4489  */
4490 int
4491 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4492 {
4493  tor_assert(rend_service_non_anonymous_mode_consistent(options));
4494  return options->HiddenServiceNonAnonymousMode ? 1 : 0;
4495 }
4496 
4497 #ifdef TOR_UNIT_TESTS
4498 
4499 STATIC void
4500 set_rend_service_list(smartlist_t *new_list)
4501 {
4502  rend_service_list = new_list;
4503 }
4504 
4505 STATIC void
4506 set_rend_rend_service_staging_list(smartlist_t *new_list)
4507 {
4508  rend_service_staging_list = new_list;
4509 }
4510 
4511 #endif /* defined(TOR_UNIT_TESTS) */
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
int crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:478
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition: circuituse.h:39
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:873
static int rend_service_derive_key_digests(struct rend_service_t *s)
Definition: rendservice.c: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:4037
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:289
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:3450
Common functions for using (pseudo-)random number generators.
Definition: node_st.h:28
#define INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS
Definition: or.h:1066
Headers for crypto_dh.c.
static smartlist_t * rend_service_list
Definition: rendservice.c:128
static unsigned int count_intro_point_circuits(const rend_service_t *service)
Definition: rendservice.c:3182
#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:2977
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:4090
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:154
crypt_path_reference_t * service_pending_final_cpath_ref
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:73
#define INTRO_POINT_LIFETIME_MAX_SECONDS
Definition: or.h:1082
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
void rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
Definition: rendservice.c:3012
#define LD_GENERAL
Definition: log.h:59
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:4318
#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:42
Header file for describe.c.
Header file for nodelist.c.
#define CIRCWINDOW_START
Definition: or.h:501
void rend_service_free_intro_(rend_intro_cell_t *request)
Definition: rendservice.c:2303
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:3899
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:632
#define MAX_INTRO_POINT_CIRCUIT_RETRIES
Definition: or.h:1087
#define NUM_INTRO_POINTS_MAX
Definition: hs_common.h:34
Header file for directory.c.
#define MAX_REND_TIMEOUT
Definition: hs_common.h:49
void smartlist_add(smartlist_t *sl, void *element)
#define REND_DESC_COOKIE_LEN_BASE64
Definition: or.h:370
int rend_service_decrypt_intro(rend_intro_cell_t *intro, crypto_pk_t *key, char **err_msg_out)
Definition: rendservice.c:2748
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:3579
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:354
#define MAX_NICKNAME_LEN
Definition: or.h:113
struct directory_request_t directory_request_t
Definition: dirclient.h:52
#define TO_CIRCUIT(x)
Definition: or.h:947
Header file for config.c.
Header file for nickname.c.
Header file for replaycache.c.
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:60
void smartlist_uniq_strings(smartlist_t *sl)
Definition: smartlist.c:574
#define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
Definition: circuitlist.h:102
void rend_service_intro_has_opened(origin_circuit_t *circuit)
Definition: rendservice.c:3257
int crypto_rand_int_range(unsigned int min, unsigned int max)
uint16_t port
#define tor_free(p)
Definition: malloc.h:52
int is_legal_nickname_or_hexdigest(const char *s)
Definition: nickname.c:31
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1340
#define LOG_NOTICE
Definition: log.h:47
int replaycache_add_test_and_elapsed(replaycache_t *r, const void *data, size_t len, time_t *elapsed)
Definition: replaycache.c:195
#define SMARTLIST_DEL_CURRENT(sl, var)
Header file for mainloop.c.
static int rend_service_load_keys(struct rend_service_t *s)
Definition: rendservice.c: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:3774
int tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
Definition: resolve.c:184
#define REND_CLIENTNAME_MAX_LEN
Definition: or.h:395
rend_auth_type_t
Definition: or.h:402
FILE * start_writing_to_stdio_file(const char *fname, int open_flags, int mode, open_file_t **data_out)
Definition: files.c:382
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:49
static rend_intro_point_t * find_expiring_intro_point(struct rend_service_t *service, origin_circuit_t *circ)
Definition: rendservice.c:3609
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:3627
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:6742
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:2214
#define LD_CIRC
Definition: log.h:79
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:2610
void rend_consider_services_upload(time_t now)
Definition: rendservice.c:4274
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:1168
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:84
circid_t n_circ_id
Definition: circuit_st.h:67
char nickname[MAX_HEX_NICKNAME_LEN+1]
#define DIGEST_LEN
Definition: digest_sizes.h:20
static int rend_add_service(smartlist_t *service_list, rend_service_t *service)
Definition: rendservice.c:338
void rend_hsdir_routers_changed(void)
Definition: rendservice.c:4324
#define PK_PKCS1_OAEP_PADDING
Definition: crypto_rsa.h:27
const char * node_describe(const node_t *node)
Definition: describe.c:101
rend_service_port_config_t * rend_service_parse_port_config(const char *string, const char *sep, char **err_msg_out)
Definition: rendservice.c: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:2871
struct crypto_pk_t * intro_key
void smartlist_remove(smartlist_t *sl, const void *element)
static uint16_t get_uint16(const void *cp)
Definition: bytes.h:37
#define NUM_INTRO_POINTS_EXTRA
Definition: hs_common.h:37
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:719
#define LOG_WARN
Definition: log.h:50
hs_service_add_ephemeral_status_t
Definition: hs_common.h:140
extend_info_t * extend_info_dup(extend_info_t *info)
const node_t * router_choose_random_node(smartlist_t *excludedsmartlist, routerset_t *excludedset, router_crn_flags_t flags)
Definition: node_select.c: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:3890
const char * routerstatus_describe(const routerstatus_t *rs)
Definition: describe.c:134
static int rend_check_authorization(rend_service_t *service, const char *descriptor_cookie, size_t cookie_len)
Definition: rendservice.c:1799
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:277
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:81
Header file for circuitlist.c.
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
Header file for rendservice.c.
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
Definition: circuitbuild.c: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:3167
int rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len)
Definition: rendservice.c:3389
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:53
#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:67
smartlist_t * routerstatus_list
int is_legal_nickname(const char *s)
Definition: nickname.c:19
static void rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
Definition: rendservice.c: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:2508
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:229
Header file for relay.c.
char identity_digest[DIGEST_LEN]
#define SMARTLIST_FOREACH(sl, type, var, cmd)
const char * escaped(const char *s)
Definition: escape.c:126
static struct rend_service_t * rend_service_get_by_pk_digest(const char *digest)
Definition: rendservice.c: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:2372
static void remove_invalid_intro_points(rend_service_t *service, smartlist_t *exclude_nodes, smartlist_t *retry_nodes, time_t now)
Definition: rendservice.c:3946
#define log_fn(severity, domain, args,...)
Definition: log.h:272
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:39
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:2435
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:4068
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3062
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:4359
#define REND_COOKIE_LEN
Definition: or.h:399
extend_info_t * chosen_exit
ssize_t crypto_dh_compute_secret(int severity, crypto_dh_t *dh, const char *pubkey, size_t pubkey_len, char *secret_out, size_t secret_bytes_out)
Definition: crypto_dh.c:79
#define INTRO_POINT_LIFETIME_MIN_SECONDS
Definition: or.h:1077
tor_addr_t addr
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
origin_circuit_t * circuit_get_next_by_pk_and_purpose(origin_circuit_t *start, const uint8_t *digest, uint8_t purpose)
Definition: circuitlist.c:1804
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:903
static void rend_authorized_client_free_void(void *authorized_client)
Definition: rendservice.c:208
int rend_service_set_connection_addr_port(edge_connection_t *conn, origin_circuit_t *circ)
Definition: rendservice.c:4394
#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:2732
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:69
void smartlist_clear(smartlist_t *sl)
#define REND_DESC_COOKIE_LEN
Definition: or.h:366
static int rend_service_launch_establish_intro(rend_service_t *service, rend_intro_point_t *intro)
Definition: rendservice.c:3080
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:83
void directory_request_set_payload(directory_request_t *req, const char *payload, size_t payload_len)
Definition: dirclient.c:1054
#define LD_CONFIG
Definition: log.h:65
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1103
int have_completed_a_circuit(void)
Definition: mainloop.c:218
void rend_consider_descriptor_republication(void)
Definition: rendservice.c:4333
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:3660
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
char * tor_dup_ip(uint32_t addr)
Definition: address.c:1890