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