Merge pull request #1949 from lewurm/fixtype
[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.AddMinutes(timeout);
218                         else
219                                 then = DateTime.MinValue;
220
221                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
222                                                                                           userName,
223                                                                                           now,
224                                               createPersistentCookie?then:now.AddYears (50),
225                                                                                           createPersistentCookie,
226                                                                                           String.Empty,
227                                                                                           cookiePath);
228
229                         HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
230                         if (requireSSL)
231                                 cookie.Secure = true;
232                         if (!String.IsNullOrEmpty (cookie_domain))
233                                 cookie.Domain = cookie_domain;
234
235                         return cookie;
236                 }
237
238                 internal static string ReturnUrl {
239                         get { return HttpContext.Current.Request ["RETURNURL"]; }
240                 }
241
242                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
243                 {
244                         if (userName == null)
245                                 return null;
246
247                         Initialize ();
248                         HttpRequest request = HttpContext.Current.Request;
249                         string returnUrl = ReturnUrl;
250                         if (returnUrl != null)
251                                 return returnUrl;
252
253                         returnUrl = request.ApplicationPath;
254                         string apppath = request.PhysicalApplicationPath;
255                         bool found = false;
256
257                         foreach (string indexFile in indexFiles) {
258                                 string filePath = Path.Combine (apppath, indexFile);
259                                 if (File.Exists (filePath)) {
260                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
261                                         found = true;
262                                         break;
263                                 }
264                         }
265
266                         if (!found)
267                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
268
269                         return returnUrl;
270                 }
271
272                 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
273                 {
274                         if (password == null)
275                                 throw new ArgumentNullException ("password");
276                         
277                         byte [] bytes;
278                         switch (passwordFormat) {
279                                 case FormsAuthPasswordFormat.MD5:
280                                         bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
281                                         break;
282
283                                 case FormsAuthPasswordFormat.SHA1:
284                                         bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
285                                         break;
286
287                                 default:
288                                         throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
289                         }
290
291                         return MachineKeySectionUtils.GetHexString (bytes);
292                 }
293                 
294                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
295                 {
296                         if (password == null)
297                                 throw new ArgumentNullException ("password");
298
299                         if (passwordFormat == null)
300                                 throw new ArgumentNullException ("passwordFormat");
301
302                         if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
303                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
304                         } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
305                                 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
306                         } else {
307                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
308                         }
309                 }
310
311                 public static void Initialize ()
312                 {
313                         if (initialized)
314                                 return;
315
316                         lock (locker) {
317                                 if (initialized)
318                                         return;
319
320                                 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
321                                 FormsAuthenticationConfiguration config = section.Forms;
322
323                                 cookieName = config.Name;
324                                 Timeout = config.Timeout;
325                                 timeout = (int)config.Timeout.TotalMinutes;
326                                 cookiePath = config.Path;
327                                 protection = config.Protection;
328                                 requireSSL = config.RequireSSL;
329                                 slidingExpiration = config.SlidingExpiration;
330                                 cookie_domain = config.Domain;
331                                 cookie_mode = config.Cookieless;
332                                 cookies_supported = true; /* XXX ? */
333                                 if (!String.IsNullOrEmpty (default_url))
334                                         default_url = MapUrl (default_url);
335                                 else
336                                         default_url = MapUrl(config.DefaultUrl);
337                                 enable_crossapp_redirects = config.EnableCrossAppRedirects;
338                                 if (!String.IsNullOrEmpty (login_url))
339                                         login_url = MapUrl (login_url);
340                                 else
341                                         login_url = MapUrl(config.LoginUrl);
342
343                                 initialized = true;
344                         }
345                 }
346
347                 static string MapUrl (string url) {
348                         if (UrlUtils.IsRelativeUrl (url))
349                                 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
350                         else
351                                 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
352                 }
353
354                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
355                 {
356                         RedirectFromLoginPage (userName, createPersistentCookie, null);
357                 }
358
359                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
360                 {
361                         if (userName == null)
362                                 return;
363
364                         Initialize ();
365                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
366                         Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
367                 }
368
369                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
370                 {
371                         if (tOld == null)
372                                 return null;
373
374                         DateTime now = DateTime.Now;
375                         TimeSpan toIssue = now - tOld.IssueDate;
376                         TimeSpan toExpiration = tOld.Expiration - now;
377                         if (toExpiration > toIssue)
378                                 return tOld;
379
380                         FormsAuthenticationTicket tNew = tOld.Clone ();
381                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
382                         return tNew;
383                 }
384
385                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
386                 {
387                         Initialize ();
388                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
389                 }
390
391                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
392                 {
393                         HttpContext context = HttpContext.Current;
394                         if (context == null)
395                                 throw new HttpException ("Context is null!");
396
397                         HttpResponse response = context.Response;
398                         if (response == null)
399                                 throw new HttpException ("Response is null!");
400
401                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
402                 }
403
404                 public static void SignOut ()
405                 {
406                         Initialize ();
407
408                         HttpContext context = HttpContext.Current;
409                         if (context == null)
410                                 throw new HttpException ("Context is null!");
411
412                         HttpResponse response = context.Response;
413                         if (response == null)
414                                 throw new HttpException ("Response is null!");
415
416                         HttpCookieCollection cc = response.Cookies;
417                         cc.Remove (cookieName);
418                         HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
419                         expiration_cookie.Expires = new DateTime (1999, 10, 12);
420                         expiration_cookie.Path = cookiePath;
421                         if (!String.IsNullOrEmpty (cookie_domain))
422                                 expiration_cookie.Domain = cookie_domain;
423                         cc.Add (expiration_cookie);
424                         Roles.DeleteCookie ();
425                 }
426
427                 public static string FormsCookieName
428                 {
429                         get {
430                                 Initialize ();
431                                 return cookieName;
432                         }
433                 }
434
435                 public static string FormsCookiePath
436                 {
437                         get {
438                                 Initialize ();
439                                 return cookiePath;
440                         }
441                 }
442
443                 public static bool RequireSSL {
444                         get {
445                                 Initialize ();
446                                 return requireSSL;
447                         }
448                 }
449
450                 public static bool SlidingExpiration {
451                         get {
452                                 Initialize ();
453                                 return slidingExpiration;
454                         }
455                 }
456
457                 public static string CookieDomain {
458                         get { Initialize (); return cookie_domain; }
459                 }
460
461                 public static HttpCookieMode CookieMode {
462                         get { Initialize (); return cookie_mode; }
463                 }
464
465                 public static bool CookiesSupported {
466                         get { Initialize (); return cookies_supported; }
467                 }
468
469                 public static string DefaultUrl {
470                         get { Initialize (); return default_url; }
471                 }
472
473                 public static bool EnableCrossAppRedirects {
474                         get { Initialize (); return enable_crossapp_redirects; }
475                 }
476
477                 public static string LoginUrl {
478                         get { Initialize (); return login_url; }
479                 }
480
481                 public static void RedirectToLoginPage ()
482                 {
483                         Redirect (LoginUrl);
484                 }
485
486                 [MonoTODO ("needs more tests")]
487                 public static void RedirectToLoginPage (string extraQueryString)
488                 {
489                         // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
490                         Redirect (LoginUrl + "?" + extraQueryString);
491                 }
492
493                 static void Redirect (string url)
494                 {
495                         HttpContext.Current.Response.Redirect (url);
496                 }
497
498                 static void Redirect (string url, bool end)
499                 {
500                         HttpContext.Current.Response.Redirect (url, end);
501                 }
502         }
503 }