2 // System.Security.CodeAccessPermission.cs
5 // Miguel de Icaza (miguel@ximian.com)
6 // Nick Drochak, ndrochak@gol.com
7 // Sebastien Pouliot <sebastien@ximian.com>
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)
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:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
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.
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;
42 namespace System.Security {
45 [SecurityPermission (SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true)]
49 [MonoTODO ("CAS support is experimental (and unsupported).")]
50 public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
53 protected CodeAccessPermission ()
57 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
60 new PermissionSet (this).Assert ();
63 internal bool CheckAssert (CodeAccessPermission asserted)
67 if (asserted.GetType () != this.GetType ())
69 return IsSubsetOf (asserted);
72 internal bool CheckDemand (CodeAccessPermission target)
76 if (target.GetType () != this.GetType ())
78 return IsSubsetOf (target);
81 internal bool CheckDeny (CodeAccessPermission denied)
85 Type t = denied.GetType ();
86 if (t != this.GetType ())
88 IPermission inter = Intersect (denied);
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));
98 internal bool CheckPermitOnly (CodeAccessPermission target)
102 if (target.GetType () != this.GetType ())
104 return IsSubsetOf (target);
107 public abstract IPermission Copy ();
109 public void Demand ()
111 // note: here we're sure it's a CAS demand
112 if (!SecurityManager.SecurityEnabled)
115 // skip frames until we get the caller (of our caller)
116 new PermissionSet (this).CasOnlyDemand (3);
119 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
122 new PermissionSet (this).Deny ();
127 public override bool Equals (object obj)
131 if (obj.GetType () != this.GetType ())
133 CodeAccessPermission cap = (obj as CodeAccessPermission);
134 return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
138 public abstract void FromXml (SecurityElement elem);
142 public override int GetHashCode ()
144 return base.GetHashCode ();
148 public abstract IPermission Intersect (IPermission target);
150 public abstract bool IsSubsetOf (IPermission target);
152 public override string ToString ()
154 SecurityElement elem = ToXml ();
155 return elem.ToString ();
158 public abstract SecurityElement ToXml ();
160 public virtual IPermission Union (IPermission other)
163 throw new System.NotSupportedException (); // other is not null.
167 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
168 public void PermitOnly ()
170 new PermissionSet (this).PermitOnly ();
173 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
174 public static void RevertAll ()
176 if (!SecurityManager.SecurityEnabled)
179 SecurityFrame sf = new SecurityFrame (1);
181 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
183 throw new NotSupportedException ("Currently only declarative Assert are supported.");
185 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
187 throw new NotSupportedException ("Currently only declarative Deny are supported.");
189 if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
191 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
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);
202 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
203 public static void RevertAssert ()
205 if (!SecurityManager.SecurityEnabled)
208 SecurityFrame sf = new SecurityFrame (1);
209 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
210 throw new NotSupportedException ("Currently only declarative Assert are supported.");
212 // we can't revert declarative security (or an empty frame) imperatively
213 ThrowExecutionEngineException (SecurityAction.Assert);
217 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
218 public static void RevertDeny ()
220 if (!SecurityManager.SecurityEnabled)
223 SecurityFrame sf = new SecurityFrame (1);
224 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
225 throw new NotSupportedException ("Currently only declarative Deny are supported.");
227 // we can't revert declarative security (or an empty frame) imperatively
228 ThrowExecutionEngineException (SecurityAction.Deny);
232 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
233 public static void RevertPermitOnly ()
235 if (!SecurityManager.SecurityEnabled)
238 SecurityFrame sf = new SecurityFrame (1);
239 if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
240 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
242 // we can't revert declarative security (or an empty frame) imperatively
243 ThrowExecutionEngineException (SecurityAction.PermitOnly);
247 // Internal helpers methods
249 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
250 internal SecurityElement Element (int version)
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 ());
259 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
263 case PermissionState.None:
265 case PermissionState.Unrestricted:
267 // unrestricted permissions are possible for identiy permissions
269 if (!allowUnrestricted) {
270 msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
271 throw new ArgumentException (msg, "state");
276 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
277 throw new ArgumentException (msg, "state");
282 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion)
285 throw new ArgumentNullException (parameterName);
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);
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
298 // we assume minimum version if no version number is supplied
299 int version = minimumVersion;
300 string v = se.Attribute ("version");
303 version = Int32.Parse (v);
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);
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);
320 // must be called after CheckSecurityElement (i.e. se != null)
321 internal static bool IsUnrestricted (SecurityElement se)
323 string value = se.Attribute ("Unrestricted");
326 return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
329 internal bool ProcessFrame (SecurityFrame frame)
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 ();
336 // check individual permissions
337 foreach (IPermission p in frame.PermitOnly) {
338 if (CheckPermitOnly (p as CodeAccessPermission)) {
345 // ...or else we throw
346 ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
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);
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
372 // continue the stack walk
376 internal static void ThrowInvalidPermission (IPermission target, Type expected)
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");
383 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
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));
391 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
392 SecurityAction action, IPermission failed)
395 throw new SecurityException (message);
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 ());