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