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