AuthenticationService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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.Reflection;
  30. using Nini.Config;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Data;
  34. using OpenSim.Services.Base;
  35. using OpenSim.Services.Interfaces;
  36. using OpenMetaverse;
  37. namespace OpenSim.Services.AuthenticationService
  38. {
  39. /// <summary>
  40. /// Simple authentication service implementation dealing only with users.
  41. /// It uses the user DB directly to access user information.
  42. /// It takes two config vars:
  43. /// - Authenticate = {true|false} : to do or not to do authentication
  44. /// - Authority = string like "osgrid.org" : this identity authority
  45. /// that will be called back for identity verification
  46. /// </summary>
  47. public class HGAuthenticationService : ServiceBase, IAuthenticationService
  48. {
  49. private static readonly ILog m_log
  50. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. protected IUserDataPlugin m_Database;
  52. protected string m_AuthorityURL;
  53. protected bool m_PerformAuthentication;
  54. protected Dictionary<UUID, List<string>> m_UserKeys = new Dictionary<UUID, List<string>>();
  55. public HGAuthenticationService(IConfigSource config) : base(config)
  56. {
  57. string dllName = String.Empty;
  58. string connString = String.Empty;
  59. //
  60. // Try reading the [DatabaseService] section first, if it exists
  61. //
  62. IConfig dbConfig = config.Configs["DatabaseService"];
  63. if (dbConfig != null)
  64. {
  65. dllName = dbConfig.GetString("StorageProvider", String.Empty);
  66. connString = dbConfig.GetString("ConnectionString", String.Empty);
  67. }
  68. //
  69. // Try reading the more specific [InventoryService] section, if it exists
  70. //
  71. IConfig authConfig = config.Configs["AuthenticationService"];
  72. if (authConfig != null)
  73. {
  74. dllName = authConfig.GetString("StorageProvider", dllName);
  75. connString = authConfig.GetString("ConnectionString", connString);
  76. m_PerformAuthentication = authConfig.GetBoolean("Authenticate", true);
  77. m_AuthorityURL = "http://" + authConfig.GetString("Authority", "localhost");
  78. }
  79. //
  80. // We tried, but this doesn't exist. We can't proceed.
  81. //
  82. if (dllName.Equals(String.Empty))
  83. throw new Exception("No InventoryService configuration");
  84. m_Database = LoadPlugin<IUserDataPlugin>(dllName);
  85. if (m_Database == null)
  86. throw new Exception("Could not find a storage interface in the given module");
  87. m_Database.Initialise(connString);
  88. }
  89. public UUID AuthenticateKey(UUID principalID, string key)
  90. {
  91. bool writeAgentData = false;
  92. UserAgentData agent = m_Database.GetAgentByUUID(principalID);
  93. if (agent == null)
  94. {
  95. agent = new UserAgentData();
  96. agent.ProfileID = principalID;
  97. agent.SessionID = UUID.Random();
  98. agent.SecureSessionID = UUID.Random();
  99. agent.AgentIP = "127.0.0.1";
  100. agent.AgentPort = 0;
  101. agent.AgentOnline = false;
  102. writeAgentData = true;
  103. }
  104. if (!m_PerformAuthentication)
  105. {
  106. if (writeAgentData)
  107. m_Database.AddNewUserAgent(agent);
  108. return agent.SessionID;
  109. }
  110. if (!VerifyKey(principalID, key))
  111. return UUID.Zero;
  112. if (writeAgentData)
  113. m_Database.AddNewUserAgent(agent);
  114. return agent.SessionID;
  115. }
  116. /// <summary>
  117. /// This implementation only authenticates users.
  118. /// </summary>
  119. /// <param name="principalID"></param>
  120. /// <param name="password"></param>
  121. /// <returns></returns>
  122. public UUID AuthenticatePassword(UUID principalID, string password)
  123. {
  124. bool writeAgentData = false;
  125. UserAgentData agent = m_Database.GetAgentByUUID(principalID);
  126. if (agent == null)
  127. {
  128. agent = new UserAgentData();
  129. agent.ProfileID = principalID;
  130. agent.SessionID = UUID.Random();
  131. agent.SecureSessionID = UUID.Random();
  132. agent.AgentIP = "127.0.0.1";
  133. agent.AgentPort = 0;
  134. agent.AgentOnline = false;
  135. writeAgentData = true;
  136. }
  137. if (!m_PerformAuthentication)
  138. {
  139. if (writeAgentData)
  140. m_Database.AddNewUserAgent(agent);
  141. return agent.SessionID;
  142. }
  143. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  144. bool passwordSuccess = false;
  145. m_log.InfoFormat("[AUTH]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
  146. // we do this to get our hash in a form that the server password code can consume
  147. // when the web-login-form submits the password in the clear (supposed to be over SSL!)
  148. if (!password.StartsWith("$1$"))
  149. password = "$1$" + Util.Md5Hash(password);
  150. password = password.Remove(0, 3); //remove $1$
  151. string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
  152. // Testing...
  153. //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
  154. //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
  155. passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
  156. || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
  157. if (!passwordSuccess)
  158. return UUID.Zero;
  159. if (writeAgentData)
  160. m_Database.AddNewUserAgent(agent);
  161. return agent.SessionID;
  162. }
  163. /// <summary>
  164. /// This generates authorization keys in the form
  165. /// http://authority/uuid
  166. /// after verifying that the caller is, indeed, authorized to request a key
  167. /// </summary>
  168. /// <param name="userID">The principal ID requesting the new key</param>
  169. /// <param name="authToken">The original authorization token for that principal, obtained during login</param>
  170. /// <returns></returns>
  171. public string GetKey(UUID principalID, string authToken)
  172. {
  173. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  174. string newKey = string.Empty;
  175. if (profile != null)
  176. {
  177. m_log.DebugFormat("[AUTH]: stored auth token is {0}. Given token is {1}", profile.WebLoginKey.ToString(), authToken);
  178. // I'm overloading webloginkey for this, so that no changes are needed in the DB
  179. // The uses of webloginkey are fairly mutually exclusive
  180. if (profile.WebLoginKey.ToString().Equals(authToken))
  181. {
  182. newKey = UUID.Random().ToString();
  183. List<string> keys;
  184. lock (m_UserKeys)
  185. {
  186. if (m_UserKeys.ContainsKey(principalID))
  187. {
  188. keys = m_UserKeys[principalID];
  189. }
  190. else
  191. {
  192. keys = new List<string>();
  193. m_UserKeys.Add(principalID, keys);
  194. }
  195. keys.Add(newKey);
  196. }
  197. m_log.InfoFormat("[AUTH]: Successfully generated new auth key for {0}", principalID);
  198. }
  199. else
  200. m_log.Warn("[AUTH]: Unauthorized key generation request. Denying new key.");
  201. }
  202. else
  203. m_log.Warn("[AUTH]: Principal not found.");
  204. return m_AuthorityURL + newKey;
  205. }
  206. /// <summary>
  207. /// This verifies the uuid portion of the key given out by GenerateKey
  208. /// </summary>
  209. /// <param name="userID"></param>
  210. /// <param name="key"></param>
  211. /// <returns></returns>
  212. public bool VerifyKey(UUID userID, string key)
  213. {
  214. lock (m_UserKeys)
  215. {
  216. if (m_UserKeys.ContainsKey(userID))
  217. {
  218. List<string> keys = m_UserKeys[userID];
  219. if (keys.Contains(key))
  220. {
  221. // Keys are one-time only, so remove it
  222. keys.Remove(key);
  223. return true;
  224. }
  225. return false;
  226. }
  227. else
  228. return false;
  229. }
  230. }
  231. public UUID CreateUserSession(UUID userID, UUID oldSessionID)
  232. {
  233. UserAgentData agent = m_Database.GetAgentByUUID(userID);
  234. if (agent == null)
  235. return UUID.Zero;
  236. agent.SessionID = UUID.Random();
  237. m_Database.AddNewUserAgent(agent);
  238. return agent.SessionID;
  239. }
  240. public bool VerifyUserSession(UUID userID, UUID sessionID)
  241. {
  242. UserProfileData userProfile = m_Database.GetUserByUUID(userID);
  243. if (userProfile != null && userProfile.CurrentAgent != null)
  244. {
  245. m_log.DebugFormat("[AUTH]: Verifying session {0} for {1}; current session {2}", sessionID, userID, userProfile.CurrentAgent.SessionID);
  246. if (userProfile.CurrentAgent.SessionID == sessionID)
  247. {
  248. return true;
  249. }
  250. }
  251. return false;
  252. }
  253. public bool DestroyUserSession(UUID userID, UUID sessionID)
  254. {
  255. if (!VerifyUserSession(userID, sessionID))
  256. return false;
  257. UserAgentData agent = m_Database.GetAgentByUUID(userID);
  258. if (agent == null)
  259. return false;
  260. agent.SessionID = UUID.Zero;
  261. m_Database.AddNewUserAgent(agent);
  262. return true;
  263. }
  264. }
  265. }