hs_common.c 62 KB

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