hs_common.c 61 KB

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