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;
231 AppDomain domain = null;
233 ArrayList frames = SecurityFrame.GetStack (skip);
234 if ((frames != null) && (frames.Count > 0)) {
235 SecurityFrame first = ((SecurityFrame) frames [0]);
236 current = first.Assembly;
237 domain = first.Domain;
238 // skip ourself, Demand and other security runtime methods
239 foreach (SecurityFrame sf in frames) {
240 if (ProcessFrame (sf, ref current, ref domain))
241 return; // reached Assert
243 SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
244 CheckAssembly (current, last);
245 CheckAppDomain (domain, last);
248 // Is there a CompressedStack to handle ?
249 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
250 if ((stack != null) && !stack.IsEmpty ()) {
251 foreach (SecurityFrame frame in stack.List) {
252 if (ProcessFrame (frame, ref current, ref domain))
253 return; // reached Assert
258 [MonoTODO ("Imperative mode isn't supported")]
259 public virtual void Deny ()
261 if (!SecurityManager.SecurityEnabled)
264 foreach (IPermission p in list) {
265 // note: we ignore non-CAS permissions
266 if (p is IStackWalk) {
267 throw new NotSupportedException ("Currently only declarative Deny are supported.");
272 [MonoTODO ("adjust class version with current runtime - unification")]
273 public virtual void FromXml (SecurityElement et)
276 throw new ArgumentNullException ("et");
277 if (et.Tag != tagName) {
278 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
279 throw new ArgumentException (msg, "et");
282 if (CodeAccessPermission.IsUnrestricted (et))
283 state = PermissionState.Unrestricted;
285 state = PermissionState.None;
288 if (et.Children != null) {
289 foreach (SecurityElement se in et.Children) {
290 string className = se.Attribute ("class");
291 if (className == null) {
292 throw new ArgumentException (Locale.GetText (
293 "No permission class is specified."));
295 if (Resolver != null) {
296 // policy class names do not have to be fully qualified
297 className = Resolver.ResolveClassName (className);
299 // TODO: adjust class version with current runtime (unification)
300 // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
301 Type classType = Type.GetType (className);
302 if (classType != null) {
303 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
309 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
310 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
317 public virtual IEnumerator GetEnumerator ()
319 return list.GetEnumerator ();
322 public virtual bool IsSubsetOf (PermissionSet target)
324 // if target is empty we must be empty too
325 if ((target == null) || (target.IsEmpty ()))
326 return this.IsEmpty ();
328 // TODO - non CAS permissions must be evaluated for unrestricted
330 // if target is unrestricted then we are a subset
331 if (!this.IsUnrestricted () && target.IsUnrestricted ())
333 // else target isn't unrestricted.
334 // so if we are unrestricted, the we can't be a subset
335 if (this.IsUnrestricted () && !target.IsUnrestricted ())
338 // if each of our permission is (a) present and (b) a subset of target
339 foreach (IPermission p in list) {
340 // for every type in both list
341 IPermission i = target.GetPermission (p.GetType ());
343 return false; // not present (condition a)
344 if (!p.IsSubsetOf (i))
345 return false; // not a subset (condition b)
350 [MonoTODO ("Imperative mode isn't supported")]
351 public virtual void PermitOnly ()
353 if (!SecurityManager.SecurityEnabled)
356 foreach (IPermission p in list) {
357 // note: we ignore non-CAS permissions
358 if (p is IStackWalk) {
359 throw new NotSupportedException ("Currently only declarative Deny are supported.");
364 public bool ContainsNonCodeAccessPermissions ()
366 foreach (IPermission p in list) {
367 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
373 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
374 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
376 if (inFormat == null)
377 throw new ArgumentNullException ("inFormat");
378 if (outFormat == null)
379 throw new ArgumentNullException ("outFormat");
383 if (inFormat == outFormat)
386 PermissionSet ps = null;
388 if (inFormat == "BINARY") {
389 if (outFormat.StartsWith ("XML")) {
390 using (MemoryStream ms = new MemoryStream (inData)) {
391 BinaryFormatter formatter = new BinaryFormatter ();
392 ps = (PermissionSet) formatter.Deserialize (ms);
395 string xml = ps.ToString ();
399 return Encoding.ASCII.GetBytes (xml);
401 return Encoding.Unicode.GetBytes (xml);
405 else if (inFormat.StartsWith ("XML")) {
406 if (outFormat == "BINARY") {
411 xml = Encoding.ASCII.GetString (inData);
414 xml = Encoding.Unicode.GetString (inData);
418 ps = new PermissionSet (PermissionState.None);
419 ps.FromXml (SecurityElement.FromString (xml));
421 MemoryStream ms = new MemoryStream ();
422 BinaryFormatter formatter = new BinaryFormatter ();
423 formatter.Serialize (ms, ps);
425 return ms.ToArray ();
428 else if (outFormat.StartsWith ("XML")) {
429 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
431 throw new XmlSyntaxException (msg);
433 throw new ArgumentException (msg);
438 // unknown inFormat, returns null
441 // unknown outFormat, throw
442 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
445 public virtual IPermission GetPermission (Type permClass)
447 foreach (object o in list) {
448 if (o.GetType ().Equals (permClass))
449 return (IPermission) o;
451 // it's normal to return null for unrestricted sets
455 public virtual PermissionSet Intersect (PermissionSet other)
457 // no intersection possible
458 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
461 PermissionState state = PermissionState.None;
462 if (this.IsUnrestricted () && other.IsUnrestricted ())
463 state = PermissionState.Unrestricted;
465 PermissionSet interSet = new PermissionSet (state);
466 if (state == PermissionState.Unrestricted) {
467 InternalIntersect (interSet, this, other, true);
468 InternalIntersect (interSet, other, this, true);
470 else if (this.IsUnrestricted ()) {
471 InternalIntersect (interSet, this, other, true);
473 else if (other.IsUnrestricted ()) {
474 InternalIntersect (interSet, other, this, true);
477 InternalIntersect (interSet, this, other, false);
482 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
484 foreach (IPermission p in b.list) {
485 // for every type in both list
486 IPermission i = a.GetPermission (p.GetType ());
488 // add intersection for this type
489 intersect.AddPermission (p.Intersect (i));
491 else if (unrestricted && (p is IUnrestrictedPermission)) {
492 intersect.AddPermission (p);
498 public virtual bool IsEmpty ()
500 // note: Unrestricted isn't empty
501 if (state == PermissionState.Unrestricted)
503 if ((list == null) || (list.Count == 0))
505 // the set may include some empty permissions
506 foreach (IPermission p in list) {
507 // empty == fully restricted == IsSubsetOg(null) == true
508 if (!p.IsSubsetOf (null))
514 public virtual bool IsUnrestricted ()
516 return (state == PermissionState.Unrestricted);
519 public virtual IPermission RemovePermission (Type permClass)
521 if (permClass == null)
524 foreach (object o in list) {
525 if (o.GetType ().Equals (permClass)) {
527 return (IPermission) o;
533 public virtual IPermission SetPermission (IPermission perm)
537 if (perm is IUnrestrictedPermission)
538 state = PermissionState.None;
539 RemovePermission (perm.GetType ());
544 public override string ToString ()
546 return ToXml ().ToString ();
549 public virtual SecurityElement ToXml ()
551 SecurityElement se = new SecurityElement (tagName);
552 se.AddAttribute ("class", GetType ().FullName);
553 se.AddAttribute ("version", version.ToString ());
554 if (state == PermissionState.Unrestricted)
555 se.AddAttribute ("Unrestricted", "true");
557 // required for permissions that do not implement IUnrestrictedPermission
558 foreach (IPermission p in list) {
559 se.AddChild (p.ToXml ());
564 public virtual PermissionSet Union (PermissionSet other)
569 PermissionSet copy = this.Copy ();
570 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
571 // so we keep the "right" type
573 copy.state = PermissionState.Unrestricted;
574 // copy all permissions that do not implement IUnrestrictedPermission
575 foreach (IPermission p in this.list) {
576 if (!(p is IUnrestrictedPermission))
577 copy.AddPermission (p);
579 foreach (IPermission p in other.list) {
580 if (!(p is IUnrestrictedPermission))
581 copy.AddPermission (p);
585 // PermissionState.None -> copy all permissions
586 foreach (IPermission p in other.list) {
587 copy.AddPermission (p);
593 public virtual int Count {
594 get { return list.Count; }
597 public virtual bool IsSynchronized {
598 get { return list.IsSynchronized; }
601 public virtual bool IsReadOnly {
602 get { return false; } // always false
605 public virtual object SyncRoot {
609 internal bool DeclarativeSecurity {
610 get { return _declsec; }
611 set { _declsec = value; }
615 void IDeserializationCallback.OnDeserialization (object sender)
621 public override bool Equals (object obj)
625 PermissionSet ps = (obj as PermissionSet);
628 if (list.Count != ps.Count)
631 for (int i=0; i < list.Count; i++) {
633 for (int j=0; i < ps.list.Count; j++) {
634 if (list [i].Equals (ps.list [j])) {
646 public override int GetHashCode ()
648 return (list.Count == 0) ? (int) state : base.GetHashCode ();
651 [MonoTODO ("what's it doing here?")]
652 static public void RevertAssert ()
654 // FIXME: There's probably a reason this was added here ?
655 CodeAccessPermission.RevertAssert ();
661 internal PolicyLevel Resolver {
662 get { return _policyLevel; }
663 set { _policyLevel = value; }
666 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
668 if (IsUnrestricted ()) {
669 // we request unrestricted
670 if (frame.Deny != null) {
671 // but have restrictions (some denied permissions)
672 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
673 } else if (frame.PermitOnly != null) {
674 // but have restrictions (only some permitted permissions)
675 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
679 // skip next steps if no Assert, Deny or PermitOnly are present
680 if (frame.HasStackModifiers) {
681 foreach (CodeAccessPermission cap in list) {
682 if (cap.ProcessFrame (frame))
683 return true; // Assert reached - abort stack walk!
687 // however the "final" grant set is resolved by assembly, so
688 // there's no need to check it every time (just when we're
689 // changing assemblies between frames).
690 if (frame.Assembly != current) {
691 CheckAssembly (current, frame);
692 current = frame.Assembly;
695 if (frame.Domain != domain) {
696 CheckAppDomain (domain, frame);
697 domain = frame.Domain;
703 internal void CheckAssembly (Assembly a, SecurityFrame frame)
705 if (!SecurityManager.IsGranted (a, this, false)) {
706 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
707 frame, SecurityAction.Demand, null);
711 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
713 if (!SecurityManager.IsGranted (domain, this)) {
714 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
715 frame, SecurityAction.Demand, null);
719 // 2.0 metadata format
721 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
723 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
724 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
725 throw new SecurityException (msg);
729 int numattr = ReadEncodedInt (data, ref pos);
730 PermissionSet ps = new PermissionSet (PermissionState.None);
731 for (int i = 0; i < numattr; i++) {
732 IPermission p = ProcessAttribute (data, ref pos);
734 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
735 throw new SecurityException (msg);
737 ps.AddPermission (p);
742 internal static int ReadEncodedInt (byte[] data, ref int position)
745 if ((data [position] & 0x80) == 0) {
746 len = data [position];
748 } else if ((data [position] & 0x40) == 0) {
749 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
752 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
753 (data [position + 2] << 8) | (data [position + 3]));
759 static object[] action = new object [1] { (SecurityAction) 0 };
761 // TODO: add support for arrays and enums
762 internal static IPermission ProcessAttribute (byte[] data, ref int position)
764 int clen = ReadEncodedInt (data, ref position);
765 string cnam = Encoding.UTF8.GetString (data, position, clen);
769 Type secattr = Type.GetType (cnam);
770 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
774 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
775 int numberOfParameters = ReadEncodedInt (data, ref position);
776 for (int j=0; j < numberOfParameters; j++) {
777 bool property = false;
778 switch (data [position++]) {
779 case 0x53: // field (technically possible and working)
782 case 0x54: // property (common case)
790 byte type = data [position++];
793 type = data [position++];
796 int plen = ReadEncodedInt (data, ref position);
797 string pnam = Encoding.UTF8.GetString (data, position, plen);
802 arrayLength = BitConverter.ToInt32 (data, position);
807 object[] arrayIndex = null;
808 for (int i = 0; i < arrayLength; i++) {
810 // TODO - setup index
813 // sadly type values doesn't match ther TypeCode enum :(
815 case 0x02: // MONO_TYPE_BOOLEAN
816 obj = (object) Convert.ToBoolean (data [position++]);
818 case 0x03: // MONO_TYPE_CHAR
819 obj = (object) Convert.ToChar (data [position]);
822 case 0x04: // MONO_TYPE_I1
823 obj = (object) Convert.ToSByte (data [position++]);
825 case 0x05: // MONO_TYPE_U1
826 obj = (object) Convert.ToByte (data [position++]);
828 case 0x06: // MONO_TYPE_I2
829 obj = (object) Convert.ToInt16 (data [position]);
832 case 0x07: // MONO_TYPE_U2
833 obj = (object) Convert.ToUInt16 (data [position]);
836 case 0x08: // MONO_TYPE_I4
837 obj = (object) Convert.ToInt32 (data [position]);
840 case 0x09: // MONO_TYPE_U4
841 obj = (object) Convert.ToUInt32 (data [position]);
844 case 0x0A: // MONO_TYPE_I8
845 obj = (object) Convert.ToInt64 (data [position]);
848 case 0x0B: // MONO_TYPE_U8
849 obj = (object) Convert.ToUInt64 (data [position]);
852 case 0x0C: // MONO_TYPE_R4
853 obj = (object) Convert.ToSingle (data [position]);
856 case 0x0D: // MONO_TYPE_R8
857 obj = (object) Convert.ToDouble (data [position]);
860 case 0x0E: // MONO_TYPE_STRING
862 if (data [position] != 0xFF) {
863 int slen = ReadEncodedInt (data, ref position);
864 s = Encoding.UTF8.GetString (data, position, slen);
871 case 0x50: // special for TYPE
872 int tlen = ReadEncodedInt (data, ref position);
873 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
877 return null; // unsupported
881 PropertyInfo pi = secattr.GetProperty (pnam);
882 pi.SetValue (sa, obj, arrayIndex);
884 FieldInfo fi = secattr.GetField (pnam);
885 fi.SetValue (sa, obj);
889 return sa.CreatePermission ();