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")]
49 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
51 private static string tagName = "PermissionSet";
52 private const int version = 1;
53 private static object[] psNone = new object [1] { PermissionState.None };
55 private PermissionState state;
56 private ArrayList list;
57 private int _hashcode;
58 private PolicyLevel _policyLevel;
59 private bool _declsec;
60 private bool _readOnly;
64 // for PolicyLevel (to avoid validation duplication)
65 internal PermissionSet ()
67 list = new ArrayList ();
70 public PermissionSet (PermissionState state) : this ()
72 if (!Enum.IsDefined (typeof (PermissionState), state))
73 throw new System.ArgumentException ("state");
77 public PermissionSet (PermissionSet permSet) : this ()
79 // LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
80 //if (!(permSet is PermissionSet))
81 // throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
83 state = PermissionState.Unrestricted;
85 state = permSet.state;
86 foreach (IPermission p in permSet.list)
91 internal PermissionSet (string xml)
94 state = PermissionState.None;
96 SecurityElement se = SecurityElement.FromString (xml);
101 // Light version for creating a (non unrestricted) PermissionSet with
102 // a single permission. This allows to relax most validations.
103 internal PermissionSet (IPermission perm)
107 // note: we do not copy IPermission like AddPermission
114 public virtual IPermission AddPermission (IPermission perm)
116 if ((perm == null) || _readOnly)
119 // we don't add to an unrestricted permission set unless...
120 if (state == PermissionState.Unrestricted) {
121 // we're adding identity permission as they don't support unrestricted
122 if (perm is IUnrestrictedPermission) {
123 // we return the union of the permission with unrestricted
124 // which results in a permission of the same type initialized
125 // with PermissionState.Unrestricted
126 object[] args = new object [1] { PermissionState.Unrestricted };
127 return (IPermission) Activator.CreateInstance (perm.GetType (), args);
131 // we can't add two permissions of the same type in a set
132 // so we remove an existing one, union with it and add it back
133 IPermission existing = RemovePermission (perm.GetType ());
134 if (existing != null) {
135 perm = perm.Union (existing);
138 // note: Add doesn't copy
143 [MonoTODO ("Imperative mode isn't supported")]
144 public virtual void Assert ()
146 new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
148 int count = this.Count;
150 // we (current frame) must have the permission to assert it to others
151 // otherwise we don't assert (but we don't throw an exception)
152 foreach (IPermission p in list) {
153 // note: we ignore non-CAS permissions
154 if (p is IStackWalk) {
155 if (!SecurityManager.IsGranted (p)) {
162 // note: we must ignore the stack modifiers for the non-CAS permissions
163 if (SecurityManager.SecurityEnabled && (count > 0))
164 throw new NotSupportedException ("Currently only declarative Assert are supported.");
167 internal void Clear ()
172 public virtual PermissionSet Copy ()
174 return new PermissionSet (this);
177 public virtual void CopyTo (Array array, int index)
180 throw new ArgumentNullException ("array");
182 if (list.Count > 0) {
183 if (array.Rank > 1) {
184 throw new ArgumentException (Locale.GetText (
185 "Array has more than one dimension"));
187 if (index < 0 || index >= array.Length) {
188 throw new IndexOutOfRangeException ("index");
191 list.CopyTo (array, index);
195 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
196 public virtual void Demand ()
198 // Note: SecurityEnabled only applies to CAS permissions
199 // so we're not checking for it (yet)
203 PermissionSet cas = this;
204 // avoid copy (if possible)
205 if (ContainsNonCodeAccessPermissions ()) {
206 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
208 foreach (IPermission p in list) {
209 Type t = p.GetType ();
210 if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
212 // we wont have to process this one in the stack walk
213 cas.RemovePermission (t);
218 // don't start the stack walk if
219 // - the permission set only contains non CAS permissions; or
220 // - security isn't enabled (applis only to CAS!)
221 if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
222 CasOnlyDemand (_declsec ? 5 : 3);
225 // The number of frames to skip depends on who's calling
226 // - CodeAccessPermission.Demand (imperative)
227 // - PermissionSet.Demand (imperative)
228 // - SecurityManager.InternalDemand (declarative)
229 internal void CasOnlyDemand (int skip)
231 Assembly current = null;
232 AppDomain domain = null;
234 ArrayList frames = SecurityFrame.GetStack (skip);
235 if ((frames != null) && (frames.Count > 0)) {
236 SecurityFrame first = ((SecurityFrame) frames [0]);
237 current = first.Assembly;
238 domain = first.Domain;
239 // skip ourself, Demand and other security runtime methods
240 foreach (SecurityFrame sf in frames) {
241 if (ProcessFrame (sf, ref current, ref domain))
242 return; // reached Assert
244 SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
245 CheckAssembly (current, last);
246 CheckAppDomain (domain, last);
249 // Is there a CompressedStack to handle ?
250 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
251 if ((stack != null) && !stack.IsEmpty ()) {
252 foreach (SecurityFrame frame in stack.List) {
253 if (ProcessFrame (frame, ref current, ref domain))
254 return; // reached Assert
259 [MonoTODO ("Imperative mode isn't supported")]
260 public virtual void Deny ()
262 if (!SecurityManager.SecurityEnabled)
265 foreach (IPermission p in list) {
266 // note: we ignore non-CAS permissions
267 if (p is IStackWalk) {
268 throw new NotSupportedException ("Currently only declarative Deny are supported.");
273 [MonoTODO ("adjust class version with current runtime - unification")]
274 public virtual void FromXml (SecurityElement et)
277 throw new ArgumentNullException ("et");
278 if (et.Tag != tagName) {
279 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
280 throw new ArgumentException (msg, "et");
283 if (CodeAccessPermission.IsUnrestricted (et))
284 state = PermissionState.Unrestricted;
286 state = PermissionState.None;
289 if (et.Children != null) {
290 foreach (SecurityElement se in et.Children) {
291 string className = se.Attribute ("class");
292 if (className == null) {
293 throw new ArgumentException (Locale.GetText (
294 "No permission class is specified."));
296 if (Resolver != null) {
297 // policy class names do not have to be fully qualified
298 className = Resolver.ResolveClassName (className);
300 // TODO: adjust class version with current runtime (unification)
301 // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
302 Type classType = Type.GetType (className);
303 if (classType != null) {
304 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
310 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
311 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
318 public virtual IEnumerator GetEnumerator ()
320 return list.GetEnumerator ();
323 public virtual bool IsSubsetOf (PermissionSet target)
325 // if target is empty we must be empty too
326 if ((target == null) || (target.IsEmpty ()))
327 return this.IsEmpty ();
329 // TODO - non CAS permissions must be evaluated for unrestricted
331 // if target is unrestricted then we are a subset
332 if (!this.IsUnrestricted () && target.IsUnrestricted ())
334 // else target isn't unrestricted.
335 // so if we are unrestricted, the we can't be a subset
336 if (this.IsUnrestricted () && !target.IsUnrestricted ())
339 // if each of our permission is (a) present and (b) a subset of target
340 foreach (IPermission p in list) {
341 // for every type in both list
342 IPermission i = target.GetPermission (p.GetType ());
344 return false; // not present (condition a)
345 if (!p.IsSubsetOf (i))
346 return false; // not a subset (condition b)
351 [MonoTODO ("Imperative mode isn't supported")]
352 public virtual void PermitOnly ()
354 if (!SecurityManager.SecurityEnabled)
357 foreach (IPermission p in list) {
358 // note: we ignore non-CAS permissions
359 if (p is IStackWalk) {
360 throw new NotSupportedException ("Currently only declarative Deny are supported.");
365 public bool ContainsNonCodeAccessPermissions ()
367 foreach (IPermission p in list) {
368 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
374 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
375 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
377 if (inFormat == null)
378 throw new ArgumentNullException ("inFormat");
379 if (outFormat == null)
380 throw new ArgumentNullException ("outFormat");
384 if (inFormat == outFormat)
387 PermissionSet ps = null;
389 if (inFormat == "BINARY") {
390 if (outFormat.StartsWith ("XML")) {
391 using (MemoryStream ms = new MemoryStream (inData)) {
392 BinaryFormatter formatter = new BinaryFormatter ();
393 ps = (PermissionSet) formatter.Deserialize (ms);
396 string xml = ps.ToString ();
400 return Encoding.ASCII.GetBytes (xml);
402 return Encoding.Unicode.GetBytes (xml);
406 else if (inFormat.StartsWith ("XML")) {
407 if (outFormat == "BINARY") {
412 xml = Encoding.ASCII.GetString (inData);
415 xml = Encoding.Unicode.GetString (inData);
419 ps = new PermissionSet (PermissionState.None);
420 ps.FromXml (SecurityElement.FromString (xml));
422 MemoryStream ms = new MemoryStream ();
423 BinaryFormatter formatter = new BinaryFormatter ();
424 formatter.Serialize (ms, ps);
426 return ms.ToArray ();
429 else if (outFormat.StartsWith ("XML")) {
430 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
432 throw new XmlSyntaxException (msg);
434 throw new ArgumentException (msg);
439 // unknown inFormat, returns null
442 // unknown outFormat, throw
443 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
446 public virtual IPermission GetPermission (Type permClass)
448 foreach (object o in list) {
449 if (o.GetType ().Equals (permClass))
450 return (IPermission) o;
452 // it's normal to return null for unrestricted sets
456 public virtual PermissionSet Intersect (PermissionSet other)
458 // no intersection possible
459 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
462 PermissionState state = PermissionState.None;
463 if (this.IsUnrestricted () && other.IsUnrestricted ())
464 state = PermissionState.Unrestricted;
466 PermissionSet interSet = new PermissionSet (state);
467 if (state == PermissionState.Unrestricted) {
468 InternalIntersect (interSet, this, other, true);
469 InternalIntersect (interSet, other, this, true);
471 else if (this.IsUnrestricted ()) {
472 InternalIntersect (interSet, this, other, true);
474 else if (other.IsUnrestricted ()) {
475 InternalIntersect (interSet, other, this, true);
478 InternalIntersect (interSet, this, other, false);
483 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
485 foreach (IPermission p in b.list) {
486 // for every type in both list
487 IPermission i = a.GetPermission (p.GetType ());
489 // add intersection for this type
490 intersect.AddPermission (p.Intersect (i));
492 else if (unrestricted && (p is IUnrestrictedPermission)) {
493 intersect.AddPermission (p);
499 public virtual bool IsEmpty ()
501 // note: Unrestricted isn't empty
502 if (state == PermissionState.Unrestricted)
504 if ((list == null) || (list.Count == 0))
506 // the set may include some empty permissions
507 foreach (IPermission p in list) {
508 // empty == fully restricted == IsSubsetOf(null) == true
509 if (!p.IsSubsetOf (null))
515 public virtual bool IsUnrestricted ()
517 return (state == PermissionState.Unrestricted);
520 public virtual IPermission RemovePermission (Type permClass)
522 if ((permClass == null) || _readOnly)
525 foreach (object o in list) {
526 if (o.GetType ().Equals (permClass)) {
528 return (IPermission) o;
534 public virtual IPermission SetPermission (IPermission perm)
536 if ((perm == null) || _readOnly)
538 if (perm is IUnrestrictedPermission)
539 state = PermissionState.None;
540 RemovePermission (perm.GetType ());
545 public override string ToString ()
547 return ToXml ().ToString ();
550 public virtual SecurityElement ToXml ()
552 SecurityElement se = new SecurityElement (tagName);
553 se.AddAttribute ("class", GetType ().FullName);
554 se.AddAttribute ("version", version.ToString ());
555 if (state == PermissionState.Unrestricted)
556 se.AddAttribute ("Unrestricted", "true");
558 // required for permissions that do not implement IUnrestrictedPermission
559 foreach (IPermission p in list) {
560 se.AddChild (p.ToXml ());
565 public virtual PermissionSet Union (PermissionSet other)
570 PermissionSet copy = this.Copy ();
571 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
572 // so we keep the "right" type
574 copy.state = PermissionState.Unrestricted;
575 // copy all permissions that do not implement IUnrestrictedPermission
576 foreach (IPermission p in this.list) {
577 if (!(p is IUnrestrictedPermission))
578 copy.AddPermission (p);
580 foreach (IPermission p in other.list) {
581 if (!(p is IUnrestrictedPermission))
582 copy.AddPermission (p);
586 // PermissionState.None -> copy all permissions
587 foreach (IPermission p in other.list) {
588 copy.AddPermission (p);
594 public virtual int Count {
595 get { return list.Count; }
598 public virtual bool IsSynchronized {
599 get { return list.IsSynchronized; }
602 public virtual bool IsReadOnly {
603 // always false (as documented) but the PermissionSet can be read-only
604 // e.g. in a PolicyStatement
605 get { return false; }
608 public virtual object SyncRoot {
612 internal bool DeclarativeSecurity {
613 get { return _declsec; }
614 set { _declsec = value; }
618 void IDeserializationCallback.OnDeserialization (object sender)
624 public override bool Equals (object obj)
628 PermissionSet ps = (obj as PermissionSet);
631 if (list.Count != ps.Count)
634 for (int i=0; i < list.Count; i++) {
636 for (int j=0; i < ps.list.Count; j++) {
637 if (list [i].Equals (ps.list [j])) {
649 public override int GetHashCode ()
651 return (list.Count == 0) ? (int) state : base.GetHashCode ();
654 [MonoTODO ("what's it doing here?")]
655 static public void RevertAssert ()
657 // FIXME: There's probably a reason this was added here ?
658 CodeAccessPermission.RevertAssert ();
664 internal PolicyLevel Resolver {
665 get { return _policyLevel; }
666 set { _policyLevel = value; }
669 internal void SetReadOnly (bool value)
674 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
676 if (IsUnrestricted ()) {
677 // we request unrestricted
678 if (frame.Deny != null) {
679 // but have restrictions (some denied permissions)
680 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
681 } else if (frame.PermitOnly != null) {
682 // but have restrictions (only some permitted permissions)
683 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
687 // skip next steps if no Assert, Deny or PermitOnly are present
688 if (frame.HasStackModifiers) {
689 foreach (CodeAccessPermission cap in list) {
690 if (cap.ProcessFrame (frame))
691 return true; // Assert reached - abort stack walk!
695 // however the "final" grant set is resolved by assembly, so
696 // there's no need to check it every time (just when we're
697 // changing assemblies between frames).
698 if (frame.Assembly != current) {
699 CheckAssembly (current, frame);
700 current = frame.Assembly;
703 if (frame.Domain != domain) {
704 CheckAppDomain (domain, frame);
705 domain = frame.Domain;
711 internal void CheckAssembly (Assembly a, SecurityFrame frame)
713 IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
715 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
716 frame, SecurityAction.Demand, p);
720 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
722 IPermission p = SecurityManager.CheckPermissionSet (domain, this);
724 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
725 frame, SecurityAction.Demand, p);
729 // 2.0 metadata format
731 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
733 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
734 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
735 throw new SecurityException (msg);
739 int numattr = ReadEncodedInt (data, ref pos);
740 PermissionSet ps = new PermissionSet (PermissionState.None);
741 for (int i = 0; i < numattr; i++) {
742 IPermission p = ProcessAttribute (data, ref pos);
744 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
745 throw new SecurityException (msg);
747 ps.AddPermission (p);
752 internal static int ReadEncodedInt (byte[] data, ref int position)
755 if ((data [position] & 0x80) == 0) {
756 len = data [position];
758 } else if ((data [position] & 0x40) == 0) {
759 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
762 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
763 (data [position + 2] << 8) | (data [position + 3]));
769 static object[] action = new object [1] { (SecurityAction) 0 };
771 // TODO: add support for arrays and enums
772 internal static IPermission ProcessAttribute (byte[] data, ref int position)
774 int clen = ReadEncodedInt (data, ref position);
775 string cnam = Encoding.UTF8.GetString (data, position, clen);
779 Type secattr = Type.GetType (cnam);
780 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
784 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
785 int numberOfParameters = ReadEncodedInt (data, ref position);
786 for (int j=0; j < numberOfParameters; j++) {
787 bool property = false;
788 switch (data [position++]) {
789 case 0x53: // field (technically possible and working)
792 case 0x54: // property (common case)
800 byte type = data [position++];
803 type = data [position++];
806 int plen = ReadEncodedInt (data, ref position);
807 string pnam = Encoding.UTF8.GetString (data, position, plen);
812 arrayLength = BitConverter.ToInt32 (data, position);
817 object[] arrayIndex = null;
818 for (int i = 0; i < arrayLength; i++) {
820 // TODO - setup index
823 // sadly type values doesn't match ther TypeCode enum :(
825 case 0x02: // MONO_TYPE_BOOLEAN
826 obj = (object) Convert.ToBoolean (data [position++]);
828 case 0x03: // MONO_TYPE_CHAR
829 obj = (object) Convert.ToChar (data [position]);
832 case 0x04: // MONO_TYPE_I1
833 obj = (object) Convert.ToSByte (data [position++]);
835 case 0x05: // MONO_TYPE_U1
836 obj = (object) Convert.ToByte (data [position++]);
838 case 0x06: // MONO_TYPE_I2
839 obj = (object) Convert.ToInt16 (data [position]);
842 case 0x07: // MONO_TYPE_U2
843 obj = (object) Convert.ToUInt16 (data [position]);
846 case 0x08: // MONO_TYPE_I4
847 obj = (object) Convert.ToInt32 (data [position]);
850 case 0x09: // MONO_TYPE_U4
851 obj = (object) Convert.ToUInt32 (data [position]);
854 case 0x0A: // MONO_TYPE_I8
855 obj = (object) Convert.ToInt64 (data [position]);
858 case 0x0B: // MONO_TYPE_U8
859 obj = (object) Convert.ToUInt64 (data [position]);
862 case 0x0C: // MONO_TYPE_R4
863 obj = (object) Convert.ToSingle (data [position]);
866 case 0x0D: // MONO_TYPE_R8
867 obj = (object) Convert.ToDouble (data [position]);
870 case 0x0E: // MONO_TYPE_STRING
872 if (data [position] != 0xFF) {
873 int slen = ReadEncodedInt (data, ref position);
874 s = Encoding.UTF8.GetString (data, position, slen);
881 case 0x50: // special for TYPE
882 int tlen = ReadEncodedInt (data, ref position);
883 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
887 return null; // unsupported
891 PropertyInfo pi = secattr.GetProperty (pnam);
892 pi.SetValue (sa, obj, arrayIndex);
894 FieldInfo fi = secattr.GetField (pnam);
895 fi.SetValue (sa, obj);
899 return sa.CreatePermission ();