move FrameworkName from corlib to System
[mcs.git] / class / corlib / System.Security / CodeAccessPermission.cs
blobd6fb5d8d9dea5089c6aab58f49b23a4e0336bf21
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)
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.
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 {
44 [Serializable]
45 [SecurityPermission (SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true)]
46 [ComVisible (true)]
47 [MonoTODO ("CAS support is experimental (and unsupported).")]
48 public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
51 protected CodeAccessPermission ()
55 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
56 public void Assert ()
58 new PermissionSet (this).Assert ();
61 internal bool CheckAssert (CodeAccessPermission asserted)
63 if (asserted == null)
64 return false;
65 if (asserted.GetType () != this.GetType ())
66 return false;
67 return IsSubsetOf (asserted);
70 internal bool CheckDemand (CodeAccessPermission target)
72 if (target == null)
73 return false;
74 if (target.GetType () != this.GetType ())
75 return false;
76 return IsSubsetOf (target);
79 internal bool CheckDeny (CodeAccessPermission denied)
81 if (denied == null)
82 return true;
83 Type t = denied.GetType ();
84 if (t != this.GetType ())
85 return true;
86 IPermission inter = Intersect (denied);
87 if (inter == null)
88 return true;
89 // sadly that's not enough :( at this stage we must also check
90 // if an empty (PermissionState.None) is a subset of the denied
91 // (which is like a empty intersection looks like for flag based
92 // permissions, e.g. AspNetHostingPermission).
93 return denied.IsSubsetOf (PermissionBuilder.Create (t));
96 internal bool CheckPermitOnly (CodeAccessPermission target)
98 if (target == null)
99 return false;
100 if (target.GetType () != this.GetType ())
101 return false;
102 return IsSubsetOf (target);
105 public abstract IPermission Copy ();
107 public void Demand ()
109 // note: here we're sure it's a CAS demand
110 if (!SecurityManager.SecurityEnabled)
111 return;
113 // skip frames until we get the caller (of our caller)
114 new PermissionSet (this).CasOnlyDemand (3);
117 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
118 public void Deny ()
120 new PermissionSet (this).Deny ();
123 [ComVisible (false)]
124 public override bool Equals (object obj)
126 if (obj == null)
127 return false;
128 if (obj.GetType () != this.GetType ())
129 return false;
130 CodeAccessPermission cap = (obj as CodeAccessPermission);
131 return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
134 public abstract void FromXml (SecurityElement elem);
136 [ComVisible (false)]
137 public override int GetHashCode ()
139 return base.GetHashCode ();
142 public abstract IPermission Intersect (IPermission target);
144 public abstract bool IsSubsetOf (IPermission target);
146 public override string ToString ()
148 SecurityElement elem = ToXml ();
149 return elem.ToString ();
152 public abstract SecurityElement ToXml ();
154 public virtual IPermission Union (IPermission other)
156 if (null != other)
157 throw new System.NotSupportedException (); // other is not null.
158 return null;
161 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
162 public void PermitOnly ()
164 new PermissionSet (this).PermitOnly ();
167 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
168 public static void RevertAll ()
170 if (!SecurityManager.SecurityEnabled)
171 return;
173 SecurityFrame sf = new SecurityFrame (1);
174 bool revert = false;
175 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
176 revert = true;
177 throw new NotSupportedException ("Currently only declarative Assert are supported.");
179 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
180 revert = true;
181 throw new NotSupportedException ("Currently only declarative Deny are supported.");
183 if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
184 revert = true;
185 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
188 if (!revert) {
189 string msg = Locale.GetText ("No stack modifiers are present on the current stack frame.");
190 // FIXME: we don't (yet) support imperative stack modifiers
191 msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
192 throw new ExecutionEngineException (msg);
196 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
197 public static void RevertAssert ()
199 if (!SecurityManager.SecurityEnabled)
200 return;
202 SecurityFrame sf = new SecurityFrame (1);
203 if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
204 throw new NotSupportedException ("Currently only declarative Assert are supported.");
205 } else {
206 // we can't revert declarative security (or an empty frame) imperatively
207 ThrowExecutionEngineException (SecurityAction.Assert);
211 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
212 public static void RevertDeny ()
214 if (!SecurityManager.SecurityEnabled)
215 return;
217 SecurityFrame sf = new SecurityFrame (1);
218 if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
219 throw new NotSupportedException ("Currently only declarative Deny are supported.");
220 } else {
221 // we can't revert declarative security (or an empty frame) imperatively
222 ThrowExecutionEngineException (SecurityAction.Deny);
226 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
227 public static void RevertPermitOnly ()
229 if (!SecurityManager.SecurityEnabled)
230 return;
232 SecurityFrame sf = new SecurityFrame (1);
233 if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
234 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
235 } else {
236 // we can't revert declarative security (or an empty frame) imperatively
237 ThrowExecutionEngineException (SecurityAction.PermitOnly);
241 // Internal helpers methods
243 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
244 internal SecurityElement Element (int version)
246 SecurityElement se = new SecurityElement ("IPermission");
247 Type type = this.GetType ();
248 se.AddAttribute ("class", type.FullName + ", " + type.Assembly.ToString ().Replace ('\"', '\''));
249 se.AddAttribute ("version", version.ToString ());
250 return se;
253 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
255 string msg;
256 switch (state) {
257 case PermissionState.None:
258 break;
259 case PermissionState.Unrestricted:
260 // unrestricted permissions are possible for identiy permissions
261 break;
262 default:
263 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
264 throw new ArgumentException (msg, "state");
266 return state;
269 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion)
271 if (se == null)
272 throw new ArgumentNullException (parameterName);
274 // Tag is case-sensitive
275 if (se.Tag != "IPermission") {
276 string msg = String.Format (Locale.GetText ("Invalid tag {0}"), se.Tag);
277 throw new ArgumentException (msg, parameterName);
280 // Note: we do not care about the class attribute at
281 // this stage (in fact we don't even if the class
282 // attribute is present or not). Anyway the object has
283 // already be created, with success, if we're loading it
285 // we assume minimum version if no version number is supplied
286 int version = minimumVersion;
287 string v = se.Attribute ("version");
288 if (v != null) {
289 try {
290 version = Int32.Parse (v);
292 catch (Exception e) {
293 string msg = Locale.GetText ("Couldn't parse version from '{0}'.");
294 msg = String.Format (msg, v);
295 throw new ArgumentException (msg, parameterName, e);
299 if ((version < minimumVersion) || (version > maximumVersion)) {
300 string msg = Locale.GetText ("Unknown version '{0}', expected versions between ['{1}','{2}'].");
301 msg = String.Format (msg, version, minimumVersion, maximumVersion);
302 throw new ArgumentException (msg, parameterName);
304 return version;
307 // must be called after CheckSecurityElement (i.e. se != null)
308 internal static bool IsUnrestricted (SecurityElement se)
310 string value = se.Attribute ("Unrestricted");
311 if (value == null)
312 return false;
313 return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
316 internal bool ProcessFrame (SecurityFrame frame)
318 // 1. CheckPermitOnly
319 if (frame.PermitOnly != null) {
320 // the demanded permission must be in one of the permitted...
321 bool permit = frame.PermitOnly.IsUnrestricted ();
322 if (!permit) {
323 // check individual permissions
324 foreach (IPermission p in frame.PermitOnly) {
325 if (CheckPermitOnly (p as CodeAccessPermission)) {
326 permit = true;
327 break;
331 if (!permit) {
332 // ...or else we throw
333 ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
337 // 2. CheckDeny
338 if (frame.Deny != null) {
339 // special case where everything is denied (i.e. no child to be processed)
340 if (frame.Deny.IsUnrestricted ())
341 ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
342 foreach (IPermission p in frame.Deny) {
343 if (!CheckDeny (p as CodeAccessPermission))
344 ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, p);
348 // 3. CheckAssert
349 if (frame.Assert != null) {
350 if (frame.Assert.IsUnrestricted ())
351 return true; // remove permission and continue stack walk
352 foreach (IPermission p in frame.Assert) {
353 if (CheckAssert (p as CodeAccessPermission)) {
354 return true; // remove permission and continue stack walk
359 // continue the stack walk
360 return false;
363 internal static void ThrowInvalidPermission (IPermission target, Type expected)
365 string msg = Locale.GetText ("Invalid permission type '{0}', expected type '{1}'.");
366 msg = String.Format (msg, target.GetType (), expected);
367 throw new ArgumentException (msg, "target");
370 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
372 string msg = Locale.GetText ("No {0} modifier is present on the current stack frame.");
373 // FIXME: we don't (yet) support imperative stack modifiers
374 msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
375 throw new ExecutionEngineException (String.Format (msg, stackmod));
378 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
379 SecurityAction action, IPermission failed)
381 #if NET_2_1
382 throw new SecurityException (message);
383 #else
384 Assembly a = frame.Assembly;
385 throw new SecurityException (Locale.GetText (message),
386 a.UnprotectedGetName (), a.GrantedPermissionSet,
387 a.DeniedPermissionSet, frame.Method, action, demanded,
388 failed, a.UnprotectedGetEvidence ());
389 #endif