FormsAuthentication.cs 15 KB

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