hs_common.c 61 KB

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