New tests, updates
[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         [MonoTODO ("CAS support is experimental (and unsupported).")]
50         public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
51
52
53                 protected CodeAccessPermission ()
54                 {
55                 }
56
57                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
58                 public void Assert ()
59                 {
60                         new PermissionSet (this).Assert ();
61                 }
62
63                 internal bool CheckAssert (CodeAccessPermission asserted)
64                 {
65                         if (asserted == null)
66                                 return false;
67                         if (asserted.GetType () != this.GetType ())
68                                 return false;
69                         return IsSubsetOf (asserted);
70                 }
71
72                 internal bool CheckDemand (CodeAccessPermission target)
73                 {
74                         if (target == null)
75                                 return false;
76                         if (target.GetType () != this.GetType ())
77                                 return false;
78                         return IsSubsetOf (target);
79                 }
80
81                 internal bool CheckDeny (CodeAccessPermission denied)
82                 {
83                         if (denied == null)
84                                 return true;
85                         Type t = denied.GetType ();
86                         if (t != this.GetType ())
87                                 return true;
88                         IPermission inter = Intersect (denied);
89                         if (inter == null)
90                                 return true;
91                         // sadly that's not enough :( at this stage we must also check
92                         // if an empty (PermissionState.None) is a subset of the denied
93                         // (which is like a empty intersection looks like for flag based
94                         // permissions, e.g. AspNetHostingPermission).
95                         return denied.IsSubsetOf (PermissionBuilder.Create (t));
96                 }
97
98                 internal bool CheckPermitOnly (CodeAccessPermission target)
99                 {
100                         if (target == null)
101                                 return false;
102                         if (target.GetType () != this.GetType ())
103                                 return false;
104                         return IsSubsetOf (target);
105                 }
106
107                 public abstract IPermission Copy ();
108
109                 public void Demand ()
110                 {
111                         // note: here we're sure it's a CAS demand
112                         if (!SecurityManager.SecurityEnabled)
113                                 return;
114
115                         // skip frames until we get the caller (of our caller)
116                         new PermissionSet (this).CasOnlyDemand (3);
117                 }
118
119                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
120                 public void Deny ()
121                 {
122                         new PermissionSet (this).Deny ();
123                 }
124
125 #if NET_2_0
126                 [ComVisible (false)]
127                 public override bool Equals (object obj)
128                 {
129                         if (obj == null)
130                                 return false;
131                         if (obj.GetType () != this.GetType ())
132                                 return false;
133                         CodeAccessPermission cap = (obj as CodeAccessPermission);
134                         return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
135                 }
136 #endif
137
138                 public abstract void FromXml (SecurityElement elem);
139
140 #if NET_2_0
141                 [ComVisible (false)]
142                 public override int GetHashCode ()
143                 {
144                         return base.GetHashCode ();
145                 }
146 #endif
147
148                 public abstract IPermission Intersect (IPermission target);
149
150                 public abstract bool IsSubsetOf (IPermission target);
151
152                 public override string ToString ()
153                 {
154                         SecurityElement elem = ToXml ();
155                         return elem.ToString ();
156                 }
157
158                 public abstract SecurityElement ToXml ();
159
160                 public virtual IPermission Union (IPermission other)
161                 {
162                         if (null != other)
163                                 throw new System.NotSupportedException (); // other is not null.
164                         return null;
165                 }
166
167                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
168                 public void PermitOnly ()
169                 {
170                         new PermissionSet (this).PermitOnly ();
171                 }
172
173                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
174                 public static void RevertAll ()
175                 {
176                         if (!SecurityManager.SecurityEnabled)
177                                 return;
178
179                         SecurityFrame sf = new SecurityFrame (1);
180                         bool revert = false;
181                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
182                                 revert = true;
183                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
184                         }
185                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
186                                 revert = true;
187                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
188                         }
189                         if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
190                                 revert = true;
191                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
192                         }
193
194                         if (!revert) {
195                                 string msg = Locale.GetText ("No stack modifiers are present on the current stack frame.");
196                                 // FIXME: we don't (yet) support imperative stack modifiers
197                                 msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
198                                 throw new ExecutionEngineException (msg);
199                         }
200                 }
201
202                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
203                 public static void RevertAssert ()
204                 {
205                         if (!SecurityManager.SecurityEnabled)
206                                 return;
207
208                         SecurityFrame sf = new SecurityFrame (1);
209                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
210                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
211                         } else {
212                                 // we can't revert declarative security (or an empty frame) imperatively
213                                 ThrowExecutionEngineException (SecurityAction.Assert);
214                         }
215                 }
216
217                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
218                 public static void RevertDeny ()
219                 {
220                         if (!SecurityManager.SecurityEnabled)
221                                 return;
222
223                         SecurityFrame sf = new SecurityFrame (1);
224                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
225                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
226                         } else {
227                                 // we can't revert declarative security (or an empty frame) imperatively
228                                 ThrowExecutionEngineException (SecurityAction.Deny);
229                         }
230                 }
231
232                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
233                 public static void RevertPermitOnly ()
234                 {
235                         if (!SecurityManager.SecurityEnabled)
236                                 return;
237
238                         SecurityFrame sf = new SecurityFrame (1);
239                         if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
240                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
241                         } else {
242                                 // we can't revert declarative security (or an empty frame) imperatively
243                                 ThrowExecutionEngineException (SecurityAction.PermitOnly);
244                         }
245                 }
246
247                 // Internal helpers methods
248
249                 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
250                 internal SecurityElement Element (int version) 
251                 {
252                         SecurityElement se = new SecurityElement ("IPermission");
253                         Type type = this.GetType ();
254                         se.AddAttribute ("class", type.FullName + ", " + type.Assembly.ToString ().Replace ('\"', '\''));
255                         se.AddAttribute ("version", version.ToString ());
256                         return se;
257                 }
258
259                 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
260                 {
261                         string msg;
262                         switch (state) {
263                         case PermissionState.None:
264                                 break;
265                         case PermissionState.Unrestricted:
266 #if NET_2_0
267                                 // unrestricted permissions are possible for identiy permissions
268 #else
269                                 if (!allowUnrestricted) {
270                                         msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
271                                         throw new ArgumentException (msg, "state");
272                                 }
273 #endif
274                                 break;
275                         default:
276                                 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
277                                 throw new ArgumentException (msg, "state");
278                         }
279                         return state;
280                 }
281
282                 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion) 
283                 {
284                         if (se == null)
285                                 throw new ArgumentNullException (parameterName);
286
287                         // Tag is case-sensitive
288                         if (se.Tag != "IPermission") {
289                                 string msg = String.Format (Locale.GetText ("Invalid tag {0}"), se.Tag);
290                                 throw new ArgumentException (msg, parameterName);
291                         }
292
293                         // Note: we do not care about the class attribute at 
294                         // this stage (in fact we don't even if the class 
295                         // attribute is present or not). Anyway the object has
296                         // already be created, with success, if we're loading it
297
298                         // we assume minimum version if no version number is supplied
299                         int version = minimumVersion;
300                         string v = se.Attribute ("version");
301                         if (v != null) {
302                                 try {
303                                         version = Int32.Parse (v);
304                                 }
305                                 catch (Exception e) {
306                                         string msg = Locale.GetText ("Couldn't parse version from '{0}'.");
307                                         msg = String.Format (msg, v);
308                                         throw new ArgumentException (msg, parameterName, e);
309                                 }
310                         }
311
312                         if ((version < minimumVersion) || (version > maximumVersion)) {
313                                 string msg = Locale.GetText ("Unknown version '{0}', expected versions between ['{1}','{2}'].");
314                                 msg = String.Format (msg, version, minimumVersion, maximumVersion);
315                                 throw new ArgumentException (msg, parameterName);
316                         }
317                         return version;
318                 }
319
320                 // must be called after CheckSecurityElement (i.e. se != null)
321                 internal static bool IsUnrestricted (SecurityElement se) 
322                 {
323                         string value = se.Attribute ("Unrestricted");
324                         if (value == null)
325                                 return false;
326                         return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
327                 }
328
329                 internal bool ProcessFrame (SecurityFrame frame)
330                 { 
331                         // 1. CheckPermitOnly
332                         if (frame.PermitOnly != null) {
333                                 // the demanded permission must be in one of the permitted...
334                                 bool permit = frame.PermitOnly.IsUnrestricted ();
335                                 if (!permit) {
336                                         // check individual permissions
337                                         foreach (IPermission p in frame.PermitOnly) {
338                                                 if (CheckPermitOnly (p as CodeAccessPermission)) {
339                                                         permit = true;
340                                                         break;
341                                                 }
342                                         }
343                                 }
344                                 if (!permit) {
345                                         // ...or else we throw
346                                         ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
347                                 }
348                         }
349
350                         // 2. CheckDeny
351                         if (frame.Deny != null) {
352                                 // special case where everything is denied (i.e. no child to be processed)
353                                 if (frame.Deny.IsUnrestricted ())
354                                         ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
355                                 foreach (IPermission p in frame.Deny) {
356                                         if (!CheckDeny (p as CodeAccessPermission))
357                                                 ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, p);
358                                 }
359                         }
360
361                         // 3. CheckAssert
362                         if (frame.Assert != null) {
363                                 if (frame.Assert.IsUnrestricted ())
364                                         return true; // remove permission and continue stack walk
365                                 foreach (IPermission p in frame.Assert) {
366                                         if (CheckAssert (p as CodeAccessPermission)) {
367                                                 return true; // remove permission and continue stack walk
368                                         }
369                                 }
370                         }
371
372                         // continue the stack walk
373                         return false; 
374                 }
375
376                 internal static void ThrowInvalidPermission (IPermission target, Type expected) 
377                 {
378                         string msg = Locale.GetText ("Invalid permission type '{0}', expected type '{1}'.");
379                         msg = String.Format (msg, target.GetType (), expected);
380                         throw new ArgumentException (msg, "target");
381                 }
382
383                 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
384                 {
385                         string msg = Locale.GetText ("No {0} modifier is present on the current stack frame.");
386                         // FIXME: we don't (yet) support imperative stack modifiers
387                         msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
388                         throw new ExecutionEngineException (String.Format (msg, stackmod));
389                 }
390
391                 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
392                         SecurityAction action, IPermission failed)
393                 {
394 #if NET_2_1
395                         throw new SecurityException (message);
396 #else
397                         Assembly a = frame.Assembly;
398                         throw new SecurityException (Locale.GetText (message), 
399                                 a.UnprotectedGetName (), a.GrantedPermissionSet, 
400                                 a.DeniedPermissionSet, frame.Method, action, demanded, 
401                                 failed, a.UnprotectedGetEvidence ());
402 #endif
403                 }
404         }
405 }