OpenIdServerHandler.cs 14 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.Generic;
  29. using System.Collections.Specialized;
  30. using System.IO;
  31. using System.Net;
  32. using System.Web;
  33. using DotNetOpenId;
  34. using DotNetOpenId.Provider;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Servers;
  37. using OpenSim.Framework.Servers.HttpServer;
  38. using OpenSim.Server.Handlers.Base;
  39. using OpenSim.Services.Interfaces;
  40. using Nini.Config;
  41. using OpenMetaverse;
  42. namespace OpenSim.Server.Handlers.Authentication
  43. {
  44. /// <summary>
  45. /// Temporary, in-memory store for OpenID associations
  46. /// </summary>
  47. public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
  48. {
  49. private class AssociationItem
  50. {
  51. public AssociationRelyingPartyType DistinguishingFactor;
  52. public string Handle;
  53. public DateTime Expires;
  54. public byte[] PrivateData;
  55. }
  56. Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
  57. SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
  58. object m_syncRoot = new object();
  59. #region IAssociationStore<AssociationRelyingPartyType> Members
  60. public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
  61. {
  62. AssociationItem item = new AssociationItem();
  63. item.DistinguishingFactor = distinguishingFactor;
  64. item.Handle = assoc.Handle;
  65. item.Expires = assoc.Expires.ToLocalTime();
  66. item.PrivateData = assoc.SerializePrivateData();
  67. lock (m_syncRoot)
  68. {
  69. m_store[item.Handle] = item;
  70. m_sortedStore[item.Expires] = item;
  71. }
  72. }
  73. public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
  74. {
  75. lock (m_syncRoot)
  76. {
  77. if (m_sortedStore.Count > 0)
  78. {
  79. AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
  80. return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
  81. }
  82. else
  83. {
  84. return null;
  85. }
  86. }
  87. }
  88. public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
  89. {
  90. AssociationItem item;
  91. bool success = false;
  92. lock (m_syncRoot)
  93. success = m_store.TryGetValue(handle, out item);
  94. if (success)
  95. return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
  96. else
  97. return null;
  98. }
  99. public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
  100. {
  101. lock (m_syncRoot)
  102. {
  103. for (int i = 0; i < m_sortedStore.Values.Count; i++)
  104. {
  105. AssociationItem item = m_sortedStore.Values[i];
  106. if (item.Handle == handle)
  107. {
  108. m_sortedStore.RemoveAt(i);
  109. break;
  110. }
  111. }
  112. return m_store.Remove(handle);
  113. }
  114. }
  115. public void ClearExpiredAssociations()
  116. {
  117. lock (m_syncRoot)
  118. {
  119. List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
  120. DateTime now = DateTime.Now;
  121. for (int i = 0; i < itemsCopy.Count; i++)
  122. {
  123. AssociationItem item = itemsCopy[i];
  124. if (item.Expires <= now)
  125. {
  126. m_sortedStore.RemoveAt(i);
  127. m_store.Remove(item.Handle);
  128. }
  129. }
  130. }
  131. }
  132. #endregion
  133. }
  134. public class OpenIdStreamHandler : BaseOutputStreamHandler
  135. {
  136. #region HTML
  137. /// <summary>Login form used to authenticate OpenID requests</summary>
  138. const string LOGIN_PAGE =
  139. @"<html>
  140. <head><title>OpenSim OpenID Login</title></head>
  141. <body>
  142. <h3>OpenSim Login</h3>
  143. <form method=""post"">
  144. <label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
  145. <label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
  146. <label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
  147. <input type=""submit"" value=""Login"">
  148. </form>
  149. </body>
  150. </html>";
  151. /// <summary>Page shown for a valid OpenID identity</summary>
  152. const string OPENID_PAGE =
  153. @"<html>
  154. <head>
  155. <title>{2} {3}</title>
  156. <link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
  157. </head>
  158. <body>OpenID identifier for {2} {3}</body>
  159. </html>
  160. ";
  161. /// <summary>Page shown for an invalid OpenID identity</summary>
  162. const string INVALID_OPENID_PAGE =
  163. @"<html><head><title>Identity not found</title></head>
  164. <body>Invalid OpenID identity</body></html>";
  165. /// <summary>Page shown if the OpenID endpoint is requested directly</summary>
  166. const string ENDPOINT_PAGE =
  167. @"<html><head><title>OpenID Endpoint</title></head><body>
  168. This is an OpenID server endpoint, not a human-readable resource.
  169. For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
  170. </body></html>";
  171. #endregion HTML
  172. IAuthenticationService m_authenticationService;
  173. IUserAccountService m_userAccountService;
  174. ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
  175. public override string ContentType { get { return "text/html"; } }
  176. /// <summary>
  177. /// Constructor
  178. /// </summary>
  179. public OpenIdStreamHandler(
  180. string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
  181. : base(httpMethod, path, "OpenId", "OpenID stream handler")
  182. {
  183. m_authenticationService = authService;
  184. m_userAccountService = userService;
  185. }
  186. /// <summary>
  187. /// Handles all GET and POST requests for OpenID identifier pages and endpoint
  188. /// server communication
  189. /// </summary>
  190. protected override void ProcessRequest(
  191. string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  192. {
  193. Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
  194. // Defult to returning HTML content
  195. httpResponse.ContentType = ContentType;
  196. try
  197. {
  198. NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
  199. NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  200. NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
  201. OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
  202. if (provider.Request != null)
  203. {
  204. if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
  205. {
  206. IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
  207. string[] passwordValues = postQuery.GetValues("pass");
  208. UserAccount account;
  209. if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
  210. {
  211. // Check for form POST data
  212. if (passwordValues != null && passwordValues.Length == 1)
  213. {
  214. if (account != null &&
  215. (m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
  216. authRequest.IsAuthenticated = true;
  217. else
  218. authRequest.IsAuthenticated = false;
  219. }
  220. else
  221. {
  222. // Authentication was requested, send the client a login form
  223. using (StreamWriter writer = new StreamWriter(response))
  224. writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
  225. return;
  226. }
  227. }
  228. else
  229. {
  230. // Cannot find an avatar matching the claimed identifier
  231. authRequest.IsAuthenticated = false;
  232. }
  233. }
  234. // Add OpenID headers to the response
  235. foreach (string key in provider.Request.Response.Headers.Keys)
  236. httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
  237. string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
  238. if (contentTypeValues != null && contentTypeValues.Length == 1)
  239. httpResponse.ContentType = contentTypeValues[0];
  240. // Set the response code and document body based on the OpenID result
  241. httpResponse.StatusCode = (int)provider.Request.Response.Code;
  242. response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
  243. response.Close();
  244. }
  245. else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
  246. {
  247. // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
  248. using (StreamWriter writer = new StreamWriter(response))
  249. writer.Write(ENDPOINT_PAGE);
  250. }
  251. else
  252. {
  253. // Try and lookup this avatar
  254. UserAccount account;
  255. if (TryGetAccount(httpRequest.Url, out account))
  256. {
  257. using (StreamWriter writer = new StreamWriter(response))
  258. {
  259. // TODO: Print out a full profile page for this avatar
  260. writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
  261. httpRequest.Url.Authority, account.FirstName, account.LastName));
  262. }
  263. }
  264. else
  265. {
  266. // Couldn't parse an avatar name, or couldn't find the avatar in the user server
  267. using (StreamWriter writer = new StreamWriter(response))
  268. writer.Write(INVALID_OPENID_PAGE);
  269. }
  270. }
  271. }
  272. catch (Exception ex)
  273. {
  274. httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
  275. using (StreamWriter writer = new StreamWriter(response))
  276. writer.Write(ex.Message);
  277. }
  278. }
  279. /// <summary>
  280. /// Parse a URL with a relative path of the form /users/First_Last and try to
  281. /// retrieve the profile matching that avatar name
  282. /// </summary>
  283. /// <param name="requestUrl">URL to parse for an avatar name</param>
  284. /// <param name="profile">Profile data for the avatar</param>
  285. /// <returns>True if the parse and lookup were successful, otherwise false</returns>
  286. bool TryGetAccount(Uri requestUrl, out UserAccount account)
  287. {
  288. if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
  289. {
  290. // Parse the avatar name from the path
  291. string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
  292. string[] name = username.Split('_');
  293. if (name.Length == 2)
  294. {
  295. account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
  296. return (account != null);
  297. }
  298. }
  299. account = null;
  300. return false;
  301. }
  302. }
  303. }