Set svn:eol-style=native, delete svn:executable.
[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         public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk {
47
48                 protected CodeAccessPermission ()
49                 {
50                 }
51
52                 [MonoTODO ("Imperative mode isn't supported")]
53                 public void Assert ()
54                 {
55                         new PermissionSet (this).Assert ();
56                 }
57
58                 internal bool CheckAssert (CodeAccessPermission asserted)
59                 {
60                         if (asserted == null)
61                                 return false;
62                         if (asserted.GetType () != this.GetType ())
63                                 return false;
64                         return IsSubsetOf (asserted);
65                 }
66
67                 internal bool CheckDemand (CodeAccessPermission target)
68                 {
69                         if (target == null)
70                                 return false;
71                         if (target.GetType () != this.GetType ())
72                                 return false;
73                         return IsSubsetOf (target);
74                 }
75
76                 internal bool CheckDeny (CodeAccessPermission denied)
77                 {
78                         if (denied == null)
79                                 return true;
80                         if (denied.GetType () != this.GetType ())
81                                 return true;
82                         return (Intersect (denied) == null);
83                 }
84
85                 internal bool CheckPermitOnly (CodeAccessPermission target)
86                 {
87                         if (target == null)
88                                 return false;
89                         if (target.GetType () != this.GetType ())
90                                 return false;
91                         return IsSubsetOf (target);
92                 }
93
94                 public abstract IPermission Copy ();
95
96                 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
97                 public void Demand ()
98                 {
99                         // note: here we're sure it's a CAS demand
100                         if (!SecurityManager.SecurityEnabled)
101                                 return;
102
103                         // skip frames until we get the caller (of our caller)
104                         new PermissionSet (this).CasOnlyDemand (3);
105                 }
106
107                 [MonoTODO ("Imperative mode isn't supported")]
108                 public void Deny ()
109                 {
110                         new PermissionSet (this).Deny ();
111                 }
112
113 #if NET_2_0
114                 [ComVisible (false)]
115                 public override bool Equals (object obj)
116                 {
117                         if (obj == null)
118                                 return false;
119                         if (obj.GetType () != this.GetType ())
120                                 return false;
121                         CodeAccessPermission cap = (obj as CodeAccessPermission);
122                         return (IsSubsetOf (cap) && cap.IsSubsetOf (this));
123                 }
124 #endif
125
126                 public abstract void FromXml (SecurityElement elem);
127
128 #if NET_2_0
129                 [ComVisible (false)]
130                 public override int GetHashCode ()
131                 {
132                         return base.GetHashCode ();
133                 }
134 #endif
135
136                 public abstract IPermission Intersect (IPermission target);
137
138                 public abstract bool IsSubsetOf (IPermission target);
139
140                 public override string ToString ()
141                 {
142                         SecurityElement elem = ToXml ();
143                         return elem.ToString ();
144                 }
145
146                 public abstract SecurityElement ToXml ();
147
148                 public virtual IPermission Union (IPermission other)
149                 {
150                         if (null != other)
151                                 throw new System.NotSupportedException (); // other is not null.
152                         return null;
153                 }
154
155                 [MonoTODO ("Imperative mode isn't supported")]
156                 public void PermitOnly ()
157                 {
158                         new PermissionSet (this).PermitOnly ();
159                 }
160
161                 [MonoTODO ("Imperative mode isn't supported")]
162                 public static void RevertAll ()
163                 {
164                         if (!SecurityManager.SecurityEnabled)
165                                 return;
166
167                         SecurityFrame sf = new SecurityFrame (1);
168                         bool revert = false;
169                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
170                                 revert = true;
171                                 // TODO
172                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
173                         }
174                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
175                                 revert = true;
176                                 // TODO
177                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
178                         }
179                         if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
180                                 revert = true;
181                                 // TODO
182                                 throw new NotSupportedException ("Currently only declarative PermitOnly are supported.");
183                         }
184
185                         if (!revert) {
186                                 string msg = Locale.GetText ("No stack modifiers are present on the current stack frame.");
187                                 // FIXME: we don't (yet) support imperative stack modifiers
188                                 msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
189                                 throw new ExecutionEngineException (msg);
190                         }
191                 }
192
193                 [MonoTODO ("Imperative mode isn't supported")]
194                 public static void RevertAssert ()
195                 {
196                         if (!SecurityManager.SecurityEnabled)
197                                 return;
198
199                         SecurityFrame sf = new SecurityFrame (1);
200                         if ((sf.Assert != null) && !sf.Assert.DeclarativeSecurity) {
201                                 // TODO
202                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
203                         } else {
204                                 // we can't revert declarative security (or an empty frame) imperatively
205                                 ThrowExecutionEngineException (SecurityAction.Assert);
206                         }
207                 }
208
209                 [MonoTODO ("Imperative mode isn't supported")]
210                 public static void RevertDeny ()
211                 {
212                         if (!SecurityManager.SecurityEnabled)
213                                 return;
214
215                         SecurityFrame sf = new SecurityFrame (1);
216                         if ((sf.Deny != null) && !sf.Deny.DeclarativeSecurity) {
217                                 // TODO
218                                 throw new NotSupportedException ("Currently only declarative Deny are supported.");
219                         } else {
220                                 // we can't revert declarative security (or an empty frame) imperatively
221                                 ThrowExecutionEngineException (SecurityAction.Deny);
222                         }
223                 }
224
225                 [MonoTODO ("Imperative mode isn't supported")]
226                 public static void RevertPermitOnly ()
227                 {
228                         if (!SecurityManager.SecurityEnabled)
229                                 return;
230
231                         SecurityFrame sf = new SecurityFrame (1);
232                         if ((sf.PermitOnly != null) && sf.PermitOnly.DeclarativeSecurity) {
233                                 // TODO
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                                 if (!allowUnrestricted) {
261                                         msg = Locale.GetText ("Unrestricted isn't not allowed for identity permissions.");
262                                         throw new ArgumentException (msg, "state");
263                                 }
264                                 break;
265                         default:
266                                 msg = String.Format (Locale.GetText ("Invalid enum {0}"), state);
267                                 throw new ArgumentException (msg, "state");
268                         }
269                         return state;
270                 }
271
272                 internal static int CheckSecurityElement (SecurityElement se, string parameterName, int minimumVersion, int maximumVersion) 
273                 {
274                         if (se == null)
275                                 throw new ArgumentNullException (parameterName);
276
277                         // Tag is case-sensitive
278                         if (se.Tag != "IPermission") {
279                                 string msg = String.Format (Locale.GetText ("Invalid tag {0}"), se.Tag);
280                                 throw new ArgumentException (msg, parameterName);
281                         }
282
283                         // Note: we do not care about the class attribute at 
284                         // this stage (in fact we don't even if the class 
285                         // attribute is present or not). Anyway the object has
286                         // already be created, with success, if we're loading it
287
288                         // we assume minimum version if no version number is supplied
289                         int version = minimumVersion;
290                         string v = se.Attribute ("version");
291                         if (v != null) {
292                                 try {
293                                         version = Int32.Parse (v);
294                                 }
295                                 catch (Exception e) {
296                                         string msg = Locale.GetText ("Couldn't parse version from '{0}'.");
297                                         msg = String.Format (msg, v);
298                                         throw new ArgumentException (msg, parameterName, e);
299                                 }
300                         }
301
302                         if ((version < minimumVersion) || (version > maximumVersion)) {
303                                 string msg = Locale.GetText ("Unknown version '{0}', expected versions between ['{1}','{2}'].");
304                                 msg = String.Format (msg, version, minimumVersion, maximumVersion);
305                                 throw new ArgumentException (msg, parameterName);
306                         }
307                         return version;
308                 }
309
310                 // must be called after CheckSecurityElement (i.e. se != null)
311                 internal static bool IsUnrestricted (SecurityElement se) 
312                 {
313                         string value = se.Attribute ("Unrestricted");
314                         if (value == null)
315                                 return false;
316                         return (String.Compare (value, Boolean.TrueString, true, CultureInfo.InvariantCulture) == 0);
317                 }
318
319                 internal bool ProcessFrame (SecurityFrame frame)
320                 { 
321                         // 1. CheckPermitOnly
322                         if (frame.PermitOnly != null) {
323                                 // the demanded permission must be in one of the permitted...
324                                 bool permit = false;
325                                 foreach (IPermission p in frame.PermitOnly) {
326                                         if (CheckPermitOnly (p as CodeAccessPermission)) {
327                                                 permit = true;
328                                                 break;
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                                 foreach (IPermission p in frame.Assert) {
351                                         if (CheckAssert (p as CodeAccessPermission)) {
352                                                 // FIXME: partial asserts
353                                                 return true; // stop the stack walk
354                                         }
355                                 }
356                         }
357
358                         // continue the stack walk
359                         return false; 
360                 }
361
362                 internal static void ThrowInvalidPermission (IPermission target, Type expected) 
363                 {
364                         string msg = Locale.GetText ("Invalid permission type '{0}', expected type '{1}'.");
365                         msg = String.Format (msg, target.GetType (), expected);
366                         throw new ArgumentException (msg, "target");
367                 }
368
369                 internal static void ThrowExecutionEngineException (SecurityAction stackmod)
370                 {
371                         string msg = Locale.GetText ("No {0} modifier is present on the current stack frame.");
372                         // FIXME: we don't (yet) support imperative stack modifiers
373                         msg += Environment.NewLine + "Currently only declarative stack modifiers are supported.";
374                         throw new ExecutionEngineException (String.Format (msg, stackmod));
375                 }
376
377                 internal static void ThrowSecurityException (object demanded, string message, SecurityFrame frame,
378                         SecurityAction action, IPermission failed)
379                 {
380                         Assembly a = frame.Assembly;
381                         throw new SecurityException (Locale.GetText (message), 
382                                 a.UnprotectedGetName (), a.GrantedPermissionSet, 
383                                 a.DeniedPermissionSet, frame.Method, action, demanded, 
384                                 failed, a.UnprotectedGetEvidence ());
385                 }
386         }
387 }