hs_common.c 61 KB

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