FormsAuthentication.cs 13 KB

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