rendcache.c 31 KB

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