hs_common.c 54 KB

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