2010-03-24 Jérémie Laval <jeremie.laval@gmail.com>
[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         [ComVisible (true)]
47         [MonoTODO ("CAS support is experimental (and unsupported).")]
48         public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
49
50
51                 protected CodeAccessPermission ()
52                 {
53                 }
54
55                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
56                 public void Assert ()
57                 {
58                         new PermissionSet (this).Assert ();
59                 }
60
61                 internal bool CheckAssert (CodeAccessPermission asserted)
62                 {
63                         if (asserted == null)
64                                 return false;
65                         if (asserted.GetType () != this.GetType ())
66                                 return false;
67                         return IsSubsetOf (asserted);
68                 }
69
70                 internal bool CheckDemand (CodeAccessPermission target)
71                 {
72                         if (target == null)
73                                 return false;
74                         if (target.GetType () != this.GetType ())
75                                 return false;
76                         return IsSubsetOf (target);
77                 }
78
79                 internal bool CheckDeny (CodeAccessPermission denied)
80                 {
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));
94                 }
95
96                 internal bool CheckPermitOnly (CodeAccessPermission target)
97                 {
98                         if (target == null)
99                                 return false;
100                         if (target.GetType () != this.GetType ())
101                                 return false;
102                         return IsSubsetOf (target);
103                 }
104
105                 public abstract IPermission Copy ();
106
107                 public void Demand ()
108                 {
109                         // note: here we're sure it's a CAS demand
110                         if (!SecurityManager.SecurityEnabled)
111                                 return;
112
113                         // skip frames until we get the caller (of our caller)
114                         new PermissionSet (this).CasOnlyDemand (3);
115                 }
116
117                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
118                 public void Deny ()
119                 {
120                         new PermissionSet (this).Deny ();
121                 }
122
123                 [ComVisible (false)]
124                 public override bool Equals (object obj)
125                 {
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));
132                 }
133
134                 public abstract void FromXml (SecurityElement elem);
135
136                 [ComVisible (false)]
137                 public override int GetHashCode ()
138                 {
139                         return base.GetHashCode ();
140                 }
141
142                 public abstract IPermission Intersect (IPermission target);
143
144                 public abstract bool IsSubsetOf (IPermission target);
145
146                 public override string ToString ()
147                 {
148                         SecurityElement elem = ToXml ();
149                         return elem.ToString ();
150                 }
151
152                 public abstract SecurityElement ToXml ();
153
154                 public virtual IPermission Union (IPermission other)
155                 {
156                         if (null != other)
157                                 throw new System.NotSupportedException (); // other is not null.
158                         return null;
159                 }
160
161                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
162                 public void PermitOnly ()
163                 {
164                         new PermissionSet (this).PermitOnly ();
165                 }
166
167                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
168                 public static void RevertAll ()
169                 {
170                         if (!SecurityManager.SecurityEnabled)
171                                 return;
172
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.");
178                         }
179                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
180                                 revert = true;
181                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
182                         }
183                         if ((sf.PermitOnly != null) && !sf.PermitOnly.DeclarativeSecurity) {
184                                 revert = true;
185                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
186                         }
187
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);
193                         }
194                 }
195
196                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
197                 public static void RevertAssert ()
198                 {
199                         if (!SecurityManager.SecurityEnabled)
200                                 return;
201
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);
208                         }
209                 }
210
211                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
212                 public static void RevertDeny ()
213                 {
214                         if (!SecurityManager.SecurityEnabled)
215                                 return;
216
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);
223                         }
224                 }
225
226                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
227                 public static void RevertPermitOnly ()
228                 {
229                         if (!SecurityManager.SecurityEnabled)
230                                 return;
231
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);
238                         }
239                 }
240
241                 // Internal helpers methods
242
243                 // snippet moved from FileIOPermission (nickd) to be reused in all derived classes
244                 internal SecurityElement Element (int version) 
245                 {
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;
251                 }
252
253                 internal static PermissionState CheckPermissionState (PermissionState state, bool allowUnrestricted)
254                 {
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");
265                         }
266                         return state;
267                 }
268
269                 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion) 
270                 {
271                         if (se == null)
272                                 throw new ArgumentNullException (parameterName);
273
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);
278                         }
279
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
284
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);
291                                 }
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);
296                                 }
297                         }
298
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);
303                         }
304                         return version;
305                 }
306
307                 // must be called after CheckSecurityElement (i.e. se != null)
308                 internal static bool IsUnrestricted (SecurityElement se) 
309                 {
310                         string value = se.Attribute ("Unrestricted");
311                         if (value == null)
312                                 return false;
313                         return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
314                 }
315
316                 internal bool ProcessFrame (SecurityFrame frame)
317                 { 
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;
328                                                 }
329                                         }
330                                 }
331                                 if (!permit) {
332                                         // ...or else we throw
333                                         ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
334                                 }
335                         }
336
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);
345                                 }
346                         }
347
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
355                                         }
356                                 }
357                         }
358
359                         // continue the stack walk
360                         return false; 
361                 }
362
363                 internal static void ThrowInvalidPermission (IPermission target, Type expected) 
364                 {
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");
368                 }
369
370                 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
371                 {
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));
376                 }
377
378                 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
379                         SecurityAction action, IPermission failed)
380                 {
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
390                 }
391         }
392 }