hs_cache.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. /* Copyright (c) 2016-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_cache.c
  5. * \brief Handle hidden service descriptor caches.
  6. **/
  7. /* For unit tests.*/
  8. #define HS_CACHE_PRIVATE
  9. #include "core/or/or.h"
  10. #include "app/config/config.h"
  11. #include "lib/crypt_ops/crypto_format.h"
  12. #include "lib/crypt_ops/crypto_util.h"
  13. #include "feature/hs/hs_ident.h"
  14. #include "feature/hs/hs_common.h"
  15. #include "feature/hs/hs_client.h"
  16. #include "feature/hs/hs_descriptor.h"
  17. #include "feature/nodelist/networkstatus.h"
  18. #include "feature/rend/rendcache.h"
  19. #include "feature/hs/hs_cache.h"
  20. #include "feature/nodelist/networkstatus_st.h"
  21. #define SUBPROCESS_PRIVATE
  22. #include "lib/process/env.h"
  23. #include "lib/process/subprocess.h"
  24. #include "lib/evloop/compat_libevent.h"
  25. #include <event2/event.h>
  26. #ifdef HAVE_UNISTD_H
  27. #include <unistd.h>
  28. #endif
  29. static int cached_client_descriptor_has_expired(time_t now,
  30. const hs_cache_client_descriptor_t *cached_desc);
  31. /********************** Directory HS cache ******************/
  32. /* Directory descriptor cache. Map indexed by blinded key. */
  33. static digest256map_t *hs_cache_v3_dir;
  34. /* Remove a given descriptor from our cache. */
  35. static void
  36. remove_v3_desc_as_dir(const hs_cache_dir_descriptor_t *desc)
  37. {
  38. tor_assert(desc);
  39. digest256map_remove(hs_cache_v3_dir, desc->key);
  40. }
  41. /* Store a given descriptor in our cache. */
  42. static void
  43. store_v3_desc_as_dir(hs_cache_dir_descriptor_t *desc)
  44. {
  45. tor_assert(desc);
  46. digest256map_set(hs_cache_v3_dir, desc->key, desc);
  47. }
  48. /* Query our cache and return the entry or NULL if not found. */
  49. static hs_cache_dir_descriptor_t *
  50. lookup_v3_desc_as_dir(const uint8_t *key)
  51. {
  52. tor_assert(key);
  53. return digest256map_get(hs_cache_v3_dir, key);
  54. }
  55. #define cache_dir_desc_free(val) \
  56. FREE_AND_NULL(hs_cache_dir_descriptor_t, cache_dir_desc_free_, (val))
  57. /* Free a directory descriptor object. */
  58. static void
  59. cache_dir_desc_free_(hs_cache_dir_descriptor_t *desc)
  60. {
  61. if (desc == NULL) {
  62. return;
  63. }
  64. hs_desc_plaintext_data_free(desc->plaintext_data);
  65. tor_free(desc->encoded_desc);
  66. tor_free(desc);
  67. }
  68. /* Helper function: Use by the free all function using the digest256map
  69. * interface to cache entries. */
  70. static void
  71. cache_dir_desc_free_void(void *ptr)
  72. {
  73. cache_dir_desc_free_(ptr);
  74. }
  75. /* Create a new directory cache descriptor object from a encoded descriptor.
  76. * On success, return the heap-allocated cache object, otherwise return NULL if
  77. * we can't decode the descriptor. */
  78. static hs_cache_dir_descriptor_t *
  79. cache_dir_desc_new(const char *desc)
  80. {
  81. hs_cache_dir_descriptor_t *dir_desc;
  82. tor_assert(desc);
  83. dir_desc = tor_malloc_zero(sizeof(hs_cache_dir_descriptor_t));
  84. dir_desc->plaintext_data =
  85. tor_malloc_zero(sizeof(hs_desc_plaintext_data_t));
  86. dir_desc->encoded_desc = tor_strdup(desc);
  87. if (hs_desc_decode_plaintext(desc, dir_desc->plaintext_data) < 0) {
  88. log_debug(LD_DIR, "Unable to decode descriptor. Rejecting.");
  89. goto err;
  90. }
  91. /* The blinded pubkey is the indexed key. */
  92. dir_desc->key = dir_desc->plaintext_data->blinded_pubkey.pubkey;
  93. dir_desc->created_ts = time(NULL);
  94. return dir_desc;
  95. err:
  96. cache_dir_desc_free(dir_desc);
  97. return NULL;
  98. }
  99. /* Return the size of a cache entry in bytes. */
  100. static size_t
  101. cache_get_dir_entry_size(const hs_cache_dir_descriptor_t *entry)
  102. {
  103. return (sizeof(*entry) + hs_desc_plaintext_obj_size(entry->plaintext_data)
  104. + strlen(entry->encoded_desc));
  105. }
  106. // PIRONION: v3 store
  107. static int
  108. hs_cache_pirserver_insert_desc(hs_cache_dir_descriptor_t *desc);
  109. /* Try to store a valid version 3 descriptor in the directory cache. Return 0
  110. * on success else a negative value is returned indicating that we have a
  111. * newer version in our cache. On error, caller is responsible to free the
  112. * given descriptor desc. */
  113. static int
  114. cache_store_v3_as_dir(hs_cache_dir_descriptor_t *desc)
  115. {
  116. hs_cache_dir_descriptor_t *cache_entry;
  117. tor_assert(desc);
  118. /* Verify if we have an entry in the cache for that key and if yes, check
  119. * if we should replace it? */
  120. cache_entry = lookup_v3_desc_as_dir(desc->key);
  121. if (cache_entry != NULL) {
  122. /* Only replace descriptor if revision-counter is greater than the one
  123. * in our cache */
  124. if (cache_entry->plaintext_data->revision_counter >=
  125. desc->plaintext_data->revision_counter) {
  126. log_info(LD_REND, "Descriptor revision counter in our cache is "
  127. "greater or equal than the one we received (%d/%d). "
  128. "Rejecting!",
  129. (int)cache_entry->plaintext_data->revision_counter,
  130. (int)desc->plaintext_data->revision_counter);
  131. goto err;
  132. }
  133. /* We now know that the descriptor we just received is a new one so
  134. * remove the entry we currently have from our cache so we can then
  135. * store the new one. */
  136. remove_v3_desc_as_dir(cache_entry);
  137. rend_cache_decrement_allocation(cache_get_dir_entry_size(cache_entry));
  138. cache_dir_desc_free(cache_entry);
  139. }
  140. /* Store the descriptor we just got. We are sure here that either we
  141. * don't have the entry or we have a newer descriptor and the old one
  142. * has been removed from the cache. */
  143. store_v3_desc_as_dir(desc);
  144. /* Also send it to the PIR server if we have one. */
  145. hs_cache_pirserver_insert_desc(desc);
  146. /* Update our total cache size with this entry for the OOM. This uses the
  147. * old HS protocol cache subsystem for which we are tied with. */
  148. rend_cache_increment_allocation(cache_get_dir_entry_size(desc));
  149. /* XXX: Update HS statistics. We should have specific stats for v3. */
  150. return 0;
  151. err:
  152. return -1;
  153. }
  154. // PIRONION: v3 lookup
  155. /* Using the query which is the base64 encoded blinded key of a version 3
  156. * descriptor, lookup in our directory cache the entry. If found, 1 is
  157. * returned and desc_out is populated with a newly allocated string being the
  158. * encoded descriptor. If not found, 0 is returned and desc_out is untouched.
  159. * On error, a negative value is returned and desc_out is untouched. */
  160. static int
  161. cache_lookup_v3_as_dir(const char *query, const char **desc_out)
  162. {
  163. int found = 0;
  164. ed25519_public_key_t blinded_key;
  165. const hs_cache_dir_descriptor_t *entry;
  166. tor_assert(query);
  167. /* Decode blinded key using the given query value. */
  168. if (ed25519_public_from_base64(&blinded_key, query) < 0) {
  169. log_info(LD_REND, "Unable to decode the v3 HSDir query %s.",
  170. safe_str_client(query));
  171. goto err;
  172. }
  173. entry = lookup_v3_desc_as_dir(blinded_key.pubkey);
  174. if (entry != NULL) {
  175. found = 1;
  176. if (desc_out) {
  177. *desc_out = entry->encoded_desc;
  178. }
  179. }
  180. return found;
  181. err:
  182. return -1;
  183. }
  184. /* Clean the v3 cache by removing any entry that has expired using the
  185. * <b>global_cutoff</b> value. If <b>global_cutoff</b> is 0, the cleaning
  186. * process will use the lifetime found in the plaintext data section. Return
  187. * the number of bytes cleaned. */
  188. STATIC size_t
  189. cache_clean_v3_as_dir(time_t now, time_t global_cutoff)
  190. {
  191. size_t bytes_removed = 0;
  192. /* Code flow error if this ever happens. */
  193. tor_assert(global_cutoff >= 0);
  194. if (!hs_cache_v3_dir) { /* No cache to clean. Just return. */
  195. return 0;
  196. }
  197. DIGEST256MAP_FOREACH_MODIFY(hs_cache_v3_dir, key,
  198. hs_cache_dir_descriptor_t *, entry) {
  199. size_t entry_size;
  200. time_t cutoff = global_cutoff;
  201. if (!cutoff) {
  202. /* Cutoff is the lifetime of the entry found in the descriptor. */
  203. cutoff = now - entry->plaintext_data->lifetime_sec;
  204. }
  205. /* If the entry has been created _after_ the cutoff, not expired so
  206. * continue to the next entry in our v3 cache. */
  207. if (entry->created_ts > cutoff) {
  208. continue;
  209. }
  210. /* Here, our entry has expired, remove and free. */
  211. MAP_DEL_CURRENT(key);
  212. entry_size = cache_get_dir_entry_size(entry);
  213. bytes_removed += entry_size;
  214. /* Entry is not in the cache anymore, destroy it. */
  215. cache_dir_desc_free(entry);
  216. /* Update our cache entry allocation size for the OOM. */
  217. rend_cache_decrement_allocation(entry_size);
  218. /* Logging. */
  219. {
  220. char key_b64[BASE64_DIGEST256_LEN + 1];
  221. digest256_to_base64(key_b64, (const char *) key);
  222. log_info(LD_REND, "Removing v3 descriptor '%s' from HSDir cache",
  223. safe_str_client(key_b64));
  224. }
  225. } DIGEST256MAP_FOREACH_END;
  226. return bytes_removed;
  227. }
  228. /* Given an encoded descriptor, store it in the directory cache depending on
  229. * which version it is. Return a negative value on error. On success, 0 is
  230. * returned. */
  231. int
  232. hs_cache_store_as_dir(const char *desc)
  233. {
  234. hs_cache_dir_descriptor_t *dir_desc = NULL;
  235. tor_assert(desc);
  236. /* Create a new cache object. This can fail if the descriptor plaintext data
  237. * is unparseable which in this case a log message will be triggered. */
  238. dir_desc = cache_dir_desc_new(desc);
  239. if (dir_desc == NULL) {
  240. goto err;
  241. }
  242. /* Call the right function against the descriptor version. At this point,
  243. * we are sure that the descriptor's version is supported else the
  244. * decoding would have failed. */
  245. switch (dir_desc->plaintext_data->version) {
  246. case HS_VERSION_THREE:
  247. default:
  248. if (cache_store_v3_as_dir(dir_desc) < 0) {
  249. goto err;
  250. }
  251. break;
  252. }
  253. return 0;
  254. err:
  255. cache_dir_desc_free(dir_desc);
  256. return -1;
  257. }
  258. /* Using the query, lookup in our directory cache the entry. If found, 1 is
  259. * returned and desc_out is populated with a newly allocated string being
  260. * the encoded descriptor. If not found, 0 is returned and desc_out is
  261. * untouched. On error, a negative value is returned and desc_out is
  262. * untouched. */
  263. int
  264. hs_cache_lookup_as_dir(uint32_t version, const char *query,
  265. const char **desc_out)
  266. {
  267. int found;
  268. tor_assert(query);
  269. /* This should never be called with an unsupported version. */
  270. tor_assert(hs_desc_is_supported_version(version));
  271. switch (version) {
  272. case HS_VERSION_THREE:
  273. default:
  274. found = cache_lookup_v3_as_dir(query, desc_out);
  275. break;
  276. }
  277. return found;
  278. }
  279. /* Clean all directory caches using the current time now. */
  280. void
  281. hs_cache_clean_as_dir(time_t now)
  282. {
  283. time_t cutoff;
  284. /* Start with v2 cache cleaning. */
  285. cutoff = now - rend_cache_max_entry_lifetime();
  286. rend_cache_clean_v2_descs_as_dir(cutoff);
  287. /* Now, clean the v3 cache. Set the cutoff to 0 telling the cleanup function
  288. * to compute the cutoff by itself using the lifetime value. */
  289. cache_clean_v3_as_dir(now, 0);
  290. }
  291. /********************** Client-side HS cache ******************/
  292. /* Client-side HS descriptor cache. Map indexed by service identity key. */
  293. static digest256map_t *hs_cache_v3_client;
  294. /* Client-side introduction point state cache. Map indexed by service public
  295. * identity key (onion address). It contains hs_cache_client_intro_state_t
  296. * objects all related to a specific service. */
  297. static digest256map_t *hs_cache_client_intro_state;
  298. /* Return the size of a client cache entry in bytes. */
  299. static size_t
  300. cache_get_client_entry_size(const hs_cache_client_descriptor_t *entry)
  301. {
  302. return sizeof(*entry) +
  303. strlen(entry->encoded_desc) + hs_desc_obj_size(entry->desc);
  304. }
  305. /* Remove a given descriptor from our cache. */
  306. static void
  307. remove_v3_desc_as_client(const hs_cache_client_descriptor_t *desc)
  308. {
  309. tor_assert(desc);
  310. digest256map_remove(hs_cache_v3_client, desc->key.pubkey);
  311. /* Update cache size with this entry for the OOM handler. */
  312. rend_cache_decrement_allocation(cache_get_client_entry_size(desc));
  313. }
  314. /* Store a given descriptor in our cache. */
  315. static void
  316. store_v3_desc_as_client(hs_cache_client_descriptor_t *desc)
  317. {
  318. tor_assert(desc);
  319. digest256map_set(hs_cache_v3_client, desc->key.pubkey, desc);
  320. /* Update cache size with this entry for the OOM handler. */
  321. rend_cache_increment_allocation(cache_get_client_entry_size(desc));
  322. }
  323. /* Query our cache and return the entry or NULL if not found or if expired. */
  324. STATIC hs_cache_client_descriptor_t *
  325. lookup_v3_desc_as_client(const uint8_t *key)
  326. {
  327. time_t now = approx_time();
  328. hs_cache_client_descriptor_t *cached_desc;
  329. tor_assert(key);
  330. /* Do the lookup */
  331. cached_desc = digest256map_get(hs_cache_v3_client, key);
  332. if (!cached_desc) {
  333. return NULL;
  334. }
  335. /* Don't return expired entries */
  336. if (cached_client_descriptor_has_expired(now, cached_desc)) {
  337. return NULL;
  338. }
  339. return cached_desc;
  340. }
  341. /* Parse the encoded descriptor in <b>desc_str</b> using
  342. * <b>service_identity_pk<b> to decrypt it first.
  343. *
  344. * If everything goes well, allocate and return a new
  345. * hs_cache_client_descriptor_t object. In case of error, return NULL. */
  346. static hs_cache_client_descriptor_t *
  347. cache_client_desc_new(const char *desc_str,
  348. const ed25519_public_key_t *service_identity_pk)
  349. {
  350. hs_descriptor_t *desc = NULL;
  351. hs_cache_client_descriptor_t *client_desc = NULL;
  352. tor_assert(desc_str);
  353. tor_assert(service_identity_pk);
  354. /* Decode the descriptor we just fetched. */
  355. if (hs_client_decode_descriptor(desc_str, service_identity_pk, &desc) < 0) {
  356. goto end;
  357. }
  358. tor_assert(desc);
  359. /* All is good: make a cache object for this descriptor */
  360. client_desc = tor_malloc_zero(sizeof(hs_cache_client_descriptor_t));
  361. ed25519_pubkey_copy(&client_desc->key, service_identity_pk);
  362. /* Set expiration time for this cached descriptor to be the start of the next
  363. * time period since that's when clients need to start using the next blinded
  364. * pk of the service (and hence will need its next descriptor). */
  365. client_desc->expiration_ts = hs_get_start_time_of_next_time_period(0);
  366. client_desc->desc = desc;
  367. client_desc->encoded_desc = tor_strdup(desc_str);
  368. end:
  369. return client_desc;
  370. }
  371. #define cache_client_desc_free(val) \
  372. FREE_AND_NULL(hs_cache_client_descriptor_t, cache_client_desc_free_, (val))
  373. /** Free memory allocated by <b>desc</b>. */
  374. static void
  375. cache_client_desc_free_(hs_cache_client_descriptor_t *desc)
  376. {
  377. if (desc == NULL) {
  378. return;
  379. }
  380. hs_descriptor_free(desc->desc);
  381. memwipe(&desc->key, 0, sizeof(desc->key));
  382. memwipe(desc->encoded_desc, 0, strlen(desc->encoded_desc));
  383. tor_free(desc->encoded_desc);
  384. tor_free(desc);
  385. }
  386. /** Helper function: Use by the free all function to clear the client cache */
  387. static void
  388. cache_client_desc_free_void(void *ptr)
  389. {
  390. hs_cache_client_descriptor_t *desc = ptr;
  391. cache_client_desc_free(desc);
  392. }
  393. /* Return a newly allocated and initialized hs_cache_intro_state_t object. */
  394. static hs_cache_intro_state_t *
  395. cache_intro_state_new(void)
  396. {
  397. hs_cache_intro_state_t *state = tor_malloc_zero(sizeof(*state));
  398. state->created_ts = approx_time();
  399. return state;
  400. }
  401. #define cache_intro_state_free(val) \
  402. FREE_AND_NULL(hs_cache_intro_state_t, cache_intro_state_free_, (val))
  403. /* Free an hs_cache_intro_state_t object. */
  404. static void
  405. cache_intro_state_free_(hs_cache_intro_state_t *state)
  406. {
  407. tor_free(state);
  408. }
  409. /* Helper function: used by the free all function. */
  410. static void
  411. cache_intro_state_free_void(void *state)
  412. {
  413. cache_intro_state_free_(state);
  414. }
  415. /* Return a newly allocated and initialized hs_cache_client_intro_state_t
  416. * object. */
  417. static hs_cache_client_intro_state_t *
  418. cache_client_intro_state_new(void)
  419. {
  420. hs_cache_client_intro_state_t *cache = tor_malloc_zero(sizeof(*cache));
  421. cache->intro_points = digest256map_new();
  422. return cache;
  423. }
  424. #define cache_client_intro_state_free(val) \
  425. FREE_AND_NULL(hs_cache_client_intro_state_t, \
  426. cache_client_intro_state_free_, (val))
  427. /* Free a cache_client_intro_state object. */
  428. static void
  429. cache_client_intro_state_free_(hs_cache_client_intro_state_t *cache)
  430. {
  431. if (cache == NULL) {
  432. return;
  433. }
  434. digest256map_free(cache->intro_points, cache_intro_state_free_void);
  435. tor_free(cache);
  436. }
  437. /* Helper function: used by the free all function. */
  438. static void
  439. cache_client_intro_state_free_void(void *entry)
  440. {
  441. cache_client_intro_state_free_(entry);
  442. }
  443. /* For the given service identity key service_pk and an introduction
  444. * authentication key auth_key, lookup the intro state object. Return 1 if
  445. * found and put it in entry if not NULL. Return 0 if not found and entry is
  446. * untouched. */
  447. static int
  448. cache_client_intro_state_lookup(const ed25519_public_key_t *service_pk,
  449. const ed25519_public_key_t *auth_key,
  450. hs_cache_intro_state_t **entry)
  451. {
  452. hs_cache_intro_state_t *state;
  453. hs_cache_client_intro_state_t *cache;
  454. tor_assert(service_pk);
  455. tor_assert(auth_key);
  456. /* Lookup the intro state cache for this service key. */
  457. cache = digest256map_get(hs_cache_client_intro_state, service_pk->pubkey);
  458. if (cache == NULL) {
  459. goto not_found;
  460. }
  461. /* From the cache we just found for the service, lookup in the introduction
  462. * points map for the given authentication key. */
  463. state = digest256map_get(cache->intro_points, auth_key->pubkey);
  464. if (state == NULL) {
  465. goto not_found;
  466. }
  467. if (entry) {
  468. *entry = state;
  469. }
  470. return 1;
  471. not_found:
  472. return 0;
  473. }
  474. /* Note the given failure in state. */
  475. static void
  476. cache_client_intro_state_note(hs_cache_intro_state_t *state,
  477. rend_intro_point_failure_t failure)
  478. {
  479. tor_assert(state);
  480. switch (failure) {
  481. case INTRO_POINT_FAILURE_GENERIC:
  482. state->error = 1;
  483. break;
  484. case INTRO_POINT_FAILURE_TIMEOUT:
  485. state->timed_out = 1;
  486. break;
  487. case INTRO_POINT_FAILURE_UNREACHABLE:
  488. state->unreachable_count++;
  489. break;
  490. default:
  491. tor_assert_nonfatal_unreached();
  492. return;
  493. }
  494. }
  495. /* For the given service identity key service_pk and an introduction
  496. * authentication key auth_key, add an entry in the client intro state cache
  497. * If no entry exists for the service, it will create one. If state is non
  498. * NULL, it will point to the new intro state entry. */
  499. static void
  500. cache_client_intro_state_add(const ed25519_public_key_t *service_pk,
  501. const ed25519_public_key_t *auth_key,
  502. hs_cache_intro_state_t **state)
  503. {
  504. hs_cache_intro_state_t *entry, *old_entry;
  505. hs_cache_client_intro_state_t *cache;
  506. tor_assert(service_pk);
  507. tor_assert(auth_key);
  508. /* Lookup the state cache for this service key. */
  509. cache = digest256map_get(hs_cache_client_intro_state, service_pk->pubkey);
  510. if (cache == NULL) {
  511. cache = cache_client_intro_state_new();
  512. digest256map_set(hs_cache_client_intro_state, service_pk->pubkey, cache);
  513. }
  514. entry = cache_intro_state_new();
  515. old_entry = digest256map_set(cache->intro_points, auth_key->pubkey, entry);
  516. /* This should never happened because the code flow is to lookup the entry
  517. * before adding it. But, just in case, non fatal assert and free it. */
  518. tor_assert_nonfatal(old_entry == NULL);
  519. tor_free(old_entry);
  520. if (state) {
  521. *state = entry;
  522. }
  523. }
  524. /* Remove every intro point state entry from cache that has been created
  525. * before or at the cutoff. */
  526. static void
  527. cache_client_intro_state_clean(time_t cutoff,
  528. hs_cache_client_intro_state_t *cache)
  529. {
  530. tor_assert(cache);
  531. DIGEST256MAP_FOREACH_MODIFY(cache->intro_points, key,
  532. hs_cache_intro_state_t *, entry) {
  533. if (entry->created_ts <= cutoff) {
  534. cache_intro_state_free(entry);
  535. MAP_DEL_CURRENT(key);
  536. }
  537. } DIGEST256MAP_FOREACH_END;
  538. }
  539. /* Return true iff no intro points are in this cache. */
  540. static int
  541. cache_client_intro_state_is_empty(const hs_cache_client_intro_state_t *cache)
  542. {
  543. return digest256map_isempty(cache->intro_points);
  544. }
  545. /** Check whether <b>client_desc</b> is useful for us, and store it in the
  546. * client-side HS cache if so. The client_desc is freed if we already have a
  547. * fresher (higher revision counter count) in the cache. */
  548. static int
  549. cache_store_as_client(hs_cache_client_descriptor_t *client_desc)
  550. {
  551. hs_cache_client_descriptor_t *cache_entry;
  552. /* TODO: Heavy code duplication with cache_store_as_dir(). Consider
  553. * refactoring and uniting! */
  554. tor_assert(client_desc);
  555. /* Check if we already have a descriptor from this HS in cache. If we do,
  556. * check if this descriptor is newer than the cached one */
  557. cache_entry = lookup_v3_desc_as_client(client_desc->key.pubkey);
  558. if (cache_entry != NULL) {
  559. /* If we have an entry in our cache that has a revision counter greater
  560. * than the one we just fetched, discard the one we fetched. */
  561. if (cache_entry->desc->plaintext_data.revision_counter >
  562. client_desc->desc->plaintext_data.revision_counter) {
  563. cache_client_desc_free(client_desc);
  564. goto done;
  565. }
  566. /* Remove old entry. Make space for the new one! */
  567. remove_v3_desc_as_client(cache_entry);
  568. /* We just removed an old descriptor and will replace it. We'll close all
  569. * intro circuits related to this old one so we don't have leftovers. We
  570. * leave the rendezvous circuits opened because they could be in use. */
  571. hs_client_close_intro_circuits_from_desc(cache_entry->desc);
  572. /* Free it. */
  573. cache_client_desc_free(cache_entry);
  574. }
  575. /* Store descriptor in cache */
  576. store_v3_desc_as_client(client_desc);
  577. done:
  578. return 0;
  579. }
  580. /* Return true iff the cached client descriptor at <b>cached_desc</b has
  581. * expired. */
  582. static int
  583. cached_client_descriptor_has_expired(time_t now,
  584. const hs_cache_client_descriptor_t *cached_desc)
  585. {
  586. /* We use the current consensus time to see if we should expire this
  587. * descriptor since we use consensus time for all other parts of the protocol
  588. * as well (e.g. to build the blinded key and compute time periods). */
  589. const networkstatus_t *ns = networkstatus_get_live_consensus(now);
  590. /* If we don't have a recent consensus, consider this entry expired since we
  591. * will want to fetch a new HS desc when we get a live consensus. */
  592. if (!ns) {
  593. return 1;
  594. }
  595. if (cached_desc->expiration_ts <= ns->valid_after) {
  596. return 1;
  597. }
  598. return 0;
  599. }
  600. /* clean the client cache using now as the current time. Return the total size
  601. * of removed bytes from the cache. */
  602. static size_t
  603. cache_clean_v3_as_client(time_t now)
  604. {
  605. size_t bytes_removed = 0;
  606. if (!hs_cache_v3_client) { /* No cache to clean. Just return. */
  607. return 0;
  608. }
  609. DIGEST256MAP_FOREACH_MODIFY(hs_cache_v3_client, key,
  610. hs_cache_client_descriptor_t *, entry) {
  611. size_t entry_size;
  612. /* If the entry has not expired, continue to the next cached entry */
  613. if (!cached_client_descriptor_has_expired(now, entry)) {
  614. continue;
  615. }
  616. /* Here, our entry has expired, remove and free. */
  617. MAP_DEL_CURRENT(key);
  618. entry_size = cache_get_client_entry_size(entry);
  619. bytes_removed += entry_size;
  620. /* Entry is not in the cache anymore, destroy it. */
  621. cache_client_desc_free(entry);
  622. /* Update our OOM. We didn't use the remove() function because we are in
  623. * a loop so we have to explicitly decrement. */
  624. rend_cache_decrement_allocation(entry_size);
  625. /* Logging. */
  626. {
  627. char key_b64[BASE64_DIGEST256_LEN + 1];
  628. digest256_to_base64(key_b64, (const char *) key);
  629. log_info(LD_REND, "Removing hidden service v3 descriptor '%s' "
  630. "from client cache",
  631. safe_str_client(key_b64));
  632. }
  633. } DIGEST256MAP_FOREACH_END;
  634. return bytes_removed;
  635. }
  636. /** Public API: Given the HS ed25519 identity public key in <b>key</b>, return
  637. * its HS encoded descriptor if it's stored in our cache, or NULL if not. */
  638. const char *
  639. hs_cache_lookup_encoded_as_client(const ed25519_public_key_t *key)
  640. {
  641. hs_cache_client_descriptor_t *cached_desc = NULL;
  642. tor_assert(key);
  643. cached_desc = lookup_v3_desc_as_client(key->pubkey);
  644. if (cached_desc) {
  645. tor_assert(cached_desc->encoded_desc);
  646. return cached_desc->encoded_desc;
  647. }
  648. return NULL;
  649. }
  650. /** Public API: Given the HS ed25519 identity public key in <b>key</b>, return
  651. * its HS descriptor if it's stored in our cache, or NULL if not. */
  652. const hs_descriptor_t *
  653. hs_cache_lookup_as_client(const ed25519_public_key_t *key)
  654. {
  655. hs_cache_client_descriptor_t *cached_desc = NULL;
  656. tor_assert(key);
  657. cached_desc = lookup_v3_desc_as_client(key->pubkey);
  658. if (cached_desc) {
  659. tor_assert(cached_desc->desc);
  660. return cached_desc->desc;
  661. }
  662. return NULL;
  663. }
  664. /** Public API: Given an encoded descriptor, store it in the client HS
  665. * cache. Return -1 on error, 0 on success .*/
  666. int
  667. hs_cache_store_as_client(const char *desc_str,
  668. const ed25519_public_key_t *identity_pk)
  669. {
  670. hs_cache_client_descriptor_t *client_desc = NULL;
  671. tor_assert(desc_str);
  672. tor_assert(identity_pk);
  673. /* Create client cache descriptor object */
  674. client_desc = cache_client_desc_new(desc_str, identity_pk);
  675. if (!client_desc) {
  676. log_warn(LD_GENERAL, "HSDesc parsing failed!");
  677. log_debug(LD_GENERAL, "Failed to parse HSDesc: %s.", escaped(desc_str));
  678. goto err;
  679. }
  680. /* Push it to the cache */
  681. if (cache_store_as_client(client_desc) < 0) {
  682. goto err;
  683. }
  684. return 0;
  685. err:
  686. cache_client_desc_free(client_desc);
  687. return -1;
  688. }
  689. /* Clean all client caches using the current time now. */
  690. void
  691. hs_cache_clean_as_client(time_t now)
  692. {
  693. /* Start with v2 cache cleaning. */
  694. rend_cache_clean(now, REND_CACHE_TYPE_CLIENT);
  695. /* Now, clean the v3 cache. Set the cutoff to 0 telling the cleanup function
  696. * to compute the cutoff by itself using the lifetime value. */
  697. cache_clean_v3_as_client(now);
  698. }
  699. /* Purge the client descriptor cache. */
  700. void
  701. hs_cache_purge_as_client(void)
  702. {
  703. DIGEST256MAP_FOREACH_MODIFY(hs_cache_v3_client, key,
  704. hs_cache_client_descriptor_t *, entry) {
  705. size_t entry_size = cache_get_client_entry_size(entry);
  706. MAP_DEL_CURRENT(key);
  707. cache_client_desc_free(entry);
  708. /* Update our OOM. We didn't use the remove() function because we are in
  709. * a loop so we have to explicitly decrement. */
  710. rend_cache_decrement_allocation(entry_size);
  711. } DIGEST256MAP_FOREACH_END;
  712. log_info(LD_REND, "Hidden service client descriptor cache purged.");
  713. }
  714. /* For a given service identity public key and an introduction authentication
  715. * key, note the given failure in the client intro state cache. */
  716. void
  717. hs_cache_client_intro_state_note(const ed25519_public_key_t *service_pk,
  718. const ed25519_public_key_t *auth_key,
  719. rend_intro_point_failure_t failure)
  720. {
  721. int found;
  722. hs_cache_intro_state_t *entry;
  723. tor_assert(service_pk);
  724. tor_assert(auth_key);
  725. found = cache_client_intro_state_lookup(service_pk, auth_key, &entry);
  726. if (!found) {
  727. /* Create a new entry and add it to the cache. */
  728. cache_client_intro_state_add(service_pk, auth_key, &entry);
  729. }
  730. /* Note down the entry. */
  731. cache_client_intro_state_note(entry, failure);
  732. }
  733. /* For a given service identity public key and an introduction authentication
  734. * key, return true iff it is present in the failure cache. */
  735. const hs_cache_intro_state_t *
  736. hs_cache_client_intro_state_find(const ed25519_public_key_t *service_pk,
  737. const ed25519_public_key_t *auth_key)
  738. {
  739. hs_cache_intro_state_t *state = NULL;
  740. cache_client_intro_state_lookup(service_pk, auth_key, &state);
  741. return state;
  742. }
  743. /* Cleanup the client introduction state cache. */
  744. void
  745. hs_cache_client_intro_state_clean(time_t now)
  746. {
  747. time_t cutoff = now - HS_CACHE_CLIENT_INTRO_STATE_MAX_AGE;
  748. DIGEST256MAP_FOREACH_MODIFY(hs_cache_client_intro_state, key,
  749. hs_cache_client_intro_state_t *, cache) {
  750. /* Cleanup intro points failure. */
  751. cache_client_intro_state_clean(cutoff, cache);
  752. /* Is this cache empty for this service key? If yes, remove it from the
  753. * cache. Else keep it. */
  754. if (cache_client_intro_state_is_empty(cache)) {
  755. cache_client_intro_state_free(cache);
  756. MAP_DEL_CURRENT(key);
  757. }
  758. } DIGEST256MAP_FOREACH_END;
  759. }
  760. /* Purge the client introduction state cache. */
  761. void
  762. hs_cache_client_intro_state_purge(void)
  763. {
  764. DIGEST256MAP_FOREACH_MODIFY(hs_cache_client_intro_state, key,
  765. hs_cache_client_intro_state_t *, cache) {
  766. MAP_DEL_CURRENT(key);
  767. cache_client_intro_state_free(cache);
  768. } DIGEST256MAP_FOREACH_END;
  769. log_info(LD_REND, "Hidden service client introduction point state "
  770. "cache purged.");
  771. }
  772. /**************** Generics *********************************/
  773. /* Do a round of OOM cleanup on all directory caches. Return the amount of
  774. * removed bytes. It is possible that the returned value is lower than
  775. * min_remove_bytes if the caches get emptied out so the caller should be
  776. * aware of this. */
  777. size_t
  778. hs_cache_handle_oom(time_t now, size_t min_remove_bytes)
  779. {
  780. time_t k;
  781. size_t bytes_removed = 0;
  782. /* Our OOM handler called with 0 bytes to remove is a code flow error. */
  783. tor_assert(min_remove_bytes != 0);
  784. /* The algorithm is as follow. K is the oldest expected descriptor age.
  785. *
  786. * 1) Deallocate all entries from v2 cache that are older than K hours.
  787. * 1.1) If the amount of remove bytes has been reached, stop.
  788. * 2) Deallocate all entries from v3 cache that are older than K hours
  789. * 2.1) If the amount of remove bytes has been reached, stop.
  790. * 3) Set K = K - RendPostPeriod and repeat process until K is < 0.
  791. *
  792. * This ends up being O(Kn).
  793. */
  794. /* Set K to the oldest expected age in seconds which is the maximum
  795. * lifetime of a cache entry. We'll use the v2 lifetime because it's much
  796. * bigger than the v3 thus leading to cleaning older descriptors. */
  797. k = rend_cache_max_entry_lifetime();
  798. do {
  799. time_t cutoff;
  800. /* If K becomes negative, it means we've empty the caches so stop and
  801. * return what we were able to cleanup. */
  802. if (k < 0) {
  803. break;
  804. }
  805. /* Compute a cutoff value with K and the current time. */
  806. cutoff = now - k;
  807. /* Start by cleaning the v2 cache with that cutoff. */
  808. bytes_removed += rend_cache_clean_v2_descs_as_dir(cutoff);
  809. if (bytes_removed < min_remove_bytes) {
  810. /* We haven't remove enough bytes so clean v3 cache. */
  811. bytes_removed += cache_clean_v3_as_dir(now, cutoff);
  812. /* Decrement K by a post period to shorten the cutoff. */
  813. k -= get_options()->RendPostPeriod;
  814. }
  815. } while (bytes_removed < min_remove_bytes);
  816. return bytes_removed;
  817. }
  818. /* Return the maximum size of a v3 HS descriptor. */
  819. unsigned int
  820. hs_cache_get_max_descriptor_size(void)
  821. {
  822. return (unsigned) networkstatus_get_param(NULL,
  823. "HSV3MaxDescriptorSize",
  824. HS_DESC_MAX_LEN, 1, INT32_MAX);
  825. }
  826. static process_handle_t *pirserver;
  827. static struct event *pirserver_read_ev;
  828. typedef enum {
  829. PIRSERVER_READSTATE_HEADER,
  830. PIRSERVER_READSTATE_BODY
  831. } PIRServerReadState;
  832. #define PIRSERVER_READHDR_SIZE 13
  833. static void
  834. hs_cache_pirserver_received(const unsigned char *hdrbuf,
  835. const char *bodybuf, size_t bodylen)
  836. {
  837. /* PIRONION TODO: actually deliver the received message */
  838. log_info(LD_DIRSERV,"PIRSERVER response header %p flag %d body len %ld body %s", *(void**)hdrbuf, hdrbuf[8], bodylen, escaped(bodybuf));
  839. }
  840. static void
  841. hs_cache_pirserver_recvcb(evutil_socket_t fd, short what,
  842. ATTR_UNUSED void *arg) {
  843. static PIRServerReadState readstate = PIRSERVER_READSTATE_HEADER;
  844. static size_t readoff = 0;
  845. static size_t readleft = PIRSERVER_READHDR_SIZE;
  846. static unsigned char hdrbuf[PIRSERVER_READHDR_SIZE];
  847. static char *bodybuf = NULL;
  848. if (!(what & EV_READ)) {
  849. /* Not sure why we're here */
  850. return;
  851. }
  852. if (readstate == PIRSERVER_READSTATE_HEADER) {
  853. int res = read(fd, hdrbuf + readoff, readleft);
  854. if (res <= 0) return;
  855. readoff += res;
  856. readleft -= res;
  857. if (readleft == 0) {
  858. readleft = ntohl(*(uint32_t*)(hdrbuf+PIRSERVER_READHDR_SIZE-4));
  859. free(bodybuf);
  860. bodybuf = NULL;
  861. if (readleft > 0) {
  862. bodybuf = malloc(readleft);
  863. readoff = 0;
  864. readstate = PIRSERVER_READSTATE_BODY;
  865. } else {
  866. hs_cache_pirserver_received(hdrbuf, NULL, 0);
  867. readoff = 0;
  868. readleft = PIRSERVER_READHDR_SIZE;
  869. readstate = PIRSERVER_READSTATE_HEADER;
  870. }
  871. }
  872. } else if (readstate == PIRSERVER_READSTATE_BODY) {
  873. int res = read(fd, bodybuf + readoff, readleft);
  874. if (res <= 0) return;
  875. readoff += res;
  876. readleft -= res;
  877. if (readleft == 0) {
  878. /* Reading is complete */
  879. hs_cache_pirserver_received(hdrbuf, bodybuf, readoff);
  880. /* Prepare for the next output from the PIR server */
  881. free(bodybuf);
  882. bodybuf = NULL;
  883. readoff = 0;
  884. readleft = PIRSERVER_READHDR_SIZE;
  885. readstate = PIRSERVER_READSTATE_HEADER;
  886. }
  887. }
  888. }
  889. /* Poke the hidden service cache PIR subsystem to launch the PIR
  890. server if needed. */
  891. static void
  892. hs_cache_pir_poke(void)
  893. {
  894. int res;
  895. const char *pirserverpath = getenv("PIR_SERVER_PATH");
  896. smartlist_t *env_vars = get_current_process_environment_variables();
  897. const char *argv[2];
  898. process_environment_t *env;
  899. if (pirserver && pirserver->status == PROCESS_STATUS_RUNNING) {
  900. /* The PIR server appears to be open */
  901. return;
  902. }
  903. if (pirserver) {
  904. if (pirserver_read_ev) {
  905. event_free(pirserver_read_ev);
  906. pirserver_read_ev = NULL;
  907. }
  908. tor_process_handle_destroy(pirserver, 1);
  909. pirserver = NULL;
  910. }
  911. if (!pirserverpath) {
  912. /* We don't have a configured PIR server */
  913. return;
  914. }
  915. argv[0] = pirserverpath;
  916. argv[1] = NULL;
  917. env = process_environment_make(env_vars);
  918. res = tor_spawn_background(pirserverpath, argv, env, &pirserver);
  919. SMARTLIST_FOREACH(env_vars, void *, x, tor_free(x));
  920. smartlist_free(env_vars);
  921. if (res != PROCESS_STATUS_RUNNING) {
  922. /* Launch failure */
  923. return;
  924. }
  925. /* Create a libevent event to listen to the PIR server's responses. */
  926. pirserver_read_ev = event_new(tor_libevent_get_base(),
  927. pirserver->stdout_pipe, EV_READ|EV_PERSIST,
  928. hs_cache_pirserver_recvcb, NULL);
  929. event_add(pirserver_read_ev, NULL);
  930. }
  931. /* Initialize the hidden service cache PIR subsystem. */
  932. static void
  933. hs_cache_pir_init(void)
  934. {
  935. pirserver = NULL;
  936. pirserver_read_ev = NULL;
  937. }
  938. static int
  939. hs_cache_pirserver_send(const unsigned char *buf, size_t len)
  940. {
  941. size_t written = 0;
  942. hs_cache_pir_poke();
  943. if (pirserver == NULL || pirserver->status != PROCESS_STATUS_RUNNING) {
  944. /* Launch failed */
  945. return -1;
  946. }
  947. /* PIRONION TODO: For now, we're going to assume that writing to the
  948. * pir server will never block, but we should actually put this into
  949. * a write buffer. */
  950. while (len) {
  951. ssize_t res = write(pirserver->stdin_pipe, buf, len);
  952. if (res < 0) return res;
  953. if (res == 0) return written;
  954. written += res;
  955. buf += res;
  956. len -= res;
  957. }
  958. return written;
  959. }
  960. static int
  961. hs_cache_pirserver_insert_desc(hs_cache_dir_descriptor_t *desc)
  962. {
  963. unsigned char hdr[13];
  964. size_t encoded_desc_len;
  965. size_t len;
  966. int res;
  967. int written = 0;
  968. /* PIRONION TODO: This isn't the real insertion protocol yet. */
  969. memmove(hdr, "12345678\x01", 9);
  970. encoded_desc_len = strlen(desc->encoded_desc);
  971. len = DIGEST256_LEN + encoded_desc_len;
  972. *(uint32_t*)(hdr+9) = htonl(len);
  973. res = hs_cache_pirserver_send(hdr, 13);
  974. if (res <= 0) return -1;
  975. written += res;
  976. res = hs_cache_pirserver_send(desc->key, DIGEST256_LEN);
  977. if (res <= 0) return -1;
  978. written += res;
  979. res = hs_cache_pirserver_send(
  980. (const unsigned char *)desc->encoded_desc,
  981. encoded_desc_len);
  982. if (res <= 0) return -1;
  983. written += res;
  984. return written;
  985. }
  986. /* Initialize the hidden service cache subsystem. */
  987. void
  988. hs_cache_init(void)
  989. {
  990. /* Calling this twice is very wrong code flow. */
  991. tor_assert(!hs_cache_v3_dir);
  992. hs_cache_v3_dir = digest256map_new();
  993. tor_assert(!hs_cache_v3_client);
  994. hs_cache_v3_client = digest256map_new();
  995. tor_assert(!hs_cache_client_intro_state);
  996. hs_cache_client_intro_state = digest256map_new();
  997. hs_cache_pir_init();
  998. }
  999. /* Cleanup the hidden service cache subsystem. */
  1000. void
  1001. hs_cache_free_all(void)
  1002. {
  1003. digest256map_free(hs_cache_v3_dir, cache_dir_desc_free_void);
  1004. hs_cache_v3_dir = NULL;
  1005. digest256map_free(hs_cache_v3_client, cache_client_desc_free_void);
  1006. hs_cache_v3_client = NULL;
  1007. digest256map_free(hs_cache_client_intro_state,
  1008. cache_client_intro_state_free_void);
  1009. hs_cache_client_intro_state = NULL;
  1010. }