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 public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
52 protected CodeAccessPermission ()
56 [MonoTODO ("Imperative mode isn't supported")]
59 new PermissionSet (this).Assert ();
62 internal bool CheckAssert (CodeAccessPermission asserted)
66 if (asserted.GetType () != this.GetType ())
68 return IsSubsetOf (asserted);
71 internal bool CheckDemand (CodeAccessPermission target)
75 if (target.GetType () != this.GetType ())
77 return IsSubsetOf (target);
80 internal bool CheckDeny (CodeAccessPermission denied)
84 Type t = denied.GetType ();
85 if (t != this.GetType ())
87 IPermission inter = Intersect (denied);
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));
97 internal bool CheckPermitOnly (CodeAccessPermission target)
101 if (target.GetType () != this.GetType ())
103 return IsSubsetOf (target);
106 public abstract IPermission Copy ();
108 public void Demand ()
110 // note: here we're sure it's a CAS demand
111 if (!SecurityManager.SecurityEnabled)
114 // skip frames until we get the caller (of our caller)
115 new PermissionSet (this).CasOnlyDemand (3);
118 [MonoTODO ("Imperative mode isn't supported")]
121 new PermissionSet (this).Deny ();
126 public override bool Equals (object obj)
130 if (obj.GetType () != this.GetType ())
132 CodeAccessPermission cap = (obj as CodeAccessPermission);
133 return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
137 public abstract void FromXml (SecurityElement elem);
141 public override int GetHashCode ()
143 return base.GetHashCode ();
147 public abstract IPermission Intersect (IPermission target);
149 public abstract bool IsSubsetOf (IPermission target);
151 public override string ToString ()
153 SecurityElement elem = ToXml ();
154 return elem.ToString ();
157 public abstract SecurityElement ToXml ();
159 public virtual IPermission Union (IPermission other)
162 throw new System.NotSupportedException (); // other is not null.
166 [MonoTODO ("Imperative mode isn't supported")]
167 public void PermitOnly ()
169 new PermissionSet (this).PermitOnly ();
172 [MonoTODO ("Imperative mode isn't supported")]
173 public static void RevertAll ()
175 if (!SecurityManager.SecurityEnabled)
178 SecurityFrame sf = new SecurityFrame (1);
180 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
182 throw new NotSupportedException ("Currently only declarative Assert are supported.");
184 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
186 throw new NotSupportedException ("Currently only declarative Deny are supported.");
188 if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
190 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
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);
201 [MonoTODO ("Imperative mode isn't supported")]
202 public static void RevertAssert ()
204 if (!SecurityManager.SecurityEnabled)
207 SecurityFrame sf = new SecurityFrame (1);
208 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
209 throw new NotSupportedException ("Currently only declarative Assert are supported.");
211 // we can't revert declarative security (or an empty frame) imperatively
212 ThrowExecutionEngineException (SecurityAction.Assert);
216 [MonoTODO ("Imperative mode isn't supported")]
217 public static void RevertDeny ()
219 if (!SecurityManager.SecurityEnabled)
222 SecurityFrame sf = new SecurityFrame (1);
223 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
224 throw new NotSupportedException ("Currently only declarative Deny are supported.");
226 // we can't revert declarative security (or an empty frame) imperatively
227 ThrowExecutionEngineException (SecurityAction.Deny);
231 [MonoTODO ("Imperative mode isn't supported")]
232 public static void RevertPermitOnly ()
234 if (!SecurityManager.SecurityEnabled)
237 SecurityFrame sf = new SecurityFrame (1);
238 if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
239 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
241 // we can't revert declarative security (or an empty frame) imperatively
242 ThrowExecutionEngineException (SecurityAction.PermitOnly);
246 // Internal helpers methods
248 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
249 internal SecurityElement Element (int version)
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 ());
258 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
262 case PermissionState.None:
264 case PermissionState.Unrestricted:
266 // unrestricted permissions are possible for identiy permissions
268 if (!allowUnrestricted) {
269 msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
270 throw new ArgumentException (msg, "state");
275 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
276 throw new ArgumentException (msg, "state");
281 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion)
284 throw new ArgumentNullException (parameterName);
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);
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
297 // we assume minimum version if no version number is supplied
298 int version = minimumVersion;
299 string v = se.Attribute ("version");
302 version = Int32.Parse (v);
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);
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);
319 // must be called after CheckSecurityElement (i.e. se != null)
320 internal static bool IsUnrestricted (SecurityElement se)
322 string value = se.Attribute ("Unrestricted");
325 return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
328 internal bool ProcessFrame (SecurityFrame frame)
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 ();
335 // check individual permissions
336 foreach (IPermission p in frame.PermitOnly) {
337 if (CheckPermitOnly (p as CodeAccessPermission)) {
344 // ...or else we throw
345 ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
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);
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
371 // continue the stack walk
375 internal static void ThrowInvalidPermission (IPermission target, Type expected)
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");
382 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
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));
390 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
391 SecurityAction action, IPermission failed)
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 ());