Merge branch 'cecil-light'
[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 void EnableFormsAuthentication (NameValueCollection configurationData)
176                 {
177                         BuildManager.AssertPreStartMethodsRunning ();
178                         if (configurationData == null || configurationData.Count == 0)
179                                 return;
180
181                         string value = configurationData ["loginUrl"];
182                         if (!String.IsNullOrEmpty (value))
183                                 login_url = value;
184
185                         value = configurationData ["defaultUrl"];
186                         if (!String.IsNullOrEmpty (value))
187                                 default_url = value;
188                 }
189 #endif
190                 public FormsAuthentication ()
191                 {
192                 }
193
194                 public static bool Authenticate (string name, string password)
195                 {
196                         if (name == null || password == null)
197                                 return false;
198
199                         Initialize ();
200                         HttpContext context = HttpContext.Current;
201                         if (context == null)
202                                 throw new HttpException ("Context is null!");
203
204                         name = name.ToLower (Helpers.InvariantCulture);
205
206                         AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
207                         FormsAuthenticationCredentials config = section.Forms.Credentials;
208                         FormsAuthenticationUser user = config.Users[name];
209                         string stored = null;
210
211                         if (user != null)
212                                 stored = user.Password;
213
214                         if (stored == null)
215                                 return false;
216
217                         bool caseInsensitive = true;
218                         switch (config.PasswordFormat) {
219                                 case FormsAuthPasswordFormat.Clear:
220                                         caseInsensitive = false;
221                                         /* Do nothing */
222                                         break;
223                                 case FormsAuthPasswordFormat.MD5:
224                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
225                                         break;
226                                 case FormsAuthPasswordFormat.SHA1:
227                                         password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
228                                         break;
229                         }
230
231                         return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
232                 }
233
234                 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
235                 {
236                         if (protection == FormsProtectionEnum.None)
237                                 return FormsAuthenticationTicket.FromByteArray (bytes);
238
239                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
240                         byte [] result = null;
241                         if (protection == FormsProtectionEnum.All) {
242                                 result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
243                         } else if (protection == FormsProtectionEnum.Encryption) {
244                                 result = MachineKeySectionUtils.Decrypt (config, bytes);
245                         } else if (protection == FormsProtectionEnum.Validation) {
246                                 result = MachineKeySectionUtils.Verify (config, bytes);
247                         }
248
249                         return FormsAuthenticationTicket.FromByteArray (result);
250                 }
251
252                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
253                 {
254                         if (String.IsNullOrEmpty (encryptedTicket))
255                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
256
257                         Initialize ();
258
259                         FormsAuthenticationTicket ticket;
260                         byte [] bytes = Convert.FromBase64String (encryptedTicket);
261
262                         try {
263                                 ticket = Decrypt2 (bytes);
264                         } catch (Exception) {
265                                 ticket = null;
266                         }
267
268                         return ticket;
269                 }
270
271                 public static string Encrypt (FormsAuthenticationTicket ticket)
272                 {
273                         if (ticket == null)
274                                 throw new ArgumentNullException ("ticket");
275
276                         Initialize ();
277                         byte [] ticket_bytes = ticket.ToByteArray ();
278                         if (protection == FormsProtectionEnum.None)
279                                 return Convert.ToBase64String (ticket_bytes);
280
281                         byte [] result = null;
282                         MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
283
284                         if (protection == FormsProtectionEnum.All) {
285                                 result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
286                         } else if (protection == FormsProtectionEnum.Encryption) {
287                                 result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
288                         } else if (protection == FormsProtectionEnum.Validation) {
289                                 result = MachineKeySectionUtils.Sign (config, ticket_bytes);
290                         }
291
292                         return Convert.ToBase64String (result);
293                 }
294
295                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
296                 {
297                         return GetAuthCookie (userName, createPersistentCookie, null);
298                 }
299
300                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
301                 {
302                         Initialize ();
303
304                         if (userName == null)
305                                 userName = String.Empty;
306
307                         if (strCookiePath == null || strCookiePath.Length == 0)
308                                 strCookiePath = cookiePath;
309
310                         DateTime now = DateTime.Now;
311                         DateTime then;
312                         if (createPersistentCookie)
313                                 then = now.AddYears (50);
314                         else
315                                 then = now.AddMinutes (timeout);
316
317                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
318                                                                                           userName,
319                                                                                           now,
320                                                                                           then,
321                                                                                           createPersistentCookie,
322                                                                                           String.Empty,
323                                                                                           cookiePath);
324
325                         if (!createPersistentCookie)
326                                 then = DateTime.MinValue;
327
328                         HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
329                         if (requireSSL)
330                                 cookie.Secure = true;
331                         if (!String.IsNullOrEmpty (cookie_domain))
332                                 cookie.Domain = cookie_domain;
333
334                         return cookie;
335                 }
336
337                 internal static string ReturnUrl {
338                         get { return HttpContext.Current.Request ["RETURNURL"]; }
339                 }
340
341                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
342                 {
343                         if (userName == null)
344                                 return null;
345
346                         Initialize ();
347                         HttpRequest request = HttpContext.Current.Request;
348                         string returnUrl = ReturnUrl;
349                         if (returnUrl != null)
350                                 return returnUrl;
351
352                         returnUrl = request.ApplicationPath;
353                         string apppath = request.PhysicalApplicationPath;
354                         bool found = false;
355
356                         foreach (string indexFile in indexFiles) {
357                                 string filePath = Path.Combine (apppath, indexFile);
358                                 if (File.Exists (filePath)) {
359                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
360                                         found = true;
361                                         break;
362                                 }
363                         }
364
365                         if (!found)
366                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
367
368                         return returnUrl;
369                 }
370
371                 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
372                 {
373                         if (password == null)
374                                 throw new ArgumentNullException ("password");
375                         
376                         byte [] bytes;
377                         switch (passwordFormat) {
378                                 case FormsAuthPasswordFormat.MD5:
379                                         bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
380                                         break;
381
382                                 case FormsAuthPasswordFormat.SHA1:
383                                         bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
384                                         break;
385
386                                 default:
387                                         throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
388                         }
389
390                         return MachineKeySectionUtils.GetHexString (bytes);
391                 }
392                 
393                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
394                 {
395                         if (password == null)
396                                 throw new ArgumentNullException ("password");
397
398                         if (passwordFormat == null)
399                                 throw new ArgumentNullException ("passwordFormat");
400
401                         if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
402                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
403                         } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
404                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
405                         } else {
406                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
407                         }
408                 }
409
410                 public static void Initialize ()
411                 {
412                         if (initialized)
413                                 return;
414
415                         lock (locker) {
416                                 if (initialized)
417                                         return;
418
419                                 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
420                                 FormsAuthenticationConfiguration config = section.Forms;
421
422                                 cookieName = config.Name;
423                                 timeout = (int)config.Timeout.TotalMinutes;
424                                 cookiePath = config.Path;
425                                 protection = config.Protection;
426                                 requireSSL = config.RequireSSL;
427                                 slidingExpiration = config.SlidingExpiration;
428                                 cookie_domain = config.Domain;
429                                 cookie_mode = config.Cookieless;
430                                 cookies_supported = true; /* XXX ? */
431 #if NET_4_0
432                                 if (!String.IsNullOrEmpty (default_url))
433                                         default_url = MapUrl (default_url);
434                                 else
435 #endif
436                                         default_url = MapUrl(config.DefaultUrl);
437                                 enable_crossapp_redirects = config.EnableCrossAppRedirects;
438 #if NET_4_0
439                                 if (!String.IsNullOrEmpty (login_url))
440                                         login_url = MapUrl (login_url);
441                                 else
442 #endif
443                                         login_url = MapUrl(config.LoginUrl);
444
445                                 initialized = true;
446                         }
447                 }
448
449                 static string MapUrl (string url) {
450                         if (UrlUtils.IsRelativeUrl (url))
451                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
452                         else
453                                 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
454                 }
455
456                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
457                 {
458                         RedirectFromLoginPage (userName, createPersistentCookie, null);
459                 }
460
461                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
462                 {
463                         if (userName == null)
464                                 return;
465
466                         Initialize ();
467                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
468                         Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
469                 }
470
471                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
472                 {
473                         if (tOld == null)
474                                 return null;
475
476                         DateTime now = DateTime.Now;
477                         TimeSpan toIssue = now - tOld.IssueDate;
478                         TimeSpan toExpiration = tOld.Expiration - now;
479                         if (toExpiration > toIssue)
480                                 return tOld;
481
482                         FormsAuthenticationTicket tNew = tOld.Clone ();
483                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
484                         return tNew;
485                 }
486
487                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
488                 {
489                         Initialize ();
490                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
491                 }
492
493                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
494                 {
495                         HttpContext context = HttpContext.Current;
496                         if (context == null)
497                                 throw new HttpException ("Context is null!");
498
499                         HttpResponse response = context.Response;
500                         if (response == null)
501                                 throw new HttpException ("Response is null!");
502
503                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
504                 }
505
506                 public static void SignOut ()
507                 {
508                         Initialize ();
509
510                         HttpContext context = HttpContext.Current;
511                         if (context == null)
512                                 throw new HttpException ("Context is null!");
513
514                         HttpResponse response = context.Response;
515                         if (response == null)
516                                 throw new HttpException ("Response is null!");
517
518                         HttpCookieCollection cc = response.Cookies;
519                         cc.Remove (cookieName);
520                         HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
521                         expiration_cookie.Expires = new DateTime (1999, 10, 12);
522                         expiration_cookie.Path = cookiePath;
523                         if (!String.IsNullOrEmpty (cookie_domain))
524                                 expiration_cookie.Domain = cookie_domain;
525                         cc.Add (expiration_cookie);
526                         Roles.DeleteCookie ();
527                 }
528
529                 public static string FormsCookieName
530                 {
531                         get {
532                                 Initialize ();
533                                 return cookieName;
534                         }
535                 }
536
537                 public static string FormsCookiePath
538                 {
539                         get {
540                                 Initialize ();
541                                 return cookiePath;
542                         }
543                 }
544
545                 public static bool RequireSSL {
546                         get {
547                                 Initialize ();
548                                 return requireSSL;
549                         }
550                 }
551
552                 public static bool SlidingExpiration {
553                         get {
554                                 Initialize ();
555                                 return slidingExpiration;
556                         }
557                 }
558
559                 public static string CookieDomain {
560                         get { Initialize (); return cookie_domain; }
561                 }
562
563                 public static HttpCookieMode CookieMode {
564                         get { Initialize (); return cookie_mode; }
565                 }
566
567                 public static bool CookiesSupported {
568                         get { Initialize (); return cookies_supported; }
569                 }
570
571                 public static string DefaultUrl {
572                         get { Initialize (); return default_url; }
573                 }
574
575                 public static bool EnableCrossAppRedirects {
576                         get { Initialize (); return enable_crossapp_redirects; }
577                 }
578
579                 public static string LoginUrl {
580                         get { Initialize (); return login_url; }
581                 }
582
583                 public static void RedirectToLoginPage ()
584                 {
585                         Redirect (LoginUrl);
586                 }
587
588                 [MonoTODO ("needs more tests")]
589                 public static void RedirectToLoginPage (string extraQueryString)
590                 {
591                         // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
592                         Redirect (LoginUrl + "?" + extraQueryString);
593                 }
594
595                 static void Redirect (string url)
596                 {
597                         HttpContext.Current.Response.Redirect (url);
598                 }
599
600                 static void Redirect (string url, bool end)
601                 {
602                         HttpContext.Current.Response.Redirect (url, end);
603                 }
604         }
605 }