1
0

HGLoginAuthService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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;
  29. using System.Collections.Generic;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Communications.Cache;
  35. using OpenSim.Framework.Capabilities;
  36. using OpenSim.Framework.Servers;
  37. using OpenMetaverse;
  38. using log4net;
  39. using Nini.Config;
  40. using Nwc.XmlRpc;
  41. namespace OpenSim.Framework.Communications.Services
  42. {
  43. public class HGLoginAuthService : LoginService
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. protected NetworkServersInfo m_serversInfo;
  47. protected bool m_authUsers = false;
  48. /// <summary>
  49. /// Used by the login service to make requests to the inventory service.
  50. /// </summary>
  51. protected IInterServiceInventoryServices m_interServiceInventoryService;
  52. /// <summary>
  53. /// Used to make requests to the local regions.
  54. /// </summary>
  55. protected ILoginServiceToRegionsConnector m_regionsConnector;
  56. public HGLoginAuthService(
  57. UserManagerBase userManager, string welcomeMess,
  58. IInterServiceInventoryServices interServiceInventoryService,
  59. NetworkServersInfo serversInfo,
  60. bool authenticate, LibraryRootFolder libraryRootFolder, ILoginServiceToRegionsConnector regionsConnector)
  61. : base(userManager, libraryRootFolder, welcomeMess)
  62. {
  63. this.m_serversInfo = serversInfo;
  64. if (m_serversInfo != null)
  65. {
  66. m_defaultHomeX = this.m_serversInfo.DefaultHomeLocX;
  67. m_defaultHomeY = this.m_serversInfo.DefaultHomeLocY;
  68. }
  69. m_authUsers = authenticate;
  70. m_interServiceInventoryService = interServiceInventoryService;
  71. m_regionsConnector = regionsConnector;
  72. m_interInventoryService = interServiceInventoryService;
  73. }
  74. public void SetServersInfo(NetworkServersInfo sinfo)
  75. {
  76. m_serversInfo = sinfo;
  77. }
  78. public override XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient)
  79. {
  80. m_log.Info("[HGLOGIN]: HGLogin called " + request.MethodName);
  81. XmlRpcResponse response = base.XmlRpcLoginMethod(request, remoteClient);
  82. Hashtable responseData = (Hashtable)response.Value;
  83. responseData["grid_service"] = m_serversInfo.GridURL;
  84. responseData["grid_service_send_key"] = m_serversInfo.GridSendKey;
  85. responseData["inventory_service"] = m_serversInfo.InventoryURL;
  86. responseData["asset_service"] = m_serversInfo.AssetURL;
  87. responseData["asset_service_send_key"] = m_serversInfo.AssetSendKey;
  88. int x = (Int32)responseData["region_x"];
  89. int y = (Int32)responseData["region_y"];
  90. uint ux = (uint)(x / Constants.RegionSize);
  91. uint uy = (uint)(y / Constants.RegionSize);
  92. ulong regionHandle = Util.UIntsToLong(ux, uy);
  93. responseData["region_handle"] = regionHandle.ToString();
  94. // Let's remove the seed cap from the login
  95. //responseData.Remove("seed_capability");
  96. // Let's add the appearance
  97. UUID userID = UUID.Zero;
  98. UUID.TryParse((string)responseData["agent_id"], out userID);
  99. AvatarAppearance appearance = m_userManager.GetUserAppearance(userID);
  100. if (appearance == null)
  101. {
  102. m_log.WarnFormat("[INTER]: Appearance not found for {0}. Creating default.", userID);
  103. appearance = new AvatarAppearance();
  104. }
  105. responseData["appearance"] = appearance.ToHashTable();
  106. // Let's also send the auth token
  107. UUID token = UUID.Random();
  108. responseData["auth_token"] = token.ToString();
  109. UserProfileData userProfile = m_userManager.GetUserProfile(userID);
  110. if (userProfile != null)
  111. {
  112. userProfile.WebLoginKey = token;
  113. m_userManager.CommitAgent(ref userProfile);
  114. }
  115. m_log.Warn("[HGLOGIN]: Auth token: " + token);
  116. return response;
  117. }
  118. public XmlRpcResponse XmlRpcGenerateKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient)
  119. {
  120. // Verify the key of who's calling
  121. UUID userID = UUID.Zero;
  122. UUID authKey = UUID.Zero;
  123. UUID.TryParse((string)request.Params[0], out userID);
  124. UUID.TryParse((string)request.Params[1], out authKey);
  125. m_log.InfoFormat("[HGLOGIN] HGGenerateKey called with authToken ", authKey);
  126. string newKey = string.Empty;
  127. if (!(m_userManager is IAuthentication))
  128. {
  129. m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Returning empty key.");
  130. }
  131. else
  132. {
  133. newKey = ((IAuthentication)m_userManager).GetNewKey(m_serversInfo.UserURL, userID, authKey);
  134. }
  135. XmlRpcResponse response = new XmlRpcResponse();
  136. response.Value = (string) newKey;
  137. return response;
  138. }
  139. public XmlRpcResponse XmlRpcVerifyKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient)
  140. {
  141. bool success = false;
  142. if (request.Params.Count >= 2)
  143. {
  144. // Verify the key of who's calling
  145. UUID userID = UUID.Zero;
  146. string authKey = string.Empty;
  147. if (UUID.TryParse((string)request.Params[0], out userID))
  148. {
  149. authKey = (string)request.Params[1];
  150. m_log.InfoFormat("[HGLOGIN] HGVerifyKey called with key {0}", authKey);
  151. if (!(m_userManager is IAuthentication))
  152. {
  153. m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Denying.");
  154. }
  155. else
  156. {
  157. success = ((IAuthentication)m_userManager).VerifyKey(userID, authKey);
  158. }
  159. }
  160. }
  161. m_log.DebugFormat("[HGLOGIN]: Response to VerifyKey is {0}", success);
  162. XmlRpcResponse response = new XmlRpcResponse();
  163. response.Value = success;
  164. return response;
  165. }
  166. public override UserProfileData GetTheUser(string firstname, string lastname)
  167. {
  168. UserProfileData profile = m_userManager.GetUserProfile(firstname, lastname);
  169. if (profile != null)
  170. {
  171. return profile;
  172. }
  173. if (!m_authUsers)
  174. {
  175. //no current user account so make one
  176. m_log.Info("[LOGIN]: No user account found so creating a new one.");
  177. m_userManager.AddUser(firstname, lastname, "test", "", m_defaultHomeX, m_defaultHomeY);
  178. return m_userManager.GetUserProfile(firstname, lastname);
  179. }
  180. return null;
  181. }
  182. public override bool AuthenticateUser(UserProfileData profile, string password)
  183. {
  184. if (!m_authUsers)
  185. {
  186. //for now we will accept any password in sandbox mode
  187. m_log.Info("[LOGIN]: Authorising user (no actual password check)");
  188. return true;
  189. }
  190. else
  191. {
  192. m_log.Info(
  193. "[LOGIN]: Authenticating " + profile.FirstName + " " + profile.SurName);
  194. if (!password.StartsWith("$1$"))
  195. password = "$1$" + Util.Md5Hash(password);
  196. password = password.Remove(0, 3); //remove $1$
  197. string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
  198. bool loginresult = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
  199. || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
  200. return loginresult;
  201. }
  202. }
  203. protected override RegionInfo RequestClosestRegion(string region)
  204. {
  205. return m_regionsConnector.RequestClosestRegion(region);
  206. }
  207. protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
  208. {
  209. return m_regionsConnector.RequestNeighbourInfo(homeRegionHandle);
  210. }
  211. protected override RegionInfo GetRegionInfo(UUID homeRegionId)
  212. {
  213. return m_regionsConnector.RequestNeighbourInfo(homeRegionId);
  214. }
  215. /// <summary>
  216. /// Not really informing the region. Just filling out the response fields related to the region.
  217. /// </summary>
  218. /// <param name="sim"></param>
  219. /// <param name="user"></param>
  220. /// <param name="response"></param>
  221. /// <returns>true if the region was successfully contacted, false otherwise</returns>
  222. protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
  223. {
  224. IPEndPoint endPoint = regionInfo.ExternalEndPoint;
  225. response.SimAddress = endPoint.Address.ToString();
  226. response.SimPort = (uint)endPoint.Port;
  227. response.RegionX = regionInfo.RegionLocX;
  228. response.RegionY = regionInfo.RegionLocY;
  229. response.SimHttpPort = regionInfo.HttpPort;
  230. string capsPath = CapsUtil.GetRandomCapsObjectPath();
  231. string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath);
  232. // Don't use the following! It Fails for logging into any region not on the same port as the http server!
  233. // Kept here so it doesn't happen again!
  234. // response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
  235. string seedcap = "http://";
  236. if (m_serversInfo.HttpUsesSSL)
  237. {
  238. // For NAT
  239. string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN);
  240. seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath;
  241. }
  242. else
  243. {
  244. // For NAT
  245. string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName);
  246. seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath;
  247. }
  248. response.SeedCapability = seedcap;
  249. // Notify the target of an incoming user
  250. m_log.InfoFormat(
  251. "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
  252. regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI);
  253. // Update agent with target sim
  254. user.CurrentAgent.Region = regionInfo.RegionID;
  255. user.CurrentAgent.Handle = regionInfo.RegionHandle;
  256. return true;
  257. }
  258. public override void LogOffUser(UserProfileData theUser, string message)
  259. {
  260. RegionInfo SimInfo;
  261. try
  262. {
  263. SimInfo = this.m_regionsConnector.RequestNeighbourInfo(theUser.CurrentAgent.Handle);
  264. if (SimInfo == null)
  265. {
  266. m_log.Error("[LOCAL LOGIN]: Region user was in isn't currently logged in");
  267. return;
  268. }
  269. }
  270. catch (Exception)
  271. {
  272. m_log.Error("[LOCAL LOGIN]: Unable to look up region to log user off");
  273. return;
  274. }
  275. m_regionsConnector.LogOffUserFromGrid(SimInfo.RegionHandle, theUser.ID, theUser.CurrentAgent.SecureSessionID, "Logging you off");
  276. }
  277. protected override bool AllowLoginWithoutInventory()
  278. {
  279. return true;
  280. }
  281. }
  282. }