hs_common.c 61 KB

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