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-2005 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;
42 using System.Threading;
44 namespace System.Security {
47 // Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
48 [StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
52 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
54 private const string tagName = "PermissionSet";
55 private const int version = 1;
56 private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
58 private PermissionState state;
59 private ArrayList list;
60 private int _hashcode;
61 private PolicyLevel _policyLevel;
62 private bool _declsec;
63 private bool _readOnly;
67 // for PolicyLevel (to avoid validation duplication)
68 internal PermissionSet ()
70 list = new ArrayList ();
73 public PermissionSet (PermissionState state) : this ()
75 if (!Enum.IsDefined (typeof (PermissionState), state))
76 throw new System.ArgumentException ("state");
80 public PermissionSet (PermissionSet permSet) : this ()
82 // LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
83 //if (!(permSet is PermissionSet))
84 // throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
85 if (permSet != null) {
86 state = permSet.state;
87 foreach (IPermission p in permSet.list)
92 state = PermissionState.Unrestricted;
97 internal PermissionSet (string xml)
100 state = PermissionState.None;
102 SecurityElement se = SecurityElement.FromString (xml);
107 // Light version for creating a (non unrestricted) PermissionSet with
108 // a single permission. This allows to relax most validations.
109 internal PermissionSet (IPermission perm)
113 // note: we do not copy IPermission like AddPermission
120 public virtual IPermission AddPermission (IPermission perm)
122 if ((perm == null) || _readOnly)
125 // we don't add to an unrestricted permission set unless...
126 if (state == PermissionState.Unrestricted) {
128 // identity permissions can be unrestricted under 2.x
131 // we're adding identity permission as they don't support unrestricted
132 if (perm is IUnrestrictedPermission) {
134 // we return the union of the permission with unrestricted
135 // which results in a permission of the same type initialized
136 // with PermissionState.Unrestricted
137 return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
141 // we can't add two permissions of the same type in a set
142 // so we remove an existing one, union with it and add it back
143 IPermission existing = RemovePermission (perm.GetType ());
144 if (existing != null) {
145 perm = perm.Union (existing);
148 // note: Add doesn't copy
153 [MonoTODO ("Imperative mode isn't supported")]
154 public virtual void Assert ()
156 new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
158 int count = this.Count;
160 // we (current frame) must have the permission to assert it to others
161 // otherwise we don't assert (but we don't throw an exception)
162 foreach (IPermission p in list) {
163 // note: we ignore non-CAS permissions
164 if (p is IStackWalk) {
165 if (!SecurityManager.IsGranted (p)) {
172 // note: we must ignore the stack modifiers for the non-CAS permissions
173 if (SecurityManager.SecurityEnabled && (count > 0))
174 throw new NotSupportedException ("Currently only declarative Assert are supported.");
177 internal void Clear ()
182 public virtual PermissionSet Copy ()
184 return new PermissionSet (this);
187 public virtual void CopyTo (Array array, int index)
190 throw new ArgumentNullException ("array");
192 if (list.Count > 0) {
193 if (array.Rank > 1) {
194 throw new ArgumentException (Locale.GetText (
195 "Array has more than one dimension"));
197 if (index < 0 || index >= array.Length) {
198 throw new IndexOutOfRangeException ("index");
201 list.CopyTo (array, index);
205 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
206 public virtual void Demand ()
208 // Note: SecurityEnabled only applies to CAS permissions
209 // so we're not checking for it (yet)
213 PermissionSet cas = this;
214 // avoid copy (if possible)
215 if (ContainsNonCodeAccessPermissions ()) {
216 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
218 foreach (IPermission p in list) {
219 Type t = p.GetType ();
220 if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
222 // we wont have to process this one in the stack walk
223 cas.RemovePermission (t);
228 // don't start the stack walk if
229 // - the permission set only contains non CAS permissions; or
230 // - security isn't enabled (applis only to CAS!)
231 if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
232 CasOnlyDemand (_declsec ? 5 : 3);
235 // The number of frames to skip depends on who's calling
236 // - CodeAccessPermission.Demand (imperative)
237 // - PermissionSet.Demand (imperative)
238 // - SecurityManager.InternalDemand (declarative)
239 internal void CasOnlyDemand (int skip)
241 Assembly current = null;
242 AppDomain domain = null;
244 ArrayList frames = SecurityFrame.GetStack (skip);
245 if ((frames != null) && (frames.Count > 0)) {
246 SecurityFrame first = ((SecurityFrame) frames [0]);
247 current = first.Assembly;
248 domain = first.Domain;
249 // skip ourself, Demand and other security runtime methods
250 foreach (SecurityFrame sf in frames) {
251 if (ProcessFrame (sf, ref current, ref domain))
252 return; // reached Assert
254 SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
255 CheckAssembly (current, last);
256 CheckAppDomain (domain, last);
259 // Is there a CompressedStack to handle ?
260 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
261 if ((stack != null) && !stack.IsEmpty ()) {
262 foreach (SecurityFrame frame in stack.List) {
263 if (ProcessFrame (frame, ref current, ref domain))
264 return; // reached Assert
269 [MonoTODO ("Imperative mode isn't supported")]
270 public virtual void Deny ()
272 if (!SecurityManager.SecurityEnabled)
275 foreach (IPermission p in list) {
276 // note: we ignore non-CAS permissions
277 if (p is IStackWalk) {
278 throw new NotSupportedException ("Currently only declarative Deny are supported.");
283 public virtual void FromXml (SecurityElement et)
286 throw new ArgumentNullException ("et");
287 if (et.Tag != tagName) {
288 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
289 throw new ArgumentException (msg, "et");
294 if (CodeAccessPermission.IsUnrestricted (et)) {
295 state = PermissionState.Unrestricted;
297 // no need to continue for an unrestricted permission
298 // because identity permissions now "supports" unrestricted
302 state = PermissionState.None;
305 if (et.Children != null) {
306 foreach (SecurityElement se in et.Children) {
307 string className = se.Attribute ("class");
308 if (className == null) {
309 throw new ArgumentException (Locale.GetText (
310 "No permission class is specified."));
312 if (Resolver != null) {
313 // policy class names do not have to be fully qualified
314 className = Resolver.ResolveClassName (className);
317 list.Add (PermissionBuilder.Create (className, se));
322 public virtual IEnumerator GetEnumerator ()
324 return list.GetEnumerator ();
327 public virtual bool IsSubsetOf (PermissionSet target)
330 // if target is empty we must be empty too
331 if ((target == null) || (target.IsEmpty ()))
332 return this.IsEmpty ();
334 // all permissions support unrestricted in 2.0
335 if (target.IsUnrestricted ())
337 if (this.IsUnrestricted ())
340 if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
343 // if each of our permission is (a) present and (b) a subset of target
344 foreach (IPermission p in list) {
346 if (target == null) {
347 if (!p.IsSubsetOf (null))
352 // non CAS permissions must be evaluated for unrestricted
353 Type t = p.GetType ();
354 IPermission i = null;
355 if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
356 i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
358 i = target.GetPermission (t);
361 if (!p.IsSubsetOf (i))
362 return false; // not a subset (condition b)
368 [MonoTODO ("Imperative mode isn't supported")]
369 public virtual void PermitOnly ()
371 if (!SecurityManager.SecurityEnabled)
374 foreach (IPermission p in list) {
375 // note: we ignore non-CAS permissions
376 if (p is IStackWalk) {
377 throw new NotSupportedException ("Currently only declarative Deny are supported.");
382 public bool ContainsNonCodeAccessPermissions ()
384 foreach (IPermission p in list) {
385 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
391 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
392 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
394 if (inFormat == null)
395 throw new ArgumentNullException ("inFormat");
396 if (outFormat == null)
397 throw new ArgumentNullException ("outFormat");
401 if (inFormat == outFormat)
404 PermissionSet ps = null;
406 if (inFormat == "BINARY") {
407 if (outFormat.StartsWith ("XML")) {
408 using (MemoryStream ms = new MemoryStream (inData)) {
409 BinaryFormatter formatter = new BinaryFormatter ();
410 ps = (PermissionSet) formatter.Deserialize (ms);
413 string xml = ps.ToString ();
417 return Encoding.ASCII.GetBytes (xml);
419 return Encoding.Unicode.GetBytes (xml);
423 else if (inFormat.StartsWith ("XML")) {
424 if (outFormat == "BINARY") {
429 xml = Encoding.ASCII.GetString (inData);
432 xml = Encoding.Unicode.GetString (inData);
436 ps = new PermissionSet (PermissionState.None);
437 ps.FromXml (SecurityElement.FromString (xml));
439 MemoryStream ms = new MemoryStream ();
440 BinaryFormatter formatter = new BinaryFormatter ();
441 formatter.Serialize (ms, ps);
443 return ms.ToArray ();
446 else if (outFormat.StartsWith ("XML")) {
447 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
449 throw new XmlSyntaxException (msg);
451 throw new ArgumentException (msg);
456 // unknown inFormat, returns null
459 // unknown outFormat, throw
460 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
463 public virtual IPermission GetPermission (Type permClass)
465 if ((permClass == null) || (list.Count == 0))
468 foreach (object o in list) {
469 if ((o != null) && o.GetType ().Equals (permClass))
470 return (IPermission) o;
472 // it's normal to return null for unrestricted sets
476 public virtual PermissionSet Intersect (PermissionSet other)
478 // no intersection possible
479 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
482 PermissionState state = PermissionState.None;
483 if (this.IsUnrestricted () && other.IsUnrestricted ())
484 state = PermissionState.Unrestricted;
486 PermissionSet interSet = new PermissionSet (state);
487 if (state == PermissionState.Unrestricted) {
488 InternalIntersect (interSet, this, other, true);
489 InternalIntersect (interSet, other, this, true);
491 else if (this.IsUnrestricted ()) {
492 InternalIntersect (interSet, this, other, true);
494 else if (other.IsUnrestricted ()) {
495 InternalIntersect (interSet, other, this, true);
498 InternalIntersect (interSet, this, other, false);
503 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
505 foreach (IPermission p in b.list) {
506 // for every type in both list
507 IPermission i = a.GetPermission (p.GetType ());
509 // add intersection for this type
510 intersect.AddPermission (p.Intersect (i));
513 // unrestricted is possible for indentity permissions
514 else if (unrestricted) {
516 else if (unrestricted && (p is IUnrestrictedPermission)) {
518 intersect.AddPermission (p);
524 public virtual bool IsEmpty ()
526 // note: Unrestricted isn't empty
527 if (state == PermissionState.Unrestricted)
529 if ((list == null) || (list.Count == 0))
531 // the set may include some empty permissions
532 foreach (IPermission p in list) {
533 // empty == fully restricted == IsSubsetOf(null) == true
534 if (!p.IsSubsetOf (null))
540 public virtual bool IsUnrestricted ()
542 return (state == PermissionState.Unrestricted);
545 public virtual IPermission RemovePermission (Type permClass)
547 if ((permClass == null) || _readOnly)
550 foreach (object o in list) {
551 if (o.GetType ().Equals (permClass)) {
553 return (IPermission) o;
559 public virtual IPermission SetPermission (IPermission perm)
561 if ((perm == null) || _readOnly)
564 IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
566 state = PermissionState.None;
568 state = u.IsUnrestricted () ? state : PermissionState.None;
571 if (perm is IUnrestrictedPermission)
572 state = PermissionState.None;
574 RemovePermission (perm.GetType ());
579 public override string ToString ()
581 return ToXml ().ToString ();
584 public virtual SecurityElement ToXml ()
586 SecurityElement se = new SecurityElement (tagName);
587 se.AddAttribute ("class", GetType ().FullName);
588 se.AddAttribute ("version", version.ToString ());
589 if (state == PermissionState.Unrestricted)
590 se.AddAttribute ("Unrestricted", "true");
592 // required for permissions that do not implement IUnrestrictedPermission
593 foreach (IPermission p in list) {
594 se.AddChild (p.ToXml ());
599 public virtual PermissionSet Union (PermissionSet other)
604 PermissionSet copy = this.Copy ();
605 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
606 // so we keep the "right" type
608 copy.state = PermissionState.Unrestricted;
609 // copy all permissions that do not implement IUnrestrictedPermission
610 foreach (IPermission p in this.list) {
611 if (!(p is IUnrestrictedPermission))
612 copy.AddPermission (p);
614 foreach (IPermission p in other.list) {
615 if (!(p is IUnrestrictedPermission))
616 copy.AddPermission (p);
620 // PermissionState.None -> copy all permissions
621 foreach (IPermission p in other.list) {
622 copy.AddPermission (p);
628 public virtual int Count {
629 get { return list.Count; }
632 public virtual bool IsSynchronized {
633 get { return list.IsSynchronized; }
636 public virtual bool IsReadOnly {
637 // always false (as documented) but the PermissionSet can be read-only
638 // e.g. in a PolicyStatement
639 get { return false; }
642 public virtual object SyncRoot {
646 internal bool DeclarativeSecurity {
647 get { return _declsec; }
648 set { _declsec = value; }
652 void IDeserializationCallback.OnDeserialization (object sender)
658 public override bool Equals (object obj)
662 PermissionSet ps = (obj as PermissionSet);
665 if (state != ps.state)
667 if (list.Count != ps.Count)
670 for (int i=0; i < list.Count; i++) {
672 for (int j=0; i < ps.list.Count; j++) {
673 if (list [i].Equals (ps.list [j])) {
685 public override int GetHashCode ()
687 return (list.Count == 0) ? (int) state : base.GetHashCode ();
690 [MonoTODO ("what's it doing here?")]
691 static public void RevertAssert ()
693 // FIXME: There's probably a reason this was added here ?
694 CodeAccessPermission.RevertAssert ();
700 internal PolicyLevel Resolver {
701 get { return _policyLevel; }
702 set { _policyLevel = value; }
705 internal void SetReadOnly (bool value)
710 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
712 if (IsUnrestricted ()) {
713 // we request unrestricted
714 if (frame.Deny != null) {
715 // but have restrictions (some denied permissions)
716 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
717 } else if (frame.PermitOnly != null) {
718 // but have restrictions (only some permitted permissions)
719 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
723 // skip next steps if no Assert, Deny or PermitOnly are present
724 if (frame.HasStackModifiers) {
725 foreach (CodeAccessPermission cap in list) {
726 if (cap.ProcessFrame (frame))
727 return true; // Assert reached - abort stack walk!
731 // however the "final" grant set is resolved by assembly, so
732 // there's no need to check it every time (just when we're
733 // changing assemblies between frames).
734 if (frame.Assembly != current) {
735 CheckAssembly (current, frame);
736 current = frame.Assembly;
739 if (frame.Domain != domain) {
740 CheckAppDomain (domain, frame);
741 domain = frame.Domain;
747 internal void CheckAssembly (Assembly a, SecurityFrame frame)
749 IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
751 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
752 frame, SecurityAction.Demand, p);
756 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
758 IPermission p = SecurityManager.CheckPermissionSet (domain, this);
760 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
761 frame, SecurityAction.Demand, p);
765 // 2.0 metadata format
767 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
769 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
770 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
771 throw new SecurityException (msg);
775 int numattr = ReadEncodedInt (data, ref pos);
776 PermissionSet ps = new PermissionSet (PermissionState.None);
777 for (int i = 0; i < numattr; i++) {
778 IPermission p = ProcessAttribute (data, ref pos);
780 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
781 throw new SecurityException (msg);
783 ps.AddPermission (p);
788 internal static int ReadEncodedInt (byte[] data, ref int position)
791 if ((data [position] & 0x80) == 0) {
792 len = data [position];
794 } else if ((data [position] & 0x40) == 0) {
795 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
798 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
799 (data [position + 2] << 8) | (data [position + 3]));
805 static object[] action = new object [1] { (SecurityAction) 0 };
807 // TODO: add support for arrays and enums
808 internal static IPermission ProcessAttribute (byte[] data, ref int position)
810 int clen = ReadEncodedInt (data, ref position);
811 string cnam = Encoding.UTF8.GetString (data, position, clen);
815 Type secattr = Type.GetType (cnam);
816 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
820 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
821 int numberOfParameters = ReadEncodedInt (data, ref position);
822 for (int j=0; j < numberOfParameters; j++) {
823 bool property = false;
824 switch (data [position++]) {
825 case 0x53: // field (technically possible and working)
828 case 0x54: // property (common case)
836 byte type = data [position++];
839 type = data [position++];
842 int plen = ReadEncodedInt (data, ref position);
843 string pnam = Encoding.UTF8.GetString (data, position, plen);
848 arrayLength = BitConverter.ToInt32 (data, position);
853 object[] arrayIndex = null;
854 for (int i = 0; i < arrayLength; i++) {
856 // TODO - setup index
859 // sadly type values doesn't match ther TypeCode enum :(
861 case 0x02: // MONO_TYPE_BOOLEAN
862 obj = (object) Convert.ToBoolean (data [position++]);
864 case 0x03: // MONO_TYPE_CHAR
865 obj = (object) Convert.ToChar (data [position]);
868 case 0x04: // MONO_TYPE_I1
869 obj = (object) Convert.ToSByte (data [position++]);
871 case 0x05: // MONO_TYPE_U1
872 obj = (object) Convert.ToByte (data [position++]);
874 case 0x06: // MONO_TYPE_I2
875 obj = (object) Convert.ToInt16 (data [position]);
878 case 0x07: // MONO_TYPE_U2
879 obj = (object) Convert.ToUInt16 (data [position]);
882 case 0x08: // MONO_TYPE_I4
883 obj = (object) Convert.ToInt32 (data [position]);
886 case 0x09: // MONO_TYPE_U4
887 obj = (object) Convert.ToUInt32 (data [position]);
890 case 0x0A: // MONO_TYPE_I8
891 obj = (object) Convert.ToInt64 (data [position]);
894 case 0x0B: // MONO_TYPE_U8
895 obj = (object) Convert.ToUInt64 (data [position]);
898 case 0x0C: // MONO_TYPE_R4
899 obj = (object) Convert.ToSingle (data [position]);
902 case 0x0D: // MONO_TYPE_R8
903 obj = (object) Convert.ToDouble (data [position]);
906 case 0x0E: // MONO_TYPE_STRING
908 if (data [position] != 0xFF) {
909 int slen = ReadEncodedInt (data, ref position);
910 s = Encoding.UTF8.GetString (data, position, slen);
917 case 0x50: // special for TYPE
918 int tlen = ReadEncodedInt (data, ref position);
919 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
923 return null; // unsupported
927 PropertyInfo pi = secattr.GetProperty (pnam);
928 pi.SetValue (sa, obj, arrayIndex);
930 FieldInfo fi = secattr.GetField (pnam);
931 fi.SetValue (sa, obj);
935 return sa.CreatePermission ();