hs_service.c 31 KB

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