hs_service.c 82 KB

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