hs_common.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 "shared_random.h"
  22. /* Ed25519 Basepoint value. Taken from section 5 of
  23. * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
  24. static const char *str_ed25519_basepoint =
  25. "(15112221349535400772501151409588531511"
  26. "454012693041857206046113283949847762202, "
  27. "463168356949264781694283940034751631413"
  28. "07993866256225615783033603165251855960)";
  29. /* Helper function: The key is a digest that we compare to a node_t object
  30. * current hsdir_index. */
  31. static int
  32. compare_digest_to_current_hsdir_index(const void *_key, const void **_member)
  33. {
  34. const char *key = _key;
  35. const node_t *node = *_member;
  36. return tor_memcmp(key, node->hsdir_index->current, DIGEST256_LEN);
  37. }
  38. /* Helper function: The key is a digest that we compare to a node_t object
  39. * next hsdir_index. */
  40. static int
  41. compare_digest_to_next_hsdir_index(const void *_key, const void **_member)
  42. {
  43. const char *key = _key;
  44. const node_t *node = *_member;
  45. return tor_memcmp(key, node->hsdir_index->next, DIGEST256_LEN);
  46. }
  47. /* Helper function: Compare two node_t objects current hsdir_index. */
  48. static int
  49. compare_node_current_hsdir_index(const void **a, const void **b)
  50. {
  51. const node_t *node1= *a;
  52. const node_t *node2 = *b;
  53. return tor_memcmp(node1->hsdir_index->current,
  54. node2->hsdir_index->current,
  55. DIGEST256_LEN);
  56. }
  57. /* Helper function: Compare two node_t objects next hsdir_index. */
  58. static int
  59. compare_node_next_hsdir_index(const void **a, const void **b)
  60. {
  61. const node_t *node1= *a;
  62. const node_t *node2 = *b;
  63. return tor_memcmp(node1->hsdir_index->next,
  64. node2->hsdir_index->next,
  65. DIGEST256_LEN);
  66. }
  67. /* Allocate and return a string containing the path to filename in directory.
  68. * This function will never return NULL. The caller must free this path. */
  69. char *
  70. hs_path_from_filename(const char *directory, const char *filename)
  71. {
  72. char *file_path = NULL;
  73. tor_assert(directory);
  74. tor_assert(filename);
  75. tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
  76. return file_path;
  77. }
  78. /* Make sure that the directory for <b>service</b> is private, using the config
  79. * <b>username</b>.
  80. * If <b>create</b> is true:
  81. * - if the directory exists, change permissions if needed,
  82. * - if the directory does not exist, create it with the correct permissions.
  83. * If <b>create</b> is false:
  84. * - if the directory exists, check permissions,
  85. * - if the directory does not exist, check if we think we can create it.
  86. * Return 0 on success, -1 on failure. */
  87. int
  88. hs_check_service_private_dir(const char *username, const char *path,
  89. unsigned int dir_group_readable,
  90. unsigned int create)
  91. {
  92. cpd_check_t check_opts = CPD_NONE;
  93. tor_assert(path);
  94. if (create) {
  95. check_opts |= CPD_CREATE;
  96. } else {
  97. check_opts |= CPD_CHECK_MODE_ONLY;
  98. check_opts |= CPD_CHECK;
  99. }
  100. if (dir_group_readable) {
  101. check_opts |= CPD_GROUP_READ;
  102. }
  103. /* Check/create directory */
  104. if (check_private_dir(path, check_opts, username) < 0) {
  105. return -1;
  106. }
  107. return 0;
  108. }
  109. /** Get the default HS time period length in minutes from the consensus. */
  110. STATIC uint64_t
  111. get_time_period_length(void)
  112. {
  113. int32_t time_period_length = networkstatus_get_param(NULL, "hsdir-interval",
  114. HS_TIME_PERIOD_LENGTH_DEFAULT,
  115. HS_TIME_PERIOD_LENGTH_MIN,
  116. HS_TIME_PERIOD_LENGTH_MAX);
  117. /* Make sure it's a positive value. */
  118. tor_assert(time_period_length >= 0);
  119. /* uint64_t will always be able to contain a int32_t */
  120. return (uint64_t) time_period_length;
  121. }
  122. /** Get the HS time period number at time <b>now</b> */
  123. uint64_t
  124. hs_get_time_period_num(time_t now)
  125. {
  126. uint64_t time_period_num;
  127. uint64_t time_period_length = get_time_period_length();
  128. uint64_t minutes_since_epoch = now / 60;
  129. /* Now subtract half a day to fit the prop224 time period schedule (see
  130. * section [TIME-PERIODS]). */
  131. tor_assert(minutes_since_epoch > HS_TIME_PERIOD_ROTATION_OFFSET);
  132. minutes_since_epoch -= HS_TIME_PERIOD_ROTATION_OFFSET;
  133. /* Calculate the time period */
  134. time_period_num = minutes_since_epoch / time_period_length;
  135. return time_period_num;
  136. }
  137. /** Get the number of the _upcoming_ HS time period, given that the current
  138. * time is <b>now</b>. */
  139. uint64_t
  140. hs_get_next_time_period_num(time_t now)
  141. {
  142. return hs_get_time_period_num(now) + 1;
  143. }
  144. /* Create a new rend_data_t for a specific given <b>version</b>.
  145. * Return a pointer to the newly allocated data structure. */
  146. static rend_data_t *
  147. rend_data_alloc(uint32_t version)
  148. {
  149. rend_data_t *rend_data = NULL;
  150. switch (version) {
  151. case HS_VERSION_TWO:
  152. {
  153. rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
  154. v2->base_.version = HS_VERSION_TWO;
  155. v2->base_.hsdirs_fp = smartlist_new();
  156. rend_data = &v2->base_;
  157. break;
  158. }
  159. default:
  160. tor_assert(0);
  161. break;
  162. }
  163. return rend_data;
  164. }
  165. /** Free all storage associated with <b>data</b> */
  166. void
  167. rend_data_free(rend_data_t *data)
  168. {
  169. if (!data) {
  170. return;
  171. }
  172. /* By using our allocation function, this should always be set. */
  173. tor_assert(data->hsdirs_fp);
  174. /* Cleanup the HSDir identity digest. */
  175. SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
  176. smartlist_free(data->hsdirs_fp);
  177. /* Depending on the version, cleanup. */
  178. switch (data->version) {
  179. case HS_VERSION_TWO:
  180. {
  181. rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
  182. tor_free(v2_data);
  183. break;
  184. }
  185. default:
  186. tor_assert(0);
  187. }
  188. }
  189. /* Allocate and return a deep copy of <b>data</b>. */
  190. rend_data_t *
  191. rend_data_dup(const rend_data_t *data)
  192. {
  193. rend_data_t *data_dup = NULL;
  194. smartlist_t *hsdirs_fp = smartlist_new();
  195. tor_assert(data);
  196. tor_assert(data->hsdirs_fp);
  197. SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
  198. smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
  199. switch (data->version) {
  200. case HS_VERSION_TWO:
  201. {
  202. rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
  203. sizeof(*v2_data));
  204. data_dup = &v2_data->base_;
  205. data_dup->hsdirs_fp = hsdirs_fp;
  206. break;
  207. }
  208. default:
  209. tor_assert(0);
  210. break;
  211. }
  212. return data_dup;
  213. }
  214. /* Compute the descriptor ID for each HS descriptor replica and save them. A
  215. * valid onion address must be present in the <b>rend_data</b>.
  216. *
  217. * Return 0 on success else -1. */
  218. static int
  219. compute_desc_id(rend_data_t *rend_data)
  220. {
  221. int ret = 0;
  222. unsigned replica;
  223. time_t now = time(NULL);
  224. tor_assert(rend_data);
  225. switch (rend_data->version) {
  226. case HS_VERSION_TWO:
  227. {
  228. rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  229. /* Compute descriptor ID for each replicas. */
  230. for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
  231. replica++) {
  232. ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
  233. v2_data->onion_address,
  234. v2_data->descriptor_cookie,
  235. now, replica);
  236. if (ret < 0) {
  237. goto end;
  238. }
  239. }
  240. break;
  241. }
  242. default:
  243. tor_assert(0);
  244. }
  245. end:
  246. return ret;
  247. }
  248. /* Allocate and initialize a rend_data_t object for a service using the
  249. * provided arguments. All arguments are optional (can be NULL), except from
  250. * <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
  251. * the service private key. The <b>cookie</b> is the rendezvous cookie and
  252. * <b>auth_type</b> is which authentiation this service is configured with.
  253. *
  254. * Return a valid rend_data_t pointer. This only returns a version 2 object of
  255. * rend_data_t. */
  256. rend_data_t *
  257. rend_data_service_create(const char *onion_address, const char *pk_digest,
  258. const uint8_t *cookie, rend_auth_type_t auth_type)
  259. {
  260. /* Create a rend_data_t object for version 2. */
  261. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  262. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  263. /* We need at least one else the call is wrong. */
  264. tor_assert(onion_address != NULL);
  265. if (pk_digest) {
  266. memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
  267. }
  268. if (cookie) {
  269. memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
  270. }
  271. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  272. v2->auth_type = auth_type;
  273. return rend_data;
  274. }
  275. /* Allocate and initialize a rend_data_t object for a client request using the
  276. * given arguments. Either an onion address or a descriptor ID is needed. Both
  277. * can be given but in this case only the onion address will be used to make
  278. * the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
  279. * <b>auth_type</b> is which authentiation the service is configured with.
  280. *
  281. * Return a valid rend_data_t pointer or NULL on error meaning the
  282. * descriptor IDs couldn't be computed from the given data. */
  283. rend_data_t *
  284. rend_data_client_create(const char *onion_address, const char *desc_id,
  285. const char *cookie, rend_auth_type_t auth_type)
  286. {
  287. /* Create a rend_data_t object for version 2. */
  288. rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
  289. rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
  290. /* We need at least one else the call is wrong. */
  291. tor_assert(onion_address != NULL || desc_id != NULL);
  292. if (cookie) {
  293. memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
  294. }
  295. if (desc_id) {
  296. memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
  297. }
  298. if (onion_address) {
  299. strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
  300. if (compute_desc_id(rend_data) < 0) {
  301. goto error;
  302. }
  303. }
  304. v2->auth_type = auth_type;
  305. return rend_data;
  306. error:
  307. rend_data_free(rend_data);
  308. return NULL;
  309. }
  310. /* Return the onion address from the rend data. Depending on the version,
  311. * the size of the address can vary but it's always NUL terminated. */
  312. const char *
  313. rend_data_get_address(const rend_data_t *rend_data)
  314. {
  315. tor_assert(rend_data);
  316. switch (rend_data->version) {
  317. case HS_VERSION_TWO:
  318. return TO_REND_DATA_V2(rend_data)->onion_address;
  319. default:
  320. /* We should always have a supported version. */
  321. tor_assert(0);
  322. }
  323. }
  324. /* Return the descriptor ID for a specific replica number from the rend
  325. * data. The returned data is a binary digest and depending on the version its
  326. * size can vary. The size of the descriptor ID is put in <b>len_out</b> if
  327. * non NULL. */
  328. const char *
  329. rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
  330. size_t *len_out)
  331. {
  332. tor_assert(rend_data);
  333. switch (rend_data->version) {
  334. case HS_VERSION_TWO:
  335. tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
  336. if (len_out) {
  337. *len_out = DIGEST_LEN;
  338. }
  339. return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
  340. default:
  341. /* We should always have a supported version. */
  342. tor_assert(0);
  343. }
  344. }
  345. /* Return the public key digest using the given <b>rend_data</b>. The size of
  346. * the digest is put in <b>len_out</b> (if set) which can differ depending on
  347. * the version. */
  348. const uint8_t *
  349. rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
  350. {
  351. tor_assert(rend_data);
  352. switch (rend_data->version) {
  353. case HS_VERSION_TWO:
  354. {
  355. const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
  356. if (len_out) {
  357. *len_out = sizeof(v2_data->rend_pk_digest);
  358. }
  359. return (const uint8_t *) v2_data->rend_pk_digest;
  360. }
  361. default:
  362. /* We should always have a supported version. */
  363. tor_assert(0);
  364. }
  365. }
  366. /* Using the given time period number, compute the disaster shared random
  367. * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
  368. static void
  369. get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
  370. {
  371. crypto_digest_t *digest;
  372. tor_assert(srv_out);
  373. digest = crypto_digest256_new(DIGEST_SHA3_256);
  374. /* Setup payload: H("shared-random-disaster" | INT_8(period_num)) */
  375. crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
  376. HS_SRV_DISASTER_PREFIX_LEN);
  377. crypto_digest_add_bytes(digest, (const char *) &time_period_num,
  378. sizeof(time_period_num));
  379. crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
  380. crypto_digest_free(digest);
  381. }
  382. /* When creating a blinded key, we need a parameter which construction is as
  383. * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
  384. *
  385. * The nonce has a pre-defined format which uses the time period number
  386. * period_num and the start of the period in second start_time_period.
  387. *
  388. * The secret of size secret_len is optional meaning that it can be NULL and
  389. * thus will be ignored for the param construction.
  390. *
  391. * The result is put in param_out. */
  392. static void
  393. build_blinded_key_param(const ed25519_public_key_t *pubkey,
  394. const uint8_t *secret, size_t secret_len,
  395. uint64_t period_num, uint64_t start_time_period,
  396. uint8_t *param_out)
  397. {
  398. size_t offset = 0;
  399. uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
  400. crypto_digest_t *digest;
  401. tor_assert(pubkey);
  402. tor_assert(param_out);
  403. /* Create the nonce N. The construction is as follow:
  404. * N = "key-blind" || INT_8(period_num) || INT_8(start_period_sec) */
  405. memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
  406. offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
  407. set_uint64(nonce + offset, period_num);
  408. offset += sizeof(uint64_t);
  409. set_uint64(nonce + offset, start_time_period);
  410. offset += sizeof(uint64_t);
  411. tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
  412. /* Generate the parameter h and the construction is as follow:
  413. * h = H(pubkey | [secret] | ed25519-basepoint | nonce) */
  414. digest = crypto_digest256_new(DIGEST_SHA3_256);
  415. crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
  416. /* Optional secret. */
  417. if (secret) {
  418. crypto_digest_add_bytes(digest, (char *) secret, secret_len);
  419. }
  420. crypto_digest_add_bytes(digest, str_ed25519_basepoint,
  421. strlen(str_ed25519_basepoint));
  422. crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
  423. /* Extract digest and put it in the param. */
  424. crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
  425. crypto_digest_free(digest);
  426. }
  427. /* Using an ed25519 public key and version to build the checksum of an
  428. * address. Put in checksum_out. Format is:
  429. * SHA3-256(".onion checksum" || PUBKEY || VERSION)
  430. *
  431. * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
  432. static void
  433. build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
  434. uint8_t *checksum_out)
  435. {
  436. size_t offset = 0;
  437. char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
  438. /* Build checksum data. */
  439. memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
  440. HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
  441. offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
  442. memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
  443. offset += ED25519_PUBKEY_LEN;
  444. set_uint8(data + offset, version);
  445. offset += sizeof(version);
  446. tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
  447. /* Hash the data payload to create the checksum. */
  448. crypto_digest256((char *) checksum_out, data, sizeof(data),
  449. DIGEST_SHA3_256);
  450. }
  451. /* Using an ed25519 public key, checksum and version to build the binary
  452. * representation of a service address. Put in addr_out. Format is:
  453. * addr_out = PUBKEY || CHECKSUM || VERSION
  454. *
  455. * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
  456. static void
  457. build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
  458. uint8_t version, char *addr_out)
  459. {
  460. size_t offset = 0;
  461. tor_assert(key);
  462. tor_assert(checksum);
  463. memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
  464. offset += ED25519_PUBKEY_LEN;
  465. memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  466. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  467. set_uint8(addr_out + offset, version);
  468. offset += sizeof(uint8_t);
  469. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  470. }
  471. /* Helper for hs_parse_address(): Using a binary representation of a service
  472. * address, parse its content into the key_out, checksum_out and version_out.
  473. * Any out variable can be NULL in case the caller would want only one field.
  474. * checksum_out MUST at least be 2 bytes long. address must be at least
  475. * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
  476. static void
  477. hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
  478. uint8_t *checksum_out, uint8_t *version_out)
  479. {
  480. size_t offset = 0;
  481. tor_assert(address);
  482. if (key_out) {
  483. /* First is the key. */
  484. memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
  485. }
  486. offset += ED25519_PUBKEY_LEN;
  487. if (checksum_out) {
  488. /* Followed by a 2 bytes checksum. */
  489. memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
  490. }
  491. offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
  492. if (version_out) {
  493. /* Finally, version value is 1 byte. */
  494. *version_out = get_uint8(address + offset);
  495. }
  496. offset += sizeof(uint8_t);
  497. /* Extra safety. */
  498. tor_assert(offset == HS_SERVICE_ADDR_LEN);
  499. }
  500. /* Using the given identity public key and a blinded public key, compute the
  501. * subcredential and put it in subcred_out. This can't fail. */
  502. void
  503. hs_get_subcredential(const ed25519_public_key_t *identity_pk,
  504. const ed25519_public_key_t *blinded_pk,
  505. uint8_t *subcred_out)
  506. {
  507. uint8_t credential[DIGEST256_LEN];
  508. crypto_digest_t *digest;
  509. tor_assert(identity_pk);
  510. tor_assert(blinded_pk);
  511. tor_assert(subcred_out);
  512. /* First, build the credential. Construction is as follow:
  513. * credential = H("credential" | public-identity-key) */
  514. digest = crypto_digest256_new(DIGEST_SHA3_256);
  515. crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
  516. HS_CREDENTIAL_PREFIX_LEN);
  517. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  518. ED25519_PUBKEY_LEN);
  519. crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
  520. crypto_digest_free(digest);
  521. /* Now, compute the subcredential. Construction is as follow:
  522. * subcredential = H("subcredential" | credential | blinded-public-key). */
  523. digest = crypto_digest256_new(DIGEST_SHA3_256);
  524. crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
  525. HS_SUBCREDENTIAL_PREFIX_LEN);
  526. crypto_digest_add_bytes(digest, (const char *) credential,
  527. sizeof(credential));
  528. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  529. ED25519_PUBKEY_LEN);
  530. crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
  531. crypto_digest_free(digest);
  532. }
  533. /* Using a base32 representation of a service address, parse its content into
  534. * the key_out, checksum_out and version_out. Any out variable can be NULL in
  535. * case the caller would want only one field. checksum_out MUST at least be 2
  536. * bytes long.
  537. *
  538. * Return 0 if parsing went well; return -1 in case of error. */
  539. int
  540. hs_parse_address(const char *address, ed25519_public_key_t *key_out,
  541. uint8_t *checksum_out, uint8_t *version_out)
  542. {
  543. char decoded[HS_SERVICE_ADDR_LEN];
  544. tor_assert(address);
  545. /* Obvious length check. */
  546. if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
  547. log_warn(LD_REND, "Service address %s has an invalid length. "
  548. "Expected %lu but got %lu.",
  549. escaped_safe_str(address),
  550. (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
  551. (unsigned long) strlen(address));
  552. goto invalid;
  553. }
  554. /* Decode address so we can extract needed fields. */
  555. if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
  556. log_warn(LD_REND, "Service address %s can't be decoded.",
  557. escaped_safe_str(address));
  558. goto invalid;
  559. }
  560. /* Parse the decoded address into the fields we need. */
  561. hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
  562. return 0;
  563. invalid:
  564. return -1;
  565. }
  566. /* Validate a given onion address. The length, the base32 decoding and
  567. * checksum are validated. Return 1 if valid else 0. */
  568. int
  569. hs_address_is_valid(const char *address)
  570. {
  571. uint8_t version;
  572. uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
  573. uint8_t target_checksum[DIGEST256_LEN];
  574. ed25519_public_key_t key;
  575. /* Parse the decoded address into the fields we need. */
  576. if (hs_parse_address(address, &key, checksum, &version) < 0) {
  577. goto invalid;
  578. }
  579. /* Get the checksum it's suppose to be and compare it with what we have
  580. * encoded in the address. */
  581. build_hs_checksum(&key, version, target_checksum);
  582. if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
  583. log_warn(LD_REND, "Service address %s invalid checksum.",
  584. escaped_safe_str(address));
  585. goto invalid;
  586. }
  587. /* Valid address. */
  588. return 1;
  589. invalid:
  590. return 0;
  591. }
  592. /* Build a service address using an ed25519 public key and a given version.
  593. * The returned address is base32 encoded and put in addr_out. The caller MUST
  594. * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
  595. *
  596. * Format is as follow:
  597. * base32(PUBKEY || CHECKSUM || VERSION)
  598. * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
  599. * */
  600. void
  601. hs_build_address(const ed25519_public_key_t *key, uint8_t version,
  602. char *addr_out)
  603. {
  604. uint8_t checksum[DIGEST256_LEN];
  605. char address[HS_SERVICE_ADDR_LEN];
  606. tor_assert(key);
  607. tor_assert(addr_out);
  608. /* Get the checksum of the address. */
  609. build_hs_checksum(key, version, checksum);
  610. /* Get the binary address representation. */
  611. build_hs_address(key, checksum, version, address);
  612. /* Encode the address. addr_out will be NUL terminated after this. */
  613. base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
  614. sizeof(address));
  615. /* Validate what we just built. */
  616. tor_assert(hs_address_is_valid(addr_out));
  617. }
  618. /* Return a newly allocated copy of lspec. */
  619. link_specifier_t *
  620. hs_link_specifier_dup(const link_specifier_t *lspec)
  621. {
  622. link_specifier_t *dup = link_specifier_new();
  623. memcpy(dup, lspec, sizeof(*dup));
  624. /* The unrecognized field is a dynamic array so make sure to copy its
  625. * content and not the pointer. */
  626. link_specifier_setlen_un_unrecognized(
  627. dup, link_specifier_getlen_un_unrecognized(lspec));
  628. if (link_specifier_getlen_un_unrecognized(dup)) {
  629. memcpy(link_specifier_getarray_un_unrecognized(dup),
  630. link_specifier_getconstarray_un_unrecognized(lspec),
  631. link_specifier_getlen_un_unrecognized(dup));
  632. }
  633. return dup;
  634. }
  635. /* From a given ed25519 public key pk and an optional secret, compute a
  636. * blinded public key and put it in blinded_pk_out. This is only useful to
  637. * the client side because the client only has access to the identity public
  638. * key of the service. */
  639. void
  640. hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
  641. const uint8_t *secret, size_t secret_len,
  642. uint64_t time_period_num,
  643. ed25519_public_key_t *blinded_pk_out)
  644. {
  645. /* Our blinding key API requires a 32 bytes parameter. */
  646. uint8_t param[DIGEST256_LEN];
  647. tor_assert(pk);
  648. tor_assert(blinded_pk_out);
  649. tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
  650. build_blinded_key_param(pk, secret, secret_len,
  651. time_period_num, get_time_period_length(), param);
  652. ed25519_public_blind(blinded_pk_out, pk, param);
  653. }
  654. /* From a given ed25519 keypair kp and an optional secret, compute a blinded
  655. * keypair for the current time period and put it in blinded_kp_out. This is
  656. * only useful by the service side because the client doesn't have access to
  657. * the identity secret key. */
  658. void
  659. hs_build_blinded_keypair(const ed25519_keypair_t *kp,
  660. const uint8_t *secret, size_t secret_len,
  661. uint64_t time_period_num,
  662. ed25519_keypair_t *blinded_kp_out)
  663. {
  664. /* Our blinding key API requires a 32 bytes parameter. */
  665. uint8_t param[DIGEST256_LEN];
  666. tor_assert(kp);
  667. tor_assert(blinded_kp_out);
  668. /* Extra safety. A zeroed key is bad. */
  669. tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
  670. tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
  671. build_blinded_key_param(&kp->pubkey, secret, secret_len,
  672. time_period_num, get_time_period_length(), param);
  673. ed25519_keypair_blind(blinded_kp_out, kp, param);
  674. }
  675. /* Return true if overlap mode is active given the date in consensus. If
  676. * consensus is NULL, then we use the latest live consensus we can find. */
  677. int
  678. hs_overlap_mode_is_active(const networkstatus_t *consensus, time_t now)
  679. {
  680. struct tm valid_after_tm;
  681. if (!consensus) {
  682. consensus = networkstatus_get_live_consensus(now);
  683. if (!consensus) {
  684. return 0;
  685. }
  686. }
  687. /* XXX: Futur commits will change this to a slot system so it can be
  688. * fine tuned better for testing networks in terms of timings. */
  689. /* From the spec: "Specifically, when a hidden service fetches a consensus
  690. * with "valid-after" between 00:00UTC and 12:00UTC, it goes into
  691. * "descriptor overlap" mode." */
  692. tor_gmtime_r(&consensus->valid_after, &valid_after_tm);
  693. if (valid_after_tm.tm_hour > 0 && valid_after_tm.tm_hour < 12) {
  694. return 1;
  695. }
  696. return 0;
  697. }
  698. /* Return 1 if any virtual port in ports needs a circuit with good uptime.
  699. * Else return 0. */
  700. int
  701. hs_service_requires_uptime_circ(const smartlist_t *ports)
  702. {
  703. tor_assert(ports);
  704. SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
  705. if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
  706. p->virtual_port)) {
  707. return 1;
  708. }
  709. } SMARTLIST_FOREACH_END(p);
  710. return 0;
  711. }
  712. /* Build hs_index which is used to find the responsible hsdirs. This index
  713. * value is used to select the responsible HSDir where their hsdir_index is
  714. * closest to this value.
  715. * SHA3-256("store-at-idx" | blinded_public_key |
  716. * INT_8(replicanum) | INT_8(period_num) )
  717. *
  718. * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
  719. void
  720. hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
  721. uint64_t period_num, uint8_t *hs_index_out)
  722. {
  723. crypto_digest_t *digest;
  724. tor_assert(blinded_pk);
  725. tor_assert(hs_index_out);
  726. /* Build hs_index. See construction at top of function comment. */
  727. digest = crypto_digest256_new(DIGEST_SHA3_256);
  728. crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
  729. crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
  730. ED25519_PUBKEY_LEN);
  731. crypto_digest_add_bytes(digest, (const char *) &replica, sizeof(replica));
  732. crypto_digest_add_bytes(digest, (const char *) &period_num,
  733. sizeof(period_num));
  734. crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
  735. crypto_digest_free(digest);
  736. }
  737. /* Build hsdir_index which is used to find the responsible hsdirs. This is the
  738. * index value that is compare to the hs_index when selecting an HSDir.
  739. * SHA3-256("node-idx" | node_identity |
  740. * shared_random_value | INT_8(period_num) )
  741. *
  742. * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
  743. void
  744. hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
  745. const uint8_t *srv_value, uint64_t period_num,
  746. uint8_t *hsdir_index_out)
  747. {
  748. crypto_digest_t *digest;
  749. tor_assert(identity_pk);
  750. tor_assert(srv_value);
  751. tor_assert(hsdir_index_out);
  752. /* Build hsdir_index. See construction at top of function comment. */
  753. digest = crypto_digest256_new(DIGEST_SHA3_256);
  754. crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
  755. crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
  756. ED25519_PUBKEY_LEN);
  757. crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
  758. crypto_digest_add_bytes(digest, (const char *) &period_num,
  759. sizeof(period_num));
  760. crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
  761. crypto_digest_free(digest);
  762. }
  763. /* Return a newly allocated buffer containing the current shared random value
  764. * or if not present, a disaster value is computed using the given time period
  765. * number. This function can't fail. */
  766. uint8_t *
  767. hs_get_current_srv(uint64_t time_period_num)
  768. {
  769. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  770. const sr_srv_t *current_srv = sr_get_current();
  771. if (current_srv) {
  772. memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
  773. } else {
  774. /* Disaster mode. */
  775. get_disaster_srv(time_period_num, sr_value);
  776. }
  777. return sr_value;
  778. }
  779. /* Return a newly allocated buffer containing the previous shared random
  780. * value or if not present, a disaster value is computed using the given time
  781. * period number. This function can't fail. */
  782. uint8_t *
  783. hs_get_previous_srv(uint64_t time_period_num)
  784. {
  785. uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
  786. const sr_srv_t *previous_srv = sr_get_previous();
  787. if (previous_srv) {
  788. memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
  789. } else {
  790. /* Disaster mode. */
  791. get_disaster_srv(time_period_num, sr_value);
  792. }
  793. return sr_value;
  794. }
  795. /* Return the number of replicas defined by a consensus parameter or the
  796. * default value. */
  797. int32_t
  798. hs_get_hsdir_n_replicas(void)
  799. {
  800. /* The [1,16] range is a specification requirement. */
  801. return networkstatus_get_param(NULL, "hsdir_n_replicas",
  802. HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
  803. }
  804. /* Return the spread fetch value defined by a consensus parameter or the
  805. * default value. */
  806. int32_t
  807. hs_get_hsdir_spread_fetch(void)
  808. {
  809. /* The [1,128] range is a specification requirement. */
  810. return networkstatus_get_param(NULL, "hsdir_spread_fetch",
  811. HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
  812. }
  813. /* Return the spread store value defined by a consensus parameter or the
  814. * default value. */
  815. int32_t
  816. hs_get_hsdir_spread_store(void)
  817. {
  818. /* The [1,128] range is a specification requirement. */
  819. return networkstatus_get_param(NULL, "hsdir_spread_store",
  820. HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
  821. }
  822. /* For a given blinded key and time period number, get the responsible HSDir
  823. * and put their routerstatus_t object in the responsible_dirs list. If
  824. * is_next_period is true, the next hsdir_index of the node_t is used. If
  825. * is_client is true, the spread fetch consensus parameter is used else the
  826. * spread store is used which is only for upload. This function can't fail but
  827. * it is possible that the responsible_dirs list contains fewer nodes than
  828. * expected.
  829. *
  830. * This function goes over the latest consensus routerstatus list and sorts it
  831. * by their node_t hsdir_index then does a binary search to find the closest
  832. * node. All of this makes it a bit CPU intensive so use it wisely. */
  833. void
  834. hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
  835. uint64_t time_period_num, int is_next_period,
  836. int is_client, smartlist_t *responsible_dirs)
  837. {
  838. smartlist_t *sorted_nodes;
  839. /* The compare function used for the smartlist bsearch. We have two
  840. * different depending on is_next_period. */
  841. int (*cmp_fct)(const void *, const void **);
  842. tor_assert(blinded_pk);
  843. tor_assert(responsible_dirs);
  844. sorted_nodes = smartlist_new();
  845. /* Add every node_t that support HSDir v3 for which we do have a valid
  846. * hsdir_index already computed for them for this consensus. */
  847. {
  848. networkstatus_t *c = networkstatus_get_latest_consensus();
  849. if (!c || smartlist_len(c->routerstatus_list) == 0) {
  850. log_warn(LD_REND, "No valid consensus so we can't get the responsible "
  851. "hidden service directories.");
  852. goto done;
  853. }
  854. SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
  855. /* Even though this node_t object won't be modified and should be const,
  856. * we can't add const object in a smartlist_t. */
  857. node_t *n = node_get_mutable_by_id(rs->identity_digest);
  858. tor_assert(n);
  859. if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
  860. if (BUG(n->hsdir_index == NULL)) {
  861. continue;
  862. }
  863. smartlist_add(sorted_nodes, n);
  864. }
  865. } SMARTLIST_FOREACH_END(rs);
  866. }
  867. if (smartlist_len(sorted_nodes) == 0) {
  868. log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
  869. goto done;
  870. }
  871. /* First thing we have to do is sort all node_t by hsdir_index. The
  872. * is_next_period tells us if we want the current or the next one. Set the
  873. * bsearch compare function also while we are at it. */
  874. if (is_next_period) {
  875. smartlist_sort(sorted_nodes, compare_node_next_hsdir_index);
  876. cmp_fct = compare_digest_to_next_hsdir_index;
  877. } else {
  878. smartlist_sort(sorted_nodes, compare_node_current_hsdir_index);
  879. cmp_fct = compare_digest_to_current_hsdir_index;
  880. }
  881. /* For all replicas, we'll select a set of HSDirs using the consensus
  882. * parameters and the sorted list. The replica starting at value 1 is
  883. * defined by the specification. */
  884. for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
  885. int idx, start, found, n_added = 0;
  886. uint8_t hs_index[DIGEST256_LEN] = {0};
  887. /* Number of node to add to the responsible dirs list depends on if we are
  888. * trying to fetch or store. A client always fetches. */
  889. int n_to_add = (is_client) ? hs_get_hsdir_spread_fetch() :
  890. hs_get_hsdir_spread_store();
  891. /* Get the index that we should use to select the node. */
  892. hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
  893. /* The compare function pointer has been set correctly earlier. */
  894. start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
  895. &found);
  896. /* Getting the length of the list if no member is greater than the key we
  897. * are looking for so start at the first element. */
  898. if (idx == smartlist_len(sorted_nodes)) {
  899. start = idx = 0;
  900. }
  901. while (n_added < n_to_add) {
  902. const node_t *node = smartlist_get(sorted_nodes, idx);
  903. /* If the node has already been selected which is possible between
  904. * replicas, the specification says to skip over. */
  905. if (!smartlist_contains(responsible_dirs, node->rs)) {
  906. smartlist_add(responsible_dirs, node->rs);
  907. ++n_added;
  908. }
  909. if (++idx == smartlist_len(sorted_nodes)) {
  910. /* Wrap if we've reached the end of the list. */
  911. idx = 0;
  912. }
  913. if (idx == start) {
  914. /* We've gone over the whole list, stop and avoid infinite loop. */
  915. break;
  916. }
  917. }
  918. }
  919. done:
  920. smartlist_free(sorted_nodes);
  921. }
  922. /* Initialize the entire HS subsytem. This is called in tor_init() before any
  923. * torrc options are loaded. Only for >= v3. */
  924. void
  925. hs_init(void)
  926. {
  927. hs_circuitmap_init();
  928. hs_service_init();
  929. hs_cache_init();
  930. }
  931. /* Release and cleanup all memory of the HS subsystem (all version). This is
  932. * called by tor_free_all(). */
  933. void
  934. hs_free_all(void)
  935. {
  936. hs_circuitmap_free_all();
  937. hs_service_free_all();
  938. hs_cache_free_all();
  939. }