hs_service.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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 "circuitbuild.h"
  11. #include "circuitlist.h"
  12. #include "config.h"
  13. #include "main.h"
  14. #include "networkstatus.h"
  15. #include "nodelist.h"
  16. #include "relay.h"
  17. #include "rendservice.h"
  18. #include "router.h"
  19. #include "routerkeys.h"
  20. #include "routerlist.h"
  21. #include "hs_circuit.h"
  22. #include "hs_common.h"
  23. #include "hs_config.h"
  24. #include "hs_circuit.h"
  25. #include "hs_descriptor.h"
  26. #include "hs_ident.h"
  27. #include "hs_intropoint.h"
  28. #include "hs_service.h"
  29. /* Trunnel */
  30. #include "ed25519_cert.h"
  31. #include "hs/cell_establish_intro.h"
  32. #include "hs/cell_common.h"
  33. /* Helper macro. Iterate over every service in the global map. The var is the
  34. * name of the service pointer. */
  35. #define FOR_EACH_SERVICE_BEGIN(var) \
  36. STMT_BEGIN \
  37. hs_service_t **var##_iter, *var; \
  38. HT_FOREACH(var##_iter, hs_service_ht, hs_service_map) { \
  39. var = *var##_iter;
  40. #define FOR_EACH_SERVICE_END } STMT_END ;
  41. /* Helper macro. Iterate over both current and previous descriptor of a
  42. * service. The var is the name of the descriptor pointer. This macro skips
  43. * any descriptor object of the service that is NULL. */
  44. #define FOR_EACH_DESCRIPTOR_BEGIN(service, var) \
  45. STMT_BEGIN \
  46. hs_service_descriptor_t *var; \
  47. for (int var ## _loop_idx = 0; var ## _loop_idx < 2; \
  48. ++var ## _loop_idx) { \
  49. (var ## _loop_idx == 0) ? (var = service->desc_current) : \
  50. (var = service->desc_next); \
  51. if (var == NULL) continue;
  52. #define FOR_EACH_DESCRIPTOR_END } STMT_END ;
  53. /* Onion service directory file names. */
  54. static const char *fname_keyfile_prefix = "hs_ed25519";
  55. static const char *fname_hostname = "hostname";
  56. static const char *address_tld = "onion";
  57. /* Staging list of service object. When configuring service, we add them to
  58. * this list considered a staging area and they will get added to our global
  59. * map once the keys have been loaded. These two steps are seperated because
  60. * loading keys requires that we are an actual running tor process. */
  61. static smartlist_t *hs_service_staging_list;
  62. /* Helper: Function to compare two objects in the service map. Return 1 if the
  63. * two service have the same master public identity key. */
  64. static inline int
  65. hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
  66. {
  67. tor_assert(first);
  68. tor_assert(second);
  69. /* Simple key compare. */
  70. return ed25519_pubkey_eq(&first->keys.identity_pk,
  71. &second->keys.identity_pk);
  72. }
  73. /* Helper: Function for the service hash table code below. The key used is the
  74. * master public identity key which is ultimately the onion address. */
  75. static inline unsigned int
  76. hs_service_ht_hash(const hs_service_t *service)
  77. {
  78. tor_assert(service);
  79. return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
  80. sizeof(service->keys.identity_pk.pubkey));
  81. }
  82. /* This is _the_ global hash map of hidden services which indexed the service
  83. * contained in it by master public identity key which is roughly the onion
  84. * address of the service. */
  85. static struct hs_service_ht *hs_service_map;
  86. /* Register the service hash table. */
  87. HT_PROTOTYPE(hs_service_ht, /* Name of hashtable. */
  88. hs_service_t, /* Object contained in the map. */
  89. hs_service_node, /* The name of the HT_ENTRY member. */
  90. hs_service_ht_hash, /* Hashing function. */
  91. hs_service_ht_eq) /* Compare function for objects. */
  92. HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
  93. hs_service_ht_hash, hs_service_ht_eq,
  94. 0.6, tor_reallocarray, tor_free_)
  95. /* Query the given service map with a public key and return a service object
  96. * if found else NULL. It is also possible to set a directory path in the
  97. * search query. If pk is NULL, then it will be set to zero indicating the
  98. * hash table to compare the directory path instead. */
  99. STATIC hs_service_t *
  100. find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
  101. {
  102. hs_service_t dummy_service;
  103. tor_assert(map);
  104. tor_assert(pk);
  105. memset(&dummy_service, 0, sizeof(dummy_service));
  106. ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
  107. return HT_FIND(hs_service_ht, map, &dummy_service);
  108. }
  109. /* Register the given service in the given map. If the service already exists
  110. * in the map, -1 is returned. On success, 0 is returned and the service
  111. * ownership has been transfered to the global map. */
  112. STATIC int
  113. register_service(hs_service_ht *map, hs_service_t *service)
  114. {
  115. tor_assert(map);
  116. tor_assert(service);
  117. tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
  118. if (find_service(map, &service->keys.identity_pk)) {
  119. /* Existing service with the same key. Do not register it. */
  120. return -1;
  121. }
  122. /* Taking ownership of the object at this point. */
  123. HT_INSERT(hs_service_ht, map, service);
  124. return 0;
  125. }
  126. /* Remove a given service from the given map. If service is NULL or the
  127. * service key is unset, return gracefully. */
  128. STATIC void
  129. remove_service(hs_service_ht *map, hs_service_t *service)
  130. {
  131. hs_service_t *elm;
  132. tor_assert(map);
  133. /* Ignore if no service or key is zero. */
  134. if (BUG(service == NULL) ||
  135. BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
  136. return;
  137. }
  138. elm = HT_REMOVE(hs_service_ht, map, service);
  139. if (elm) {
  140. tor_assert(elm == service);
  141. } else {
  142. log_warn(LD_BUG, "Could not find service in the global map "
  143. "while removing service %s",
  144. escaped(service->config.directory_path));
  145. }
  146. }
  147. /* Set the default values for a service configuration object <b>c</b>. */
  148. static void
  149. set_service_default_config(hs_service_config_t *c,
  150. const or_options_t *options)
  151. {
  152. tor_assert(c);
  153. c->ports = smartlist_new();
  154. c->directory_path = NULL;
  155. c->descriptor_post_period = options->RendPostPeriod;
  156. c->max_streams_per_rdv_circuit = 0;
  157. c->max_streams_close_circuit = 0;
  158. c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
  159. c->allow_unknown_ports = 0;
  160. c->is_single_onion = 0;
  161. c->dir_group_readable = 0;
  162. c->is_ephemeral = 0;
  163. }
  164. /* From a service configuration object config, clear everything from it
  165. * meaning free allocated pointers and reset the values. */
  166. static void
  167. service_clear_config(hs_service_config_t *config)
  168. {
  169. if (config == NULL) {
  170. return;
  171. }
  172. tor_free(config->directory_path);
  173. if (config->ports) {
  174. SMARTLIST_FOREACH(config->ports, rend_service_port_config_t *, p,
  175. rend_service_port_config_free(p););
  176. smartlist_free(config->ports);
  177. }
  178. memset(config, 0, sizeof(*config));
  179. }
  180. /* Helper: Function that needs to return 1 for the HT for each loop which
  181. * frees every service in an hash map. */
  182. static int
  183. ht_free_service_(struct hs_service_t *service, void *data)
  184. {
  185. (void) data;
  186. hs_service_free(service);
  187. /* This function MUST return 1 so the given object is then removed from the
  188. * service map leading to this free of the object being safe. */
  189. return 1;
  190. }
  191. /* Free every service that can be found in the global map. Once done, clear
  192. * and free the global map. */
  193. static void
  194. service_free_all(void)
  195. {
  196. if (hs_service_map) {
  197. /* The free helper function returns 1 so this is safe. */
  198. hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
  199. HT_CLEAR(hs_service_ht, hs_service_map);
  200. tor_free(hs_service_map);
  201. hs_service_map = NULL;
  202. }
  203. if (hs_service_staging_list) {
  204. /* Cleanup staging list. */
  205. SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
  206. hs_service_free(s));
  207. smartlist_free(hs_service_staging_list);
  208. hs_service_staging_list = NULL;
  209. }
  210. }
  211. /* Free a given service intro point object. */
  212. static void
  213. service_intro_point_free(hs_service_intro_point_t *ip)
  214. {
  215. if (!ip) {
  216. return;
  217. }
  218. memwipe(&ip->auth_key_kp, 0, sizeof(ip->auth_key_kp));
  219. memwipe(&ip->enc_key_kp, 0, sizeof(ip->enc_key_kp));
  220. crypto_pk_free(ip->legacy_key);
  221. replaycache_free(ip->replay_cache);
  222. hs_intro_free_content(&ip->base);
  223. tor_free(ip);
  224. }
  225. /* Helper: free an hs_service_intro_point_t object. This function is used by
  226. * digest256map_free() which requires a void * pointer. */
  227. static void
  228. service_intro_point_free_(void *obj)
  229. {
  230. service_intro_point_free(obj);
  231. }
  232. /* Return a newly allocated service intro point and fully initialized from the
  233. * given extend_info_t ei if non NULL. If is_legacy is true, we also generate
  234. * the legacy key. On error, NULL is returned. */
  235. static hs_service_intro_point_t *
  236. service_intro_point_new(const extend_info_t *ei, unsigned int is_legacy)
  237. {
  238. hs_desc_link_specifier_t *ls;
  239. hs_service_intro_point_t *ip;
  240. ip = tor_malloc_zero(sizeof(*ip));
  241. /* We'll create the key material. No need for extra strong, those are short
  242. * term keys. */
  243. ed25519_keypair_generate(&ip->auth_key_kp, 0);
  244. /* XXX: These will be controlled by consensus params. (#20961) */
  245. ip->introduce2_max =
  246. crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
  247. INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
  248. ip->time_to_expire = time(NULL) +
  249. crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
  250. INTRO_POINT_LIFETIME_MAX_SECONDS);
  251. ip->replay_cache = replaycache_new(0, 0);
  252. /* Initialize the base object. We don't need the certificate object. */
  253. ip->base.link_specifiers = smartlist_new();
  254. /* Generate the encryption key for this intro point. */
  255. curve25519_keypair_generate(&ip->enc_key_kp, 0);
  256. /* Figure out if this chosen node supports v3 or is legacy only. */
  257. if (is_legacy) {
  258. ip->base.is_only_legacy = 1;
  259. /* Legacy mode that is doesn't support v3+ with ed25519 auth key. */
  260. ip->legacy_key = crypto_pk_new();
  261. if (crypto_pk_generate_key(ip->legacy_key) < 0) {
  262. goto err;
  263. }
  264. }
  265. if (ei == NULL) {
  266. goto done;
  267. }
  268. /* We'll try to add all link specifier. Legacy, IPv4 and ed25519 are
  269. * mandatory. */
  270. ls = hs_desc_link_specifier_new(ei, LS_IPV4);
  271. /* It is impossible to have an extend info object without a v4. */
  272. tor_assert(ls);
  273. smartlist_add(ip->base.link_specifiers, ls);
  274. ls = hs_desc_link_specifier_new(ei, LS_LEGACY_ID);
  275. /* It is impossible to have an extend info object without an identity
  276. * digest. */
  277. tor_assert(ls);
  278. smartlist_add(ip->base.link_specifiers, ls);
  279. ls = hs_desc_link_specifier_new(ei, LS_ED25519_ID);
  280. /* It is impossible to have an extend info object without an ed25519
  281. * identity key. */
  282. tor_assert(ls);
  283. smartlist_add(ip->base.link_specifiers, ls);
  284. /* IPv6 is optional. */
  285. ls = hs_desc_link_specifier_new(ei, LS_IPV6);
  286. if (ls) {
  287. smartlist_add(ip->base.link_specifiers, ls);
  288. }
  289. /* Finally, copy onion key from the extend_info_t object. */
  290. memcpy(&ip->onion_key, &ei->curve25519_onion_key, sizeof(ip->onion_key));
  291. done:
  292. return ip;
  293. err:
  294. service_intro_point_free(ip);
  295. return NULL;
  296. }
  297. /* Add the given intro point object to the given intro point map. The intro
  298. * point MUST have its RSA encryption key set if this is a legacy type or the
  299. * authentication key set otherwise. */
  300. static void
  301. service_intro_point_add(digest256map_t *map, hs_service_intro_point_t *ip)
  302. {
  303. uint8_t key[DIGEST256_LEN] = {0};
  304. tor_assert(map);
  305. tor_assert(ip);
  306. memcpy(key, ip->auth_key_kp.pubkey.pubkey, sizeof(key));
  307. digest256map_set(map, key, ip);
  308. }
  309. /* From a given intro point, return the first link specifier of type
  310. * encountered in the link specifier list. Return NULL if it can't be found.
  311. *
  312. * The caller does NOT have ownership of the object, the intro point does. */
  313. static hs_desc_link_specifier_t *
  314. get_link_spec_by_type(const hs_service_intro_point_t *ip, uint8_t type)
  315. {
  316. hs_desc_link_specifier_t *lnk_spec = NULL;
  317. tor_assert(ip);
  318. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  319. hs_desc_link_specifier_t *, ls) {
  320. if (ls->type == type) {
  321. lnk_spec = ls;
  322. goto end;
  323. }
  324. } SMARTLIST_FOREACH_END(ls);
  325. end:
  326. return lnk_spec;
  327. }
  328. /* Given a service intro point, return the node_t associated to it. This can
  329. * return NULL if the given intro point has no legacy ID or if the node can't
  330. * be found in the consensus. */
  331. static const node_t *
  332. get_node_from_intro_point(const hs_service_intro_point_t *ip)
  333. {
  334. const hs_desc_link_specifier_t *ls;
  335. tor_assert(ip);
  336. ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
  337. /* Legacy ID is mandatory for an intro point object to have. */
  338. tor_assert(ls);
  339. /* XXX In the future, we want to only use the ed25519 ID (#22173). */
  340. return node_get_by_id((const char *) ls->u.legacy_id);
  341. }
  342. /* Given a service intro point, return the extend_info_t for it. This can
  343. * return NULL if the node can't be found for the intro point or the extend
  344. * info can't be created for the found node. If direct_conn is set, the extend
  345. * info is validated on if we can connect directly. */
  346. static extend_info_t *
  347. get_extend_info_from_intro_point(const hs_service_intro_point_t *ip,
  348. unsigned int direct_conn)
  349. {
  350. extend_info_t *info = NULL;
  351. const node_t *node;
  352. tor_assert(ip);
  353. node = get_node_from_intro_point(ip);
  354. if (node == NULL) {
  355. /* This can happen if the relay serving as intro point has been removed
  356. * from the consensus. In that case, the intro point will be removed from
  357. * the descriptor during the scheduled events. */
  358. goto end;
  359. }
  360. /* In the case of a direct connection (single onion service), it is possible
  361. * our firewall policy won't allow it so this can return a NULL value. */
  362. info = extend_info_from_node(node, direct_conn);
  363. end:
  364. return info;
  365. }
  366. /* Return an introduction point circuit matching the given intro point object.
  367. * NULL is returned is no such circuit can be found. */
  368. static origin_circuit_t *
  369. get_intro_circuit(const hs_service_intro_point_t *ip)
  370. {
  371. origin_circuit_t *circ = NULL;
  372. tor_assert(ip);
  373. if (ip->base.is_only_legacy) {
  374. uint8_t digest[DIGEST_LEN];
  375. if (BUG(crypto_pk_get_digest(ip->legacy_key, (char *) digest) < 0)) {
  376. goto end;
  377. }
  378. circ = hs_circuitmap_get_intro_circ_v2_service_side(digest);
  379. } else {
  380. circ = hs_circuitmap_get_intro_circ_v3_service_side(
  381. &ip->auth_key_kp.pubkey);
  382. }
  383. end:
  384. return circ;
  385. }
  386. /* Close all rendezvous circuits for the given service. */
  387. static void
  388. close_service_rp_circuits(hs_service_t *service)
  389. {
  390. origin_circuit_t *ocirc = NULL;
  391. tor_assert(service);
  392. /* The reason we go over all circuit instead of using the circuitmap API is
  393. * because most hidden service circuits are rendezvous circuits so there is
  394. * no real improvement at getting all rendezvous circuits from the
  395. * circuitmap and then going over them all to find the right ones.
  396. * Furthermore, another option would have been to keep a list of RP cookies
  397. * for a service but it creates an engineering complexity since we don't
  398. * have a "RP circuit closed" event to clean it up properly so we avoid a
  399. * memory DoS possibility. */
  400. while ((ocirc = circuit_get_next_service_rp_circ(ocirc))) {
  401. /* Only close circuits that are v3 and for this service. */
  402. if (ocirc->hs_ident != NULL &&
  403. ed25519_pubkey_eq(&ocirc->hs_ident->identity_pk,
  404. &service->keys.identity_pk)) {
  405. /* Reason is FINISHED because service has been removed and thus the
  406. * circuit is considered old/uneeded. When freed, it is removed from the
  407. * hs circuitmap. */
  408. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  409. }
  410. }
  411. }
  412. /* Close the circuit(s) for the given map of introduction points. */
  413. static void
  414. close_intro_circuits(hs_service_intropoints_t *intro_points)
  415. {
  416. tor_assert(intro_points);
  417. DIGEST256MAP_FOREACH(intro_points->map, key,
  418. const hs_service_intro_point_t *, ip) {
  419. origin_circuit_t *ocirc = get_intro_circuit(ip);
  420. if (ocirc) {
  421. /* Reason is FINISHED because service has been removed and thus the
  422. * circuit is considered old/uneeded. When freed, the circuit is removed
  423. * from the HS circuitmap. */
  424. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  425. }
  426. } DIGEST256MAP_FOREACH_END;
  427. }
  428. /* Close all introduction circuits for the given service. */
  429. static void
  430. close_service_intro_circuits(hs_service_t *service)
  431. {
  432. tor_assert(service);
  433. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  434. close_intro_circuits(&desc->intro_points);
  435. } FOR_EACH_DESCRIPTOR_END;
  436. }
  437. /* Close any circuits related to the given service. */
  438. static void
  439. close_service_circuits(hs_service_t *service)
  440. {
  441. tor_assert(service);
  442. /* Only support for version >= 3. */
  443. if (BUG(service->config.version < HS_VERSION_THREE)) {
  444. return;
  445. }
  446. /* Close intro points. */
  447. close_service_intro_circuits(service);
  448. /* Close rendezvous points. */
  449. close_service_rp_circuits(service);
  450. }
  451. /* Move introduction points from the src descriptor to the dst descriptor. The
  452. * destination service intropoints are wiped out if any before moving. */
  453. static void
  454. move_descriptor_intro_points(hs_service_descriptor_t *src,
  455. hs_service_descriptor_t *dst)
  456. {
  457. tor_assert(src);
  458. tor_assert(dst);
  459. digest256map_free(dst->intro_points.map, service_intro_point_free_);
  460. dst->intro_points.map = src->intro_points.map;
  461. /* Nullify the source. */
  462. src->intro_points.map = NULL;
  463. }
  464. /* Move introduction points from the src service to the dst service. The
  465. * destination service intropoints are wiped out if any before moving. */
  466. static void
  467. move_intro_points(hs_service_t *src, hs_service_t *dst)
  468. {
  469. tor_assert(src);
  470. tor_assert(dst);
  471. if (src->desc_current && dst->desc_current) {
  472. move_descriptor_intro_points(src->desc_current, dst->desc_current);
  473. }
  474. if (src->desc_next && dst->desc_next) {
  475. move_descriptor_intro_points(src->desc_next, dst->desc_next);
  476. }
  477. }
  478. /* Move every ephemeral services from the src service map to the dst service
  479. * map. It is possible that a service can't be register to the dst map which
  480. * won't stop the process of moving them all but will trigger a log warn. */
  481. static void
  482. move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
  483. {
  484. hs_service_t **iter, **next;
  485. tor_assert(src);
  486. tor_assert(dst);
  487. /* Iterate over the map to find ephemeral service and move them to the other
  488. * map. We loop using this method to have a safe removal process. */
  489. for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
  490. hs_service_t *s = *iter;
  491. if (!s->config.is_ephemeral) {
  492. /* Yeah, we are in a very manual loop :). */
  493. next = HT_NEXT(hs_service_ht, src, iter);
  494. continue;
  495. }
  496. /* Remove service from map and then register to it to the other map.
  497. * Reminder that "*iter" and "s" are the same thing. */
  498. next = HT_NEXT_RMV(hs_service_ht, src, iter);
  499. if (register_service(dst, s) < 0) {
  500. log_warn(LD_BUG, "Ephemeral service key is already being used. "
  501. "Skipping.");
  502. }
  503. }
  504. }
  505. /* Return a const string of the directory path escaped. If this is an
  506. * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
  507. * the main thread because escaped() uses a static variable. */
  508. static const char *
  509. service_escaped_dir(const hs_service_t *s)
  510. {
  511. return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
  512. escaped(s->config.directory_path);
  513. }
  514. /* Register services that are in the staging list. Once this function returns,
  515. * the global service map will be set with the right content and all non
  516. * surviving services will be cleaned up. */
  517. static void
  518. register_all_services(void)
  519. {
  520. struct hs_service_ht *new_service_map;
  521. tor_assert(hs_service_staging_list);
  522. /* We'll save us some allocation and computing time. */
  523. if (smartlist_len(hs_service_staging_list) == 0) {
  524. return;
  525. }
  526. /* Allocate a new map that will replace the current one. */
  527. new_service_map = tor_malloc_zero(sizeof(*new_service_map));
  528. HT_INIT(hs_service_ht, new_service_map);
  529. /* First step is to transfer all ephemeral services from the current global
  530. * map to the new one we are constructing. We do not prune ephemeral
  531. * services as the only way to kill them is by deleting it from the control
  532. * port or stopping the tor daemon. */
  533. move_ephemeral_services(hs_service_map, new_service_map);
  534. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
  535. hs_service_t *s;
  536. /* Check if that service is already in our global map and if so, we'll
  537. * transfer the intro points to it. */
  538. s = find_service(hs_service_map, &snew->keys.identity_pk);
  539. if (s) {
  540. /* Pass ownership of intro points from s (the current service) to snew
  541. * (the newly configured one). */
  542. move_intro_points(s, snew);
  543. /* Remove the service from the global map because after this, we need to
  544. * go over the remaining service in that map that aren't surviving the
  545. * reload to close their circuits. */
  546. remove_service(hs_service_map, s);
  547. }
  548. /* Great, this service is now ready to be added to our new map. */
  549. if (BUG(register_service(new_service_map, snew) < 0)) {
  550. /* This should never happen because prior to registration, we validate
  551. * every service against the entire set. Not being able to register a
  552. * service means we failed to validate correctly. In that case, don't
  553. * break tor and ignore the service but tell user. */
  554. log_warn(LD_BUG, "Unable to register service with directory %s",
  555. service_escaped_dir(snew));
  556. SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
  557. hs_service_free(snew);
  558. }
  559. } SMARTLIST_FOREACH_END(snew);
  560. /* Close any circuits associated with the non surviving services. Every
  561. * service in the current global map are roaming. */
  562. FOR_EACH_SERVICE_BEGIN(service) {
  563. close_service_circuits(service);
  564. } FOR_EACH_SERVICE_END;
  565. /* Time to make the switch. We'll clear the staging list because its content
  566. * has now changed ownership to the map. */
  567. smartlist_clear(hs_service_staging_list);
  568. service_free_all();
  569. hs_service_map = new_service_map;
  570. }
  571. /* Write the onion address of a given service to the given filename fname_ in
  572. * the service directory. Return 0 on success else -1 on error. */
  573. static int
  574. write_address_to_file(const hs_service_t *service, const char *fname_)
  575. {
  576. int ret = -1;
  577. char *fname = NULL;
  578. /* Length of an address plus the sizeof the address tld (onion) which counts
  579. * the NUL terminated byte so we keep it for the "." and the newline. */
  580. char buf[HS_SERVICE_ADDR_LEN_BASE32 + sizeof(address_tld) + 1];
  581. tor_assert(service);
  582. tor_assert(fname_);
  583. /* Construct the full address with the onion tld and write the hostname file
  584. * to disk. */
  585. tor_snprintf(buf, sizeof(buf), "%s.%s\n", service->onion_address,
  586. address_tld);
  587. /* Notice here that we use the given "fname_". */
  588. fname = hs_path_from_filename(service->config.directory_path, fname_);
  589. if (write_str_to_file(fname, buf, 0) < 0) {
  590. log_warn(LD_REND, "Could not write onion address to hostname file %s",
  591. escaped(fname));
  592. goto end;
  593. }
  594. #ifndef _WIN32
  595. if (service->config.dir_group_readable) {
  596. /* Mode to 0640. */
  597. if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
  598. log_warn(LD_FS, "Unable to make onion service hostname file %s "
  599. "group-readable.", escaped(fname));
  600. }
  601. }
  602. #endif /* _WIN32 */
  603. /* Success. */
  604. ret = 0;
  605. end:
  606. tor_free(fname);
  607. return ret;
  608. }
  609. /* Load and/or generate private keys for the given service. On success, the
  610. * hostname file will be written to disk along with the master private key iff
  611. * the service is not configured for offline keys. Return 0 on success else -1
  612. * on failure. */
  613. static int
  614. load_service_keys(hs_service_t *service)
  615. {
  616. int ret = -1;
  617. char *fname = NULL;
  618. ed25519_keypair_t *kp;
  619. const hs_service_config_t *config;
  620. tor_assert(service);
  621. config = &service->config;
  622. /* Create and fix permission on service directory. We are about to write
  623. * files to that directory so make sure it exists and has the right
  624. * permissions. We do this here because at this stage we know that Tor is
  625. * actually running and the service we have has been validated. */
  626. if (BUG(hs_check_service_private_dir(get_options()->User,
  627. config->directory_path,
  628. config->dir_group_readable, 1) < 0)) {
  629. goto end;
  630. }
  631. /* Try to load the keys from file or generate it if not found. */
  632. fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
  633. /* Don't ask for key creation, we want to know if we were able to load it or
  634. * we had to generate it. Better logging! */
  635. kp = ed_key_init_from_file(fname, 0, LOG_INFO, NULL, 0, 0, 0, NULL);
  636. if (!kp) {
  637. log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
  638. /* We'll now try to generate the keys and for it we want the strongest
  639. * randomness for it. The keypair will be written in different files. */
  640. uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
  641. INIT_ED_KEY_SPLIT;
  642. kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
  643. NULL);
  644. if (!kp) {
  645. log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
  646. goto end;
  647. }
  648. }
  649. /* Copy loaded or generated keys to service object. */
  650. ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
  651. memcpy(&service->keys.identity_sk, &kp->seckey,
  652. sizeof(service->keys.identity_sk));
  653. /* This does a proper memory wipe. */
  654. ed25519_keypair_free(kp);
  655. /* Build onion address from the newly loaded keys. */
  656. tor_assert(service->config.version <= UINT8_MAX);
  657. hs_build_address(&service->keys.identity_pk,
  658. (uint8_t) service->config.version,
  659. service->onion_address);
  660. /* Write onion address to hostname file. */
  661. if (write_address_to_file(service, fname_hostname) < 0) {
  662. goto end;
  663. }
  664. /* Succes. */
  665. ret = 0;
  666. end:
  667. tor_free(fname);
  668. return ret;
  669. }
  670. /* Free a given service descriptor object and all key material is wiped. */
  671. static void
  672. service_descriptor_free(hs_service_descriptor_t *desc)
  673. {
  674. if (!desc) {
  675. return;
  676. }
  677. hs_descriptor_free(desc->desc);
  678. memwipe(&desc->signing_kp, 0, sizeof(desc->signing_kp));
  679. memwipe(&desc->blinded_kp, 0, sizeof(desc->blinded_kp));
  680. /* Cleanup all intro points. */
  681. digest256map_free(desc->intro_points.map, service_intro_point_free_);
  682. tor_free(desc);
  683. }
  684. /* Return a newly allocated service descriptor object. */
  685. static hs_service_descriptor_t *
  686. service_descriptor_new(void)
  687. {
  688. hs_service_descriptor_t *sdesc = tor_malloc_zero(sizeof(*sdesc));
  689. sdesc->desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  690. /* Initialize the intro points map. */
  691. sdesc->intro_points.map = digest256map_new();
  692. return sdesc;
  693. }
  694. #if 0
  695. /* Copy the descriptor link specifier object from src to dst. */
  696. static void
  697. link_specifier_copy(hs_desc_link_specifier_t *dst,
  698. const hs_desc_link_specifier_t *src)
  699. {
  700. tor_assert(dst);
  701. tor_assert(src);
  702. memcpy(dst, src, sizeof(hs_desc_link_specifier_t));
  703. }
  704. /* Using a given descriptor signing keypair signing_kp, a service intro point
  705. * object ip and the time now, setup the content of an already allocated
  706. * descriptor intro desc_ip.
  707. *
  708. * Return 0 on success else a negative value. */
  709. static int
  710. setup_desc_intro_point(const ed25519_keypair_t *signing_kp,
  711. const hs_service_intro_point_t *ip,
  712. time_t now, hs_desc_intro_point_t *desc_ip)
  713. {
  714. int ret = -1;
  715. time_t nearest_hour = now - (now % 3600);
  716. tor_assert(signing_kp);
  717. tor_assert(ip);
  718. tor_assert(desc_ip);
  719. /* Copy the onion key. */
  720. memcpy(&desc_ip->onion_key, &ip->onion_key, sizeof(desc_ip->onion_key));
  721. /* Key and certificate material. */
  722. desc_ip->auth_key_cert = tor_cert_create(signing_kp,
  723. CERT_TYPE_AUTH_HS_IP_KEY,
  724. &ip->auth_key_kp.pubkey,
  725. nearest_hour,
  726. HS_DESC_CERT_LIFETIME,
  727. CERT_FLAG_INCLUDE_SIGNING_KEY);
  728. if (desc_ip->auth_key_cert == NULL) {
  729. log_warn(LD_REND, "Unable to create intro point auth-key certificate");
  730. goto done;
  731. }
  732. /* Copy link specifier(s). */
  733. SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
  734. const hs_desc_link_specifier_t *, ls) {
  735. hs_desc_link_specifier_t *dup = tor_malloc_zero(sizeof(*dup));
  736. link_specifier_copy(dup, ls);
  737. smartlist_add(desc_ip->link_specifiers, dup);
  738. } SMARTLIST_FOREACH_END(ls);
  739. /* For a legacy intro point, we'll use an RSA/ed cross certificate. */
  740. if (ip->base.is_only_legacy) {
  741. desc_ip->legacy.key = crypto_pk_dup_key(ip->legacy_key);
  742. /* Create cross certification cert. */
  743. ssize_t cert_len = tor_make_rsa_ed25519_crosscert(
  744. &signing_kp->pubkey,
  745. desc_ip->legacy.key,
  746. nearest_hour + HS_DESC_CERT_LIFETIME,
  747. &desc_ip->legacy.cert.encoded);
  748. if (cert_len < 0) {
  749. log_warn(LD_REND, "Unable to create enc key legacy cross cert.");
  750. goto done;
  751. }
  752. desc_ip->legacy.cert.len = cert_len;
  753. }
  754. /* Encryption key and its cross certificate. */
  755. {
  756. ed25519_public_key_t ed25519_pubkey;
  757. /* Use the public curve25519 key. */
  758. memcpy(&desc_ip->enc_key, &ip->enc_key_kp.pubkey,
  759. sizeof(desc_ip->enc_key));
  760. /* The following can't fail. */
  761. ed25519_public_key_from_curve25519_public_key(&ed25519_pubkey,
  762. &ip->enc_key_kp.pubkey,
  763. 0);
  764. desc_ip->enc_key_cert = tor_cert_create(signing_kp,
  765. CERT_TYPE_CROSS_HS_IP_KEYS,
  766. &ed25519_pubkey, nearest_hour,
  767. HS_DESC_CERT_LIFETIME,
  768. CERT_FLAG_INCLUDE_SIGNING_KEY);
  769. if (desc_ip->enc_key_cert == NULL) {
  770. log_warn(LD_REND, "Unable to create enc key curve25519 cross cert.");
  771. goto done;
  772. }
  773. }
  774. /* Success. */
  775. ret = 0;
  776. done:
  777. return ret;
  778. }
  779. /* Using the given descriptor from the given service, build the descriptor
  780. * intro point list so we can then encode the descriptor for publication. This
  781. * function does not pick intro points, they have to be in the descriptor
  782. * current map. Cryptographic material (keys) must be initialized in the
  783. * descriptor for this function to make sense. */
  784. static void
  785. build_desc_intro_points(const hs_service_t *service,
  786. hs_service_descriptor_t *desc, time_t now)
  787. {
  788. hs_desc_encrypted_data_t *encrypted;
  789. tor_assert(service);
  790. tor_assert(desc);
  791. /* Ease our life. */
  792. encrypted = &desc->desc->encrypted_data;
  793. /* Cleanup intro points, we are about to set them from scratch. */
  794. hs_descriptor_free_intro_points(desc->desc);
  795. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  796. const hs_service_intro_point_t *, ip) {
  797. hs_desc_intro_point_t *desc_ip = hs_desc_intro_point_new();
  798. if (setup_desc_intro_point(&desc->signing_kp, ip, now, desc_ip) < 0) {
  799. hs_desc_intro_point_free(desc_ip);
  800. continue;
  801. }
  802. /* We have a valid descriptor intro point. Add it to the list. */
  803. smartlist_add(encrypted->intro_points, desc_ip);
  804. } DIGEST256MAP_FOREACH_END;
  805. }
  806. #endif /* build_desc_intro_points is disabled because not used */
  807. /* Populate the descriptor encrypted section fomr the given service object.
  808. * This will generate a valid list of introduction points that can be used
  809. * after for circuit creation. Return 0 on success else -1 on error. */
  810. static int
  811. build_service_desc_encrypted(const hs_service_t *service,
  812. hs_service_descriptor_t *desc)
  813. {
  814. hs_desc_encrypted_data_t *encrypted;
  815. tor_assert(service);
  816. tor_assert(desc);
  817. encrypted = &desc->desc->encrypted_data;
  818. encrypted->create2_ntor = 1;
  819. encrypted->single_onion_service = service->config.is_single_onion;
  820. /* Setup introduction points from what we have in the service. */
  821. if (encrypted->intro_points == NULL) {
  822. encrypted->intro_points = smartlist_new();
  823. }
  824. /* We do NOT build introduction point yet, we only do that once the circuit
  825. * have been opened. Until we have the right number of introduction points,
  826. * we do not encode anything in the descriptor. */
  827. /* XXX: Support client authorization (#20700). */
  828. encrypted->intro_auth_types = NULL;
  829. return 0;
  830. }
  831. /* Populare the descriptor plaintext section from the given service object.
  832. * The caller must make sure that the keys in the descriptors are valid that
  833. * is are non-zero. Return 0 on success else -1 on error. */
  834. static int
  835. build_service_desc_plaintext(const hs_service_t *service,
  836. hs_service_descriptor_t *desc, time_t now)
  837. {
  838. int ret = -1;
  839. hs_desc_plaintext_data_t *plaintext;
  840. tor_assert(service);
  841. tor_assert(desc);
  842. /* XXX: Use a "assert_desc_ok()" ? */
  843. tor_assert(!tor_mem_is_zero((char *) &desc->blinded_kp,
  844. sizeof(desc->blinded_kp)));
  845. tor_assert(!tor_mem_is_zero((char *) &desc->signing_kp,
  846. sizeof(desc->signing_kp)));
  847. /* Set the subcredential. */
  848. hs_get_subcredential(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
  849. desc->desc->subcredential);
  850. plaintext = &desc->desc->plaintext_data;
  851. plaintext->version = service->config.version;
  852. plaintext->lifetime_sec = HS_DESC_DEFAULT_LIFETIME;
  853. plaintext->signing_key_cert =
  854. tor_cert_create(&desc->blinded_kp, CERT_TYPE_SIGNING_HS_DESC,
  855. &desc->signing_kp.pubkey, now, HS_DESC_CERT_LIFETIME,
  856. CERT_FLAG_INCLUDE_SIGNING_KEY);
  857. if (plaintext->signing_key_cert == NULL) {
  858. log_warn(LD_REND, "Unable to create descriptor signing certificate for "
  859. "service %s",
  860. safe_str_client(service->onion_address));
  861. goto end;
  862. }
  863. /* Copy public key material to go in the descriptor. */
  864. ed25519_pubkey_copy(&plaintext->signing_pubkey, &desc->signing_kp.pubkey);
  865. ed25519_pubkey_copy(&plaintext->blinded_pubkey, &desc->blinded_kp.pubkey);
  866. /* Success. */
  867. ret = 0;
  868. end:
  869. return ret;
  870. }
  871. /* For the given service and descriptor object, create the key material which
  872. * is the blinded keypair and the descriptor signing keypair. Return 0 on
  873. * success else -1 on error where the generated keys MUST be ignored. */
  874. static int
  875. build_service_desc_keys(const hs_service_t *service,
  876. hs_service_descriptor_t *desc,
  877. uint64_t time_period_num)
  878. {
  879. int ret = 0;
  880. ed25519_keypair_t kp;
  881. tor_assert(desc);
  882. tor_assert(!tor_mem_is_zero((char *) &service->keys.identity_pk,
  883. ED25519_PUBKEY_LEN));
  884. /* XXX: Support offline key feature (#18098). */
  885. /* Copy the identity keys to the keypair so we can use it to create the
  886. * blinded key. */
  887. memcpy(&kp.pubkey, &service->keys.identity_pk, sizeof(kp.pubkey));
  888. memcpy(&kp.seckey, &service->keys.identity_sk, sizeof(kp.seckey));
  889. /* Build blinded keypair for this time period. */
  890. hs_build_blinded_keypair(&kp, NULL, 0, time_period_num, &desc->blinded_kp);
  891. /* Let's not keep too much traces of our keys in memory. */
  892. memwipe(&kp, 0, sizeof(kp));
  893. /* No need for extra strong, this is a temporary key only for this
  894. * descriptor. Nothing long term. */
  895. if (ed25519_keypair_generate(&desc->signing_kp, 0) < 0) {
  896. log_warn(LD_REND, "Can't generate descriptor signing keypair for "
  897. "service %s",
  898. safe_str_client(service->onion_address));
  899. ret = -1;
  900. }
  901. return ret;
  902. }
  903. /* Given a service and the current time, build a descriptor for the service.
  904. * This function does not pick introduction point, this needs to be done by
  905. * the update function. On success, desc_out will point to the newly allocated
  906. * descriptor object.
  907. *
  908. * This can error if we are unable to create keys or certificate. */
  909. static void
  910. build_service_descriptor(hs_service_t *service, time_t now,
  911. uint64_t time_period_num,
  912. hs_service_descriptor_t **desc_out)
  913. {
  914. char *encoded_desc;
  915. hs_service_descriptor_t *desc;
  916. tor_assert(service);
  917. tor_assert(desc_out);
  918. desc = service_descriptor_new();
  919. /* Create the needed keys so we can setup the descriptor content. */
  920. if (build_service_desc_keys(service, desc, time_period_num) < 0) {
  921. goto err;
  922. }
  923. /* Setup plaintext descriptor content. */
  924. if (build_service_desc_plaintext(service, desc, now) < 0) {
  925. goto err;
  926. }
  927. /* Setup encrypted descriptor content. */
  928. if (build_service_desc_encrypted(service, desc) < 0) {
  929. goto err;
  930. }
  931. /* Let's make sure that we've created a descriptor that can actually be
  932. * encoded properly. This function also checks if the encoded output is
  933. * decodable after. */
  934. if (BUG(hs_desc_encode_descriptor(desc->desc, &desc->signing_kp,
  935. &encoded_desc) < 0)) {
  936. goto err;
  937. }
  938. tor_free(encoded_desc);
  939. /* Assign newly built descriptor to the next slot. */
  940. *desc_out = desc;
  941. return;
  942. err:
  943. service_descriptor_free(desc);
  944. }
  945. /* Build descriptors for each service if needed. There are conditions to build
  946. * a descriptor which are details in the function. */
  947. static void
  948. build_all_descriptors(time_t now)
  949. {
  950. FOR_EACH_SERVICE_BEGIN(service) {
  951. if (service->desc_current == NULL) {
  952. /* This means we just booted up because else this descriptor will never
  953. * be NULL as it should always point to the descriptor that was in
  954. * desc_next after rotation. */
  955. build_service_descriptor(service, now, hs_get_time_period_num(now),
  956. &service->desc_current);
  957. log_info(LD_REND, "Hidden service %s current descriptor successfully "
  958. "built. Now scheduled for upload.",
  959. safe_str_client(service->onion_address));
  960. }
  961. /* A next descriptor to NULL indicate that we need to build a fresh one if
  962. * we are in the overlap period for the _next_ time period since it means
  963. * we either just booted or we just rotated our descriptors. */
  964. if (hs_overlap_mode_is_active(NULL, now) && service->desc_next == NULL) {
  965. build_service_descriptor(service, now, hs_get_next_time_period_num(now),
  966. &service->desc_next);
  967. log_info(LD_REND, "Hidden service %s next descriptor successfully "
  968. "built. Now scheduled for upload.",
  969. safe_str_client(service->onion_address));
  970. }
  971. } FOR_EACH_DESCRIPTOR_END;
  972. }
  973. /* Randomly pick a node to become an introduction point but not present in the
  974. * given exclude_nodes list. The chosen node is put in the exclude list
  975. * regardless of success or not because in case of failure, the node is simply
  976. * unsusable from that point on. If direct_conn is set, try to pick a node
  977. * that our local firewall/policy allows to directly connect to and if not,
  978. * fallback to a normal 3-hop node. Return a newly allocated service intro
  979. * point ready to be used for encoding. NULL on error. */
  980. static hs_service_intro_point_t *
  981. pick_intro_point(unsigned int direct_conn, smartlist_t *exclude_nodes)
  982. {
  983. const node_t *node;
  984. extend_info_t *info = NULL;
  985. hs_service_intro_point_t *ip = NULL;
  986. /* Normal 3-hop introduction point flags. */
  987. router_crn_flags_t flags = CRN_NEED_UPTIME | CRN_NEED_DESC;
  988. /* Single onion flags. */
  989. router_crn_flags_t direct_flags = flags | CRN_PREF_ADDR | CRN_DIRECT_CONN;
  990. node = router_choose_random_node(exclude_nodes, get_options()->ExcludeNodes,
  991. direct_conn ? direct_flags : flags);
  992. if (node == NULL && direct_conn) {
  993. /* Unable to find a node for direct connection, let's fall back to a
  994. * normal 3-hop node. */
  995. node = router_choose_random_node(exclude_nodes,
  996. get_options()->ExcludeNodes, flags);
  997. }
  998. if (!node) {
  999. goto err;
  1000. }
  1001. /* We have a suitable node, add it to the exclude list. We do this *before*
  1002. * we can validate the extend information because even in case of failure,
  1003. * we don't want to use that node anymore. */
  1004. smartlist_add(exclude_nodes, (void *) node);
  1005. /* We do this to ease our life but also this call makes appropriate checks
  1006. * of the node object such as validating ntor support for instance. */
  1007. info = extend_info_from_node(node, direct_conn);
  1008. if (BUG(info == NULL)) {
  1009. goto err;
  1010. }
  1011. /* Create our objects and populate them with the node information. */
  1012. ip = service_intro_point_new(info, !node_supports_ed25519_hs_intro(node));
  1013. if (ip == NULL) {
  1014. goto err;
  1015. }
  1016. extend_info_free(info);
  1017. return ip;
  1018. err:
  1019. service_intro_point_free(ip);
  1020. extend_info_free(info);
  1021. return NULL;
  1022. }
  1023. /* For a given descriptor from the given service, pick any needed intro points
  1024. * and update the current map with those newly picked intro points. Return the
  1025. * number node that might have been added to the descriptor current map. */
  1026. static unsigned int
  1027. pick_needed_intro_points(hs_service_t *service,
  1028. hs_service_descriptor_t *desc)
  1029. {
  1030. int i = 0, num_needed_ip;
  1031. smartlist_t *exclude_nodes = smartlist_new();
  1032. tor_assert(service);
  1033. tor_assert(desc);
  1034. /* Compute how many intro points we actually need to open. */
  1035. num_needed_ip = service->config.num_intro_points -
  1036. digest256map_size(desc->intro_points.map);
  1037. if (BUG(num_needed_ip < 0)) {
  1038. /* Let's not make tor freak out here and just skip this. */
  1039. goto done;
  1040. }
  1041. /* We want to end up with config.num_intro_points intro points, but if we
  1042. * have no intro points at all (chances are they all cycled or we are
  1043. * starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits and use the
  1044. * first config.num_intro_points that complete. See proposal #155, section 4
  1045. * for the rationale of this which is purely for performance.
  1046. *
  1047. * The ones after the first config.num_intro_points will be converted to
  1048. * 'General' internal circuits and then we'll drop them from the list of
  1049. * intro points. */
  1050. if (digest256map_size(desc->intro_points.map) == 0) {
  1051. /* XXX: Should a consensus param control that value? */
  1052. num_needed_ip += NUM_INTRO_POINTS_EXTRA;
  1053. }
  1054. /* Build an exclude list of nodes of our intro point(s). The expiring intro
  1055. * points are OK to pick again because this is afterall a concept of round
  1056. * robin so they are considered valid nodes to pick again. */
  1057. DIGEST256MAP_FOREACH(desc->intro_points.map, key,
  1058. hs_service_intro_point_t *, ip) {
  1059. smartlist_add(exclude_nodes, (void *) get_node_from_intro_point(ip));
  1060. } DIGEST256MAP_FOREACH_END;
  1061. for (i = 0; i < num_needed_ip; i++) {
  1062. hs_service_intro_point_t *ip;
  1063. /* This function will add the picked intro point node to the exclude nodes
  1064. * list so we don't pick the same one at the next iteration. */
  1065. ip = pick_intro_point(service->config.is_single_onion, exclude_nodes);
  1066. if (ip == NULL) {
  1067. /* If we end up unable to pick an introduction point it is because we
  1068. * can't find suitable node and calling this again is highly unlikely to
  1069. * give us a valid node all of the sudden. */
  1070. log_info(LD_REND, "Unable to find a suitable node to be an "
  1071. "introduction point for service %s.",
  1072. safe_str_client(service->onion_address));
  1073. goto done;
  1074. }
  1075. /* Valid intro point object, add it to the descriptor current map. */
  1076. service_intro_point_add(desc->intro_points.map, ip);
  1077. }
  1078. /* Success. */
  1079. done:
  1080. /* We don't have ownership of the node_t object in this list. */
  1081. smartlist_free(exclude_nodes);
  1082. return i;
  1083. }
  1084. /* Update the given descriptor from the given service. The possible update
  1085. * actions includes:
  1086. * - Picking missing intro points if needed.
  1087. * - Incrementing the revision counter if needed.
  1088. */
  1089. static void
  1090. update_service_descriptor(hs_service_t *service,
  1091. hs_service_descriptor_t *desc, time_t now)
  1092. {
  1093. unsigned int num_intro_points;
  1094. tor_assert(service);
  1095. tor_assert(desc);
  1096. tor_assert(desc->desc);
  1097. num_intro_points = digest256map_size(desc->intro_points.map);
  1098. /* Pick any missing introduction point(s). */
  1099. if (num_intro_points < service->config.num_intro_points) {
  1100. unsigned int num_new_intro_points = pick_needed_intro_points(service,
  1101. desc);
  1102. if (num_new_intro_points != 0) {
  1103. log_info(LD_REND, "Service %s just picked %u intro points and wanted "
  1104. "%u. It currently has %d intro points. "
  1105. "Launching ESTABLISH_INTRO circuit shortly.",
  1106. safe_str_client(service->onion_address),
  1107. num_new_intro_points,
  1108. service->config.num_intro_points - num_intro_points,
  1109. num_intro_points);
  1110. /* We'll build those introduction point into the descriptor once we have
  1111. * confirmation that the circuits are opened and ready. However,
  1112. * indicate that this descriptor should be uploaded from now on. */
  1113. desc->next_upload_time = now;
  1114. }
  1115. }
  1116. }
  1117. /* Update descriptors for each service if needed. */
  1118. static void
  1119. update_all_descriptors(time_t now)
  1120. {
  1121. FOR_EACH_SERVICE_BEGIN(service) {
  1122. /* We'll try to update each descriptor that is if certain conditions apply
  1123. * in order for the descriptor to be updated. */
  1124. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1125. update_service_descriptor(service, desc, now);
  1126. } FOR_EACH_DESCRIPTOR_END;
  1127. } FOR_EACH_SERVICE_END;
  1128. }
  1129. /* Return true iff the given intro point has expired that is it has been used
  1130. * for too long or we've reached our max seen INTRODUCE2 cell. */
  1131. static int
  1132. intro_point_should_expire(const hs_service_intro_point_t *ip,
  1133. time_t now)
  1134. {
  1135. tor_assert(ip);
  1136. if (ip->introduce2_count >= ip->introduce2_max) {
  1137. goto expired;
  1138. }
  1139. if (ip->time_to_expire <= now) {
  1140. goto expired;
  1141. }
  1142. /* Not expiring. */
  1143. return 0;
  1144. expired:
  1145. return 1;
  1146. }
  1147. /* Go over the given set of intro points for each service and remove any
  1148. * invalid ones. The conditions for removal are:
  1149. *
  1150. * - The node doesn't exists anymore (not in consensus)
  1151. * OR
  1152. * - The intro point maximum circuit retry count has been reached and no
  1153. * circuit can be found associated with it.
  1154. * OR
  1155. * - The intro point has expired and we should pick a new one.
  1156. *
  1157. * If an intro point is removed, the circuit (if any) is immediately close.
  1158. * If a circuit can't be found, the intro point is kept if it hasn't reached
  1159. * its maximum circuit retry value and thus should be retried. */
  1160. static void
  1161. cleanup_intro_points(hs_service_t *service, time_t now)
  1162. {
  1163. tor_assert(service);
  1164. /* For both descriptors, cleanup the intro points. */
  1165. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1166. /* Go over the current intro points we have, make sure they are still
  1167. * valid and remove any of them that aren't. */
  1168. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1169. hs_service_intro_point_t *, ip) {
  1170. const node_t *node = get_node_from_intro_point(ip);
  1171. origin_circuit_t *ocirc = get_intro_circuit(ip);
  1172. int has_expired = intro_point_should_expire(ip, now);
  1173. /* We cleanup an intro point if it has expired or if we do not know the
  1174. * node_t anymore (removed from our latest consensus) or if we've
  1175. * reached the maximum number of retry with a non existing circuit. */
  1176. if (has_expired || node == NULL ||
  1177. (ocirc == NULL &&
  1178. ip->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES)) {
  1179. MAP_DEL_CURRENT(key);
  1180. service_intro_point_free(ip);
  1181. /* XXX: Legacy code does NOT do that, it keeps the circuit open until
  1182. * a new descriptor is uploaded and then closed all expiring intro
  1183. * point circuit. Here, we close immediately and because we just
  1184. * discarded the intro point, a new one will be selected, a new
  1185. * descriptor created and uploaded. There is no difference to an
  1186. * attacker between the timing of a new consensus and intro point
  1187. * rotation (possibly?). */
  1188. if (ocirc) {
  1189. /* After this, no new cells will be handled on the circuit. */
  1190. circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
  1191. }
  1192. continue;
  1193. }
  1194. if (ocirc == NULL) {
  1195. /* Circuit disappeared so make sure the intro point is updated. By
  1196. * keeping the object in the descriptor, we'll be able to retry. */
  1197. ip->circuit_established = 0;
  1198. }
  1199. } DIGEST256MAP_FOREACH_END;
  1200. } FOR_EACH_DESCRIPTOR_END;
  1201. }
  1202. /** We just entered overlap period and we need to rotate our <b>service</b>
  1203. * descriptors */
  1204. static void
  1205. rotate_service_descriptors(hs_service_t *service)
  1206. {
  1207. if (service->desc_current) {
  1208. /* Close all IP circuits for the descriptor. */
  1209. close_intro_circuits(&service->desc_current->intro_points);
  1210. /* We don't need this one anymore, we won't serve any clients coming with
  1211. * this service descriptor. */
  1212. service_descriptor_free(service->desc_current);
  1213. }
  1214. /* The next one become the current one and emptying the next will trigger
  1215. * a descriptor creation for it. */
  1216. service->desc_current = service->desc_next;
  1217. service->desc_next = NULL;
  1218. }
  1219. /* Rotate descriptors for each service if needed. If we are just entering
  1220. * the overlap period, rotate them that is point the previous descriptor to
  1221. * the current and cleanup the previous one. A non existing current
  1222. * descriptor will trigger a descriptor build for the next time period. */
  1223. static void
  1224. rotate_all_descriptors(time_t now)
  1225. {
  1226. FOR_EACH_SERVICE_BEGIN(service) {
  1227. /* We are _not_ in the overlap period so skip rotation. */
  1228. if (!hs_overlap_mode_is_active(NULL, now)) {
  1229. service->state.in_overlap_period = 0;
  1230. continue;
  1231. }
  1232. /* We've entered the overlap period already so skip rotation. */
  1233. if (service->state.in_overlap_period) {
  1234. continue;
  1235. }
  1236. /* It's the first time the service encounters the overlap period so flag
  1237. * it in order to make sure we don't rotate at next check. */
  1238. service->state.in_overlap_period = 1;
  1239. /* If we have a next descriptor lined up, rotate the descriptors so that it
  1240. * becomes current. */
  1241. if (service->desc_next) {
  1242. rotate_service_descriptors(service);
  1243. }
  1244. log_info(LD_REND, "We've just entered the overlap period. Service %s "
  1245. "descriptors have been rotated!",
  1246. safe_str_client(service->onion_address));
  1247. } FOR_EACH_SERVICE_END;
  1248. }
  1249. /* Scheduled event run from the main loop. Make sure all our services are up
  1250. * to date and ready for the other scheduled events. This includes looking at
  1251. * the introduction points status and descriptor rotation time. */
  1252. static void
  1253. run_housekeeping_event(time_t now)
  1254. {
  1255. /* Note that nothing here opens circuit(s) nor uploads descriptor(s). We are
  1256. * simply moving things around or removing uneeded elements. */
  1257. FOR_EACH_SERVICE_BEGIN(service) {
  1258. /* Cleanup invalid intro points from the service descriptor. */
  1259. cleanup_intro_points(service, now);
  1260. /* At this point, the service is now ready to go through the scheduled
  1261. * events guaranteeing a valid state. Intro points might be missing from
  1262. * the descriptors after the cleanup but the update/build process will
  1263. * make sure we pick those missing ones. */
  1264. } FOR_EACH_SERVICE_END;
  1265. }
  1266. /* Scheduled event run from the main loop. Make sure all descriptors are up to
  1267. * date. Once this returns, each service descriptor needs to be considered for
  1268. * new introduction circuits and then for upload. */
  1269. static void
  1270. run_build_descriptor_event(time_t now)
  1271. {
  1272. /* For v2 services, this step happens in the upload event. */
  1273. /* Run v3+ events. */
  1274. /* We start by rotating the descriptors only if needed. */
  1275. rotate_all_descriptors(now);
  1276. /* Then, we'll try to build new descriptors that we might need. The
  1277. * condition is that the next descriptor is non existing because it has
  1278. * been rotated or we just started up. */
  1279. build_all_descriptors(now);
  1280. /* Finally, we'll check if we should update the descriptors. Missing
  1281. * introduction points will be picked in this function which is useful for
  1282. * newly built descriptors. */
  1283. update_all_descriptors(now);
  1284. }
  1285. /* For the given service, launch any intro point circuits that could be
  1286. * needed. This considers every descriptor of the service. */
  1287. static void
  1288. launch_intro_point_circuits(hs_service_t *service, time_t now)
  1289. {
  1290. tor_assert(service);
  1291. /* For both descriptors, try to launch any missing introduction point
  1292. * circuits using the current map. */
  1293. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1294. /* Keep a ref on if we need a direct connection. We use this often. */
  1295. unsigned int direct_conn = service->config.is_single_onion;
  1296. DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
  1297. hs_service_intro_point_t *, ip) {
  1298. extend_info_t *ei;
  1299. /* Skip the intro point that already has an existing circuit
  1300. * (established or not). */
  1301. if (get_intro_circuit(ip)) {
  1302. continue;
  1303. }
  1304. ei = get_extend_info_from_intro_point(ip, direct_conn);
  1305. if (ei == NULL) {
  1306. if (!direct_conn) {
  1307. /* In case of a multi-hop connection, it should never happen that we
  1308. * can't get the extend info from the node. Avoid connection and
  1309. * remove intro point from descriptor in order to recover from this
  1310. * potential bug. */
  1311. tor_assert_nonfatal(ei);
  1312. }
  1313. MAP_DEL_CURRENT(key);
  1314. service_intro_point_free(ip);
  1315. continue;
  1316. }
  1317. /* Launch a circuit to the intro point. */
  1318. ip->circuit_retries++;
  1319. if (hs_circ_launch_intro_point(service, ip, ei, now) < 0) {
  1320. log_warn(LD_REND, "Unable to launch intro circuit to node %s "
  1321. "for service %s.",
  1322. safe_str_client(extend_info_describe(ei)),
  1323. safe_str_client(service->onion_address));
  1324. /* Intro point will be retried if possible after this. */
  1325. }
  1326. extend_info_free(ei);
  1327. } DIGEST256MAP_FOREACH_END;
  1328. } FOR_EACH_DESCRIPTOR_END;
  1329. }
  1330. /* Don't try to build more than this many circuits before giving up for a
  1331. * while. Dynamically calculated based on the configured number of intro
  1332. * points for the given service and how many descriptor exists. The default
  1333. * use case of 3 introduction points and two descriptors will allow 28
  1334. * circuits for a retry period (((3 + 2) + (3 * 3)) * 2). */
  1335. static unsigned int
  1336. get_max_intro_circ_per_period(const hs_service_t *service)
  1337. {
  1338. unsigned int count = 0;
  1339. unsigned int multiplier = 0;
  1340. unsigned int num_wanted_ip;
  1341. tor_assert(service);
  1342. tor_assert(service->config.num_intro_points <=
  1343. HS_CONFIG_V3_MAX_INTRO_POINTS);
  1344. num_wanted_ip = service->config.num_intro_points;
  1345. /* The calculation is as follow. We have a number of intro points that we
  1346. * want configured as a torrc option (num_intro_points). We then add an
  1347. * extra value so we can launch multiple circuits at once and pick the
  1348. * quickest ones. For instance, we want 3 intros, we add 2 extra so we'll
  1349. * pick 5 intros and launch 5 circuits. */
  1350. count += (num_wanted_ip + NUM_INTRO_POINTS_EXTRA);
  1351. /* Then we add the number of retries that is possible to do for each intro
  1352. * point. If we want 3 intros, we'll allow 3 times the number of possible
  1353. * retry. */
  1354. count += (num_wanted_ip * MAX_INTRO_POINT_CIRCUIT_RETRIES);
  1355. /* Then, we multiply by a factor of 2 if we have both descriptor or 0 if we
  1356. * have none. */
  1357. multiplier += (service->desc_current) ? 1 : 0;
  1358. multiplier += (service->desc_next) ? 1 : 0;
  1359. return (count * multiplier);
  1360. }
  1361. /* For the given service, return 1 if the service is allowed to launch more
  1362. * introduction circuits else 0 if the maximum has been reached for the retry
  1363. * period of INTRO_CIRC_RETRY_PERIOD. */
  1364. static int
  1365. can_service_launch_intro_circuit(hs_service_t *service, time_t now)
  1366. {
  1367. tor_assert(service);
  1368. /* Consider the intro circuit retry period of the service. */
  1369. if (now > (service->state.intro_circ_retry_started_time +
  1370. INTRO_CIRC_RETRY_PERIOD)) {
  1371. service->state.intro_circ_retry_started_time = now;
  1372. service->state.num_intro_circ_launched = 0;
  1373. goto allow;
  1374. }
  1375. /* Check if we can still launch more circuits in this period. */
  1376. if (service->state.num_intro_circ_launched <=
  1377. get_max_intro_circ_per_period(service)) {
  1378. goto allow;
  1379. }
  1380. /* Rate limit log that we've reached our circuit creation limit. */
  1381. {
  1382. char *msg;
  1383. time_t elapsed_time = now - service->state.intro_circ_retry_started_time;
  1384. static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
  1385. if ((msg = rate_limit_log(&rlimit, now))) {
  1386. log_info(LD_REND, "Hidden service %s exceeded its circuit launch limit "
  1387. "of %u per %d seconds. It launched %u circuits in "
  1388. "the last %ld seconds. Will retry in %ld seconds.",
  1389. safe_str_client(service->onion_address),
  1390. get_max_intro_circ_per_period(service),
  1391. INTRO_CIRC_RETRY_PERIOD,
  1392. service->state.num_intro_circ_launched, elapsed_time,
  1393. INTRO_CIRC_RETRY_PERIOD - elapsed_time);
  1394. tor_free(msg);
  1395. }
  1396. }
  1397. /* Not allow. */
  1398. return 0;
  1399. allow:
  1400. return 1;
  1401. }
  1402. /* Scheduled event run from the main loop. Make sure we have all the circuits
  1403. * we need for each service. */
  1404. static void
  1405. run_build_circuit_event(time_t now)
  1406. {
  1407. /* Make sure we can actually have enough information or able to build
  1408. * internal circuits as required by services. */
  1409. if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN ||
  1410. !have_completed_a_circuit()) {
  1411. return;
  1412. }
  1413. /* Run v2 check. */
  1414. if (num_rend_services() > 0) {
  1415. rend_consider_services_intro_points(now);
  1416. }
  1417. /* Run v3+ check. */
  1418. FOR_EACH_SERVICE_BEGIN(service) {
  1419. /* For introduction circuit, we need to make sure we don't stress too much
  1420. * circuit creation so make sure this service is respecting that limit. */
  1421. if (can_service_launch_intro_circuit(service, now)) {
  1422. /* Launch intro point circuits if needed. */
  1423. launch_intro_point_circuits(service, now);
  1424. /* Once the circuits have opened, we'll make sure to update the
  1425. * descriptor intro point list and cleanup any extraneous. */
  1426. }
  1427. } FOR_EACH_SERVICE_END;
  1428. }
  1429. /* Scheduled event run from the main loop. Try to upload the descriptor for
  1430. * each service. */
  1431. static void
  1432. run_upload_descriptor_event(time_t now)
  1433. {
  1434. /* v2 services use the same function for descriptor creation and upload so
  1435. * we do everything here because the intro circuits were checked before. */
  1436. if (num_rend_services() > 0) {
  1437. rend_consider_services_upload(now);
  1438. rend_consider_descriptor_republication();
  1439. }
  1440. /* Run v3+ check. */
  1441. FOR_EACH_SERVICE_BEGIN(service) {
  1442. /* XXX: Upload if needed the descriptor(s). Update next upload time. */
  1443. (void) service;
  1444. } FOR_EACH_SERVICE_END;
  1445. }
  1446. /* ========== */
  1447. /* Public API */
  1448. /* ========== */
  1449. /* Load and/or generate keys for all onion services including the client
  1450. * authorization if any. Return 0 on success, -1 on failure. */
  1451. int
  1452. hs_service_load_all_keys(void)
  1453. {
  1454. /* Load v2 service keys if we have v2. */
  1455. if (num_rend_services() != 0) {
  1456. if (rend_service_load_all_keys(NULL) < 0) {
  1457. goto err;
  1458. }
  1459. }
  1460. /* Load or/and generate them for v3+. */
  1461. SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
  1462. /* Ignore ephemeral service, they already have their keys set. */
  1463. if (service->config.is_ephemeral) {
  1464. continue;
  1465. }
  1466. log_info(LD_REND, "Loading v3 onion service keys from %s",
  1467. service_escaped_dir(service));
  1468. if (load_service_keys(service) < 0) {
  1469. goto err;
  1470. }
  1471. /* XXX: Load/Generate client authorization keys. (#20700) */
  1472. } SMARTLIST_FOREACH_END(service);
  1473. /* Final step, the staging list contains service in a quiescent state that
  1474. * is ready to be used. Register them to the global map. Once this is over,
  1475. * the staging list will be cleaned up. */
  1476. register_all_services();
  1477. /* All keys have been loaded successfully. */
  1478. return 0;
  1479. err:
  1480. return -1;
  1481. }
  1482. /* Put all service object in the given service list. After this, the caller
  1483. * looses ownership of every elements in the list and responsible to free the
  1484. * list pointer. */
  1485. void
  1486. hs_service_stage_services(const smartlist_t *service_list)
  1487. {
  1488. tor_assert(service_list);
  1489. /* This list is freed at registration time but this function can be called
  1490. * multiple time. */
  1491. if (hs_service_staging_list == NULL) {
  1492. hs_service_staging_list = smartlist_new();
  1493. }
  1494. /* Add all service object to our staging list. Caller is responsible for
  1495. * freeing the service_list. */
  1496. smartlist_add_all(hs_service_staging_list, service_list);
  1497. }
  1498. /* Allocate and initilize a service object. The service configuration will
  1499. * contain the default values. Return the newly allocated object pointer. This
  1500. * function can't fail. */
  1501. hs_service_t *
  1502. hs_service_new(const or_options_t *options)
  1503. {
  1504. hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
  1505. /* Set default configuration value. */
  1506. set_service_default_config(&service->config, options);
  1507. /* Set the default service version. */
  1508. service->config.version = HS_SERVICE_DEFAULT_VERSION;
  1509. return service;
  1510. }
  1511. /* Free the given <b>service</b> object and all its content. This function
  1512. * also takes care of wiping service keys from memory. It is safe to pass a
  1513. * NULL pointer. */
  1514. void
  1515. hs_service_free(hs_service_t *service)
  1516. {
  1517. if (service == NULL) {
  1518. return;
  1519. }
  1520. /* Free descriptors. Go over both descriptor with this loop. */
  1521. FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
  1522. service_descriptor_free(desc);
  1523. } FOR_EACH_DESCRIPTOR_END;
  1524. /* Free service configuration. */
  1525. service_clear_config(&service->config);
  1526. /* Wipe service keys. */
  1527. memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
  1528. tor_free(service);
  1529. }
  1530. /* Periodic callback. Entry point from the main loop to the HS service
  1531. * subsystem. This is call every second. This is skipped if tor can't build a
  1532. * circuit or the network is disabled. */
  1533. void
  1534. hs_service_run_scheduled_events(time_t now)
  1535. {
  1536. /* First thing we'll do here is to make sure our services are in a
  1537. * quiescent state for the scheduled events. */
  1538. run_housekeeping_event(now);
  1539. /* Order matters here. We first make sure the descriptor object for each
  1540. * service contains the latest data. Once done, we check if we need to open
  1541. * new introduction circuit. Finally, we try to upload the descriptor for
  1542. * each service. */
  1543. /* Make sure descriptors are up to date. */
  1544. run_build_descriptor_event(now);
  1545. /* Make sure services have enough circuits. */
  1546. run_build_circuit_event(now);
  1547. /* Upload the descriptors if needed/possible. */
  1548. run_upload_descriptor_event(now);
  1549. }
  1550. /* Initialize the service HS subsystem. */
  1551. void
  1552. hs_service_init(void)
  1553. {
  1554. /* Should never be called twice. */
  1555. tor_assert(!hs_service_map);
  1556. tor_assert(!hs_service_staging_list);
  1557. /* v2 specific. */
  1558. rend_service_init();
  1559. hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
  1560. HT_INIT(hs_service_ht, hs_service_map);
  1561. hs_service_staging_list = smartlist_new();
  1562. }
  1563. /* Release all global storage of the hidden service subsystem. */
  1564. void
  1565. hs_service_free_all(void)
  1566. {
  1567. rend_service_free_all();
  1568. service_free_all();
  1569. }
  1570. /* XXX We don't currently use these functions, apart from generating unittest
  1571. data. When we start implementing the service-side support for prop224 we
  1572. should revisit these functions and use them. */
  1573. /** Given an ESTABLISH_INTRO <b>cell</b>, encode it and place its payload in
  1574. * <b>buf_out</b> which has size <b>buf_out_len</b>. Return the number of
  1575. * bytes written, or a negative integer if there was an error. */
  1576. ssize_t
  1577. get_establish_intro_payload(uint8_t *buf_out, size_t buf_out_len,
  1578. const trn_cell_establish_intro_t *cell)
  1579. {
  1580. ssize_t bytes_used = 0;
  1581. if (buf_out_len < RELAY_PAYLOAD_SIZE) {
  1582. return -1;
  1583. }
  1584. bytes_used = trn_cell_establish_intro_encode(buf_out, buf_out_len,
  1585. cell);
  1586. return bytes_used;
  1587. }
  1588. /* Set the cell extensions of <b>cell</b>. */
  1589. static void
  1590. set_trn_cell_extensions(trn_cell_establish_intro_t *cell)
  1591. {
  1592. trn_cell_extension_t *trn_cell_extensions = trn_cell_extension_new();
  1593. /* For now, we don't use extensions at all. */
  1594. trn_cell_extensions->num = 0; /* It's already zeroed, but be explicit. */
  1595. trn_cell_establish_intro_set_extensions(cell, trn_cell_extensions);
  1596. }
  1597. /** Given the circuit handshake info in <b>circuit_key_material</b>, create and
  1598. * return an ESTABLISH_INTRO cell. Return NULL if something went wrong. The
  1599. * returned cell is allocated on the heap and it's the responsibility of the
  1600. * caller to free it. */
  1601. trn_cell_establish_intro_t *
  1602. generate_establish_intro_cell(const uint8_t *circuit_key_material,
  1603. size_t circuit_key_material_len)
  1604. {
  1605. trn_cell_establish_intro_t *cell = NULL;
  1606. ssize_t encoded_len;
  1607. log_warn(LD_GENERAL,
  1608. "Generating ESTABLISH_INTRO cell (key_material_len: %u)",
  1609. (unsigned) circuit_key_material_len);
  1610. /* Generate short-term keypair for use in ESTABLISH_INTRO */
  1611. ed25519_keypair_t key_struct;
  1612. if (ed25519_keypair_generate(&key_struct, 0) < 0) {
  1613. goto err;
  1614. }
  1615. cell = trn_cell_establish_intro_new();
  1616. /* Set AUTH_KEY_TYPE: 2 means ed25519 */
  1617. trn_cell_establish_intro_set_auth_key_type(cell,
  1618. HS_INTRO_AUTH_KEY_TYPE_ED25519);
  1619. /* Set AUTH_KEY_LEN field */
  1620. /* Must also set byte-length of AUTH_KEY to match */
  1621. int auth_key_len = ED25519_PUBKEY_LEN;
  1622. trn_cell_establish_intro_set_auth_key_len(cell, auth_key_len);
  1623. trn_cell_establish_intro_setlen_auth_key(cell, auth_key_len);
  1624. /* Set AUTH_KEY field */
  1625. uint8_t *auth_key_ptr = trn_cell_establish_intro_getarray_auth_key(cell);
  1626. memcpy(auth_key_ptr, key_struct.pubkey.pubkey, auth_key_len);
  1627. /* No cell extensions needed */
  1628. set_trn_cell_extensions(cell);
  1629. /* Set signature size.
  1630. We need to do this up here, because _encode() needs it and we need to call
  1631. _encode() to calculate the MAC and signature.
  1632. */
  1633. int sig_len = ED25519_SIG_LEN;
  1634. trn_cell_establish_intro_set_sig_len(cell, sig_len);
  1635. trn_cell_establish_intro_setlen_sig(cell, sig_len);
  1636. /* XXX How to make this process easier and nicer? */
  1637. /* Calculate the cell MAC (aka HANDSHAKE_AUTH). */
  1638. {
  1639. /* To calculate HANDSHAKE_AUTH, we dump the cell in bytes, and then derive
  1640. the MAC from it. */
  1641. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  1642. uint8_t mac[TRUNNEL_SHA3_256_LEN];
  1643. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  1644. sizeof(cell_bytes_tmp),
  1645. cell);
  1646. if (encoded_len < 0) {
  1647. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell.");
  1648. goto err;
  1649. }
  1650. /* sanity check */
  1651. tor_assert(encoded_len > ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN);
  1652. /* Calculate MAC of all fields before HANDSHAKE_AUTH */
  1653. crypto_mac_sha3_256(mac, sizeof(mac),
  1654. circuit_key_material, circuit_key_material_len,
  1655. cell_bytes_tmp,
  1656. encoded_len -
  1657. (ED25519_SIG_LEN + 2 + TRUNNEL_SHA3_256_LEN));
  1658. /* Write the MAC to the cell */
  1659. uint8_t *handshake_ptr =
  1660. trn_cell_establish_intro_getarray_handshake_mac(cell);
  1661. memcpy(handshake_ptr, mac, sizeof(mac));
  1662. }
  1663. /* Calculate the cell signature */
  1664. {
  1665. /* To calculate the sig we follow the same procedure as above. We first
  1666. dump the cell up to the sig, and then calculate the sig */
  1667. uint8_t cell_bytes_tmp[RELAY_PAYLOAD_SIZE] = {0};
  1668. ed25519_signature_t sig;
  1669. encoded_len = trn_cell_establish_intro_encode(cell_bytes_tmp,
  1670. sizeof(cell_bytes_tmp),
  1671. cell);
  1672. if (encoded_len < 0) {
  1673. log_warn(LD_OR, "Unable to pre-encode ESTABLISH_INTRO cell (2).");
  1674. goto err;
  1675. }
  1676. tor_assert(encoded_len > ED25519_SIG_LEN);
  1677. if (ed25519_sign_prefixed(&sig,
  1678. cell_bytes_tmp,
  1679. encoded_len -
  1680. (ED25519_SIG_LEN + sizeof(cell->sig_len)),
  1681. ESTABLISH_INTRO_SIG_PREFIX,
  1682. &key_struct)) {
  1683. log_warn(LD_BUG, "Unable to gen signature for ESTABLISH_INTRO cell.");
  1684. goto err;
  1685. }
  1686. /* And write the signature to the cell */
  1687. uint8_t *sig_ptr = trn_cell_establish_intro_getarray_sig(cell);
  1688. memcpy(sig_ptr, sig.sig, sig_len);
  1689. }
  1690. /* We are done! Return the cell! */
  1691. return cell;
  1692. err:
  1693. trn_cell_establish_intro_free(cell);
  1694. return NULL;
  1695. }
  1696. #ifdef TOR_UNIT_TESTS
  1697. /* Return the global service map size. Only used by unit test. */
  1698. STATIC unsigned int
  1699. get_hs_service_map_size(void)
  1700. {
  1701. return HT_SIZE(hs_service_map);
  1702. }
  1703. /* Return the staging list size. Only used by unit test. */
  1704. STATIC int
  1705. get_hs_service_staging_list_size(void)
  1706. {
  1707. return smartlist_len(hs_service_staging_list);
  1708. }
  1709. STATIC hs_service_ht *
  1710. get_hs_service_map(void)
  1711. {
  1712. return hs_service_map;
  1713. }
  1714. STATIC hs_service_t *
  1715. get_first_service(void)
  1716. {
  1717. hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
  1718. if (obj == NULL) {
  1719. return NULL;
  1720. }
  1721. return *obj;
  1722. }
  1723. #endif /* TOR_UNIT_TESTS */