GatekeeperService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using System.Text.RegularExpressions;
  32. using OpenSim.Framework;
  33. using OpenSim.Services.Interfaces;
  34. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  35. using OpenSim.Server.Base;
  36. using OpenSim.Services.Connectors.InstantMessage;
  37. using OpenSim.Services.Connectors.Hypergrid;
  38. using OpenMetaverse;
  39. using Nini.Config;
  40. using log4net;
  41. namespace OpenSim.Services.HypergridService
  42. {
  43. public class GatekeeperService : IGatekeeperService
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private static bool m_Initialized = false;
  47. private static IGridService m_GridService;
  48. private static IPresenceService m_PresenceService;
  49. private static IUserAccountService m_UserAccountService;
  50. private static IUserAgentService m_UserAgentService;
  51. private static ISimulationService m_SimulationService;
  52. private static IGridUserService m_GridUserService;
  53. private static IBansService m_BansService;
  54. private static Regex m_AllowedClientsRegex = null;
  55. private static Regex m_DeniedClientsRegex = null;
  56. private static string m_DeniedMacs = string.Empty;
  57. private static string m_DeniedID0s = string.Empty;
  58. private static bool m_ForeignAgentsAllowed = true;
  59. private static readonly List<string> m_ForeignsAllowedExceptions = new();
  60. private static readonly List<string> m_ForeignsDisallowedExceptions = new();
  61. private static UUID m_ScopeID;
  62. private static bool m_AllowTeleportsToAnyRegion;
  63. private static OSHHTPHost m_gatekeeperHost;
  64. private static string m_gatekeeperURL;
  65. private static HashSet<OSHHTPHost> m_gateKeeperAlias;
  66. private static GridRegion m_DefaultGatewayRegion;
  67. private static bool m_allowDuplicatePresences = false;
  68. private static string m_messageKey;
  69. public GatekeeperService(IConfigSource config, ISimulationService simService)
  70. {
  71. if (!m_Initialized)
  72. {
  73. m_Initialized = true;
  74. IConfig serverConfig = config.Configs["GatekeeperService"];
  75. if (serverConfig is null)
  76. throw new Exception(String.Format("No section GatekeeperService in config file"));
  77. string accountService = serverConfig.GetString("UserAccountService", string.Empty);
  78. string homeUsersService = serverConfig.GetString("UserAgentService", string.Empty);
  79. string gridService = serverConfig.GetString("GridService", string.Empty);
  80. string presenceService = serverConfig.GetString("PresenceService", string.Empty);
  81. string simulationService = serverConfig.GetString("SimulationService", string.Empty);
  82. string gridUserService = serverConfig.GetString("GridUserService", string.Empty);
  83. string bansService = serverConfig.GetString("BansService", string.Empty);
  84. // These are mandatory, the others aren't
  85. if (gridService.Length == 0 || presenceService.Length == 0)
  86. throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
  87. string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
  88. UUID.TryParse(scope, out m_ScopeID);
  89. //m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
  90. m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);
  91. string[] sections = new string[] { "Const, Startup", "Hypergrid", "GatekeeperService" };
  92. string externalName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", sections, string.Empty);
  93. if(string.IsNullOrEmpty(externalName))
  94. externalName = serverConfig.GetString("ExternalName", string.Empty);
  95. m_gatekeeperHost = new OSHHTPHost(externalName, true);
  96. if (!m_gatekeeperHost.IsResolvedHost)
  97. {
  98. m_log.Error((m_gatekeeperHost.IsValidHost ? "Could not resolve GatekeeperURI" : "GatekeeperURI is a invalid host ") + externalName ?? "");
  99. throw new Exception("GatekeeperURI is invalid");
  100. }
  101. m_gatekeeperURL = m_gatekeeperHost.URIwEndSlash;
  102. string gatekeeperURIAlias = Util.GetConfigVarFromSections<string>(config, "GatekeeperURIAlias", sections, string.Empty);
  103. if (!string.IsNullOrWhiteSpace(gatekeeperURIAlias))
  104. {
  105. string[] alias = gatekeeperURIAlias.Split(',');
  106. for (int i = 0; i < alias.Length; ++i)
  107. {
  108. OSHHTPHost tmp = new(alias[i].Trim(), false);
  109. if (tmp.IsValidHost)
  110. {
  111. m_gateKeeperAlias ??= new HashSet<OSHHTPHost>();
  112. m_gateKeeperAlias.Add(tmp);
  113. }
  114. }
  115. }
  116. object[] args = new object[] { config };
  117. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  118. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  119. if (!string.IsNullOrEmpty(accountService))
  120. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
  121. if (!string.IsNullOrEmpty(homeUsersService))
  122. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(homeUsersService, args);
  123. if (!string.IsNullOrEmpty(gridUserService))
  124. m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
  125. if (!string.IsNullOrEmpty(bansService))
  126. m_BansService = ServerUtils.LoadPlugin<IBansService>(bansService, args);
  127. if (simService is not null)
  128. m_SimulationService = simService;
  129. else if (simulationService != string.Empty)
  130. m_SimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
  131. string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "GatekeeperService" };
  132. string AllowedClients = Util.GetConfigVarFromSections<string>(config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
  133. if (!string.IsNullOrEmpty(AllowedClients))
  134. {
  135. try
  136. {
  137. m_AllowedClientsRegex = new Regex(AllowedClients, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  138. }
  139. catch
  140. {
  141. m_AllowedClientsRegex = null;
  142. m_log.Error("[GATEKEEPER SERVICE]: failed to parse AllowedClients");
  143. }
  144. }
  145. string DeniedClients = Util.GetConfigVarFromSections<string>(config, "DeniedClients", possibleAccessControlConfigSections, string.Empty);
  146. if (!string.IsNullOrEmpty(DeniedClients))
  147. {
  148. try
  149. {
  150. m_DeniedClientsRegex = new Regex(DeniedClients, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  151. }
  152. catch
  153. {
  154. m_DeniedClientsRegex = null;
  155. m_log.Error("[GATEKEEPER SERVICE]: failed to parse DeniedClients");
  156. }
  157. }
  158. m_DeniedMacs = Util.GetConfigVarFromSections<string>(config, "DeniedMacs", possibleAccessControlConfigSections, string.Empty);
  159. m_DeniedID0s = Util.GetConfigVarFromSections<string>(config, "DeniedID0s", possibleAccessControlConfigSections, string.Empty);
  160. m_ForeignAgentsAllowed = serverConfig.GetBoolean("ForeignAgentsAllowed", true);
  161. LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_ForeignsAllowedExceptions);
  162. LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_ForeignsDisallowedExceptions);
  163. if (m_GridService is null || m_PresenceService is null || m_SimulationService is null)
  164. throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
  165. IConfig presenceConfig = config.Configs["PresenceService"];
  166. if (presenceConfig is not null)
  167. {
  168. m_allowDuplicatePresences = presenceConfig.GetBoolean("AllowDuplicatePresences", m_allowDuplicatePresences);
  169. }
  170. IConfig messagingConfig = config.Configs["Messaging"];
  171. if (messagingConfig is not null)
  172. m_messageKey = messagingConfig.GetString("MessageKey", String.Empty);
  173. m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
  174. }
  175. }
  176. public GatekeeperService(IConfigSource config)
  177. : this(config, null)
  178. {
  179. }
  180. protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, List<string> exceptions)
  181. {
  182. string value = config.GetString(variable, string.Empty);
  183. string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  184. foreach (string ps in parts)
  185. {
  186. string s = ps.Trim();
  187. if(!s.EndsWith("/"))
  188. s += '/';
  189. exceptions.Add(s);
  190. }
  191. }
  192. public bool LinkLocalRegion(string regionName, out UUID regionID, out ulong regionHandle, out string externalName, out string imageURL, out string reason, out int sizeX, out int sizeY)
  193. {
  194. regionID = UUID.Zero;
  195. regionHandle = 0;
  196. sizeX = (int)Constants.RegionSize;
  197. sizeY = (int)Constants.RegionSize;
  198. externalName = m_gatekeeperURL + ((regionName != string.Empty) ? " " + regionName : "");
  199. imageURL = string.Empty;
  200. reason = string.Empty;
  201. GridRegion region;
  202. //m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName.Length == 0)? "default region" : regionName);
  203. if (!m_AllowTeleportsToAnyRegion || regionName.Length == 0)
  204. {
  205. List<GridRegion> defs = m_GridService.GetDefaultHypergridRegions(m_ScopeID);
  206. if (defs is not null && defs.Count > 0)
  207. {
  208. region = defs[0];
  209. m_DefaultGatewayRegion = region;
  210. }
  211. else
  212. {
  213. reason = "Grid setup problem. Try specifying a particular region here.";
  214. m_log.Debug("[GATEKEEPER SERVICE]: Unable to send information. Please specify a default region for this grid!");
  215. return false;
  216. }
  217. }
  218. else
  219. {
  220. region = m_GridService.GetLocalRegionByName(m_ScopeID, regionName);
  221. if (region is null)
  222. {
  223. m_log.DebugFormat($"[GATEKEEPER SERVICE]: LinkLocalRegion could not find local region {regionName}");
  224. reason = "Region not found";
  225. return false;
  226. }
  227. }
  228. regionID = region.RegionID;
  229. regionHandle = region.RegionHandle;
  230. sizeX = region.RegionSizeX;
  231. sizeY = region.RegionSizeY;
  232. string regionimage = "regionImage" + regionID.ToString();
  233. regionimage = regionimage.Replace("-", "");
  234. imageURL = region.ServerURI + "index.php?method=" + regionimage;
  235. return true;
  236. }
  237. public GridRegion GetHyperlinkRegion(UUID regionID, UUID agentID, string agentHomeURI, out string message)
  238. {
  239. message = null;
  240. if (!m_AllowTeleportsToAnyRegion)
  241. {
  242. // Don't even check the given regionID
  243. m_log.DebugFormat(
  244. "[GATEKEEPER SERVICE]: Returning gateway region {0} {1} @ {2} to user {3}{4} as teleporting to arbitrary regions is not allowed.",
  245. m_DefaultGatewayRegion.RegionName,
  246. m_DefaultGatewayRegion.RegionID,
  247. m_DefaultGatewayRegion.ServerURI,
  248. agentID,
  249. agentHomeURI is null ? "" : " @ " + agentHomeURI);
  250. message = "Teleporting to the default region.";
  251. return m_DefaultGatewayRegion;
  252. }
  253. GridRegion region = m_GridService.GetRegionByUUID(m_ScopeID, regionID);
  254. if (region == null)
  255. {
  256. m_log.DebugFormat(
  257. "[GATEKEEPER SERVICE]: Could not find region with ID {0} as requested by user {1}{2}. Returning null.",
  258. regionID, agentID, (agentHomeURI is null) ? "" : " @ " + agentHomeURI);
  259. message = "The teleport destination could not be found.";
  260. return null;
  261. }
  262. m_log.DebugFormat(
  263. "[GATEKEEPER SERVICE]: Returning region {0} {1} @ {2} to user {3}{4}.",
  264. region.RegionName,
  265. region.RegionID,
  266. region.ServerURI,
  267. agentID,
  268. agentHomeURI is null ? "" : " @ " + agentHomeURI);
  269. return region;
  270. }
  271. #region Login Agent
  272. public bool LoginAgent(GridRegion source, AgentCircuitData aCircuit, GridRegion destination, out string reason)
  273. {
  274. reason = string.Empty;
  275. string authURL = string.Empty;
  276. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  277. authURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  278. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login request for {0} {1} @ {2} ({3}) at {4} using viewer {5}, channel {6}, IP {7}, Mac {8}, Id0 {9}, Teleport Flags: {10}. From region {11}",
  279. aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionID,
  280. aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, (TeleportFlags)aCircuit.teleportFlags,
  281. (source == null) ? "Unknown" : string.Format("{0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI));
  282. string curViewer = Util.GetViewerName(aCircuit);
  283. string curMac = aCircuit.Mac.ToString();
  284. //
  285. // Check client
  286. //
  287. if (m_AllowedClientsRegex is not null)
  288. {
  289. lock(m_AllowedClientsRegex)
  290. {
  291. Match am = m_AllowedClientsRegex.Match(curViewer);
  292. if (!am.Success)
  293. {
  294. reason = "Login failed: client " + curViewer + " is not allowed";
  295. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", curViewer);
  296. return false;
  297. }
  298. }
  299. }
  300. if (m_DeniedClientsRegex is not null)
  301. {
  302. lock(m_DeniedClientsRegex)
  303. {
  304. Match dm = m_DeniedClientsRegex.Match(curViewer);
  305. if (dm.Success)
  306. {
  307. reason = "Login failed: client " + curViewer + " is denied";
  308. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", curViewer);
  309. return false;
  310. }
  311. }
  312. }
  313. if (!String.IsNullOrWhiteSpace(m_DeniedMacs))
  314. {
  315. //m_log.InfoFormat("[GATEKEEPER SERVICE]: Checking users Mac {0} against list of denied macs {1} ...", curMac, m_DeniedMacs);
  316. if (m_DeniedMacs.Contains(curMac, StringComparison.InvariantCultureIgnoreCase))
  317. {
  318. reason = "Login failed: client with Mac " + curMac + " is denied";
  319. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client with mac {0} is denied", curMac);
  320. return false;
  321. }
  322. }
  323. if (!string.IsNullOrWhiteSpace(m_DeniedID0s))
  324. {
  325. //m_log.InfoFormat("[GATEKEEPER SERVICE]: Checking users Mac {0} against list of denied macs {1} ...", curMac, m_DeniedMacs);
  326. if (m_DeniedID0s.Contains(aCircuit.Id0, StringComparison.InvariantCultureIgnoreCase))
  327. {
  328. reason = "Login failed: client with id0 " + aCircuit.Id0 + " is denied";
  329. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client with mac {0} is denied", aCircuit.Id0);
  330. return false;
  331. }
  332. }
  333. //
  334. // Authenticate the user
  335. //
  336. if (!Authenticate(aCircuit))
  337. {
  338. reason = "Unable to verify identity";
  339. m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname);
  340. return false;
  341. }
  342. m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL);
  343. //
  344. // Check for impersonations
  345. //
  346. UserAccount account = null;
  347. if (m_UserAccountService is not null)
  348. {
  349. // Check to see if we have a local user with that UUID
  350. account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID);
  351. if (account is not null)
  352. {
  353. // Make sure this is the user coming home, and not a foreign user with same UUID as a local user
  354. if (m_UserAgentService is not null)
  355. {
  356. if (!m_UserAgentService.IsAgentComingHome(aCircuit.SessionID, m_gatekeeperURL))
  357. {
  358. // Can't do, sorry
  359. reason = "Unauthorized";
  360. m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.",
  361. aCircuit.firstname, aCircuit.lastname);
  362. return false;
  363. }
  364. }
  365. }
  366. }
  367. //
  368. // Foreign agents allowed? Exceptions?
  369. //
  370. if (account is null)
  371. {
  372. bool allowed = m_ForeignAgentsAllowed;
  373. if (m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsAllowedExceptions))
  374. allowed = false;
  375. if (!m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsDisallowedExceptions))
  376. allowed = true;
  377. if (!allowed)
  378. {
  379. reason = "Destination does not allow visitors from your world";
  380. m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agents are not permitted {0} {1} @ {2}. Refusing service.",
  381. aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs["HomeURI"]);
  382. return false;
  383. }
  384. }
  385. //
  386. // Is the user banned?
  387. // This uses a Ban service that's more powerful than the configs
  388. //
  389. string uui = (account is not null ? aCircuit.AgentID.ToString() : Util.ProduceUserUniversalIdentifier(aCircuit));
  390. if (m_BansService is not null && m_BansService.IsBanned(uui, aCircuit.IPAddress, aCircuit.Id0, authURL))
  391. {
  392. reason = "You are banned from this world";
  393. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: user {0} is banned", uui);
  394. return false;
  395. }
  396. UUID agentID = aCircuit.AgentID;
  397. if(agentID.Equals(Constants.servicesGodAgentID))
  398. {
  399. // really?
  400. reason = "Invalid account ID";
  401. return false;
  402. }
  403. if(m_GridUserService is not null)
  404. {
  405. GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(uui);
  406. if (guinfo is not null)
  407. {
  408. if (!m_allowDuplicatePresences)
  409. {
  410. if (guinfo.Online && !guinfo.LastRegionID.IsZero())
  411. {
  412. if (SendAgentGodKillToRegion(UUID.Zero, agentID, uui, guinfo))
  413. {
  414. if (account is not null)
  415. m_log.InfoFormat(
  416. "[GATEKEEPER SERVICE]: Login failed for {0} {1}, reason: already logged in",
  417. account.FirstName, account.LastName);
  418. reason = "You appear to be already logged in on the destination grid " +
  419. "Please wait a a minute or two and retry. " +
  420. "If this takes longer than a few minutes please contact the grid owner.";
  421. return false;
  422. }
  423. }
  424. }
  425. }
  426. }
  427. m_log.DebugFormat("[GATEKEEPER SERVICE]: User {0} is ok", aCircuit.Name);
  428. bool isFirstLogin = false;
  429. //
  430. // Login the presence, if it's not there yet (by the login service)
  431. //
  432. PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID);
  433. if (presence is not null) // it has been placed there by the login service
  434. isFirstLogin = true;
  435. else
  436. {
  437. if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID))
  438. {
  439. reason = "Unable to login presence";
  440. m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.",
  441. aCircuit.firstname, aCircuit.lastname);
  442. return false;
  443. }
  444. }
  445. //
  446. // Get the region
  447. //
  448. destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
  449. if (destination is null)
  450. {
  451. reason = "Destination region not found";
  452. return false;
  453. }
  454. m_log.DebugFormat(
  455. "[GATEKEEPER SERVICE]: Destination {0} is ok for {1}", destination.RegionName, aCircuit.Name);
  456. //
  457. // Adjust the visible name
  458. //
  459. if (account is not null)
  460. {
  461. aCircuit.firstname = account.FirstName;
  462. aCircuit.lastname = account.LastName;
  463. }
  464. if (account is null)
  465. {
  466. if (!aCircuit.lastname.StartsWith("@"))
  467. aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
  468. try
  469. {
  470. Uri uri = new(aCircuit.ServiceURLs["HomeURI"].ToString());
  471. aCircuit.lastname = "@" + uri.Authority;
  472. }
  473. catch
  474. {
  475. m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
  476. aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
  477. }
  478. }
  479. //
  480. // Finally launch the agent at the destination
  481. //
  482. Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
  483. // Preserve our TeleportFlags we have gathered so-far
  484. loginFlag |= (Constants.TeleportFlags) aCircuit.teleportFlags;
  485. m_log.DebugFormat("[GATEKEEPER SERVICE]: Launching {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag);
  486. EntityTransferContext ctx = new();
  487. if (!m_SimulationService.QueryAccess(
  488. destination, aCircuit.AgentID, aCircuit.ServiceURLs["HomeURI"].ToString(),
  489. true, aCircuit.startpos, new List<UUID>(), ctx, out reason))
  490. return false;
  491. bool didit = m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, ctx, out reason);
  492. if(didit)
  493. {
  494. m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence {0} is ok", aCircuit.Name);
  495. if(!isFirstLogin && m_GridUserService is not null && account is null)
  496. {
  497. // Also login foreigners with GridUser service
  498. string userId = aCircuit.AgentID.ToString();
  499. string first = aCircuit.firstname, last = aCircuit.lastname;
  500. if (last.StartsWith("@"))
  501. {
  502. string[] parts = aCircuit.firstname.Split('.');
  503. if (parts.Length >= 2)
  504. {
  505. first = parts[0];
  506. last = parts[1];
  507. }
  508. }
  509. userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
  510. m_GridUserService.LoggedIn(userId);
  511. }
  512. }
  513. return didit;
  514. }
  515. protected bool Authenticate(AgentCircuitData aCircuit)
  516. {
  517. if (!CheckAddress(aCircuit.ServiceSessionID))
  518. return false;
  519. if (string.IsNullOrEmpty(aCircuit.IPAddress))
  520. {
  521. m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide a client IP address.");
  522. return false;
  523. }
  524. string userURL = string.Empty;
  525. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  526. userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  527. OSHHTPHost userHomeHost = new(userURL, true);
  528. if(!userHomeHost.IsResolvedHost)
  529. {
  530. m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide an authentication server URL");
  531. return false;
  532. }
  533. if (m_gatekeeperHost.Equals(userHomeHost))
  534. {
  535. return m_UserAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  536. }
  537. else
  538. {
  539. IUserAgentService userAgentService = new UserAgentServiceConnector(userURL);
  540. try
  541. {
  542. return userAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  543. }
  544. catch
  545. {
  546. m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to contact authentication service at {0}", userURL);
  547. return false;
  548. }
  549. }
  550. }
  551. // Check that the service token was generated for *this* grid.
  552. // If it wasn't then that's a fake agent.
  553. protected bool CheckAddress(string serviceToken)
  554. {
  555. string[] parts = serviceToken.Split(new char[] { ';' });
  556. if (parts.Length < 2)
  557. return false;
  558. OSHHTPHost reqGrid = new(parts[0], false);
  559. if(!reqGrid.IsValidHost)
  560. {
  561. m_log.DebugFormat("[GATEKEEPER SERVICE]: Visitor provided malformed gird address {0}", parts[0]);
  562. return false;
  563. }
  564. m_log.DebugFormat("[GATEKEEPER SERVICE]: Verifying grid {0} against {1}", reqGrid.URI, m_gatekeeperHost.URI);
  565. if(m_gatekeeperHost.Equals(reqGrid))
  566. return true;
  567. if (m_gateKeeperAlias != null && m_gateKeeperAlias.Contains(reqGrid))
  568. return true;
  569. return false;
  570. }
  571. #endregion
  572. #region Misc
  573. private bool IsException(AgentCircuitData aCircuit, List<string> exceptions)
  574. {
  575. if (exceptions.Count > 0) // we have exceptions
  576. {
  577. // Retrieve the visitor's origin
  578. string userURL = aCircuit.ServiceURLs["HomeURI"].ToString().Trim();
  579. if (string.IsNullOrEmpty(userURL))
  580. return false;
  581. if (!userURL.EndsWith("/"))
  582. userURL += "/";
  583. foreach (string s in exceptions)
  584. {
  585. if (userURL.Equals(s))
  586. return true;
  587. }
  588. }
  589. return false;
  590. }
  591. private bool SendAgentGodKillToRegion(UUID scopeID, UUID agentID, string uui, GridUserInfo guinfo)
  592. {
  593. UUID regionID = guinfo.LastRegionID;
  594. GridRegion regInfo = m_GridService.GetRegionByUUID(scopeID, regionID);
  595. if(regInfo is null)
  596. return false;
  597. string regURL = regInfo.ServerURI;
  598. if(string.IsNullOrEmpty(regURL))
  599. return false;
  600. GridInstantMessage msg = new GridInstantMessage();
  601. msg.imSessionID = UUID.Zero.Guid;
  602. msg.fromAgentID = Constants.servicesGodAgentID.Guid;
  603. msg.toAgentID = agentID.Guid;
  604. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  605. msg.fromAgentName = "GRID";
  606. msg.message = string.Format("New login detected");
  607. msg.dialog = 250; // God kick
  608. msg.fromGroup = false;
  609. msg.offline = (byte)0;
  610. msg.ParentEstateID = 0;
  611. msg.Position = Vector3.Zero;
  612. msg.RegionID = scopeID.Guid;
  613. msg.binaryBucket = new byte[1] {0};
  614. InstantMessageServiceConnector.SendInstantMessage(regURL,msg, m_messageKey);
  615. m_GridUserService.LoggedOut(uui,
  616. UUID.Zero, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
  617. return true;
  618. }
  619. #endregion
  620. }
  621. }