GatekeeperService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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.Hypergrid;
  37. using OpenMetaverse;
  38. using Nini.Config;
  39. using log4net;
  40. namespace OpenSim.Services.HypergridService
  41. {
  42. public class GatekeeperService : IGatekeeperService
  43. {
  44. private static readonly ILog m_log =
  45. LogManager.GetLogger(
  46. MethodBase.GetCurrentMethod().DeclaringType);
  47. private static bool m_Initialized = false;
  48. private static IGridService m_GridService;
  49. private static IPresenceService m_PresenceService;
  50. private static IUserAccountService m_UserAccountService;
  51. private static IUserAgentService m_UserAgentService;
  52. private static ISimulationService m_SimulationService;
  53. protected string m_AllowedClients = string.Empty;
  54. protected string m_DeniedClients = string.Empty;
  55. private static UUID m_ScopeID;
  56. private static bool m_AllowTeleportsToAnyRegion;
  57. private static string m_ExternalName;
  58. private static GridRegion m_DefaultGatewayRegion;
  59. public GatekeeperService(IConfigSource config, ISimulationService simService)
  60. {
  61. if (!m_Initialized)
  62. {
  63. m_Initialized = true;
  64. IConfig serverConfig = config.Configs["GatekeeperService"];
  65. if (serverConfig == null)
  66. throw new Exception(String.Format("No section GatekeeperService in config file"));
  67. string accountService = serverConfig.GetString("UserAccountService", String.Empty);
  68. string homeUsersService = serverConfig.GetString("UserAgentService", string.Empty);
  69. string gridService = serverConfig.GetString("GridService", String.Empty);
  70. string presenceService = serverConfig.GetString("PresenceService", String.Empty);
  71. string simulationService = serverConfig.GetString("SimulationService", String.Empty);
  72. // These 3 are mandatory, the others aren't
  73. if (gridService == string.Empty || presenceService == string.Empty)
  74. throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
  75. string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
  76. UUID.TryParse(scope, out m_ScopeID);
  77. //m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
  78. m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);
  79. m_ExternalName = serverConfig.GetString("ExternalName", string.Empty);
  80. if (m_ExternalName != string.Empty && !m_ExternalName.EndsWith("/"))
  81. m_ExternalName = m_ExternalName + "/";
  82. Object[] args = new Object[] { config };
  83. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  84. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  85. if (accountService != string.Empty)
  86. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
  87. if (homeUsersService != string.Empty)
  88. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(homeUsersService, args);
  89. if (simService != null)
  90. m_SimulationService = simService;
  91. else if (simulationService != string.Empty)
  92. m_SimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
  93. m_AllowedClients = serverConfig.GetString("AllowedClients", string.Empty);
  94. m_DeniedClients = serverConfig.GetString("DeniedClients", string.Empty);
  95. if (m_GridService == null || m_PresenceService == null || m_SimulationService == null)
  96. throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
  97. m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
  98. }
  99. }
  100. public GatekeeperService(IConfigSource config)
  101. : this(config, null)
  102. {
  103. }
  104. public bool LinkRegion(string regionName, out UUID regionID, out ulong regionHandle, out string externalName, out string imageURL, out string reason)
  105. {
  106. regionID = UUID.Zero;
  107. regionHandle = 0;
  108. externalName = m_ExternalName + ((regionName != string.Empty) ? " " + regionName : "");
  109. imageURL = string.Empty;
  110. reason = string.Empty;
  111. GridRegion region = null;
  112. m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName == string.Empty)? "default region" : regionName);
  113. if (!m_AllowTeleportsToAnyRegion || regionName == string.Empty)
  114. {
  115. List<GridRegion> defs = m_GridService.GetDefaultRegions(m_ScopeID);
  116. if (defs != null && defs.Count > 0)
  117. {
  118. region = defs[0];
  119. m_DefaultGatewayRegion = region;
  120. }
  121. else
  122. {
  123. reason = "Grid setup problem. Try specifying a particular region here.";
  124. m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to send information. Please specify a default region for this grid!");
  125. return false;
  126. }
  127. }
  128. else
  129. {
  130. region = m_GridService.GetRegionByName(m_ScopeID, regionName);
  131. if (region == null)
  132. {
  133. reason = "Region not found";
  134. return false;
  135. }
  136. }
  137. regionID = region.RegionID;
  138. regionHandle = region.RegionHandle;
  139. string regionimage = "regionImage" + regionID.ToString();
  140. regionimage = regionimage.Replace("-", "");
  141. imageURL = region.ServerURI + "index.php?method=" + regionimage;
  142. return true;
  143. }
  144. public GridRegion GetHyperlinkRegion(UUID regionID)
  145. {
  146. m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to get hyperlink region {0}", regionID);
  147. if (!m_AllowTeleportsToAnyRegion)
  148. // Don't even check the given regionID
  149. return m_DefaultGatewayRegion;
  150. GridRegion region = m_GridService.GetRegionByUUID(m_ScopeID, regionID);
  151. return region;
  152. }
  153. #region Login Agent
  154. public bool LoginAgent(AgentCircuitData aCircuit, GridRegion destination, out string reason)
  155. {
  156. reason = string.Empty;
  157. string authURL = string.Empty;
  158. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  159. authURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  160. 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}",
  161. aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionName,
  162. aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0);
  163. //
  164. // Check client
  165. //
  166. if (m_AllowedClients != string.Empty)
  167. {
  168. Regex arx = new Regex(m_AllowedClients);
  169. Match am = arx.Match(aCircuit.Viewer);
  170. if (!am.Success)
  171. {
  172. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", aCircuit.Viewer);
  173. return false;
  174. }
  175. }
  176. if (m_DeniedClients != string.Empty)
  177. {
  178. Regex drx = new Regex(m_DeniedClients);
  179. Match dm = drx.Match(aCircuit.Viewer);
  180. if (dm.Success)
  181. {
  182. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", aCircuit.Viewer);
  183. return false;
  184. }
  185. }
  186. //
  187. // Authenticate the user
  188. //
  189. if (!Authenticate(aCircuit))
  190. {
  191. reason = "Unable to verify identity";
  192. m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname);
  193. return false;
  194. }
  195. m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL);
  196. //
  197. // Check for impersonations
  198. //
  199. UserAccount account = null;
  200. if (m_UserAccountService != null)
  201. {
  202. // Check to see if we have a local user with that UUID
  203. account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID);
  204. if (account != null)
  205. {
  206. // Make sure this is the user coming home, and not a foreign user with same UUID as a local user
  207. if (m_UserAgentService != null)
  208. {
  209. if (!m_UserAgentService.AgentIsComingHome(aCircuit.SessionID, m_ExternalName))
  210. {
  211. // Can't do, sorry
  212. reason = "Unauthorized";
  213. m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.",
  214. aCircuit.firstname, aCircuit.lastname);
  215. return false;
  216. }
  217. }
  218. }
  219. }
  220. m_log.DebugFormat("[GATEKEEPER SERVICE]: User is ok");
  221. // May want to authorize
  222. bool isFirstLogin = false;
  223. //
  224. // Login the presence, if it's not there yet (by the login service)
  225. //
  226. PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID);
  227. if (presence != null) // it has been placed there by the login service
  228. isFirstLogin = true;
  229. else
  230. if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID))
  231. {
  232. reason = "Unable to login presence";
  233. m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.",
  234. aCircuit.firstname, aCircuit.lastname);
  235. return false;
  236. }
  237. m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence ok");
  238. //
  239. // Get the region
  240. //
  241. destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
  242. if (destination == null)
  243. {
  244. reason = "Destination region not found";
  245. return false;
  246. }
  247. m_log.DebugFormat("[GATEKEEPER SERVICE]: destination ok: {0}", destination.RegionName);
  248. //
  249. // Adjust the visible name
  250. //
  251. if (account != null)
  252. {
  253. aCircuit.firstname = account.FirstName;
  254. aCircuit.lastname = account.LastName;
  255. }
  256. if (account == null && !aCircuit.lastname.StartsWith("@"))
  257. {
  258. aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
  259. try
  260. {
  261. Uri uri = new Uri(aCircuit.ServiceURLs["HomeURI"].ToString());
  262. aCircuit.lastname = "@" + uri.Host; // + ":" + uri.Port;
  263. }
  264. catch
  265. {
  266. m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
  267. aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
  268. }
  269. }
  270. //
  271. // Finally launch the agent at the destination
  272. //
  273. Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
  274. m_log.DebugFormat("[GATEKEEPER SERVICE]: launching agent {0}", loginFlag);
  275. return m_SimulationService.CreateAgent(destination, aCircuit, (uint)loginFlag, out reason);
  276. }
  277. protected bool Authenticate(AgentCircuitData aCircuit)
  278. {
  279. if (!CheckAddress(aCircuit.ServiceSessionID))
  280. return false;
  281. string userURL = string.Empty;
  282. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  283. userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  284. if (userURL == string.Empty)
  285. {
  286. m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide an authentication server URL");
  287. return false;
  288. }
  289. if (userURL == m_ExternalName)
  290. return m_UserAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  291. else
  292. {
  293. // Object[] args = new Object[] { userURL };
  294. IUserAgentService userAgentService = new UserAgentServiceConnector(userURL);
  295. if (userAgentService != null)
  296. {
  297. try
  298. {
  299. return userAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  300. }
  301. catch
  302. {
  303. m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to contact authentication service at {0}", userURL);
  304. return false;
  305. }
  306. }
  307. }
  308. return false;
  309. }
  310. // Check that the service token was generated for *this* grid.
  311. // If it wasn't then that's a fake agent.
  312. protected bool CheckAddress(string serviceToken)
  313. {
  314. string[] parts = serviceToken.Split(new char[] { ';' });
  315. if (parts.Length < 2)
  316. return false;
  317. char[] trailing_slash = new char[] { '/' };
  318. string addressee = parts[0].TrimEnd(trailing_slash);
  319. string externalname = m_ExternalName.TrimEnd(trailing_slash);
  320. m_log.DebugFormat("[GATEKEEPER SERVICE]: Verifying {0} against {1}", addressee, externalname);
  321. return string.Equals(addressee, externalname, StringComparison.OrdinalIgnoreCase);
  322. }
  323. #endregion
  324. #region Misc
  325. #endregion
  326. }
  327. }