OpenIdService.cs 14 KB

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