hs_common.c 58 KB

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