GatekeeperService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. private static IGridUserService m_GridUserService;
  54. private static string m_AllowedClients = string.Empty;
  55. private static string m_DeniedClients = string.Empty;
  56. private static bool m_ForeignAgentsAllowed = true;
  57. private static List<string> m_ForeignsAllowedExceptions = new List<string>();
  58. private static List<string> m_ForeignsDisallowedExceptions = new List<string>();
  59. private static UUID m_ScopeID;
  60. private static bool m_AllowTeleportsToAnyRegion;
  61. private static string m_ExternalName;
  62. private static Uri m_Uri;
  63. private static GridRegion m_DefaultGatewayRegion;
  64. public GatekeeperService(IConfigSource config, ISimulationService simService)
  65. {
  66. if (!m_Initialized)
  67. {
  68. m_Initialized = true;
  69. IConfig serverConfig = config.Configs["GatekeeperService"];
  70. if (serverConfig == null)
  71. throw new Exception(String.Format("No section GatekeeperService in config file"));
  72. string accountService = serverConfig.GetString("UserAccountService", String.Empty);
  73. string homeUsersService = serverConfig.GetString("UserAgentService", string.Empty);
  74. string gridService = serverConfig.GetString("GridService", String.Empty);
  75. string presenceService = serverConfig.GetString("PresenceService", String.Empty);
  76. string simulationService = serverConfig.GetString("SimulationService", String.Empty);
  77. string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
  78. // These are mandatory, the others aren't
  79. if (gridService == string.Empty || presenceService == string.Empty)
  80. throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
  81. string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
  82. UUID.TryParse(scope, out m_ScopeID);
  83. //m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
  84. m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);
  85. m_ExternalName = serverConfig.GetString("ExternalName", string.Empty);
  86. if (m_ExternalName != string.Empty && !m_ExternalName.EndsWith("/"))
  87. m_ExternalName = m_ExternalName + "/";
  88. try
  89. {
  90. m_Uri = new Uri(m_ExternalName);
  91. }
  92. catch
  93. {
  94. m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed gatekeeper address {0}", m_ExternalName);
  95. }
  96. Object[] args = new Object[] { config };
  97. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  98. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  99. if (accountService != string.Empty)
  100. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
  101. if (homeUsersService != string.Empty)
  102. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(homeUsersService, args);
  103. if (gridUserService != string.Empty)
  104. m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
  105. if (simService != null)
  106. m_SimulationService = simService;
  107. else if (simulationService != string.Empty)
  108. m_SimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
  109. m_AllowedClients = serverConfig.GetString("AllowedClients", string.Empty);
  110. m_DeniedClients = serverConfig.GetString("DeniedClients", string.Empty);
  111. m_ForeignAgentsAllowed = serverConfig.GetBoolean("ForeignAgentsAllowed", true);
  112. LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_ForeignsAllowedExceptions);
  113. LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_ForeignsDisallowedExceptions);
  114. if (m_GridService == null || m_PresenceService == null || m_SimulationService == null)
  115. throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
  116. m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
  117. }
  118. }
  119. public GatekeeperService(IConfigSource config)
  120. : this(config, null)
  121. {
  122. }
  123. protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, List<string> exceptions)
  124. {
  125. string value = config.GetString(variable, string.Empty);
  126. string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  127. foreach (string s in parts)
  128. exceptions.Add(s.Trim());
  129. }
  130. public bool LinkRegion(string regionName, out UUID regionID, out ulong regionHandle, out string externalName, out string imageURL, out string reason)
  131. {
  132. regionID = UUID.Zero;
  133. regionHandle = 0;
  134. externalName = m_ExternalName + ((regionName != string.Empty) ? " " + regionName : "");
  135. imageURL = string.Empty;
  136. reason = string.Empty;
  137. GridRegion region = null;
  138. m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to link to {0}", (regionName == string.Empty)? "default region" : regionName);
  139. if (!m_AllowTeleportsToAnyRegion || regionName == string.Empty)
  140. {
  141. List<GridRegion> defs = m_GridService.GetDefaultRegions(m_ScopeID);
  142. if (defs != null && defs.Count > 0)
  143. {
  144. region = defs[0];
  145. m_DefaultGatewayRegion = region;
  146. }
  147. else
  148. {
  149. reason = "Grid setup problem. Try specifying a particular region here.";
  150. m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to send information. Please specify a default region for this grid!");
  151. return false;
  152. }
  153. }
  154. else
  155. {
  156. region = m_GridService.GetRegionByName(m_ScopeID, regionName);
  157. if (region == null)
  158. {
  159. reason = "Region not found";
  160. return false;
  161. }
  162. }
  163. regionID = region.RegionID;
  164. regionHandle = region.RegionHandle;
  165. string regionimage = "regionImage" + regionID.ToString();
  166. regionimage = regionimage.Replace("-", "");
  167. imageURL = region.ServerURI + "index.php?method=" + regionimage;
  168. return true;
  169. }
  170. public GridRegion GetHyperlinkRegion(UUID regionID)
  171. {
  172. m_log.DebugFormat("[GATEKEEPER SERVICE]: Request to get hyperlink region {0}", regionID);
  173. if (!m_AllowTeleportsToAnyRegion)
  174. // Don't even check the given regionID
  175. return m_DefaultGatewayRegion;
  176. GridRegion region = m_GridService.GetRegionByUUID(m_ScopeID, regionID);
  177. return region;
  178. }
  179. #region Login Agent
  180. public bool LoginAgent(AgentCircuitData aCircuit, GridRegion destination, out string reason)
  181. {
  182. reason = string.Empty;
  183. string authURL = string.Empty;
  184. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  185. authURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  186. 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}",
  187. aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionName,
  188. aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, aCircuit.teleportFlags.ToString());
  189. //
  190. // Check client
  191. //
  192. if (m_AllowedClients != string.Empty)
  193. {
  194. Regex arx = new Regex(m_AllowedClients);
  195. Match am = arx.Match(aCircuit.Viewer);
  196. if (!am.Success)
  197. {
  198. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", aCircuit.Viewer);
  199. return false;
  200. }
  201. }
  202. if (m_DeniedClients != string.Empty)
  203. {
  204. Regex drx = new Regex(m_DeniedClients);
  205. Match dm = drx.Match(aCircuit.Viewer);
  206. if (dm.Success)
  207. {
  208. m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", aCircuit.Viewer);
  209. return false;
  210. }
  211. }
  212. //
  213. // Authenticate the user
  214. //
  215. if (!Authenticate(aCircuit))
  216. {
  217. reason = "Unable to verify identity";
  218. m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname);
  219. return false;
  220. }
  221. m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL);
  222. //
  223. // Check for impersonations
  224. //
  225. UserAccount account = null;
  226. if (m_UserAccountService != null)
  227. {
  228. // Check to see if we have a local user with that UUID
  229. account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID);
  230. if (account != null)
  231. {
  232. // Make sure this is the user coming home, and not a foreign user with same UUID as a local user
  233. if (m_UserAgentService != null)
  234. {
  235. if (!m_UserAgentService.IsAgentComingHome(aCircuit.SessionID, m_ExternalName))
  236. {
  237. // Can't do, sorry
  238. reason = "Unauthorized";
  239. m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.",
  240. aCircuit.firstname, aCircuit.lastname);
  241. return false;
  242. }
  243. }
  244. }
  245. }
  246. m_log.DebugFormat("[GATEKEEPER SERVICE]: User is ok");
  247. //
  248. // Foreign agents allowed? Exceptions?
  249. //
  250. if (account == null)
  251. {
  252. bool allowed = m_ForeignAgentsAllowed;
  253. if (m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsAllowedExceptions))
  254. allowed = false;
  255. if (!m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsDisallowedExceptions))
  256. allowed = true;
  257. if (!allowed)
  258. {
  259. reason = "Destination does not allow visitors from your world";
  260. m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agents are not permitted {0} {1} @ {2}. Refusing service.",
  261. aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs["HomeURI"]);
  262. return false;
  263. }
  264. }
  265. bool isFirstLogin = false;
  266. //
  267. // Login the presence, if it's not there yet (by the login service)
  268. //
  269. PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID);
  270. if (presence != null) // it has been placed there by the login service
  271. isFirstLogin = true;
  272. else
  273. {
  274. if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID))
  275. {
  276. reason = "Unable to login presence";
  277. m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.",
  278. aCircuit.firstname, aCircuit.lastname);
  279. return false;
  280. }
  281. m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence ok");
  282. // Also login foreigners with GridUser service
  283. if (m_GridUserService != null && account == null)
  284. {
  285. string userId = aCircuit.AgentID.ToString();
  286. string first = aCircuit.firstname, last = aCircuit.lastname;
  287. if (last.StartsWith("@"))
  288. {
  289. string[] parts = aCircuit.firstname.Split('.');
  290. if (parts.Length >= 2)
  291. {
  292. first = parts[0];
  293. last = parts[1];
  294. }
  295. }
  296. userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
  297. m_GridUserService.LoggedIn(userId);
  298. }
  299. }
  300. //
  301. // Get the region
  302. //
  303. destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
  304. if (destination == null)
  305. {
  306. reason = "Destination region not found";
  307. return false;
  308. }
  309. m_log.DebugFormat("[GATEKEEPER SERVICE]: destination ok: {0}", destination.RegionName);
  310. //
  311. // Adjust the visible name
  312. //
  313. if (account != null)
  314. {
  315. aCircuit.firstname = account.FirstName;
  316. aCircuit.lastname = account.LastName;
  317. }
  318. if (account == null)
  319. {
  320. if (!aCircuit.lastname.StartsWith("@"))
  321. aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
  322. try
  323. {
  324. Uri uri = new Uri(aCircuit.ServiceURLs["HomeURI"].ToString());
  325. aCircuit.lastname = "@" + uri.Host; // + ":" + uri.Port;
  326. }
  327. catch
  328. {
  329. m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
  330. aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
  331. }
  332. }
  333. //
  334. // Finally launch the agent at the destination
  335. //
  336. Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
  337. // Preserve our TeleportFlags we have gathered so-far
  338. loginFlag |= (Constants.TeleportFlags) aCircuit.teleportFlags;
  339. m_log.DebugFormat("[GATEKEEPER SERVICE]: launching agent {0}", loginFlag);
  340. return m_SimulationService.CreateAgent(destination, aCircuit, (uint)loginFlag, out reason);
  341. }
  342. protected bool Authenticate(AgentCircuitData aCircuit)
  343. {
  344. if (!CheckAddress(aCircuit.ServiceSessionID))
  345. return false;
  346. string userURL = string.Empty;
  347. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  348. userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  349. if (userURL == string.Empty)
  350. {
  351. m_log.DebugFormat("[GATEKEEPER SERVICE]: Agent did not provide an authentication server URL");
  352. return false;
  353. }
  354. if (userURL == m_ExternalName)
  355. {
  356. return m_UserAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  357. }
  358. else
  359. {
  360. IUserAgentService userAgentService = new UserAgentServiceConnector(userURL);
  361. try
  362. {
  363. return userAgentService.VerifyAgent(aCircuit.SessionID, aCircuit.ServiceSessionID);
  364. }
  365. catch
  366. {
  367. m_log.DebugFormat("[GATEKEEPER SERVICE]: Unable to contact authentication service at {0}", userURL);
  368. return false;
  369. }
  370. }
  371. }
  372. // Check that the service token was generated for *this* grid.
  373. // If it wasn't then that's a fake agent.
  374. protected bool CheckAddress(string serviceToken)
  375. {
  376. string[] parts = serviceToken.Split(new char[] { ';' });
  377. if (parts.Length < 2)
  378. return false;
  379. char[] trailing_slash = new char[] { '/' };
  380. string addressee = parts[0].TrimEnd(trailing_slash);
  381. string externalname = m_ExternalName.TrimEnd(trailing_slash);
  382. m_log.DebugFormat("[GATEKEEPER SERVICE]: Verifying {0} against {1}", addressee, externalname);
  383. Uri uri;
  384. try
  385. {
  386. uri = new Uri(addressee);
  387. }
  388. catch
  389. {
  390. m_log.DebugFormat("[GATEKEEPER SERVICE]: Visitor provided malformed service address {0}", addressee);
  391. return false;
  392. }
  393. return string.Equals(uri.GetLeftPart(UriPartial.Authority), m_Uri.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase) ;
  394. }
  395. #endregion
  396. #region Misc
  397. private bool IsException(AgentCircuitData aCircuit, List<string> exceptions)
  398. {
  399. bool exception = false;
  400. if (exceptions.Count > 0) // we have exceptions
  401. {
  402. // Retrieve the visitor's origin
  403. string userURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  404. if (!userURL.EndsWith("/"))
  405. userURL += "/";
  406. if (exceptions.Find(delegate(string s)
  407. {
  408. if (!s.EndsWith("/"))
  409. s += "/";
  410. return s == userURL;
  411. }) != null)
  412. exception = true;
  413. }
  414. return exception;
  415. }
  416. #endregion
  417. }
  418. }