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)
329 // if target is empty we must be empty too
330 if ((target == null) || (target.IsEmpty ()))
331 return this.IsEmpty ();
333 // TODO - non CAS permissions must be evaluated for unrestricted
335 // if target is unrestricted then we are a subset
336 if (!this.IsUnrestricted () && target.IsUnrestricted ())
338 // else target isn't unrestricted.
339 // so if we are unrestricted, the we can't be a subset
340 if (this.IsUnrestricted () && !target.IsUnrestricted ())
343 // if each of our permission is (a) present and (b) a subset of target
344 foreach (IPermission p in list) {
345 // for every type in both list
346 IPermission i = target.GetPermission (p.GetType ());
348 return false; // not present (condition a)
349 if (!p.IsSubsetOf (i))
350 return false; // not a subset (condition b)
355 [MonoTODO ("Imperative mode isn't supported")]
356 public virtual void PermitOnly ()
358 if (!SecurityManager.SecurityEnabled)
361 foreach (IPermission p in list) {
362 // note: we ignore non-CAS permissions
363 if (p is IStackWalk) {
364 throw new NotSupportedException ("Currently only declarative Deny are supported.");
369 public bool ContainsNonCodeAccessPermissions ()
371 foreach (IPermission p in list) {
372 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
378 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
379 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
381 if (inFormat == null)
382 throw new ArgumentNullException ("inFormat");
383 if (outFormat == null)
384 throw new ArgumentNullException ("outFormat");
388 if (inFormat == outFormat)
391 PermissionSet ps = null;
393 if (inFormat == "BINARY") {
394 if (outFormat.StartsWith ("XML")) {
395 using (MemoryStream ms = new MemoryStream (inData)) {
396 BinaryFormatter formatter = new BinaryFormatter ();
397 ps = (PermissionSet) formatter.Deserialize (ms);
400 string xml = ps.ToString ();
404 return Encoding.ASCII.GetBytes (xml);
406 return Encoding.Unicode.GetBytes (xml);
410 else if (inFormat.StartsWith ("XML")) {
411 if (outFormat == "BINARY") {
416 xml = Encoding.ASCII.GetString (inData);
419 xml = Encoding.Unicode.GetString (inData);
423 ps = new PermissionSet (PermissionState.None);
424 ps.FromXml (SecurityElement.FromString (xml));
426 MemoryStream ms = new MemoryStream ();
427 BinaryFormatter formatter = new BinaryFormatter ();
428 formatter.Serialize (ms, ps);
430 return ms.ToArray ();
433 else if (outFormat.StartsWith ("XML")) {
434 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
436 throw new XmlSyntaxException (msg);
438 throw new ArgumentException (msg);
443 // unknown inFormat, returns null
446 // unknown outFormat, throw
447 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
450 public virtual IPermission GetPermission (Type permClass)
452 if ((permClass == null) || (list.Count == 0))
455 foreach (object o in list) {
456 if ((o != null) && o.GetType ().Equals (permClass))
457 return (IPermission) o;
459 // it's normal to return null for unrestricted sets
463 public virtual PermissionSet Intersect (PermissionSet other)
465 // no intersection possible
466 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
469 PermissionState state = PermissionState.None;
470 if (this.IsUnrestricted () && other.IsUnrestricted ())
471 state = PermissionState.Unrestricted;
473 PermissionSet interSet = new PermissionSet (state);
474 if (state == PermissionState.Unrestricted) {
475 InternalIntersect (interSet, this, other, true);
476 InternalIntersect (interSet, other, this, true);
478 else if (this.IsUnrestricted ()) {
479 InternalIntersect (interSet, this, other, true);
481 else if (other.IsUnrestricted ()) {
482 InternalIntersect (interSet, other, this, true);
485 InternalIntersect (interSet, this, other, false);
490 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
492 foreach (IPermission p in b.list) {
493 // for every type in both list
494 IPermission i = a.GetPermission (p.GetType ());
496 // add intersection for this type
497 intersect.AddPermission (p.Intersect (i));
500 // unrestricted is possible for indentity permissions
501 else if (unrestricted) {
503 else if (unrestricted && (p is IUnrestrictedPermission)) {
505 intersect.AddPermission (p);
511 public virtual bool IsEmpty ()
513 // note: Unrestricted isn't empty
514 if (state == PermissionState.Unrestricted)
516 if ((list == null) || (list.Count == 0))
518 // the set may include some empty permissions
519 foreach (IPermission p in list) {
520 // empty == fully restricted == IsSubsetOf(null) == true
521 if (!p.IsSubsetOf (null))
527 public virtual bool IsUnrestricted ()
529 return (state == PermissionState.Unrestricted);
532 public virtual IPermission RemovePermission (Type permClass)
534 if ((permClass == null) || _readOnly)
537 foreach (object o in list) {
538 if (o.GetType ().Equals (permClass)) {
540 return (IPermission) o;
546 public virtual IPermission SetPermission (IPermission perm)
548 if ((perm == null) || _readOnly)
551 IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
553 state = PermissionState.None;
555 state = u.IsUnrestricted () ? state : PermissionState.None;
558 if (perm is IUnrestrictedPermission)
559 state = PermissionState.None;
561 RemovePermission (perm.GetType ());
566 public override string ToString ()
568 return ToXml ().ToString ();
571 public virtual SecurityElement ToXml ()
573 SecurityElement se = new SecurityElement (tagName);
574 se.AddAttribute ("class", GetType ().FullName);
575 se.AddAttribute ("version", version.ToString ());
576 if (state == PermissionState.Unrestricted)
577 se.AddAttribute ("Unrestricted", "true");
579 // required for permissions that do not implement IUnrestrictedPermission
580 foreach (IPermission p in list) {
581 se.AddChild (p.ToXml ());
586 public virtual PermissionSet Union (PermissionSet other)
591 PermissionSet copy = this.Copy ();
592 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
593 // so we keep the "right" type
595 copy.state = PermissionState.Unrestricted;
596 // copy all permissions that do not implement IUnrestrictedPermission
597 foreach (IPermission p in this.list) {
598 if (!(p is IUnrestrictedPermission))
599 copy.AddPermission (p);
601 foreach (IPermission p in other.list) {
602 if (!(p is IUnrestrictedPermission))
603 copy.AddPermission (p);
607 // PermissionState.None -> copy all permissions
608 foreach (IPermission p in other.list) {
609 copy.AddPermission (p);
615 public virtual int Count {
616 get { return list.Count; }
619 public virtual bool IsSynchronized {
620 get { return list.IsSynchronized; }
623 public virtual bool IsReadOnly {
624 // always false (as documented) but the PermissionSet can be read-only
625 // e.g. in a PolicyStatement
626 get { return false; }
629 public virtual object SyncRoot {
633 internal bool DeclarativeSecurity {
634 get { return _declsec; }
635 set { _declsec = value; }
639 void IDeserializationCallback.OnDeserialization (object sender)
645 public override bool Equals (object obj)
649 PermissionSet ps = (obj as PermissionSet);
652 if (state != ps.state)
654 if (list.Count != ps.Count)
657 for (int i=0; i < list.Count; i++) {
659 for (int j=0; i < ps.list.Count; j++) {
660 if (list [i].Equals (ps.list [j])) {
672 public override int GetHashCode ()
674 return (list.Count == 0) ? (int) state : base.GetHashCode ();
677 [MonoTODO ("what's it doing here?")]
678 static public void RevertAssert ()
680 // FIXME: There's probably a reason this was added here ?
681 CodeAccessPermission.RevertAssert ();
687 internal PolicyLevel Resolver {
688 get { return _policyLevel; }
689 set { _policyLevel = value; }
692 internal void SetReadOnly (bool value)
697 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
699 if (IsUnrestricted ()) {
700 // we request unrestricted
701 if (frame.Deny != null) {
702 // but have restrictions (some denied permissions)
703 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
704 } else if (frame.PermitOnly != null) {
705 // but have restrictions (only some permitted permissions)
706 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
710 // skip next steps if no Assert, Deny or PermitOnly are present
711 if (frame.HasStackModifiers) {
712 foreach (CodeAccessPermission cap in list) {
713 if (cap.ProcessFrame (frame))
714 return true; // Assert reached - abort stack walk!
718 // however the "final" grant set is resolved by assembly, so
719 // there's no need to check it every time (just when we're
720 // changing assemblies between frames).
721 if (frame.Assembly != current) {
722 CheckAssembly (current, frame);
723 current = frame.Assembly;
726 if (frame.Domain != domain) {
727 CheckAppDomain (domain, frame);
728 domain = frame.Domain;
734 internal void CheckAssembly (Assembly a, SecurityFrame frame)
736 IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
738 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
739 frame, SecurityAction.Demand, p);
743 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
745 IPermission p = SecurityManager.CheckPermissionSet (domain, this);
747 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
748 frame, SecurityAction.Demand, p);
752 // 2.0 metadata format
754 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
756 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
757 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
758 throw new SecurityException (msg);
762 int numattr = ReadEncodedInt (data, ref pos);
763 PermissionSet ps = new PermissionSet (PermissionState.None);
764 for (int i = 0; i < numattr; i++) {
765 IPermission p = ProcessAttribute (data, ref pos);
767 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
768 throw new SecurityException (msg);
770 ps.AddPermission (p);
775 internal static int ReadEncodedInt (byte[] data, ref int position)
778 if ((data [position] & 0x80) == 0) {
779 len = data [position];
781 } else if ((data [position] & 0x40) == 0) {
782 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
785 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
786 (data [position + 2] << 8) | (data [position + 3]));
792 static object[] action = new object [1] { (SecurityAction) 0 };
794 // TODO: add support for arrays and enums
795 internal static IPermission ProcessAttribute (byte[] data, ref int position)
797 int clen = ReadEncodedInt (data, ref position);
798 string cnam = Encoding.UTF8.GetString (data, position, clen);
802 Type secattr = Type.GetType (cnam);
803 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
807 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
808 int numberOfParameters = ReadEncodedInt (data, ref position);
809 for (int j=0; j < numberOfParameters; j++) {
810 bool property = false;
811 switch (data [position++]) {
812 case 0x53: // field (technically possible and working)
815 case 0x54: // property (common case)
823 byte type = data [position++];
826 type = data [position++];
829 int plen = ReadEncodedInt (data, ref position);
830 string pnam = Encoding.UTF8.GetString (data, position, plen);
835 arrayLength = BitConverter.ToInt32 (data, position);
840 object[] arrayIndex = null;
841 for (int i = 0; i < arrayLength; i++) {
843 // TODO - setup index
846 // sadly type values doesn't match ther TypeCode enum :(
848 case 0x02: // MONO_TYPE_BOOLEAN
849 obj = (object) Convert.ToBoolean (data [position++]);
851 case 0x03: // MONO_TYPE_CHAR
852 obj = (object) Convert.ToChar (data [position]);
855 case 0x04: // MONO_TYPE_I1
856 obj = (object) Convert.ToSByte (data [position++]);
858 case 0x05: // MONO_TYPE_U1
859 obj = (object) Convert.ToByte (data [position++]);
861 case 0x06: // MONO_TYPE_I2
862 obj = (object) Convert.ToInt16 (data [position]);
865 case 0x07: // MONO_TYPE_U2
866 obj = (object) Convert.ToUInt16 (data [position]);
869 case 0x08: // MONO_TYPE_I4
870 obj = (object) Convert.ToInt32 (data [position]);
873 case 0x09: // MONO_TYPE_U4
874 obj = (object) Convert.ToUInt32 (data [position]);
877 case 0x0A: // MONO_TYPE_I8
878 obj = (object) Convert.ToInt64 (data [position]);
881 case 0x0B: // MONO_TYPE_U8
882 obj = (object) Convert.ToUInt64 (data [position]);
885 case 0x0C: // MONO_TYPE_R4
886 obj = (object) Convert.ToSingle (data [position]);
889 case 0x0D: // MONO_TYPE_R8
890 obj = (object) Convert.ToDouble (data [position]);
893 case 0x0E: // MONO_TYPE_STRING
895 if (data [position] != 0xFF) {
896 int slen = ReadEncodedInt (data, ref position);
897 s = Encoding.UTF8.GetString (data, position, slen);
904 case 0x50: // special for TYPE
905 int tlen = ReadEncodedInt (data, ref position);
906 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
910 return null; // unsupported
914 PropertyInfo pi = secattr.GetProperty (pnam);
915 pi.SetValue (sa, obj, arrayIndex);
917 FieldInfo fi = secattr.GetField (pnam);
918 fi.SetValue (sa, obj);
922 return sa.CreatePermission ();