FormsAuthentication.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. //
  2. // System.Web.Security.FormsAuthentication
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. // Copyright (c) 2005 Novell, Inc (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Collections;
  31. using System.IO;
  32. using System.Security.Cryptography;
  33. using System.Security.Permissions;
  34. using System.Text;
  35. using System.Web;
  36. using System.Web.Configuration;
  37. using System.Web.Util;
  38. namespace System.Web.Security
  39. {
  40. // CAS - no InheritanceDemand here as the class is sealed
  41. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  42. public sealed class FormsAuthentication
  43. {
  44. const int MD5_hash_size = 16;
  45. const int SHA1_hash_size = 20;
  46. static string authConfigPath = "system.web/authentication";
  47. static string machineKeyConfigPath = "system.web/machineKey";
  48. static bool initialized;
  49. static string cookieName;
  50. static string cookiePath;
  51. static int timeout;
  52. static FormsProtectionEnum protection;
  53. static object locker = new object ();
  54. static byte [] init_vector; // initialization vector used for 3DES
  55. #if NET_1_1
  56. static bool requireSSL;
  57. static bool slidingExpiration;
  58. #endif
  59. #if NET_2_0
  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. #endif
  67. // same names and order used in xsp
  68. static string [] indexFiles = { "index.aspx",
  69. "Default.aspx",
  70. "default.aspx",
  71. "index.html",
  72. "index.htm" };
  73. #if NET_2_0
  74. [Obsolete]
  75. #endif
  76. public FormsAuthentication ()
  77. {
  78. }
  79. public static bool Authenticate (string name, string password)
  80. {
  81. if (name == null || password == null)
  82. return false;
  83. Initialize ();
  84. HttpContext context = HttpContext.Current;
  85. if (context == null)
  86. throw new HttpException ("Context is null!");
  87. #if CONFIGURATION_2_0
  88. AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetWebApplicationSection (authConfigPath);
  89. FormsAuthenticationCredentials config = section.Forms.Credentials;
  90. FormsAuthenticationUser user = config.Users[name];
  91. string stored = null;
  92. if (user != null)
  93. stored = user.Password;
  94. #else
  95. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  96. Hashtable users = config.CredentialUsers;
  97. string stored = users [name] as string;
  98. #endif
  99. if (stored == null)
  100. return false;
  101. switch (config.PasswordFormat) {
  102. case FormsAuthPasswordFormat.Clear:
  103. /* Do nothing */
  104. break;
  105. case FormsAuthPasswordFormat.MD5:
  106. password = HashPasswordForStoringInConfigFile (password, "MD5");
  107. break;
  108. case FormsAuthPasswordFormat.SHA1:
  109. password = HashPasswordForStoringInConfigFile (password, "SHA1");
  110. break;
  111. }
  112. return (password == stored);
  113. }
  114. static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
  115. {
  116. if (protection == FormsProtectionEnum.None)
  117. return FormsAuthenticationTicket.FromByteArray (bytes);
  118. #if CONFIGURATION_2_0
  119. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  120. #else
  121. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  122. #endif
  123. bool all = (protection == FormsProtectionEnum.All);
  124. byte [] result = bytes;
  125. if (all || protection == FormsProtectionEnum.Encryption) {
  126. ICryptoTransform decryptor;
  127. decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
  128. result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
  129. bytes = null;
  130. }
  131. if (all || protection == FormsProtectionEnum.Validation) {
  132. int count;
  133. MachineKeyValidation validationType;
  134. #if CONFIGURATION_2_0
  135. validationType = config.Validation;
  136. #else
  137. validationType = config.ValidationType;
  138. #endif
  139. if (validationType == MachineKeyValidation.MD5)
  140. count = MD5_hash_size;
  141. else
  142. count = SHA1_hash_size; // 3DES and SHA1
  143. #if CONFIGURATION_2_0
  144. byte [] vk = config.ValidationKeyBytes;
  145. #else
  146. byte [] vk = config.ValidationKey;
  147. #endif
  148. byte [] mix = new byte [result.Length - count + vk.Length];
  149. Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
  150. Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
  151. byte [] hash = null;
  152. switch (validationType) {
  153. case MachineKeyValidation.MD5:
  154. hash = MD5.Create ().ComputeHash (mix);
  155. break;
  156. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  157. case MachineKeyValidation.TripleDES:
  158. case MachineKeyValidation.SHA1:
  159. hash = SHA1.Create ().ComputeHash (mix);
  160. break;
  161. }
  162. if (result.Length < count)
  163. throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
  164. int i, k;
  165. for (i = result.Length - count, k = 0; k < count; i++, k++) {
  166. if (result [i] != hash [k])
  167. throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
  168. }
  169. }
  170. return FormsAuthenticationTicket.FromByteArray (result);
  171. }
  172. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  173. {
  174. if (encryptedTicket == null || encryptedTicket == String.Empty)
  175. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  176. Initialize ();
  177. FormsAuthenticationTicket ticket;
  178. #if CONFIGURATION_2_0
  179. byte [] bytes = MachineKeySection.GetBytes (encryptedTicket, encryptedTicket.Length);
  180. #else
  181. byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
  182. #endif
  183. try {
  184. ticket = Decrypt2 (bytes);
  185. } catch (Exception) {
  186. ticket = null;
  187. }
  188. return ticket;
  189. }
  190. public static string Encrypt (FormsAuthenticationTicket ticket)
  191. {
  192. if (ticket == null)
  193. throw new ArgumentNullException ("ticket");
  194. Initialize ();
  195. byte [] ticket_bytes = ticket.ToByteArray ();
  196. if (protection == FormsProtectionEnum.None)
  197. return GetHexString (ticket_bytes);
  198. byte [] result = ticket_bytes;
  199. #if CONFIGURATION_2_0
  200. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  201. #else
  202. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  203. #endif
  204. bool all = (protection == FormsProtectionEnum.All);
  205. if (all || protection == FormsProtectionEnum.Validation) {
  206. byte [] valid_bytes = null;
  207. #if CONFIGURATION_2_0
  208. byte [] vk = config.ValidationKeyBytes;
  209. #else
  210. byte [] vk = config.ValidationKey;
  211. #endif
  212. byte [] mix = new byte [ticket_bytes.Length + vk.Length];
  213. Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
  214. Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
  215. switch (
  216. #if CONFIGURATION_2_0
  217. config.Validation
  218. #else
  219. config.ValidationType
  220. #endif
  221. ) {
  222. case MachineKeyValidation.MD5:
  223. valid_bytes = MD5.Create ().ComputeHash (mix);
  224. break;
  225. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  226. case MachineKeyValidation.TripleDES:
  227. case MachineKeyValidation.SHA1:
  228. valid_bytes = SHA1.Create ().ComputeHash (mix);
  229. break;
  230. }
  231. int tlen = ticket_bytes.Length;
  232. int vlen = valid_bytes.Length;
  233. result = new byte [tlen + vlen];
  234. Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
  235. Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
  236. }
  237. if (all || protection == FormsProtectionEnum.Encryption) {
  238. ICryptoTransform encryptor;
  239. encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
  240. result = encryptor.TransformFinalBlock (result, 0, result.Length);
  241. }
  242. return GetHexString (result);
  243. }
  244. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  245. {
  246. return GetAuthCookie (userName, createPersistentCookie, null);
  247. }
  248. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  249. {
  250. Initialize ();
  251. if (userName == null)
  252. userName = String.Empty;
  253. if (strCookiePath == null || strCookiePath.Length == 0)
  254. strCookiePath = cookiePath;
  255. DateTime now = DateTime.Now;
  256. DateTime then;
  257. if (createPersistentCookie)
  258. then = now.AddYears (50);
  259. else
  260. then = now.AddMinutes (timeout);
  261. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  262. userName,
  263. now,
  264. then,
  265. createPersistentCookie,
  266. String.Empty,
  267. cookiePath);
  268. if (!createPersistentCookie)
  269. then = DateTime.MinValue;
  270. return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  271. }
  272. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  273. {
  274. if (userName == null)
  275. return null;
  276. Initialize ();
  277. HttpRequest request = HttpContext.Current.Request;
  278. string returnUrl = request ["RETURNURL"];
  279. if (returnUrl != null)
  280. return returnUrl;
  281. returnUrl = request.ApplicationPath;
  282. string apppath = request.PhysicalApplicationPath;
  283. bool found = false;
  284. foreach (string indexFile in indexFiles) {
  285. string filePath = Path.Combine (apppath, indexFile);
  286. if (File.Exists (filePath)) {
  287. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  288. found = true;
  289. break;
  290. }
  291. }
  292. if (!found)
  293. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  294. return returnUrl;
  295. }
  296. static string GetHexString (byte [] bytes)
  297. {
  298. StringBuilder result = new StringBuilder (bytes.Length * 2);
  299. foreach (byte b in bytes)
  300. result.AppendFormat ("{0:X2}", (int) b);
  301. return result.ToString ();
  302. }
  303. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  304. {
  305. if (password == null)
  306. throw new ArgumentNullException ("password");
  307. if (passwordFormat == null)
  308. throw new ArgumentNullException ("passwordFormat");
  309. byte [] bytes;
  310. if (String.Compare (passwordFormat, "MD5", true) == 0) {
  311. bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  312. } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
  313. bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  314. } else {
  315. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  316. }
  317. return GetHexString (bytes);
  318. }
  319. public static void Initialize ()
  320. {
  321. if (initialized)
  322. return;
  323. lock (locker) {
  324. if (initialized)
  325. return;
  326. #if CONFIGURATION_2_0
  327. AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection (authConfigPath);
  328. FormsAuthenticationConfiguration config = section.Forms;
  329. cookieName = config.Name;
  330. timeout = (int)config.Timeout.TotalMinutes;
  331. cookiePath = config.Path;
  332. protection = config.Protection;
  333. requireSSL = config.RequireSSL;
  334. slidingExpiration = config.SlidingExpiration;
  335. cookie_domain = config.Domain;
  336. cookie_mode = config.Cookieless;
  337. cookies_supported = true; /* XXX ? */
  338. default_url = config.DefaultUrl;
  339. enable_crossapp_redirects = config.EnableCrossAppRedirects;
  340. login_url = config.LoginUrl;
  341. #else
  342. HttpContext context = HttpContext.Current;
  343. #if NET_2_0
  344. AuthConfig authConfig = null;
  345. if (context != null)
  346. authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  347. #else
  348. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  349. #endif
  350. if (authConfig != null) {
  351. cookieName = authConfig.CookieName;
  352. timeout = authConfig.Timeout;
  353. cookiePath = authConfig.CookiePath;
  354. protection = authConfig.Protection;
  355. #if NET_1_1
  356. requireSSL = authConfig.RequireSSL;
  357. slidingExpiration = authConfig.SlidingExpiration;
  358. #endif
  359. #if NET_2_0
  360. cookie_domain = authConfig.CookieDomain;
  361. cookie_mode = authConfig.CookieMode;
  362. cookies_supported = authConfig.CookiesSupported;
  363. default_url = authConfig.DefaultUrl;
  364. enable_crossapp_redirects = authConfig.EnableCrossAppRedirects;
  365. login_url = authConfig.LoginUrl;
  366. #endif
  367. } else {
  368. cookieName = ".MONOAUTH";
  369. timeout = 30;
  370. cookiePath = "/";
  371. protection = FormsProtectionEnum.All;
  372. #if NET_1_1
  373. slidingExpiration = true;
  374. #endif
  375. #if NET_2_0
  376. cookie_domain = String.Empty;
  377. cookie_mode = HttpCookieMode.UseDeviceProfile;
  378. cookies_supported = true;
  379. default_url = "/default.aspx";
  380. login_url = "/login.aspx";
  381. #endif
  382. }
  383. #endif
  384. // IV is 8 bytes long for 3DES
  385. init_vector = new byte [8];
  386. int len = cookieName.Length;
  387. for (int i = 0; i < 8; i++) {
  388. if (i >= len)
  389. break;
  390. init_vector [i] = (byte) cookieName [i];
  391. }
  392. initialized = true;
  393. }
  394. }
  395. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  396. {
  397. RedirectFromLoginPage (userName, createPersistentCookie, null);
  398. }
  399. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  400. {
  401. if (userName == null)
  402. return;
  403. Initialize ();
  404. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  405. Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  406. }
  407. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  408. {
  409. if (tOld == null)
  410. return null;
  411. DateTime now = DateTime.Now;
  412. TimeSpan toIssue = now - tOld.IssueDate;
  413. TimeSpan toExpiration = tOld.Expiration - now;
  414. if (toExpiration > toIssue)
  415. return tOld;
  416. FormsAuthenticationTicket tNew = tOld.Clone ();
  417. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  418. return tNew;
  419. }
  420. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  421. {
  422. Initialize ();
  423. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  424. }
  425. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  426. {
  427. HttpContext context = HttpContext.Current;
  428. if (context == null)
  429. throw new HttpException ("Context is null!");
  430. HttpResponse response = context.Response;
  431. if (response == null)
  432. throw new HttpException ("Response is null!");
  433. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  434. }
  435. public static void SignOut ()
  436. {
  437. Initialize ();
  438. HttpContext context = HttpContext.Current;
  439. if (context == null)
  440. throw new HttpException ("Context is null!");
  441. HttpResponse response = context.Response;
  442. if (response == null)
  443. throw new HttpException ("Response is null!");
  444. HttpCookieCollection cc = response.Cookies;
  445. cc.Remove (cookieName);
  446. HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
  447. expiration_cookie.Expires = new DateTime (1999, 10, 12);
  448. expiration_cookie.Path = cookiePath;
  449. cc.Add (expiration_cookie);
  450. }
  451. public static string FormsCookieName
  452. {
  453. get {
  454. Initialize ();
  455. return cookieName;
  456. }
  457. }
  458. public static string FormsCookiePath
  459. {
  460. get {
  461. Initialize ();
  462. return cookiePath;
  463. }
  464. }
  465. #if NET_1_1
  466. public static bool RequireSSL {
  467. get {
  468. Initialize ();
  469. return requireSSL;
  470. }
  471. }
  472. public static bool SlidingExpiration {
  473. get {
  474. Initialize ();
  475. return slidingExpiration;
  476. }
  477. }
  478. #endif
  479. #if NET_2_0
  480. public static string CookieDomain {
  481. get { return cookie_domain; }
  482. }
  483. public static HttpCookieMode CookieMode {
  484. get { return cookie_mode; }
  485. }
  486. public static bool CookiesSupported {
  487. get { return cookies_supported; }
  488. }
  489. public static string DefaultUrl {
  490. get { return default_url; }
  491. }
  492. public static bool EnableCrossAppRedirects {
  493. get { return enable_crossapp_redirects; }
  494. }
  495. public static string LoginUrl {
  496. get { return login_url; }
  497. }
  498. public static void RedirectToLoginPage ()
  499. {
  500. Redirect (LoginUrl);
  501. }
  502. [MonoTODO ("needs more tests")]
  503. public static void RedirectToLoginPage (string extraQueryString)
  504. {
  505. // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
  506. Redirect (LoginUrl + "?" + extraQueryString);
  507. }
  508. #endif
  509. private static void Redirect (string url)
  510. {
  511. HttpContext.Current.Response.Redirect (url);
  512. }
  513. private static void Redirect (string url, bool end)
  514. {
  515. HttpContext.Current.Response.Redirect (url, end);
  516. }
  517. }
  518. }