rendcache.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /* Copyright (c) 2015, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file rendcache.c
  5. * \brief Hidden service desriptor cache.
  6. **/
  7. #include "rendcache.h"
  8. #include "config.h"
  9. #include "rephist.h"
  10. #include "routerlist.h"
  11. #include "routerparse.h"
  12. /** Map from service id (as generated by rend_get_service_id) to
  13. * rend_cache_entry_t. */
  14. static strmap_t *rend_cache = NULL;
  15. /** Map from descriptor id to rend_cache_entry_t; only for hidden service
  16. * directories. */
  17. static digestmap_t *rend_cache_v2_dir = NULL;
  18. /** (Client side only) Map from service id to rend_cache_failure_t. This
  19. * cache is used to track intro point(IP) failures so we know when to keep
  20. * or discard a new descriptor we just fetched. Here is a description of the
  21. * cache behavior.
  22. *
  23. * Everytime tor discards an IP (ex: receives a NACK), we add an entry to
  24. * this cache noting the identity digest of the IP and it's failure type for
  25. * the service ID. The reason we indexed this cache by service ID is to
  26. * differentiate errors that can occur only for a specific service like a
  27. * NACK for instance. It applies for one but maybe not for the others.
  28. *
  29. * Once a service descriptor is fetched and considered valid, each IP is
  30. * looked up in this cache and if present, it is discarded from the fetched
  31. * descriptor. At the end, all IP(s) in the cache, for a specific service
  32. * ID, that were NOT present in the descriptor are removed from this cache.
  33. * Which means that if at least one IP was not in this cache, thus usuable,
  34. * it's considered a new descriptor so we keep it. Else, if all IPs were in
  35. * this cache, we discard the descriptor as it's considered unsuable.
  36. *
  37. * Once a descriptor is removed from the rend cache or expires, the entry
  38. * in this cache is also removed for the service ID.
  39. *
  40. * This scheme allows us to not realy on the descriptor's timestamp (which
  41. * is rounded down to the hour) to know if we have a newer descriptor. We
  42. * only rely on the usability of intro points from an internal state. */
  43. static strmap_t *rend_cache_failure = NULL;
  44. /** DOCDOC */
  45. static size_t rend_cache_total_allocation = 0;
  46. /** Initializes the service descriptor cache.
  47. */
  48. void
  49. rend_cache_init(void)
  50. {
  51. rend_cache = strmap_new();
  52. rend_cache_v2_dir = digestmap_new();
  53. rend_cache_failure = strmap_new();
  54. }
  55. /** Return the approximate number of bytes needed to hold <b>e</b>. */
  56. static size_t
  57. rend_cache_entry_allocation(const rend_cache_entry_t *e)
  58. {
  59. if (!e)
  60. return 0;
  61. /* This doesn't count intro_nodes or key size */
  62. return sizeof(*e) + e->len + sizeof(*e->parsed);
  63. }
  64. /** DOCDOC */
  65. size_t
  66. rend_cache_get_total_allocation(void)
  67. {
  68. return rend_cache_total_allocation;
  69. }
  70. /** Decrement the total bytes attributed to the rendezvous cache by n. */
  71. static void
  72. rend_cache_decrement_allocation(size_t n)
  73. {
  74. static int have_underflowed = 0;
  75. if (rend_cache_total_allocation >= n) {
  76. rend_cache_total_allocation -= n;
  77. } else {
  78. rend_cache_total_allocation = 0;
  79. if (! have_underflowed) {
  80. have_underflowed = 1;
  81. log_warn(LD_BUG, "Underflow in rend_cache_decrement_allocation");
  82. }
  83. }
  84. }
  85. /** Increase the total bytes attributed to the rendezvous cache by n. */
  86. static void
  87. rend_cache_increment_allocation(size_t n)
  88. {
  89. static int have_overflowed = 0;
  90. if (rend_cache_total_allocation <= SIZE_MAX - n) {
  91. rend_cache_total_allocation += n;
  92. } else {
  93. rend_cache_total_allocation = SIZE_MAX;
  94. if (! have_overflowed) {
  95. have_overflowed = 1;
  96. log_warn(LD_BUG, "Overflow in rend_cache_increment_allocation");
  97. }
  98. }
  99. }
  100. /** Helper: free a rend cache failure intro object. */
  101. static void
  102. rend_cache_failure_intro_entry_free(rend_cache_failure_intro_t *entry)
  103. {
  104. if (entry == NULL) {
  105. return;
  106. }
  107. tor_free(entry);
  108. }
  109. /** Allocate a rend cache failure intro object and return it. <b>failure</b>
  110. * is set into the object. This function can not fail. */
  111. static rend_cache_failure_intro_t *
  112. rend_cache_failure_intro_entry_new(rend_intro_point_failure_t failure)
  113. {
  114. rend_cache_failure_intro_t *entry = tor_malloc(sizeof(*entry));
  115. entry->failure_type = failure;
  116. entry->created_ts = time(NULL);
  117. return entry;
  118. }
  119. /** Helper: free a rend cache failure object. */
  120. static void
  121. rend_cache_failure_entry_free(rend_cache_failure_t *entry)
  122. {
  123. if (entry == NULL) {
  124. return;
  125. }
  126. /* Free and remove every intro failure object. */
  127. DIGESTMAP_FOREACH_MODIFY(entry->intro_failures, key,
  128. rend_cache_failure_intro_t *, e) {
  129. rend_cache_failure_intro_entry_free(e);
  130. MAP_DEL_CURRENT(key);
  131. } DIGESTMAP_FOREACH_END;
  132. tor_free(entry);
  133. }
  134. /** Helper: deallocate a rend_cache_failure_t. (Used with strmap_free(),
  135. * which requires a function pointer whose argument is void*). */
  136. static void
  137. rend_cache_failure_entry_free_(void *entry)
  138. {
  139. rend_cache_failure_entry_free(entry);
  140. }
  141. /** Allocate a rend cache failure object and return it. This function can
  142. * not fail. */
  143. static rend_cache_failure_t *
  144. rend_cache_failure_entry_new(void)
  145. {
  146. rend_cache_failure_t *entry = tor_malloc(sizeof(*entry));
  147. entry->intro_failures = digestmap_new();
  148. return entry;
  149. }
  150. /** Remove failure cache entry for the service ID in the given descriptor
  151. * <b>desc</b>. */
  152. static void
  153. rend_cache_failure_remove(rend_service_descriptor_t *desc)
  154. {
  155. char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
  156. rend_cache_failure_t *entry;
  157. if (desc == NULL) {
  158. return;
  159. }
  160. if (rend_get_service_id(desc->pk, service_id) < 0) {
  161. return;
  162. }
  163. entry = strmap_get_lc(rend_cache_failure, service_id);
  164. if (entry != NULL) {
  165. strmap_remove_lc(rend_cache_failure, service_id);
  166. rend_cache_failure_entry_free(entry);
  167. }
  168. }
  169. /** Helper: free storage held by a single service descriptor cache entry. */
  170. static void
  171. rend_cache_entry_free(rend_cache_entry_t *e)
  172. {
  173. if (!e)
  174. return;
  175. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  176. /* We are about to remove a descriptor from the cache so remove the entry
  177. * in the failure cache. */
  178. rend_cache_failure_remove(e->parsed);
  179. rend_service_descriptor_free(e->parsed);
  180. tor_free(e->desc);
  181. tor_free(e);
  182. }
  183. /** Helper: deallocate a rend_cache_entry_t. (Used with strmap_free(), which
  184. * requires a function pointer whose argument is void*). */
  185. static void
  186. rend_cache_entry_free_(void *p)
  187. {
  188. rend_cache_entry_free(p);
  189. }
  190. /** Free all storage held by the service descriptor cache. */
  191. void
  192. rend_cache_free_all(void)
  193. {
  194. strmap_free(rend_cache, rend_cache_entry_free_);
  195. digestmap_free(rend_cache_v2_dir, rend_cache_entry_free_);
  196. strmap_free(rend_cache_failure, rend_cache_failure_entry_free_);
  197. rend_cache = NULL;
  198. rend_cache_v2_dir = NULL;
  199. rend_cache_failure = NULL;
  200. rend_cache_total_allocation = 0;
  201. }
  202. /** Removes all old entries from the service descriptor cache.
  203. */
  204. void
  205. rend_cache_clean(time_t now)
  206. {
  207. strmap_iter_t *iter;
  208. const char *key;
  209. void *val;
  210. rend_cache_entry_t *ent;
  211. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  212. for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
  213. strmap_iter_get(iter, &key, &val);
  214. ent = (rend_cache_entry_t*)val;
  215. if (ent->parsed->timestamp < cutoff) {
  216. iter = strmap_iter_next_rmv(rend_cache, iter);
  217. rend_cache_entry_free(ent);
  218. } else {
  219. iter = strmap_iter_next(rend_cache, iter);
  220. }
  221. }
  222. }
  223. /** Remove ALL entries from the rendezvous service descriptor cache.
  224. */
  225. void
  226. rend_cache_purge(void)
  227. {
  228. if (rend_cache) {
  229. log_info(LD_REND, "Purging HS descriptor cache");
  230. strmap_free(rend_cache, rend_cache_entry_free_);
  231. }
  232. rend_cache = strmap_new();
  233. }
  234. /** Remove ALL entries from the failure cache. This is also called when a
  235. * NEWNYM signal is received. */
  236. void
  237. rend_cache_failure_purge(void)
  238. {
  239. if (rend_cache_failure) {
  240. log_info(LD_REND, "Purging HS failure cache");
  241. strmap_free(rend_cache_failure, rend_cache_failure_entry_free_);
  242. }
  243. rend_cache_failure = strmap_new();
  244. }
  245. /** Lookup the rend failure cache using a relay identity digest in
  246. * <b>identity</b> and service ID <b>service_id</b>. If found, the intro
  247. * failure is set in <b>intro_entry</b> else it stays untouched. Return 1
  248. * iff found else 0. */
  249. static int
  250. cache_failure_intro_lookup(const uint8_t *identity, const char *service_id,
  251. rend_cache_failure_intro_t **intro_entry)
  252. {
  253. rend_cache_failure_t *elem;
  254. rend_cache_failure_intro_t *intro_elem;
  255. tor_assert(rend_cache_failure);
  256. if (intro_entry) {
  257. *intro_entry = NULL;
  258. }
  259. /* Lookup descriptor and return it. */
  260. elem = strmap_get_lc(rend_cache_failure, service_id);
  261. if (elem == NULL) {
  262. goto not_found;
  263. }
  264. intro_elem = digestmap_get(elem->intro_failures, (char *) identity);
  265. if (intro_elem == NULL) {
  266. goto not_found;
  267. }
  268. if (intro_entry) {
  269. *intro_entry = intro_elem;
  270. }
  271. return 1;
  272. not_found:
  273. return 0;
  274. }
  275. /** Add an intro point failure to the failure cache using the relay
  276. * <b>identity</b> and service ID <b>service_id</b>. Record the
  277. * <b>failure</b> in that object. */
  278. static void
  279. cache_failure_intro_add(const uint8_t *identity, const char *service_id,
  280. rend_intro_point_failure_t failure)
  281. {
  282. rend_cache_failure_t *fail_entry;
  283. rend_cache_failure_intro_t *entry;
  284. /* Make sure we have a failure object for this service ID and if not,
  285. * create it with this new intro failure entry. */
  286. fail_entry = strmap_get_lc(rend_cache_failure, service_id);
  287. if (fail_entry == NULL) {
  288. fail_entry = rend_cache_failure_entry_new();
  289. /* Add failure entry to global rend failure cache. */
  290. strmap_set_lc(rend_cache_failure, service_id, fail_entry);
  291. }
  292. entry = rend_cache_failure_intro_entry_new(failure);
  293. digestmap_set(fail_entry->intro_failures, (char *) identity, entry);
  294. }
  295. /** Using a parsed descriptor <b>desc</b>, check if the introduction points
  296. * are present in the failure cache and if so they are removed from the
  297. * descriptor and kept into the failure cache. Then, each intro points that
  298. * are NOT in the descriptor but in the failure cache for the given
  299. * <b>service_id</b> are removed from the failure cache. */
  300. static void
  301. validate_intro_point_failure(const rend_service_descriptor_t *desc,
  302. const char *service_id)
  303. {
  304. rend_cache_failure_t *new_entry, *cur_entry;
  305. /* New entry for the service ID that will be replacing the one in the
  306. * failure cache since we have a new descriptor. In the case where all
  307. * intro points are removed, we are assured that the new entry is the same
  308. * as the current one. */
  309. new_entry = tor_malloc(sizeof(*new_entry));
  310. new_entry->intro_failures = digestmap_new();
  311. tor_assert(desc);
  312. SMARTLIST_FOREACH_BEGIN(desc->intro_nodes, rend_intro_point_t *, intro) {
  313. int found;
  314. rend_cache_failure_intro_t *entry;
  315. const uint8_t *identity =
  316. (uint8_t *) intro->extend_info->identity_digest;
  317. found = cache_failure_intro_lookup(identity, service_id, &entry);
  318. if (found) {
  319. /* This intro point is in our cache, discard it from the descriptor
  320. * because chances are that it's unusable. */
  321. SMARTLIST_DEL_CURRENT(desc->intro_nodes, intro);
  322. rend_intro_point_free(intro);
  323. /* Keep it for our new entry. */
  324. digestmap_set(new_entry->intro_failures, (char *) identity, entry);
  325. continue;
  326. }
  327. } SMARTLIST_FOREACH_END(intro);
  328. /* Swap the failure entry in the cache and free the current one. */
  329. cur_entry = strmap_get_lc(rend_cache_failure, service_id);
  330. if (cur_entry != NULL) {
  331. rend_cache_failure_entry_free(cur_entry);
  332. }
  333. strmap_set_lc(rend_cache_failure, service_id, new_entry);
  334. }
  335. /** Note down an intro failure in the rend failure cache using the type of
  336. * failure in <b>failure</b> for the relay identity digest in
  337. * <b>identity</b> and service ID <b>service_id</b>. If an entry already
  338. * exists in the cache, the failure type is changed with <b>failure</b>. */
  339. void
  340. rend_cache_intro_failure_note(rend_intro_point_failure_t failure,
  341. const uint8_t *identity,
  342. const char *service_id)
  343. {
  344. int found;
  345. rend_cache_failure_intro_t *entry;
  346. found = cache_failure_intro_lookup(identity, service_id, &entry);
  347. if (!found) {
  348. cache_failure_intro_add(identity, service_id, failure);
  349. } else {
  350. /* Replace introduction point failure with this one. */
  351. entry->failure_type = failure;
  352. }
  353. }
  354. /** Remove all old v2 descriptors and those for which this hidden service
  355. * directory is not responsible for any more.
  356. *
  357. * If at all possible, remove at least <b>force_remove</b> bytes of data.
  358. */
  359. void
  360. rend_cache_clean_v2_descs_as_dir(time_t now, size_t force_remove)
  361. {
  362. digestmap_iter_t *iter;
  363. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  364. const int LAST_SERVED_CUTOFF_STEP = 1800;
  365. time_t last_served_cutoff = cutoff;
  366. size_t bytes_removed = 0;
  367. do {
  368. for (iter = digestmap_iter_init(rend_cache_v2_dir);
  369. !digestmap_iter_done(iter); ) {
  370. const char *key;
  371. void *val;
  372. rend_cache_entry_t *ent;
  373. digestmap_iter_get(iter, &key, &val);
  374. ent = val;
  375. if (ent->parsed->timestamp < cutoff ||
  376. ent->last_served < last_served_cutoff ||
  377. !hid_serv_responsible_for_desc_id(key)) {
  378. char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  379. base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
  380. log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
  381. safe_str_client(key_base32));
  382. bytes_removed += rend_cache_entry_allocation(ent);
  383. iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
  384. rend_cache_entry_free(ent);
  385. } else {
  386. iter = digestmap_iter_next(rend_cache_v2_dir, iter);
  387. }
  388. }
  389. /* In case we didn't remove enough bytes, advance the cutoff a little. */
  390. last_served_cutoff += LAST_SERVED_CUTOFF_STEP;
  391. if (last_served_cutoff > now)
  392. break;
  393. } while (bytes_removed < force_remove);
  394. }
  395. /** Lookup in the client cache the given service ID <b>query</b> for
  396. * <b>version</b>.
  397. *
  398. * Return 0 if found and if <b>e</b> is non NULL, set it with the entry
  399. * found. Else, a negative value is returned and <b>e</b> is untouched.
  400. * -EINVAL means that <b>query</b> is not a valid service id.
  401. * -ENOENT means that no entry in the cache was found. */
  402. int
  403. rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
  404. {
  405. int ret = 0;
  406. char key[REND_SERVICE_ID_LEN_BASE32 + 2]; /* <version><query>\0 */
  407. rend_cache_entry_t *entry = NULL;
  408. static const int default_version = 2;
  409. tor_assert(rend_cache);
  410. tor_assert(query);
  411. if (!rend_valid_service_id(query)) {
  412. ret = -EINVAL;
  413. goto end;
  414. }
  415. switch (version) {
  416. case 0:
  417. log_warn(LD_REND, "Cache lookup of a v0 renddesc is deprecated.");
  418. break;
  419. case 2:
  420. /* Default is version 2. */
  421. default:
  422. tor_snprintf(key, sizeof(key), "%d%s", default_version, query);
  423. entry = strmap_get_lc(rend_cache, key);
  424. break;
  425. }
  426. if (!entry) {
  427. ret = -ENOENT;
  428. goto end;
  429. }
  430. tor_assert(entry->parsed && entry->parsed->intro_nodes);
  431. if (e) {
  432. *e = entry;
  433. }
  434. end:
  435. return ret;
  436. }
  437. /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
  438. * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
  439. * well-formed-but-not-found, and -1 on failure.
  440. */
  441. int
  442. rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
  443. {
  444. rend_cache_entry_t *e;
  445. char desc_id_digest[DIGEST_LEN];
  446. tor_assert(rend_cache_v2_dir);
  447. if (base32_decode(desc_id_digest, DIGEST_LEN,
  448. desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
  449. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  450. "Rejecting v2 rendezvous descriptor request -- descriptor ID "
  451. "contains illegal characters: %s",
  452. safe_str(desc_id));
  453. return -1;
  454. }
  455. /* Lookup descriptor and return. */
  456. e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
  457. if (e) {
  458. *desc = e->desc;
  459. e->last_served = approx_time();
  460. return 1;
  461. }
  462. return 0;
  463. }
  464. /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
  465. * local rend cache. Don't attempt to decrypt the included list of introduction
  466. * points (as we don't have a descriptor cookie for it).
  467. *
  468. * If we have a newer descriptor with the same ID, ignore this one.
  469. * If we have an older descriptor with the same ID, replace it.
  470. *
  471. * Return an appropriate rend_cache_store_status_t.
  472. */
  473. rend_cache_store_status_t
  474. rend_cache_store_v2_desc_as_dir(const char *desc)
  475. {
  476. const or_options_t *options = get_options();
  477. rend_service_descriptor_t *parsed;
  478. char desc_id[DIGEST_LEN];
  479. char *intro_content;
  480. size_t intro_size;
  481. size_t encoded_size;
  482. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  483. int number_parsed = 0, number_stored = 0;
  484. const char *current_desc = desc;
  485. const char *next_desc;
  486. rend_cache_entry_t *e;
  487. time_t now = time(NULL);
  488. tor_assert(rend_cache_v2_dir);
  489. tor_assert(desc);
  490. if (!hid_serv_acting_as_directory()) {
  491. /* Cannot store descs, because we are (currently) not acting as
  492. * hidden service directory. */
  493. log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
  494. return RCS_NOTDIR;
  495. }
  496. while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  497. &intro_size, &encoded_size,
  498. &next_desc, current_desc, 1) >= 0) {
  499. number_parsed++;
  500. /* We don't care about the introduction points. */
  501. tor_free(intro_content);
  502. /* For pretty log statements. */
  503. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  504. desc_id, DIGEST_LEN);
  505. /* Is desc ID in the range that we are (directly or indirectly) responsible
  506. * for? */
  507. if (!hid_serv_responsible_for_desc_id(desc_id)) {
  508. log_info(LD_REND, "Service descriptor with desc ID %s is not in "
  509. "interval that we are responsible for.",
  510. safe_str_client(desc_id_base32));
  511. goto skip;
  512. }
  513. /* Is descriptor too old? */
  514. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  515. log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
  516. safe_str(desc_id_base32));
  517. goto skip;
  518. }
  519. /* Is descriptor too far in the future? */
  520. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  521. log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
  522. "future.",
  523. safe_str(desc_id_base32));
  524. goto skip;
  525. }
  526. /* Do we already have a newer descriptor? */
  527. e = digestmap_get(rend_cache_v2_dir, desc_id);
  528. if (e && e->parsed->timestamp > parsed->timestamp) {
  529. log_info(LD_REND, "We already have a newer service descriptor with the "
  530. "same desc ID %s and version.",
  531. safe_str(desc_id_base32));
  532. goto skip;
  533. }
  534. /* Do we already have this descriptor? */
  535. if (e && !strcmp(desc, e->desc)) {
  536. log_info(LD_REND, "We already have this service descriptor with desc "
  537. "ID %s.", safe_str(desc_id_base32));
  538. goto skip;
  539. }
  540. /* Store received descriptor. */
  541. if (!e) {
  542. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  543. digestmap_set(rend_cache_v2_dir, desc_id, e);
  544. /* Treat something just uploaded as having been served a little
  545. * while ago, so that flooding with new descriptors doesn't help
  546. * too much.
  547. */
  548. e->last_served = approx_time() - 3600;
  549. } else {
  550. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  551. rend_service_descriptor_free(e->parsed);
  552. tor_free(e->desc);
  553. }
  554. e->parsed = parsed;
  555. e->desc = tor_strndup(current_desc, encoded_size);
  556. e->len = encoded_size;
  557. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  558. log_info(LD_REND, "Successfully stored service descriptor with desc ID "
  559. "'%s' and len %d.",
  560. safe_str(desc_id_base32), (int)encoded_size);
  561. /* Statistics: Note down this potentially new HS. */
  562. if (options->HiddenServiceStatistics) {
  563. rep_hist_stored_maybe_new_hs(e->parsed->pk);
  564. }
  565. number_stored++;
  566. goto advance;
  567. skip:
  568. rend_service_descriptor_free(parsed);
  569. advance:
  570. /* advance to next descriptor, if available. */
  571. current_desc = next_desc;
  572. /* check if there is a next descriptor. */
  573. if (!current_desc ||
  574. strcmpstart(current_desc, "rendezvous-service-descriptor "))
  575. break;
  576. }
  577. if (!number_parsed) {
  578. log_info(LD_REND, "Could not parse any descriptor.");
  579. return RCS_BADDESC;
  580. }
  581. log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
  582. number_parsed, number_stored, number_stored != 1 ? "s" : "");
  583. return RCS_OKAY;
  584. }
  585. /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
  586. * of introduction points with <b>descriptor_cookie</b> (which may also be
  587. * <b>NULL</b> if decryption is not necessary), and store the descriptor to
  588. * the local cache under its version and service id.
  589. *
  590. * If we have a newer v2 descriptor with the same ID, ignore this one.
  591. * If we have an older descriptor with the same ID, replace it.
  592. * If the descriptor's service ID does not match
  593. * <b>rend_query</b>-\>onion_address, reject it.
  594. *
  595. * If the descriptor's descriptor ID doesn't match <b>desc_id_base32</b>,
  596. * reject it.
  597. *
  598. * Return an appropriate rend_cache_store_status_t. If entry is not NULL,
  599. * set it with the cache entry pointer of the descriptor.
  600. */
  601. rend_cache_store_status_t
  602. rend_cache_store_v2_desc_as_client(const char *desc,
  603. const char *desc_id_base32,
  604. const rend_data_t *rend_query,
  605. rend_cache_entry_t **entry)
  606. {
  607. /*XXXX this seems to have a bit of duplicate code with
  608. * rend_cache_store_v2_desc_as_dir(). Fix that. */
  609. /* Though having similar elements, both functions were separated on
  610. * purpose:
  611. * - dirs don't care about encoded/encrypted introduction points, clients
  612. * do.
  613. * - dirs store descriptors in a separate cache by descriptor ID, whereas
  614. * clients store them by service ID; both caches are different data
  615. * structures and have different access methods.
  616. * - dirs store a descriptor only if they are responsible for its ID,
  617. * clients do so in every way (because they have requested it before).
  618. * - dirs can process multiple concatenated descriptors which is required
  619. * for replication, whereas clients only accept a single descriptor.
  620. * Thus, combining both methods would result in a lot of if statements
  621. * which probably would not improve, but worsen code readability. -KL */
  622. rend_service_descriptor_t *parsed = NULL;
  623. char desc_id[DIGEST_LEN];
  624. char *intro_content = NULL;
  625. size_t intro_size;
  626. size_t encoded_size;
  627. const char *next_desc;
  628. time_t now = time(NULL);
  629. char key[REND_SERVICE_ID_LEN_BASE32+2];
  630. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  631. char want_desc_id[DIGEST_LEN];
  632. rend_cache_entry_t *e;
  633. rend_cache_store_status_t retval = RCS_BADDESC;
  634. tor_assert(rend_cache);
  635. tor_assert(desc);
  636. tor_assert(desc_id_base32);
  637. memset(want_desc_id, 0, sizeof(want_desc_id));
  638. if (entry) {
  639. *entry = NULL;
  640. }
  641. if (base32_decode(want_desc_id, sizeof(want_desc_id),
  642. desc_id_base32, strlen(desc_id_base32)) != 0) {
  643. log_warn(LD_BUG, "Couldn't decode base32 %s for descriptor id.",
  644. escaped_safe_str_client(desc_id_base32));
  645. goto err;
  646. }
  647. /* Parse the descriptor. */
  648. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  649. &intro_size, &encoded_size,
  650. &next_desc, desc, 0) < 0) {
  651. log_warn(LD_REND, "Could not parse descriptor.");
  652. goto err;
  653. }
  654. /* Compute service ID from public key. */
  655. if (rend_get_service_id(parsed->pk, service_id)<0) {
  656. log_warn(LD_REND, "Couldn't compute service ID.");
  657. goto err;
  658. }
  659. if (rend_query->onion_address[0] != '\0' &&
  660. strcmp(rend_query->onion_address, service_id)) {
  661. log_warn(LD_REND, "Received service descriptor for service ID %s; "
  662. "expected descriptor for service ID %s.",
  663. service_id, safe_str(rend_query->onion_address));
  664. goto err;
  665. }
  666. if (tor_memneq(desc_id, want_desc_id, DIGEST_LEN)) {
  667. log_warn(LD_REND, "Received service descriptor for %s with incorrect "
  668. "descriptor ID.", service_id);
  669. goto err;
  670. }
  671. /* Decode/decrypt introduction points. */
  672. if (intro_content && intro_size > 0) {
  673. int n_intro_points;
  674. if (rend_query->auth_type != REND_NO_AUTH &&
  675. !tor_mem_is_zero(rend_query->descriptor_cookie,
  676. sizeof(rend_query->descriptor_cookie))) {
  677. char *ipos_decrypted = NULL;
  678. size_t ipos_decrypted_size;
  679. if (rend_decrypt_introduction_points(&ipos_decrypted,
  680. &ipos_decrypted_size,
  681. rend_query->descriptor_cookie,
  682. intro_content,
  683. intro_size) < 0) {
  684. log_warn(LD_REND, "Failed to decrypt introduction points. We are "
  685. "probably unable to parse the encoded introduction points.");
  686. } else {
  687. /* Replace encrypted with decrypted introduction points. */
  688. log_info(LD_REND, "Successfully decrypted introduction points.");
  689. tor_free(intro_content);
  690. intro_content = ipos_decrypted;
  691. intro_size = ipos_decrypted_size;
  692. }
  693. }
  694. n_intro_points = rend_parse_introduction_points(parsed, intro_content,
  695. intro_size);
  696. if (n_intro_points <= 0) {
  697. log_warn(LD_REND, "Failed to parse introduction points. Either the "
  698. "service has published a corrupt descriptor or you have "
  699. "provided invalid authorization data.");
  700. goto err;
  701. } else if (n_intro_points > MAX_INTRO_POINTS) {
  702. log_warn(LD_REND, "Found too many introduction points on a hidden "
  703. "service descriptor for %s. This is probably a (misguided) "
  704. "attempt to improve reliability, but it could also be an "
  705. "attempt to do a guard enumeration attack. Rejecting.",
  706. safe_str_client(service_id));
  707. goto err;
  708. }
  709. } else {
  710. log_info(LD_REND, "Descriptor does not contain any introduction points.");
  711. parsed->intro_nodes = smartlist_new();
  712. }
  713. /* We don't need the encoded/encrypted introduction points any longer. */
  714. tor_free(intro_content);
  715. /* Is descriptor too old? */
  716. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  717. log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
  718. safe_str_client(service_id));
  719. goto err;
  720. }
  721. /* Is descriptor too far in the future? */
  722. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  723. log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
  724. "the future.", safe_str_client(service_id));
  725. goto err;
  726. }
  727. /* Do we have the same exact copy already in our cache? */
  728. tor_snprintf(key, sizeof(key), "2%s", service_id);
  729. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  730. if (e && !strcmp(desc, e->desc)) {
  731. log_info(LD_REND,"We already have this service descriptor %s.",
  732. safe_str_client(service_id));
  733. goto okay;
  734. }
  735. /* Verify that we are not replacing an older descriptor. It's important to
  736. * avoid an evil HSDir serving old descriptor. We validate if the
  737. * timestamp is greater than and not equal because it's a rounded down
  738. * timestamp to the hour so if the descriptor changed in the same hour,
  739. * the rend cache failure will tells us if we have a new descriptor. */
  740. if (e && e->parsed->timestamp > parsed->timestamp) {
  741. log_info(LD_REND, "We already have a new enough service descriptor for "
  742. "service ID %s with the same desc ID and version.",
  743. safe_str_client(service_id));
  744. goto okay;
  745. }
  746. /* Lookup our failure cache for intro point that might be unsuable. */
  747. validate_intro_point_failure(parsed, service_id);
  748. /* It's now possible that our intro point list is empty, this means that
  749. * this descriptor is useless to us because intro points have all failed
  750. * somehow before. Discard the descriptor. */
  751. if (smartlist_len(parsed->intro_nodes) == 0) {
  752. log_info(LD_REND, "Service descriptor with service ID %s, every "
  753. "intro points are unusable. Discarding it.",
  754. safe_str_client(service_id));
  755. goto err;
  756. }
  757. /* Now either purge the current one and replace it's content or create a
  758. * new one and add it to the rend cache. */
  759. if (!e) {
  760. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  761. strmap_set_lc(rend_cache, key, e);
  762. } else {
  763. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  764. rend_cache_failure_remove(e->parsed);
  765. rend_service_descriptor_free(e->parsed);
  766. tor_free(e->desc);
  767. }
  768. e->parsed = parsed;
  769. e->desc = tor_malloc_zero(encoded_size + 1);
  770. strlcpy(e->desc, desc, encoded_size + 1);
  771. e->len = encoded_size;
  772. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  773. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  774. safe_str_client(service_id), (int)encoded_size);
  775. if (entry) {
  776. *entry = e;
  777. }
  778. return RCS_OKAY;
  779. okay:
  780. if (entry) {
  781. *entry = e;
  782. }
  783. retval = RCS_OKAY;
  784. err:
  785. rend_service_descriptor_free(parsed);
  786. tor_free(intro_content);
  787. return retval;
  788. }