rendcache.c 34 KB

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