hs_service.c 27 KB

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