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