hs_common.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. /* Copyright (c) 2016-2019, 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 "core/or/or.h"
  12. #include "app/config/config.h"
  13. #include "core/or/circuitbuild.h"
  14. #include "core/or/policies.h"
  15. #include "feature/dirauth/shared_random_state.h"
  16. #include "feature/hs/hs_cache.h"
  17. #include "feature/hs/hs_circuitmap.h"
  18. #include "feature/hs/hs_client.h"
  19. #include "feature/hs/hs_common.h"
  20. #include "feature/hs/hs_ident.h"
  21. #include "feature/hs/hs_service.h"
  22. #include "feature/hs_common/shared_random_client.h"
  23. #include "feature/nodelist/describe.h"
  24. #include "feature/nodelist/networkstatus.h"
  25. #include "feature/nodelist/nodelist.h"
  26. #include "feature/nodelist/routerset.h"
  27. #include "feature/rend/rendcommon.h"
  28. #include "feature/rend/rendservice.h"
  29. #include "lib/crypt_ops/crypto_rand.h"
  30. #include "lib/crypt_ops/crypto_util.h"
  31. #include "core/or/edge_connection_st.h"
  32. #include "feature/nodelist/networkstatus_st.h"
  33. #include "feature/nodelist/node_st.h"
  34. #include "core/or/origin_circuit_st.h"
  35. #include "feature/nodelist/routerstatus_st.h"
  36. /* Trunnel */
  37. #include "trunnel/ed25519_cert.h"
  38. /* Ed25519 Basepoint value. Taken from section 5 of
  39. * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
  40. static const char *str_ed25519_basepoint =
  41. "(15112221349535400772501151409588531511"
  42. "454012693041857206046113283949847762202, "
  43. "463168356949264781694283940034751631413"
  44. "07993866256225615783033603165251855960)";
  45. #ifdef HAVE_SYS_UN_H
  46. /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
  47. * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
  48. * else return -ENOSYS if AF_UNIX is not supported (see function in the
  49. * #else statement below). */
  50. static int
  51. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  52. {
  53. tor_assert(ports);
  54. tor_assert(p);
  55. tor_assert(p->is_unix_addr);
  56. smartlist_add(ports, p);
  57. return 0;
  58. }
  59. /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
  60. * on success else return -ENOSYS if AF_UNIX is not supported (see function
  61. * in the #else statement below). */
  62. static int
  63. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  64. {
  65. tor_assert(conn);
  66. tor_assert(p);
  67. tor_assert(p->is_unix_addr);
  68. conn->base_.socket_family = AF_UNIX;
  69. tor_addr_make_unspec(&conn->base_.addr);
  70. conn->base_.port = 1;
  71. conn->base_.address = tor_strdup(p->unix_addr);
  72. return 0;
  73. }
  74. #else /* !(defined(HAVE_SYS_UN_H)) */
  75. static int
  76. set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
  77. {
  78. (void) conn;
  79. (void) p;
  80. return -ENOSYS;
  81. }
  82. static int
  83. add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
  84. {
  85. (void) ports;
  86. (void) p;
  87. return -ENOSYS;
  88. }
  89. #endif /* defined(HAVE_SYS_UN_H) */
  90. /* Helper function: The key is a digest that we compare to a node_t object
  91. * current hsdir_index. */
  92. static int
  93. compare_digest_to_fetch_hsdir_index(const void *_key, const void **_member)
  94. {
  95. const char *key = _key;
  96. const node_t *node = *_member;
  97. return tor_memcmp(key, node->hsdir_index.fetch, DIGEST256_LEN);
  98. }
  99. /* Helper function: The key is a digest that we compare to a node_t object
  100. * next hsdir_index. */
  101. static int
  102. compare_digest_to_store_first_hsdir_index(const void *_key,
  103. const void **_member)
  104. {
  105. const char *key = _key;
  106. const node_t *node = *_member;
  107. return tor_memcmp(key, node->hsdir_index.store_first, DIGEST256_LEN);
  108. }
  109. /* Helper function: The key is a digest that we compare to a node_t object
  110. * next hsdir_index. */
  111. static int
  112. compare_digest_to_store_second_hsdir_index(const void *_key,
  113. const void **_member)
  114. {
  115. const char *key = _key;
  116. const node_t *node = *_member;
  117. return tor_memcmp(key, node->hsdir_index.store_second, DIGEST256_LEN);
  118. }
  119. /* Helper function: Compare two node_t objects current hsdir_index. */
  120. static int
  121. compare_node_fetch_hsdir_index(const void **a, const void **b)
  122. {
  123. const node_t *node1= *a;
  124. const node_t *node2 = *b;
  125. return tor_memcmp(node1->hsdir_index.fetch,
  126. node2->hsdir_index.fetch,
  127. DIGEST256_LEN);
  128. }
  129. /* Helper function: Compare two node_t objects next hsdir_index. */
  130. static int
  131. compare_node_store_first_hsdir_index(const void **a, const void **b)
  132. {
  133. const node_t *node1= *a;
  134. const node_t *node2 = *b;
  135. return tor_memcmp(node1->hsdir_index.store_first,
  136. node2->hsdir_index.store_first,
  137. DIGEST256_LEN);
  138. }
  139. /* Helper function: Compare two node_t objects next hsdir_index. */
  140. static int
  141. compare_node_store_second_hsdir_index(const void **a, const void **b)
  142. {
  143. const node_t *node1= *a;
  144. const node_t *node2 = *b;
  145. return tor_memcmp(node1->hsdir_index.store_second,
  146. node2->hsdir_index.store_second,
  147. DIGEST256_LEN);
  148. }
  149. /* Allocate and return a string containing the path to filename in directory.
  150. * This function will never return NULL. The caller must free this path. */
  151. char *
  152. hs_path_from_filename(const char *directory, const char *filename)
  153. {
  154. char *file_path = NULL;
  155. tor_assert(directory);
  156. tor_assert(filename);
  157. tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
  158. return file_path;
  159. }
  160. /* Make sure that the directory for <b>service</b> is private, using the config
  161. * <b>username</b>.
  162. * If <b>create</b> is true:
  163. * - if the directory exists, change permissions if needed,
  164. * - if the directory does not exist, create it with the correct permissions.
  165. * If <b>create</b> is false:
  166. * - if the directory exists, check permissions,
  167. * - if the directory does not exist, check if we think we can create it.
  168. * Return 0 on success, -1 on failure. */
  169. int
  170. hs_check_service_private_dir(const char *username, const char *path,
  171. unsigned int dir_group_readable,
  172. unsigned int create)
  173. {
  174. cpd_check_t check_opts = CPD_NONE;
  175. tor_assert(path);
  176. if (create) {
  177. check_opts |= CPD_CREATE;
  178. } else {
  179. check_opts |= CPD_CHECK_MODE_ONLY;
  180. check_opts |= CPD_CHECK;
  181. }
  182. if (dir_group_readable) {
  183. check_opts |= CPD_GROUP_READ;
  184. }
  185. /* Check/create directory */
  186. if (check_private_dir(path, check_opts, username) < 0) {
  187. return -1;
  188. }
  189. return 0;
  190. }
  191. /* Default, minimum, and maximum values for the maximum rendezvous failures
  192. * consensus parameter. */
  193. #define MAX_REND_FAILURES_DEFAULT 2
  194. #define MAX_REND_FAILURES_MIN 1
  195. #define MAX_REND_FAILURES_MAX 10
  196. /** How many times will a hidden service operator attempt to connect to
  197. * a requested rendezvous point before giving up? */
  198. int
  199. hs_get_service_max_rend_failures(void)
  200. {
  201. return networkstatus_get_param(NULL, "hs_service_max_rdv_failures",
  202. MAX_REND_FAILURES_DEFAULT,
  203. MAX_REND_FAILURES_MIN,
  204. MAX_REND_FAILURES_MAX);
  205. }
  206. /** Get the default HS time period length in minutes from the consensus. */
  207. STATIC uint64_t
  208. get_time_period_length(void)
  209. {
  210. /* If we are on a test network, make the time period smaller than normal so
  211. that we actually see it rotate. Specifically, make it the same length as
  212. an SRV protocol run. */
  213. if (get_options()->TestingTorNetwork) {
  214. unsigned run_duration = sr_state_get_protocol_run_duration();
  215. /* An SRV run should take more than a minute (it's 24 rounds) */
  216. tor_assert_nonfatal(run_duration > 60);
  217. /* Turn it from seconds to minutes before returning: */
  218. return sr_state_get_protocol_run_duration() / 60;
  219. }
  220. int32_t time_period_length = networkstatus_get_param(NULL, "hsdir_interval",
  221. HS_TIME_PERIOD_LENGTH_DEFAULT,
  222. HS_TIME_PERIOD_LENGTH_MIN,
  223. HS_TIME_PERIOD_LENGTH_MAX);
  224. /* Make sure it's a positive value. */
  225. tor_assert(time_period_length > 0);
  226. /* uint64_t will always be able to contain a positive int32_t */
  227. return (uint64_t) time_period_length;
  228. }
  229. /** Get the HS time period number at time <b>now</b>. If <b>now</b> is not set,
  230. * we try to get the time ourselves from a live consensus. */
  231. uint64_t
  232. hs_get_time_period_num(time_t now)
  233. {
  234. uint64_t time_period_num;
  235. time_t current_time;
  236. /* If no time is specified, set current time based on consensus time, and
  237. * only fall back to system time if that fails. */
  238. if (now != 0) {
  239. current_time = now;
  240. } else {
  241. networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
  242. current_time = ns ? ns->valid_after : approx_time();
  243. }
  244. /* Start by calculating minutes since the epoch */
  245. uint64_t time_period_length = get_time_period_length();
  246. uint64_t minutes_since_epoch = current_time / 60;
  247. /* Apply the rotation offset as specified by prop224 (section
  248. * [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
  249. * publication */
  250. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  251. time_period_rotation_offset /= 60; /* go from seconds to minutes */
  252. tor_assert(minutes_since_epoch > time_period_rotation_offset);
  253. minutes_since_epoch -= time_period_rotation_offset;
  254. /* Calculate the time period */
  255. time_period_num = minutes_since_epoch / time_period_length;
  256. return time_period_num;
  257. }
  258. /** Get the number of the _upcoming_ HS time period, given that the current
  259. * time is <b>now</b>. If <b>now</b> is not set, we try to get the time from a
  260. * live consensus. */
  261. uint64_t
  262. hs_get_next_time_period_num(time_t now)
  263. {
  264. return hs_get_time_period_num(now) + 1;
  265. }
  266. /* Get the number of the _previous_ HS time period, given that the current time
  267. * is <b>now</b>. If <b>now</b> is not set, we try to get the time from a live
  268. * consensus. */
  269. uint64_t
  270. hs_get_previous_time_period_num(time_t now)
  271. {
  272. return hs_get_time_period_num(now) - 1;
  273. }
  274. /* Return the start time of the upcoming time period based on <b>now</b>. If
  275. <b>now</b> is not set, we try to get the time ourselves from a live
  276. consensus. */
  277. time_t
  278. hs_get_start_time_of_next_time_period(time_t now)
  279. {
  280. uint64_t time_period_length = get_time_period_length();
  281. /* Get start time of next time period */
  282. uint64_t next_time_period_num = hs_get_next_time_period_num(now);
  283. uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
  284. /* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
  285. unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
  286. return (time_t)(start_of_next_tp_in_mins * 60 + time_period_rotation_offset);
  287. }
  288. /* Create a new rend_data_t for a specific given <b>version</b>.
  289. * Return a pointer to the newly allocated data structure. */
  290. static rend_data_t *
  291. rend_data_alloc(uint32_t version)
  292. {
  293. rend_data_t *rend_data = NULL;
  294. switch (version) {
  295. case HS_VERSION_TWO:
  296. {
  297. rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
  298. v2->base_.version = HS_VERSION_TWO;
  299. v2->base_.hsdirs_fp = smartlist_new();
  300. rend_data = &v2->base_;
  301. break;
  302. }
  303. default:
  304. tor_assert(0);
  305. break;
  306. }
  307. return rend_data;
  308. }
  309. /** Free all storage associated with <b>data</b> */
  310. void
  311. rend_data_free_(rend_data_t *data)
  312. {
  313. if (!data) {
  314. return;
  315. }
  316. /* By using our allocation function, this should always be set. */
  317. tor_assert(data->hsdirs_fp);
  318. /* Cleanup the HSDir identity digest. */
  319. SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
  320. smartlist_free(data->hsdirs_fp);
  321. /* Depending on the version, cleanup. */
  322. switch (data->version) {
  323. case HS_VERSION_TWO:
  324. {
  325. rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
  326. tor_free(v2_data);
  327. break;
  328. }
  329. default:
  330. tor_assert(0);
  331. }
  332. }
  333. /* Allocate and return a deep copy of <b>data</b>. */
  334. rend_data_t *
  335. rend_data_dup(const rend_data_t *data)
  336. {
  337. rend_data_t *data_dup = NULL;
  338. smartlist_t *hsdirs_fp = smartlist_new();
  339. tor_assert(data);
  340. tor_assert(data->hsdirs_fp);
  341. SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
  342. smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
  343. switch (data->version) {
  344. case HS_VERSION_TWO:
  345. {
  346. rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
  347. sizeof(*v2_data));
  348. data_dup = &v2_data->base_;
  349. data_dup->hsdirs_fp = hsdirs_fp;
  350. break;
  351. }
  352. default:
  353. tor_assert(0);
  354. break;
  355. }
  356. return data_dup;
  357. }
  358. /* Compute the descriptor ID for each HS descriptor replica and save them. A
  359. * valid onion address must be present in the <b>rend_data</b>.
  360. *
  361. * Return 0 on success else -1. */
  362. static int
  363. compute_desc_id(rend_data_t *rend_data)
  364. {
  365. int ret = 0;
  366. unsigned replica;
  367. time_t now = time(NULL);
  368. tor_assert(rend_data);
  369. switch (rend_data->version) {
  370. case HS_VERSION_TWO:
  371. {
  372. rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  373. /* Compute descriptor ID for each replicas. */
  374. for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
  375. replica++) {
  376. ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
  377. v2_data->onion_address,
  378. v2_data->descriptor_cookie,
  379. now, replica);
  380. if (ret < 0) {
  381. goto end;
  382. }
  383. }
  384. break;
  385. }
  386. default:
  387. tor_assert(0);
  388. }
  389. end:
  390. return ret;
  391. }
  392. /* Allocate and initialize a rend_data_t object for a service using the
  393. * provided arguments. All arguments are optional (can be NULL), except from
  394. * <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
  395. * the service private key. The <b>cookie</b> is the rendezvous cookie and
  396. * <b>auth_type</b> is which authentiation this service is configured with.
  397. *
  398. * Return a valid rend_data_t pointer. This only returns a version 2 object of
  399. * rend_data_t. */
  400. rend_data_t *
  401. rend_data_service_create(const char *onion_address, const char *pk_digest,
  402. const uint8_t *cookie, rend_auth_type_t auth_type)
  403. {
  404. /* Create a rend_data_t object for version 2. */
  405. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  406. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  407. /* We need at least one else the call is wrong. */
  408. tor_assert(onion_address != NULL);
  409. if (pk_digest) {
  410. memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
  411. }
  412. if (cookie) {
  413. memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
  414. }
  415. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  416. v2->auth_type = auth_type;
  417. return rend_data;
  418. }
  419. /* Allocate and initialize a rend_data_t object for a client request using the
  420. * given arguments. Either an onion address or a descriptor ID is needed. Both
  421. * can be given but in this case only the onion address will be used to make
  422. * the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
  423. * <b>auth_type</b> is which authentiation the service is configured with.
  424. *
  425. * Return a valid rend_data_t pointer or NULL on error meaning the
  426. * descriptor IDs couldn't be computed from the given data. */
  427. rend_data_t *
  428. rend_data_client_create(const char *onion_address, const char *desc_id,
  429. const char *cookie, rend_auth_type_t auth_type)
  430. {
  431. /* Create a rend_data_t object for version 2. */
  432. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  433. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  434. /* We need at least one else the call is wrong. */
  435. tor_assert(onion_address != NULL || desc_id != NULL);
  436. if (cookie) {
  437. memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
  438. }
  439. if (desc_id) {
  440. memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
  441. }
  442. if (onion_address) {
  443. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  444. if (compute_desc_id(rend_data) < 0) {
  445. goto error;
  446. }
  447. }
  448. v2->auth_type = auth_type;
  449. return rend_data;
  450. error:
  451. rend_data_free(rend_data);
  452. return NULL;
  453. }
  454. /* Return the onion address from the rend data. Depending on the version,
  455. * the size of the address can vary but it's always NUL terminated. */
  456. const char *
  457. rend_data_get_address(const rend_data_t *rend_data)
  458. {
  459. tor_assert(rend_data);
  460. switch (rend_data->version) {
  461. case HS_VERSION_TWO:
  462. return TO_REND_DATA_V2(rend_data)->onion_address;
  463. default:
  464. /* We should always have a supported version. */
  465. tor_assert_unreached();
  466. }
  467. }
  468. /* Return the descriptor ID for a specific replica number from the rend
  469. * data. The returned data is a binary digest and depending on the version its
  470. * size can vary. The size of the descriptor ID is put in <b>len_out</b> if
  471. * non NULL. */
  472. const char *
  473. rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
  474. size_t *len_out)
  475. {
  476. tor_assert(rend_data);
  477. switch (rend_data->version) {
  478. case HS_VERSION_TWO:
  479. tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
  480. if (len_out) {
  481. *len_out = DIGEST_LEN;
  482. }
  483. return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
  484. default:
  485. /* We should always have a supported version. */
  486. tor_assert_unreached();
  487. }
  488. }
  489. /* Return the public key digest using the given <b>rend_data</b>. The size of
  490. * the digest is put in <b>len_out</b> (if set) which can differ depending on
  491. * the version. */
  492. const uint8_t *
  493. rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
  494. {
  495. tor_assert(rend_data);
  496. switch (rend_data->version) {
  497. case HS_VERSION_TWO:
  498. {
  499. const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  500. if (len_out) {
  501. *len_out = sizeof(v2_data->rend_pk_digest);
  502. }
  503. return (const uint8_t *) v2_data->rend_pk_digest;
  504. }
  505. default:
  506. /* We should always have a supported version. */
  507. tor_assert_unreached();
  508. }
  509. }
  510. /* Using the given time period number, compute the disaster shared random
  511. * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
  512. static void
  513. compute_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  514. {
  515. crypto_digest_t *digest;
  516. tor_assert(srv_out);
  517. digest = crypto_digest256_new(DIGEST_SHA3_256);
  518. /* Start setting up payload:
  519. * H("shared-random-disaster" | INT_8(period_length) | INT_8(period_num)) */
  520. crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
  521. HS_SRV_DISASTER_PREFIX_LEN);
  522. /* Setup INT_8(period_length) | INT_8(period_num) */
  523. {
  524. uint64_t time_period_length = get_time_period_length();
  525. char period_stuff[sizeof(uint64_t)*2];
  526. size_t offset = 0;
  527. set_uint64(period_stuff, tor_htonll(time_period_length));
  528. offset += sizeof(uint64_t);
  529. set_uint64(period_stuff+offset, tor_htonll(time_period_num));
  530. offset += sizeof(uint64_t);
  531. tor_assert(offset == sizeof(period_stuff));
  532. crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
  533. }
  534. crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
  535. crypto_digest_free(digest);
  536. }
  537. /** Due to the high cost of computing the disaster SRV and that potentially we
  538. * would have to do it thousands of times in a row, we always cache the
  539. * computer disaster SRV (and its corresponding time period num) in case we
  540. * want to reuse it soon after. We need to cache two SRVs, one for each active
  541. * time period.
  542. */
  543. static uint8_t cached_disaster_srv[2][DIGEST256_LEN];
  544. static uint64_t cached_time_period_nums[2] = {0};
  545. /** Compute the disaster SRV value for this <b>time_period_num</b> and put it
  546. * in <b>srv_out</b> (of size at least DIGEST256_LEN). First check our caches
  547. * to see if we have already computed it. */
  548. STATIC void
  549. get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  550. {
  551. if (time_period_num == cached_time_period_nums[0]) {
  552. memcpy(srv_out, cached_disaster_srv[0], DIGEST256_LEN);
  553. return;
  554. } else if (time_period_num == cached_time_period_nums[1]) {
  555. memcpy(srv_out, cached_disaster_srv[1], DIGEST256_LEN);
  556. return;
  557. } else {
  558. int replace_idx;
  559. // Replace the lower period number.
  560. if (cached_time_period_nums[0] <= cached_time_period_nums[1]) {
  561. replace_idx = 0;
  562. } else {
  563. replace_idx = 1;
  564. }
  565. cached_time_period_nums[replace_idx] = time_period_num;
  566. compute_disaster_srv(time_period_num, cached_disaster_srv[replace_idx]);
  567. memcpy(srv_out, cached_disaster_srv[replace_idx], DIGEST256_LEN);
  568. return;
  569. }
  570. }
  571. #ifdef TOR_UNIT_TESTS
  572. /** Get the first cached disaster SRV. Only used by unittests. */
  573. STATIC uint8_t *
  574. get_first_cached_disaster_srv(void)
  575. {
  576. return cached_disaster_srv[0];
  577. }
  578. /** Get the second cached disaster SRV. Only used by unittests. */
  579. STATIC uint8_t *
  580. get_second_cached_disaster_srv(void)
  581. {
  582. return cached_disaster_srv[1];
  583. }
  584. #endif /* defined(TOR_UNIT_TESTS) */
  585. /* When creating a blinded key, we need a parameter which construction is as
  586. * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
  587. *
  588. * The nonce has a pre-defined format which uses the time period number
  589. * period_num and the start of the period in second start_time_period.
  590. *
  591. * The secret of size secret_len is optional meaning that it can be NULL and
  592. * thus will be ignored for the param construction.
  593. *
  594. * The result is put in param_out. */
  595. static void
  596. build_blinded_key_param(const ed25519_public_key_t *pubkey,
  597. const uint8_t *secret, size_t secret_len,
  598. uint64_t period_num, uint64_t period_length,
  599. uint8_t *param_out)
  600. {
  601. size_t offset = 0;
  602. const char blind_str[] = "Derive temporary signing key";
  603. uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
  604. crypto_digest_t *digest;
  605. tor_assert(pubkey);
  606. tor_assert(param_out);
  607. /* Create the nonce N. The construction is as follow:
  608. * N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
  609. memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
  610. offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
  611. set_uint64(nonce + offset, tor_htonll(period_num));
  612. offset += sizeof(uint64_t);
  613. set_uint64(nonce + offset, tor_htonll(period_length));
  614. offset += sizeof(uint64_t);
  615. tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
  616. /* Generate the parameter h and the construction is as follow:
  617. * h = H(BLIND_STRING | pubkey | [secret] | ed25519-basepoint | N) */
  618. digest = crypto_digest256_new(DIGEST_SHA3_256);
  619. crypto_digest_add_bytes(digest, blind_str, sizeof(blind_str));
  620. crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
  621. /* Optional secret. */
  622. if (secret) {
  623. crypto_digest_add_bytes(digest, (char *) secret, secret_len);
  624. }
  625. crypto_digest_add_bytes(digest, str_ed25519_basepoint,
  626. strlen(str_ed25519_basepoint));
  627. crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
  628. /* Extract digest and put it in the param. */
  629. crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
  630. crypto_digest_free(digest);
  631. memwipe(nonce, 0, sizeof(nonce));
  632. }
  633. /* Using an ed25519 public key and version to build the checksum of an
  634. * address. Put in checksum_out. Format is:
  635. * SHA3-256(".onion checksum" || PUBKEY || VERSION)
  636. *
  637. * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
  638. static void
  639. build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
  640. uint8_t *checksum_out)
  641. {
  642. size_t offset = 0;
  643. char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
  644. /* Build checksum data. */
  645. memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
  646. HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
  647. offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
  648. memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
  649. offset += ED25519_PUBKEY_LEN;
  650. set_uint8(data + offset, version);
  651. offset += sizeof(version);
  652. tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
  653. /* Hash the data payload to create the checksum. */
  654. crypto_digest256((char *) checksum_out, data, sizeof(data),
  655. DIGEST_SHA3_256);
  656. }
  657. /* Using an ed25519 public key, checksum and version to build the binary
  658. * representation of a service address. Put in addr_out. Format is:
  659. * addr_out = PUBKEY || CHECKSUM || VERSION
  660. *
  661. * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
  662. static void
  663. build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
  664. uint8_t version, char *addr_out)
  665. {
  666. size_t offset = 0;
  667. tor_assert(key);
  668. tor_assert(checksum);
  669. memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
  670. offset += ED25519_PUBKEY_LEN;
  671. memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  672. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  673. set_uint8(addr_out + offset, version);
  674. offset += sizeof(uint8_t);
  675. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  676. }
  677. /* Helper for hs_parse_address(): Using a binary representation of a service
  678. * address, parse its content into the key_out, checksum_out and version_out.
  679. * Any out variable can be NULL in case the caller would want only one field.
  680. * checksum_out MUST at least be 2 bytes long. address must be at least
  681. * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
  682. static void
  683. hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
  684. uint8_t *checksum_out, uint8_t *version_out)
  685. {
  686. size_t offset = 0;
  687. tor_assert(address);
  688. if (key_out) {
  689. /* First is the key. */
  690. memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
  691. }
  692. offset += ED25519_PUBKEY_LEN;
  693. if (checksum_out) {
  694. /* Followed by a 2 bytes checksum. */
  695. memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  696. }
  697. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  698. if (version_out) {
  699. /* Finally, version value is 1 byte. */
  700. *version_out = get_uint8(address + offset);
  701. }
  702. offset += sizeof(uint8_t);
  703. /* Extra safety. */
  704. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  705. }
  706. /* Using the given identity public key and a blinded public key, compute the
  707. * subcredential and put it in subcred_out (must be of size DIGEST256_LEN).
  708. * This can't fail. */
  709. void
  710. hs_get_subcredential(const ed25519_public_key_t *identity_pk,
  711. const ed25519_public_key_t *blinded_pk,
  712. uint8_t *subcred_out)
  713. {
  714. uint8_t credential[DIGEST256_LEN];
  715. crypto_digest_t *digest;
  716. tor_assert(identity_pk);
  717. tor_assert(blinded_pk);
  718. tor_assert(subcred_out);
  719. /* First, build the credential. Construction is as follow:
  720. * credential = H("credential" | public-identity-key) */
  721. digest = crypto_digest256_new(DIGEST_SHA3_256);
  722. crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
  723. HS_CREDENTIAL_PREFIX_LEN);
  724. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  725. ED25519_PUBKEY_LEN);
  726. crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
  727. crypto_digest_free(digest);
  728. /* Now, compute the subcredential. Construction is as follow:
  729. * subcredential = H("subcredential" | credential | blinded-public-key). */
  730. digest = crypto_digest256_new(DIGEST_SHA3_256);
  731. crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
  732. HS_SUBCREDENTIAL_PREFIX_LEN);
  733. crypto_digest_add_bytes(digest, (const char *) credential,
  734. sizeof(credential));
  735. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  736. ED25519_PUBKEY_LEN);
  737. crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
  738. crypto_digest_free(digest);
  739. memwipe(credential, 0, sizeof(credential));
  740. }
  741. /* From the given list of hidden service ports, find the ones that match the
  742. * given edge connection conn, pick one at random and use it to set the
  743. * connection address. Return 0 on success or -1 if none. */
  744. int
  745. hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
  746. {
  747. rend_service_port_config_t *chosen_port;
  748. unsigned int warn_once = 0;
  749. smartlist_t *matching_ports;
  750. tor_assert(ports);
  751. tor_assert(conn);
  752. matching_ports = smartlist_new();
  753. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  754. if (TO_CONN(conn)->port != p->virtual_port) {
  755. continue;
  756. }
  757. if (!(p->is_unix_addr)) {
  758. smartlist_add(matching_ports, p);
  759. } else {
  760. if (add_unix_port(matching_ports, p)) {
  761. if (!warn_once) {
  762. /* Unix port not supported so warn only once. */
  763. log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
  764. "which is unsupported on this platform. "
  765. "Ignoring it.",
  766. TO_CONN(conn)->port);
  767. }
  768. warn_once++;
  769. }
  770. }
  771. } SMARTLIST_FOREACH_END(p);
  772. chosen_port = smartlist_choose(matching_ports);
  773. smartlist_free(matching_ports);
  774. if (chosen_port) {
  775. if (!(chosen_port->is_unix_addr)) {
  776. /* save the original destination before we overwrite it */
  777. if (conn->hs_ident) {
  778. conn->hs_ident->orig_virtual_port = TO_CONN(conn)->port;
  779. }
  780. /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
  781. tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
  782. TO_CONN(conn)->port = chosen_port->real_port;
  783. } else {
  784. if (set_unix_port(conn, chosen_port)) {
  785. /* Simply impossible to end up here else we were able to add a Unix
  786. * port without AF_UNIX support... ? */
  787. tor_assert(0);
  788. }
  789. }
  790. }
  791. return (chosen_port) ? 0 : -1;
  792. }
  793. /* Using a base32 representation of a service address, parse its content into
  794. * the key_out, checksum_out and version_out. Any out variable can be NULL in
  795. * case the caller would want only one field. checksum_out MUST at least be 2
  796. * bytes long.
  797. *
  798. * Return 0 if parsing went well; return -1 in case of error. */
  799. int
  800. hs_parse_address(const char *address, ed25519_public_key_t *key_out,
  801. uint8_t *checksum_out, uint8_t *version_out)
  802. {
  803. char decoded[HS_SERVICE_ADDR_LEN];
  804. tor_assert(address);
  805. /* Obvious length check. */
  806. if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
  807. log_warn(LD_REND, "Service address %s has an invalid length. "
  808. "Expected %lu but got %lu.",
  809. escaped_safe_str(address),
  810. (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
  811. (unsigned long) strlen(address));
  812. goto invalid;
  813. }
  814. /* Decode address so we can extract needed fields. */
  815. if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
  816. log_warn(LD_REND, "Service address %s can't be decoded.",
  817. escaped_safe_str(address));
  818. goto invalid;
  819. }
  820. /* Parse the decoded address into the fields we need. */
  821. hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
  822. return 0;
  823. invalid:
  824. return -1;
  825. }
  826. /* Validate a given onion address. The length, the base32 decoding and
  827. * checksum are validated. Return 1 if valid else 0. */
  828. int
  829. hs_address_is_valid(const char *address)
  830. {
  831. uint8_t version;
  832. uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
  833. uint8_t target_checksum[DIGEST256_LEN];
  834. ed25519_public_key_t service_pubkey;
  835. /* Parse the decoded address into the fields we need. */
  836. if (hs_parse_address(address, &service_pubkey, checksum, &version) < 0) {
  837. goto invalid;
  838. }
  839. /* Get the checksum it's suppose to be and compare it with what we have
  840. * encoded in the address. */
  841. build_hs_checksum(&service_pubkey, version, target_checksum);
  842. if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
  843. log_warn(LD_REND, "Service address %s invalid checksum.",
  844. escaped_safe_str(address));
  845. goto invalid;
  846. }
  847. /* Validate that this pubkey does not have a torsion component. We need to do
  848. * this on the prop224 client-side so that attackers can't give equivalent
  849. * forms of an onion address to users. */
  850. if (ed25519_validate_pubkey(&service_pubkey) < 0) {
  851. log_warn(LD_REND, "Service address %s has bad pubkey .",
  852. escaped_safe_str(address));
  853. goto invalid;
  854. }
  855. /* Valid address. */
  856. return 1;
  857. invalid:
  858. return 0;
  859. }
  860. /* Build a service address using an ed25519 public key and a given version.
  861. * The returned address is base32 encoded and put in addr_out. The caller MUST
  862. * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
  863. *
  864. * Format is as follow:
  865. * base32(PUBKEY || CHECKSUM || VERSION)
  866. * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
  867. * */
  868. void
  869. hs_build_address(const ed25519_public_key_t *key, uint8_t version,
  870. char *addr_out)
  871. {
  872. uint8_t checksum[DIGEST256_LEN];
  873. char address[HS_SERVICE_ADDR_LEN];
  874. tor_assert(key);
  875. tor_assert(addr_out);
  876. /* Get the checksum of the address. */
  877. build_hs_checksum(key, version, checksum);
  878. /* Get the binary address representation. */
  879. build_hs_address(key, checksum, version, address);
  880. /* Encode the address. addr_out will be NUL terminated after this. */
  881. base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
  882. sizeof(address));
  883. /* Validate what we just built. */
  884. tor_assert(hs_address_is_valid(addr_out));
  885. }
  886. /* Return a newly allocated copy of lspec. */
  887. link_specifier_t *
  888. hs_link_specifier_dup(const link_specifier_t *lspec)
  889. {
  890. link_specifier_t *result = link_specifier_new();
  891. memcpy(result, lspec, sizeof(*result));
  892. /* The unrecognized field is a dynamic array so make sure to copy its
  893. * content and not the pointer. */
  894. link_specifier_setlen_un_unrecognized(
  895. result, link_specifier_getlen_un_unrecognized(lspec));
  896. if (link_specifier_getlen_un_unrecognized(result)) {
  897. memcpy(link_specifier_getarray_un_unrecognized(result),
  898. link_specifier_getconstarray_un_unrecognized(lspec),
  899. link_specifier_getlen_un_unrecognized(result));
  900. }
  901. return result;
  902. }
  903. /* From a given ed25519 public key pk and an optional secret, compute a
  904. * blinded public key and put it in blinded_pk_out. This is only useful to
  905. * the client side because the client only has access to the identity public
  906. * key of the service. */
  907. void
  908. hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
  909. const uint8_t *secret, size_t secret_len,
  910. uint64_t time_period_num,
  911. ed25519_public_key_t *blinded_pk_out)
  912. {
  913. /* Our blinding key API requires a 32 bytes parameter. */
  914. uint8_t param[DIGEST256_LEN];
  915. tor_assert(pk);
  916. tor_assert(blinded_pk_out);
  917. tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
  918. build_blinded_key_param(pk, secret, secret_len,
  919. time_period_num, get_time_period_length(), param);
  920. ed25519_public_blind(blinded_pk_out, pk, param);
  921. memwipe(param, 0, sizeof(param));
  922. }
  923. /* From a given ed25519 keypair kp and an optional secret, compute a blinded
  924. * keypair for the current time period and put it in blinded_kp_out. This is
  925. * only useful by the service side because the client doesn't have access to
  926. * the identity secret key. */
  927. void
  928. hs_build_blinded_keypair(const ed25519_keypair_t *kp,
  929. const uint8_t *secret, size_t secret_len,
  930. uint64_t time_period_num,
  931. ed25519_keypair_t *blinded_kp_out)
  932. {
  933. /* Our blinding key API requires a 32 bytes parameter. */
  934. uint8_t param[DIGEST256_LEN];
  935. tor_assert(kp);
  936. tor_assert(blinded_kp_out);
  937. /* Extra safety. A zeroed key is bad. */
  938. tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
  939. tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
  940. build_blinded_key_param(&kp->pubkey, secret, secret_len,
  941. time_period_num, get_time_period_length(), param);
  942. ed25519_keypair_blind(blinded_kp_out, kp, param);
  943. memwipe(param, 0, sizeof(param));
  944. }
  945. /* Return true if we are currently in the time segment between a new time
  946. * period and a new SRV (in the real network that happens between 12:00 and
  947. * 00:00 UTC). Here is a diagram showing exactly when this returns true:
  948. *
  949. * +------------------------------------------------------------------+
  950. * | |
  951. * | 00:00 12:00 00:00 12:00 00:00 12:00 |
  952. * | SRV#1 TP#1 SRV#2 TP#2 SRV#3 TP#3 |
  953. * | |
  954. * | $==========|-----------$===========|-----------$===========| |
  955. * | ^^^^^^^^^^^^ ^^^^^^^^^^^^ |
  956. * | |
  957. * +------------------------------------------------------------------+
  958. */
  959. MOCK_IMPL(int,
  960. hs_in_period_between_tp_and_srv,(const networkstatus_t *consensus, time_t now))
  961. {
  962. time_t valid_after;
  963. time_t srv_start_time, tp_start_time;
  964. if (!consensus) {
  965. consensus = networkstatus_get_live_consensus(now);
  966. if (!consensus) {
  967. return 0;
  968. }
  969. }
  970. /* Get start time of next TP and of current SRV protocol run, and check if we
  971. * are between them. */
  972. valid_after = consensus->valid_after;
  973. srv_start_time = sr_state_get_start_time_of_current_protocol_run();
  974. tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
  975. if (valid_after >= srv_start_time && valid_after < tp_start_time) {
  976. return 0;
  977. }
  978. return 1;
  979. }
  980. /* Return 1 if any virtual port in ports needs a circuit with good uptime.
  981. * Else return 0. */
  982. int
  983. hs_service_requires_uptime_circ(const smartlist_t *ports)
  984. {
  985. tor_assert(ports);
  986. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  987. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  988. p->virtual_port)) {
  989. return 1;
  990. }
  991. } SMARTLIST_FOREACH_END(p);
  992. return 0;
  993. }
  994. /* Build hs_index which is used to find the responsible hsdirs. This index
  995. * value is used to select the responsible HSDir where their hsdir_index is
  996. * closest to this value.
  997. * SHA3-256("store-at-idx" | blinded_public_key |
  998. * INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
  999. *
  1000. * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
  1001. void
  1002. hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
  1003. uint64_t period_num, uint8_t *hs_index_out)
  1004. {
  1005. crypto_digest_t *digest;
  1006. tor_assert(blinded_pk);
  1007. tor_assert(hs_index_out);
  1008. /* Build hs_index. See construction at top of function comment. */
  1009. digest = crypto_digest256_new(DIGEST_SHA3_256);
  1010. crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
  1011. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  1012. ED25519_PUBKEY_LEN);
  1013. /* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
  1014. {
  1015. uint64_t period_length = get_time_period_length();
  1016. char buf[sizeof(uint64_t)*3];
  1017. size_t offset = 0;
  1018. set_uint64(buf, tor_htonll(replica));
  1019. offset += sizeof(uint64_t);
  1020. set_uint64(buf+offset, tor_htonll(period_length));
  1021. offset += sizeof(uint64_t);
  1022. set_uint64(buf+offset, tor_htonll(period_num));
  1023. offset += sizeof(uint64_t);
  1024. tor_assert(offset == sizeof(buf));
  1025. crypto_digest_add_bytes(digest, buf, sizeof(buf));
  1026. }
  1027. crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
  1028. crypto_digest_free(digest);
  1029. }
  1030. /* Build hsdir_index which is used to find the responsible hsdirs. This is the
  1031. * index value that is compare to the hs_index when selecting an HSDir.
  1032. * SHA3-256("node-idx" | node_identity |
  1033. * shared_random_value | INT_8(period_length) | INT_8(period_num) )
  1034. *
  1035. * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
  1036. void
  1037. hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
  1038. const uint8_t *srv_value, uint64_t period_num,
  1039. uint8_t *hsdir_index_out)
  1040. {
  1041. crypto_digest_t *digest;
  1042. tor_assert(identity_pk);
  1043. tor_assert(srv_value);
  1044. tor_assert(hsdir_index_out);
  1045. /* Build hsdir_index. See construction at top of function comment. */
  1046. digest = crypto_digest256_new(DIGEST_SHA3_256);
  1047. crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
  1048. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  1049. ED25519_PUBKEY_LEN);
  1050. crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
  1051. {
  1052. uint64_t time_period_length = get_time_period_length();
  1053. char period_stuff[sizeof(uint64_t)*2];
  1054. size_t offset = 0;
  1055. set_uint64(period_stuff, tor_htonll(period_num));
  1056. offset += sizeof(uint64_t);
  1057. set_uint64(period_stuff+offset, tor_htonll(time_period_length));
  1058. offset += sizeof(uint64_t);
  1059. tor_assert(offset == sizeof(period_stuff));
  1060. crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
  1061. }
  1062. crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
  1063. crypto_digest_free(digest);
  1064. }
  1065. /* Return a newly allocated buffer containing the current shared random value
  1066. * or if not present, a disaster value is computed using the given time period
  1067. * number. If a consensus is provided in <b>ns</b>, use it to get the SRV
  1068. * value. This function can't fail. */
  1069. uint8_t *
  1070. hs_get_current_srv(uint64_t time_period_num, const networkstatus_t *ns)
  1071. {
  1072. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  1073. const sr_srv_t *current_srv = sr_get_current(ns);
  1074. if (current_srv) {
  1075. memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
  1076. } else {
  1077. /* Disaster mode. */
  1078. get_disaster_srv(time_period_num, sr_value);
  1079. }
  1080. return sr_value;
  1081. }
  1082. /* Return a newly allocated buffer containing the previous shared random
  1083. * value or if not present, a disaster value is computed using the given time
  1084. * period number. This function can't fail. */
  1085. uint8_t *
  1086. hs_get_previous_srv(uint64_t time_period_num, const networkstatus_t *ns)
  1087. {
  1088. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  1089. const sr_srv_t *previous_srv = sr_get_previous(ns);
  1090. if (previous_srv) {
  1091. memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
  1092. } else {
  1093. /* Disaster mode. */
  1094. get_disaster_srv(time_period_num, sr_value);
  1095. }
  1096. return sr_value;
  1097. }
  1098. /* Return the number of replicas defined by a consensus parameter or the
  1099. * default value. */
  1100. int32_t
  1101. hs_get_hsdir_n_replicas(void)
  1102. {
  1103. /* The [1,16] range is a specification requirement. */
  1104. return networkstatus_get_param(NULL, "hsdir_n_replicas",
  1105. HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
  1106. }
  1107. /* Return the spread fetch value defined by a consensus parameter or the
  1108. * default value. */
  1109. int32_t
  1110. hs_get_hsdir_spread_fetch(void)
  1111. {
  1112. /* The [1,128] range is a specification requirement. */
  1113. return networkstatus_get_param(NULL, "hsdir_spread_fetch",
  1114. HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
  1115. }
  1116. /* Return the spread store value defined by a consensus parameter or the
  1117. * default value. */
  1118. int32_t
  1119. hs_get_hsdir_spread_store(void)
  1120. {
  1121. /* The [1,128] range is a specification requirement. */
  1122. return networkstatus_get_param(NULL, "hsdir_spread_store",
  1123. HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
  1124. }
  1125. /** <b>node</b> is an HSDir so make sure that we have assigned an hsdir index.
  1126. * Return 0 if everything is as expected, else return -1. */
  1127. static int
  1128. node_has_hsdir_index(const node_t *node)
  1129. {
  1130. tor_assert(node_supports_v3_hsdir(node));
  1131. /* A node can't have an HSDir index without a descriptor since we need desc
  1132. * to get its ed25519 key. for_direct_connect should be zero, since we
  1133. * always use the consensus-indexed node's keys to build the hash ring, even
  1134. * if some of the consensus-indexed nodes are also bridges. */
  1135. if (!node_has_preferred_descriptor(node, 0)) {
  1136. return 0;
  1137. }
  1138. /* At this point, since the node has a desc, this node must also have an
  1139. * hsdir index. If not, something went wrong, so BUG out. */
  1140. if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.fetch,
  1141. DIGEST256_LEN))) {
  1142. return 0;
  1143. }
  1144. if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.store_first,
  1145. DIGEST256_LEN))) {
  1146. return 0;
  1147. }
  1148. if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.store_second,
  1149. DIGEST256_LEN))) {
  1150. return 0;
  1151. }
  1152. return 1;
  1153. }
  1154. /* For a given blinded key and time period number, get the responsible HSDir
  1155. * and put their routerstatus_t object in the responsible_dirs list. If
  1156. * 'use_second_hsdir_index' is true, use the second hsdir_index of the node_t
  1157. * is used. If 'for_fetching' is true, the spread fetch consensus parameter is
  1158. * used else the spread store is used which is only for upload. This function
  1159. * can't fail but it is possible that the responsible_dirs list contains fewer
  1160. * nodes than expected.
  1161. *
  1162. * This function goes over the latest consensus routerstatus list and sorts it
  1163. * by their node_t hsdir_index then does a binary search to find the closest
  1164. * node. All of this makes it a bit CPU intensive so use it wisely. */
  1165. void
  1166. hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
  1167. uint64_t time_period_num, int use_second_hsdir_index,
  1168. int for_fetching, smartlist_t *responsible_dirs)
  1169. {
  1170. smartlist_t *sorted_nodes;
  1171. /* The compare function used for the smartlist bsearch. We have two
  1172. * different depending on is_next_period. */
  1173. int (*cmp_fct)(const void *, const void **);
  1174. tor_assert(blinded_pk);
  1175. tor_assert(responsible_dirs);
  1176. sorted_nodes = smartlist_new();
  1177. /* Make sure we actually have a live consensus */
  1178. networkstatus_t *c = networkstatus_get_live_consensus(approx_time());
  1179. if (!c || smartlist_len(c->routerstatus_list) == 0) {
  1180. log_warn(LD_REND, "No live consensus so we can't get the responsible "
  1181. "hidden service directories.");
  1182. goto done;
  1183. }
  1184. /* Ensure the nodelist is fresh, since it contains the HSDir indices. */
  1185. nodelist_ensure_freshness(c);
  1186. /* Add every node_t that support HSDir v3 for which we do have a valid
  1187. * hsdir_index already computed for them for this consensus. */
  1188. {
  1189. SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
  1190. /* Even though this node_t object won't be modified and should be const,
  1191. * we can't add const object in a smartlist_t. */
  1192. node_t *n = node_get_mutable_by_id(rs->identity_digest);
  1193. tor_assert(n);
  1194. if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
  1195. if (!node_has_hsdir_index(n)) {
  1196. log_info(LD_GENERAL, "Node %s was found without hsdir index.",
  1197. node_describe(n));
  1198. continue;
  1199. }
  1200. smartlist_add(sorted_nodes, n);
  1201. }
  1202. } SMARTLIST_FOREACH_END(rs);
  1203. }
  1204. if (smartlist_len(sorted_nodes) == 0) {
  1205. log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
  1206. goto done;
  1207. }
  1208. /* First thing we have to do is sort all node_t by hsdir_index. The
  1209. * is_next_period tells us if we want the current or the next one. Set the
  1210. * bsearch compare function also while we are at it. */
  1211. if (for_fetching) {
  1212. smartlist_sort(sorted_nodes, compare_node_fetch_hsdir_index);
  1213. cmp_fct = compare_digest_to_fetch_hsdir_index;
  1214. } else if (use_second_hsdir_index) {
  1215. smartlist_sort(sorted_nodes, compare_node_store_second_hsdir_index);
  1216. cmp_fct = compare_digest_to_store_second_hsdir_index;
  1217. } else {
  1218. smartlist_sort(sorted_nodes, compare_node_store_first_hsdir_index);
  1219. cmp_fct = compare_digest_to_store_first_hsdir_index;
  1220. }
  1221. /* For all replicas, we'll select a set of HSDirs using the consensus
  1222. * parameters and the sorted list. The replica starting at value 1 is
  1223. * defined by the specification. */
  1224. for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
  1225. int idx, start, found, n_added = 0;
  1226. uint8_t hs_index[DIGEST256_LEN] = {0};
  1227. /* Number of node to add to the responsible dirs list depends on if we are
  1228. * trying to fetch or store. A client always fetches. */
  1229. int n_to_add = (for_fetching) ? hs_get_hsdir_spread_fetch() :
  1230. hs_get_hsdir_spread_store();
  1231. /* Get the index that we should use to select the node. */
  1232. hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
  1233. /* The compare function pointer has been set correctly earlier. */
  1234. start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
  1235. &found);
  1236. /* Getting the length of the list if no member is greater than the key we
  1237. * are looking for so start at the first element. */
  1238. if (idx == smartlist_len(sorted_nodes)) {
  1239. start = idx = 0;
  1240. }
  1241. while (n_added < n_to_add) {
  1242. const node_t *node = smartlist_get(sorted_nodes, idx);
  1243. /* If the node has already been selected which is possible between
  1244. * replicas, the specification says to skip over. */
  1245. if (!smartlist_contains(responsible_dirs, node->rs)) {
  1246. smartlist_add(responsible_dirs, node->rs);
  1247. ++n_added;
  1248. }
  1249. if (++idx == smartlist_len(sorted_nodes)) {
  1250. /* Wrap if we've reached the end of the list. */
  1251. idx = 0;
  1252. }
  1253. if (idx == start) {
  1254. /* We've gone over the whole list, stop and avoid infinite loop. */
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. done:
  1260. smartlist_free(sorted_nodes);
  1261. }
  1262. /*********************** HSDir request tracking ***************************/
  1263. /** Return the period for which a hidden service directory cannot be queried
  1264. * for the same descriptor ID again, taking TestingTorNetwork into account. */
  1265. time_t
  1266. hs_hsdir_requery_period(const or_options_t *options)
  1267. {
  1268. tor_assert(options);
  1269. if (options->TestingTorNetwork) {
  1270. return REND_HID_SERV_DIR_REQUERY_PERIOD_TESTING;
  1271. } else {
  1272. return REND_HID_SERV_DIR_REQUERY_PERIOD;
  1273. }
  1274. }
  1275. /** Tracks requests for fetching hidden service descriptors. It's used by
  1276. * hidden service clients, to avoid querying HSDirs that have already failed
  1277. * giving back a descriptor. The same data structure is used to track both v2
  1278. * and v3 HS descriptor requests.
  1279. *
  1280. * The string map is a key/value store that contains the last request times to
  1281. * hidden service directories for certain queries. Specifically:
  1282. *
  1283. * key = base32(hsdir_identity) + base32(hs_identity)
  1284. * value = time_t of last request for that hs_identity to that HSDir
  1285. *
  1286. * where 'hsdir_identity' is the identity digest of the HSDir node, and
  1287. * 'hs_identity' is the descriptor ID of the HS in the v2 case, or the ed25519
  1288. * blinded public key of the HS in the v3 case. */
  1289. static strmap_t *last_hid_serv_requests_ = NULL;
  1290. /** Returns last_hid_serv_requests_, initializing it to a new strmap if
  1291. * necessary. */
  1292. STATIC strmap_t *
  1293. get_last_hid_serv_requests(void)
  1294. {
  1295. if (!last_hid_serv_requests_)
  1296. last_hid_serv_requests_ = strmap_new();
  1297. return last_hid_serv_requests_;
  1298. }
  1299. /** Look up the last request time to hidden service directory <b>hs_dir</b>
  1300. * for descriptor request key <b>req_key_str</b> which is the descriptor ID
  1301. * for a v2 service or the blinded key for v3. If <b>set</b> is non-zero,
  1302. * assign the current time <b>now</b> and return that. Otherwise, return the
  1303. * most recent request time, or 0 if no such request has been sent before. */
  1304. time_t
  1305. hs_lookup_last_hid_serv_request(routerstatus_t *hs_dir,
  1306. const char *req_key_str,
  1307. time_t now, int set)
  1308. {
  1309. char hsdir_id_base32[BASE32_DIGEST_LEN + 1];
  1310. char *hsdir_desc_comb_id = NULL;
  1311. time_t *last_request_ptr;
  1312. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  1313. /* Create the key */
  1314. base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
  1315. hs_dir->identity_digest, DIGEST_LEN);
  1316. tor_asprintf(&hsdir_desc_comb_id, "%s%s", hsdir_id_base32, req_key_str);
  1317. if (set) {
  1318. time_t *oldptr;
  1319. last_request_ptr = tor_malloc_zero(sizeof(time_t));
  1320. *last_request_ptr = now;
  1321. oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
  1322. last_request_ptr);
  1323. tor_free(oldptr);
  1324. } else {
  1325. last_request_ptr = strmap_get(last_hid_serv_requests,
  1326. hsdir_desc_comb_id);
  1327. }
  1328. tor_free(hsdir_desc_comb_id);
  1329. return (last_request_ptr) ? *last_request_ptr : 0;
  1330. }
  1331. /** Clean the history of request times to hidden service directories, so that
  1332. * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
  1333. * seconds any more. */
  1334. void
  1335. hs_clean_last_hid_serv_requests(time_t now)
  1336. {
  1337. strmap_iter_t *iter;
  1338. time_t cutoff = now - hs_hsdir_requery_period(get_options());
  1339. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  1340. for (iter = strmap_iter_init(last_hid_serv_requests);
  1341. !strmap_iter_done(iter); ) {
  1342. const char *key;
  1343. void *val;
  1344. time_t *ent;
  1345. strmap_iter_get(iter, &key, &val);
  1346. ent = (time_t *) val;
  1347. if (*ent < cutoff) {
  1348. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  1349. tor_free(ent);
  1350. } else {
  1351. iter = strmap_iter_next(last_hid_serv_requests, iter);
  1352. }
  1353. }
  1354. }
  1355. /** Remove all requests related to the descriptor request key string
  1356. * <b>req_key_str</b> from the history of times of requests to hidden service
  1357. * directories.
  1358. *
  1359. * This is called from rend_client_note_connection_attempt_ended(), which
  1360. * must be idempotent, so any future changes to this function must leave it
  1361. * idempotent too. */
  1362. void
  1363. hs_purge_hid_serv_from_last_hid_serv_requests(const char *req_key_str)
  1364. {
  1365. strmap_iter_t *iter;
  1366. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  1367. for (iter = strmap_iter_init(last_hid_serv_requests);
  1368. !strmap_iter_done(iter); ) {
  1369. const char *key;
  1370. void *val;
  1371. strmap_iter_get(iter, &key, &val);
  1372. /* XXX: The use of REND_DESC_ID_V2_LEN_BASE32 is very wrong in terms of
  1373. * semantic, see #23305. */
  1374. /* This strmap contains variable-sized elements so this is a basic length
  1375. * check on the strings we are about to compare. The key is variable sized
  1376. * since it's composed as follows:
  1377. * key = base32(hsdir_identity) + base32(req_key_str)
  1378. * where 'req_key_str' is the descriptor ID of the HS in the v2 case, or
  1379. * the ed25519 blinded public key of the HS in the v3 case. */
  1380. if (strlen(key) < REND_DESC_ID_V2_LEN_BASE32 + strlen(req_key_str)) {
  1381. iter = strmap_iter_next(last_hid_serv_requests, iter);
  1382. continue;
  1383. }
  1384. /* Check if the tracked request matches our request key */
  1385. if (tor_memeq(key + REND_DESC_ID_V2_LEN_BASE32, req_key_str,
  1386. strlen(req_key_str))) {
  1387. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  1388. tor_free(val);
  1389. } else {
  1390. iter = strmap_iter_next(last_hid_serv_requests, iter);
  1391. }
  1392. }
  1393. }
  1394. /** Purge the history of request times to hidden service directories,
  1395. * so that future lookups of an HS descriptor will not fail because we
  1396. * accessed all of the HSDir relays responsible for the descriptor
  1397. * recently. */
  1398. void
  1399. hs_purge_last_hid_serv_requests(void)
  1400. {
  1401. /* Don't create the table if it doesn't exist yet (and it may very
  1402. * well not exist if the user hasn't accessed any HSes)... */
  1403. strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
  1404. /* ... and let get_last_hid_serv_requests re-create it for us if
  1405. * necessary. */
  1406. last_hid_serv_requests_ = NULL;
  1407. if (old_last_hid_serv_requests != NULL) {
  1408. log_info(LD_REND, "Purging client last-HS-desc-request-time table");
  1409. strmap_free(old_last_hid_serv_requests, tor_free_);
  1410. }
  1411. }
  1412. /***********************************************************************/
  1413. /** Given the list of responsible HSDirs in <b>responsible_dirs</b>, pick the
  1414. * one that we should use to fetch a descriptor right now. Take into account
  1415. * previous failed attempts at fetching this descriptor from HSDirs using the
  1416. * string identifier <b>req_key_str</b>.
  1417. *
  1418. * Steals ownership of <b>responsible_dirs</b>.
  1419. *
  1420. * Return the routerstatus of the chosen HSDir if successful, otherwise return
  1421. * NULL if no HSDirs are worth trying right now. */
  1422. routerstatus_t *
  1423. hs_pick_hsdir(smartlist_t *responsible_dirs, const char *req_key_str)
  1424. {
  1425. smartlist_t *usable_responsible_dirs = smartlist_new();
  1426. const or_options_t *options = get_options();
  1427. routerstatus_t *hs_dir;
  1428. time_t now = time(NULL);
  1429. int excluded_some;
  1430. tor_assert(req_key_str);
  1431. /* Clean outdated request history first. */
  1432. hs_clean_last_hid_serv_requests(now);
  1433. /* Only select those hidden service directories to which we did not send a
  1434. * request recently and for which we have a router descriptor here.
  1435. *
  1436. * Use for_direct_connect==0 even if we will be connecting to the node
  1437. * directly, since we always use the key information in the
  1438. * consensus-indexed node descriptors for building the index.
  1439. **/
  1440. SMARTLIST_FOREACH_BEGIN(responsible_dirs, routerstatus_t *, dir) {
  1441. time_t last = hs_lookup_last_hid_serv_request(dir, req_key_str, 0, 0);
  1442. const node_t *node = node_get_by_id(dir->identity_digest);
  1443. if (last + hs_hsdir_requery_period(options) >= now ||
  1444. !node || !node_has_preferred_descriptor(node, 0)) {
  1445. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  1446. continue;
  1447. }
  1448. if (!routerset_contains_node(options->ExcludeNodes, node)) {
  1449. smartlist_add(usable_responsible_dirs, dir);
  1450. }
  1451. } SMARTLIST_FOREACH_END(dir);
  1452. excluded_some =
  1453. smartlist_len(usable_responsible_dirs) < smartlist_len(responsible_dirs);
  1454. hs_dir = smartlist_choose(usable_responsible_dirs);
  1455. if (!hs_dir && !options->StrictNodes) {
  1456. hs_dir = smartlist_choose(responsible_dirs);
  1457. }
  1458. smartlist_free(responsible_dirs);
  1459. smartlist_free(usable_responsible_dirs);
  1460. if (!hs_dir) {
  1461. log_info(LD_REND, "Could not pick one of the responsible hidden "
  1462. "service directories, because we requested them all "
  1463. "recently without success.");
  1464. if (options->StrictNodes && excluded_some) {
  1465. log_warn(LD_REND, "Could not pick a hidden service directory for the "
  1466. "requested hidden service: they are all either down or "
  1467. "excluded, and StrictNodes is set.");
  1468. }
  1469. } else {
  1470. /* Remember that we are requesting a descriptor from this hidden service
  1471. * directory now. */
  1472. hs_lookup_last_hid_serv_request(hs_dir, req_key_str, now, 1);
  1473. }
  1474. return hs_dir;
  1475. }
  1476. /* From a list of link specifier, an onion key and if we are requesting a
  1477. * direct connection (ex: single onion service), return a newly allocated
  1478. * extend_info_t object. This function always returns an extend info with
  1479. * an IPv4 address, or NULL.
  1480. *
  1481. * It performs the following checks:
  1482. * if either IPv4 or legacy ID is missing, return NULL.
  1483. * if direct_conn, and we can't reach the IPv4 address, return NULL.
  1484. */
  1485. extend_info_t *
  1486. hs_get_extend_info_from_lspecs(const smartlist_t *lspecs,
  1487. const curve25519_public_key_t *onion_key,
  1488. int direct_conn)
  1489. {
  1490. int have_v4 = 0, have_legacy_id = 0, have_ed25519_id = 0;
  1491. char legacy_id[DIGEST_LEN] = {0};
  1492. uint16_t port_v4 = 0;
  1493. tor_addr_t addr_v4;
  1494. ed25519_public_key_t ed25519_pk;
  1495. extend_info_t *info = NULL;
  1496. tor_assert(lspecs);
  1497. SMARTLIST_FOREACH_BEGIN(lspecs, const link_specifier_t *, ls) {
  1498. switch (link_specifier_get_ls_type(ls)) {
  1499. case LS_IPV4:
  1500. /* Skip if we already seen a v4. */
  1501. if (have_v4) continue;
  1502. tor_addr_from_ipv4h(&addr_v4,
  1503. link_specifier_get_un_ipv4_addr(ls));
  1504. port_v4 = link_specifier_get_un_ipv4_port(ls);
  1505. have_v4 = 1;
  1506. break;
  1507. case LS_LEGACY_ID:
  1508. /* Make sure we do have enough bytes for the legacy ID. */
  1509. if (link_specifier_getlen_un_legacy_id(ls) < sizeof(legacy_id)) {
  1510. break;
  1511. }
  1512. memcpy(legacy_id, link_specifier_getconstarray_un_legacy_id(ls),
  1513. sizeof(legacy_id));
  1514. have_legacy_id = 1;
  1515. break;
  1516. case LS_ED25519_ID:
  1517. memcpy(ed25519_pk.pubkey,
  1518. link_specifier_getconstarray_un_ed25519_id(ls),
  1519. ED25519_PUBKEY_LEN);
  1520. have_ed25519_id = 1;
  1521. break;
  1522. default:
  1523. /* Ignore unknown. */
  1524. break;
  1525. }
  1526. } SMARTLIST_FOREACH_END(ls);
  1527. /* Legacy ID is mandatory, and we require IPv4. */
  1528. if (!have_v4 || !have_legacy_id) {
  1529. goto done;
  1530. }
  1531. /* We know we have IPv4, because we just checked. */
  1532. if (!direct_conn) {
  1533. /* All clients can extend to any IPv4 via a 3-hop path. */
  1534. goto validate;
  1535. } else if (direct_conn &&
  1536. fascist_firewall_allows_address_addr(&addr_v4, port_v4,
  1537. FIREWALL_OR_CONNECTION,
  1538. 0, 0)) {
  1539. /* Direct connection and we can reach it in IPv4 so go for it. */
  1540. goto validate;
  1541. /* We will add support for falling back to a 3-hop path in a later
  1542. * release. */
  1543. } else {
  1544. /* If we can't reach IPv4, return NULL. */
  1545. goto done;
  1546. }
  1547. /* We will add support for IPv6 in a later release. */
  1548. validate:
  1549. /* We'll validate now that the address we've picked isn't a private one. If
  1550. * it is, are we allowing to extend to private address? */
  1551. if (!extend_info_addr_is_allowed(&addr_v4)) {
  1552. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  1553. "Requested address is private and we are not allowed to extend to "
  1554. "it: %s:%u", fmt_addr(&addr_v4), port_v4);
  1555. goto done;
  1556. }
  1557. /* We do have everything for which we think we can connect successfully. */
  1558. info = extend_info_new(NULL, legacy_id,
  1559. (have_ed25519_id) ? &ed25519_pk : NULL, NULL,
  1560. onion_key, &addr_v4, port_v4);
  1561. done:
  1562. return info;
  1563. }
  1564. /***********************************************************************/
  1565. /* Initialize the entire HS subsytem. This is called in tor_init() before any
  1566. * torrc options are loaded. Only for >= v3. */
  1567. void
  1568. hs_init(void)
  1569. {
  1570. hs_circuitmap_init();
  1571. hs_service_init();
  1572. hs_cache_init();
  1573. hs_client_pir_init();
  1574. }
  1575. /* Release and cleanup all memory of the HS subsystem (all version). This is
  1576. * called by tor_free_all(). */
  1577. void
  1578. hs_free_all(void)
  1579. {
  1580. hs_circuitmap_free_all();
  1581. hs_service_free_all();
  1582. hs_cache_free_all();
  1583. hs_client_free_all();
  1584. }
  1585. /* For the given origin circuit circ, decrement the number of rendezvous
  1586. * stream counter. This handles every hidden service version. */
  1587. void
  1588. hs_dec_rdv_stream_counter(origin_circuit_t *circ)
  1589. {
  1590. tor_assert(circ);
  1591. if (circ->rend_data) {
  1592. circ->rend_data->nr_streams--;
  1593. } else if (circ->hs_ident) {
  1594. circ->hs_ident->num_rdv_streams--;
  1595. } else {
  1596. /* Should not be called if this circuit is not for hidden service. */
  1597. tor_assert_nonfatal_unreached();
  1598. }
  1599. }
  1600. /* For the given origin circuit circ, increment the number of rendezvous
  1601. * stream counter. This handles every hidden service version. */
  1602. void
  1603. hs_inc_rdv_stream_counter(origin_circuit_t *circ)
  1604. {
  1605. tor_assert(circ);
  1606. if (circ->rend_data) {
  1607. circ->rend_data->nr_streams++;
  1608. } else if (circ->hs_ident) {
  1609. circ->hs_ident->num_rdv_streams++;
  1610. } else {
  1611. /* Should not be called if this circuit is not for hidden service. */
  1612. tor_assert_nonfatal_unreached();
  1613. }
  1614. }