* roottypes.cs: Rename from tree.cs.
[mono.git] / mcs / class / corlib / System.Security / CodeAccessPermission.cs
1 //
2 // System.Security.CodeAccessPermission.cs
3 //
4 // Authors:
5 //      Miguel de Icaza (miguel@ximian.com)
6 //      Nick Drochak, ndrochak@gol.com
7 //      Sebastien Pouliot  <sebastien@ximian.com>
8 //
9 // (C) Ximian, Inc. http://www.ximian.com
10 // Copyright (C) 2001 Nick Drochak, All Rights Reserved
11 // Portions (C) 2004 Motus Technologies Inc. (http://www.motus.com)
12 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.Diagnostics;
35 using System.Globalization;
36 using System.Reflection;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Security.Permissions;
40 using System.Threading;
41
42 namespace System.Security {
43
44         [Serializable]
45         [SecurityPermission (SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true)]
46 #if NET_2_0
47         [ComVisible (true)]
48 #endif
49         public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
50
51
52                 protected CodeAccessPermission ()
53                 {
54                 }
55
56                 [MonoTODO ("Imperative mode isn't supported")]
57                 public void Assert ()
58                 {
59                         new PermissionSet (this).Assert ();
60                 }
61
62                 internal bool CheckAssert (CodeAccessPermission asserted)
63                 {
64                         if (asserted == null)
65                                 return false;
66                         if (asserted.GetType () != this.GetType ())
67                                 return false;
68                         return IsSubsetOf (asserted);
69                 }
70
71                 internal bool CheckDemand (CodeAccessPermission target)
72                 {
73                         if (target == null)
74                                 return false;
75                         if (target.GetType () != this.GetType ())
76                                 return false;
77                         return IsSubsetOf (target);
78                 }
79
80                 internal bool CheckDeny (CodeAccessPermission denied)
81                 {
82                         if (denied == null)
83                                 return true;
84                         Type t = denied.GetType ();
85                         if (t != this.GetType ())
86                                 return true;
87                         IPermission inter = Intersect (denied);
88                         if (inter == null)
89                                 return true;
90                         // sadly that's not enough :( at this stage we must also check
91                         // if an empty (PermissionState.None) is a subset of the denied
92                         // (which is like a empty intersection looks like for flag based
93                         // permissions, e.g. AspNetHostingPermission).
94                         return denied.IsSubsetOf (PermissionBuilder.Create (t));
95                 }
96
97                 internal bool CheckPermitOnly (CodeAccessPermission target)
98                 {
99                         if (target == null)
100                                 return false;
101                         if (target.GetType () != this.GetType ())
102                                 return false;
103                         return IsSubsetOf (target);
104                 }
105
106                 public abstract IPermission Copy ();
107
108                 public void Demand ()
109                 {
110                         // note: here we're sure it's a CAS demand
111                         if (!SecurityManager.SecurityEnabled)
112                                 return;
113
114                         // skip frames until we get the caller (of our caller)
115                         new PermissionSet (this).CasOnlyDemand (3);
116                 }
117
118                 [MonoTODO ("Imperative mode isn't supported")]
119                 public void Deny ()
120                 {
121                         new PermissionSet (this).Deny ();
122                 }
123
124 #if NET_2_0
125                 [ComVisible (false)]
126                 public override bool Equals (object obj)
127                 {
128                         if (obj == null)
129                                 return false;
130                         if (obj.GetType () != this.GetType ())
131                                 return false;
132                         CodeAccessPermission cap = (obj as CodeAccessPermission);
133                         return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
134                 }
135 #endif
136
137                 public abstract void FromXml (SecurityElement elem);
138
139 #if NET_2_0
140                 [ComVisible (false)]
141                 public override int GetHashCode ()
142                 {
143                         return base.GetHashCode ();
144                 }
145 #endif
146
147                 public abstract IPermission Intersect (IPermission target);
148
149                 public abstract bool IsSubsetOf (IPermission target);
150
151                 public override string ToString ()
152                 {
153                         SecurityElement elem = ToXml ();
154                         return elem.ToString ();
155                 }
156
157                 public abstract SecurityElement ToXml ();
158
159                 public virtual IPermission Union (IPermission other)
160                 {
161                         if (null != other)
162                                 throw new System.NotSupportedException (); // other is not null.
163                         return null;
164                 }
165
166                 [MonoTODO ("Imperative mode isn't supported")]
167                 public void PermitOnly ()
168                 {
169                         new PermissionSet (this).PermitOnly ();
170                 }
171
172                 [MonoTODO ("Imperative mode isn't supported")]
173                 public static void RevertAll ()
174                 {
175                         if (!SecurityManager.SecurityEnabled)
176                                 return;
177
178                         SecurityFrame sf = new SecurityFrame (1);
179                         bool revert = false;
180                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
181                                 revert = true;
182                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
183                         }
184                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
185                                 revert = true;
186                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
187                         }
188                         if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
189                                 revert = true;
190                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
191                         }
192
193                         if (!revert) {
194                                 string msg = Locale.GetText ("No stack modifiers are present on the current stack frame.");
195                                 // FIXME: we don't (yet) support imperative stack modifiers
196                                 msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
197                                 throw new ExecutionEngineException (msg);
198                         }
199                 }
200
201                 [MonoTODO ("Imperative mode isn't supported")]
202                 public static void RevertAssert ()
203                 {
204                         if (!SecurityManager.SecurityEnabled)
205                                 return;
206
207                         SecurityFrame sf = new SecurityFrame (1);
208                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
209                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
210                         } else {
211                                 // we can't revert declarative security (or an empty frame) imperatively
212                                 ThrowExecutionEngineException (SecurityAction.Assert);
213                         }
214                 }
215
216                 [MonoTODO ("Imperative mode isn't supported")]
217                 public static void RevertDeny ()
218                 {
219                         if (!SecurityManager.SecurityEnabled)
220                                 return;
221
222                         SecurityFrame sf = new SecurityFrame (1);
223                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
224                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
225                         } else {
226                                 // we can't revert declarative security (or an empty frame) imperatively
227                                 ThrowExecutionEngineException (SecurityAction.Deny);
228                         }
229                 }
230
231                 [MonoTODO ("Imperative mode isn't supported")]
232                 public static void RevertPermitOnly ()
233                 {
234                         if (!SecurityManager.SecurityEnabled)
235                                 return;
236
237                         SecurityFrame sf = new SecurityFrame (1);
238                         if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
239                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
240                         } else {
241                                 // we can't revert declarative security (or an empty frame) imperatively
242                                 ThrowExecutionEngineException (SecurityAction.PermitOnly);
243                         }
244                 }
245
246                 // Internal helpers methods
247
248                 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
249                 internal SecurityElement Element (int version) 
250                 {
251                         SecurityElement se = new SecurityElement ("IPermission");
252                         Type type = this.GetType ();
253                         se.AddAttribute ("class", type.FullName + ", " + type.Assembly.ToString ().Replace ('\"', '\''));
254                         se.AddAttribute ("version", version.ToString ());
255                         return se;
256                 }
257
258                 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
259                 {
260                         string msg;
261                         switch (state) {
262                         case PermissionState.None:
263                                 break;
264                         case PermissionState.Unrestricted:
265 #if NET_2_0
266                                 // unrestricted permissions are possible for identiy permissions
267 #else
268                                 if (!allowUnrestricted) {
269                                         msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
270                                         throw new ArgumentException (msg, "state");
271                                 }
272 #endif
273                                 break;
274                         default:
275                                 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
276                                 throw new ArgumentException (msg, "state");
277                         }
278                         return state;
279                 }
280
281                 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion) 
282                 {
283                         if (se == null)
284                                 throw new ArgumentNullException (parameterName);
285
286                         // Tag is case-sensitive
287                         if (se.Tag != "IPermission") {
288                                 string msg = String.Format (Locale.GetText ("Invalid tag {0}"), se.Tag);
289                                 throw new ArgumentException (msg, parameterName);
290                         }
291
292                         // Note: we do not care about the class attribute at 
293                         // this stage (in fact we don't even if the class 
294                         // attribute is present or not). Anyway the object has
295                         // already be created, with success, if we're loading it
296
297                         // we assume minimum version if no version number is supplied
298                         int version = minimumVersion;
299                         string v = se.Attribute ("version");
300                         if (v != null) {
301                                 try {
302                                         version = Int32.Parse (v);
303                                 }
304                                 catch (Exception e) {
305                                         string msg = Locale.GetText ("Couldn't parse version from '{0}'.");
306                                         msg = String.Format (msg, v);
307                                         throw new ArgumentException (msg, parameterName, e);
308                                 }
309                         }
310
311                         if ((version < minimumVersion) || (version > maximumVersion)) {
312                                 string msg = Locale.GetText ("Unknown version '{0}', expected versions between ['{1}','{2}'].");
313                                 msg = String.Format (msg, version, minimumVersion, maximumVersion);
314                                 throw new ArgumentException (msg, parameterName);
315                         }
316                         return version;
317                 }
318
319                 // must be called after CheckSecurityElement (i.e. se != null)
320                 internal static bool IsUnrestricted (SecurityElement se) 
321                 {
322                         string value = se.Attribute ("Unrestricted");
323                         if (value == null)
324                                 return false;
325                         return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
326                 }
327
328                 internal bool ProcessFrame (SecurityFrame frame)
329                 { 
330                         // 1. CheckPermitOnly
331                         if (frame.PermitOnly != null) {
332                                 // the demanded permission must be in one of the permitted...
333                                 bool permit = frame.PermitOnly.IsUnrestricted ();
334                                 if (!permit) {
335                                         // check individual permissions
336                                         foreach (IPermission p in frame.PermitOnly) {
337                                                 if (CheckPermitOnly (p as CodeAccessPermission)) {
338                                                         permit = true;
339                                                         break;
340                                                 }
341                                         }
342                                 }
343                                 if (!permit) {
344                                         // ...or else we throw
345                                         ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
346                                 }
347                         }
348
349                         // 2. CheckDeny
350                         if (frame.Deny != null) {
351                                 // special case where everything is denied (i.e. no child to be processed)
352                                 if (frame.Deny.IsUnrestricted ())
353                                         ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
354                                 foreach (IPermission p in frame.Deny) {
355                                         if (!CheckDeny (p as CodeAccessPermission))
356                                                 ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, p);
357                                 }
358                         }
359
360                         // 3. CheckAssert
361                         if (frame.Assert != null) {
362                                 if (frame.Assert.IsUnrestricted ())
363                                         return true; // remove permission and continue stack walk
364                                 foreach (IPermission p in frame.Assert) {
365                                         if (CheckAssert (p as CodeAccessPermission)) {
366                                                 return true; // remove permission and continue stack walk
367                                         }
368                                 }
369                         }
370
371                         // continue the stack walk
372                         return false; 
373                 }
374
375                 internal static void ThrowInvalidPermission (IPermission target, Type expected) 
376                 {
377                         string msg = Locale.GetText ("Invalid permission type '{0}', expected type '{1}'.");
378                         msg = String.Format (msg, target.GetType (), expected);
379                         throw new ArgumentException (msg, "target");
380                 }
381
382                 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
383                 {
384                         string msg = Locale.GetText ("No {0} modifier is present on the current stack frame.");
385                         // FIXME: we don't (yet) support imperative stack modifiers
386                         msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
387                         throw new ExecutionEngineException (String.Format (msg, stackmod));
388                 }
389
390                 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
391                         SecurityAction action, IPermission failed)
392                 {
393                         Assembly a = frame.Assembly;
394                         throw new SecurityException (Locale.GetText (message), 
395                                 a.UnprotectedGetName (), a.GrantedPermissionSet, 
396                                 a.DeniedPermissionSet, frame.Method, action, demanded, 
397                                 failed, a.UnprotectedGetEvidence ());
398                 }
399         }
400 }