rendcache.c 35 KB

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