AuthenticationService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. /// <summary>
  90. /// This implementation only authenticates users.
  91. /// </summary>
  92. /// <param name="principalID"></param>
  93. /// <param name="password"></param>
  94. /// <returns></returns>
  95. public bool Authenticate(UUID principalID, string password)
  96. {
  97. if (!m_PerformAuthentication)
  98. return true;
  99. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  100. bool passwordSuccess = false;
  101. m_log.InfoFormat("[AUTH]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
  102. // we do this to get our hash in a form that the server password code can consume
  103. // when the web-login-form submits the password in the clear (supposed to be over SSL!)
  104. if (!password.StartsWith("$1$"))
  105. password = "$1$" + Util.Md5Hash(password);
  106. password = password.Remove(0, 3); //remove $1$
  107. string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
  108. // Testing...
  109. //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
  110. //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
  111. passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
  112. || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
  113. return passwordSuccess;
  114. }
  115. /// <summary>
  116. /// This generates authorization keys in the form
  117. /// http://authority/uuid
  118. /// after verifying that the caller is, indeed, authorized to request a key
  119. /// </summary>
  120. /// <param name="userID">The principal ID requesting the new key</param>
  121. /// <param name="authToken">The original authorization token for that principal, obtained during login</param>
  122. /// <returns></returns>
  123. public string GetKey(UUID principalID, string authToken)
  124. {
  125. UserProfileData profile = m_Database.GetUserByUUID(principalID);
  126. string newKey = string.Empty;
  127. if (profile != null)
  128. {
  129. m_log.DebugFormat("[AUTH]: stored auth token is {0}. Given token is {1}", profile.WebLoginKey.ToString(), authToken);
  130. // I'm overloading webloginkey for this, so that no changes are needed in the DB
  131. // The uses of webloginkey are fairly mutually exclusive
  132. if (profile.WebLoginKey.ToString().Equals(authToken))
  133. {
  134. newKey = UUID.Random().ToString();
  135. List<string> keys;
  136. lock (m_UserKeys)
  137. {
  138. if (m_UserKeys.ContainsKey(principalID))
  139. {
  140. keys = m_UserKeys[principalID];
  141. }
  142. else
  143. {
  144. keys = new List<string>();
  145. m_UserKeys.Add(principalID, keys);
  146. }
  147. keys.Add(newKey);
  148. }
  149. m_log.InfoFormat("[AUTH]: Successfully generated new auth key for {0}", principalID);
  150. }
  151. else
  152. m_log.Warn("[AUTH]: Unauthorized key generation request. Denying new key.");
  153. }
  154. else
  155. m_log.Warn("[AUTH]: Principal not found.");
  156. return m_AuthorityURL + newKey;
  157. }
  158. /// <summary>
  159. /// This verifies the uuid portion of the key given out by GenerateKey
  160. /// </summary>
  161. /// <param name="userID"></param>
  162. /// <param name="key"></param>
  163. /// <returns></returns>
  164. public bool VerifyKey(UUID userID, string key)
  165. {
  166. lock (m_UserKeys)
  167. {
  168. if (m_UserKeys.ContainsKey(userID))
  169. {
  170. List<string> keys = m_UserKeys[userID];
  171. if (keys.Contains(key))
  172. {
  173. // Keys are one-time only, so remove it
  174. keys.Remove(key);
  175. return true;
  176. }
  177. return false;
  178. }
  179. else
  180. return false;
  181. }
  182. }
  183. public UUID AllocateUserSession(UUID userID)
  184. {
  185. // Not implemented yet
  186. return UUID.Zero;
  187. }
  188. public bool VerifyUserSession(UUID userID, UUID sessionID)
  189. {
  190. UserProfileData userProfile = m_Database.GetUserByUUID(userID);
  191. if (userProfile != null && userProfile.CurrentAgent != null)
  192. {
  193. m_log.DebugFormat("[AUTH]: Verifying session {0} for {1}; current session {2}", sessionID, userID, userProfile.CurrentAgent.SessionID);
  194. if (userProfile.CurrentAgent.SessionID == sessionID)
  195. {
  196. return true;
  197. }
  198. }
  199. return false;
  200. }
  201. public void DestroyUserSession(UUID userID)
  202. {
  203. // Not implemented yet
  204. }
  205. }
  206. }