AuthenticationService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. if (!m_AuthorityURL.EndsWith("/"))
  79. m_AuthorityURL += "/";
  80. }
  81. //
  82. // We tried, but this doesn't exist. We can't proceed.
  83. //
  84. if (dllName.Equals(String.Empty))
  85. throw new Exception("No InventoryService configuration");
  86. m_Database = LoadPlugin<IUserDataPlugin>(dllName);
  87. if (m_Database == null)
  88. throw new Exception("Could not find a storage interface in the given module");
  89. m_Database.Initialise(connString);
  90. }
  91. public UUID AuthenticateKey(UUID principalID, string key)
  92. {
  93. bool writeAgentData = false;
  94. UserAgentData agent = m_Database.GetAgentByUUID(principalID);
  95. if (agent == null)
  96. {
  97. agent = new UserAgentData();
  98. agent.ProfileID = principalID;
  99. agent.SessionID = UUID.Random();
  100. agent.SecureSessionID = UUID.Random();
  101. agent.AgentIP = "127.0.0.1";
  102. agent.AgentPort = 0;
  103. agent.AgentOnline = false;
  104. writeAgentData = true;
  105. }
  106. if (!m_PerformAuthentication)
  107. {
  108. if (writeAgentData)
  109. m_Database.AddNewUserAgent(agent);
  110. return agent.SessionID;
  111. }
  112. if (!VerifyKey(principalID, key))
  113. return UUID.Zero;
  114. if (writeAgentData)
  115. m_Database.AddNewUserAgent(agent);
  116. return agent.SessionID;
  117. }
  118. /// <summary>
  119. /// This implementation only authenticates users.
  120. /// </summary>
  121. /// <param name="principalID"></param>
  122. /// <param name="password"></param>
  123. /// <returns></returns>
  124. public UUID AuthenticatePassword(UUID principalID, string password)
  125. {
  126. bool writeAgentData = false;
  127. UserAgentData agent = m_Database.GetAgentByUUID(principalID);
  128. if (agent == null)
  129. {
  130. agent = new UserAgentData();
  131. agent.ProfileID = principalID;
  132. agent.SessionID = UUID.Random();
  133. agent.SecureSessionID = UUID.Random();
  134. agent.AgentIP = "127.0.0.1";
  135. agent.AgentPort = 0;
  136. agent.AgentOnline = false;
  137. writeAgentData = true;
  138. }
  139. if (!m_PerformAuthentication)
  140. {
  141. if (writeAgentData)
  142. m_Database.AddNewUserAgent(agent);
  143. return agent.SessionID;
  144. }
  145. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  146. bool passwordSuccess = false;
  147. m_log.InfoFormat("[AUTH]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
  148. // we do this to get our hash in a form that the server password code can consume
  149. // when the web-login-form submits the password in the clear (supposed to be over SSL!)
  150. if (!password.StartsWith("$1$"))
  151. password = "$1$" + Util.Md5Hash(password);
  152. password = password.Remove(0, 3); //remove $1$
  153. string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
  154. // Testing...
  155. //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
  156. //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
  157. passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
  158. || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
  159. if (!passwordSuccess)
  160. return UUID.Zero;
  161. if (writeAgentData)
  162. m_Database.AddNewUserAgent(agent);
  163. return agent.SessionID;
  164. }
  165. /// <summary>
  166. /// This generates authorization keys in the form
  167. /// http://authority/uuid
  168. /// after verifying that the caller is, indeed, authorized to request a key
  169. /// </summary>
  170. /// <param name="userID">The principal ID requesting the new key</param>
  171. /// <param name="authToken">The original authorization token for that principal, obtained during login</param>
  172. /// <returns></returns>
  173. public string GetKey(UUID principalID, string authToken)
  174. {
  175. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  176. string newKey = string.Empty;
  177. if (profile != null)
  178. {
  179. m_log.DebugFormat("[AUTH]: stored auth token is {0}. Given token is {1}", profile.WebLoginKey.ToString(), authToken);
  180. // I'm overloading webloginkey for this, so that no changes are needed in the DB
  181. // The uses of webloginkey are fairly mutually exclusive
  182. if (profile.WebLoginKey.ToString().Equals(authToken))
  183. {
  184. newKey = UUID.Random().ToString();
  185. List<string> keys;
  186. lock (m_UserKeys)
  187. {
  188. if (m_UserKeys.ContainsKey(principalID))
  189. {
  190. keys = m_UserKeys[principalID];
  191. }
  192. else
  193. {
  194. keys = new List<string>();
  195. m_UserKeys.Add(principalID, keys);
  196. }
  197. keys.Add(newKey);
  198. }
  199. m_log.InfoFormat("[AUTH]: Successfully generated new auth key for {0}", principalID);
  200. }
  201. else
  202. m_log.Warn("[AUTH]: Unauthorized key generation request. Denying new key.");
  203. }
  204. else
  205. m_log.Warn("[AUTH]: Principal not found.");
  206. return m_AuthorityURL + newKey;
  207. }
  208. /// <summary>
  209. /// This verifies the uuid portion of the key given out by GenerateKey
  210. /// </summary>
  211. /// <param name="userID"></param>
  212. /// <param name="key"></param>
  213. /// <returns></returns>
  214. public bool VerifyKey(UUID userID, string key)
  215. {
  216. lock (m_UserKeys)
  217. {
  218. if (m_UserKeys.ContainsKey(userID))
  219. {
  220. List<string> keys = m_UserKeys[userID];
  221. if (keys.Contains(key))
  222. {
  223. // Keys are one-time only, so remove it
  224. keys.Remove(key);
  225. return true;
  226. }
  227. return false;
  228. }
  229. else
  230. return false;
  231. }
  232. }
  233. public UUID CreateUserSession(UUID userID, UUID oldSessionID)
  234. {
  235. UserAgentData agent = m_Database.GetAgentByUUID(userID);
  236. if (agent == null)
  237. return UUID.Zero;
  238. agent.SessionID = UUID.Random();
  239. m_Database.AddNewUserAgent(agent);
  240. return agent.SessionID;
  241. }
  242. public bool VerifyUserSession(UUID userID, UUID sessionID)
  243. {
  244. UserProfileData userProfile = m_Database.GetUserByUUID(userID);
  245. if (userProfile != null && userProfile.CurrentAgent != null)
  246. {
  247. m_log.DebugFormat("[AUTH]: Verifying session {0} for {1}; current session {2}", sessionID, userID, userProfile.CurrentAgent.SessionID);
  248. if (userProfile.CurrentAgent.SessionID == sessionID)
  249. {
  250. return true;
  251. }
  252. }
  253. return false;
  254. }
  255. public bool DestroyUserSession(UUID userID, UUID sessionID)
  256. {
  257. if (!VerifyUserSession(userID, sessionID))
  258. return false;
  259. UserAgentData agent = m_Database.GetAgentByUUID(userID);
  260. if (agent == null)
  261. return false;
  262. agent.SessionID = UUID.Zero;
  263. m_Database.AddNewUserAgent(agent);
  264. return true;
  265. }
  266. }
  267. }