RolePrincipal.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. //
  2. // System.Web.Security.RolePrincipal
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. // Sebastien Pouliot <[email protected]>
  7. //
  8. // (C) 2003 Ben Maurer
  9. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  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. #if NET_2_0
  31. using System.Collections.Specialized;
  32. using System.Security.Cryptography;
  33. using System.Security.Permissions;
  34. using System.Security.Principal;
  35. using System.Web.Configuration;
  36. using System.IO;
  37. using System.Text;
  38. namespace System.Web.Security {
  39. [Serializable]
  40. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  41. public sealed class RolePrincipal : IPrincipal {
  42. private IIdentity _identity;
  43. private bool _listChanged;
  44. private string[] _cachedArray;
  45. private HybridDictionary _cachedRoles;
  46. readonly string _providerName;
  47. private int _version = 1;
  48. private string _cookiePath;
  49. private DateTime _issueDate;
  50. private DateTime _exprireDate;
  51. public RolePrincipal (IIdentity identity)
  52. {
  53. if (identity == null)
  54. throw new ArgumentNullException ("identity");
  55. this._identity = identity;
  56. this._cookiePath = RoleManagerConfig.CookiePath;
  57. this._issueDate = DateTime.Now;
  58. this._exprireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout);
  59. }
  60. public RolePrincipal (IIdentity identity, string encryptedTicket)
  61. : this (identity)
  62. {
  63. DecryptTicket (encryptedTicket);
  64. }
  65. public RolePrincipal (string providerName, IIdentity identity)
  66. : this (identity)
  67. {
  68. if (providerName == null)
  69. throw new ArgumentNullException ("providerName");
  70. this._providerName = providerName;
  71. }
  72. public RolePrincipal (string providerName, IIdentity identity, string encryptedTicket)
  73. : this (providerName, identity)
  74. {
  75. DecryptTicket (encryptedTicket);
  76. }
  77. public string [] GetRoles ()
  78. {
  79. if (!_identity.IsAuthenticated)
  80. return new string[0];
  81. if (!IsRoleListCached && !Expired) {
  82. _cachedArray = Provider.GetRolesForUser (_identity.Name);
  83. _cachedRoles = new HybridDictionary (true);
  84. foreach (string r in _cachedArray)
  85. _cachedRoles.Add(r, r);
  86. _listChanged = true;
  87. }
  88. return _cachedArray;
  89. }
  90. public bool IsInRole (string role)
  91. {
  92. if (!_identity.IsAuthenticated)
  93. return false;
  94. GetRoles ();
  95. return _cachedRoles [role] != null;
  96. }
  97. public string ToEncryptedTicket ()
  98. {
  99. string roles = string.Join (",", GetRoles ());
  100. string cookiePath = RoleManagerConfig.CookiePath;
  101. int approxTicketLen = roles.Length + cookiePath.Length + 64;
  102. MemoryStream ticket = new MemoryStream (approxTicketLen);
  103. BinaryWriter writer = new BinaryWriter (ticket);
  104. // version
  105. writer.Write (Version);
  106. // issue datetime
  107. DateTime issueDate = DateTime.Now;
  108. writer.Write (issueDate.Ticks);
  109. // expiration datetime
  110. writer.Write (issueDate.Add(RoleManagerConfig.CookieTimeout).Ticks);
  111. writer.Write (cookiePath);
  112. writer.Write (roles);
  113. CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
  114. if (cookieProtection == CookieProtection.None)
  115. return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
  116. if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
  117. byte [] hashBytes = null;
  118. byte [] validationBytes = MachineConfig.ValidationKeyBytes;
  119. writer.Write (validationBytes);
  120. switch (MachineConfig.Validation) {
  121. case MachineKeyValidation.MD5:
  122. hashBytes = MD5.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
  123. break;
  124. case MachineKeyValidation.TripleDES:
  125. case MachineKeyValidation.SHA1:
  126. hashBytes = SHA1.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
  127. break;
  128. }
  129. writer.Seek (-validationBytes.Length, SeekOrigin.Current);
  130. writer.Write (hashBytes);
  131. }
  132. byte [] ticketBytes = null;
  133. if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
  134. ICryptoTransform enc;
  135. enc = TripleDES.Create ().CreateEncryptor (MachineConfig.DecryptionKey192Bits, InitVector);
  136. ticketBytes = enc.TransformFinalBlock (ticket.GetBuffer (), 0, (int) ticket.Position);
  137. }
  138. if (ticketBytes == null)
  139. return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
  140. else
  141. return GetBase64FromBytes (ticketBytes, 0, ticketBytes.Length);
  142. }
  143. private void DecryptTicket (string encryptedTicket)
  144. {
  145. if (encryptedTicket == null || encryptedTicket == String.Empty)
  146. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  147. byte [] ticketBytes = GetBytesFromBase64 (encryptedTicket);
  148. byte [] decryptedTicketBytes = null;
  149. CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
  150. if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
  151. ICryptoTransform decryptor;
  152. decryptor = TripleDES.Create ().CreateDecryptor (MachineConfig.DecryptionKey192Bits, InitVector);
  153. decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length);
  154. }
  155. else
  156. decryptedTicketBytes = ticketBytes;
  157. if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
  158. byte [] validationBytes = MachineConfig.ValidationKeyBytes;
  159. byte [] rolesWithValidationBytes = null;
  160. byte [] tmpValidation = null;
  161. int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes
  162. rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length];
  163. Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize);
  164. Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length);
  165. switch (MachineConfig.Validation) {
  166. case MachineKeyValidation.MD5:
  167. tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes);
  168. break;
  169. case MachineKeyValidation.TripleDES:
  170. case MachineKeyValidation.SHA1:
  171. tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes);
  172. break;
  173. }
  174. for (int i = 0; i < tmpValidation.Length; i++) {
  175. if (i >= decryptedTicketBytes.Length ||
  176. tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize])
  177. throw new HttpException ("ticket validation failed");
  178. }
  179. }
  180. MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
  181. BinaryReader reader = new BinaryReader (ticket);
  182. // version
  183. _version = reader.ReadInt32 ();
  184. // issued date
  185. _issueDate = new DateTime (reader.ReadInt64 ());
  186. // expire date
  187. _exprireDate = new DateTime (reader.ReadInt64 ());
  188. // cookie path
  189. _cookiePath = reader.ReadString ();
  190. // roles
  191. string roles = reader.ReadString ();
  192. if (!Expired)
  193. InitializeRoles (roles);
  194. }
  195. private void InitializeRoles (string decryptedRoles)
  196. {
  197. _cachedArray = decryptedRoles.Split (',');
  198. _cachedRoles = new HybridDictionary (true);
  199. foreach (string r in _cachedArray)
  200. _cachedRoles.Add (r, r);
  201. }
  202. private byte [] InitVector
  203. {
  204. get { return new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
  205. }
  206. public bool CachedListChanged {
  207. get { return _listChanged; }
  208. }
  209. public string CookiePath {
  210. get { return _cookiePath; }
  211. }
  212. public bool Expired {
  213. get { return ExpireDate < DateTime.Now; }
  214. }
  215. public DateTime ExpireDate {
  216. get { return _exprireDate; }
  217. }
  218. public IIdentity Identity {
  219. get { return _identity; }
  220. }
  221. public bool IsRoleListCached {
  222. get { return (_cachedRoles != null) && RoleManagerConfig.CacheRolesInCookie; }
  223. }
  224. public DateTime IssueDate {
  225. get { return _issueDate; }
  226. }
  227. public string ProviderName {
  228. get { return String.IsNullOrEmpty(_providerName) ? Provider.Name : _providerName; }
  229. }
  230. public int Version {
  231. get { return _version; }
  232. }
  233. RoleProvider Provider {
  234. get {
  235. if (String.IsNullOrEmpty (_providerName))
  236. return Roles.Provider;
  237. return Roles.Providers [_providerName];
  238. }
  239. }
  240. public void SetDirty ()
  241. {
  242. _listChanged = true;
  243. _cachedRoles = null;
  244. _cachedArray = null;
  245. }
  246. static string GetBase64FromBytes (byte [] bytes, int offset, int len)
  247. {
  248. return Convert.ToBase64String (bytes, offset, len);
  249. }
  250. static byte [] GetBytesFromBase64 (string base64String)
  251. {
  252. return Convert.FromBase64String (base64String);
  253. }
  254. RoleManagerSection RoleManagerConfig
  255. {
  256. get { return (RoleManagerSection) WebConfigurationManager.GetSection ("system.web/roleManager"); }
  257. }
  258. MachineKeySection MachineConfig
  259. {
  260. get { return (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey"); }
  261. }
  262. }
  263. }
  264. #endif