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;
63 // for PolicyLevel (to avoid validation duplication)
64 internal PermissionSet ()
66 list = new ArrayList ();
69 public PermissionSet (PermissionState state) : this ()
71 if (!Enum.IsDefined (typeof (PermissionState), state))
72 throw new System.ArgumentException ("state");
76 public PermissionSet (PermissionSet permSet) : this ()
78 // LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
79 //if (!(permSet is PermissionSet))
80 // throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
82 state = PermissionState.Unrestricted;
84 state = permSet.state;
85 foreach (IPermission p in permSet.list)
90 internal PermissionSet (string xml)
93 state = PermissionState.None;
95 SecurityElement se = SecurityElement.FromString (xml);
100 // Light version for creating a (non unrestricted) PermissionSet with
101 // a single permission. This allows to relax most validations.
102 internal PermissionSet (IPermission perm)
106 // note: we do not copy IPermission like AddPermission
113 public virtual IPermission AddPermission (IPermission perm)
118 // we don't add to an unrestricted permission set unless...
119 if (state == PermissionState.Unrestricted) {
120 // we're adding identity permission as they don't support unrestricted
121 if (perm is IUnrestrictedPermission) {
122 // we return the union of the permission with unrestricted
123 // which results in a permission of the same type initialized
124 // with PermissionState.Unrestricted
125 object[] args = new object [1] { PermissionState.Unrestricted };
126 return (IPermission) Activator.CreateInstance (perm.GetType (), args);
130 // we can't add two permissions of the same type in a set
131 // so we remove an existing one, union with it and add it back
132 IPermission existing = RemovePermission (perm.GetType ());
133 if (existing != null) {
134 perm = perm.Union (existing);
137 // note: Add doesn't copy
142 [MonoTODO ("Imperative mode isn't supported")]
143 public virtual void Assert ()
145 new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
147 int count = this.Count;
149 // we (current frame) must have the permission to assert it to others
150 // otherwise we don't assert (but we don't throw an exception)
151 foreach (IPermission p in list) {
152 // note: we ignore non-CAS permissions
153 if (p is IStackWalk) {
154 if (!SecurityManager.IsGranted (p)) {
161 // note: we must ignore the stack modifiers for the non-CAS permissions
162 if (SecurityManager.SecurityEnabled && (count > 0))
163 throw new NotSupportedException ("Currently only declarative Assert are supported.");
166 internal void Clear ()
171 public virtual PermissionSet Copy ()
173 return new PermissionSet (this);
176 public virtual void CopyTo (Array array, int index)
179 throw new ArgumentNullException ("array");
181 if (list.Count > 0) {
182 if (array.Rank > 1) {
183 throw new ArgumentException (Locale.GetText (
184 "Array has more than one dimension"));
186 if (index < 0 || index >= array.Length) {
187 throw new IndexOutOfRangeException ("index");
190 list.CopyTo (array, index);
194 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
195 public virtual void Demand ()
197 // Note: SecurityEnabled only applies to CAS permissions
198 // so we're not checking for it (yet)
202 PermissionSet cas = this;
203 // avoid copy (if possible)
204 if (ContainsNonCodeAccessPermissions ()) {
205 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
207 foreach (IPermission p in list) {
208 Type t = p.GetType ();
209 if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
211 // we wont have to process this one in the stack walk
212 cas.RemovePermission (t);
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 (!cas.IsEmpty () && 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;
232 // skip ourself, Demand and other security runtime methods
233 foreach (SecurityFrame sf in SecurityFrame.GetStack (skip)) {
234 if (ProcessFrame (sf, ref current))
235 return; // reached Assert
238 // Is there a CompressedStack to handle ?
239 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
240 if ((stack != null) && !stack.IsEmpty ()) {
241 foreach (SecurityFrame frame in stack.List) {
242 if (ProcessFrame (frame, ref current))
243 return; // reached Assert
248 [MonoTODO ("Imperative mode isn't supported")]
249 public virtual void Deny ()
251 if (!SecurityManager.SecurityEnabled)
254 foreach (IPermission p in list) {
255 // note: we ignore non-CAS permissions
256 if (p is IStackWalk) {
257 throw new NotSupportedException ("Currently only declarative Deny are supported.");
262 [MonoTODO ("adjust class version with current runtime - unification")]
263 public virtual void FromXml (SecurityElement et)
266 throw new ArgumentNullException ("et");
267 if (et.Tag != tagName) {
268 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
269 throw new ArgumentException (msg, "et");
272 if (CodeAccessPermission.IsUnrestricted (et))
273 state = PermissionState.Unrestricted;
275 state = PermissionState.None;
278 if (et.Children != null) {
279 foreach (SecurityElement se in et.Children) {
280 string className = se.Attribute ("class");
281 if (className == null) {
282 throw new ArgumentException (Locale.GetText (
283 "No permission class is specified."));
285 if (Resolver != null) {
286 // policy class names do not have to be fully qualified
287 className = Resolver.ResolveClassName (className);
289 // TODO: adjust class version with current runtime (unification)
290 // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
291 Type classType = Type.GetType (className);
292 if (classType != null) {
293 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
299 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
300 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
307 public virtual IEnumerator GetEnumerator ()
309 return list.GetEnumerator ();
312 public virtual bool IsSubsetOf (PermissionSet target)
314 // if target is empty we must be empty too
315 if ((target == null) || (target.IsEmpty ()))
316 return this.IsEmpty ();
318 // TODO - non CAS permissions must be evaluated for unrestricted
320 // if target is unrestricted then we are a subset
321 if (!this.IsUnrestricted () && target.IsUnrestricted ())
323 // else target isn't unrestricted.
324 // so if we are unrestricted, the we can't be a subset
325 if (this.IsUnrestricted () && !target.IsUnrestricted ())
328 // if each of our permission is (a) present and (b) a subset of target
329 foreach (IPermission p in list) {
330 // for every type in both list
331 IPermission i = target.GetPermission (p.GetType ());
333 return false; // not present (condition a)
334 if (!p.IsSubsetOf (i))
335 return false; // not a subset (condition b)
340 [MonoTODO ("Imperative mode isn't supported")]
341 public virtual void PermitOnly ()
343 if (!SecurityManager.SecurityEnabled)
346 foreach (IPermission p in list) {
347 // note: we ignore non-CAS permissions
348 if (p is IStackWalk) {
349 throw new NotSupportedException ("Currently only declarative Deny are supported.");
354 public bool ContainsNonCodeAccessPermissions ()
356 foreach (IPermission p in list) {
357 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
363 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
364 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
366 if (inFormat == null)
367 throw new ArgumentNullException ("inFormat");
368 if (outFormat == null)
369 throw new ArgumentNullException ("outFormat");
373 if (inFormat == outFormat)
376 PermissionSet ps = null;
378 if (inFormat == "BINARY") {
379 if (outFormat.StartsWith ("XML")) {
380 using (MemoryStream ms = new MemoryStream (inData)) {
381 BinaryFormatter formatter = new BinaryFormatter ();
382 ps = (PermissionSet) formatter.Deserialize (ms);
385 string xml = ps.ToString ();
389 return Encoding.ASCII.GetBytes (xml);
391 return Encoding.Unicode.GetBytes (xml);
395 else if (inFormat.StartsWith ("XML")) {
396 if (outFormat == "BINARY") {
401 xml = Encoding.ASCII.GetString (inData);
404 xml = Encoding.Unicode.GetString (inData);
408 ps = new PermissionSet (PermissionState.None);
409 ps.FromXml (SecurityElement.FromString (xml));
411 MemoryStream ms = new MemoryStream ();
412 BinaryFormatter formatter = new BinaryFormatter ();
413 formatter.Serialize (ms, ps);
415 return ms.ToArray ();
418 else if (outFormat.StartsWith ("XML")) {
419 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
421 throw new XmlSyntaxException (msg);
423 throw new ArgumentException (msg);
428 // unknown inFormat, returns null
431 // unknown outFormat, throw
432 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
435 public virtual IPermission GetPermission (Type permClass)
437 foreach (object o in list) {
438 if (o.GetType ().Equals (permClass))
439 return (IPermission) o;
441 // it's normal to return null for unrestricted sets
445 public virtual PermissionSet Intersect (PermissionSet other)
447 // no intersection possible
448 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
451 PermissionState state = PermissionState.None;
452 if (this.IsUnrestricted () && other.IsUnrestricted ())
453 state = PermissionState.Unrestricted;
455 PermissionSet interSet = new PermissionSet (state);
456 if (state == PermissionState.Unrestricted) {
457 InternalIntersect (interSet, this, other, true);
458 InternalIntersect (interSet, other, this, true);
460 else if (this.IsUnrestricted ()) {
461 InternalIntersect (interSet, this, other, true);
463 else if (other.IsUnrestricted ()) {
464 InternalIntersect (interSet, other, this, true);
467 InternalIntersect (interSet, this, other, false);
472 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
474 foreach (IPermission p in b.list) {
475 // for every type in both list
476 IPermission i = a.GetPermission (p.GetType ());
478 // add intersection for this type
479 intersect.AddPermission (p.Intersect (i));
481 else if (unrestricted && (p is IUnrestrictedPermission)) {
482 intersect.AddPermission (p);
488 public virtual bool IsEmpty ()
490 // note: Unrestricted isn't empty
491 if (state == PermissionState.Unrestricted)
493 if ((list == null) || (list.Count == 0))
495 // the set may include some empty permissions
496 foreach (IPermission p in list) {
497 // empty == fully restricted == IsSubsetOg(null) == true
498 if (!p.IsSubsetOf (null))
504 public virtual bool IsUnrestricted ()
506 return (state == PermissionState.Unrestricted);
509 public virtual IPermission RemovePermission (Type permClass)
511 if (permClass == null)
514 foreach (object o in list) {
515 if (o.GetType ().Equals (permClass)) {
517 return (IPermission) o;
523 public virtual IPermission SetPermission (IPermission perm)
527 if (perm is IUnrestrictedPermission)
528 state = PermissionState.None;
529 RemovePermission (perm.GetType ());
534 public override string ToString ()
536 return ToXml ().ToString ();
539 public virtual SecurityElement ToXml ()
541 SecurityElement se = new SecurityElement (tagName);
542 se.AddAttribute ("class", GetType ().FullName);
543 se.AddAttribute ("version", version.ToString ());
544 if (state == PermissionState.Unrestricted)
545 se.AddAttribute ("Unrestricted", "true");
547 // required for permissions that do not implement IUnrestrictedPermission
548 foreach (IPermission p in list) {
549 se.AddChild (p.ToXml ());
554 public virtual PermissionSet Union (PermissionSet other)
559 PermissionSet copy = this.Copy ();
560 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
561 // so we keep the "right" type
563 copy.state = PermissionState.Unrestricted;
564 // copy all permissions that do not implement IUnrestrictedPermission
565 foreach (IPermission p in this.list) {
566 if (!(p is IUnrestrictedPermission))
567 copy.AddPermission (p);
569 foreach (IPermission p in other.list) {
570 if (!(p is IUnrestrictedPermission))
571 copy.AddPermission (p);
575 // PermissionState.None -> copy all permissions
576 foreach (IPermission p in other.list) {
577 copy.AddPermission (p);
583 public virtual int Count {
584 get { return list.Count; }
587 public virtual bool IsSynchronized {
588 get { return list.IsSynchronized; }
591 public virtual bool IsReadOnly {
592 get { return false; } // always false
595 public virtual object SyncRoot {
599 internal bool DeclarativeSecurity {
600 get { return _declsec; }
601 set { _declsec = value; }
605 void IDeserializationCallback.OnDeserialization (object sender)
611 public override bool Equals (object obj)
615 PermissionSet ps = (obj as PermissionSet);
618 if (list.Count != ps.Count)
621 for (int i=0; i < list.Count; i++) {
623 for (int j=0; i < ps.list.Count; j++) {
624 if (list [i].Equals (ps.list [j])) {
636 public override int GetHashCode ()
638 return (list.Count == 0) ? (int) state : base.GetHashCode ();
641 [MonoTODO ("what's it doing here?")]
642 static public void RevertAssert ()
644 // FIXME: There's probably a reason this was added here ?
645 CodeAccessPermission.RevertAssert ();
651 internal PolicyLevel Resolver {
652 get { return _policyLevel; }
653 set { _policyLevel = value; }
656 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current)
658 if (IsUnrestricted ()) {
659 // we request unrestricted
660 if (frame.Deny != null) {
661 // but have restrictions (some denied permissions)
662 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame.Assembly,
663 frame.Method, SecurityAction.Demand, null);
664 } else if (frame.PermitOnly != null) {
665 // but have restrictions (only some permitted permissions)
666 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame.Assembly,
667 frame.Method, SecurityAction.Demand, null);
671 foreach (CodeAccessPermission cap in list) {
672 if (cap.ProcessFrame (frame, ref current))
673 return true; // Assert reached - abort stack walk!
678 // 2.0 metadata format
680 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
682 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
683 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
684 throw new SecurityException (msg);
688 int numattr = ReadEncodedInt (data, ref pos);
689 PermissionSet ps = new PermissionSet (PermissionState.None);
690 for (int i = 0; i < numattr; i++) {
691 IPermission p = ProcessAttribute (data, ref pos);
693 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
694 throw new SecurityException (msg);
696 ps.AddPermission (p);
701 internal static int ReadEncodedInt (byte[] data, ref int position)
704 if ((data [position] & 0x80) == 0) {
705 len = data [position];
707 } else if ((data [position] & 0x40) == 0) {
708 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
711 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
712 (data [position + 2] << 8) | (data [position + 3]));
718 static object[] action = new object [1] { (SecurityAction) 0 };
720 // TODO: add support for arrays and enums
721 internal static IPermission ProcessAttribute (byte[] data, ref int position)
723 int clen = ReadEncodedInt (data, ref position);
724 string cnam = Encoding.UTF8.GetString (data, position, clen);
728 Type secattr = Type.GetType (cnam);
729 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
733 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
734 int numberOfParameters = ReadEncodedInt (data, ref position);
735 for (int j=0; j < numberOfParameters; j++) {
736 bool property = false;
737 switch (data [position++]) {
738 case 0x53: // field (technically possible and working)
741 case 0x54: // property (common case)
749 byte type = data [position++];
752 type = data [position++];
755 int plen = ReadEncodedInt (data, ref position);
756 string pnam = Encoding.UTF8.GetString (data, position, plen);
761 arrayLength = BitConverter.ToInt32 (data, position);
766 object[] arrayIndex = null;
767 for (int i = 0; i < arrayLength; i++) {
769 // TODO - setup index
772 // sadly type values doesn't match ther TypeCode enum :(
774 case 0x02: // MONO_TYPE_BOOLEAN
775 obj = (object) Convert.ToBoolean (data [position++]);
777 case 0x03: // MONO_TYPE_CHAR
778 obj = (object) Convert.ToChar (data [position]);
781 case 0x04: // MONO_TYPE_I1
782 obj = (object) Convert.ToSByte (data [position++]);
784 case 0x05: // MONO_TYPE_U1
785 obj = (object) Convert.ToByte (data [position++]);
787 case 0x06: // MONO_TYPE_I2
788 obj = (object) Convert.ToInt16 (data [position]);
791 case 0x07: // MONO_TYPE_U2
792 obj = (object) Convert.ToUInt16 (data [position]);
795 case 0x08: // MONO_TYPE_I4
796 obj = (object) Convert.ToInt32 (data [position]);
799 case 0x09: // MONO_TYPE_U4
800 obj = (object) Convert.ToUInt32 (data [position]);
803 case 0x0A: // MONO_TYPE_I8
804 obj = (object) Convert.ToInt64 (data [position]);
807 case 0x0B: // MONO_TYPE_U8
808 obj = (object) Convert.ToUInt64 (data [position]);
811 case 0x0C: // MONO_TYPE_R4
812 obj = (object) Convert.ToSingle (data [position]);
815 case 0x0D: // MONO_TYPE_R8
816 obj = (object) Convert.ToDouble (data [position]);
819 case 0x0E: // MONO_TYPE_STRING
821 if (data [position] != 0xFF) {
822 int slen = ReadEncodedInt (data, ref position);
823 s = Encoding.UTF8.GetString (data, position, slen);
830 case 0x50: // special for TYPE
831 int tlen = ReadEncodedInt (data, ref position);
832 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
836 return null; // unsupported
840 PropertyInfo pi = secattr.GetProperty (pnam);
841 pi.SetValue (sa, obj, arrayIndex);
843 FieldInfo fi = secattr.GetField (pnam);
844 fi.SetValue (sa, obj);
848 return sa.CreatePermission ();