hs_common.c 61 KB

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