hs_common.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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 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. get_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_num));
  456. offset += sizeof(uint64_t);
  457. set_uint64(period_stuff+offset, tor_htonll(time_period_length));
  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. /* When creating a blinded key, we need a parameter which construction is as
  466. * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
  467. *
  468. * The nonce has a pre-defined format which uses the time period number
  469. * period_num and the start of the period in second start_time_period.
  470. *
  471. * The secret of size secret_len is optional meaning that it can be NULL and
  472. * thus will be ignored for the param construction.
  473. *
  474. * The result is put in param_out. */
  475. static void
  476. build_blinded_key_param(const ed25519_public_key_t *pubkey,
  477. const uint8_t *secret, size_t secret_len,
  478. uint64_t period_num, uint64_t period_length,
  479. uint8_t *param_out)
  480. {
  481. size_t offset = 0;
  482. uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
  483. crypto_digest_t *digest;
  484. tor_assert(pubkey);
  485. tor_assert(param_out);
  486. /* Create the nonce N. The construction is as follow:
  487. * N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
  488. memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
  489. offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
  490. set_uint64(nonce + offset, tor_htonll(period_num));
  491. offset += sizeof(uint64_t);
  492. set_uint64(nonce + offset, tor_htonll(period_length));
  493. offset += sizeof(uint64_t);
  494. tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
  495. /* Generate the parameter h and the construction is as follow:
  496. * h = H(pubkey | [secret] | ed25519-basepoint | nonce) */
  497. digest = crypto_digest256_new(DIGEST_SHA3_256);
  498. crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
  499. /* Optional secret. */
  500. if (secret) {
  501. crypto_digest_add_bytes(digest, (char *) secret, secret_len);
  502. }
  503. crypto_digest_add_bytes(digest, str_ed25519_basepoint,
  504. strlen(str_ed25519_basepoint));
  505. crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
  506. /* Extract digest and put it in the param. */
  507. crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
  508. crypto_digest_free(digest);
  509. memwipe(nonce, 0, sizeof(nonce));
  510. }
  511. /* Using an ed25519 public key and version to build the checksum of an
  512. * address. Put in checksum_out. Format is:
  513. * SHA3-256(".onion checksum" || PUBKEY || VERSION)
  514. *
  515. * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
  516. static void
  517. build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
  518. uint8_t *checksum_out)
  519. {
  520. size_t offset = 0;
  521. char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
  522. /* Build checksum data. */
  523. memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
  524. HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
  525. offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
  526. memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
  527. offset += ED25519_PUBKEY_LEN;
  528. set_uint8(data + offset, version);
  529. offset += sizeof(version);
  530. tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
  531. /* Hash the data payload to create the checksum. */
  532. crypto_digest256((char *) checksum_out, data, sizeof(data),
  533. DIGEST_SHA3_256);
  534. }
  535. /* Using an ed25519 public key, checksum and version to build the binary
  536. * representation of a service address. Put in addr_out. Format is:
  537. * addr_out = PUBKEY || CHECKSUM || VERSION
  538. *
  539. * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
  540. static void
  541. build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
  542. uint8_t version, char *addr_out)
  543. {
  544. size_t offset = 0;
  545. tor_assert(key);
  546. tor_assert(checksum);
  547. memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
  548. offset += ED25519_PUBKEY_LEN;
  549. memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  550. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  551. set_uint8(addr_out + offset, version);
  552. offset += sizeof(uint8_t);
  553. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  554. }
  555. /* Helper for hs_parse_address(): Using a binary representation of a service
  556. * address, parse its content into the key_out, checksum_out and version_out.
  557. * Any out variable can be NULL in case the caller would want only one field.
  558. * checksum_out MUST at least be 2 bytes long. address must be at least
  559. * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
  560. static void
  561. hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
  562. uint8_t *checksum_out, uint8_t *version_out)
  563. {
  564. size_t offset = 0;
  565. tor_assert(address);
  566. if (key_out) {
  567. /* First is the key. */
  568. memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
  569. }
  570. offset += ED25519_PUBKEY_LEN;
  571. if (checksum_out) {
  572. /* Followed by a 2 bytes checksum. */
  573. memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  574. }
  575. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  576. if (version_out) {
  577. /* Finally, version value is 1 byte. */
  578. *version_out = get_uint8(address + offset);
  579. }
  580. offset += sizeof(uint8_t);
  581. /* Extra safety. */
  582. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  583. }
  584. /* Using the given identity public key and a blinded public key, compute the
  585. * subcredential and put it in subcred_out (must be of size DIGEST256_LEN).
  586. * This can't fail. */
  587. void
  588. hs_get_subcredential(const ed25519_public_key_t *identity_pk,
  589. const ed25519_public_key_t *blinded_pk,
  590. uint8_t *subcred_out)
  591. {
  592. uint8_t credential[DIGEST256_LEN];
  593. crypto_digest_t *digest;
  594. tor_assert(identity_pk);
  595. tor_assert(blinded_pk);
  596. tor_assert(subcred_out);
  597. /* First, build the credential. Construction is as follow:
  598. * credential = H("credential" | public-identity-key) */
  599. digest = crypto_digest256_new(DIGEST_SHA3_256);
  600. crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
  601. HS_CREDENTIAL_PREFIX_LEN);
  602. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  603. ED25519_PUBKEY_LEN);
  604. crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
  605. crypto_digest_free(digest);
  606. /* Now, compute the subcredential. Construction is as follow:
  607. * subcredential = H("subcredential" | credential | blinded-public-key). */
  608. digest = crypto_digest256_new(DIGEST_SHA3_256);
  609. crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
  610. HS_SUBCREDENTIAL_PREFIX_LEN);
  611. crypto_digest_add_bytes(digest, (const char *) credential,
  612. sizeof(credential));
  613. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  614. ED25519_PUBKEY_LEN);
  615. crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
  616. crypto_digest_free(digest);
  617. memwipe(credential, 0, sizeof(credential));
  618. }
  619. /* From the given list of hidden service ports, find the ones that much the
  620. * given edge connection conn, pick one at random and use it to set the
  621. * connection address. Return 0 on success or -1 if none. */
  622. int
  623. hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
  624. {
  625. rend_service_port_config_t *chosen_port;
  626. unsigned int warn_once = 0;
  627. smartlist_t *matching_ports;
  628. tor_assert(ports);
  629. tor_assert(conn);
  630. matching_ports = smartlist_new();
  631. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  632. if (TO_CONN(conn)->port != p->virtual_port) {
  633. continue;
  634. }
  635. if (!(p->is_unix_addr)) {
  636. smartlist_add(matching_ports, p);
  637. } else {
  638. if (add_unix_port(matching_ports, p)) {
  639. if (!warn_once) {
  640. /* Unix port not supported so warn only once. */
  641. log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
  642. "which is unsupported on this platform. "
  643. "Ignoring it.",
  644. TO_CONN(conn)->port);
  645. }
  646. warn_once++;
  647. }
  648. }
  649. } SMARTLIST_FOREACH_END(p);
  650. chosen_port = smartlist_choose(matching_ports);
  651. smartlist_free(matching_ports);
  652. if (chosen_port) {
  653. if (!(chosen_port->is_unix_addr)) {
  654. /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
  655. tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
  656. TO_CONN(conn)->port = chosen_port->real_port;
  657. } else {
  658. if (set_unix_port(conn, chosen_port)) {
  659. /* Simply impossible to end up here else we were able to add a Unix
  660. * port without AF_UNIX support... ? */
  661. tor_assert(0);
  662. }
  663. }
  664. }
  665. return (chosen_port) ? 0 : -1;
  666. }
  667. /* Using a base32 representation of a service address, parse its content into
  668. * the key_out, checksum_out and version_out. Any out variable can be NULL in
  669. * case the caller would want only one field. checksum_out MUST at least be 2
  670. * bytes long.
  671. *
  672. * Return 0 if parsing went well; return -1 in case of error. */
  673. int
  674. hs_parse_address(const char *address, ed25519_public_key_t *key_out,
  675. uint8_t *checksum_out, uint8_t *version_out)
  676. {
  677. char decoded[HS_SERVICE_ADDR_LEN];
  678. tor_assert(address);
  679. /* Obvious length check. */
  680. if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
  681. log_warn(LD_REND, "Service address %s has an invalid length. "
  682. "Expected %lu but got %lu.",
  683. escaped_safe_str(address),
  684. (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
  685. (unsigned long) strlen(address));
  686. goto invalid;
  687. }
  688. /* Decode address so we can extract needed fields. */
  689. if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
  690. log_warn(LD_REND, "Service address %s can't be decoded.",
  691. escaped_safe_str(address));
  692. goto invalid;
  693. }
  694. /* Parse the decoded address into the fields we need. */
  695. hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
  696. return 0;
  697. invalid:
  698. return -1;
  699. }
  700. /* Validate a given onion address. The length, the base32 decoding and
  701. * checksum are validated. Return 1 if valid else 0. */
  702. int
  703. hs_address_is_valid(const char *address)
  704. {
  705. uint8_t version;
  706. uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
  707. uint8_t target_checksum[DIGEST256_LEN];
  708. ed25519_public_key_t key;
  709. /* Parse the decoded address into the fields we need. */
  710. if (hs_parse_address(address, &key, checksum, &version) < 0) {
  711. goto invalid;
  712. }
  713. /* Get the checksum it's suppose to be and compare it with what we have
  714. * encoded in the address. */
  715. build_hs_checksum(&key, version, target_checksum);
  716. if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
  717. log_warn(LD_REND, "Service address %s invalid checksum.",
  718. escaped_safe_str(address));
  719. goto invalid;
  720. }
  721. /* Valid address. */
  722. return 1;
  723. invalid:
  724. return 0;
  725. }
  726. /* Build a service address using an ed25519 public key and a given version.
  727. * The returned address is base32 encoded and put in addr_out. The caller MUST
  728. * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
  729. *
  730. * Format is as follow:
  731. * base32(PUBKEY || CHECKSUM || VERSION)
  732. * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
  733. * */
  734. void
  735. hs_build_address(const ed25519_public_key_t *key, uint8_t version,
  736. char *addr_out)
  737. {
  738. uint8_t checksum[DIGEST256_LEN];
  739. char address[HS_SERVICE_ADDR_LEN];
  740. tor_assert(key);
  741. tor_assert(addr_out);
  742. /* Get the checksum of the address. */
  743. build_hs_checksum(key, version, checksum);
  744. /* Get the binary address representation. */
  745. build_hs_address(key, checksum, version, address);
  746. /* Encode the address. addr_out will be NUL terminated after this. */
  747. base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
  748. sizeof(address));
  749. /* Validate what we just built. */
  750. tor_assert(hs_address_is_valid(addr_out));
  751. }
  752. /* Return a newly allocated copy of lspec. */
  753. link_specifier_t *
  754. hs_link_specifier_dup(const link_specifier_t *lspec)
  755. {
  756. link_specifier_t *dup = link_specifier_new();
  757. memcpy(dup, lspec, sizeof(*dup));
  758. /* The unrecognized field is a dynamic array so make sure to copy its
  759. * content and not the pointer. */
  760. link_specifier_setlen_un_unrecognized(
  761. dup, link_specifier_getlen_un_unrecognized(lspec));
  762. if (link_specifier_getlen_un_unrecognized(dup)) {
  763. memcpy(link_specifier_getarray_un_unrecognized(dup),
  764. link_specifier_getconstarray_un_unrecognized(lspec),
  765. link_specifier_getlen_un_unrecognized(dup));
  766. }
  767. return dup;
  768. }
  769. /* From a given ed25519 public key pk and an optional secret, compute a
  770. * blinded public key and put it in blinded_pk_out. This is only useful to
  771. * the client side because the client only has access to the identity public
  772. * key of the service. */
  773. void
  774. hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
  775. const uint8_t *secret, size_t secret_len,
  776. uint64_t time_period_num,
  777. ed25519_public_key_t *blinded_pk_out)
  778. {
  779. /* Our blinding key API requires a 32 bytes parameter. */
  780. uint8_t param[DIGEST256_LEN];
  781. tor_assert(pk);
  782. tor_assert(blinded_pk_out);
  783. tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
  784. build_blinded_key_param(pk, secret, secret_len,
  785. time_period_num, get_time_period_length(), param);
  786. ed25519_public_blind(blinded_pk_out, pk, param);
  787. memwipe(param, 0, sizeof(param));
  788. }
  789. /* From a given ed25519 keypair kp and an optional secret, compute a blinded
  790. * keypair for the current time period and put it in blinded_kp_out. This is
  791. * only useful by the service side because the client doesn't have access to
  792. * the identity secret key. */
  793. void
  794. hs_build_blinded_keypair(const ed25519_keypair_t *kp,
  795. const uint8_t *secret, size_t secret_len,
  796. uint64_t time_period_num,
  797. ed25519_keypair_t *blinded_kp_out)
  798. {
  799. /* Our blinding key API requires a 32 bytes parameter. */
  800. uint8_t param[DIGEST256_LEN];
  801. tor_assert(kp);
  802. tor_assert(blinded_kp_out);
  803. /* Extra safety. A zeroed key is bad. */
  804. tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
  805. tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
  806. build_blinded_key_param(&kp->pubkey, secret, secret_len,
  807. time_period_num, get_time_period_length(), param);
  808. ed25519_keypair_blind(blinded_kp_out, kp, param);
  809. memwipe(param, 0, sizeof(param));
  810. }
  811. /* Return true if overlap mode is active given the date in consensus. If
  812. * consensus is NULL, then we use the latest live consensus we can find. */
  813. MOCK_IMPL(int,
  814. hs_overlap_mode_is_active, (const networkstatus_t *consensus, time_t now))
  815. {
  816. time_t valid_after;
  817. time_t srv_start_time, tp_start_time;
  818. if (!consensus) {
  819. consensus = networkstatus_get_live_consensus(now);
  820. if (!consensus) {
  821. return 0;
  822. }
  823. }
  824. /* We consider to be in overlap mode when we are in the period of time
  825. * between a fresh SRV and the beginning of the new time period (in the
  826. * normal network this is between 00:00 (inclusive) and 12:00 UTC
  827. * (exclusive)) */
  828. valid_after = consensus->valid_after;
  829. srv_start_time =sr_state_get_start_time_of_current_protocol_run(valid_after);
  830. tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
  831. if (valid_after >= srv_start_time && valid_after < tp_start_time) {
  832. return 1;
  833. }
  834. return 0;
  835. }
  836. /* Return 1 if any virtual port in ports needs a circuit with good uptime.
  837. * Else return 0. */
  838. int
  839. hs_service_requires_uptime_circ(const smartlist_t *ports)
  840. {
  841. tor_assert(ports);
  842. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  843. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  844. p->virtual_port)) {
  845. return 1;
  846. }
  847. } SMARTLIST_FOREACH_END(p);
  848. return 0;
  849. }
  850. /* Build hs_index which is used to find the responsible hsdirs. This index
  851. * value is used to select the responsible HSDir where their hsdir_index is
  852. * closest to this value.
  853. * SHA3-256("store-at-idx" | blinded_public_key |
  854. * INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
  855. *
  856. * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
  857. void
  858. hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
  859. uint64_t period_num, uint8_t *hs_index_out)
  860. {
  861. crypto_digest_t *digest;
  862. tor_assert(blinded_pk);
  863. tor_assert(hs_index_out);
  864. /* Build hs_index. See construction at top of function comment. */
  865. digest = crypto_digest256_new(DIGEST_SHA3_256);
  866. crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
  867. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  868. ED25519_PUBKEY_LEN);
  869. /* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
  870. {
  871. uint64_t period_length = get_time_period_length();
  872. char buf[sizeof(uint64_t)*3];
  873. size_t offset = 0;
  874. set_uint64(buf, tor_htonll(replica));
  875. offset += sizeof(uint64_t);
  876. set_uint64(buf, tor_htonll(period_length));
  877. offset += sizeof(uint64_t);
  878. set_uint64(buf, tor_htonll(period_num));
  879. offset += sizeof(uint64_t);
  880. tor_assert(offset == sizeof(buf));
  881. crypto_digest_add_bytes(digest, buf, sizeof(buf));
  882. }
  883. crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
  884. crypto_digest_free(digest);
  885. }
  886. /* Build hsdir_index which is used to find the responsible hsdirs. This is the
  887. * index value that is compare to the hs_index when selecting an HSDir.
  888. * SHA3-256("node-idx" | node_identity |
  889. * shared_random_value | INT_8(period_length) | INT_8(period_num) )
  890. *
  891. * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
  892. void
  893. hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
  894. const uint8_t *srv_value, uint64_t period_num,
  895. uint8_t *hsdir_index_out)
  896. {
  897. crypto_digest_t *digest;
  898. tor_assert(identity_pk);
  899. tor_assert(srv_value);
  900. tor_assert(hsdir_index_out);
  901. /* Build hsdir_index. See construction at top of function comment. */
  902. digest = crypto_digest256_new(DIGEST_SHA3_256);
  903. crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
  904. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  905. ED25519_PUBKEY_LEN);
  906. crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
  907. {
  908. uint64_t time_period_length = get_time_period_length();
  909. char period_stuff[sizeof(uint64_t)*2];
  910. size_t offset = 0;
  911. set_uint64(period_stuff, tor_htonll(period_num));
  912. offset += sizeof(uint64_t);
  913. set_uint64(period_stuff+offset, tor_htonll(time_period_length));
  914. offset += sizeof(uint64_t);
  915. tor_assert(offset == sizeof(period_stuff));
  916. crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
  917. }
  918. crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
  919. crypto_digest_free(digest);
  920. }
  921. /* Return a newly allocated buffer containing the current shared random value
  922. * or if not present, a disaster value is computed using the given time period
  923. * number. This function can't fail. */
  924. uint8_t *
  925. hs_get_current_srv(uint64_t time_period_num)
  926. {
  927. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  928. const sr_srv_t *current_srv = sr_get_current();
  929. if (current_srv) {
  930. memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
  931. } else {
  932. /* Disaster mode. */
  933. get_disaster_srv(time_period_num, sr_value);
  934. }
  935. return sr_value;
  936. }
  937. /* Return a newly allocated buffer containing the previous shared random
  938. * value or if not present, a disaster value is computed using the given time
  939. * period number. This function can't fail. */
  940. uint8_t *
  941. hs_get_previous_srv(uint64_t time_period_num)
  942. {
  943. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  944. const sr_srv_t *previous_srv = sr_get_previous();
  945. if (previous_srv) {
  946. memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
  947. } else {
  948. /* Disaster mode. */
  949. get_disaster_srv(time_period_num, sr_value);
  950. }
  951. return sr_value;
  952. }
  953. /* Return the number of replicas defined by a consensus parameter or the
  954. * default value. */
  955. int32_t
  956. hs_get_hsdir_n_replicas(void)
  957. {
  958. /* The [1,16] range is a specification requirement. */
  959. return networkstatus_get_param(NULL, "hsdir_n_replicas",
  960. HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
  961. }
  962. /* Return the spread fetch value defined by a consensus parameter or the
  963. * default value. */
  964. int32_t
  965. hs_get_hsdir_spread_fetch(void)
  966. {
  967. /* The [1,128] range is a specification requirement. */
  968. return networkstatus_get_param(NULL, "hsdir_spread_fetch",
  969. HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
  970. }
  971. /* Return the spread store value defined by a consensus parameter or the
  972. * default value. */
  973. int32_t
  974. hs_get_hsdir_spread_store(void)
  975. {
  976. /* The [1,128] range is a specification requirement. */
  977. return networkstatus_get_param(NULL, "hsdir_spread_store",
  978. HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
  979. }
  980. /** <b>node</b> is an HSDir so make sure that we have assigned an hsdir index.
  981. * Return 0 if everything is as expected, else return -1. */
  982. static int
  983. node_has_hsdir_index(const node_t *node)
  984. {
  985. tor_assert(node_supports_v3_hsdir(node));
  986. /* A node can't have an HSDir index without a descriptor since we need desc
  987. * to get its ed25519 key */
  988. if (!node_has_descriptor(node)) {
  989. return 0;
  990. }
  991. /* At this point, since the node has a desc, this node must also have an
  992. * hsdir index. If not, something went wrong, so BUG out. */
  993. if (BUG(node->hsdir_index == NULL) ||
  994. BUG(tor_mem_is_zero((const char*)node->hsdir_index->current,
  995. DIGEST256_LEN))) {
  996. return 0;
  997. }
  998. return 1;
  999. }
  1000. /* For a given blinded key and time period number, get the responsible HSDir
  1001. * and put their routerstatus_t object in the responsible_dirs list. If
  1002. * is_next_period is true, the next hsdir_index of the node_t is used. If
  1003. * is_client is true, the spread fetch consensus parameter is used else the
  1004. * spread store is used which is only for upload. This function can't fail but
  1005. * it is possible that the responsible_dirs list contains fewer nodes than
  1006. * expected.
  1007. *
  1008. * This function goes over the latest consensus routerstatus list and sorts it
  1009. * by their node_t hsdir_index then does a binary search to find the closest
  1010. * node. All of this makes it a bit CPU intensive so use it wisely. */
  1011. void
  1012. hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
  1013. uint64_t time_period_num, int is_next_period,
  1014. int is_client, smartlist_t *responsible_dirs)
  1015. {
  1016. smartlist_t *sorted_nodes;
  1017. /* The compare function used for the smartlist bsearch. We have two
  1018. * different depending on is_next_period. */
  1019. int (*cmp_fct)(const void *, const void **);
  1020. tor_assert(blinded_pk);
  1021. tor_assert(responsible_dirs);
  1022. sorted_nodes = smartlist_new();
  1023. /* Add every node_t that support HSDir v3 for which we do have a valid
  1024. * hsdir_index already computed for them for this consensus. */
  1025. {
  1026. networkstatus_t *c = networkstatus_get_latest_consensus();
  1027. if (!c || smartlist_len(c->routerstatus_list) == 0) {
  1028. log_warn(LD_REND, "No valid consensus so we can't get the responsible "
  1029. "hidden service directories.");
  1030. goto done;
  1031. }
  1032. SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
  1033. /* Even though this node_t object won't be modified and should be const,
  1034. * we can't add const object in a smartlist_t. */
  1035. node_t *n = node_get_mutable_by_id(rs->identity_digest);
  1036. tor_assert(n);
  1037. if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
  1038. if (!node_has_hsdir_index(n)) {
  1039. log_info(LD_GENERAL, "Node %s was found without hsdir index.",
  1040. node_describe(n));
  1041. continue;
  1042. }
  1043. smartlist_add(sorted_nodes, n);
  1044. }
  1045. } SMARTLIST_FOREACH_END(rs);
  1046. }
  1047. if (smartlist_len(sorted_nodes) == 0) {
  1048. log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
  1049. goto done;
  1050. }
  1051. /* First thing we have to do is sort all node_t by hsdir_index. The
  1052. * is_next_period tells us if we want the current or the next one. Set the
  1053. * bsearch compare function also while we are at it. */
  1054. if (is_next_period) {
  1055. smartlist_sort(sorted_nodes, compare_node_next_hsdir_index);
  1056. cmp_fct = compare_digest_to_next_hsdir_index;
  1057. } else {
  1058. smartlist_sort(sorted_nodes, compare_node_current_hsdir_index);
  1059. cmp_fct = compare_digest_to_current_hsdir_index;
  1060. }
  1061. /* For all replicas, we'll select a set of HSDirs using the consensus
  1062. * parameters and the sorted list. The replica starting at value 1 is
  1063. * defined by the specification. */
  1064. for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
  1065. int idx, start, found, n_added = 0;
  1066. uint8_t hs_index[DIGEST256_LEN] = {0};
  1067. /* Number of node to add to the responsible dirs list depends on if we are
  1068. * trying to fetch or store. A client always fetches. */
  1069. int n_to_add = (is_client) ? hs_get_hsdir_spread_fetch() :
  1070. hs_get_hsdir_spread_store();
  1071. /* Get the index that we should use to select the node. */
  1072. hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
  1073. /* The compare function pointer has been set correctly earlier. */
  1074. start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
  1075. &found);
  1076. /* Getting the length of the list if no member is greater than the key we
  1077. * are looking for so start at the first element. */
  1078. if (idx == smartlist_len(sorted_nodes)) {
  1079. start = idx = 0;
  1080. }
  1081. while (n_added < n_to_add) {
  1082. const node_t *node = smartlist_get(sorted_nodes, idx);
  1083. /* If the node has already been selected which is possible between
  1084. * replicas, the specification says to skip over. */
  1085. if (!smartlist_contains(responsible_dirs, node->rs)) {
  1086. smartlist_add(responsible_dirs, node->rs);
  1087. ++n_added;
  1088. }
  1089. if (++idx == smartlist_len(sorted_nodes)) {
  1090. /* Wrap if we've reached the end of the list. */
  1091. idx = 0;
  1092. }
  1093. if (idx == start) {
  1094. /* We've gone over the whole list, stop and avoid infinite loop. */
  1095. break;
  1096. }
  1097. }
  1098. }
  1099. done:
  1100. smartlist_free(sorted_nodes);
  1101. }
  1102. /* Initialize the entire HS subsytem. This is called in tor_init() before any
  1103. * torrc options are loaded. Only for >= v3. */
  1104. void
  1105. hs_init(void)
  1106. {
  1107. hs_circuitmap_init();
  1108. hs_service_init();
  1109. hs_cache_init();
  1110. }
  1111. /* Release and cleanup all memory of the HS subsystem (all version). This is
  1112. * called by tor_free_all(). */
  1113. void
  1114. hs_free_all(void)
  1115. {
  1116. hs_circuitmap_free_all();
  1117. hs_service_free_all();
  1118. hs_cache_free_all();
  1119. }