hs_common.c 63 KB

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