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")]
50 [MonoTODO ("CAS support is experimental (and unsupported).")]
51 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
53 private const string tagName = "PermissionSet";
54 private const int version = 1;
55 private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
57 private PermissionState state;
58 private ArrayList list;
59 private PolicyLevel _policyLevel;
60 private bool _declsec;
61 private bool _readOnly;
62 private bool[] _ignored; // for asserts and non-CAS permissions
66 // for PolicyLevel (to avoid validation duplication)
67 internal PermissionSet ()
69 list = new ArrayList ();
72 public PermissionSet (PermissionState state) : this ()
74 this.state = CodeAccessPermission.CheckPermissionState (state, true);
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.
82 if (permSet != null) {
83 state = permSet.state;
84 foreach (IPermission p in permSet.list)
89 internal PermissionSet (string xml)
92 state = PermissionState.None;
94 SecurityElement se = SecurityElement.FromString (xml);
99 // Light version for creating a (non unrestricted) PermissionSet with
100 // a single permission. This allows to relax most validations.
101 internal PermissionSet (IPermission perm)
105 // note: we do not copy IPermission like AddPermission
112 public IPermission AddPermission (IPermission perm)
114 if ((perm == null) || _readOnly)
117 // we don't add to an unrestricted permission set unless...
118 if (state == PermissionState.Unrestricted) {
119 // identity permissions can be unrestricted under 2.x
121 // we return the union of the permission with unrestricted
122 // which results in a permission of the same type initialized
123 // with PermissionState.Unrestricted
124 return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
128 // we can't add two permissions of the same type in a set
129 // so we remove an existing one, union with it and add it back
130 IPermission existing = RemovePermission (perm.GetType ());
131 if (existing != null) {
132 perm = perm.Union (existing);
135 // note: Add doesn't copy
140 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
141 [SecurityPermission (SecurityAction.Demand, Assertion = true)]
142 public void Assert ()
144 int count = this.Count;
146 // we (current frame) must have the permission to assert it to others
147 // otherwise we don't assert (but we don't throw an exception)
148 foreach (IPermission p in list) {
149 // note: we ignore non-CAS permissions
150 if (p is IStackWalk) {
151 if (!SecurityManager.IsGranted (p)) {
158 // note: we must ignore the stack modifiers for the non-CAS permissions
159 if (SecurityManager.SecurityEnabled && (count > 0))
160 throw new NotSupportedException ("Currently only declarative Assert are supported.");
163 internal void Clear ()
168 public virtual PermissionSet Copy ()
170 return new PermissionSet (this);
173 public virtual void CopyTo (Array array, int index)
176 throw new ArgumentNullException ("array");
178 if (list.Count > 0) {
179 if (array.Rank > 1) {
180 throw new ArgumentException (Locale.GetText (
181 "Array has more than one dimension"));
183 if (index < 0 || index >= array.Length) {
184 throw new IndexOutOfRangeException ("index");
187 list.CopyTo (array, index);
191 public void Demand ()
193 // Note: SecurityEnabled only applies to CAS permissions
194 // so we're not checking for it (yet)
199 if ((_ignored == null) || (_ignored.Length != n)) {
200 _ignored = new bool [n];
203 bool call_cas_only = this.IsUnrestricted ();
204 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
205 for (int i = 0; i < n; i++) {
206 IPermission p = (IPermission) list [i];
207 Type t = p.GetType ();
208 if (t.IsSubclassOf (typeof (CodeAccessPermission))) {
209 _ignored [i] = false;
210 call_cas_only = true;
217 // don't start the stack walk if
218 // - the permission set only contains non CAS permissions; or
219 // - security isn't enabled (applis only to CAS!)
220 if (call_cas_only && SecurityManager.SecurityEnabled)
221 CasOnlyDemand (_declsec ? 5 : 3);
224 // The number of frames to skip depends on who's calling
225 // - CodeAccessPermission.Demand (imperative)
226 // - PermissionSet.Demand (imperative)
227 // - SecurityManager.InternalDemand (declarative)
228 internal void CasOnlyDemand (int skip)
230 Assembly current = null;
231 AppDomain domain = null;
233 if (_ignored == null) {
234 // special case when directly called from CodeAccessPermission.Demand
235 _ignored = new bool [list.Count];
239 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
242 if (!SecurityManager.SecurityEnabled)
245 foreach (IPermission p in list) {
246 // note: we ignore non-CAS permissions
247 if (p is IStackWalk) {
248 throw new NotSupportedException ("Currently only declarative Deny are supported.");
253 public virtual void FromXml (SecurityElement et)
256 throw new ArgumentNullException ("et");
257 if (et.Tag != tagName) {
258 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
259 throw new ArgumentException (msg, "et");
264 if (CodeAccessPermission.IsUnrestricted (et)) {
265 state = PermissionState.Unrestricted;
266 // no need to continue for an unrestricted permission
267 // because identity permissions now "supports" unrestricted
270 state = PermissionState.None;
273 if (et.Children != null) {
274 foreach (SecurityElement se in et.Children) {
275 string className = se.Attribute ("class");
276 if (className == null) {
277 throw new ArgumentException (Locale.GetText (
278 "No permission class is specified."));
280 if (Resolver != null) {
281 // policy class names do not have to be fully qualified
282 className = Resolver.ResolveClassName (className);
285 list.Add (PermissionBuilder.Create (className, se));
290 public IEnumerator GetEnumerator ()
292 return list.GetEnumerator ();
295 public bool IsSubsetOf (PermissionSet target)
297 // if target is empty we must be empty too
298 if ((target == null) || (target.IsEmpty ()))
299 return this.IsEmpty ();
301 // all permissions support unrestricted in 2.0
302 if (target.IsUnrestricted ())
304 if (this.IsUnrestricted ())
307 if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
310 // if each of our permission is (a) present and (b) a subset of target
311 foreach (IPermission p in list) {
312 // non CAS permissions must be evaluated for unrestricted
313 Type t = p.GetType ();
314 IPermission i = null;
315 if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
316 i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
318 i = target.GetPermission (t);
321 if (!p.IsSubsetOf (i))
322 return false; // not a subset (condition b)
327 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
328 public void PermitOnly ()
330 if (!SecurityManager.SecurityEnabled)
333 foreach (IPermission p in list) {
334 // note: we ignore non-CAS permissions
335 if (p is IStackWalk) {
336 throw new NotSupportedException ("Currently only declarative Deny are supported.");
341 public bool ContainsNonCodeAccessPermissions ()
343 if (list.Count > 0) {
344 foreach (IPermission p in list) {
345 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
352 // FIXME little documentation in Fx 2.0 beta 1
353 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
355 if (inFormat == null)
356 throw new ArgumentNullException ("inFormat");
357 if (outFormat == null)
358 throw new ArgumentNullException ("outFormat");
362 if (inFormat == outFormat)
365 PermissionSet ps = null;
367 if (inFormat == "BINARY") {
368 if (outFormat.StartsWith ("XML")) {
369 using (MemoryStream ms = new MemoryStream (inData)) {
370 BinaryFormatter formatter = new BinaryFormatter ();
371 ps = (PermissionSet) formatter.Deserialize (ms);
374 string xml = ps.ToString ();
378 return Encoding.ASCII.GetBytes (xml);
380 return Encoding.Unicode.GetBytes (xml);
384 else if (inFormat.StartsWith ("XML")) {
385 if (outFormat == "BINARY") {
390 xml = Encoding.ASCII.GetString (inData);
393 xml = Encoding.Unicode.GetString (inData);
397 ps = new PermissionSet (PermissionState.None);
398 ps.FromXml (SecurityElement.FromString (xml));
400 MemoryStream ms = new MemoryStream ();
401 BinaryFormatter formatter = new BinaryFormatter ();
402 formatter.Serialize (ms, ps);
404 return ms.ToArray ();
407 else if (outFormat.StartsWith ("XML")) {
408 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
409 throw new XmlSyntaxException (msg);
413 // unknown inFormat, returns null
416 // unknown outFormat, throw
417 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
420 public IPermission GetPermission (Type permClass)
422 if ((permClass == null) || (list.Count == 0))
425 foreach (object o in list) {
426 if ((o != null) && o.GetType ().Equals (permClass))
427 return (IPermission) o;
429 // it's normal to return null for unrestricted sets
433 public PermissionSet Intersect (PermissionSet other)
435 // no intersection possible
436 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
439 PermissionState state = PermissionState.None;
440 if (this.IsUnrestricted () && other.IsUnrestricted ())
441 state = PermissionState.Unrestricted;
443 PermissionSet interSet = null;
444 // much simpler with 2.0
445 if (state == PermissionState.Unrestricted) {
446 interSet = new PermissionSet (state);
447 } else if (this.IsUnrestricted ()) {
448 interSet = other.Copy ();
449 } else if (other.IsUnrestricted ()) {
450 interSet = this.Copy ();
452 interSet = new PermissionSet (state);
453 InternalIntersect (interSet, this, other, false);
458 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
460 foreach (IPermission p in b.list) {
461 // for every type in both list
462 IPermission i = a.GetPermission (p.GetType ());
464 // add intersection for this type
465 intersect.AddPermission (p.Intersect (i));
467 // unrestricted is possible for indentity permissions
468 else if (unrestricted) {
469 intersect.AddPermission (p);
475 public bool IsEmpty ()
477 // note: Unrestricted isn't empty
478 if (state == PermissionState.Unrestricted)
480 if ((list == null) || (list.Count == 0))
482 // the set may include some empty permissions
483 foreach (IPermission p in list) {
484 // empty == fully restricted == IsSubsetOf(null) == true
485 if (!p.IsSubsetOf (null))
491 public bool IsUnrestricted ()
493 return (state == PermissionState.Unrestricted);
496 public IPermission RemovePermission (Type permClass)
498 if ((permClass == null) || _readOnly)
501 foreach (object o in list) {
502 if (o.GetType ().Equals (permClass)) {
504 return (IPermission) o;
510 public IPermission SetPermission (IPermission perm)
512 if ((perm == null) || _readOnly)
514 IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
516 state = PermissionState.None;
518 state = u.IsUnrestricted () ? state : PermissionState.None;
520 RemovePermission (perm.GetType ());
525 public override string ToString ()
527 return ToXml ().ToString ();
530 public virtual SecurityElement ToXml ()
532 SecurityElement se = new SecurityElement (tagName);
533 se.AddAttribute ("class", GetType ().FullName);
534 se.AddAttribute ("version", version.ToString ());
535 if (state == PermissionState.Unrestricted)
536 se.AddAttribute ("Unrestricted", "true");
538 // required for permissions that do not implement IUnrestrictedPermission
539 foreach (IPermission p in list) {
540 se.AddChild (p.ToXml ());
545 public PermissionSet Union (PermissionSet other)
550 PermissionSet copy = null;
551 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
552 // there are no child elements in unrestricted permission sets
553 return new PermissionSet (PermissionState.Unrestricted);
556 // PermissionState.None -> copy all permissions
557 foreach (IPermission p in other.list) {
558 copy.AddPermission (p);
564 public virtual int Count {
565 get { return list.Count; }
568 public virtual bool IsSynchronized {
569 get { return list.IsSynchronized; }
572 public virtual bool IsReadOnly {
573 // always false (as documented) but the PermissionSet can be read-only
574 // e.g. in a PolicyStatement
575 get { return false; }
578 public virtual object SyncRoot {
582 internal bool DeclarativeSecurity {
583 get { return _declsec; }
584 set { _declsec = value; }
587 [MonoTODO ("may not be required")]
588 void IDeserializationCallback.OnDeserialization (object sender)
593 public override bool Equals (object obj)
597 PermissionSet ps = (obj as PermissionSet);
600 if (state != ps.state)
602 if (list.Count != ps.Count)
605 for (int i=0; i < list.Count; i++) {
607 for (int j=0; i < ps.list.Count; j++) {
608 if (list [i].Equals (ps.list [j])) {
620 public override int GetHashCode ()
622 return (list.Count == 0) ? (int) state : base.GetHashCode ();
625 // FIXME what's it doing here? There's probably a reason this was added here.
626 static public void RevertAssert ()
628 CodeAccessPermission.RevertAssert ();
633 internal PolicyLevel Resolver {
634 get { return _policyLevel; }
635 set { _policyLevel = value; }
638 internal void SetReadOnly (bool value)
643 private bool AllIgnored ()
645 if (_ignored == null)
646 throw new NotSupportedException ("bad bad bad");
648 for (int i=0; i < _ignored.Length; i++) {
652 // everything is ignored (i.e. non-CAS permission or asserted permission).
656 // 2.0 metadata format
658 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
660 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
661 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
662 throw new SecurityException (msg);
666 int numattr = ReadEncodedInt (data, ref pos);
667 PermissionSet ps = new PermissionSet (PermissionState.None);
668 for (int i = 0; i < numattr; i++) {
669 IPermission p = ProcessAttribute (data, ref pos);
671 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
672 throw new SecurityException (msg);
674 ps.AddPermission (p);
679 internal static int ReadEncodedInt (byte[] data, ref int position)
682 if ((data [position] & 0x80) == 0) {
683 len = data [position];
685 } else if ((data [position] & 0x40) == 0) {
686 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
689 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
690 (data [position + 2] << 8) | (data [position + 3]));
696 static object[] action = new object [1] { (SecurityAction) 0 };
698 // TODO: add support for arrays and enums (2.0)
699 internal static IPermission ProcessAttribute (byte[] data, ref int position)
701 int clen = ReadEncodedInt (data, ref position);
702 string cnam = Encoding.UTF8.GetString (data, position, clen);
705 Type secattr = Type.GetType (cnam);
706 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
710 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
711 int numberOfParameters = ReadEncodedInt (data, ref position);
712 for (int j=0; j < numberOfParameters; j++) {
713 bool property = false;
714 switch (data [position++]) {
715 case 0x53: // field (technically possible and working)
718 case 0x54: // property (common case)
726 byte type = data [position++];
729 type = data [position++];
732 int plen = ReadEncodedInt (data, ref position);
733 string pnam = Encoding.UTF8.GetString (data, position, plen);
738 arrayLength = BitConverter.ToInt32 (data, position);
743 object[] arrayIndex = null;
744 for (int i = 0; i < arrayLength; i++) {
746 // TODO - setup index (2.0)
749 // sadly type values doesn't match ther TypeCode enum :(
751 case 0x02: // MONO_TYPE_BOOLEAN
752 obj = (object) Convert.ToBoolean (data [position++]);
754 case 0x03: // MONO_TYPE_CHAR
755 obj = (object) Convert.ToChar (data [position]);
758 case 0x04: // MONO_TYPE_I1
759 obj = (object) Convert.ToSByte (data [position++]);
761 case 0x05: // MONO_TYPE_U1
762 obj = (object) Convert.ToByte (data [position++]);
764 case 0x06: // MONO_TYPE_I2
765 obj = (object) Convert.ToInt16 (data [position]);
768 case 0x07: // MONO_TYPE_U2
769 obj = (object) Convert.ToUInt16 (data [position]);
772 case 0x08: // MONO_TYPE_I4
773 obj = (object) Convert.ToInt32 (data [position]);
776 case 0x09: // MONO_TYPE_U4
777 obj = (object) Convert.ToUInt32 (data [position]);
780 case 0x0A: // MONO_TYPE_I8
781 obj = (object) Convert.ToInt64 (data [position]);
784 case 0x0B: // MONO_TYPE_U8
785 obj = (object) Convert.ToUInt64 (data [position]);
788 case 0x0C: // MONO_TYPE_R4
789 obj = (object) Convert.ToSingle (data [position]);
792 case 0x0D: // MONO_TYPE_R8
793 obj = (object) Convert.ToDouble (data [position]);
796 case 0x0E: // MONO_TYPE_STRING
798 if (data [position] != 0xFF) {
799 int slen = ReadEncodedInt (data, ref position);
800 s = Encoding.UTF8.GetString (data, position, slen);
807 case 0x50: // special for TYPE
808 int tlen = ReadEncodedInt (data, ref position);
809 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
813 return null; // unsupported
817 PropertyInfo pi = secattr.GetProperty (pnam);
818 pi.SetValue (sa, obj, arrayIndex);
820 FieldInfo fi = secattr.GetField (pnam);
821 fi.SetValue (sa, obj);
825 return sa.CreatePermission ();