hs_service.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_service.c
  5. * \brief Implement next generation hidden service functionality
  6. **/
  7. #define HS_SERVICE_PRIVATE
  8. #include "or.h"
  9. #include "circuitlist.h"
  10. #include "config.h"
  11. #include "relay.h"
  12. #include "rendservice.h"
  13. #include "router.h"
  14. #include "routerkeys.h"
  15. #include "hs_common.h"
  16. #include "hs_config.h"
  17. #include "hs_intropoint.h"
  18. #include "hs_service.h"
  19. #include "hs/cell_establish_intro.h"
  20. #include "hs/cell_common.h"
  21. /* Onion service directory file names. */
  22. static const char *fname_keyfile_prefix = "hs_ed25519";
  23. static const char *fname_hostname = "hostname";
  24. static const char *address_tld = "onion";
  25. /* Staging list of service object. When configuring service, we add them to
  26. * this list considered a staging area and they will get added to our global
  27. * map once the keys have been loaded. These two steps are seperated because
  28. * loading keys requires that we are an actual running tor process. */
  29. static smartlist_t *hs_service_staging_list;
  30. /* Helper: Function to compare two objects in the service map. Return 1 if the
  31. * two service have the same master public identity key. */
  32. static inline int
  33. hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
  34. {
  35. tor_assert(first);
  36. tor_assert(second);
  37. /* Simple key compare. */
  38. return ed25519_pubkey_eq(&first->keys.identity_pk,
  39. &second->keys.identity_pk);
  40. }
  41. /* Helper: Function for the service hash table code below. The key used is the
  42. * master public identity key which is ultimately the onion address. */
  43. static inline unsigned int
  44. hs_service_ht_hash(const hs_service_t *service)
  45. {
  46. tor_assert(service);
  47. return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
  48. sizeof(service->keys.identity_pk.pubkey));
  49. }
  50. /* This is _the_ global hash map of hidden services which indexed the service
  51. * contained in it by master public identity key which is roughly the onion
  52. * address of the service. */
  53. static struct hs_service_ht *hs_service_map;
  54. /* Register the service hash table. */
  55. HT_PROTOTYPE(hs_service_ht, /* Name of hashtable. */
  56. hs_service_t, /* Object contained in the map. */
  57. hs_service_node, /* The name of the HT_ENTRY member. */
  58. hs_service_ht_hash, /* Hashing function. */
  59. hs_service_ht_eq) /* Compare function for objects. */
  60. HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
  61. hs_service_ht_hash, hs_service_ht_eq,
  62. 0.6, tor_reallocarray, tor_free_)
  63. /* Query the given service map with a public key and return a service object
  64. * if found else NULL. It is also possible to set a directory path in the
  65. * search query. If pk is NULL, then it will be set to zero indicating the
  66. * hash table to compare the directory path instead. */
  67. STATIC hs_service_t *
  68. find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
  69. {
  70. hs_service_t dummy_service;
  71. tor_assert(map);
  72. tor_assert(pk);
  73. memset(&dummy_service, 0, sizeof(dummy_service));
  74. ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
  75. return HT_FIND(hs_service_ht, map, &dummy_service);
  76. }
  77. /* Register the given service in the given map. If the service already exists
  78. * in the map, -1 is returned. On success, 0 is returned and the service
  79. * ownership has been transfered to the global map. */
  80. STATIC int
  81. register_service(hs_service_ht *map, hs_service_t *service)
  82. {
  83. tor_assert(map);
  84. tor_assert(service);
  85. tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
  86. if (find_service(map, &service->keys.identity_pk)) {
  87. /* Existing service with the same key. Do not register it. */
  88. return -1;
  89. }
  90. /* Taking ownership of the object at this point. */
  91. HT_INSERT(hs_service_ht, map, service);
  92. return 0;
  93. }
  94. /* Remove a given service from the given map. If service is NULL or the
  95. * service key is unset, return gracefully. */
  96. STATIC void
  97. remove_service(hs_service_ht *map, hs_service_t *service)
  98. {
  99. hs_service_t *elm;
  100. tor_assert(map);
  101. /* Ignore if no service or key is zero. */
  102. if (BUG(service == NULL) ||
  103. BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
  104. return;
  105. }
  106. elm = HT_REMOVE(hs_service_ht, map, service);
  107. if (elm) {
  108. tor_assert(elm == service);
  109. } else {
  110. log_warn(LD_BUG, "Could not find service in the global map "
  111. "while removing service %s",
  112. escaped(service->config.directory_path));
  113. }
  114. }
  115. /* Set the default values for a service configuration object <b>c</b>. */
  116. static void
  117. set_service_default_config(hs_service_config_t *c,
  118. const or_options_t *options)
  119. {
  120. tor_assert(c);
  121. c->ports = smartlist_new();
  122. c->directory_path = NULL;
  123. c->descriptor_post_period = options->RendPostPeriod;
  124. c->max_streams_per_rdv_circuit = 0;
  125. c->max_streams_close_circuit = 0;
  126. c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
  127. c->allow_unknown_ports = 0;
  128. c->is_single_onion = 0;
  129. c->dir_group_readable = 0;
  130. c->is_ephemeral = 0;
  131. }
  132. /* From a service configuration object config, clear everything from it
  133. * meaning free allocated pointers and reset the values. */
  134. static void
  135. service_clear_config(hs_service_config_t *config)
  136. {
  137. if (config == NULL) {
  138. return;
  139. }
  140. tor_free(config->directory_path);
  141. if (config->ports) {
  142. SMARTLIST_FOREACH(config->ports, rend_service_port_config_t *, p,
  143. rend_service_port_config_free(p););
  144. smartlist_free(config->ports);
  145. }
  146. memset(config, 0, sizeof(*config));
  147. }
  148. /* Helper: Function that needs to return 1 for the HT for each loop which
  149. * frees every service in an hash map. */
  150. static int
  151. ht_free_service_(struct hs_service_t *service, void *data)
  152. {
  153. (void) data;
  154. hs_service_free(service);
  155. /* This function MUST return 1 so the given object is then removed from the
  156. * service map leading to this free of the object being safe. */
  157. return 1;
  158. }
  159. /* Free every service that can be found in the global map. Once done, clear
  160. * and free the global map. */
  161. static void
  162. service_free_all(void)
  163. {
  164. if (hs_service_map) {
  165. /* The free helper function returns 1 so this is safe. */
  166. hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
  167. HT_CLEAR(hs_service_ht, hs_service_map);
  168. tor_free(hs_service_map);
  169. hs_service_map = NULL;
  170. }
  171. if (hs_service_staging_list) {
  172. /* Cleanup staging list. */
  173. SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
  174. hs_service_free(s));
  175. smartlist_free(hs_service_staging_list);
  176. hs_service_staging_list = NULL;
  177. }
  178. }
  179. /* Close all rendezvous circuits for the given service. */
  180. static void
  181. close_service_rp_circuits(hs_service_t *service)
  182. {
  183. tor_assert(service);
  184. /* XXX: To implement. */
  185. return;
  186. }
  187. /* Close the circuit(s) for the given map of introduction points. */
  188. static void
  189. close_intro_circuits(hs_service_intropoints_t *intro_points)
  190. {
  191. tor_assert(intro_points);
  192. DIGEST256MAP_FOREACH(intro_points->map, key,
  193. const hs_service_intro_point_t *, ip) {
  194. origin_circuit_t *ocirc =
  195. hs_circuitmap_get_intro_circ_v3_service_side(
  196. &ip->auth_key_kp.pubkey);
  197. if (ocirc) {
  198. hs_circuitmap_remove_circuit(TO_CIRCUIT(ocirc));
  199. /* Reason is FINISHED because service has been removed and thus the
  200. * circuit is considered old/uneeded. */
  201. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  202. }
  203. } DIGEST256MAP_FOREACH_END;
  204. }
  205. /* Close all introduction circuits for the given service. */
  206. static void
  207. close_service_intro_circuits(hs_service_t *service)
  208. {
  209. tor_assert(service);
  210. if (service->desc_current) {
  211. close_intro_circuits(&service->desc_current->intro_points);
  212. }
  213. if (service->desc_next) {
  214. close_intro_circuits(&service->desc_next->intro_points);
  215. }
  216. }
  217. /* Close any circuits related to the given service. */
  218. static void
  219. close_service_circuits(hs_service_t *service)
  220. {
  221. tor_assert(service);
  222. /* Only support for version >= 3. */
  223. if (BUG(service->config.version < HS_VERSION_THREE)) {
  224. return;
  225. }
  226. /* Close intro points. */
  227. close_service_intro_circuits(service);
  228. /* Close rendezvous points. */
  229. close_service_rp_circuits(service);
  230. }
  231. /* Move introduction points from the src descriptor to the dst descriptor. The
  232. * destination service intropoints are wiped out if any before moving. */
  233. static void
  234. move_descriptor_intro_points(hs_service_descriptor_t *src,
  235. hs_service_descriptor_t *dst)
  236. {
  237. tor_assert(src);
  238. tor_assert(dst);
  239. /* XXX: Free dst introduction points. */
  240. dst->intro_points.map = src->intro_points.map;
  241. /* Nullify the source. */
  242. src->intro_points.map = NULL;
  243. }
  244. /* Move introduction points from the src service to the dst service. The
  245. * destination service intropoints are wiped out if any before moving. */
  246. static void
  247. move_intro_points(hs_service_t *src, hs_service_t *dst)
  248. {
  249. tor_assert(src);
  250. tor_assert(dst);
  251. /* Cleanup destination. */
  252. if (src->desc_current && dst->desc_current) {
  253. move_descriptor_intro_points(src->desc_current, dst->desc_current);
  254. }
  255. if (src->desc_next && dst->desc_next) {
  256. move_descriptor_intro_points(src->desc_next, dst->desc_next);
  257. }
  258. }
  259. /* Move every ephemeral services from the src service map to the dst service
  260. * map. It is possible that a service can't be register to the dst map which
  261. * won't stop the process of moving them all but will trigger a log warn. */
  262. static void
  263. move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
  264. {
  265. hs_service_t **iter, **next;
  266. tor_assert(src);
  267. tor_assert(dst);
  268. /* Iterate over the map to find ephemeral service and move them to the other
  269. * map. We loop using this method to have a safe removal process. */
  270. for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
  271. hs_service_t *s = *iter;
  272. if (!s->config.is_ephemeral) {
  273. /* Yeah, we are in a very manual loop :). */
  274. next = HT_NEXT(hs_service_ht, src, iter);
  275. continue;
  276. }
  277. /* Remove service from map and then register to it to the other map.
  278. * Reminder that "*iter" and "s" are the same thing. */
  279. next = HT_NEXT_RMV(hs_service_ht, src, iter);
  280. if (register_service(dst, s) < 0) {
  281. log_warn(LD_BUG, "Ephemeral service key is already being used. "
  282. "Skipping.");
  283. }
  284. }
  285. }
  286. /* Return a const string of the directory path escaped. If this is an
  287. * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
  288. * the main thread because escaped() uses a static variable. */
  289. static const char *
  290. service_escaped_dir(const hs_service_t *s)
  291. {
  292. return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
  293. escaped(s->config.directory_path);
  294. }
  295. /* Register services that are in the staging list. Once this function returns,
  296. * the global service map will be set with the right content and all non
  297. * surviving services will be cleaned up. */
  298. static void
  299. register_all_services(void)
  300. {
  301. struct hs_service_ht *new_service_map;
  302. hs_service_t *s, **iter;
  303. tor_assert(hs_service_staging_list);
  304. /* We'll save us some allocation and computing time. */
  305. if (smartlist_len(hs_service_staging_list) == 0) {
  306. return;
  307. }
  308. /* Allocate a new map that will replace the current one. */
  309. new_service_map = tor_malloc_zero(sizeof(*new_service_map));
  310. HT_INIT(hs_service_ht, new_service_map);
  311. /* First step is to transfer all ephemeral services from the current global
  312. * map to the new one we are constructing. We do not prune ephemeral
  313. * services as the only way to kill them is by deleting it from the control
  314. * port or stopping the tor daemon. */
  315. move_ephemeral_services(hs_service_map, new_service_map);
  316. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
  317. /* Check if that service is already in our global map and if so, we'll
  318. * transfer the intro points to it. */
  319. s = find_service(hs_service_map, &snew->keys.identity_pk);
  320. if (s) {
  321. /* Pass ownership of intro points from s (the current service) to snew
  322. * (the newly configured one). */
  323. move_intro_points(s, snew);
  324. /* Remove the service from the global map because after this, we need to
  325. * go over the remaining service in that map that aren't surviving the
  326. * reload to close their circuits. */
  327. remove_service(hs_service_map, s);
  328. }
  329. /* Great, this service is now ready to be added to our new map. */
  330. if (BUG(register_service(new_service_map, snew) < 0)) {
  331. /* This should never happen because prior to registration, we validate
  332. * every service against the entire set. Not being able to register a
  333. * service means we failed to validate correctly. In that case, don't
  334. * break tor and ignore the service but tell user. */
  335. log_warn(LD_BUG, "Unable to register service with directory %s",
  336. service_escaped_dir(snew));
  337. SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
  338. hs_service_free(snew);
  339. }
  340. } SMARTLIST_FOREACH_END(snew);
  341. /* Close any circuits associated with the non surviving services. Every
  342. * service in the current global map are roaming. */
  343. HT_FOREACH(iter, hs_service_ht, hs_service_map) {
  344. close_service_circuits(*iter);
  345. }
  346. /* Time to make the switch. We'll clear the staging list because its content
  347. * has now changed ownership to the map. */
  348. smartlist_clear(hs_service_staging_list);
  349. service_free_all();
  350. hs_service_map = new_service_map;
  351. }
  352. /* Write the onion address of a given service to the given filename fname_ in
  353. * the service directory. Return 0 on success else -1 on error. */
  354. static int
  355. write_address_to_file(const hs_service_t *service, const char *fname_)
  356. {
  357. int ret = -1;
  358. char *fname = NULL;
  359. /* Length of an address plus the sizeof the address tld (onion) which counts
  360. * the NUL terminated byte so we keep it for the "." and the newline. */
  361. char buf[HS_SERVICE_ADDR_LEN_BASE32 + sizeof(address_tld) + 1];
  362. tor_assert(service);
  363. tor_assert(fname_);
  364. /* Construct the full address with the onion tld and write the hostname file
  365. * to disk. */
  366. tor_snprintf(buf, sizeof(buf), "%s.%s\n", service->onion_address,
  367. address_tld);
  368. /* Notice here that we use the given "fname_". */
  369. fname = hs_path_from_filename(service->config.directory_path, fname_);
  370. if (write_str_to_file(fname, buf, 0) < 0) {
  371. log_warn(LD_REND, "Could not write onion address to hostname file %s",
  372. escaped(fname));
  373. goto end;
  374. }
  375. #ifndef _WIN32
  376. if (service->config.dir_group_readable) {
  377. /* Mode to 0640. */
  378. if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
  379. log_warn(LD_FS, "Unable to make onion service hostname file %s "
  380. "group-readable.", escaped(fname));
  381. }
  382. }
  383. #endif /* _WIN32 */
  384. /* Success. */
  385. ret = 0;
  386. end:
  387. tor_free(fname);
  388. return ret;
  389. }
  390. /* Load and/or generate private keys for the given service. On success, the
  391. * hostname file will be written to disk along with the master private key iff
  392. * the service is not configured for offline keys. Return 0 on success else -1
  393. * on failure. */
  394. static int
  395. load_service_keys(hs_service_t *service)
  396. {
  397. int ret = -1;
  398. char *fname = NULL;
  399. ed25519_keypair_t *kp;
  400. const hs_service_config_t *config;
  401. tor_assert(service);
  402. config = &service->config;
  403. /* Create and fix permission on service directory. We are about to write
  404. * files to that directory so make sure it exists and has the right
  405. * permissions. We do this here because at this stage we know that Tor is
  406. * actually running and the service we have has been validated. */
  407. if (BUG(hs_check_service_private_dir(get_options()->User,
  408. config->directory_path,
  409. config->dir_group_readable, 1) < 0)) {
  410. goto end;
  411. }
  412. /* Try to load the keys from file or generate it if not found. */
  413. fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
  414. /* Don't ask for key creation, we want to know if we were able to load it or
  415. * we had to generate it. Better logging! */
  416. kp = ed_key_init_from_file(fname, 0, LOG_INFO, NULL, 0, 0, 0, NULL);
  417. if (!kp) {
  418. log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
  419. /* We'll now try to generate the keys and for it we want the strongest
  420. * randomness for it. The keypair will be written in different files. */
  421. uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
  422. INIT_ED_KEY_SPLIT;
  423. kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
  424. NULL);
  425. if (!kp) {
  426. log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
  427. goto end;
  428. }
  429. }
  430. /* Copy loaded or generated keys to service object. */
  431. ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
  432. memcpy(&service->keys.identity_sk, &kp->seckey,
  433. sizeof(service->keys.identity_sk));
  434. /* This does a proper memory wipe. */
  435. ed25519_keypair_free(kp);
  436. /* Build onion address from the newly loaded keys. */
  437. tor_assert(service->config.version <= UINT8_MAX);
  438. hs_build_address(&service->keys.identity_pk,
  439. (uint8_t) service->config.version,
  440. service->onion_address);
  441. /* Write onion address to hostname file. */
  442. if (write_address_to_file(service, fname_hostname) < 0) {
  443. goto end;
  444. }
  445. /* Succes. */
  446. ret = 0;
  447. end:
  448. tor_free(fname);
  449. return ret;
  450. }
  451. /* Load and/or generate keys for all onion services including the client
  452. * authorization if any. Return 0 on success, -1 on failure. */
  453. int
  454. hs_service_load_all_keys(void)
  455. {
  456. /* Load v2 service keys if we have v2. */
  457. if (num_rend_services() != 0) {
  458. if (rend_service_load_all_keys(NULL) < 0) {
  459. goto err;
  460. }
  461. }
  462. /* Load or/and generate them for v3+. */
  463. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
  464. /* Ignore ephemeral service, they already have their keys set. */
  465. if (service->config.is_ephemeral) {
  466. continue;
  467. }
  468. log_info(LD_REND, "Loading v3 onion service keys from %s",
  469. service_escaped_dir(service));
  470. if (load_service_keys(service) < 0) {
  471. goto err;
  472. }
  473. /* XXX: Load/Generate client authorization keys. (#20700) */
  474. } SMARTLIST_FOREACH_END(service);
  475. /* Final step, the staging list contains service in a quiescent state that
  476. * is ready to be used. Register them to the global map. Once this is over,
  477. * the staging list will be cleaned up. */
  478. register_all_services();
  479. /* All keys have been loaded successfully. */
  480. return 0;
  481. err:
  482. return -1;
  483. }
  484. /* Put all service object in the given service list. After this, the caller
  485. * looses ownership of every elements in the list and responsible to free the
  486. * list pointer. */
  487. void
  488. hs_service_stage_services(const smartlist_t *service_list)
  489. {
  490. tor_assert(service_list);
  491. /* This list is freed at registration time but this function can be called
  492. * multiple time. */
  493. if (hs_service_staging_list == NULL) {
  494. hs_service_staging_list = smartlist_new();
  495. }
  496. /* Add all service object to our staging list. Caller is responsible for
  497. * freeing the service_list. */
  498. smartlist_add_all(hs_service_staging_list, service_list);
  499. }
  500. /* Allocate and initilize a service object. The service configuration will
  501. * contain the default values. Return the newly allocated object pointer. This
  502. * function can't fail. */
  503. hs_service_t *
  504. hs_service_new(const or_options_t *options)
  505. {
  506. hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
  507. /* Set default configuration value. */
  508. set_service_default_config(&service->config, options);
  509. /* Set the default service version. */
  510. service->config.version = HS_SERVICE_DEFAULT_VERSION;
  511. return service;
  512. }
  513. /* Free the given <b>service</b> object and all its content. This function
  514. * also takes care of wiping service keys from memory. It is safe to pass a
  515. * NULL pointer. */
  516. void
  517. hs_service_free(hs_service_t *service)
  518. {
  519. if (service == NULL) {
  520. return;
  521. }
  522. /* Free descriptors. */
  523. if (service->desc_current) {
  524. hs_descriptor_free(service->desc_current->desc);
  525. /* Wipe keys. */
  526. memwipe(&service->desc_current->signing_kp, 0,
  527. sizeof(service->desc_current->signing_kp));
  528. memwipe(&service->desc_current->blinded_kp, 0,
  529. sizeof(service->desc_current->blinded_kp));
  530. /* XXX: Free intro points. */
  531. tor_free(service->desc_current);
  532. }
  533. if (service->desc_next) {
  534. hs_descriptor_free(service->desc_next->desc);
  535. /* Wipe keys. */
  536. memwipe(&service->desc_next->signing_kp, 0,
  537. sizeof(service->desc_next->signing_kp));
  538. memwipe(&service->desc_next->blinded_kp, 0,
  539. sizeof(service->desc_next->blinded_kp));
  540. /* XXX: Free intro points. */
  541. tor_free(service->desc_next);
  542. }
  543. /* Free service configuration. */
  544. service_clear_config(&service->config);
  545. /* Wipe service keys. */
  546. memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
  547. tor_free(service);
  548. }
  549. /* Initialize the service HS subsystem. */
  550. void
  551. hs_service_init(void)
  552. {
  553. /* Should never be called twice. */
  554. tor_assert(!hs_service_map);
  555. tor_assert(!hs_service_staging_list);
  556. /* v2 specific. */
  557. rend_service_init();
  558. hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
  559. HT_INIT(hs_service_ht, hs_service_map);
  560. hs_service_staging_list = smartlist_new();
  561. }
  562. /* Release all global storage of the hidden service subsystem. */
  563. void
  564. hs_service_free_all(void)
  565. {
  566. rend_service_free_all();
  567. service_free_all();
  568. }
  569. /* XXX We don't currently use these functions, apart from generating unittest
  570. data. When we start implementing the service-side support for prop224 we
  571. should revisit these functions and use them. */
  572. /** Given an ESTABLISH_INTRO <b>cell</b>, encode it and place its payload in
  573. * <b>buf_out</b> which has size <b>buf_out_len</b>. Return the number of
  574. * bytes written, or a negative integer if there was an error. */
  575. ssize_t
  576. get_establish_intro_payload(uint8_t *buf_out, size_t buf_out_len,
  577. const trn_cell_establish_intro_t *cell)
  578. {
  579. ssize_t bytes_used = 0;
  580. if (buf_out_len < RELAY_PAYLOAD_SIZE) {
  581. return -1;
  582. }
  583. bytes_used = trn_cell_establish_intro_encode(buf_out, buf_out_len,
  584. cell);
  585. return bytes_used;
  586. }
  587. /* Set the cell extensions of <b>cell</b>. */
  588. static void
  589. set_trn_cell_extensions(trn_cell_establish_intro_t *cell)
  590. {
  591. trn_cell_extension_t *trn_cell_extensions = trn_cell_extension_new();
  592. /* For now, we don't use extensions at all. */
  593. trn_cell_extensions->num = 0; /* It's already zeroed, but be explicit. */
  594. trn_cell_establish_intro_set_extensions(cell, trn_cell_extensions);
  595. }
  596. /** Given the circuit handshake info in <b>circuit_key_material</b>, create and
  597. * return an ESTABLISH_INTRO cell. Return NULL if something went wrong. The
  598. * returned cell is allocated on the heap and it's the responsibility of the
  599. * caller to free it. */
  600. trn_cell_establish_intro_t *
  601. generate_establish_intro_cell(const uint8_t *circuit_key_material,
  602. size_t circuit_key_material_len)
  603. {
  604. trn_cell_establish_intro_t *cell = NULL;
  605. ssize_t encoded_len;
  606. log_warn(LD_GENERAL,
  607. "Generating ESTABLISH_INTRO cell (key_material_len: %u)",
  608. (unsigned) circuit_key_material_len);
  609. /* Generate short-term keypair for use in ESTABLISH_INTRO */
  610. ed25519_keypair_t key_struct;
  611. if (ed25519_keypair_generate(&key_struct, 0) < 0) {
  612. goto err;
  613. }
  614. cell = trn_cell_establish_intro_new();
  615. /* Set AUTH_KEY_TYPE: 2 means ed25519 */
  616. trn_cell_establish_intro_set_auth_key_type(cell,
  617. HS_INTRO_AUTH_KEY_TYPE_ED25519);
  618. /* Set AUTH_KEY_LEN field */
  619. /* Must also set byte-length of AUTH_KEY to match */
  620. int auth_key_len = ED25519_PUBKEY_LEN;
  621. trn_cell_establish_intro_set_auth_key_len(cell, auth_key_len);
  622. trn_cell_establish_intro_setlen_auth_key(cell, auth_key_len);
  623. /* Set AUTH_KEY field */
  624. uint8_t *auth_key_ptr = trn_cell_establish_intro_getarray_auth_key(cell);
  625. memcpy(auth_key_ptr, key_struct.pubkey.pubkey, auth_key_len);
  626. /* No cell extensions needed */
  627. set_trn_cell_extensions(cell);
  628. /* Set signature size.
  629. We need to do this up here, because _encode() needs it and we need to call
  630. _encode() to calculate the MAC and signature.
  631. */
  632. int sig_len = ED25519_SIG_LEN;
  633. trn_cell_establish_intro_set_sig_len(cell, sig_len);
  634. trn_cell_establish_intro_setlen_sig(cell, sig_len);
  635. /* XXX How to make this process easier and nicer? */
  636. /* Calculate the cell MAC (aka HANDSHAKE_AUTH). */
  637. {
  638. /* To calculate HANDSHAKE_AUTH, we dump the cell in bytes, and then derive
  639. the MAC from it. */
  640. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  641. uint8_t mac[TRUNNEL_SHA3_256_LEN];
  642. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  643. sizeof(cell_bytes_tmp),
  644. cell);
  645. if (encoded_len < 0) {
  646. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell.");
  647. goto err;
  648. }
  649. /* sanity check */
  650. tor_assert(encoded_len > ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN);
  651. /* Calculate MAC of all fields before HANDSHAKE_AUTH */
  652. crypto_mac_sha3_256(mac, sizeof(mac),
  653. circuit_key_material, circuit_key_material_len,
  654. cell_bytes_tmp,
  655. encoded_len -
  656. (ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN));
  657. /* Write the MAC to the cell */
  658. uint8_t *handshake_ptr =
  659. trn_cell_establish_intro_getarray_handshake_mac(cell);
  660. memcpy(handshake_ptr, mac, sizeof(mac));
  661. }
  662. /* Calculate the cell signature */
  663. {
  664. /* To calculate the sig we follow the same procedure as above. We first
  665. dump the cell up to the sig, and then calculate the sig */
  666. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  667. ed25519_signature_t sig;
  668. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  669. sizeof(cell_bytes_tmp),
  670. cell);
  671. if (encoded_len < 0) {
  672. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell (2).");
  673. goto err;
  674. }
  675. tor_assert(encoded_len > ED25519_SIG_LEN);
  676. if (ed25519_sign_prefixed(&sig,
  677. cell_bytes_tmp,
  678. encoded_len -
  679. (ED25519_SIG_LEN + sizeof(cell->sig_len)),
  680. ESTABLISH_INTRO_SIG_PREFIX,
  681. &key_struct)) {
  682. log_warn(LD_BUG, "Unable to gen signature for ESTABLISH_INTRO cell.");
  683. goto err;
  684. }
  685. /* And write the signature to the cell */
  686. uint8_t *sig_ptr = trn_cell_establish_intro_getarray_sig(cell);
  687. memcpy(sig_ptr, sig.sig, sig_len);
  688. }
  689. /* We are done! Return the cell! */
  690. return cell;
  691. err:
  692. trn_cell_establish_intro_free(cell);
  693. return NULL;
  694. }
  695. #ifdef TOR_UNIT_TESTS
  696. /* Return the global service map size. Only used by unit test. */
  697. STATIC unsigned int
  698. get_hs_service_map_size(void)
  699. {
  700. return HT_SIZE(hs_service_map);
  701. }
  702. /* Return the staging list size. Only used by unit test. */
  703. STATIC int
  704. get_hs_service_staging_list_size(void)
  705. {
  706. return smartlist_len(hs_service_staging_list);
  707. }
  708. STATIC hs_service_ht *
  709. get_hs_service_map(void)
  710. {
  711. return hs_service_map;
  712. }
  713. STATIC hs_service_t *
  714. get_first_service(void)
  715. {
  716. hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
  717. if (obj == NULL) {
  718. return NULL;
  719. }
  720. return *obj;
  721. }
  722. #endif /* TOR_UNIT_TESTS */