hs_common.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_common.c
  5. * \brief Contains code shared between different HS protocol version as well
  6. * as useful data structures and accessors used by other subsystems.
  7. * The rendcommon.c should only contains code relating to the v2
  8. * protocol.
  9. **/
  10. #define HS_COMMON_PRIVATE
  11. #include "or.h"
  12. #include "config.h"
  13. #include "networkstatus.h"
  14. #include "nodelist.h"
  15. #include "hs_cache.h"
  16. #include "hs_common.h"
  17. #include "hs_service.h"
  18. #include "rendcommon.h"
  19. #include "rendservice.h"
  20. #include "router.h"
  21. #include "shared_random.h"
  22. #include "shared_random_state.h"
  23. /* Ed25519 Basepoint value. Taken from section 5 of
  24. * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
  25. static const char *str_ed25519_basepoint =
  26. "(15112221349535400772501151409588531511"
  27. "454012693041857206046113283949847762202, "
  28. "463168356949264781694283940034751631413"
  29. "07993866256225615783033603165251855960)";
  30. #ifdef HAVE_SYS_UN_H
  31. /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
  32. * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
  33. * else return -ENOSYS if AF_UNIX is not supported (see function in the
  34. * #else statement below). */
  35. static int
  36. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  37. {
  38. tor_assert(ports);
  39. tor_assert(p);
  40. tor_assert(p->is_unix_addr);
  41. smartlist_add(ports, p);
  42. return 0;
  43. }
  44. /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
  45. * on success else return -ENOSYS if AF_UNIX is not supported (see function
  46. * in the #else statement below). */
  47. static int
  48. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  49. {
  50. tor_assert(conn);
  51. tor_assert(p);
  52. tor_assert(p->is_unix_addr);
  53. conn->base_.socket_family = AF_UNIX;
  54. tor_addr_make_unspec(&conn->base_.addr);
  55. conn->base_.port = 1;
  56. conn->base_.address = tor_strdup(p->unix_addr);
  57. return 0;
  58. }
  59. #else /* defined(HAVE_SYS_UN_H) */
  60. static int
  61. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  62. {
  63. (void) conn;
  64. (void) p;
  65. return -ENOSYS;
  66. }
  67. static int
  68. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  69. {
  70. (void) ports;
  71. (void) p;
  72. return -ENOSYS;
  73. }
  74. #endif /* HAVE_SYS_UN_H */
  75. /* Helper function: The key is a digest that we compare to a node_t object
  76. * current hsdir_index. */
  77. static int
  78. compare_digest_to_current_hsdir_index(const void *_key, const void **_member)
  79. {
  80. const char *key = _key;
  81. const node_t *node = *_member;
  82. return tor_memcmp(key, node->hsdir_index->current, DIGEST256_LEN);
  83. }
  84. /* Helper function: The key is a digest that we compare to a node_t object
  85. * next hsdir_index. */
  86. static int
  87. compare_digest_to_next_hsdir_index(const void *_key, const void **_member)
  88. {
  89. const char *key = _key;
  90. const node_t *node = *_member;
  91. return tor_memcmp(key, node->hsdir_index->next, DIGEST256_LEN);
  92. }
  93. /* Helper function: Compare two node_t objects current hsdir_index. */
  94. static int
  95. compare_node_current_hsdir_index(const void **a, const void **b)
  96. {
  97. const node_t *node1= *a;
  98. const node_t *node2 = *b;
  99. return tor_memcmp(node1->hsdir_index->current,
  100. node2->hsdir_index->current,
  101. DIGEST256_LEN);
  102. }
  103. /* Helper function: Compare two node_t objects next hsdir_index. */
  104. static int
  105. compare_node_next_hsdir_index(const void **a, const void **b)
  106. {
  107. const node_t *node1= *a;
  108. const node_t *node2 = *b;
  109. return tor_memcmp(node1->hsdir_index->next,
  110. node2->hsdir_index->next,
  111. DIGEST256_LEN);
  112. }
  113. /* Allocate and return a string containing the path to filename in directory.
  114. * This function will never return NULL. The caller must free this path. */
  115. char *
  116. hs_path_from_filename(const char *directory, const char *filename)
  117. {
  118. char *file_path = NULL;
  119. tor_assert(directory);
  120. tor_assert(filename);
  121. tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
  122. return file_path;
  123. }
  124. /* Make sure that the directory for <b>service</b> is private, using the config
  125. * <b>username</b>.
  126. * If <b>create</b> is true:
  127. * - if the directory exists, change permissions if needed,
  128. * - if the directory does not exist, create it with the correct permissions.
  129. * If <b>create</b> is false:
  130. * - if the directory exists, check permissions,
  131. * - if the directory does not exist, check if we think we can create it.
  132. * Return 0 on success, -1 on failure. */
  133. int
  134. hs_check_service_private_dir(const char *username, const char *path,
  135. unsigned int dir_group_readable,
  136. unsigned int create)
  137. {
  138. cpd_check_t check_opts = CPD_NONE;
  139. tor_assert(path);
  140. if (create) {
  141. check_opts |= CPD_CREATE;
  142. } else {
  143. check_opts |= CPD_CHECK_MODE_ONLY;
  144. check_opts |= CPD_CHECK;
  145. }
  146. if (dir_group_readable) {
  147. check_opts |= CPD_GROUP_READ;
  148. }
  149. /* Check/create directory */
  150. if (check_private_dir(path, check_opts, username) < 0) {
  151. return -1;
  152. }
  153. return 0;
  154. }
  155. /** Get the default HS time period length in minutes from the consensus. */
  156. STATIC uint64_t
  157. get_time_period_length(void)
  158. {
  159. /* If we are on a test network, make the time period smaller than normal so
  160. that we actually see it rotate. Specifically, make it the same length as
  161. an SRV protocol run. */
  162. if (get_options()->TestingTorNetwork) {
  163. unsigned run_duration = sr_state_get_protocol_run_duration();
  164. /* An SRV run should take more than a minute (it's 24 rounds) */
  165. tor_assert_nonfatal(run_duration > 60);
  166. /* Turn it from seconds to minutes before returning: */
  167. return sr_state_get_protocol_run_duration() / 60;
  168. }
  169. int32_t time_period_length = networkstatus_get_param(NULL, "hsdir-interval",
  170. HS_TIME_PERIOD_LENGTH_DEFAULT,
  171. HS_TIME_PERIOD_LENGTH_MIN,
  172. HS_TIME_PERIOD_LENGTH_MAX);
  173. /* Make sure it's a positive value. */
  174. tor_assert(time_period_length >= 0);
  175. /* uint64_t will always be able to contain a int32_t */
  176. return (uint64_t) time_period_length;
  177. }
  178. /** Get the HS time period number at time <b>now</b> */
  179. uint64_t
  180. hs_get_time_period_num(time_t now)
  181. {
  182. uint64_t time_period_num;
  183. /* Start by calculating minutes since the epoch */
  184. uint64_t time_period_length = get_time_period_length();
  185. uint64_t minutes_since_epoch = now / 60;
  186. /* Apply the rotation offset as specified by prop224 (section
  187. * [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
  188. * publication */
  189. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  190. time_period_rotation_offset /= 60; /* go from seconds to minutes */
  191. tor_assert(minutes_since_epoch > time_period_rotation_offset);
  192. minutes_since_epoch -= time_period_rotation_offset;
  193. /* Calculate the time period */
  194. time_period_num = minutes_since_epoch / time_period_length;
  195. return time_period_num;
  196. }
  197. /** Get the number of the _upcoming_ HS time period, given that the current
  198. * time is <b>now</b>. */
  199. uint64_t
  200. hs_get_next_time_period_num(time_t now)
  201. {
  202. return hs_get_time_period_num(now) + 1;
  203. }
  204. /* Return the start time of the upcoming time period based on <b>now</b>. */
  205. time_t
  206. hs_get_start_time_of_next_time_period(time_t now)
  207. {
  208. uint64_t time_period_length = get_time_period_length();
  209. /* Get start time of next time period */
  210. uint64_t next_time_period_num = hs_get_next_time_period_num(now);
  211. uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
  212. /* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
  213. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  214. return (time_t)(start_of_next_tp_in_mins * 60 + time_period_rotation_offset);
  215. }
  216. /* Create a new rend_data_t for a specific given <b>version</b>.
  217. * Return a pointer to the newly allocated data structure. */
  218. static rend_data_t *
  219. rend_data_alloc(uint32_t version)
  220. {
  221. rend_data_t *rend_data = NULL;
  222. switch (version) {
  223. case HS_VERSION_TWO:
  224. {
  225. rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
  226. v2->base_.version = HS_VERSION_TWO;
  227. v2->base_.hsdirs_fp = smartlist_new();
  228. rend_data = &v2->base_;
  229. break;
  230. }
  231. default:
  232. tor_assert(0);
  233. break;
  234. }
  235. return rend_data;
  236. }
  237. /** Free all storage associated with <b>data</b> */
  238. void
  239. rend_data_free(rend_data_t *data)
  240. {
  241. if (!data) {
  242. return;
  243. }
  244. /* By using our allocation function, this should always be set. */
  245. tor_assert(data->hsdirs_fp);
  246. /* Cleanup the HSDir identity digest. */
  247. SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
  248. smartlist_free(data->hsdirs_fp);
  249. /* Depending on the version, cleanup. */
  250. switch (data->version) {
  251. case HS_VERSION_TWO:
  252. {
  253. rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
  254. tor_free(v2_data);
  255. break;
  256. }
  257. default:
  258. tor_assert(0);
  259. }
  260. }
  261. /* Allocate and return a deep copy of <b>data</b>. */
  262. rend_data_t *
  263. rend_data_dup(const rend_data_t *data)
  264. {
  265. rend_data_t *data_dup = NULL;
  266. smartlist_t *hsdirs_fp = smartlist_new();
  267. tor_assert(data);
  268. tor_assert(data->hsdirs_fp);
  269. SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
  270. smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
  271. switch (data->version) {
  272. case HS_VERSION_TWO:
  273. {
  274. rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
  275. sizeof(*v2_data));
  276. data_dup = &v2_data->base_;
  277. data_dup->hsdirs_fp = hsdirs_fp;
  278. break;
  279. }
  280. default:
  281. tor_assert(0);
  282. break;
  283. }
  284. return data_dup;
  285. }
  286. /* Compute the descriptor ID for each HS descriptor replica and save them. A
  287. * valid onion address must be present in the <b>rend_data</b>.
  288. *
  289. * Return 0 on success else -1. */
  290. static int
  291. compute_desc_id(rend_data_t *rend_data)
  292. {
  293. int ret = 0;
  294. unsigned replica;
  295. time_t now = time(NULL);
  296. tor_assert(rend_data);
  297. switch (rend_data->version) {
  298. case HS_VERSION_TWO:
  299. {
  300. rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  301. /* Compute descriptor ID for each replicas. */
  302. for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
  303. replica++) {
  304. ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
  305. v2_data->onion_address,
  306. v2_data->descriptor_cookie,
  307. now, replica);
  308. if (ret < 0) {
  309. goto end;
  310. }
  311. }
  312. break;
  313. }
  314. default:
  315. tor_assert(0);
  316. }
  317. end:
  318. return ret;
  319. }
  320. /* Allocate and initialize a rend_data_t object for a service using the
  321. * provided arguments. All arguments are optional (can be NULL), except from
  322. * <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
  323. * the service private key. The <b>cookie</b> is the rendezvous cookie and
  324. * <b>auth_type</b> is which authentiation this service is configured with.
  325. *
  326. * Return a valid rend_data_t pointer. This only returns a version 2 object of
  327. * rend_data_t. */
  328. rend_data_t *
  329. rend_data_service_create(const char *onion_address, const char *pk_digest,
  330. const uint8_t *cookie, rend_auth_type_t auth_type)
  331. {
  332. /* Create a rend_data_t object for version 2. */
  333. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  334. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  335. /* We need at least one else the call is wrong. */
  336. tor_assert(onion_address != NULL);
  337. if (pk_digest) {
  338. memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
  339. }
  340. if (cookie) {
  341. memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
  342. }
  343. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  344. v2->auth_type = auth_type;
  345. return rend_data;
  346. }
  347. /* Allocate and initialize a rend_data_t object for a client request using the
  348. * given arguments. Either an onion address or a descriptor ID is needed. Both
  349. * can be given but in this case only the onion address will be used to make
  350. * the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
  351. * <b>auth_type</b> is which authentiation the service is configured with.
  352. *
  353. * Return a valid rend_data_t pointer or NULL on error meaning the
  354. * descriptor IDs couldn't be computed from the given data. */
  355. rend_data_t *
  356. rend_data_client_create(const char *onion_address, const char *desc_id,
  357. const char *cookie, rend_auth_type_t auth_type)
  358. {
  359. /* Create a rend_data_t object for version 2. */
  360. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  361. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  362. /* We need at least one else the call is wrong. */
  363. tor_assert(onion_address != NULL || desc_id != NULL);
  364. if (cookie) {
  365. memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
  366. }
  367. if (desc_id) {
  368. memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
  369. }
  370. if (onion_address) {
  371. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  372. if (compute_desc_id(rend_data) < 0) {
  373. goto error;
  374. }
  375. }
  376. v2->auth_type = auth_type;
  377. return rend_data;
  378. error:
  379. rend_data_free(rend_data);
  380. return NULL;
  381. }
  382. /* Return the onion address from the rend data. Depending on the version,
  383. * the size of the address can vary but it's always NUL terminated. */
  384. const char *
  385. rend_data_get_address(const rend_data_t *rend_data)
  386. {
  387. tor_assert(rend_data);
  388. switch (rend_data->version) {
  389. case HS_VERSION_TWO:
  390. return TO_REND_DATA_V2(rend_data)->onion_address;
  391. default:
  392. /* We should always have a supported version. */
  393. tor_assert(0);
  394. }
  395. }
  396. /* Return the descriptor ID for a specific replica number from the rend
  397. * data. The returned data is a binary digest and depending on the version its
  398. * size can vary. The size of the descriptor ID is put in <b>len_out</b> if
  399. * non NULL. */
  400. const char *
  401. rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
  402. size_t *len_out)
  403. {
  404. tor_assert(rend_data);
  405. switch (rend_data->version) {
  406. case HS_VERSION_TWO:
  407. tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
  408. if (len_out) {
  409. *len_out = DIGEST_LEN;
  410. }
  411. return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
  412. default:
  413. /* We should always have a supported version. */
  414. tor_assert(0);
  415. }
  416. }
  417. /* Return the public key digest using the given <b>rend_data</b>. The size of
  418. * the digest is put in <b>len_out</b> (if set) which can differ depending on
  419. * the version. */
  420. const uint8_t *
  421. rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
  422. {
  423. tor_assert(rend_data);
  424. switch (rend_data->version) {
  425. case HS_VERSION_TWO:
  426. {
  427. const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  428. if (len_out) {
  429. *len_out = sizeof(v2_data->rend_pk_digest);
  430. }
  431. return (const uint8_t *) v2_data->rend_pk_digest;
  432. }
  433. default:
  434. /* We should always have a supported version. */
  435. tor_assert(0);
  436. }
  437. }
  438. /* Using the given time period number, compute the disaster shared random
  439. * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
  440. static void
  441. compute_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  442. {
  443. crypto_digest_t *digest;
  444. tor_assert(srv_out);
  445. digest = crypto_digest256_new(DIGEST_SHA3_256);
  446. /* Start setting up payload:
  447. * H("shared-random-disaster" | INT_8(period_length) | INT_8(period_num)) */
  448. crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
  449. HS_SRV_DISASTER_PREFIX_LEN);
  450. /* Setup INT_8(period_length) | INT_8(period_num) */
  451. {
  452. uint64_t time_period_length = get_time_period_length();
  453. char period_stuff[sizeof(uint64_t)*2];
  454. size_t offset = 0;
  455. set_uint64(period_stuff, tor_htonll(time_period_length));
  456. offset += sizeof(uint64_t);
  457. set_uint64(period_stuff+offset, tor_htonll(time_period_num));
  458. offset += sizeof(uint64_t);
  459. tor_assert(offset == sizeof(period_stuff));
  460. crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
  461. }
  462. crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
  463. crypto_digest_free(digest);
  464. }
  465. /** Due to the high cost of computing the disaster SRV and that potentially we
  466. * would have to do it thousands of times in a row, we always cache the
  467. * computer disaster SRV (and its corresponding time period num) in case we
  468. * want to reuse it soon after. We need to cache two SRVs, one for each active
  469. * time period (in case of overlap mode).
  470. */
  471. static uint8_t cached_disaster_srv[2][DIGEST256_LEN];
  472. static uint64_t cached_time_period_nums[2] = {0};
  473. /** Compute the disaster SRV value for this <b>time_period_num</b> and put it
  474. * in <b>srv_out</b> (of size at least DIGEST256_LEN). First check our caches
  475. * to see if we have already computed it. */
  476. STATIC void
  477. get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  478. {
  479. if (time_period_num == cached_time_period_nums[0]) {
  480. memcpy(srv_out, cached_disaster_srv[0], DIGEST256_LEN);
  481. return;
  482. } else if (time_period_num == cached_time_period_nums[1]) {
  483. memcpy(srv_out, cached_disaster_srv[1], DIGEST256_LEN);
  484. return;
  485. } else {
  486. int replace_idx;
  487. // Replace the lower period number.
  488. if (cached_time_period_nums[0] <= cached_time_period_nums[1]) {
  489. replace_idx = 0;
  490. } else {
  491. replace_idx = 1;
  492. }
  493. cached_time_period_nums[replace_idx] = time_period_num;
  494. compute_disaster_srv(time_period_num, cached_disaster_srv[replace_idx]);
  495. memcpy(srv_out, cached_disaster_srv[replace_idx], DIGEST256_LEN);
  496. return;
  497. }
  498. }
  499. #ifdef TOR_UNIT_TESTS
  500. /** Get the first cached disaster SRV. Only used by unittests. */
  501. STATIC uint8_t *
  502. get_first_cached_disaster_srv(void)
  503. {
  504. return cached_disaster_srv[0];
  505. }
  506. /** Get the second cached disaster SRV. Only used by unittests. */
  507. STATIC uint8_t *
  508. get_second_cached_disaster_srv(void)
  509. {
  510. return cached_disaster_srv[1];
  511. }
  512. #endif
  513. /* When creating a blinded key, we need a parameter which construction is as
  514. * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
  515. *
  516. * The nonce has a pre-defined format which uses the time period number
  517. * period_num and the start of the period in second start_time_period.
  518. *
  519. * The secret of size secret_len is optional meaning that it can be NULL and
  520. * thus will be ignored for the param construction.
  521. *
  522. * The result is put in param_out. */
  523. static void
  524. build_blinded_key_param(const ed25519_public_key_t *pubkey,
  525. const uint8_t *secret, size_t secret_len,
  526. uint64_t period_num, uint64_t period_length,
  527. uint8_t *param_out)
  528. {
  529. size_t offset = 0;
  530. const char blind_str[] = "Derive temporary signing key";
  531. uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
  532. crypto_digest_t *digest;
  533. tor_assert(pubkey);
  534. tor_assert(param_out);
  535. /* Create the nonce N. The construction is as follow:
  536. * N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
  537. memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
  538. offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
  539. set_uint64(nonce + offset, tor_htonll(period_num));
  540. offset += sizeof(uint64_t);
  541. set_uint64(nonce + offset, tor_htonll(period_length));
  542. offset += sizeof(uint64_t);
  543. tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
  544. /* Generate the parameter h and the construction is as follow:
  545. * h = H(BLIND_STRING | pubkey | [secret] | ed25519-basepoint | N) */
  546. digest = crypto_digest256_new(DIGEST_SHA3_256);
  547. crypto_digest_add_bytes(digest, blind_str, sizeof(blind_str));
  548. crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
  549. /* Optional secret. */
  550. if (secret) {
  551. crypto_digest_add_bytes(digest, (char *) secret, secret_len);
  552. }
  553. crypto_digest_add_bytes(digest, str_ed25519_basepoint,
  554. strlen(str_ed25519_basepoint));
  555. crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
  556. /* Extract digest and put it in the param. */
  557. crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
  558. crypto_digest_free(digest);
  559. memwipe(nonce, 0, sizeof(nonce));
  560. }
  561. /* Using an ed25519 public key and version to build the checksum of an
  562. * address. Put in checksum_out. Format is:
  563. * SHA3-256(".onion checksum" || PUBKEY || VERSION)
  564. *
  565. * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
  566. static void
  567. build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
  568. uint8_t *checksum_out)
  569. {
  570. size_t offset = 0;
  571. char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
  572. /* Build checksum data. */
  573. memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
  574. HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
  575. offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
  576. memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
  577. offset += ED25519_PUBKEY_LEN;
  578. set_uint8(data + offset, version);
  579. offset += sizeof(version);
  580. tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
  581. /* Hash the data payload to create the checksum. */
  582. crypto_digest256((char *) checksum_out, data, sizeof(data),
  583. DIGEST_SHA3_256);
  584. }
  585. /* Using an ed25519 public key, checksum and version to build the binary
  586. * representation of a service address. Put in addr_out. Format is:
  587. * addr_out = PUBKEY || CHECKSUM || VERSION
  588. *
  589. * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
  590. static void
  591. build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
  592. uint8_t version, char *addr_out)
  593. {
  594. size_t offset = 0;
  595. tor_assert(key);
  596. tor_assert(checksum);
  597. memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
  598. offset += ED25519_PUBKEY_LEN;
  599. memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  600. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  601. set_uint8(addr_out + offset, version);
  602. offset += sizeof(uint8_t);
  603. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  604. }
  605. /* Helper for hs_parse_address(): Using a binary representation of a service
  606. * address, parse its content into the key_out, checksum_out and version_out.
  607. * Any out variable can be NULL in case the caller would want only one field.
  608. * checksum_out MUST at least be 2 bytes long. address must be at least
  609. * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
  610. static void
  611. hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
  612. uint8_t *checksum_out, uint8_t *version_out)
  613. {
  614. size_t offset = 0;
  615. tor_assert(address);
  616. if (key_out) {
  617. /* First is the key. */
  618. memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
  619. }
  620. offset += ED25519_PUBKEY_LEN;
  621. if (checksum_out) {
  622. /* Followed by a 2 bytes checksum. */
  623. memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  624. }
  625. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  626. if (version_out) {
  627. /* Finally, version value is 1 byte. */
  628. *version_out = get_uint8(address + offset);
  629. }
  630. offset += sizeof(uint8_t);
  631. /* Extra safety. */
  632. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  633. }
  634. /* Using the given identity public key and a blinded public key, compute the
  635. * subcredential and put it in subcred_out (must be of size DIGEST256_LEN).
  636. * This can't fail. */
  637. void
  638. hs_get_subcredential(const ed25519_public_key_t *identity_pk,
  639. const ed25519_public_key_t *blinded_pk,
  640. uint8_t *subcred_out)
  641. {
  642. uint8_t credential[DIGEST256_LEN];
  643. crypto_digest_t *digest;
  644. tor_assert(identity_pk);
  645. tor_assert(blinded_pk);
  646. tor_assert(subcred_out);
  647. /* First, build the credential. Construction is as follow:
  648. * credential = H("credential" | public-identity-key) */
  649. digest = crypto_digest256_new(DIGEST_SHA3_256);
  650. crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
  651. HS_CREDENTIAL_PREFIX_LEN);
  652. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  653. ED25519_PUBKEY_LEN);
  654. crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
  655. crypto_digest_free(digest);
  656. /* Now, compute the subcredential. Construction is as follow:
  657. * subcredential = H("subcredential" | credential | blinded-public-key). */
  658. digest = crypto_digest256_new(DIGEST_SHA3_256);
  659. crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
  660. HS_SUBCREDENTIAL_PREFIX_LEN);
  661. crypto_digest_add_bytes(digest, (const char *) credential,
  662. sizeof(credential));
  663. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  664. ED25519_PUBKEY_LEN);
  665. crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
  666. crypto_digest_free(digest);
  667. memwipe(credential, 0, sizeof(credential));
  668. }
  669. /* From the given list of hidden service ports, find the ones that much the
  670. * given edge connection conn, pick one at random and use it to set the
  671. * connection address. Return 0 on success or -1 if none. */
  672. int
  673. hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
  674. {
  675. rend_service_port_config_t *chosen_port;
  676. unsigned int warn_once = 0;
  677. smartlist_t *matching_ports;
  678. tor_assert(ports);
  679. tor_assert(conn);
  680. matching_ports = smartlist_new();
  681. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  682. if (TO_CONN(conn)->port != p->virtual_port) {
  683. continue;
  684. }
  685. if (!(p->is_unix_addr)) {
  686. smartlist_add(matching_ports, p);
  687. } else {
  688. if (add_unix_port(matching_ports, p)) {
  689. if (!warn_once) {
  690. /* Unix port not supported so warn only once. */
  691. log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
  692. "which is unsupported on this platform. "
  693. "Ignoring it.",
  694. TO_CONN(conn)->port);
  695. }
  696. warn_once++;
  697. }
  698. }
  699. } SMARTLIST_FOREACH_END(p);
  700. chosen_port = smartlist_choose(matching_ports);
  701. smartlist_free(matching_ports);
  702. if (chosen_port) {
  703. if (!(chosen_port->is_unix_addr)) {
  704. /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
  705. tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
  706. TO_CONN(conn)->port = chosen_port->real_port;
  707. } else {
  708. if (set_unix_port(conn, chosen_port)) {
  709. /* Simply impossible to end up here else we were able to add a Unix
  710. * port without AF_UNIX support... ? */
  711. tor_assert(0);
  712. }
  713. }
  714. }
  715. return (chosen_port) ? 0 : -1;
  716. }
  717. /* Using a base32 representation of a service address, parse its content into
  718. * the key_out, checksum_out and version_out. Any out variable can be NULL in
  719. * case the caller would want only one field. checksum_out MUST at least be 2
  720. * bytes long.
  721. *
  722. * Return 0 if parsing went well; return -1 in case of error. */
  723. int
  724. hs_parse_address(const char *address, ed25519_public_key_t *key_out,
  725. uint8_t *checksum_out, uint8_t *version_out)
  726. {
  727. char decoded[HS_SERVICE_ADDR_LEN];
  728. tor_assert(address);
  729. /* Obvious length check. */
  730. if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
  731. log_warn(LD_REND, "Service address %s has an invalid length. "
  732. "Expected %lu but got %lu.",
  733. escaped_safe_str(address),
  734. (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
  735. (unsigned long) strlen(address));
  736. goto invalid;
  737. }
  738. /* Decode address so we can extract needed fields. */
  739. if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
  740. log_warn(LD_REND, "Service address %s can't be decoded.",
  741. escaped_safe_str(address));
  742. goto invalid;
  743. }
  744. /* Parse the decoded address into the fields we need. */
  745. hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
  746. return 0;
  747. invalid:
  748. return -1;
  749. }
  750. /* Validate a given onion address. The length, the base32 decoding and
  751. * checksum are validated. Return 1 if valid else 0. */
  752. int
  753. hs_address_is_valid(const char *address)
  754. {
  755. uint8_t version;
  756. uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
  757. uint8_t target_checksum[DIGEST256_LEN];
  758. ed25519_public_key_t key;
  759. /* Parse the decoded address into the fields we need. */
  760. if (hs_parse_address(address, &key, checksum, &version) < 0) {
  761. goto invalid;
  762. }
  763. /* Get the checksum it's suppose to be and compare it with what we have
  764. * encoded in the address. */
  765. build_hs_checksum(&key, version, target_checksum);
  766. if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
  767. log_warn(LD_REND, "Service address %s invalid checksum.",
  768. escaped_safe_str(address));
  769. goto invalid;
  770. }
  771. /* Valid address. */
  772. return 1;
  773. invalid:
  774. return 0;
  775. }
  776. /* Build a service address using an ed25519 public key and a given version.
  777. * The returned address is base32 encoded and put in addr_out. The caller MUST
  778. * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
  779. *
  780. * Format is as follow:
  781. * base32(PUBKEY || CHECKSUM || VERSION)
  782. * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
  783. * */
  784. void
  785. hs_build_address(const ed25519_public_key_t *key, uint8_t version,
  786. char *addr_out)
  787. {
  788. uint8_t checksum[DIGEST256_LEN];
  789. char address[HS_SERVICE_ADDR_LEN];
  790. tor_assert(key);
  791. tor_assert(addr_out);
  792. /* Get the checksum of the address. */
  793. build_hs_checksum(key, version, checksum);
  794. /* Get the binary address representation. */
  795. build_hs_address(key, checksum, version, address);
  796. /* Encode the address. addr_out will be NUL terminated after this. */
  797. base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
  798. sizeof(address));
  799. /* Validate what we just built. */
  800. tor_assert(hs_address_is_valid(addr_out));
  801. }
  802. /* Return a newly allocated copy of lspec. */
  803. link_specifier_t *
  804. hs_link_specifier_dup(const link_specifier_t *lspec)
  805. {
  806. link_specifier_t *dup = link_specifier_new();
  807. memcpy(dup, lspec, sizeof(*dup));
  808. /* The unrecognized field is a dynamic array so make sure to copy its
  809. * content and not the pointer. */
  810. link_specifier_setlen_un_unrecognized(
  811. dup, link_specifier_getlen_un_unrecognized(lspec));
  812. if (link_specifier_getlen_un_unrecognized(dup)) {
  813. memcpy(link_specifier_getarray_un_unrecognized(dup),
  814. link_specifier_getconstarray_un_unrecognized(lspec),
  815. link_specifier_getlen_un_unrecognized(dup));
  816. }
  817. return dup;
  818. }
  819. /* From a given ed25519 public key pk and an optional secret, compute a
  820. * blinded public key and put it in blinded_pk_out. This is only useful to
  821. * the client side because the client only has access to the identity public
  822. * key of the service. */
  823. void
  824. hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
  825. const uint8_t *secret, size_t secret_len,
  826. uint64_t time_period_num,
  827. ed25519_public_key_t *blinded_pk_out)
  828. {
  829. /* Our blinding key API requires a 32 bytes parameter. */
  830. uint8_t param[DIGEST256_LEN];
  831. tor_assert(pk);
  832. tor_assert(blinded_pk_out);
  833. tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
  834. build_blinded_key_param(pk, secret, secret_len,
  835. time_period_num, get_time_period_length(), param);
  836. ed25519_public_blind(blinded_pk_out, pk, param);
  837. memwipe(param, 0, sizeof(param));
  838. }
  839. /* From a given ed25519 keypair kp and an optional secret, compute a blinded
  840. * keypair for the current time period and put it in blinded_kp_out. This is
  841. * only useful by the service side because the client doesn't have access to
  842. * the identity secret key. */
  843. void
  844. hs_build_blinded_keypair(const ed25519_keypair_t *kp,
  845. const uint8_t *secret, size_t secret_len,
  846. uint64_t time_period_num,
  847. ed25519_keypair_t *blinded_kp_out)
  848. {
  849. /* Our blinding key API requires a 32 bytes parameter. */
  850. uint8_t param[DIGEST256_LEN];
  851. tor_assert(kp);
  852. tor_assert(blinded_kp_out);
  853. /* Extra safety. A zeroed key is bad. */
  854. tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
  855. tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
  856. build_blinded_key_param(&kp->pubkey, secret, secret_len,
  857. time_period_num, get_time_period_length(), param);
  858. ed25519_keypair_blind(blinded_kp_out, kp, param);
  859. memwipe(param, 0, sizeof(param));
  860. }
  861. /* Return true if overlap mode is active given the date in consensus. If
  862. * consensus is NULL, then we use the latest live consensus we can find. */
  863. MOCK_IMPL(int,
  864. hs_overlap_mode_is_active, (const networkstatus_t *consensus, time_t now))
  865. {
  866. time_t valid_after;
  867. time_t srv_start_time, tp_start_time;
  868. if (!consensus) {
  869. consensus = networkstatus_get_live_consensus(now);
  870. if (!consensus) {
  871. return 0;
  872. }
  873. }
  874. /* We consider to be in overlap mode when we are in the period of time
  875. * between a fresh SRV and the beginning of the new time period (in the
  876. * normal network this is between 00:00 (inclusive) and 12:00 UTC
  877. * (exclusive)) */
  878. valid_after = consensus->valid_after;
  879. srv_start_time =sr_state_get_start_time_of_current_protocol_run(valid_after);
  880. tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
  881. if (valid_after >= srv_start_time && valid_after < tp_start_time) {
  882. return 1;
  883. }
  884. return 0;
  885. }
  886. /* Return 1 if any virtual port in ports needs a circuit with good uptime.
  887. * Else return 0. */
  888. int
  889. hs_service_requires_uptime_circ(const smartlist_t *ports)
  890. {
  891. tor_assert(ports);
  892. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  893. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  894. p->virtual_port)) {
  895. return 1;
  896. }
  897. } SMARTLIST_FOREACH_END(p);
  898. return 0;
  899. }
  900. /* Build hs_index which is used to find the responsible hsdirs. This index
  901. * value is used to select the responsible HSDir where their hsdir_index is
  902. * closest to this value.
  903. * SHA3-256("store-at-idx" | blinded_public_key |
  904. * INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
  905. *
  906. * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
  907. void
  908. hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
  909. uint64_t period_num, uint8_t *hs_index_out)
  910. {
  911. crypto_digest_t *digest;
  912. tor_assert(blinded_pk);
  913. tor_assert(hs_index_out);
  914. /* Build hs_index. See construction at top of function comment. */
  915. digest = crypto_digest256_new(DIGEST_SHA3_256);
  916. crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
  917. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  918. ED25519_PUBKEY_LEN);
  919. /* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
  920. {
  921. uint64_t period_length = get_time_period_length();
  922. char buf[sizeof(uint64_t)*3];
  923. size_t offset = 0;
  924. set_uint64(buf, tor_htonll(replica));
  925. offset += sizeof(uint64_t);
  926. set_uint64(buf+offset, tor_htonll(period_length));
  927. offset += sizeof(uint64_t);
  928. set_uint64(buf+offset, tor_htonll(period_num));
  929. offset += sizeof(uint64_t);
  930. tor_assert(offset == sizeof(buf));
  931. crypto_digest_add_bytes(digest, buf, sizeof(buf));
  932. }
  933. crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
  934. crypto_digest_free(digest);
  935. }
  936. /* Build hsdir_index which is used to find the responsible hsdirs. This is the
  937. * index value that is compare to the hs_index when selecting an HSDir.
  938. * SHA3-256("node-idx" | node_identity |
  939. * shared_random_value | INT_8(period_length) | INT_8(period_num) )
  940. *
  941. * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
  942. void
  943. hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
  944. const uint8_t *srv_value, uint64_t period_num,
  945. uint8_t *hsdir_index_out)
  946. {
  947. crypto_digest_t *digest;
  948. tor_assert(identity_pk);
  949. tor_assert(srv_value);
  950. tor_assert(hsdir_index_out);
  951. /* Build hsdir_index. See construction at top of function comment. */
  952. digest = crypto_digest256_new(DIGEST_SHA3_256);
  953. crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
  954. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  955. ED25519_PUBKEY_LEN);
  956. crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
  957. {
  958. uint64_t time_period_length = get_time_period_length();
  959. char period_stuff[sizeof(uint64_t)*2];
  960. size_t offset = 0;
  961. set_uint64(period_stuff, tor_htonll(period_num));
  962. offset += sizeof(uint64_t);
  963. set_uint64(period_stuff+offset, tor_htonll(time_period_length));
  964. offset += sizeof(uint64_t);
  965. tor_assert(offset == sizeof(period_stuff));
  966. crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
  967. }
  968. crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
  969. crypto_digest_free(digest);
  970. }
  971. /* Return a newly allocated buffer containing the current shared random value
  972. * or if not present, a disaster value is computed using the given time period
  973. * number. If a consensus is provided in <b>ns</b>, use it to get the SRV
  974. * value. This function can't fail. */
  975. uint8_t *
  976. hs_get_current_srv(uint64_t time_period_num, const networkstatus_t *ns)
  977. {
  978. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  979. const sr_srv_t *current_srv = sr_get_current(ns);
  980. if (current_srv) {
  981. memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
  982. } else {
  983. /* Disaster mode. */
  984. get_disaster_srv(time_period_num, sr_value);
  985. }
  986. return sr_value;
  987. }
  988. /* Return a newly allocated buffer containing the previous shared random
  989. * value or if not present, a disaster value is computed using the given time
  990. * period number. This function can't fail. */
  991. uint8_t *
  992. hs_get_previous_srv(uint64_t time_period_num, const networkstatus_t *ns)
  993. {
  994. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  995. const sr_srv_t *previous_srv = sr_get_previous(ns);
  996. if (previous_srv) {
  997. memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
  998. } else {
  999. /* Disaster mode. */
  1000. get_disaster_srv(time_period_num, sr_value);
  1001. }
  1002. return sr_value;
  1003. }
  1004. /* Return the number of replicas defined by a consensus parameter or the
  1005. * default value. */
  1006. int32_t
  1007. hs_get_hsdir_n_replicas(void)
  1008. {
  1009. /* The [1,16] range is a specification requirement. */
  1010. return networkstatus_get_param(NULL, "hsdir_n_replicas",
  1011. HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
  1012. }
  1013. /* Return the spread fetch value defined by a consensus parameter or the
  1014. * default value. */
  1015. int32_t
  1016. hs_get_hsdir_spread_fetch(void)
  1017. {
  1018. /* The [1,128] range is a specification requirement. */
  1019. return networkstatus_get_param(NULL, "hsdir_spread_fetch",
  1020. HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
  1021. }
  1022. /* Return the spread store value defined by a consensus parameter or the
  1023. * default value. */
  1024. int32_t
  1025. hs_get_hsdir_spread_store(void)
  1026. {
  1027. /* The [1,128] range is a specification requirement. */
  1028. return networkstatus_get_param(NULL, "hsdir_spread_store",
  1029. HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
  1030. }
  1031. /** <b>node</b> is an HSDir so make sure that we have assigned an hsdir index.
  1032. * Return 0 if everything is as expected, else return -1. */
  1033. static int
  1034. node_has_hsdir_index(const node_t *node)
  1035. {
  1036. tor_assert(node_supports_v3_hsdir(node));
  1037. /* A node can't have an HSDir index without a descriptor since we need desc
  1038. * to get its ed25519 key */
  1039. if (!node_has_descriptor(node)) {
  1040. return 0;
  1041. }
  1042. /* At this point, since the node has a desc, this node must also have an
  1043. * hsdir index. If not, something went wrong, so BUG out. */
  1044. if (BUG(node->hsdir_index == NULL) ||
  1045. BUG(tor_mem_is_zero((const char*)node->hsdir_index->current,
  1046. DIGEST256_LEN))) {
  1047. return 0;
  1048. }
  1049. return 1;
  1050. }
  1051. /* For a given blinded key and time period number, get the responsible HSDir
  1052. * and put their routerstatus_t object in the responsible_dirs list. If
  1053. * is_next_period is true, the next hsdir_index of the node_t is used. If
  1054. * is_client is true, the spread fetch consensus parameter is used else the
  1055. * spread store is used which is only for upload. This function can't fail but
  1056. * it is possible that the responsible_dirs list contains fewer nodes than
  1057. * expected.
  1058. *
  1059. * This function goes over the latest consensus routerstatus list and sorts it
  1060. * by their node_t hsdir_index then does a binary search to find the closest
  1061. * node. All of this makes it a bit CPU intensive so use it wisely. */
  1062. void
  1063. hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
  1064. uint64_t time_period_num, int is_next_period,
  1065. int is_client, smartlist_t *responsible_dirs)
  1066. {
  1067. smartlist_t *sorted_nodes;
  1068. /* The compare function used for the smartlist bsearch. We have two
  1069. * different depending on is_next_period. */
  1070. int (*cmp_fct)(const void *, const void **);
  1071. tor_assert(blinded_pk);
  1072. tor_assert(responsible_dirs);
  1073. sorted_nodes = smartlist_new();
  1074. /* Add every node_t that support HSDir v3 for which we do have a valid
  1075. * hsdir_index already computed for them for this consensus. */
  1076. {
  1077. networkstatus_t *c = networkstatus_get_latest_consensus();
  1078. if (!c || smartlist_len(c->routerstatus_list) == 0) {
  1079. log_warn(LD_REND, "No valid consensus so we can't get the responsible "
  1080. "hidden service directories.");
  1081. goto done;
  1082. }
  1083. SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
  1084. /* Even though this node_t object won't be modified and should be const,
  1085. * we can't add const object in a smartlist_t. */
  1086. node_t *n = node_get_mutable_by_id(rs->identity_digest);
  1087. tor_assert(n);
  1088. if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
  1089. if (!node_has_hsdir_index(n)) {
  1090. log_info(LD_GENERAL, "Node %s was found without hsdir index.",
  1091. node_describe(n));
  1092. continue;
  1093. }
  1094. smartlist_add(sorted_nodes, n);
  1095. }
  1096. } SMARTLIST_FOREACH_END(rs);
  1097. }
  1098. if (smartlist_len(sorted_nodes) == 0) {
  1099. log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
  1100. goto done;
  1101. }
  1102. /* First thing we have to do is sort all node_t by hsdir_index. The
  1103. * is_next_period tells us if we want the current or the next one. Set the
  1104. * bsearch compare function also while we are at it. */
  1105. if (is_next_period) {
  1106. smartlist_sort(sorted_nodes, compare_node_next_hsdir_index);
  1107. cmp_fct = compare_digest_to_next_hsdir_index;
  1108. } else {
  1109. smartlist_sort(sorted_nodes, compare_node_current_hsdir_index);
  1110. cmp_fct = compare_digest_to_current_hsdir_index;
  1111. }
  1112. /* For all replicas, we'll select a set of HSDirs using the consensus
  1113. * parameters and the sorted list. The replica starting at value 1 is
  1114. * defined by the specification. */
  1115. for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
  1116. int idx, start, found, n_added = 0;
  1117. uint8_t hs_index[DIGEST256_LEN] = {0};
  1118. /* Number of node to add to the responsible dirs list depends on if we are
  1119. * trying to fetch or store. A client always fetches. */
  1120. int n_to_add = (is_client) ? hs_get_hsdir_spread_fetch() :
  1121. hs_get_hsdir_spread_store();
  1122. /* Get the index that we should use to select the node. */
  1123. hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
  1124. /* The compare function pointer has been set correctly earlier. */
  1125. start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
  1126. &found);
  1127. /* Getting the length of the list if no member is greater than the key we
  1128. * are looking for so start at the first element. */
  1129. if (idx == smartlist_len(sorted_nodes)) {
  1130. start = idx = 0;
  1131. }
  1132. while (n_added < n_to_add) {
  1133. const node_t *node = smartlist_get(sorted_nodes, idx);
  1134. /* If the node has already been selected which is possible between
  1135. * replicas, the specification says to skip over. */
  1136. if (!smartlist_contains(responsible_dirs, node->rs)) {
  1137. smartlist_add(responsible_dirs, node->rs);
  1138. ++n_added;
  1139. }
  1140. if (++idx == smartlist_len(sorted_nodes)) {
  1141. /* Wrap if we've reached the end of the list. */
  1142. idx = 0;
  1143. }
  1144. if (idx == start) {
  1145. /* We've gone over the whole list, stop and avoid infinite loop. */
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. done:
  1151. smartlist_free(sorted_nodes);
  1152. }
  1153. /* Initialize the entire HS subsytem. This is called in tor_init() before any
  1154. * torrc options are loaded. Only for >= v3. */
  1155. void
  1156. hs_init(void)
  1157. {
  1158. hs_circuitmap_init();
  1159. hs_service_init();
  1160. hs_cache_init();
  1161. }
  1162. /* Release and cleanup all memory of the HS subsystem (all version). This is
  1163. * called by tor_free_all(). */
  1164. void
  1165. hs_free_all(void)
  1166. {
  1167. hs_circuitmap_free_all();
  1168. hs_service_free_all();
  1169. hs_cache_free_all();
  1170. }
  1171. /* For the given origin circuit circ, decrement the number of rendezvous
  1172. * stream counter. This handles every hidden service version. */
  1173. void
  1174. hs_dec_rdv_stream_counter(origin_circuit_t *circ)
  1175. {
  1176. tor_assert(circ);
  1177. if (circ->rend_data) {
  1178. circ->rend_data->nr_streams--;
  1179. } else if (circ->hs_ident) {
  1180. circ->hs_ident->num_rdv_streams--;
  1181. } else {
  1182. /* Should not be called if this circuit is not for hidden service. */
  1183. tor_assert_nonfatal_unreached();
  1184. }
  1185. }
  1186. /* For the given origin circuit circ, increment the number of rendezvous
  1187. * stream counter. This handles every hidden service version. */
  1188. void
  1189. hs_inc_rdv_stream_counter(origin_circuit_t *circ)
  1190. {
  1191. tor_assert(circ);
  1192. if (circ->rend_data) {
  1193. circ->rend_data->nr_streams++;
  1194. } else if (circ->hs_ident) {
  1195. circ->hs_ident->num_rdv_streams++;
  1196. } else {
  1197. /* Should not be called if this circuit is not for hidden service. */
  1198. tor_assert_nonfatal_unreached();
  1199. }
  1200. }