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 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
49 private static string tagName = "PermissionSet";
50 private const int version = 1;
51 private static object[] psNone = new object [1] { PermissionState.None };
53 private PermissionState state;
54 private ArrayList list;
55 private int _hashcode;
56 private PolicyLevel _policyLevel;
57 private bool _declsec;
61 // for PolicyLevel (to avoid validation duplication)
62 internal PermissionSet ()
64 list = new ArrayList ();
67 public PermissionSet (PermissionState state) : this ()
69 if (!Enum.IsDefined (typeof (PermissionState), state))
70 throw new System.ArgumentException ("state");
74 public PermissionSet (PermissionSet permSet) : this ()
76 // LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
77 //if (!(permSet is PermissionSet))
78 // throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
80 state = PermissionState.Unrestricted;
82 state = permSet.state;
83 foreach (IPermission p in permSet.list)
88 internal PermissionSet (string xml)
91 state = PermissionState.None;
93 SecurityElement se = SecurityElement.FromString (xml);
98 // Light version for creating a (non unrestricted) PermissionSet with
99 // a single permission. This allows to relax most validations.
100 internal PermissionSet (IPermission perm)
104 // note: we do not copy IPermission like AddPermission
111 public virtual IPermission AddPermission (IPermission perm)
116 // we don't add to an unrestricted permission set unless...
117 if (state == PermissionState.Unrestricted) {
118 // we're adding identity permission as they don't support unrestricted
119 if (perm is IUnrestrictedPermission) {
120 // we return the union of the permission with unrestricted
121 // which results in a permission of the same type initialized
122 // with PermissionState.Unrestricted
123 object[] args = new object [1] { PermissionState.Unrestricted };
124 return (IPermission) Activator.CreateInstance (perm.GetType (), args);
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 ("Imperative mode isn't supported")]
141 public virtual void Assert ()
143 new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
145 int count = this.Count;
147 // we (current frame) must have the permission to assert it to others
148 // otherwise we don't assert (but we don't throw an exception)
149 foreach (IPermission p in list) {
150 // note: we ignore non-CAS permissions
151 if (p is IStackWalk) {
152 if (!SecurityManager.IsGranted (p)) {
159 // note: we must ignore the stack modifiers for the non-CAS permissions
160 if (SecurityManager.SecurityEnabled && (count > 0))
161 throw new NotSupportedException ("Currently only declarative Assert are supported.");
164 internal void Clear ()
169 public virtual PermissionSet Copy ()
171 return new PermissionSet (this);
174 public virtual void CopyTo (Array array, int index)
177 throw new ArgumentNullException ("array");
179 if (list.Count > 0) {
180 if (array.Rank > 1) {
181 throw new ArgumentException (Locale.GetText (
182 "Array has more than one dimension"));
184 if (index < 0 || index >= array.Length) {
185 throw new IndexOutOfRangeException ("index");
188 list.CopyTo (array, index);
192 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
193 public virtual void Demand ()
195 // Note: SecurityEnabled only applies to CAS permissions
196 // so we're not checking for it (yet)
200 PermissionSet cas = this;
201 // avoid copy (if possible)
202 if (ContainsNonCodeAccessPermissions ()) {
203 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
205 foreach (IPermission p in list) {
206 Type t = p.GetType ();
207 if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
209 // we wont have to process this one in the stack walk
210 cas.RemovePermission (t);
215 // don't start the stack walk if
216 // - the permission set only contains non CAS permissions; or
217 // - security isn't enabled (applis only to CAS!)
218 if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
219 CasOnlyDemand (_declsec ? 5 : 3);
222 // The number of frames to skip depends on who's calling
223 // - CodeAccessPermission.Demand (imperative)
224 // - PermissionSet.Demand (imperative)
225 // - SecurityManager.InternalDemand (declarative)
226 internal void CasOnlyDemand (int skip)
228 Assembly current = null;
230 // skip ourself, Demand and other security runtime methods
231 foreach (SecurityFrame sf in SecurityFrame.GetStack (skip)) {
232 if (ProcessFrame (sf, ref current))
233 return; // reached Assert
236 // Is there a CompressedStack to handle ?
237 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
238 if ((stack != null) && !stack.IsEmpty ()) {
239 foreach (SecurityFrame frame in stack.List) {
240 if (ProcessFrame (frame, ref current))
241 return; // reached Assert
246 [MonoTODO ("Imperative mode isn't supported")]
247 public virtual void Deny ()
249 if (!SecurityManager.SecurityEnabled)
252 foreach (IPermission p in list) {
253 // note: we ignore non-CAS permissions
254 if (p is IStackWalk) {
255 throw new NotSupportedException ("Currently only declarative Deny are supported.");
260 [MonoTODO ("adjust class version with current runtime - unification")]
261 public virtual void FromXml (SecurityElement et)
264 throw new ArgumentNullException ("et");
265 if (et.Tag != tagName) {
266 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
267 throw new ArgumentException (msg, "et");
270 if (CodeAccessPermission.IsUnrestricted (et))
271 state = PermissionState.Unrestricted;
273 state = PermissionState.None;
276 if (et.Children != null) {
277 foreach (SecurityElement se in et.Children) {
278 string className = se.Attribute ("class");
279 if (className == null) {
280 throw new ArgumentException (Locale.GetText (
281 "No permission class is specified."));
283 if (Resolver != null) {
284 // policy class names do not have to be fully qualified
285 className = Resolver.ResolveClassName (className);
287 // TODO: adjust class version with current runtime (unification)
288 // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
289 Type classType = Type.GetType (className);
290 if (classType != null) {
291 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
297 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
298 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
305 public virtual IEnumerator GetEnumerator ()
307 return list.GetEnumerator ();
310 public virtual bool IsSubsetOf (PermissionSet target)
312 // if target is empty we must be empty too
313 if ((target == null) || (target.IsEmpty ()))
314 return this.IsEmpty ();
316 // TODO - non CAS permissions must be evaluated for unrestricted
318 // if target is unrestricted then we are a subset
319 if (!this.IsUnrestricted () && target.IsUnrestricted ())
321 // else target isn't unrestricted.
322 // so if we are unrestricted, the we can't be a subset
323 if (this.IsUnrestricted () && !target.IsUnrestricted ())
326 // if each of our permission is (a) present and (b) a subset of target
327 foreach (IPermission p in list) {
328 // for every type in both list
329 IPermission i = target.GetPermission (p.GetType ());
331 return false; // not present (condition a)
332 if (!p.IsSubsetOf (i))
333 return false; // not a subset (condition b)
338 [MonoTODO ("Imperative mode isn't supported")]
339 public virtual void PermitOnly ()
341 if (!SecurityManager.SecurityEnabled)
344 foreach (IPermission p in list) {
345 // note: we ignore non-CAS permissions
346 if (p is IStackWalk) {
347 throw new NotSupportedException ("Currently only declarative Deny are supported.");
352 public bool ContainsNonCodeAccessPermissions ()
354 foreach (IPermission p in list) {
355 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
361 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
362 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
364 if (inFormat == null)
365 throw new ArgumentNullException ("inFormat");
366 if (outFormat == null)
367 throw new ArgumentNullException ("outFormat");
371 if (inFormat == outFormat)
374 PermissionSet ps = null;
376 if (inFormat == "BINARY") {
377 if (outFormat.StartsWith ("XML")) {
378 using (MemoryStream ms = new MemoryStream (inData)) {
379 BinaryFormatter formatter = new BinaryFormatter ();
380 ps = (PermissionSet) formatter.Deserialize (ms);
383 string xml = ps.ToString ();
387 return Encoding.ASCII.GetBytes (xml);
389 return Encoding.Unicode.GetBytes (xml);
393 else if (inFormat.StartsWith ("XML")) {
394 if (outFormat == "BINARY") {
399 xml = Encoding.ASCII.GetString (inData);
402 xml = Encoding.Unicode.GetString (inData);
406 ps = new PermissionSet (PermissionState.None);
407 ps.FromXml (SecurityElement.FromString (xml));
409 MemoryStream ms = new MemoryStream ();
410 BinaryFormatter formatter = new BinaryFormatter ();
411 formatter.Serialize (ms, ps);
413 return ms.ToArray ();
416 else if (outFormat.StartsWith ("XML")) {
417 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
419 throw new XmlSyntaxException (msg);
421 throw new ArgumentException (msg);
426 // unknown inFormat, returns null
429 // unknown outFormat, throw
430 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
433 public virtual IPermission GetPermission (Type permClass)
435 foreach (object o in list) {
436 if (o.GetType ().Equals (permClass))
437 return (IPermission) o;
439 // it's normal to return null for unrestricted sets
443 public virtual PermissionSet Intersect (PermissionSet other)
445 // no intersection possible
446 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
449 PermissionState state = PermissionState.None;
450 if (this.IsUnrestricted () && other.IsUnrestricted ())
451 state = PermissionState.Unrestricted;
453 PermissionSet interSet = new PermissionSet (state);
454 if (state == PermissionState.Unrestricted) {
455 InternalIntersect (interSet, this, other, true);
456 InternalIntersect (interSet, other, this, true);
458 else if (this.IsUnrestricted ()) {
459 InternalIntersect (interSet, this, other, true);
461 else if (other.IsUnrestricted ()) {
462 InternalIntersect (interSet, other, this, true);
465 InternalIntersect (interSet, this, other, false);
470 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
472 foreach (IPermission p in b.list) {
473 // for every type in both list
474 IPermission i = a.GetPermission (p.GetType ());
476 // add intersection for this type
477 intersect.AddPermission (p.Intersect (i));
479 else if (unrestricted && (p is IUnrestrictedPermission)) {
480 intersect.AddPermission (p);
486 public virtual bool IsEmpty ()
488 // note: Unrestricted isn't empty
489 if (state == PermissionState.Unrestricted)
491 if ((list == null) || (list.Count == 0))
493 // the set may include some empty permissions
494 foreach (IPermission p in list) {
495 // empty == fully restricted == IsSubsetOg(null) == true
496 if (!p.IsSubsetOf (null))
502 public virtual bool IsUnrestricted ()
504 return (state == PermissionState.Unrestricted);
507 public virtual IPermission RemovePermission (Type permClass)
509 if (permClass == null)
512 foreach (object o in list) {
513 if (o.GetType ().Equals (permClass)) {
515 return (IPermission) o;
521 public virtual IPermission SetPermission (IPermission perm)
525 if (perm is IUnrestrictedPermission)
526 state = PermissionState.None;
527 RemovePermission (perm.GetType ());
532 public override string ToString ()
534 return ToXml ().ToString ();
537 public virtual SecurityElement ToXml ()
539 SecurityElement se = new SecurityElement (tagName);
540 se.AddAttribute ("class", GetType ().FullName);
541 se.AddAttribute ("version", version.ToString ());
542 if (state == PermissionState.Unrestricted)
543 se.AddAttribute ("Unrestricted", "true");
545 // required for permissions that do not implement IUnrestrictedPermission
546 foreach (IPermission p in list) {
547 se.AddChild (p.ToXml ());
552 public virtual PermissionSet Union (PermissionSet other)
557 PermissionSet copy = this.Copy ();
558 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
559 // so we keep the "right" type
561 copy.state = PermissionState.Unrestricted;
562 // copy all permissions that do not implement IUnrestrictedPermission
563 foreach (IPermission p in this.list) {
564 if (!(p is IUnrestrictedPermission))
565 copy.AddPermission (p);
567 foreach (IPermission p in other.list) {
568 if (!(p is IUnrestrictedPermission))
569 copy.AddPermission (p);
573 // PermissionState.None -> copy all permissions
574 foreach (IPermission p in other.list) {
575 copy.AddPermission (p);
581 public virtual int Count {
582 get { return list.Count; }
585 public virtual bool IsSynchronized {
586 get { return list.IsSynchronized; }
589 public virtual bool IsReadOnly {
590 get { return false; } // always false
593 public virtual object SyncRoot {
597 internal bool DeclarativeSecurity {
598 get { return _declsec; }
599 set { _declsec = value; }
603 void IDeserializationCallback.OnDeserialization (object sender)
609 public override bool Equals (object obj)
613 PermissionSet ps = (obj as PermissionSet);
616 if (list.Count != ps.Count)
619 for (int i=0; i < list.Count; i++) {
621 for (int j=0; i < ps.list.Count; j++) {
622 if (list [i].Equals (ps.list [j])) {
634 public override int GetHashCode ()
636 return (list.Count == 0) ? (int) state : base.GetHashCode ();
639 [MonoTODO ("what's it doing here?")]
640 static public void RevertAssert ()
642 // FIXME: There's probably a reason this was added here ?
643 CodeAccessPermission.RevertAssert ();
649 internal PolicyLevel Resolver {
650 get { return _policyLevel; }
651 set { _policyLevel = value; }
654 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current)
656 if (IsUnrestricted ()) {
657 // we request unrestricted
658 if (frame.Deny != null) {
659 // but have restrictions (some denied permissions)
660 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame.Assembly,
661 frame.Method, SecurityAction.Demand, null);
662 } else if (frame.PermitOnly != null) {
663 // but have restrictions (onyl some permitted permissions)
664 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame.Assembly,
665 frame.Method, SecurityAction.Demand, null);
669 foreach (CodeAccessPermission cap in list) {
670 if (cap.ProcessFrame (frame, ref current))
671 return true; // Assert reached - abort stack walk!
676 // 2.0 metadata format
678 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
680 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
681 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
682 throw new SecurityException (msg);
686 int numattr = ReadEncodedInt (data, ref pos);
687 PermissionSet ps = new PermissionSet (PermissionState.None);
688 for (int i = 0; i < numattr; i++) {
689 IPermission p = ProcessAttribute (data, ref pos);
691 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
692 throw new SecurityException (msg);
694 ps.AddPermission (p);
699 internal static int ReadEncodedInt (byte[] data, ref int position)
702 if ((data [position] & 0x80) == 0) {
703 len = data [position];
705 } else if ((data [position] & 0x40) == 0) {
706 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
709 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
710 (data [position + 2] << 8) | (data [position + 3]));
716 static object[] action = new object [1] { (SecurityAction) 0 };
718 // TODO: add support for arrays and enums
719 internal static IPermission ProcessAttribute (byte[] data, ref int position)
721 int clen = ReadEncodedInt (data, ref position);
722 string cnam = Encoding.UTF8.GetString (data, position, clen);
726 Type secattr = Type.GetType (cnam);
727 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
731 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
732 int numberOfParameters = ReadEncodedInt (data, ref position);
733 for (int j=0; j < numberOfParameters; j++) {
734 bool property = false;
735 switch (data [position++]) {
736 case 0x53: // field (technically possible and working)
739 case 0x54: // property (common case)
747 byte type = data [position++];
750 type = data [position++];
753 int plen = ReadEncodedInt (data, ref position);
754 string pnam = Encoding.UTF8.GetString (data, position, plen);
759 arrayLength = BitConverter.ToInt32 (data, position);
764 object[] arrayIndex = null;
765 for (int i = 0; i < arrayLength; i++) {
767 // TODO - setup index
770 // sadly type values doesn't match ther TypeCode enum :(
772 case 0x02: // MONO_TYPE_BOOLEAN
773 obj = (object) Convert.ToBoolean (data [position++]);
775 case 0x03: // MONO_TYPE_CHAR
776 obj = (object) Convert.ToChar (data [position]);
779 case 0x04: // MONO_TYPE_I1
780 obj = (object) Convert.ToSByte (data [position++]);
782 case 0x05: // MONO_TYPE_U1
783 obj = (object) Convert.ToByte (data [position++]);
785 case 0x06: // MONO_TYPE_I2
786 obj = (object) Convert.ToInt16 (data [position]);
789 case 0x07: // MONO_TYPE_U2
790 obj = (object) Convert.ToUInt16 (data [position]);
793 case 0x08: // MONO_TYPE_I4
794 obj = (object) Convert.ToInt32 (data [position]);
797 case 0x09: // MONO_TYPE_U4
798 obj = (object) Convert.ToUInt32 (data [position]);
801 case 0x0A: // MONO_TYPE_I8
802 obj = (object) Convert.ToInt64 (data [position]);
805 case 0x0B: // MONO_TYPE_U8
806 obj = (object) Convert.ToUInt64 (data [position]);
809 case 0x0C: // MONO_TYPE_R4
810 obj = (object) Convert.ToSingle (data [position]);
813 case 0x0D: // MONO_TYPE_R8
814 obj = (object) Convert.ToDouble (data [position]);
817 case 0x0E: // MONO_TYPE_STRING
819 if (data [position] != 0xFF) {
820 int slen = ReadEncodedInt (data, ref position);
821 s = Encoding.UTF8.GetString (data, position, slen);
828 case 0x50: // special for TYPE
829 int tlen = ReadEncodedInt (data, ref position);
830 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
834 return null; // unsupported
838 PropertyInfo pi = secattr.GetProperty (pnam);
839 pi.SetValue (sa, obj, arrayIndex);
841 FieldInfo fi = secattr.GetField (pnam);
842 fi.SetValue (sa, obj);
846 return sa.CreatePermission ();