added new property from 4.0
[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 #if TARGET_J2EE
54                 const string Forms_initialized = "Forms.initialized";
55                 const string Forms_cookieName = "Forms.cookieName";
56                 const string Forms_cookiePath = "Forms.cookiePath";
57                 const string Forms_timeout = "Forms.timeout";
58                 const string Forms_protection = "Forms.protection";
59                 static bool initialized
60                 {
61                         get {
62                                 object o = AppDomain.CurrentDomain.GetData (Forms_initialized);
63                                 return o != null ? (bool) o : false;
64                         }
65                         set { AppDomain.CurrentDomain.SetData (Forms_initialized, value); }
66                 }
67                 static string cookieName
68                 {
69                         get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookieName); }
70                         set { AppDomain.CurrentDomain.SetData (Forms_cookieName, value); }
71                 }
72                 static string cookiePath
73                 {
74                         get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookiePath); }
75                         set { AppDomain.CurrentDomain.SetData (Forms_cookiePath, value); }
76                 }
77                 static int timeout
78                 {
79                         get {
80                                 object o = AppDomain.CurrentDomain.GetData (Forms_timeout);
81                                 return o != null ? (int) o : 0;
82                         }
83                         set { AppDomain.CurrentDomain.SetData (Forms_timeout, value); }
84                 }
85                 static FormsProtectionEnum protection
86                 {
87                         get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
88                         set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
89                 }
90
91                 const string Forms_requireSSL = "Forms.requireSSL";
92                 const string Forms_slidingExpiration = "Forms.slidingExpiration";
93
94                 static bool requireSSL
95                 {
96                         get {
97                                 object o = AppDomain.CurrentDomain.GetData (Forms_requireSSL);
98                                 return o != null ? (bool) o : false;
99                         }
100                         set { AppDomain.CurrentDomain.SetData (Forms_requireSSL, value); }
101                 }
102                 static bool slidingExpiration
103                 {
104                         get {
105                                 object o = AppDomain.CurrentDomain.GetData (Forms_slidingExpiration);
106                                 return o != null ? (bool) o : false;
107                         }
108                         set { AppDomain.CurrentDomain.SetData (Forms_slidingExpiration, value); }
109                 }
110
111                 const string Forms_cookie_domain = "Forms.cookie_domain";
112                 const string Forms_cookie_mode = "Forms.cookie_mode";
113                 const string Forms_cookies_supported = "Forms.cookies_supported";
114                 const string Forms_default_url = "Forms.default_url";
115                 const string Forms_enable_crossapp_redirects = "Forms.enable_crossapp_redirects";
116                 const string Forms_login_url = "Forms.login_url";
117                 static string cookie_domain
118                 {
119                         get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookie_domain); }
120                         set { AppDomain.CurrentDomain.SetData (Forms_cookie_domain, value); }
121                 }
122                 static HttpCookieMode cookie_mode
123                 {
124                         get { return (HttpCookieMode) AppDomain.CurrentDomain.GetData (Forms_cookie_mode); }
125                         set { AppDomain.CurrentDomain.SetData (Forms_cookie_mode, value); }
126                 }
127                 static bool cookies_supported
128                 {
129                         get {
130                                 object o = AppDomain.CurrentDomain.GetData (Forms_cookies_supported);
131                                 return o != null ? (bool) o : false;
132                         }
133                         set { AppDomain.CurrentDomain.SetData (Forms_cookies_supported, value); }
134                 }
135                 static string default_url
136                 {
137                         get { return (string) AppDomain.CurrentDomain.GetData (Forms_default_url); }
138                         set { AppDomain.CurrentDomain.SetData (Forms_default_url, value); }
139                 }
140                 static bool enable_crossapp_redirects
141                 {
142                         get {
143                                 object o = AppDomain.CurrentDomain.GetData (Forms_enable_crossapp_redirects);
144                                 return o != null ? (bool) o : false;
145                         }
146                         set { AppDomain.CurrentDomain.SetData (Forms_enable_crossapp_redirects, value); }
147                 }
148                 static string login_url
149                 {
150                         get { return (string) AppDomain.CurrentDomain.GetData (Forms_login_url); }
151                         set { AppDomain.CurrentDomain.SetData (Forms_login_url, value); }
152                 }
153 #else
154                 static bool initialized;
155                 static string cookieName;
156                 static string cookiePath;
157                 static int timeout;
158                 static FormsProtectionEnum protection;
159                 static bool requireSSL;
160                 static bool slidingExpiration;
161                 static string cookie_domain;
162                 static HttpCookieMode cookie_mode;
163                 static bool cookies_supported;
164                 static string default_url;
165                 static bool enable_crossapp_redirects;
166                 static string login_url;
167 #endif
168                 // same names and order used in xsp
169                 static string [] indexFiles = { "index.aspx",
170                                                 "Default.aspx",
171                                                 "default.aspx",
172                                                 "index.html",
173                                                 "index.htm" };
174 #if NET_4_0
175                 public static TimeSpan Timeout {
176                         get; private set;
177                 }
178
179                 public static bool IsEnabled { 
180                         get { return initialized; }
181                 }
182
183                 public static void EnableFormsAuthentication (NameValueCollection configurationData)
184                 {
185                         BuildManager.AssertPreStartMethodsRunning ();
186                         if (configurationData == null || configurationData.Count == 0)
187                                 return;
188
189                         string value = configurationData ["loginUrl"];
190                         if (!String.IsNullOrEmpty (value))
191                                 login_url = value;
192
193                         value = configurationData ["defaultUrl"];
194                         if (!String.IsNullOrEmpty (value))
195                                 default_url = value;
196                 }
197 #endif
198                 public FormsAuthentication ()
199                 {
200                 }
201
202                 public static bool Authenticate (string name, string password)
203                 {
204                         if (name == null || password == null)
205                                 return false;
206
207                         Initialize ();
208                         HttpContext context = HttpContext.Current;
209                         if (context == null)
210                                 throw new HttpException ("Context is null!");
211
212                         name = name.ToLower (Helpers.InvariantCulture);
213
214                         AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
215                         FormsAuthenticationCredentials config = section.Forms.Credentials;
216                         FormsAuthenticationUser user = config.Users[name];
217                         string stored = null;
218
219                         if (user != null)
220                                 stored = user.Password;
221
222                         if (stored == null)
223                                 return false;
224
225                         bool caseInsensitive = true;
226                         switch (config.PasswordFormat) {
227                                 case FormsAuthPasswordFormat.Clear:
228                                         caseInsensitive = false;
229                                         /* Do nothing */
230                                         break;
231                                 case FormsAuthPasswordFormat.MD5:
232                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
233                                         break;
234                                 case FormsAuthPasswordFormat.SHA1:
235                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
236                                         break;
237                         }
238
239                         return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
240                 }
241
242                 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
243                 {
244                         if (protection == FormsProtectionEnum.None)
245                                 return FormsAuthenticationTicket.FromByteArray (bytes);
246
247                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
248                         byte [] result = null;
249                         if (protection == FormsProtectionEnum.All) {
250                                 result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
251                         } else if (protection == FormsProtectionEnum.Encryption) {
252                                 result = MachineKeySectionUtils.Decrypt (config, bytes);
253                         } else if (protection == FormsProtectionEnum.Validation) {
254                                 result = MachineKeySectionUtils.Verify (config, bytes);
255                         }
256
257                         return FormsAuthenticationTicket.FromByteArray (result);
258                 }
259
260                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
261                 {
262                         if (String.IsNullOrEmpty (encryptedTicket))
263                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
264
265                         Initialize ();
266
267                         FormsAuthenticationTicket ticket;
268                         byte [] bytes = Convert.FromBase64String (encryptedTicket);
269
270                         try {
271                                 ticket = Decrypt2 (bytes);
272                         } catch (Exception) {
273                                 ticket = null;
274                         }
275
276                         return ticket;
277                 }
278
279                 public static string Encrypt (FormsAuthenticationTicket ticket)
280                 {
281                         if (ticket == null)
282                                 throw new ArgumentNullException ("ticket");
283
284                         Initialize ();
285                         byte [] ticket_bytes = ticket.ToByteArray ();
286                         if (protection == FormsProtectionEnum.None)
287                                 return Convert.ToBase64String (ticket_bytes);
288
289                         byte [] result = null;
290                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
291
292                         if (protection == FormsProtectionEnum.All) {
293                                 result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
294                         } else if (protection == FormsProtectionEnum.Encryption) {
295                                 result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
296                         } else if (protection == FormsProtectionEnum.Validation) {
297                                 result = MachineKeySectionUtils.Sign (config, ticket_bytes);
298                         }
299
300                         return Convert.ToBase64String (result);
301                 }
302
303                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
304                 {
305                         return GetAuthCookie (userName, createPersistentCookie, null);
306                 }
307
308                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
309                 {
310                         Initialize ();
311
312                         if (userName == null)
313                                 userName = String.Empty;
314
315                         if (strCookiePath == null || strCookiePath.Length == 0)
316                                 strCookiePath = cookiePath;
317
318                         DateTime now = DateTime.Now;
319                         DateTime then;
320                         if (createPersistentCookie)
321                                 then = now.AddYears (50);
322                         else
323                                 then = now.AddMinutes (timeout);
324
325                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
326                                                                                           userName,
327                                                                                           now,
328                                                                                           then,
329                                                                                           createPersistentCookie,
330                                                                                           String.Empty,
331                                                                                           cookiePath);
332
333                         if (!createPersistentCookie)
334                                 then = DateTime.MinValue;
335
336                         HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
337                         if (requireSSL)
338                                 cookie.Secure = true;
339                         if (!String.IsNullOrEmpty (cookie_domain))
340                                 cookie.Domain = cookie_domain;
341
342                         return cookie;
343                 }
344
345                 internal static string ReturnUrl {
346                         get { return HttpContext.Current.Request ["RETURNURL"]; }
347                 }
348
349                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
350                 {
351                         if (userName == null)
352                                 return null;
353
354                         Initialize ();
355                         HttpRequest request = HttpContext.Current.Request;
356                         string returnUrl = ReturnUrl;
357                         if (returnUrl != null)
358                                 return returnUrl;
359
360                         returnUrl = request.ApplicationPath;
361                         string apppath = request.PhysicalApplicationPath;
362                         bool found = false;
363
364                         foreach (string indexFile in indexFiles) {
365                                 string filePath = Path.Combine (apppath, indexFile);
366                                 if (File.Exists (filePath)) {
367                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
368                                         found = true;
369                                         break;
370                                 }
371                         }
372
373                         if (!found)
374                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
375
376                         return returnUrl;
377                 }
378
379                 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
380                 {
381                         if (password == null)
382                                 throw new ArgumentNullException ("password");
383                         
384                         byte [] bytes;
385                         switch (passwordFormat) {
386                                 case FormsAuthPasswordFormat.MD5:
387                                         bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
388                                         break;
389
390                                 case FormsAuthPasswordFormat.SHA1:
391                                         bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
392                                         break;
393
394                                 default:
395                                         throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
396                         }
397
398                         return MachineKeySectionUtils.GetHexString (bytes);
399                 }
400                 
401                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
402                 {
403                         if (password == null)
404                                 throw new ArgumentNullException ("password");
405
406                         if (passwordFormat == null)
407                                 throw new ArgumentNullException ("passwordFormat");
408
409                         if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
410                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
411                         } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
412                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
413                         } else {
414                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
415                         }
416                 }
417
418                 public static void Initialize ()
419                 {
420                         if (initialized)
421                                 return;
422
423                         lock (locker) {
424                                 if (initialized)
425                                         return;
426
427                                 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
428                                 FormsAuthenticationConfiguration config = section.Forms;
429
430                                 cookieName = config.Name;
431 #if NET_4_0
432                                 Timeout = config.Timeout;
433 #endif
434                                 timeout = (int)config.Timeout.TotalMinutes;
435                                 cookiePath = config.Path;
436                                 protection = config.Protection;
437                                 requireSSL = config.RequireSSL;
438                                 slidingExpiration = config.SlidingExpiration;
439                                 cookie_domain = config.Domain;
440                                 cookie_mode = config.Cookieless;
441                                 cookies_supported = true; /* XXX ? */
442 #if NET_4_0
443                                 if (!String.IsNullOrEmpty (default_url))
444                                         default_url = MapUrl (default_url);
445                                 else
446 #endif
447                                         default_url = MapUrl(config.DefaultUrl);
448                                 enable_crossapp_redirects = config.EnableCrossAppRedirects;
449 #if NET_4_0
450                                 if (!String.IsNullOrEmpty (login_url))
451                                         login_url = MapUrl (login_url);
452                                 else
453 #endif
454                                         login_url = MapUrl(config.LoginUrl);
455
456                                 initialized = true;
457                         }
458                 }
459
460                 static string MapUrl (string url) {
461                         if (UrlUtils.IsRelativeUrl (url))
462                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
463                         else
464                                 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
465                 }
466
467                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
468                 {
469                         RedirectFromLoginPage (userName, createPersistentCookie, null);
470                 }
471
472                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
473                 {
474                         if (userName == null)
475                                 return;
476
477                         Initialize ();
478                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
479                         Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
480                 }
481
482                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
483                 {
484                         if (tOld == null)
485                                 return null;
486
487                         DateTime now = DateTime.Now;
488                         TimeSpan toIssue = now - tOld.IssueDate;
489                         TimeSpan toExpiration = tOld.Expiration - now;
490                         if (toExpiration > toIssue)
491                                 return tOld;
492
493                         FormsAuthenticationTicket tNew = tOld.Clone ();
494                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
495                         return tNew;
496                 }
497
498                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
499                 {
500                         Initialize ();
501                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
502                 }
503
504                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
505                 {
506                         HttpContext context = HttpContext.Current;
507                         if (context == null)
508                                 throw new HttpException ("Context is null!");
509
510                         HttpResponse response = context.Response;
511                         if (response == null)
512                                 throw new HttpException ("Response is null!");
513
514                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
515                 }
516
517                 public static void SignOut ()
518                 {
519                         Initialize ();
520
521                         HttpContext context = HttpContext.Current;
522                         if (context == null)
523                                 throw new HttpException ("Context is null!");
524
525                         HttpResponse response = context.Response;
526                         if (response == null)
527                                 throw new HttpException ("Response is null!");
528
529                         HttpCookieCollection cc = response.Cookies;
530                         cc.Remove (cookieName);
531                         HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
532                         expiration_cookie.Expires = new DateTime (1999, 10, 12);
533                         expiration_cookie.Path = cookiePath;
534                         if (!String.IsNullOrEmpty (cookie_domain))
535                                 expiration_cookie.Domain = cookie_domain;
536                         cc.Add (expiration_cookie);
537                         Roles.DeleteCookie ();
538                 }
539
540                 public static string FormsCookieName
541                 {
542                         get {
543                                 Initialize ();
544                                 return cookieName;
545                         }
546                 }
547
548                 public static string FormsCookiePath
549                 {
550                         get {
551                                 Initialize ();
552                                 return cookiePath;
553                         }
554                 }
555
556                 public static bool RequireSSL {
557                         get {
558                                 Initialize ();
559                                 return requireSSL;
560                         }
561                 }
562
563                 public static bool SlidingExpiration {
564                         get {
565                                 Initialize ();
566                                 return slidingExpiration;
567                         }
568                 }
569
570                 public static string CookieDomain {
571                         get { Initialize (); return cookie_domain; }
572                 }
573
574                 public static HttpCookieMode CookieMode {
575                         get { Initialize (); return cookie_mode; }
576                 }
577
578                 public static bool CookiesSupported {
579                         get { Initialize (); return cookies_supported; }
580                 }
581
582                 public static string DefaultUrl {
583                         get { Initialize (); return default_url; }
584                 }
585
586                 public static bool EnableCrossAppRedirects {
587                         get { Initialize (); return enable_crossapp_redirects; }
588                 }
589
590                 public static string LoginUrl {
591                         get { Initialize (); return login_url; }
592                 }
593
594                 public static void RedirectToLoginPage ()
595                 {
596                         Redirect (LoginUrl);
597                 }
598
599                 [MonoTODO ("needs more tests")]
600                 public static void RedirectToLoginPage (string extraQueryString)
601                 {
602                         // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
603                         Redirect (LoginUrl + "?" + extraQueryString);
604                 }
605
606                 static void Redirect (string url)
607                 {
608                         HttpContext.Current.Response.Redirect (url);
609                 }
610
611                 static void Redirect (string url, bool end)
612                 {
613                         HttpContext.Current.Response.Redirect (url, end);
614                 }
615         }
616 }