rendcache.c 35 KB

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