rendcache.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. /** Add an intro point failure to the failure cache using the relay
  316. * <b>identity</b> and service ID <b>service_id</b>. Record the
  317. * <b>failure</b> in that object. */
  318. static void
  319. cache_failure_intro_add(const uint8_t *identity, const char *service_id,
  320. rend_intro_point_failure_t failure)
  321. {
  322. rend_cache_failure_t *fail_entry;
  323. rend_cache_failure_intro_t *entry;
  324. /* Make sure we have a failure object for this service ID and if not,
  325. * create it with this new intro failure entry. */
  326. fail_entry = strmap_get_lc(rend_cache_failure, service_id);
  327. if (fail_entry == NULL) {
  328. fail_entry = rend_cache_failure_entry_new();
  329. /* Add failure entry to global rend failure cache. */
  330. strmap_set_lc(rend_cache_failure, service_id, fail_entry);
  331. }
  332. entry = rend_cache_failure_intro_entry_new(failure);
  333. digestmap_set(fail_entry->intro_failures, (char *) identity, entry);
  334. }
  335. /** Using a parsed descriptor <b>desc</b>, check if the introduction points
  336. * are present in the failure cache and if so they are removed from the
  337. * descriptor and kept into the failure cache. Then, each intro points that
  338. * are NOT in the descriptor but in the failure cache for the given
  339. * <b>service_id</b> are removed from the failure cache. */
  340. static void
  341. validate_intro_point_failure(const rend_service_descriptor_t *desc,
  342. const char *service_id)
  343. {
  344. rend_cache_failure_t *new_entry, *cur_entry;
  345. /* New entry for the service ID that will be replacing the one in the
  346. * failure cache since we have a new descriptor. In the case where all
  347. * intro points are removed, we are assured that the new entry is the same
  348. * as the current one. */
  349. new_entry = tor_malloc(sizeof(*new_entry));
  350. new_entry->intro_failures = digestmap_new();
  351. tor_assert(desc);
  352. SMARTLIST_FOREACH_BEGIN(desc->intro_nodes, rend_intro_point_t *, intro) {
  353. int found;
  354. rend_cache_failure_intro_t *entry;
  355. const uint8_t *identity =
  356. (uint8_t *) intro->extend_info->identity_digest;
  357. found = cache_failure_intro_lookup(identity, service_id, &entry);
  358. if (found) {
  359. /* This intro point is in our cache, discard it from the descriptor
  360. * because chances are that it's unusable. */
  361. SMARTLIST_DEL_CURRENT(desc->intro_nodes, intro);
  362. rend_intro_point_free(intro);
  363. /* Keep it for our new entry. */
  364. digestmap_set(new_entry->intro_failures, (char *) identity, entry);
  365. continue;
  366. }
  367. } SMARTLIST_FOREACH_END(intro);
  368. /* Swap the failure entry in the cache and free the current one. */
  369. cur_entry = strmap_get_lc(rend_cache_failure, service_id);
  370. if (cur_entry != NULL) {
  371. rend_cache_failure_entry_free(cur_entry);
  372. }
  373. strmap_set_lc(rend_cache_failure, service_id, new_entry);
  374. }
  375. /** Note down an intro failure in the rend failure cache using the type of
  376. * failure in <b>failure</b> for the relay identity digest in
  377. * <b>identity</b> and service ID <b>service_id</b>. If an entry already
  378. * exists in the cache, the failure type is changed with <b>failure</b>. */
  379. void
  380. rend_cache_intro_failure_note(rend_intro_point_failure_t failure,
  381. const uint8_t *identity,
  382. const char *service_id)
  383. {
  384. int found;
  385. rend_cache_failure_intro_t *entry;
  386. found = cache_failure_intro_lookup(identity, service_id, &entry);
  387. if (!found) {
  388. cache_failure_intro_add(identity, service_id, failure);
  389. } else {
  390. /* Replace introduction point failure with this one. */
  391. entry->failure_type = failure;
  392. }
  393. }
  394. /** Remove all old v2 descriptors and those for which this hidden service
  395. * directory is not responsible for any more.
  396. *
  397. * If at all possible, remove at least <b>force_remove</b> bytes of data.
  398. */
  399. void
  400. rend_cache_clean_v2_descs_as_dir(time_t now, size_t force_remove)
  401. {
  402. digestmap_iter_t *iter;
  403. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  404. const int LAST_SERVED_CUTOFF_STEP = 1800;
  405. time_t last_served_cutoff = cutoff;
  406. size_t bytes_removed = 0;
  407. do {
  408. for (iter = digestmap_iter_init(rend_cache_v2_dir);
  409. !digestmap_iter_done(iter); ) {
  410. const char *key;
  411. void *val;
  412. rend_cache_entry_t *ent;
  413. digestmap_iter_get(iter, &key, &val);
  414. ent = val;
  415. if (ent->parsed->timestamp < cutoff ||
  416. ent->last_served < last_served_cutoff ||
  417. !hid_serv_responsible_for_desc_id(key)) {
  418. char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  419. base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
  420. log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
  421. safe_str_client(key_base32));
  422. bytes_removed += rend_cache_entry_allocation(ent);
  423. iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
  424. rend_cache_entry_free(ent);
  425. } else {
  426. iter = digestmap_iter_next(rend_cache_v2_dir, iter);
  427. }
  428. }
  429. /* In case we didn't remove enough bytes, advance the cutoff a little. */
  430. last_served_cutoff += LAST_SERVED_CUTOFF_STEP;
  431. if (last_served_cutoff > now)
  432. break;
  433. } while (bytes_removed < force_remove);
  434. }
  435. /** Lookup in the client cache the given service ID <b>query</b> for
  436. * <b>version</b>.
  437. *
  438. * Return 0 if found and if <b>e</b> is non NULL, set it with the entry
  439. * found. Else, a negative value is returned and <b>e</b> is untouched.
  440. * -EINVAL means that <b>query</b> is not a valid service id.
  441. * -ENOENT means that no entry in the cache was found. */
  442. int
  443. rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
  444. {
  445. int ret = 0;
  446. char key[REND_SERVICE_ID_LEN_BASE32 + 2]; /* <version><query>\0 */
  447. rend_cache_entry_t *entry = NULL;
  448. static const int default_version = 2;
  449. tor_assert(rend_cache);
  450. tor_assert(query);
  451. if (!rend_valid_service_id(query)) {
  452. ret = -EINVAL;
  453. goto end;
  454. }
  455. switch (version) {
  456. case 0:
  457. log_warn(LD_REND, "Cache lookup of a v0 renddesc is deprecated.");
  458. break;
  459. case 2:
  460. /* Default is version 2. */
  461. default:
  462. tor_snprintf(key, sizeof(key), "%d%s", default_version, query);
  463. entry = strmap_get_lc(rend_cache, key);
  464. break;
  465. }
  466. if (!entry) {
  467. ret = -ENOENT;
  468. goto end;
  469. }
  470. tor_assert(entry->parsed && entry->parsed->intro_nodes);
  471. if (e) {
  472. *e = entry;
  473. }
  474. end:
  475. return ret;
  476. }
  477. /*
  478. * Lookup the v2 service descriptor with the service ID <b>query</b> in the
  479. * local service descriptor cache. Return 0 if found and if <b>e</b> is
  480. * non NULL, set it with the entry found. Else, a negative value is returned
  481. * and <b>e</b> is untouched.
  482. * -EINVAL means that <b>query</b> is not a valid service id.
  483. * -ENOENT means that no entry in the cache was found. */
  484. int
  485. rend_cache_lookup_v2_desc_as_service(const char *query, rend_cache_entry_t **e)
  486. {
  487. int ret = 0;
  488. rend_cache_entry_t *entry = NULL;
  489. tor_assert(rend_cache_local_service);
  490. tor_assert(query);
  491. if (!rend_valid_service_id(query)) {
  492. ret = -EINVAL;
  493. goto end;
  494. }
  495. /* Lookup descriptor and return. */
  496. entry = strmap_get_lc(rend_cache_local_service, query);
  497. if (!entry) {
  498. ret = -ENOENT;
  499. goto end;
  500. }
  501. if (e) {
  502. *e = entry;
  503. }
  504. end:
  505. return ret;
  506. }
  507. /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
  508. * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
  509. * well-formed-but-not-found, and -1 on failure.
  510. */
  511. int
  512. rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
  513. {
  514. rend_cache_entry_t *e;
  515. char desc_id_digest[DIGEST_LEN];
  516. tor_assert(rend_cache_v2_dir);
  517. if (base32_decode(desc_id_digest, DIGEST_LEN,
  518. desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
  519. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  520. "Rejecting v2 rendezvous descriptor request -- descriptor ID "
  521. "contains illegal characters: %s",
  522. safe_str(desc_id));
  523. return -1;
  524. }
  525. /* Lookup descriptor and return. */
  526. e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
  527. if (e) {
  528. *desc = e->desc;
  529. e->last_served = approx_time();
  530. return 1;
  531. }
  532. return 0;
  533. }
  534. /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
  535. * local rend cache. Don't attempt to decrypt the included list of introduction
  536. * points (as we don't have a descriptor cookie for it).
  537. *
  538. * If we have a newer descriptor with the same ID, ignore this one.
  539. * If we have an older descriptor with the same ID, replace it.
  540. *
  541. * Return an appropriate rend_cache_store_status_t.
  542. */
  543. rend_cache_store_status_t
  544. rend_cache_store_v2_desc_as_dir(const char *desc)
  545. {
  546. const or_options_t *options = get_options();
  547. rend_service_descriptor_t *parsed;
  548. char desc_id[DIGEST_LEN];
  549. char *intro_content;
  550. size_t intro_size;
  551. size_t encoded_size;
  552. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  553. int number_parsed = 0, number_stored = 0;
  554. const char *current_desc = desc;
  555. const char *next_desc;
  556. rend_cache_entry_t *e;
  557. time_t now = time(NULL);
  558. tor_assert(rend_cache_v2_dir);
  559. tor_assert(desc);
  560. if (!hid_serv_acting_as_directory()) {
  561. /* Cannot store descs, because we are (currently) not acting as
  562. * hidden service directory. */
  563. log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
  564. return RCS_NOTDIR;
  565. }
  566. while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  567. &intro_size, &encoded_size,
  568. &next_desc, current_desc, 1) >= 0) {
  569. number_parsed++;
  570. /* We don't care about the introduction points. */
  571. tor_free(intro_content);
  572. /* For pretty log statements. */
  573. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  574. desc_id, DIGEST_LEN);
  575. /* Is desc ID in the range that we are (directly or indirectly) responsible
  576. * for? */
  577. if (!hid_serv_responsible_for_desc_id(desc_id)) {
  578. log_info(LD_REND, "Service descriptor with desc ID %s is not in "
  579. "interval that we are responsible for.",
  580. safe_str_client(desc_id_base32));
  581. goto skip;
  582. }
  583. /* Is descriptor too old? */
  584. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  585. log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
  586. safe_str(desc_id_base32));
  587. goto skip;
  588. }
  589. /* Is descriptor too far in the future? */
  590. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  591. log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
  592. "future.",
  593. safe_str(desc_id_base32));
  594. goto skip;
  595. }
  596. /* Do we already have a newer descriptor? */
  597. e = digestmap_get(rend_cache_v2_dir, desc_id);
  598. if (e && e->parsed->timestamp > parsed->timestamp) {
  599. log_info(LD_REND, "We already have a newer service descriptor with the "
  600. "same desc ID %s and version.",
  601. safe_str(desc_id_base32));
  602. goto skip;
  603. }
  604. /* Do we already have this descriptor? */
  605. if (e && !strcmp(desc, e->desc)) {
  606. log_info(LD_REND, "We already have this service descriptor with desc "
  607. "ID %s.", safe_str(desc_id_base32));
  608. goto skip;
  609. }
  610. /* Store received descriptor. */
  611. if (!e) {
  612. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  613. digestmap_set(rend_cache_v2_dir, desc_id, e);
  614. /* Treat something just uploaded as having been served a little
  615. * while ago, so that flooding with new descriptors doesn't help
  616. * too much.
  617. */
  618. e->last_served = approx_time() - 3600;
  619. } else {
  620. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  621. rend_service_descriptor_free(e->parsed);
  622. tor_free(e->desc);
  623. }
  624. e->parsed = parsed;
  625. e->desc = tor_strndup(current_desc, encoded_size);
  626. e->len = encoded_size;
  627. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  628. log_info(LD_REND, "Successfully stored service descriptor with desc ID "
  629. "'%s' and len %d.",
  630. safe_str(desc_id_base32), (int)encoded_size);
  631. /* Statistics: Note down this potentially new HS. */
  632. if (options->HiddenServiceStatistics) {
  633. rep_hist_stored_maybe_new_hs(e->parsed->pk);
  634. }
  635. number_stored++;
  636. goto advance;
  637. skip:
  638. rend_service_descriptor_free(parsed);
  639. advance:
  640. /* advance to next descriptor, if available. */
  641. current_desc = next_desc;
  642. /* check if there is a next descriptor. */
  643. if (!current_desc ||
  644. strcmpstart(current_desc, "rendezvous-service-descriptor "))
  645. break;
  646. }
  647. if (!number_parsed) {
  648. log_info(LD_REND, "Could not parse any descriptor.");
  649. return RCS_BADDESC;
  650. }
  651. log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
  652. number_parsed, number_stored, number_stored != 1 ? "s" : "");
  653. return RCS_OKAY;
  654. }
  655. /** Parse the v2 service descriptor in <b>desc</b> and store it to the
  656. * local service rend cache. Don't attempt to decrypt the included list of
  657. * introduction points.
  658. *
  659. * If we have a newer descriptor with the same ID, ignore this one.
  660. * If we have an older descriptor with the same ID, replace it.
  661. *
  662. * Return an appropriate rend_cache_store_status_t.
  663. */
  664. rend_cache_store_status_t
  665. rend_cache_store_v2_desc_as_service(const char *desc)
  666. {
  667. rend_service_descriptor_t *parsed = NULL;
  668. char desc_id[DIGEST_LEN];
  669. char *intro_content = NULL;
  670. size_t intro_size;
  671. size_t encoded_size;
  672. const char *next_desc;
  673. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  674. rend_cache_entry_t *e;
  675. rend_cache_store_status_t retval = RCS_BADDESC;
  676. tor_assert(rend_cache_local_service);
  677. tor_assert(desc);
  678. /* Parse the descriptor. */
  679. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  680. &intro_size, &encoded_size,
  681. &next_desc, desc, 0) < 0) {
  682. log_warn(LD_REND, "Could not parse descriptor.");
  683. goto err;
  684. }
  685. /* Compute service ID from public key. */
  686. if (rend_get_service_id(parsed->pk, service_id)<0) {
  687. log_warn(LD_REND, "Couldn't compute service ID.");
  688. goto err;
  689. }
  690. /* Do we already have a newer descriptor? Allow new descriptors with a
  691. rounded timestamp equal to or newer than the current descriptor */
  692. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache_local_service,
  693. service_id);
  694. if (e && e->parsed->timestamp > parsed->timestamp) {
  695. log_info(LD_REND, "We already have a newer service descriptor for "
  696. "service ID %s.", safe_str_client(service_id));
  697. goto okay;
  698. }
  699. /* We don't care about the introduction points. */
  700. tor_free(intro_content);
  701. if (!e) {
  702. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  703. strmap_set_lc(rend_cache_local_service, service_id, e);
  704. } else {
  705. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  706. rend_service_descriptor_free(e->parsed);
  707. tor_free(e->desc);
  708. }
  709. e->parsed = parsed;
  710. e->desc = tor_malloc_zero(encoded_size + 1);
  711. strlcpy(e->desc, desc, encoded_size + 1);
  712. e->len = encoded_size;
  713. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  714. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  715. safe_str_client(service_id), (int)encoded_size);
  716. return RCS_OKAY;
  717. okay:
  718. retval = RCS_OKAY;
  719. err:
  720. rend_service_descriptor_free(parsed);
  721. tor_free(intro_content);
  722. return retval;
  723. }
  724. /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
  725. * of introduction points with <b>descriptor_cookie</b> (which may also be
  726. * <b>NULL</b> if decryption is not necessary), and store the descriptor to
  727. * the local cache under its version and service id.
  728. *
  729. * If we have a newer v2 descriptor with the same ID, ignore this one.
  730. * If we have an older descriptor with the same ID, replace it.
  731. * If the descriptor's service ID does not match
  732. * <b>rend_query</b>-\>onion_address, reject it.
  733. *
  734. * If the descriptor's descriptor ID doesn't match <b>desc_id_base32</b>,
  735. * reject it.
  736. *
  737. * Return an appropriate rend_cache_store_status_t. If entry is not NULL,
  738. * set it with the cache entry pointer of the descriptor.
  739. */
  740. rend_cache_store_status_t
  741. rend_cache_store_v2_desc_as_client(const char *desc,
  742. const char *desc_id_base32,
  743. const rend_data_t *rend_query,
  744. rend_cache_entry_t **entry)
  745. {
  746. /*XXXX this seems to have a bit of duplicate code with
  747. * rend_cache_store_v2_desc_as_dir(). Fix that. */
  748. /* Though having similar elements, both functions were separated on
  749. * purpose:
  750. * - dirs don't care about encoded/encrypted introduction points, clients
  751. * do.
  752. * - dirs store descriptors in a separate cache by descriptor ID, whereas
  753. * clients store them by service ID; both caches are different data
  754. * structures and have different access methods.
  755. * - dirs store a descriptor only if they are responsible for its ID,
  756. * clients do so in every way (because they have requested it before).
  757. * - dirs can process multiple concatenated descriptors which is required
  758. * for replication, whereas clients only accept a single descriptor.
  759. * Thus, combining both methods would result in a lot of if statements
  760. * which probably would not improve, but worsen code readability. -KL */
  761. rend_service_descriptor_t *parsed = NULL;
  762. char desc_id[DIGEST_LEN];
  763. char *intro_content = NULL;
  764. size_t intro_size;
  765. size_t encoded_size;
  766. const char *next_desc;
  767. time_t now = time(NULL);
  768. char key[REND_SERVICE_ID_LEN_BASE32+2];
  769. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  770. char want_desc_id[DIGEST_LEN];
  771. rend_cache_entry_t *e;
  772. rend_cache_store_status_t retval = RCS_BADDESC;
  773. tor_assert(rend_cache);
  774. tor_assert(desc);
  775. tor_assert(desc_id_base32);
  776. memset(want_desc_id, 0, sizeof(want_desc_id));
  777. if (entry) {
  778. *entry = NULL;
  779. }
  780. if (base32_decode(want_desc_id, sizeof(want_desc_id),
  781. desc_id_base32, strlen(desc_id_base32)) != 0) {
  782. log_warn(LD_BUG, "Couldn't decode base32 %s for descriptor id.",
  783. escaped_safe_str_client(desc_id_base32));
  784. goto err;
  785. }
  786. /* Parse the descriptor. */
  787. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  788. &intro_size, &encoded_size,
  789. &next_desc, desc, 0) < 0) {
  790. log_warn(LD_REND, "Could not parse descriptor.");
  791. goto err;
  792. }
  793. /* Compute service ID from public key. */
  794. if (rend_get_service_id(parsed->pk, service_id)<0) {
  795. log_warn(LD_REND, "Couldn't compute service ID.");
  796. goto err;
  797. }
  798. if (rend_query->onion_address[0] != '\0' &&
  799. strcmp(rend_query->onion_address, service_id)) {
  800. log_warn(LD_REND, "Received service descriptor for service ID %s; "
  801. "expected descriptor for service ID %s.",
  802. service_id, safe_str(rend_query->onion_address));
  803. goto err;
  804. }
  805. if (tor_memneq(desc_id, want_desc_id, DIGEST_LEN)) {
  806. log_warn(LD_REND, "Received service descriptor for %s with incorrect "
  807. "descriptor ID.", service_id);
  808. goto err;
  809. }
  810. /* Decode/decrypt introduction points. */
  811. if (intro_content && intro_size > 0) {
  812. int n_intro_points;
  813. if (rend_query->auth_type != REND_NO_AUTH &&
  814. !tor_mem_is_zero(rend_query->descriptor_cookie,
  815. sizeof(rend_query->descriptor_cookie))) {
  816. char *ipos_decrypted = NULL;
  817. size_t ipos_decrypted_size;
  818. if (rend_decrypt_introduction_points(&ipos_decrypted,
  819. &ipos_decrypted_size,
  820. rend_query->descriptor_cookie,
  821. intro_content,
  822. intro_size) < 0) {
  823. log_warn(LD_REND, "Failed to decrypt introduction points. We are "
  824. "probably unable to parse the encoded introduction points.");
  825. } else {
  826. /* Replace encrypted with decrypted introduction points. */
  827. log_info(LD_REND, "Successfully decrypted introduction points.");
  828. tor_free(intro_content);
  829. intro_content = ipos_decrypted;
  830. intro_size = ipos_decrypted_size;
  831. }
  832. }
  833. n_intro_points = rend_parse_introduction_points(parsed, intro_content,
  834. intro_size);
  835. if (n_intro_points <= 0) {
  836. log_warn(LD_REND, "Failed to parse introduction points. Either the "
  837. "service has published a corrupt descriptor or you have "
  838. "provided invalid authorization data.");
  839. goto err;
  840. } else if (n_intro_points > MAX_INTRO_POINTS) {
  841. log_warn(LD_REND, "Found too many introduction points on a hidden "
  842. "service descriptor for %s. This is probably a (misguided) "
  843. "attempt to improve reliability, but it could also be an "
  844. "attempt to do a guard enumeration attack. Rejecting.",
  845. safe_str_client(service_id));
  846. goto err;
  847. }
  848. } else {
  849. log_info(LD_REND, "Descriptor does not contain any introduction points.");
  850. parsed->intro_nodes = smartlist_new();
  851. }
  852. /* We don't need the encoded/encrypted introduction points any longer. */
  853. tor_free(intro_content);
  854. /* Is descriptor too old? */
  855. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  856. log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
  857. safe_str_client(service_id));
  858. goto err;
  859. }
  860. /* Is descriptor too far in the future? */
  861. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  862. log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
  863. "the future.", safe_str_client(service_id));
  864. goto err;
  865. }
  866. /* Do we have the same exact copy already in our cache? */
  867. tor_snprintf(key, sizeof(key), "2%s", service_id);
  868. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  869. if (e && !strcmp(desc, e->desc)) {
  870. log_info(LD_REND,"We already have this service descriptor %s.",
  871. safe_str_client(service_id));
  872. goto okay;
  873. }
  874. /* Verify that we are not replacing an older descriptor. It's important to
  875. * avoid an evil HSDir serving old descriptor. We validate if the
  876. * timestamp is greater than and not equal because it's a rounded down
  877. * timestamp to the hour so if the descriptor changed in the same hour,
  878. * the rend cache failure will tells us if we have a new descriptor. */
  879. if (e && e->parsed->timestamp > parsed->timestamp) {
  880. log_info(LD_REND, "We already have a new enough service descriptor for "
  881. "service ID %s with the same desc ID and version.",
  882. safe_str_client(service_id));
  883. goto okay;
  884. }
  885. /* Lookup our failure cache for intro point that might be unsuable. */
  886. validate_intro_point_failure(parsed, service_id);
  887. /* It's now possible that our intro point list is empty, this means that
  888. * this descriptor is useless to us because intro points have all failed
  889. * somehow before. Discard the descriptor. */
  890. if (smartlist_len(parsed->intro_nodes) == 0) {
  891. log_info(LD_REND, "Service descriptor with service ID %s, every "
  892. "intro points are unusable. Discarding it.",
  893. safe_str_client(service_id));
  894. goto err;
  895. }
  896. /* Now either purge the current one and replace it's content or create a
  897. * new one and add it to the rend cache. */
  898. if (!e) {
  899. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  900. strmap_set_lc(rend_cache, key, e);
  901. } else {
  902. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  903. rend_cache_failure_remove(e->parsed);
  904. rend_service_descriptor_free(e->parsed);
  905. tor_free(e->desc);
  906. }
  907. e->parsed = parsed;
  908. e->desc = tor_malloc_zero(encoded_size + 1);
  909. strlcpy(e->desc, desc, encoded_size + 1);
  910. e->len = encoded_size;
  911. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  912. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  913. safe_str_client(service_id), (int)encoded_size);
  914. if (entry) {
  915. *entry = e;
  916. }
  917. return RCS_OKAY;
  918. okay:
  919. if (entry) {
  920. *entry = e;
  921. }
  922. retval = RCS_OKAY;
  923. err:
  924. rend_service_descriptor_free(parsed);
  925. tor_free(intro_content);
  926. return retval;
  927. }