hs_common.c 58 KB

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