OpenIdServerHandler.cs 14 KB

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