Tor  0.4.3.1-alpha-dev
rendcache.c
Go to the documentation of this file.
1 /* Copyright (c) 2015-2020, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
3 
4 /**
5  * \file rendcache.c
6  * \brief Hidden service descriptor cache.
7  **/
8 
9 #define RENDCACHE_PRIVATE
10 #include "feature/rend/rendcache.h"
11 
12 #include "app/config/config.h"
13 #include "feature/stats/rephist.h"
16 #include "feature/rend/rendparse.h"
17 
18 #include "core/or/extend_info_st.h"
21 
22 #include "lib/ctime/di_ops.h"
23 
24 /** Map from service id (as generated by rend_get_service_id) to
25  * rend_cache_entry_t. */
26 STATIC strmap_t *rend_cache = NULL;
27 
28 /** Map from service id to rend_cache_entry_t; only for hidden services. */
29 static strmap_t *rend_cache_local_service = NULL;
30 
31 /** Map from descriptor id to rend_cache_entry_t; only for hidden service
32  * directories. */
33 STATIC digestmap_t *rend_cache_v2_dir = NULL;
34 
35 /** (Client side only) Map from service id to rend_cache_failure_t. This
36  * cache is used to track intro point(IP) failures so we know when to keep
37  * or discard a new descriptor we just fetched. Here is a description of the
38  * cache behavior.
39  *
40  * Everytime tor discards an IP (ex: receives a NACK), we add an entry to
41  * this cache noting the identity digest of the IP and it's failure type for
42  * the service ID. The reason we indexed this cache by service ID is to
43  * differentiate errors that can occur only for a specific service like a
44  * NACK for instance. It applies for one but maybe not for the others.
45  *
46  * Once a service descriptor is fetched and considered valid, each IP is
47  * looked up in this cache and if present, it is discarded from the fetched
48  * descriptor. At the end, all IP(s) in the cache, for a specific service
49  * ID, that were NOT present in the descriptor are removed from this cache.
50  * Which means that if at least one IP was not in this cache, thus usable,
51  * it's considered a new descriptor so we keep it. Else, if all IPs were in
52  * this cache, we discard the descriptor as it's considered unusable.
53  *
54  * Once a descriptor is removed from the rend cache or expires, the entry
55  * in this cache is also removed for the service ID.
56  *
57  * This scheme allows us to not rely on the descriptor's timestamp (which
58  * is rounded down to the hour) to know if we have a newer descriptor. We
59  * only rely on the usability of intro points from an internal state. */
60 STATIC strmap_t *rend_cache_failure = NULL;
61 
62 /* DOCDOC */
63 STATIC size_t rend_cache_total_allocation = 0;
64 
65 /** Initializes the service descriptor cache.
66 */
67 void
69 {
70  rend_cache = strmap_new();
71  rend_cache_v2_dir = digestmap_new();
72  rend_cache_local_service = strmap_new();
73  rend_cache_failure = strmap_new();
74 }
75 
76 /** Return the approximate number of bytes needed to hold <b>e</b>. */
77 STATIC size_t
79 {
80  if (!e)
81  return 0;
82 
83  /* This doesn't count intro_nodes or key size */
84  return sizeof(*e) + e->len + sizeof(*e->parsed);
85 }
86 
87 /* DOCDOC */
88 size_t
89 rend_cache_get_total_allocation(void)
90 {
91  return rend_cache_total_allocation;
92 }
93 
94 /** Decrement the total bytes attributed to the rendezvous cache by n. */
95 void
97 {
98  static int have_underflowed = 0;
99 
100  if (rend_cache_total_allocation >= n) {
101  rend_cache_total_allocation -= n;
102  } else {
103  rend_cache_total_allocation = 0;
104  if (! have_underflowed) {
105  have_underflowed = 1;
106  log_warn(LD_BUG, "Underflow in rend_cache_decrement_allocation");
107  }
108  }
109 }
110 
111 /** Increase the total bytes attributed to the rendezvous cache by n. */
112 void
114 {
115  static int have_overflowed = 0;
116  if (rend_cache_total_allocation <= SIZE_MAX - n) {
117  rend_cache_total_allocation += n;
118  } else {
119  rend_cache_total_allocation = SIZE_MAX;
120  if (! have_overflowed) {
121  have_overflowed = 1;
122  log_warn(LD_BUG, "Overflow in rend_cache_increment_allocation");
123  }
124  }
125 }
126 
127 /** Helper: free a rend cache failure intro object. */
128 STATIC void
130 {
131  if (entry == NULL) {
132  return;
133  }
134  tor_free(entry);
135 }
136 
137 static void
138 rend_cache_failure_intro_entry_free_void(void *entry)
139 {
141 }
142 
143 /** Allocate a rend cache failure intro object and return it. <b>failure</b>
144  * is set into the object. This function can not fail. */
146 rend_cache_failure_intro_entry_new(rend_intro_point_failure_t failure)
147 {
148  rend_cache_failure_intro_t *entry = tor_malloc(sizeof(*entry));
149  entry->failure_type = failure;
150  entry->created_ts = time(NULL);
151  return entry;
152 }
153 
154 /** Helper: free a rend cache failure object. */
155 STATIC void
157 {
158  if (entry == NULL) {
159  return;
160  }
161 
162  /* Free and remove every intro failure object. */
163  digestmap_free(entry->intro_failures,
164  rend_cache_failure_intro_entry_free_void);
165 
166  tor_free(entry);
167 }
168 
169 /** Helper: deallocate a rend_cache_failure_t. (Used with strmap_free(),
170  * which requires a function pointer whose argument is void*). */
171 STATIC void
173 {
175 }
176 
177 /** Allocate a rend cache failure object and return it. This function can
178  * not fail. */
181 {
182  rend_cache_failure_t *entry = tor_malloc(sizeof(*entry));
183  entry->intro_failures = digestmap_new();
184  return entry;
185 }
186 
187 /** Remove failure cache entry for the service ID in the given descriptor
188  * <b>desc</b>. */
189 STATIC void
191 {
192  char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
193  rend_cache_failure_t *entry;
194 
195  if (desc == NULL) {
196  return;
197  }
198  if (rend_get_service_id(desc->pk, service_id) < 0) {
199  return;
200  }
201  entry = strmap_get_lc(rend_cache_failure, service_id);
202  if (entry != NULL) {
204  rend_cache_failure_entry_free(entry);
205  }
206 }
207 
208 /** Helper: free storage held by a single service descriptor cache entry. */
209 STATIC void
211 {
212  if (!e)
213  return;
215  /* We are about to remove a descriptor from the cache so remove the entry
216  * in the failure cache. */
218  rend_service_descriptor_free(e->parsed);
219  tor_free(e->desc);
220  tor_free(e);
221 }
222 
223 /** Helper: deallocate a rend_cache_entry_t. (Used with strmap_free(), which
224  * requires a function pointer whose argument is void*). */
225 static void
227 {
229 }
230 
231 /** Check if a failure cache entry exists for the given intro point. */
232 bool
233 rend_cache_intro_failure_exists(const char *service_id,
234  const uint8_t *intro_identity)
235 {
236  tor_assert(service_id);
237  tor_assert(intro_identity);
238 
239  return cache_failure_intro_lookup(intro_identity, service_id, NULL);
240 }
241 
242 /** Free all storage held by the service descriptor cache. */
243 void
245 {
250  rend_cache = NULL;
251  rend_cache_v2_dir = NULL;
253  rend_cache_failure = NULL;
254  rend_cache_total_allocation = 0;
255 }
256 
257 /** Remove all entries that re REND_CACHE_FAILURE_MAX_AGE old. This is
258  * called every second.
259  *
260  * We have to clean these regurlarly else if for whatever reasons an hidden
261  * service goes offline and a client tries to connect to it during that
262  * time, a failure entry is created and the client will be unable to connect
263  * for a while even though the service has return online. */
264 void
266 {
267  time_t cutoff = now - REND_CACHE_FAILURE_MAX_AGE;
268  STRMAP_FOREACH_MODIFY(rend_cache_failure, key,
269  rend_cache_failure_t *, ent) {
270  /* Free and remove every intro failure object that match the cutoff. */
271  DIGESTMAP_FOREACH_MODIFY(ent->intro_failures, ip_key,
272  rend_cache_failure_intro_t *, ip_ent) {
273  if (ip_ent->created_ts < cutoff) {
274  rend_cache_failure_intro_entry_free(ip_ent);
275  MAP_DEL_CURRENT(ip_key);
276  }
278  /* If the entry is now empty of intro point failures, remove it. */
279  if (digestmap_isempty(ent->intro_failures)) {
280  rend_cache_failure_entry_free(ent);
281  MAP_DEL_CURRENT(key);
282  }
283  } STRMAP_FOREACH_END;
284 }
285 
286 /** Removes all old entries from the client or service descriptor cache.
287 */
288 void
289 rend_cache_clean(time_t now, rend_cache_type_t cache_type)
290 {
291  strmap_iter_t *iter;
292  const char *key;
293  void *val;
294  rend_cache_entry_t *ent;
295  time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
296  strmap_t *cache = NULL;
297 
298  if (cache_type == REND_CACHE_TYPE_CLIENT) {
299  cache = rend_cache;
300  } else if (cache_type == REND_CACHE_TYPE_SERVICE) {
301  cache = rend_cache_local_service;
302  }
303  tor_assert(cache);
304 
305  for (iter = strmap_iter_init(cache); !strmap_iter_done(iter); ) {
306  strmap_iter_get(iter, &key, &val);
307  ent = (rend_cache_entry_t*)val;
308  if (ent->parsed->timestamp < cutoff) {
309  iter = strmap_iter_next_rmv(cache, iter);
310  rend_cache_entry_free(ent);
311  } else {
312  iter = strmap_iter_next(cache, iter);
313  }
314  }
315 }
316 
317 /** Remove ALL entries from the rendezvous service descriptor cache.
318 */
319 void
321 {
322  if (rend_cache) {
323  log_info(LD_REND, "Purging HS v2 descriptor cache");
325  }
326  rend_cache = strmap_new();
327 }
328 
329 /** Remove ALL entries from the failure cache. This is also called when a
330  * NEWNYM signal is received. */
331 void
333 {
334  if (rend_cache_failure) {
335  log_info(LD_REND, "Purging HS v2 failure cache");
337  }
338  rend_cache_failure = strmap_new();
339 }
340 
341 /** Lookup the rend failure cache using a relay identity digest in
342  * <b>identity</b> which has DIGEST_LEN bytes and service ID <b>service_id</b>
343  * which is a null-terminated string. If found, the intro failure is set in
344  * <b>intro_entry</b> else it stays untouched. Return 1 iff found else 0. */
345 STATIC int
346 cache_failure_intro_lookup(const uint8_t *identity, const char *service_id,
347  rend_cache_failure_intro_t **intro_entry)
348 {
349  rend_cache_failure_t *elem;
350  rend_cache_failure_intro_t *intro_elem;
351 
353 
354  if (intro_entry) {
355  *intro_entry = NULL;
356  }
357 
358  /* Lookup descriptor and return it. */
359  elem = strmap_get_lc(rend_cache_failure, service_id);
360  if (elem == NULL) {
361  goto not_found;
362  }
363  intro_elem = digestmap_get(elem->intro_failures, (char *) identity);
364  if (intro_elem == NULL) {
365  goto not_found;
366  }
367  if (intro_entry) {
368  *intro_entry = intro_elem;
369  }
370  return 1;
371  not_found:
372  return 0;
373 }
374 
375 /** Allocate a new cache failure intro object and copy the content from
376  * <b>entry</b> to this newly allocated object. Return it. */
379 {
380  rend_cache_failure_intro_t *ent_dup =
381  rend_cache_failure_intro_entry_new(entry->failure_type);
382  ent_dup->created_ts = entry->created_ts;
383  return ent_dup;
384 }
385 
386 /** Add an intro point failure to the failure cache using the relay
387  * <b>identity</b> and service ID <b>service_id</b>. Record the
388  * <b>failure</b> in that object. */
389 STATIC void
390 cache_failure_intro_add(const uint8_t *identity, const char *service_id,
391  rend_intro_point_failure_t failure)
392 {
393  rend_cache_failure_t *fail_entry;
394  rend_cache_failure_intro_t *entry, *old_entry;
395 
396  /* Make sure we have a failure object for this service ID and if not,
397  * create it with this new intro failure entry. */
398  fail_entry = strmap_get_lc(rend_cache_failure, service_id);
399  if (fail_entry == NULL) {
400  fail_entry = rend_cache_failure_entry_new();
401  /* Add failure entry to global rend failure cache. */
402  strmap_set_lc(rend_cache_failure, service_id, fail_entry);
403  }
404  entry = rend_cache_failure_intro_entry_new(failure);
405  old_entry = digestmap_set(fail_entry->intro_failures,
406  (char *) identity, entry);
407  /* This _should_ be NULL, but in case it isn't, free it. */
408  rend_cache_failure_intro_entry_free(old_entry);
409 }
410 
411 /** Using a parsed descriptor <b>desc</b>, check if the introduction points
412  * are present in the failure cache and if so they are removed from the
413  * descriptor and kept into the failure cache. Then, each intro points that
414  * are NOT in the descriptor but in the failure cache for the given
415  * <b>service_id</b> are removed from the failure cache. */
416 STATIC void
418  const char *service_id)
419 {
420  rend_cache_failure_t *new_entry, *cur_entry;
421  /* New entry for the service ID that will be replacing the one in the
422  * failure cache since we have a new descriptor. In the case where all
423  * intro points are removed, we are assured that the new entry is the same
424  * as the current one. */
425  new_entry = tor_malloc(sizeof(*new_entry));
426  new_entry->intro_failures = digestmap_new();
427 
428  tor_assert(desc);
429 
431  int found;
433  const uint8_t *identity =
434  (uint8_t *) intro->extend_info->identity_digest;
435 
436  found = cache_failure_intro_lookup(identity, service_id, &entry);
437  if (found) {
438  /* Dup here since it will be freed at the end when removing the
439  * original entry in the cache. */
441  /* This intro point is in our cache, discard it from the descriptor
442  * because chances are that it's unusable. */
443  SMARTLIST_DEL_CURRENT(desc->intro_nodes, intro);
444  /* Keep it for our new entry. */
445  digestmap_set(new_entry->intro_failures, (char *) identity, ent_dup);
446  /* Only free it when we're done looking at it. */
447  rend_intro_point_free(intro);
448  continue;
449  }
450  } SMARTLIST_FOREACH_END(intro);
451 
452  /* Swap the failure entry in the cache and free the current one. */
453  cur_entry = strmap_get_lc(rend_cache_failure, service_id);
454  if (cur_entry != NULL) {
455  rend_cache_failure_entry_free(cur_entry);
456  }
457  strmap_set_lc(rend_cache_failure, service_id, new_entry);
458 }
459 
460 /** Note down an intro failure in the rend failure cache using the type of
461  * failure in <b>failure</b> for the relay identity digest in
462  * <b>identity</b> and service ID <b>service_id</b>. If an entry already
463  * exists in the cache, the failure type is changed with <b>failure</b>. */
464 void
465 rend_cache_intro_failure_note(rend_intro_point_failure_t failure,
466  const uint8_t *identity,
467  const char *service_id)
468 {
469  int found;
471 
472  found = cache_failure_intro_lookup(identity, service_id, &entry);
473  if (!found) {
474  cache_failure_intro_add(identity, service_id, failure);
475  } else {
476  /* Replace introduction point failure with this one. */
477  entry->failure_type = failure;
478  }
479 }
480 
481 /** Remove all old v2 descriptors and those for which this hidden service
482  * directory is not responsible for any more. The cutoff is the time limit for
483  * which we want to keep the cache entry. In other words, any entry created
484  * before will be removed. */
485 size_t
487 {
488  digestmap_iter_t *iter;
489  size_t bytes_removed = 0;
490 
491  for (iter = digestmap_iter_init(rend_cache_v2_dir);
492  !digestmap_iter_done(iter); ) {
493  const char *key;
494  void *val;
495  rend_cache_entry_t *ent;
496  digestmap_iter_get(iter, &key, &val);
497  ent = val;
498  if (ent->parsed->timestamp < cutoff) {
499  char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
500  base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
501  log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
502  safe_str_client(key_base32));
503  bytes_removed += rend_cache_entry_allocation(ent);
504  iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
505  rend_cache_entry_free(ent);
506  } else {
507  iter = digestmap_iter_next(rend_cache_v2_dir, iter);
508  }
509  }
510 
511  return bytes_removed;
512 }
513 
514 /** Lookup in the client cache the given service ID <b>query</b> for
515  * <b>version</b>.
516  *
517  * Return 0 if found and if <b>e</b> is non NULL, set it with the entry
518  * found. Else, a negative value is returned and <b>e</b> is untouched.
519  * -EINVAL means that <b>query</b> is not a valid service id.
520  * -ENOENT means that no entry in the cache was found. */
521 int
522 rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
523 {
524  int ret = 0;
525  char key[REND_SERVICE_ID_LEN_BASE32 + 2]; /* <version><query>\0 */
526  rend_cache_entry_t *entry = NULL;
527  static const int default_version = 2;
528 
529  tor_assert(query);
530 
531  /* This is possible if we are in the shutdown process and the cache was
532  * freed while some other subsystem might do a lookup to the cache for
533  * cleanup reasons such HS circuit cleanup for instance. */
534  if (!rend_cache) {
535  ret = -ENOENT;
536  goto end;
537  }
538 
539  if (!rend_valid_v2_service_id(query)) {
540  ret = -EINVAL;
541  goto end;
542  }
543 
544  switch (version) {
545  case 0:
546  log_warn(LD_REND, "Cache lookup of a v0 renddesc is deprecated.");
547  break;
548  case 2:
549  /* Default is version 2. */
550  default:
551  tor_snprintf(key, sizeof(key), "%d%s", default_version, query);
552  entry = strmap_get_lc(rend_cache, key);
553  break;
554  }
555  if (!entry) {
556  ret = -ENOENT;
557  goto end;
558  }
559  tor_assert(entry->parsed && entry->parsed->intro_nodes);
560 
561  if (e) {
562  *e = entry;
563  }
564 
565  end:
566  return ret;
567 }
568 
569 /*
570  * Lookup the v2 service descriptor with the service ID <b>query</b> in the
571  * local service descriptor cache. Return 0 if found and if <b>e</b> is
572  * non NULL, set it with the entry found. Else, a negative value is returned
573  * and <b>e</b> is untouched.
574  * -EINVAL means that <b>query</b> is not a valid service id.
575  * -ENOENT means that no entry in the cache was found. */
576 int
577 rend_cache_lookup_v2_desc_as_service(const char *query, rend_cache_entry_t **e)
578 {
579  int ret = 0;
580  rend_cache_entry_t *entry = NULL;
581 
583  tor_assert(query);
584 
585  if (!rend_valid_v2_service_id(query)) {
586  ret = -EINVAL;
587  goto end;
588  }
589 
590  /* Lookup descriptor and return. */
591  entry = strmap_get_lc(rend_cache_local_service, query);
592  if (!entry) {
593  ret = -ENOENT;
594  goto end;
595  }
596 
597  if (e) {
598  *e = entry;
599  }
600 
601  end:
602  return ret;
603 }
604 
605 /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
606  * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
607  * well-formed-but-not-found, and -1 on failure.
608  */
609 int
610 rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
611 {
613  char desc_id_digest[DIGEST_LEN];
615  if (base32_decode(desc_id_digest, DIGEST_LEN,
616  desc_id, REND_DESC_ID_V2_LEN_BASE32) != DIGEST_LEN) {
617  log_fn(LOG_PROTOCOL_WARN, LD_REND,
618  "Rejecting v2 rendezvous descriptor request -- descriptor ID "
619  "has wrong length or illegal characters: %s",
620  safe_str(desc_id));
621  return -1;
622  }
623  /* Lookup descriptor and return. */
624  e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
625  if (e) {
626  *desc = e->desc;
627  e->last_served = approx_time();
628  return 1;
629  }
630  return 0;
631 }
632 
633 /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
634  * local rend cache. Don't attempt to decrypt the included list of introduction
635  * points (as we don't have a descriptor cookie for it).
636  *
637  * If we have a newer descriptor with the same ID, ignore this one.
638  * If we have an older descriptor with the same ID, replace it.
639  *
640  * Return 0 on success, or -1 if we couldn't parse any of them.
641  *
642  * We should only call this function for public (e.g. non bridge) relays.
643  */
644 int
646 {
647  const or_options_t *options = get_options();
649  char desc_id[DIGEST_LEN];
650  char *intro_content;
651  size_t intro_size;
652  size_t encoded_size;
653  char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
654  int number_parsed = 0, number_stored = 0;
655  const char *current_desc = desc;
656  const char *next_desc;
658  time_t now = time(NULL);
660  tor_assert(desc);
661  while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
662  &intro_size, &encoded_size,
663  &next_desc, current_desc, 1) >= 0) {
664  number_parsed++;
665  /* We don't care about the introduction points. */
666  tor_free(intro_content);
667  /* For pretty log statements. */
668  base32_encode(desc_id_base32, sizeof(desc_id_base32),
669  desc_id, DIGEST_LEN);
670  /* Is descriptor too old? */
671  if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
672  log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
673  safe_str(desc_id_base32));
674  goto skip;
675  }
676  /* Is descriptor too far in the future? */
677  if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
678  log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
679  "future.",
680  safe_str(desc_id_base32));
681  goto skip;
682  }
683  /* Do we already have a newer descriptor? */
684  e = digestmap_get(rend_cache_v2_dir, desc_id);
685  if (e && e->parsed->timestamp > parsed->timestamp) {
686  log_info(LD_REND, "We already have a newer service descriptor with the "
687  "same desc ID %s and version.",
688  safe_str(desc_id_base32));
689  goto skip;
690  }
691  /* Do we already have this descriptor? */
692  if (e && !strcmp(desc, e->desc)) {
693  log_info(LD_REND, "We already have this service descriptor with desc "
694  "ID %s.", safe_str(desc_id_base32));
695  goto skip;
696  }
697  /* Store received descriptor. */
698  if (!e) {
699  e = tor_malloc_zero(sizeof(rend_cache_entry_t));
700  digestmap_set(rend_cache_v2_dir, desc_id, e);
701  /* Treat something just uploaded as having been served a little
702  * while ago, so that flooding with new descriptors doesn't help
703  * too much.
704  */
705  e->last_served = approx_time() - 3600;
706  } else {
708  rend_service_descriptor_free(e->parsed);
709  tor_free(e->desc);
710  }
711  e->parsed = parsed;
712  e->desc = tor_strndup(current_desc, encoded_size);
713  e->len = encoded_size;
715  log_info(LD_REND, "Successfully stored service descriptor with desc ID "
716  "'%s' and len %d.",
717  safe_str(desc_id_base32), (int)encoded_size);
718  /* Statistics: Note down this potentially new HS. */
719  if (options->HiddenServiceStatistics) {
721  }
722 
723  number_stored++;
724  goto advance;
725  skip:
726  rend_service_descriptor_free(parsed);
727  advance:
728  /* advance to next descriptor, if available. */
729  current_desc = next_desc;
730  /* check if there is a next descriptor. */
731  if (!current_desc ||
732  strcmpstart(current_desc, "rendezvous-service-descriptor "))
733  break;
734  }
735  if (!number_parsed) {
736  log_info(LD_REND, "Could not parse any descriptor.");
737  return -1;
738  }
739  log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
740  number_parsed, number_stored, number_stored != 1 ? "s" : "");
741  return 0;
742 }
743 
744 /** Parse the v2 service descriptor in <b>desc</b> and store it to the
745 * local service rend cache. Don't attempt to decrypt the included list of
746 * introduction points.
747 *
748 * If we have a newer descriptor with the same ID, ignore this one.
749 * If we have an older descriptor with the same ID, replace it.
750 *
751 * Return 0 on success, or -1 if we couldn't understand the descriptor.
752 */
753 int
755 {
756  rend_service_descriptor_t *parsed = NULL;
757  char desc_id[DIGEST_LEN];
758  char *intro_content = NULL;
759  size_t intro_size;
760  size_t encoded_size;
761  const char *next_desc;
762  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
764  int retval = -1;
766  tor_assert(desc);
767 
768  /* Parse the descriptor. */
769  if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
770  &intro_size, &encoded_size,
771  &next_desc, desc, 0) < 0) {
772  log_warn(LD_REND, "Could not parse descriptor.");
773  goto err;
774  }
775  /* Compute service ID from public key. */
776  if (rend_get_service_id(parsed->pk, service_id)<0) {
777  log_warn(LD_REND, "Couldn't compute service ID.");
778  goto err;
779  }
780 
781  /* Do we already have a newer descriptor? Allow new descriptors with a
782  rounded timestamp equal to or newer than the current descriptor */
784  service_id);
785  if (e && e->parsed->timestamp > parsed->timestamp) {
786  log_info(LD_REND, "We already have a newer service descriptor for "
787  "service ID %s.", safe_str_client(service_id));
788  goto okay;
789  }
790  /* We don't care about the introduction points. */
791  tor_free(intro_content);
792  if (!e) {
793  e = tor_malloc_zero(sizeof(rend_cache_entry_t));
794  strmap_set_lc(rend_cache_local_service, service_id, e);
795  } else {
797  rend_service_descriptor_free(e->parsed);
798  tor_free(e->desc);
799  }
800  e->parsed = parsed;
801  e->desc = tor_malloc_zero(encoded_size + 1);
802  strlcpy(e->desc, desc, encoded_size + 1);
803  e->len = encoded_size;
805  log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
806  safe_str_client(service_id), (int)encoded_size);
807  return 0;
808 
809  okay:
810  retval = 0;
811 
812  err:
813  rend_service_descriptor_free(parsed);
814  tor_free(intro_content);
815  return retval;
816 }
817 
818 /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
819  * of introduction points with <b>descriptor_cookie</b> (which may also be
820  * <b>NULL</b> if decryption is not necessary), and store the descriptor to
821  * the local cache under its version and service id.
822  *
823  * If we have a newer v2 descriptor with the same ID, ignore this one.
824  * If we have an older descriptor with the same ID, replace it.
825  * If the descriptor's service ID does not match
826  * <b>rend_query</b>->onion_address, reject it.
827  *
828  * If the descriptor's descriptor ID doesn't match <b>desc_id_base32</b>,
829  * reject it.
830  *
831  * Return 0 on success, or -1 if we rejected the descriptor.
832  * If entry is not NULL, set it with the cache entry pointer of the descriptor.
833  */
834 int
836  const char *desc_id_base32,
837  const rend_data_t *rend_query,
838  rend_cache_entry_t **entry)
839 {
840  /*XXXX this seems to have a bit of duplicate code with
841  * rend_cache_store_v2_desc_as_dir(). Fix that. */
842  /* Though having similar elements, both functions were separated on
843  * purpose:
844  * - dirs don't care about encoded/encrypted introduction points, clients
845  * do.
846  * - dirs store descriptors in a separate cache by descriptor ID, whereas
847  * clients store them by service ID; both caches are different data
848  * structures and have different access methods.
849  * - dirs store a descriptor only if they are responsible for its ID,
850  * clients do so in every way (because they have requested it before).
851  * - dirs can process multiple concatenated descriptors which is required
852  * for replication, whereas clients only accept a single descriptor.
853  * Thus, combining both methods would result in a lot of if statements
854  * which probably would not improve, but worsen code readability. -KL */
855  rend_service_descriptor_t *parsed = NULL;
856  char desc_id[DIGEST_LEN];
857  char *intro_content = NULL;
858  size_t intro_size;
859  size_t encoded_size;
860  const char *next_desc;
861  time_t now = time(NULL);
862  char key[REND_SERVICE_ID_LEN_BASE32+2];
863  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
864  char want_desc_id[DIGEST_LEN];
866  int retval = -1;
867  rend_data_v2_t *rend_data = TO_REND_DATA_V2(rend_query);
868 
870  tor_assert(desc);
871  tor_assert(desc_id_base32);
872  memset(want_desc_id, 0, sizeof(want_desc_id));
873  if (entry) {
874  *entry = NULL;
875  }
876  if (base32_decode(want_desc_id, sizeof(want_desc_id),
877  desc_id_base32, strlen(desc_id_base32)) !=
878  sizeof(want_desc_id)) {
879  log_warn(LD_BUG, "Couldn't decode base32 %s for descriptor id.",
880  escaped_safe_str_client(desc_id_base32));
881  goto err;
882  }
883  /* Parse the descriptor. */
884  if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
885  &intro_size, &encoded_size,
886  &next_desc, desc, 0) < 0) {
887  log_warn(LD_REND, "Could not parse descriptor.");
888  goto err;
889  }
890  /* Compute service ID from public key. */
891  if (rend_get_service_id(parsed->pk, service_id)<0) {
892  log_warn(LD_REND, "Couldn't compute service ID.");
893  goto err;
894  }
895  if (rend_data->onion_address[0] != '\0' &&
896  strcmp(rend_data->onion_address, service_id)) {
897  log_warn(LD_REND, "Received service descriptor for service ID %s; "
898  "expected descriptor for service ID %s.",
899  service_id, safe_str(rend_data->onion_address));
900  goto err;
901  }
902  if (tor_memneq(desc_id, want_desc_id, DIGEST_LEN)) {
903  log_warn(LD_REND, "Received service descriptor for %s with incorrect "
904  "descriptor ID.", service_id);
905  goto err;
906  }
907 
908  /* Decode/decrypt introduction points. */
909  if (intro_content && intro_size > 0) {
910  int n_intro_points;
911  if (rend_data->auth_type != REND_NO_AUTH &&
913  sizeof(rend_data->descriptor_cookie))) {
914  char *ipos_decrypted = NULL;
915  size_t ipos_decrypted_size;
916  if (rend_decrypt_introduction_points(&ipos_decrypted,
917  &ipos_decrypted_size,
918  rend_data->descriptor_cookie,
919  intro_content,
920  intro_size) < 0) {
921  log_warn(LD_REND, "Failed to decrypt introduction points. We are "
922  "probably unable to parse the encoded introduction points.");
923  } else {
924  /* Replace encrypted with decrypted introduction points. */
925  log_info(LD_REND, "Successfully decrypted introduction points.");
926  tor_free(intro_content);
927  intro_content = ipos_decrypted;
928  intro_size = ipos_decrypted_size;
929  }
930  }
931  n_intro_points = rend_parse_introduction_points(parsed, intro_content,
932  intro_size);
933  if (n_intro_points <= 0) {
934  log_warn(LD_REND, "Failed to parse introduction points. Either the "
935  "service has published a corrupt descriptor or you have "
936  "provided invalid authorization data.");
937  goto err;
938  } else if (n_intro_points > MAX_INTRO_POINTS) {
939  log_warn(LD_REND, "Found too many introduction points on a hidden "
940  "service descriptor for %s. This is probably a (misguided) "
941  "attempt to improve reliability, but it could also be an "
942  "attempt to do a guard enumeration attack. Rejecting.",
943  safe_str_client(service_id));
944 
945  goto err;
946  }
947  } else {
948  log_info(LD_REND, "Descriptor does not contain any introduction points.");
949  parsed->intro_nodes = smartlist_new();
950  }
951  /* We don't need the encoded/encrypted introduction points any longer. */
952  tor_free(intro_content);
953  /* Is descriptor too old? */
954  if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
955  log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
956  safe_str_client(service_id));
957  goto err;
958  }
959  /* Is descriptor too far in the future? */
960  if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
961  log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
962  "the future.", safe_str_client(service_id));
963  goto err;
964  }
965  /* Do we have the same exact copy already in our cache? */
966  tor_snprintf(key, sizeof(key), "2%s", service_id);
968  if (e && !strcmp(desc, e->desc)) {
969  log_info(LD_REND,"We already have this service descriptor %s.",
970  safe_str_client(service_id));
971  goto okay;
972  }
973  /* Verify that we are not replacing an older descriptor. It's important to
974  * avoid an evil HSDir serving old descriptor. We validate if the
975  * timestamp is greater than and not equal because it's a rounded down
976  * timestamp to the hour so if the descriptor changed in the same hour,
977  * the rend cache failure will tell us if we have a new descriptor. */
978  if (e && e->parsed->timestamp > parsed->timestamp) {
979  log_info(LD_REND, "We already have a new enough service descriptor for "
980  "service ID %s with the same desc ID and version.",
981  safe_str_client(service_id));
982  goto okay;
983  }
984  /* Lookup our failure cache for intro point that might be unusable. */
985  validate_intro_point_failure(parsed, service_id);
986  /* It's now possible that our intro point list is empty, which means that
987  * this descriptor is useless to us because intro points have all failed
988  * somehow before. Discard the descriptor. */
989  if (smartlist_len(parsed->intro_nodes) == 0) {
990  log_info(LD_REND, "Service descriptor with service ID %s has no "
991  "usable intro points. Discarding it.",
992  safe_str_client(service_id));
993  goto err;
994  }
995  /* Now either purge the current one and replace its content or create a
996  * new one and add it to the rend cache. */
997  if (!e) {
998  e = tor_malloc_zero(sizeof(rend_cache_entry_t));
999  strmap_set_lc(rend_cache, key, e);
1000  } else {
1003  rend_service_descriptor_free(e->parsed);
1004  tor_free(e->desc);
1005  }
1006  e->parsed = parsed;
1007  e->desc = tor_malloc_zero(encoded_size + 1);
1008  strlcpy(e->desc, desc, encoded_size + 1);
1009  e->len = encoded_size;
1011  log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
1012  safe_str_client(service_id), (int)encoded_size);
1013  if (entry) {
1014  *entry = e;
1015  }
1016  return 0;
1017 
1018  okay:
1019  if (entry) {
1020  *entry = e;
1021  }
1022  retval = 0;
1023 
1024  err:
1025  rend_service_descriptor_free(parsed);
1026  tor_free(intro_content);
1027  return retval;
1028 }
STATIC strmap_t * rend_cache
Definition: rendcache.c:26
Header file for rendcommon.c.
void * strmap_get_lc(const strmap_t *map, const char *key)
Definition: map.c:393
STATIC void rend_cache_failure_remove(rend_service_descriptor_t *desc)
Definition: rendcache.c:190
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Headers for di_ops.c.
STATIC void cache_failure_intro_add(const uint8_t *identity, const char *service_id, rend_intro_point_failure_t failure)
Definition: rendcache.c:390
STATIC strmap_t * rend_cache_failure
Definition: rendcache.c:60
char descriptor_cookie[REND_DESC_COOKIE_LEN]
Definition: or.h:446
STATIC void rend_cache_entry_free_(rend_cache_entry_t *e)
Definition: rendcache.c:210
STATIC int cache_failure_intro_lookup(const uint8_t *identity, const char *service_id, rend_cache_failure_intro_t **intro_entry)
Definition: rendcache.c:346
void rend_cache_intro_failure_note(rend_intro_point_failure_t failure, const uint8_t *identity, const char *service_id)
Definition: rendcache.c:465
#define REND_CACHE_MAX_SKEW
Definition: rendcache.h:20
void rend_cache_purge(void)
Definition: rendcache.c:320
void rend_cache_failure_purge(void)
Definition: rendcache.c:332
int rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
Definition: rendcache.c:610
Header file for rendparse.c.
rend_service_descriptor_t * parsed
Definition: rendcache.h:34
time_t last_served
Definition: rendcache.h:31
STATIC void rend_cache_failure_entry_free_(rend_cache_failure_t *entry)
Definition: rendcache.c:156
size_t rend_cache_clean_v2_descs_as_dir(time_t cutoff)
Definition: rendcache.c:486
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:354
Header file for config.c.
const or_options_t * get_options(void)
Definition: config.c:926
#define tor_assert(expr)
Definition: util_bug.h:102
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:60
Parsed v2 HS descriptor structure.
int rend_parse_introduction_points(rend_service_descriptor_t *parsed, const char *intro_points_encoded, size_t intro_points_encoded_size)
Definition: rendparse.c:378
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:206
#define MAP_DEL_CURRENT(keyvar)
Definition: map.h:140
int rend_decrypt_introduction_points(char **ipos_decrypted, size_t *ipos_decrypted_size, const char *descriptor_cookie, const char *ipos_encrypted, size_t ipos_encrypted_size)
Definition: rendparse.c:267
#define tor_free(p)
Definition: malloc.h:52
void rend_cache_clean(time_t now, rend_cache_type_t cache_type)
Definition: rendcache.c:289
#define SMARTLIST_DEL_CURRENT(sl, var)
void * strmap_set_lc(strmap_t *map, const char *key, void *val)
Definition: map.c:379
v2 hidden service introduction point structure.
smartlist_t * smartlist_new(void)
#define STATIC
Definition: testsupport.h:32
bool rend_cache_intro_failure_exists(const char *service_id, const uint8_t *intro_identity)
Definition: rendcache.c:233
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
STATIC digestmap_t * rend_cache_v2_dir
Definition: rendcache.c:33
STATIC void rend_cache_failure_entry_free_void(void *entry)
Definition: rendcache.c:172
Definition: rendcache.h:29
int base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:90
int rend_cache_store_v2_desc_as_dir(const char *desc)
Definition: rendcache.c:645
size_t len
Definition: rendcache.h:30
void rend_cache_free_all(void)
Definition: rendcache.c:244
#define DIGEST_LEN
Definition: digest_sizes.h:20
Header file for rendcache.c.
void rend_cache_decrement_allocation(size_t n)
Definition: rendcache.c:96
void rend_cache_failure_clean(time_t now)
Definition: rendcache.c:265
STATIC void rend_cache_failure_intro_entry_free_(rend_cache_failure_intro_t *entry)
Definition: rendcache.c:129
void * strmap_remove_lc(strmap_t *map, const char *key)
Definition: map.c:405
Header file for rephist.c.
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:719
int rend_cache_store_v2_desc_as_client(const char *desc, const char *desc_id_base32, const rend_data_t *rend_query, rend_cache_entry_t **entry)
Definition: rendcache.c:835
Extend-info structure.
#define LD_REND
Definition: log.h:84
int rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
Definition: rendcache.c:522
STATIC rend_cache_failure_intro_t * rend_cache_failure_intro_entry_new(rend_intro_point_failure_t failure)
Definition: rendcache.c:146
#define DIGESTMAP_FOREACH_END
Definition: map.h:168
#define REND_SERVICE_ID_LEN_BASE32
Definition: or.h:331
#define REND_CACHE_FAILURE_MAX_AGE
Definition: rendcache.h:22
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
#define REND_CACHE_MAX_AGE
Definition: rendcache.h:17
#define DIGESTMAP_FOREACH_MODIFY(map, keyvar, valtype, valvar)
Definition: map.h:165
#define log_fn(severity, domain, args,...)
Definition: log.h:287
int rend_get_service_id(crypto_pk_t *pk, char *out)
Definition: rendcommon.c:706
char onion_address[REND_SERVICE_ID_LEN_BASE32+1]
Definition: or.h:438
STATIC void validate_intro_point_failure(const rend_service_descriptor_t *desc, const char *service_id)
Definition: rendcache.c:417
void rep_hist_stored_maybe_new_hs(const crypto_pk_t *pubkey)
Definition: rephist.c:2569
void rend_cache_init(void)
Definition: rendcache.c:68
time_t approx_time(void)
Definition: approx_time.c:32
STATIC rend_cache_failure_t * rend_cache_failure_entry_new(void)
Definition: rendcache.c:180
int safe_mem_is_zero(const void *mem, size_t sz)
Definition: di_ops.c:224
static void rend_cache_entry_free_void(void *p)
Definition: rendcache.c:226
int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out, char *desc_id_out, char **intro_points_encrypted_out, size_t *intro_points_encrypted_size_out, size_t *encoded_size_out, const char **next_out, const char *desc, int as_hsdir)
Definition: rendparse.c:72
int rend_cache_store_v2_desc_as_service(const char *desc)
Definition: rendcache.c:754
int HiddenServiceStatistics
void rend_cache_increment_allocation(size_t n)
Definition: rendcache.c:113
STATIC size_t rend_cache_entry_allocation(const rend_cache_entry_t *e)
Definition: rendcache.c:78
static rend_cache_failure_intro_t * cache_failure_intro_dup(const rend_cache_failure_intro_t *entry)
Definition: rendcache.c:378
static strmap_t * rend_cache_local_service
Definition: rendcache.c:29
#define LD_BUG
Definition: log.h:86
rend_auth_type_t auth_type
Definition: or.h:449
Header file for routerlist.c.
char * desc
Definition: rendcache.h:33
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1117