2005-09-09 Sebastien Pouliot <sebastien@ximian.com>
[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 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.Util;
40
41 namespace System.Web.Security
42 {
43         // CAS - no InheritanceDemand here as the class is sealed
44         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45         public sealed class FormsAuthentication
46         {
47                 const int MD5_hash_size = 16;
48                 const int SHA1_hash_size = 20;
49
50                 static string authConfigPath = "system.web/authentication";
51                 static bool initialized;
52                 static string cookieName;
53                 static string cookiePath;
54                 static int timeout;
55                 static FormsProtectionEnum protection;
56                 static object locker = new object ();
57                 static byte [] init_vector; // initialization vector used for 3DES
58 #if NET_1_1
59                 static bool requireSSL;
60                 static bool slidingExpiration;
61 #endif
62 #if NET_2_0
63                 static string cookie_domain;
64                 static HttpCookieMode cookie_mode;
65                 static bool cookies_supported;
66                 static string default_url;
67                 static bool enable_crossapp_redirects;
68                 static string login_url;
69 #endif
70                 // same names and order used in xsp
71                 static string [] indexFiles = { "index.aspx",
72                                                 "Default.aspx",
73                                                 "default.aspx",
74                                                 "index.html",
75                                                 "index.htm" };
76
77 #if NET_2_0
78                 [Obsolete]
79 #endif
80                 public FormsAuthentication ()
81                 {
82                 }
83
84                 public static bool Authenticate (string name, string password)
85                 {
86                         if (name == null || password == null)
87                                 return false;
88
89                         Initialize ();
90                         HttpContext context = HttpContext.Current;
91                         if (context == null)
92                                 throw new HttpException ("Context is null!");
93
94                         AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
95                         Hashtable users = config.CredentialUsers;
96                         string stored = users [name] as string;
97                         if (stored == null)
98                                 return false;
99
100                         switch (config.PasswordFormat) {
101                         case FormsAuthPasswordFormat.Clear:
102                                 /* Do nothing */
103                                 break;
104                         case FormsAuthPasswordFormat.MD5:
105                                 password = HashPasswordForStoringInConfigFile (password, "MD5");
106                                 break;
107                         case FormsAuthPasswordFormat.SHA1:
108                                 password = HashPasswordForStoringInConfigFile (password, "SHA1");
109                                 break;
110                         }
111
112                         return (password == stored);
113                 }
114
115                 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
116                 {
117                         if (protection == FormsProtectionEnum.None)
118                                 return FormsAuthenticationTicket.FromByteArray (bytes);
119
120                         MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
121                         bool all = (protection == FormsProtectionEnum.All);
122
123                         byte [] result = bytes;
124                         if (all || protection == FormsProtectionEnum.Encryption) {
125                                 ICryptoTransform decryptor;
126                                 decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
127                                 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
128                                 bytes = null;
129                         }
130
131                         if (all || protection == FormsProtectionEnum.Validation) {
132                                 int count;
133
134                                 if (config.ValidationType == MachineKeyValidation.MD5)
135                                         count = MD5_hash_size;
136                                 else
137                                         count = SHA1_hash_size; // 3DES and SHA1
138
139                                 byte [] vk = config.ValidationKey;
140                                 byte [] mix = new byte [result.Length - count + vk.Length];
141                                 Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
142                                 Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
143
144                                 byte [] hash = null;
145                                 switch (config.ValidationType) {
146                                 case MachineKeyValidation.MD5:
147                                         hash = MD5.Create ().ComputeHash (mix);
148                                         break;
149                                 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
150                                 case MachineKeyValidation.TripleDES:
151                                 case MachineKeyValidation.SHA1:
152                                         hash = SHA1.Create ().ComputeHash (mix);
153                                         break;
154                                 }
155
156                                 if (result.Length < count)
157                                         throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
158
159                                 int i, k;
160                                 for (i = result.Length - count, k = 0; k < count; i++, k++) {
161                                         if (result [i] != hash [k])
162                                                 throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
163                                 }
164                         }
165
166                         return FormsAuthenticationTicket.FromByteArray (result);
167                 }
168
169                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
170                 {
171                         if (encryptedTicket == null || encryptedTicket == String.Empty)
172                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
173
174                         Initialize ();
175
176                         FormsAuthenticationTicket ticket;
177                         byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
178                         try {
179                                 ticket = Decrypt2 (bytes);
180                         } catch (Exception) {
181                                 ticket = null;
182                         }
183
184                         return ticket;
185                 }
186
187                 public static string Encrypt (FormsAuthenticationTicket ticket)
188                 {
189                         if (ticket == null)
190                                 throw new ArgumentNullException ("ticket");
191
192                         Initialize ();
193                         byte [] ticket_bytes = ticket.ToByteArray ();
194                         if (protection == FormsProtectionEnum.None)
195                                 return GetHexString (ticket_bytes);
196
197                         byte [] result = ticket_bytes;
198                         MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
199                         bool all = (protection == FormsProtectionEnum.All);
200                         if (all || protection == FormsProtectionEnum.Validation) {
201                                 byte [] valid_bytes = null;
202                                 byte [] vk = config.ValidationKey;
203                                 byte [] mix = new byte [ticket_bytes.Length + vk.Length];
204                                 Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
205                                 Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
206
207                                 switch (config.ValidationType) {
208                                 case MachineKeyValidation.MD5:
209                                         valid_bytes = MD5.Create ().ComputeHash (mix);
210                                         break;
211                                 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
212                                 case MachineKeyValidation.TripleDES:
213                                 case MachineKeyValidation.SHA1:
214                                         valid_bytes = SHA1.Create ().ComputeHash (mix);
215                                         break;
216                                 }
217
218                                 int tlen = ticket_bytes.Length;
219                                 int vlen = valid_bytes.Length;
220                                 result = new byte [tlen + vlen];
221                                 Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
222                                 Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
223                         }
224
225                         if (all || protection == FormsProtectionEnum.Encryption) {
226                                 ICryptoTransform encryptor;
227                                 encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
228                                 result = encryptor.TransformFinalBlock (result, 0, result.Length);
229                         }
230
231                         return GetHexString (result);
232                 }
233
234                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
235                 {
236                         return GetAuthCookie (userName, createPersistentCookie, null);
237                 }
238
239                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
240                 {
241                         Initialize ();
242
243                         if (userName == null)
244                                 userName = String.Empty;
245
246                         if (strCookiePath == null || strCookiePath.Length == 0)
247                                 strCookiePath = cookiePath;
248
249                         DateTime now = DateTime.Now;
250                         DateTime then;
251                         if (createPersistentCookie)
252                                 then = now.AddYears (50);
253                         else
254                                 then = now.AddMinutes (timeout);
255
256                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
257                                                                                           userName,
258                                                                                           now,
259                                                                                           then,
260                                                                                           createPersistentCookie,
261                                                                                           String.Empty,
262                                                                                           cookiePath);
263
264                         if (!createPersistentCookie)
265                                 then = DateTime.MinValue;
266
267                         return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
268                 }
269
270                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
271                 {
272                         if (userName == null)
273                                 return null;
274
275                         Initialize ();
276                         HttpRequest request = HttpContext.Current.Request;
277                         string returnUrl = request ["RETURNURL"];
278                         if (returnUrl != null)
279                                 return returnUrl;
280
281                         returnUrl = request.ApplicationPath;
282                         string apppath = request.PhysicalApplicationPath;
283                         bool found = false;
284
285                         foreach (string indexFile in indexFiles) {
286                                 string filePath = Path.Combine (apppath, indexFile);
287                                 if (File.Exists (filePath)) {
288                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
289                                         found = true;
290                                         break;
291                                 }
292                         }
293
294                         if (!found)
295                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
296
297                         return returnUrl;
298                 }
299
300                 static string GetHexString (byte [] bytes)
301                 {
302                         StringBuilder result = new StringBuilder (bytes.Length * 2);
303                         foreach (byte b in bytes)
304                                 result.AppendFormat ("{0:X2}", (int) b);
305
306                         return result.ToString ();
307                 }
308
309                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
310                 {
311                         if (password == null)
312                                 throw new ArgumentNullException ("password");
313
314                         if (passwordFormat == null)
315                                 throw new ArgumentNullException ("passwordFormat");
316
317                         byte [] bytes;
318                         if (String.Compare (passwordFormat, "MD5", true) == 0) {
319                                 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
320                         } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
321                                 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
322                         } else {
323                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
324                         }
325
326                         return GetHexString (bytes);
327                 }
328
329                 public static void Initialize ()
330                 {
331                         if (initialized)
332                                 return;
333
334                         lock (locker) {
335                                 if (initialized)
336                                         return;
337
338                                 HttpContext context = HttpContext.Current;
339 #if NET_2_0
340                                 AuthConfig authConfig = null;
341                                 if (context != null)
342                                         authConfig = context.GetConfig (authConfigPath) as AuthConfig;
343 #else
344                                 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
345 #endif
346                                 if (authConfig != null) {
347                                         cookieName = authConfig.CookieName;
348                                         timeout = authConfig.Timeout;
349                                         cookiePath = authConfig.CookiePath;
350                                         protection = authConfig.Protection;
351 #if NET_1_1
352                                         requireSSL = authConfig.RequireSSL;
353                                         slidingExpiration = authConfig.SlidingExpiration;
354 #endif
355 #if NET_2_0
356                                         cookie_domain = authConfig.CookieDomain;
357                                         cookie_mode = authConfig.CookieMode;
358                                         cookies_supported = authConfig.CookiesSupported;
359                                         default_url = authConfig.DefaultUrl;
360                                         enable_crossapp_redirects = authConfig.EnableCrossAppRedirects;
361                                         login_url = authConfig.LoginUrl;
362 #endif
363                                 } else {
364                                         cookieName = ".MONOAUTH";
365                                         timeout = 30;
366                                         cookiePath = "/";
367                                         protection = FormsProtectionEnum.All;
368 #if NET_1_1
369                                         slidingExpiration = true;
370 #endif
371 #if NET_2_0
372                                         cookie_domain = String.Empty;
373                                         cookie_mode = HttpCookieMode.UseDeviceProfile;
374                                         cookies_supported = true;
375                                         default_url = "/default.aspx";
376                                         login_url = "/login.aspx";
377 #endif
378                                 }
379
380                                 // IV is 8 bytes long for 3DES
381                                 init_vector = new byte [8];
382                                 int len = cookieName.Length;
383                                 for (int i = 0; i < 8; i++) {
384                                         if (i >= len)
385                                                 break;
386
387                                         init_vector [i] = (byte) cookieName [i];
388                                 }
389
390                                 initialized = true;
391                         }
392                 }
393
394                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
395                 {
396                         RedirectFromLoginPage (userName, createPersistentCookie, null);
397                 }
398
399                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
400                 {
401                         if (userName == null)
402                                 return;
403
404                         Initialize ();
405                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
406                         Redirect (GetRedirectUrl (userName, createPersistentCookie));
407                 }
408
409                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
410                 {
411                         if (tOld == null)
412                                 return null;
413
414                         DateTime now = DateTime.Now;
415                         TimeSpan toIssue = now - tOld.IssueDate;
416                         TimeSpan toExpiration = tOld.Expiration - now;
417                         if (toExpiration > toIssue)
418                                 return tOld;
419
420                         FormsAuthenticationTicket tNew = tOld.Clone ();
421                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
422                         return tNew;
423                 }
424
425                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
426                 {
427                         Initialize ();
428                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
429                 }
430
431                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
432                 {
433                         HttpContext context = HttpContext.Current;
434                         if (context == null)
435                                 throw new HttpException ("Context is null!");
436
437                         HttpResponse response = context.Response;
438                         if (response == null)
439                                 throw new HttpException ("Response is null!");
440
441                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
442                 }
443
444                 public static void SignOut ()
445                 {
446                         Initialize ();
447
448                         HttpContext context = HttpContext.Current;
449                         if (context == null)
450                                 throw new HttpException ("Context is null!");
451
452                         HttpResponse response = context.Response;
453                         if (response == null)
454                                 throw new HttpException ("Response is null!");
455
456                         HttpCookieCollection cc = response.Cookies;
457                         cc.Remove (cookieName);
458                         HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
459                         expiration_cookie.Expires = new DateTime (1999, 10, 12);
460                         expiration_cookie.Path = cookiePath;
461                         cc.Add (expiration_cookie);
462                 }
463
464                 public static string FormsCookieName
465                 {
466                         get {
467                                 Initialize ();
468                                 return cookieName;
469                         }
470                 }
471
472                 public static string FormsCookiePath
473                 {
474                         get {
475                                 Initialize ();
476                                 return cookiePath;
477                         }
478                 }
479 #if NET_1_1
480                 public static bool RequireSSL {
481                         get {
482                                 Initialize ();
483                                 return requireSSL;
484                         }
485                 }
486
487                 public static bool SlidingExpiration {
488                         get {
489                                 Initialize ();
490                                 return slidingExpiration;
491                         }
492                 }
493 #endif
494
495 #if NET_2_0
496                 public static string CookieDomain {
497                         get { return cookie_domain; }
498                 }
499
500                 public static HttpCookieMode CookieMode {
501                         get { return cookie_mode; }
502                 }
503
504                 public static bool CookiesSupported {
505                         get { return cookies_supported; }
506                 }
507
508                 public static string DefaultUrl {
509                         get { return default_url; }
510                 }
511
512                 public static bool EnableCrossAppRedirects {
513                         get { return enable_crossapp_redirects; }
514                 }
515
516                 public static string LoginUrl {
517                         get { return login_url; }
518                 }
519
520                 public static void RedirectToLoginPage ()
521                 {
522                         Redirect (LoginUrl);
523                 }
524
525                 [MonoTODO ("needs more tests")]
526                 public static void RedirectToLoginPage (string extraQueryString)
527                 {
528                         // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
529                         Redirect (LoginUrl + "?" + extraQueryString);
530                 }
531 #endif
532                 private static void Redirect (string url)
533                 {
534                         HttpContext.Current.Response.Redirect (url);
535                 }
536         }
537 }