FormsAuthentication.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. public FormsAuthentication ()
  74. {
  75. }
  76. public static bool Authenticate (string name, string password)
  77. {
  78. if (name == null || password == null)
  79. return false;
  80. Initialize ();
  81. HttpContext context = HttpContext.Current;
  82. if (context == null)
  83. throw new HttpException ("Context is null!");
  84. #if NET_2_0
  85. AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
  86. FormsAuthenticationCredentials config = section.Forms.Credentials;
  87. FormsAuthenticationUser user = config.Users[name];
  88. string stored = null;
  89. if (user != null)
  90. stored = user.Password;
  91. #else
  92. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  93. Hashtable users = config.CredentialUsers;
  94. string stored = users [name] as string;
  95. #endif
  96. if (stored == null)
  97. return false;
  98. switch (config.PasswordFormat) {
  99. case FormsAuthPasswordFormat.Clear:
  100. /* Do nothing */
  101. break;
  102. case FormsAuthPasswordFormat.MD5:
  103. password = HashPasswordForStoringInConfigFile (password, "MD5");
  104. break;
  105. case FormsAuthPasswordFormat.SHA1:
  106. password = HashPasswordForStoringInConfigFile (password, "SHA1");
  107. break;
  108. }
  109. return (password == stored);
  110. }
  111. static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
  112. {
  113. if (protection == FormsProtectionEnum.None)
  114. return FormsAuthenticationTicket.FromByteArray (bytes);
  115. #if NET_2_0
  116. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  117. #else
  118. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  119. #endif
  120. bool all = (protection == FormsProtectionEnum.All);
  121. byte [] result = bytes;
  122. if (all || protection == FormsProtectionEnum.Encryption) {
  123. ICryptoTransform decryptor;
  124. decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
  125. result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
  126. bytes = null;
  127. }
  128. if (all || protection == FormsProtectionEnum.Validation) {
  129. int count;
  130. MachineKeyValidation validationType;
  131. #if NET_2_0
  132. validationType = config.Validation;
  133. #else
  134. validationType = config.ValidationType;
  135. #endif
  136. if (validationType == MachineKeyValidation.MD5)
  137. count = MD5_hash_size;
  138. else
  139. count = SHA1_hash_size; // 3DES and SHA1
  140. #if NET_2_0
  141. byte [] vk = config.ValidationKeyBytes;
  142. #else
  143. byte [] vk = config.ValidationKey;
  144. #endif
  145. byte [] mix = new byte [result.Length - count + vk.Length];
  146. Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
  147. Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
  148. byte [] hash = null;
  149. switch (validationType) {
  150. case MachineKeyValidation.MD5:
  151. hash = MD5.Create ().ComputeHash (mix);
  152. break;
  153. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  154. case MachineKeyValidation.TripleDES:
  155. case MachineKeyValidation.SHA1:
  156. hash = SHA1.Create ().ComputeHash (mix);
  157. break;
  158. }
  159. if (result.Length < count)
  160. throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
  161. int i, k;
  162. for (i = result.Length - count, k = 0; k < count; i++, k++) {
  163. if (result [i] != hash [k])
  164. throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
  165. }
  166. }
  167. return FormsAuthenticationTicket.FromByteArray (result);
  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. Initialize ();
  174. FormsAuthenticationTicket ticket;
  175. #if NET_2_0
  176. byte [] bytes = MachineKeySection.GetBytes (encryptedTicket, encryptedTicket.Length);
  177. #else
  178. byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
  179. #endif
  180. try {
  181. ticket = Decrypt2 (bytes);
  182. } catch (Exception) {
  183. ticket = null;
  184. }
  185. return ticket;
  186. }
  187. public static string Encrypt (FormsAuthenticationTicket ticket)
  188. {
  189. if (ticket == null)
  190. throw new ArgumentNullException ("ticket");
  191. Initialize ();
  192. byte [] ticket_bytes = ticket.ToByteArray ();
  193. if (protection == FormsProtectionEnum.None)
  194. return GetHexString (ticket_bytes);
  195. byte [] result = ticket_bytes;
  196. #if NET_2_0
  197. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  198. #else
  199. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  200. #endif
  201. bool all = (protection == FormsProtectionEnum.All);
  202. if (all || protection == FormsProtectionEnum.Validation) {
  203. byte [] valid_bytes = null;
  204. #if NET_2_0
  205. byte [] vk = config.ValidationKeyBytes;
  206. #else
  207. byte [] vk = config.ValidationKey;
  208. #endif
  209. byte [] mix = new byte [ticket_bytes.Length + vk.Length];
  210. Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
  211. Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
  212. switch (
  213. #if NET_2_0
  214. config.Validation
  215. #else
  216. config.ValidationType
  217. #endif
  218. ) {
  219. case MachineKeyValidation.MD5:
  220. valid_bytes = MD5.Create ().ComputeHash (mix);
  221. break;
  222. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  223. case MachineKeyValidation.TripleDES:
  224. case MachineKeyValidation.SHA1:
  225. valid_bytes = SHA1.Create ().ComputeHash (mix);
  226. break;
  227. }
  228. int tlen = ticket_bytes.Length;
  229. int vlen = valid_bytes.Length;
  230. result = new byte [tlen + vlen];
  231. Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
  232. Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
  233. }
  234. if (all || protection == FormsProtectionEnum.Encryption) {
  235. ICryptoTransform encryptor;
  236. encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
  237. result = encryptor.TransformFinalBlock (result, 0, result.Length);
  238. }
  239. return GetHexString (result);
  240. }
  241. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  242. {
  243. return GetAuthCookie (userName, createPersistentCookie, null);
  244. }
  245. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  246. {
  247. Initialize ();
  248. if (userName == null)
  249. userName = String.Empty;
  250. if (strCookiePath == null || strCookiePath.Length == 0)
  251. strCookiePath = cookiePath;
  252. DateTime now = DateTime.Now;
  253. DateTime then;
  254. if (createPersistentCookie)
  255. then = now.AddYears (50);
  256. else
  257. then = now.AddMinutes (timeout);
  258. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  259. userName,
  260. now,
  261. then,
  262. createPersistentCookie,
  263. String.Empty,
  264. cookiePath);
  265. if (!createPersistentCookie)
  266. then = DateTime.MinValue;
  267. HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  268. if (requireSSL)
  269. cookie.Secure = true;
  270. return cookie;
  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 NET_2_0
  327. AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (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 = MapUrl(config.DefaultUrl);
  339. enable_crossapp_redirects = config.EnableCrossAppRedirects;
  340. login_url = MapUrl(config.LoginUrl);
  341. #else
  342. HttpContext context = HttpContext.Current;
  343. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  344. if (authConfig != null) {
  345. cookieName = authConfig.CookieName;
  346. timeout = authConfig.Timeout;
  347. cookiePath = authConfig.CookiePath;
  348. protection = authConfig.Protection;
  349. #if NET_1_1
  350. requireSSL = authConfig.RequireSSL;
  351. slidingExpiration = authConfig.SlidingExpiration;
  352. #endif
  353. } else {
  354. cookieName = ".MONOAUTH";
  355. timeout = 30;
  356. cookiePath = "/";
  357. protection = FormsProtectionEnum.All;
  358. #if NET_1_1
  359. slidingExpiration = true;
  360. #endif
  361. }
  362. #endif
  363. // IV is 8 bytes long for 3DES
  364. init_vector = new byte [8];
  365. int len = cookieName.Length;
  366. for (int i = 0; i < 8; i++) {
  367. if (i >= len)
  368. break;
  369. init_vector [i] = (byte) cookieName [i];
  370. }
  371. initialized = true;
  372. }
  373. }
  374. static string MapUrl (string url) {
  375. if (UrlUtils.IsRelativeUrl (url))
  376. return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
  377. else
  378. return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
  379. }
  380. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  381. {
  382. RedirectFromLoginPage (userName, createPersistentCookie, null);
  383. }
  384. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  385. {
  386. if (userName == null)
  387. return;
  388. Initialize ();
  389. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  390. Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  391. }
  392. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  393. {
  394. if (tOld == null)
  395. return null;
  396. DateTime now = DateTime.Now;
  397. TimeSpan toIssue = now - tOld.IssueDate;
  398. TimeSpan toExpiration = tOld.Expiration - now;
  399. if (toExpiration > toIssue)
  400. return tOld;
  401. FormsAuthenticationTicket tNew = tOld.Clone ();
  402. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  403. return tNew;
  404. }
  405. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  406. {
  407. Initialize ();
  408. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  409. }
  410. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  411. {
  412. HttpContext context = HttpContext.Current;
  413. if (context == null)
  414. throw new HttpException ("Context is null!");
  415. HttpResponse response = context.Response;
  416. if (response == null)
  417. throw new HttpException ("Response is null!");
  418. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  419. }
  420. public static void SignOut ()
  421. {
  422. Initialize ();
  423. HttpContext context = HttpContext.Current;
  424. if (context == null)
  425. throw new HttpException ("Context is null!");
  426. HttpResponse response = context.Response;
  427. if (response == null)
  428. throw new HttpException ("Response is null!");
  429. HttpCookieCollection cc = response.Cookies;
  430. cc.Remove (cookieName);
  431. HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
  432. expiration_cookie.Expires = new DateTime (1999, 10, 12);
  433. expiration_cookie.Path = cookiePath;
  434. cc.Add (expiration_cookie);
  435. }
  436. public static string FormsCookieName
  437. {
  438. get {
  439. Initialize ();
  440. return cookieName;
  441. }
  442. }
  443. public static string FormsCookiePath
  444. {
  445. get {
  446. Initialize ();
  447. return cookiePath;
  448. }
  449. }
  450. #if NET_1_1
  451. public static bool RequireSSL {
  452. get {
  453. Initialize ();
  454. return requireSSL;
  455. }
  456. }
  457. public static bool SlidingExpiration {
  458. get {
  459. Initialize ();
  460. return slidingExpiration;
  461. }
  462. }
  463. #endif
  464. #if NET_2_0
  465. public static string CookieDomain {
  466. get { Initialize (); return cookie_domain; }
  467. }
  468. public static HttpCookieMode CookieMode {
  469. get { Initialize (); return cookie_mode; }
  470. }
  471. public static bool CookiesSupported {
  472. get { Initialize (); return cookies_supported; }
  473. }
  474. public static string DefaultUrl {
  475. get { Initialize (); return default_url; }
  476. }
  477. public static bool EnableCrossAppRedirects {
  478. get { Initialize (); return enable_crossapp_redirects; }
  479. }
  480. public static string LoginUrl {
  481. get { Initialize (); return login_url; }
  482. }
  483. public static void RedirectToLoginPage ()
  484. {
  485. Redirect (LoginUrl);
  486. }
  487. [MonoTODO ("needs more tests")]
  488. public static void RedirectToLoginPage (string extraQueryString)
  489. {
  490. // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
  491. Redirect (LoginUrl + "?" + extraQueryString);
  492. }
  493. #endif
  494. private static void Redirect (string url)
  495. {
  496. HttpContext.Current.Response.Redirect (url);
  497. }
  498. private static void Redirect (string url, bool end)
  499. {
  500. HttpContext.Current.Response.Redirect (url, end);
  501. }
  502. }
  503. }