rendcache.c 35 KB

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