OpenIdServerHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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, IStreamHandler
  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. string forPost;
  199. using(StreamReader sr = new StreamReader(httpRequest.InputStream))
  200. forPost = sr.ReadToEnd();
  201. NameValueCollection postQuery = HttpUtility.ParseQueryString(forPost);
  202. NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  203. NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
  204. OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
  205. if (provider.Request != null)
  206. {
  207. if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
  208. {
  209. IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
  210. string[] passwordValues = postQuery.GetValues("pass");
  211. UserAccount account;
  212. if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
  213. {
  214. // Check for form POST data
  215. if (passwordValues != null && passwordValues.Length == 1)
  216. {
  217. if (account != null &&
  218. (m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
  219. authRequest.IsAuthenticated = true;
  220. else
  221. authRequest.IsAuthenticated = false;
  222. }
  223. else
  224. {
  225. // Authentication was requested, send the client a login form
  226. using (StreamWriter writer = new StreamWriter(response))
  227. writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
  228. return;
  229. }
  230. }
  231. else
  232. {
  233. // Cannot find an avatar matching the claimed identifier
  234. authRequest.IsAuthenticated = false;
  235. }
  236. }
  237. // Add OpenID headers to the response
  238. foreach (string key in provider.Request.Response.Headers.Keys)
  239. httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
  240. string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
  241. if (contentTypeValues != null && contentTypeValues.Length == 1)
  242. httpResponse.ContentType = contentTypeValues[0];
  243. // Set the response code and document body based on the OpenID result
  244. httpResponse.StatusCode = (int)provider.Request.Response.Code;
  245. response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
  246. response.Close();
  247. }
  248. else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
  249. {
  250. // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
  251. using (StreamWriter writer = new StreamWriter(response))
  252. writer.Write(ENDPOINT_PAGE);
  253. }
  254. else
  255. {
  256. // Try and lookup this avatar
  257. UserAccount account;
  258. if (TryGetAccount(httpRequest.Url, out account))
  259. {
  260. using (StreamWriter writer = new StreamWriter(response))
  261. {
  262. // TODO: Print out a full profile page for this avatar
  263. writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
  264. httpRequest.Url.Authority, account.FirstName, account.LastName));
  265. }
  266. }
  267. else
  268. {
  269. // Couldn't parse an avatar name, or couldn't find the avatar in the user server
  270. using (StreamWriter writer = new StreamWriter(response))
  271. writer.Write(INVALID_OPENID_PAGE);
  272. }
  273. }
  274. }
  275. catch (Exception ex)
  276. {
  277. httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
  278. using (StreamWriter writer = new StreamWriter(response))
  279. writer.Write(ex.Message);
  280. }
  281. }
  282. /// <summary>
  283. /// Parse a URL with a relative path of the form /users/First_Last and try to
  284. /// retrieve the profile matching that avatar name
  285. /// </summary>
  286. /// <param name="requestUrl">URL to parse for an avatar name</param>
  287. /// <param name="profile">Profile data for the avatar</param>
  288. /// <returns>True if the parse and lookup were successful, otherwise false</returns>
  289. bool TryGetAccount(Uri requestUrl, out UserAccount account)
  290. {
  291. if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
  292. {
  293. // Parse the avatar name from the path
  294. string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
  295. string[] name = username.Split('_');
  296. if (name.Length == 2)
  297. {
  298. account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
  299. return (account != null);
  300. }
  301. }
  302. account = null;
  303. return false;
  304. }
  305. }
  306. }