OpenIdServerHandler.cs 14 KB

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