2 // System.Web.Security.RolePrincipal
5 // Ben Maurer (bmaurer@users.sourceforge.net)
6 // Sebastien Pouliot <sebastien@ximian.com>
9 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
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;
39 namespace System.Web.Security {
42 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 class RolePrincipal : IPrincipal {
52 string[] _cachedArray;
53 HybridDictionary _cachedRoles;
54 readonly string _providerName;
62 public RolePrincipal (IIdentity identity)
65 throw new ArgumentNullException ("identity");
67 this._identity = identity;
68 this._cookiePath = RoleManagerConfig.CookiePath;
69 this._issueDate = DateTime.Now;
70 this._expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout);
73 public RolePrincipal (IIdentity identity, string encryptedTicket)
76 DecryptTicket (encryptedTicket);
79 public RolePrincipal (string providerName, IIdentity identity)
82 if (providerName == null)
83 throw new ArgumentNullException ("providerName");
85 this._providerName = providerName;
88 public RolePrincipal (string providerName, IIdentity identity, string encryptedTicket)
89 : this (providerName, identity)
91 DecryptTicket (encryptedTicket);
94 public string [] GetRoles ()
96 if (!_identity.IsAuthenticated)
99 if (!IsRoleListCached || Expired) {
100 _cachedArray = Provider.GetRolesForUser (_identity.Name);
101 _cachedRoles = new HybridDictionary (true);
103 foreach (string r in _cachedArray)
104 _cachedRoles.Add(r, r);
112 public bool IsInRole (string role)
114 if (!_identity.IsAuthenticated)
119 return _cachedRoles [role] != null;
122 public string ToEncryptedTicket ()
124 string roles = string.Join (",", GetRoles ());
125 string cookiePath = RoleManagerConfig.CookiePath;
126 int approxTicketLen = roles.Length + cookiePath.Length + 64;
128 if (_cachedArray.Length > Roles.MaxCachedResults)
131 MemoryStream ticket = new MemoryStream (approxTicketLen);
132 BinaryWriter writer = new BinaryWriter (ticket);
135 writer.Write (Version);
138 DateTime issueDate = DateTime.Now;
139 writer.Write (issueDate.Ticks);
141 // expiration datetime
142 writer.Write (_expireDate.Ticks);
144 writer.Write (cookiePath);
145 writer.Write (roles);
147 CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
149 if (cookieProtection == CookieProtection.None)
150 return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
152 if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
154 byte [] hashBytes = null;
155 byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
156 writer.Write (validationBytes);
158 switch (MachineConfig.Validation) {
159 case MachineKeyValidation.MD5:
160 hashBytes = MD5.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
163 case MachineKeyValidation.TripleDES:
164 case MachineKeyValidation.SHA1:
165 hashBytes = SHA1.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
169 writer.Seek (-validationBytes.Length, SeekOrigin.Current);
170 writer.Write (hashBytes);
173 byte [] ticketBytes = null;
174 if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
175 ICryptoTransform enc;
176 enc = TripleDES.Create ().CreateEncryptor (MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
178 ticketBytes = enc.TransformFinalBlock (ticket.GetBuffer (), 0, (int) ticket.Position);
181 if (ticketBytes == null)
182 return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
184 return GetBase64FromBytes (ticketBytes, 0, ticketBytes.Length);
187 void DecryptTicket (string encryptedTicket)
189 if (encryptedTicket == null || encryptedTicket == String.Empty)
190 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
192 byte [] ticketBytes = GetBytesFromBase64 (encryptedTicket);
193 byte [] decryptedTicketBytes = null;
195 CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
196 if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
197 ICryptoTransform decryptor;
198 decryptor = TripleDES.Create ().CreateDecryptor (
199 MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
201 decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length);
204 decryptedTicketBytes = ticketBytes;
206 if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
207 byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
208 byte [] rolesWithValidationBytes = null;
209 byte [] tmpValidation = null;
211 int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes
213 rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length];
215 Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize);
216 Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length);
218 switch (MachineConfig.Validation) {
219 case MachineKeyValidation.MD5:
220 tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes);
223 case MachineKeyValidation.TripleDES:
224 case MachineKeyValidation.SHA1:
225 tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes);
228 for (int i = 0; i < tmpValidation.Length; i++) {
229 if (i >= decryptedTicketBytes.Length ||
230 tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize])
231 throw new HttpException ("ticket validation failed");
235 MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
236 BinaryReader reader = new BinaryReader (ticket);
239 _version = reader.ReadInt32 ();
242 _issueDate = new DateTime (reader.ReadInt64 ());
245 _expireDate = new DateTime (reader.ReadInt64 ());
248 _cookiePath = reader.ReadString ();
251 string roles = reader.ReadString ();
254 InitializeRoles (roles);
255 //update ticket if less than half of CookieTimeout remaining.
256 if (Roles.CookieSlidingExpiration){
257 if (_expireDate-DateTime.Now < TimeSpan.FromTicks (RoleManagerConfig.CookieTimeout.Ticks/2)) {
258 _issueDate = DateTime.Now;
259 _expireDate = DateTime.Now.Add (RoleManagerConfig.CookieTimeout);
264 // issue a new ticket
265 _issueDate = DateTime.Now;
266 _expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout);
270 void InitializeRoles (string decryptedRoles)
272 _cachedArray = decryptedRoles.Split (',');
273 _cachedRoles = new HybridDictionary (true);
275 foreach (string r in _cachedArray)
276 _cachedRoles.Add (r, r);
281 get { return new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
284 public bool CachedListChanged {
285 get { return _listChanged; }
288 public string CookiePath {
289 get { return _cookiePath; }
292 public bool Expired {
293 get { return ExpireDate < DateTime.Now; }
296 public DateTime ExpireDate {
297 get { return _expireDate; }
300 public IIdentity Identity {
301 get { return _identity; }
304 public bool IsRoleListCached {
305 get { return (_cachedRoles != null) && RoleManagerConfig.CacheRolesInCookie; }
308 public DateTime IssueDate {
309 get { return _issueDate; }
312 public string ProviderName {
313 get { return String.IsNullOrEmpty(_providerName) ? Provider.Name : _providerName; }
317 get { return _version; }
320 RoleProvider Provider {
322 if (String.IsNullOrEmpty (_providerName))
323 return Roles.Provider;
325 return Roles.Providers [_providerName];
329 public void SetDirty ()
336 static string GetBase64FromBytes (byte [] bytes, int offset, int len)
338 return Convert.ToBase64String (bytes, offset, len);
341 static byte [] GetBytesFromBase64 (string base64String)
343 return Convert.FromBase64String (base64String);
346 RoleManagerSection RoleManagerConfig
348 get { return (RoleManagerSection) WebConfigurationManager.GetSection ("system.web/roleManager"); }
351 MachineKeySection MachineConfig
353 get { return (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey"); }