hs_common.c 59 KB

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