Merge pull request #853 from echampet/onclick
[mono.git] / mcs / class / System.Web / System.Web.Security / FormsAuthentication.cs
1 //
2 // System.Web.Security.FormsAuthentication
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (c) 2005-2010 Novell, Inc (http://www.novell.com)
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.IO;
34 using System.Security.Cryptography;
35 using System.Security.Permissions;
36 using System.Text;
37 using System.Web;
38 using System.Web.Configuration;
39 using System.Web.Compilation;
40 using System.Web.Util;
41 using System.Globalization;
42 using System.Collections.Specialized;
43
44 namespace System.Web.Security
45 {
46         // CAS - no InheritanceDemand here as the class is sealed
47         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48         public sealed class FormsAuthentication
49         {
50                 static string authConfigPath = "system.web/authentication";
51                 static string machineKeyConfigPath = "system.web/machineKey";
52                 static object locker = new object ();
53                 static bool initialized;
54                 static string cookieName;
55                 static string cookiePath;
56                 static int timeout;
57                 static FormsProtectionEnum protection;
58                 static bool requireSSL;
59                 static bool slidingExpiration;
60                 static string cookie_domain;
61                 static HttpCookieMode cookie_mode;
62                 static bool cookies_supported;
63                 static string default_url;
64                 static bool enable_crossapp_redirects;
65                 static string login_url;
66                 // same names and order used in xsp
67                 static string [] indexFiles = { "index.aspx",
68                                                 "Default.aspx",
69                                                 "default.aspx",
70                                                 "index.html",
71                                                 "index.htm" };
72                 public static TimeSpan Timeout {
73                         get; private set;
74                 }
75
76                 public static bool IsEnabled { 
77                         get { return initialized; }
78                 }
79
80                 public static void EnableFormsAuthentication (NameValueCollection configurationData)
81                 {
82                         BuildManager.AssertPreStartMethodsRunning ();
83                         if (configurationData == null || configurationData.Count == 0)
84                                 return;
85
86                         string value = configurationData ["loginUrl"];
87                         if (!String.IsNullOrEmpty (value))
88                                 login_url = value;
89
90                         value = configurationData ["defaultUrl"];
91                         if (!String.IsNullOrEmpty (value))
92                                 default_url = value;
93                 }
94                 public FormsAuthentication ()
95                 {
96                 }
97
98                 public static bool Authenticate (string name, string password)
99                 {
100                         if (name == null || password == null)
101                                 return false;
102
103                         Initialize ();
104                         HttpContext context = HttpContext.Current;
105                         if (context == null)
106                                 throw new HttpException ("Context is null!");
107
108                         name = name.ToLower (Helpers.InvariantCulture);
109
110                         AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
111                         FormsAuthenticationCredentials config = section.Forms.Credentials;
112                         FormsAuthenticationUser user = config.Users[name];
113                         string stored = null;
114
115                         if (user != null)
116                                 stored = user.Password;
117
118                         if (stored == null)
119                                 return false;
120
121                         bool caseInsensitive = true;
122                         switch (config.PasswordFormat) {
123                                 case FormsAuthPasswordFormat.Clear:
124                                         caseInsensitive = false;
125                                         /* Do nothing */
126                                         break;
127                                 case FormsAuthPasswordFormat.MD5:
128                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
129                                         break;
130                                 case FormsAuthPasswordFormat.SHA1:
131                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
132                                         break;
133                         }
134
135                         return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
136                 }
137
138                 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
139                 {
140                         if (protection == FormsProtectionEnum.None)
141                                 return FormsAuthenticationTicket.FromByteArray (bytes);
142
143                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
144                         byte [] result = null;
145                         if (protection == FormsProtectionEnum.All) {
146                                 result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
147                         } else if (protection == FormsProtectionEnum.Encryption) {
148                                 result = MachineKeySectionUtils.Decrypt (config, bytes);
149                         } else if (protection == FormsProtectionEnum.Validation) {
150                                 result = MachineKeySectionUtils.Verify (config, bytes);
151                         }
152
153                         return FormsAuthenticationTicket.FromByteArray (result);
154                 }
155
156                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
157                 {
158                         if (String.IsNullOrEmpty (encryptedTicket))
159                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
160
161                         Initialize ();
162
163                         FormsAuthenticationTicket ticket;
164                         byte [] bytes = Convert.FromBase64String (encryptedTicket);
165
166                         try {
167                                 ticket = Decrypt2 (bytes);
168                         } catch (Exception) {
169                                 ticket = null;
170                         }
171
172                         return ticket;
173                 }
174
175                 public static string Encrypt (FormsAuthenticationTicket ticket)
176                 {
177                         if (ticket == null)
178                                 throw new ArgumentNullException ("ticket");
179
180                         Initialize ();
181                         byte [] ticket_bytes = ticket.ToByteArray ();
182                         if (protection == FormsProtectionEnum.None)
183                                 return Convert.ToBase64String (ticket_bytes);
184
185                         byte [] result = null;
186                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
187
188                         if (protection == FormsProtectionEnum.All) {
189                                 result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
190                         } else if (protection == FormsProtectionEnum.Encryption) {
191                                 result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
192                         } else if (protection == FormsProtectionEnum.Validation) {
193                                 result = MachineKeySectionUtils.Sign (config, ticket_bytes);
194                         }
195
196                         return Convert.ToBase64String (result);
197                 }
198
199                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
200                 {
201                         return GetAuthCookie (userName, createPersistentCookie, null);
202                 }
203
204                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
205                 {
206                         Initialize ();
207
208                         if (userName == null)
209                                 userName = String.Empty;
210
211                         if (strCookiePath == null || strCookiePath.Length == 0)
212                                 strCookiePath = cookiePath;
213
214                         DateTime now = DateTime.Now;
215                         DateTime then;
216                         if (createPersistentCookie)
217                                 then = now.AddYears (50);
218                         else
219                                 then = now.AddMinutes (timeout);
220
221                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
222                                                                                           userName,
223                                                                                           now,
224                                                                                           then,
225                                                                                           createPersistentCookie,
226                                                                                           String.Empty,
227                                                                                           cookiePath);
228
229                         if (!createPersistentCookie)
230                                 then = DateTime.MinValue;
231
232                         HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
233                         if (requireSSL)
234                                 cookie.Secure = true;
235                         if (!String.IsNullOrEmpty (cookie_domain))
236                                 cookie.Domain = cookie_domain;
237
238                         return cookie;
239                 }
240
241                 internal static string ReturnUrl {
242                         get { return HttpContext.Current.Request ["RETURNURL"]; }
243                 }
244
245                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
246                 {
247                         if (userName == null)
248                                 return null;
249
250                         Initialize ();
251                         HttpRequest request = HttpContext.Current.Request;
252                         string returnUrl = ReturnUrl;
253                         if (returnUrl != null)
254                                 return returnUrl;
255
256                         returnUrl = request.ApplicationPath;
257                         string apppath = request.PhysicalApplicationPath;
258                         bool found = false;
259
260                         foreach (string indexFile in indexFiles) {
261                                 string filePath = Path.Combine (apppath, indexFile);
262                                 if (File.Exists (filePath)) {
263                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
264                                         found = true;
265                                         break;
266                                 }
267                         }
268
269                         if (!found)
270                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
271
272                         return returnUrl;
273                 }
274
275                 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
276                 {
277                         if (password == null)
278                                 throw new ArgumentNullException ("password");
279                         
280                         byte [] bytes;
281                         switch (passwordFormat) {
282                                 case FormsAuthPasswordFormat.MD5:
283                                         bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
284                                         break;
285
286                                 case FormsAuthPasswordFormat.SHA1:
287                                         bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
288                                         break;
289
290                                 default:
291                                         throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
292                         }
293
294                         return MachineKeySectionUtils.GetHexString (bytes);
295                 }
296                 
297                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
298                 {
299                         if (password == null)
300                                 throw new ArgumentNullException ("password");
301
302                         if (passwordFormat == null)
303                                 throw new ArgumentNullException ("passwordFormat");
304
305                         if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
306                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
307                         } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
308                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
309                         } else {
310                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
311                         }
312                 }
313
314                 public static void Initialize ()
315                 {
316                         if (initialized)
317                                 return;
318
319                         lock (locker) {
320                                 if (initialized)
321                                         return;
322
323                                 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
324                                 FormsAuthenticationConfiguration config = section.Forms;
325
326                                 cookieName = config.Name;
327                                 Timeout = config.Timeout;
328                                 timeout = (int)config.Timeout.TotalMinutes;
329                                 cookiePath = config.Path;
330                                 protection = config.Protection;
331                                 requireSSL = config.RequireSSL;
332                                 slidingExpiration = config.SlidingExpiration;
333                                 cookie_domain = config.Domain;
334                                 cookie_mode = config.Cookieless;
335                                 cookies_supported = true; /* XXX ? */
336                                 if (!String.IsNullOrEmpty (default_url))
337                                         default_url = MapUrl (default_url);
338                                 else
339                                         default_url = MapUrl(config.DefaultUrl);
340                                 enable_crossapp_redirects = config.EnableCrossAppRedirects;
341                                 if (!String.IsNullOrEmpty (login_url))
342                                         login_url = MapUrl (login_url);
343                                 else
344                                         login_url = MapUrl(config.LoginUrl);
345
346                                 initialized = true;
347                         }
348                 }
349
350                 static string MapUrl (string url) {
351                         if (UrlUtils.IsRelativeUrl (url))
352                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
353                         else
354                                 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
355                 }
356
357                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
358                 {
359                         RedirectFromLoginPage (userName, createPersistentCookie, null);
360                 }
361
362                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
363                 {
364                         if (userName == null)
365                                 return;
366
367                         Initialize ();
368                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
369                         Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
370                 }
371
372                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
373                 {
374                         if (tOld == null)
375                                 return null;
376
377                         DateTime now = DateTime.Now;
378                         TimeSpan toIssue = now - tOld.IssueDate;
379                         TimeSpan toExpiration = tOld.Expiration - now;
380                         if (toExpiration > toIssue)
381                                 return tOld;
382
383                         FormsAuthenticationTicket tNew = tOld.Clone ();
384                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
385                         return tNew;
386                 }
387
388                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
389                 {
390                         Initialize ();
391                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
392                 }
393
394                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
395                 {
396                         HttpContext context = HttpContext.Current;
397                         if (context == null)
398                                 throw new HttpException ("Context is null!");
399
400                         HttpResponse response = context.Response;
401                         if (response == null)
402                                 throw new HttpException ("Response is null!");
403
404                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
405                 }
406
407                 public static void SignOut ()
408                 {
409                         Initialize ();
410
411                         HttpContext context = HttpContext.Current;
412                         if (context == null)
413                                 throw new HttpException ("Context is null!");
414
415                         HttpResponse response = context.Response;
416                         if (response == null)
417                                 throw new HttpException ("Response is null!");
418
419                         HttpCookieCollection cc = response.Cookies;
420                         cc.Remove (cookieName);
421                         HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
422                         expiration_cookie.Expires = new DateTime (1999, 10, 12);
423                         expiration_cookie.Path = cookiePath;
424                         if (!String.IsNullOrEmpty (cookie_domain))
425                                 expiration_cookie.Domain = cookie_domain;
426                         cc.Add (expiration_cookie);
427                         Roles.DeleteCookie ();
428                 }
429
430                 public static string FormsCookieName
431                 {
432                         get {
433                                 Initialize ();
434                                 return cookieName;
435                         }
436                 }
437
438                 public static string FormsCookiePath
439                 {
440                         get {
441                                 Initialize ();
442                                 return cookiePath;
443                         }
444                 }
445
446                 public static bool RequireSSL {
447                         get {
448                                 Initialize ();
449                                 return requireSSL;
450                         }
451                 }
452
453                 public static bool SlidingExpiration {
454                         get {
455                                 Initialize ();
456                                 return slidingExpiration;
457                         }
458                 }
459
460                 public static string CookieDomain {
461                         get { Initialize (); return cookie_domain; }
462                 }
463
464                 public static HttpCookieMode CookieMode {
465                         get { Initialize (); return cookie_mode; }
466                 }
467
468                 public static bool CookiesSupported {
469                         get { Initialize (); return cookies_supported; }
470                 }
471
472                 public static string DefaultUrl {
473                         get { Initialize (); return default_url; }
474                 }
475
476                 public static bool EnableCrossAppRedirects {
477                         get { Initialize (); return enable_crossapp_redirects; }
478                 }
479
480                 public static string LoginUrl {
481                         get { Initialize (); return login_url; }
482                 }
483
484                 public static void RedirectToLoginPage ()
485                 {
486                         Redirect (LoginUrl);
487                 }
488
489                 [MonoTODO ("needs more tests")]
490                 public static void RedirectToLoginPage (string extraQueryString)
491                 {
492                         // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
493                         Redirect (LoginUrl + "?" + extraQueryString);
494                 }
495
496                 static void Redirect (string url)
497                 {
498                         HttpContext.Current.Response.Redirect (url);
499                 }
500
501                 static void Redirect (string url, bool end)
502                 {
503                         HttpContext.Current.Response.Redirect (url, end);
504                 }
505         }
506 }