hs_common.c 61 KB

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