hs_common.c 54 KB

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