rendcache.c 34 KB

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