2004-11-30 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / corlib / System.Security / PermissionSet.cs
1 //
2 // System.Security.PermissionSet.cs
3 //
4 // Authors:
5 //      Nick Drochak(ndrochak@gol.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // (C) Nick Drochak
9 // Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Diagnostics;
34 using System.IO;
35 using System.Reflection;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization;
38 using System.Runtime.Serialization.Formatters.Binary;
39 using System.Security.Permissions;
40 using System.Security.Policy;
41 using System.Text;
42
43 namespace System.Security {
44
45         [Serializable]
46         public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
47
48                 private static string tagName = "PermissionSet";
49                 private const int version = 1;
50                 private static object[] psNone = new object [1] { PermissionState.None };
51
52                 private PermissionState state;
53                 private ArrayList list;
54                 private int _hashcode;
55                 private PolicyLevel _policyLevel;
56
57                 // constructors
58
59                 // for PolicyLevel (to avoid validation duplication)
60                 internal PermissionSet () 
61                 {
62                         list = new ArrayList ();
63                 }
64
65                 public PermissionSet (PermissionState state) : this ()
66                 {
67                         if (!Enum.IsDefined (typeof (PermissionState), state))
68                                 throw new System.ArgumentException ("state");
69                         this.state = state;
70                 }
71
72                 public PermissionSet (PermissionSet permSet) : this ()
73                 {
74                         // LAMESPEC: This would be handled by the compiler.  No way permSet is not a PermissionSet.
75                         //if (!(permSet is PermissionSet))
76                         //      throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
77                         if (permSet == null)
78                                 state = PermissionState.Unrestricted;
79                         else {
80                                 state = permSet.state;
81                                 foreach (IPermission p in permSet.list)
82                                         list.Add (p);
83                         }
84                 }
85
86                 internal PermissionSet (string xml)
87                         : this ()
88                 {
89                         state = PermissionState.None;
90                         if (xml != null) {
91                                 SecurityElement se = SecurityElement.FromString (xml);
92                                 FromXml (se);
93                         }
94                 }
95
96                 // methods
97
98                 public virtual IPermission AddPermission (IPermission perm)
99                 {
100                         if (perm == null)
101                                 return null;
102
103                         // we don't add to an unrestricted permission set unless...
104                         if (state == PermissionState.Unrestricted) {
105                                 // we're adding identity permission as they don't support unrestricted
106                                 if (perm is IUnrestrictedPermission) {
107                                         // we return the union of the permission with unrestricted
108                                         // which results in a permission of the same type initialized 
109                                         // with PermissionState.Unrestricted
110                                         object[] args = new object [1] { PermissionState.Unrestricted };
111                                         return (IPermission) Activator.CreateInstance (perm.GetType (), args);
112                                 }
113                         }
114
115                         // we can't add two permissions of the same type in a set
116                         // so we remove an existing one, union with it and add it back
117                         IPermission existing = RemovePermission (perm.GetType ());
118                         if (existing != null) {
119                                 perm = perm.Union (existing);
120                         }
121
122                         list.Add (perm);
123                         return perm;
124                 }
125
126                 [MonoTODO ("unmanaged side is incomplete")]
127                 public virtual void Assert ()
128                 {
129                         new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
130
131                         // we (current frame) must have the permission to assert it to others
132                         // otherwise we don't assert (but we don't throw an exception)
133                         foreach (IPermission p in list) {
134                                 // note: we ignore non-CAS permissions
135                                 if (p is IStackWalk) {
136                                         if (!SecurityManager.IsGranted (p)) {
137                                                 return;
138                                         }
139                                 }
140                         }
141
142                         CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Assert, this.Copy ());
143                 }
144
145                 internal void Clear () 
146                 {
147                         list.Clear ();
148                 }
149
150                 public virtual PermissionSet Copy ()
151                 {
152                         return new PermissionSet (this);
153                 }
154
155                 public virtual void CopyTo (Array array, int index)
156                 {
157                         if (null == array)
158                                 throw new ArgumentNullException ("array");
159
160                         if (list.Count > 0) {
161                                 if (array.Rank > 1) {
162                                         throw new ArgumentException (Locale.GetText (
163                                                 "Array has more than one dimension"));
164                                 }
165                                 if (index < 0 || index >= array.Length) {
166                                         throw new IndexOutOfRangeException ("index");
167                                 }
168
169                                 list.CopyTo (array, index);
170                         }
171                 }
172
173                 [MonoTODO ("Assert, Deny and PermitOnly aren't yet supported")]
174                 public virtual void Demand ()
175                 {
176                         if (IsEmpty ())
177                                 return;
178
179                         PermissionSet cas = this;
180                         // avoid copy (if possible)
181                         if (ContainsNonCodeAccessPermissions ()) {
182                                 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
183                                 cas = this.Copy ();
184                                 foreach (IPermission p in list) {
185                                         Type t = p.GetType ();
186                                         if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
187                                                 p.Demand ();
188                                                 // we wont have to process this one in the stack walk
189                                                 cas.RemovePermission (t);
190                                         }
191                                 }
192
193                                 // don't start the walk if the permission set only contains non CAS permissions
194                                 if (cas.Count == 0)
195                                         return;
196                         }
197
198                         // Note: SecurityEnabled only applies to CAS permissions
199                         if (!SecurityManager.SecurityEnabled)
200                                 return;
201
202                         // FIXME: optimize
203                         foreach (IPermission p in cas.list) {
204                                 p.Demand ();
205                         }
206                 }
207
208                 [MonoTODO ("unmanaged side is incomplete")]
209                 public virtual void Deny ()
210                 {
211                         CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Deny, this.Copy ());
212                 }
213
214                 [MonoTODO ("adjust class version with current runtime - unification")]
215                 public virtual void FromXml (SecurityElement et)
216                 {
217                         if (et == null)
218                                 throw new ArgumentNullException ("et");
219                         if (et.Tag != tagName) {
220                                 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
221                                 throw new ArgumentException (msg, "et");
222                         }
223
224                         if (CodeAccessPermission.IsUnrestricted (et))
225                                 state = PermissionState.Unrestricted;
226                         else
227                                 state = PermissionState.None;
228
229                         list.Clear ();
230                         if (et.Children != null) {
231                                 foreach (SecurityElement se in et.Children) {
232                                         string className = se.Attribute ("class");
233                                         if (className == null) {
234                                                 throw new ArgumentException (Locale.GetText (
235                                                         "No permission class is specified."));
236                                         }
237                                         if (Resolver != null) {
238                                                 // policy class names do not have to be fully qualified
239                                                 className = Resolver.ResolveClassName (className);
240                                         }
241                                         // TODO: adjust class version with current runtime (unification)
242                                         // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
243                                         Type classType = Type.GetType (className);
244                                         if (classType != null) {
245                                                 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
246                                                 p.FromXml (se);
247                                                 list.Add (p);
248                                         }
249 #if !NET_2_0
250                                         else {
251                                                 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
252                                                 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
253                                         }
254 #endif
255                                 }
256                         }
257                 }
258
259                 public virtual IEnumerator GetEnumerator ()
260                 {
261                         return list.GetEnumerator ();
262                 }
263
264                 public virtual bool IsSubsetOf (PermissionSet target)
265                 {
266                         // if target is empty we must be empty too
267                         if ((target == null) || (target.IsEmpty ()))
268                                 return this.IsEmpty ();
269
270                         // TODO - non CAS permissions must be evaluated for unrestricted
271
272                         // if target is unrestricted then we are a subset
273                         if (!this.IsUnrestricted () && target.IsUnrestricted ())
274                                 return true;
275                         // else target isn't unrestricted.
276                         // so if we are unrestricted, the we can't be a subset
277                         if (this.IsUnrestricted () && !target.IsUnrestricted ())
278                                 return false;
279
280                         // if each of our permission is (a) present and (b) a subset of target
281                         foreach (IPermission p in list) {
282                                 // for every type in both list
283                                 IPermission i = target.GetPermission (p.GetType ());
284                                 if (i == null)
285                                         return false; // not present (condition a)
286                                 if (!p.IsSubsetOf (i))
287                                         return false; // not a subset (condition b)
288                         }
289                         return true;
290                 }
291
292                 [MonoTODO ("unmanaged side is incomplete")]
293                 public virtual void PermitOnly ()
294                 {
295                         CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.PermitOnly, this.Copy ());
296                 }
297
298                 public bool ContainsNonCodeAccessPermissions () 
299                 {
300                         foreach (IPermission p in list) {
301                                 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
302                                         return true;
303                         }
304                         return false;
305                 }
306
307                 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
308                 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
309                 {
310                         if (inFormat == null)
311                                 throw new ArgumentNullException ("inFormat");
312                         if (outFormat == null)
313                                 throw new ArgumentNullException ("outFormat");
314                         if (inData == null)
315                                 return null;
316
317                         if (inFormat == outFormat)
318                                 return inData;
319
320                         PermissionSet ps = null;
321
322                         if (inFormat == "BINARY") {
323                                 if (outFormat.StartsWith ("XML")) {
324                                         using (MemoryStream ms = new MemoryStream (inData)) {
325                                                 BinaryFormatter formatter = new BinaryFormatter ();
326                                                 ps = (PermissionSet) formatter.Deserialize (ms);
327                                                 ms.Close ();
328                                         }
329                                         string xml = ps.ToString ();
330                                         switch (outFormat) {
331                                                 case "XML":
332                                                 case "XMLASCII":
333                                                         return Encoding.ASCII.GetBytes (xml);
334                                                 case "XMLUNICODE":
335                                                         return Encoding.Unicode.GetBytes (xml);
336                                         }
337                                 }
338                         }
339                         else if (inFormat.StartsWith ("XML")) {
340                                 if (outFormat == "BINARY") {
341                                         string xml = null;
342                                         switch (inFormat) {
343                                                 case "XML":
344                                                 case "XMLASCII":
345                                                         xml = Encoding.ASCII.GetString (inData);
346                                                         break;
347                                                 case "XMLUNICODE":
348                                                         xml = Encoding.Unicode.GetString (inData);
349                                                         break;
350                                         }
351                                         if (xml != null) {
352                                                 ps = new PermissionSet (PermissionState.None);
353                                                 ps.FromXml (SecurityElement.FromString (xml));
354
355                                                 MemoryStream ms = new MemoryStream ();
356                                                 BinaryFormatter formatter = new BinaryFormatter ();
357                                                 formatter.Serialize (ms, ps);
358                                                 ms.Close ();
359                                                 return ms.ToArray ();
360                                         }
361                                 }
362                                 else if (outFormat.StartsWith ("XML")) {
363                                         string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
364 #if NET_2_0
365                                         throw new XmlSyntaxException (msg);
366 #else
367                                         throw new ArgumentException (msg);
368 #endif
369                                 }
370                         }
371                         else {
372                                 // unknown inFormat, returns null
373                                 return null;
374                         }
375                         // unknown outFormat, throw
376                         throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
377                 }
378
379                 public virtual IPermission GetPermission (Type permClass) 
380                 {
381                         foreach (object o in list) {
382                                 if (o.GetType ().Equals (permClass))
383                                         return (IPermission) o;
384                         }
385                         // it's normal to return null for unrestricted sets
386                         return null;
387                 }
388
389                 public virtual PermissionSet Intersect (PermissionSet other) 
390                 {
391                         // no intersection possible
392                         if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
393                                 return null;
394
395                         PermissionState state = PermissionState.None;
396                         if (this.IsUnrestricted () && other.IsUnrestricted ())
397                                 state = PermissionState.Unrestricted;
398
399                         PermissionSet interSet = new PermissionSet (state);
400                         if (state == PermissionState.Unrestricted) {
401                                 InternalIntersect (interSet, this, other, true);
402                                 InternalIntersect (interSet, other, this, true);
403                         }
404                         else if (this.IsUnrestricted ()) {
405                                 InternalIntersect (interSet, this, other, true);
406                         }
407                         else if (other.IsUnrestricted ()) {
408                                 InternalIntersect (interSet, other, this, true);
409                         }
410                         else {
411                                 InternalIntersect (interSet, this, other, false);
412                         }
413                         return interSet;
414                 }
415
416                 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
417                 {
418                         foreach (IPermission p in b.list) {
419                                 // for every type in both list
420                                 IPermission i = a.GetPermission (p.GetType ());
421                                 if (i != null) {
422                                         // add intersection for this type
423                                         intersect.AddPermission (p.Intersect (i));
424                                 }
425                                 else if (unrestricted && (p is IUnrestrictedPermission)) {
426                                         intersect.AddPermission (p);
427                                 }
428                                 // or reject!
429                         }
430                 }
431
432                 public virtual bool IsEmpty () 
433                 {
434                         // note: Unrestricted isn't empty
435                         if (state == PermissionState.Unrestricted)
436                                 return false;
437                         if ((list == null) || (list.Count == 0))
438                                 return true;
439                         // the set may include some empty permissions
440                         foreach (IPermission p in list) {
441                                 // empty == fully restricted == IsSubsetOg(null) == true
442                                 if (!p.IsSubsetOf (null))
443                                         return false;
444                         }
445                         return true;
446                 }
447
448                 public virtual bool IsUnrestricted () 
449                 {
450                         return (state == PermissionState.Unrestricted);
451                 }
452
453                 public virtual IPermission RemovePermission (Type permClass) 
454                 {
455                         if (permClass == null)
456                                 return null;
457
458                         foreach (object o in list) {
459                                 if (o.GetType ().Equals (permClass)) {
460                                         list.Remove (o);
461                                         return (IPermission) o;
462                                 }
463                         }
464                         return null;
465                 }
466
467                 public virtual IPermission SetPermission (IPermission perm) 
468                 {
469                         if (perm == null)
470                                 return null;
471                         if (perm is IUnrestrictedPermission)
472                                 state = PermissionState.None;
473                         RemovePermission (perm.GetType ());
474                         list.Add (perm);
475                         return perm;
476                 }
477
478                 public override string ToString ()
479                 {
480                         return ToXml ().ToString ();
481                 }
482
483                 public virtual SecurityElement ToXml ()
484                 {
485                         SecurityElement se = new SecurityElement (tagName);
486                         se.AddAttribute ("class", GetType ().FullName);
487                         se.AddAttribute ("version", version.ToString ());
488                         if (state == PermissionState.Unrestricted)
489                                 se.AddAttribute ("Unrestricted", "true");
490
491                         // required for permissions that do not implement IUnrestrictedPermission
492                         foreach (IPermission p in list) {
493                                 se.AddChild (p.ToXml ());
494                         }
495                         return se;
496                 }
497
498                 public virtual PermissionSet Union (PermissionSet other)
499                 {
500                         if (other == null)
501                                 return this.Copy ();
502
503                         PermissionSet copy = this.Copy ();
504                         if (this.IsUnrestricted () || other.IsUnrestricted ()) {
505                                 // so we keep the "right" type
506                                 copy.Clear ();
507                                 copy.state = PermissionState.Unrestricted;
508                                 // copy all permissions that do not implement IUnrestrictedPermission
509                                 foreach (IPermission p in this.list) {
510                                         if (!(p is IUnrestrictedPermission))
511                                                 copy.AddPermission (p);
512                                 }
513                                 foreach (IPermission p in other.list) {
514                                         if (!(p is IUnrestrictedPermission))
515                                                 copy.AddPermission (p);
516                                 }
517                         }
518                         else {
519                                 // PermissionState.None -> copy all permissions
520                                 foreach (IPermission p in other.list) {
521                                         copy.AddPermission (p);
522                                 }
523                         }
524                         return copy;
525                 }
526
527                 public virtual int Count {
528                         get { return list.Count; }
529                 }
530
531                 public virtual bool IsSynchronized {
532                         get { return list.IsSynchronized; }
533                 }
534
535                 public virtual bool IsReadOnly {
536                         get { return false; } // always false
537                 }
538
539                 public virtual object SyncRoot {
540                         get { return this; }
541                 }
542
543                 [MonoTODO()]
544                 void IDeserializationCallback.OnDeserialization (object sender) 
545                 {
546                 }
547
548 #if NET_2_0
549                 [ComVisible (false)]
550                 public override bool Equals (object obj)
551                 {
552                         if (obj == null)
553                                 return false;
554                         PermissionSet ps = (obj as PermissionSet);
555                         if (ps == null)
556                                 return false;
557                         if (list.Count != ps.Count)
558                                 return false;
559
560                         for (int i=0; i < list.Count; i++) {
561                                 bool found = false;
562                                 for (int j=0; i < ps.list.Count; j++) {
563                                         if (list [i].Equals (ps.list [j])) {
564                                                 found = true;
565                                                 break;
566                                         }
567                                 }
568                                 if (!found)
569                                         return false;
570                         }
571                         return true;
572                 }
573
574                 [ComVisible (false)]
575                 public override int GetHashCode ()
576                 {
577                         if (list.Count == 0)
578                                 return (int) state;
579
580                         if (_hashcode == 0) {
581                                 _hashcode = state.GetHashCode ();
582                                 foreach (IPermission p in list) {
583                                         _hashcode ^= p.GetHashCode ();
584                                 }
585                         }
586                         return _hashcode;
587                 }
588
589                 [MonoTODO ("what's it doing here?")]
590                 static public void RevertAssert ()
591                 {
592                 }
593 #endif
594
595                 // internal
596
597                 internal PolicyLevel Resolver {
598                         get { return _policyLevel; }
599                         set { _policyLevel = value; }
600                 }
601
602
603                 internal void ImmediateCallerDemand ()
604                 {
605                         if (!SecurityManager.SecurityEnabled)
606                                 return;
607                         if (IsEmpty ())
608                                 return;
609
610                         StackTrace st = new StackTrace (1); // skip ourself
611                         StackFrame sf = st.GetFrame (0);
612                         MethodBase mb = sf.GetMethod ();
613                         Assembly af = mb.ReflectedType.Assembly;
614                         if (!af.Demand (this)) {
615                                 Type t = this.GetType ();
616                                 // TODO add more details
617                                 throw new SecurityException ("LinkDemand failed", t);
618                         }
619                 }
620
621                 // Note: Non-CAS demands aren't affected by SecurityManager.SecurityEnabled
622                 internal void ImmediateCallerNonCasDemand ()
623                 {
624                         if (IsEmpty ())
625                                 return;
626
627                         // non CAS permissions (e.g. PrincipalPermission) requires direct call to Demand
628                         foreach (IPermission p in list) {
629                                 p.Demand ();
630                         }
631                 }
632         }
633 }