2 // System.Security.PermissionSet.cs
5 // Nick Drochak(ndrochak@gol.com)
6 // Sebastien Pouliot <sebastien@ximian.com>
9 // Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.Diagnostics;
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;
43 namespace System.Security {
46 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
48 private static string tagName = "PermissionSet";
49 private const int version = 1;
50 private static object[] psNone = new object [1] { PermissionState.None };
52 private PermissionState state;
53 private ArrayList list;
54 private int _hashcode;
55 private PolicyLevel _policyLevel;
59 // for PolicyLevel (to avoid validation duplication)
60 internal PermissionSet ()
62 list = new ArrayList ();
65 public PermissionSet (PermissionState state) : this ()
67 if (!Enum.IsDefined (typeof (PermissionState), state))
68 throw new System.ArgumentException ("state");
72 public PermissionSet (PermissionSet permSet) : this ()
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.
78 state = PermissionState.Unrestricted;
80 state = permSet.state;
81 foreach (IPermission p in permSet.list)
86 internal PermissionSet (string xml)
89 state = PermissionState.None;
91 SecurityElement se = SecurityElement.FromString (xml);
98 public virtual IPermission AddPermission (IPermission perm)
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);
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);
126 [MonoTODO ("unmanaged side is incomplete")]
127 public virtual void Assert ()
129 new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
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)) {
142 CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Assert, this.Copy ());
145 internal void Clear ()
150 public virtual PermissionSet Copy ()
152 return new PermissionSet (this);
155 public virtual void CopyTo (Array array, int index)
158 throw new ArgumentNullException ("array");
160 if (list.Count > 0) {
161 if (array.Rank > 1) {
162 throw new ArgumentException (Locale.GetText (
163 "Array has more than one dimension"));
165 if (index < 0 || index >= array.Length) {
166 throw new IndexOutOfRangeException ("index");
169 list.CopyTo (array, index);
173 [MonoTODO ("Assert, Deny and PermitOnly aren't yet supported")]
174 public virtual void Demand ()
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
184 foreach (IPermission p in list) {
185 Type t = p.GetType ();
186 if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
188 // we wont have to process this one in the stack walk
189 cas.RemovePermission (t);
193 // don't start the walk if the permission set only contains non CAS permissions
198 // Note: SecurityEnabled only applies to CAS permissions
199 if (!SecurityManager.SecurityEnabled)
203 foreach (IPermission p in cas.list) {
208 [MonoTODO ("unmanaged side is incomplete")]
209 public virtual void Deny ()
211 CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Deny, this.Copy ());
214 [MonoTODO ("adjust class version with current runtime - unification")]
215 public virtual void FromXml (SecurityElement et)
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");
224 if (CodeAccessPermission.IsUnrestricted (et))
225 state = PermissionState.Unrestricted;
227 state = PermissionState.None;
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."));
237 if (Resolver != null) {
238 // policy class names do not have to be fully qualified
239 className = Resolver.ResolveClassName (className);
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);
251 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
252 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
259 public virtual IEnumerator GetEnumerator ()
261 return list.GetEnumerator ();
264 public virtual bool IsSubsetOf (PermissionSet target)
266 // if target is empty we must be empty too
267 if ((target == null) || (target.IsEmpty ()))
268 return this.IsEmpty ();
270 // TODO - non CAS permissions must be evaluated for unrestricted
272 // if target is unrestricted then we are a subset
273 if (!this.IsUnrestricted () && target.IsUnrestricted ())
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 ())
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 ());
285 return false; // not present (condition a)
286 if (!p.IsSubsetOf (i))
287 return false; // not a subset (condition b)
292 [MonoTODO ("unmanaged side is incomplete")]
293 public virtual void PermitOnly ()
295 CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.PermitOnly, this.Copy ());
298 public bool ContainsNonCodeAccessPermissions ()
300 foreach (IPermission p in list) {
301 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
307 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
308 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
310 if (inFormat == null)
311 throw new ArgumentNullException ("inFormat");
312 if (outFormat == null)
313 throw new ArgumentNullException ("outFormat");
317 if (inFormat == outFormat)
320 PermissionSet ps = null;
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);
329 string xml = ps.ToString ();
333 return Encoding.ASCII.GetBytes (xml);
335 return Encoding.Unicode.GetBytes (xml);
339 else if (inFormat.StartsWith ("XML")) {
340 if (outFormat == "BINARY") {
345 xml = Encoding.ASCII.GetString (inData);
348 xml = Encoding.Unicode.GetString (inData);
352 ps = new PermissionSet (PermissionState.None);
353 ps.FromXml (SecurityElement.FromString (xml));
355 MemoryStream ms = new MemoryStream ();
356 BinaryFormatter formatter = new BinaryFormatter ();
357 formatter.Serialize (ms, ps);
359 return ms.ToArray ();
362 else if (outFormat.StartsWith ("XML")) {
363 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
365 throw new XmlSyntaxException (msg);
367 throw new ArgumentException (msg);
372 // unknown inFormat, returns null
375 // unknown outFormat, throw
376 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
379 public virtual IPermission GetPermission (Type permClass)
381 foreach (object o in list) {
382 if (o.GetType ().Equals (permClass))
383 return (IPermission) o;
385 // it's normal to return null for unrestricted sets
389 public virtual PermissionSet Intersect (PermissionSet other)
391 // no intersection possible
392 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
395 PermissionState state = PermissionState.None;
396 if (this.IsUnrestricted () && other.IsUnrestricted ())
397 state = PermissionState.Unrestricted;
399 PermissionSet interSet = new PermissionSet (state);
400 if (state == PermissionState.Unrestricted) {
401 InternalIntersect (interSet, this, other, true);
402 InternalIntersect (interSet, other, this, true);
404 else if (this.IsUnrestricted ()) {
405 InternalIntersect (interSet, this, other, true);
407 else if (other.IsUnrestricted ()) {
408 InternalIntersect (interSet, other, this, true);
411 InternalIntersect (interSet, this, other, false);
416 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
418 foreach (IPermission p in b.list) {
419 // for every type in both list
420 IPermission i = a.GetPermission (p.GetType ());
422 // add intersection for this type
423 intersect.AddPermission (p.Intersect (i));
425 else if (unrestricted && (p is IUnrestrictedPermission)) {
426 intersect.AddPermission (p);
432 public virtual bool IsEmpty ()
434 // note: Unrestricted isn't empty
435 if (state == PermissionState.Unrestricted)
437 if ((list == null) || (list.Count == 0))
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))
448 public virtual bool IsUnrestricted ()
450 return (state == PermissionState.Unrestricted);
453 public virtual IPermission RemovePermission (Type permClass)
455 if (permClass == null)
458 foreach (object o in list) {
459 if (o.GetType ().Equals (permClass)) {
461 return (IPermission) o;
467 public virtual IPermission SetPermission (IPermission perm)
471 if (perm is IUnrestrictedPermission)
472 state = PermissionState.None;
473 RemovePermission (perm.GetType ());
478 public override string ToString ()
480 return ToXml ().ToString ();
483 public virtual SecurityElement ToXml ()
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");
491 // required for permissions that do not implement IUnrestrictedPermission
492 foreach (IPermission p in list) {
493 se.AddChild (p.ToXml ());
498 public virtual PermissionSet Union (PermissionSet other)
503 PermissionSet copy = this.Copy ();
504 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
505 // so we keep the "right" type
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);
513 foreach (IPermission p in other.list) {
514 if (!(p is IUnrestrictedPermission))
515 copy.AddPermission (p);
519 // PermissionState.None -> copy all permissions
520 foreach (IPermission p in other.list) {
521 copy.AddPermission (p);
527 public virtual int Count {
528 get { return list.Count; }
531 public virtual bool IsSynchronized {
532 get { return list.IsSynchronized; }
535 public virtual bool IsReadOnly {
536 get { return false; } // always false
539 public virtual object SyncRoot {
544 void IDeserializationCallback.OnDeserialization (object sender)
550 public override bool Equals (object obj)
554 PermissionSet ps = (obj as PermissionSet);
557 if (list.Count != ps.Count)
560 for (int i=0; i < list.Count; i++) {
562 for (int j=0; i < ps.list.Count; j++) {
563 if (list [i].Equals (ps.list [j])) {
575 public override int GetHashCode ()
580 if (_hashcode == 0) {
581 _hashcode = state.GetHashCode ();
582 foreach (IPermission p in list) {
583 _hashcode ^= p.GetHashCode ();
589 [MonoTODO ("what's it doing here?")]
590 static public void RevertAssert ()
597 internal PolicyLevel Resolver {
598 get { return _policyLevel; }
599 set { _policyLevel = value; }
603 internal void ImmediateCallerDemand ()
605 if (!SecurityManager.SecurityEnabled)
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);
621 // Note: Non-CAS demands aren't affected by SecurityManager.SecurityEnabled
622 internal void ImmediateCallerNonCasDemand ()
627 // non CAS permissions (e.g. PrincipalPermission) requires direct call to Demand
628 foreach (IPermission p in list) {