hs_common.c 61 KB

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