hs_service.c 31 KB

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