rendcache.c 35 KB

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