//
// (C) Nick Drochak
// Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
using System.Collections;
using System.Diagnostics;
+using System.IO;
using System.Reflection;
+using System.Runtime.InteropServices;
using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
+using System.Security.Policy;
+using System.Text;
+using System.Threading;
namespace System.Security {
private static string tagName = "PermissionSet";
private const int version = 1;
+ private static object[] psNone = new object [1] { PermissionState.None };
private PermissionState state;
private ArrayList list;
private int _hashcode;
+ private PolicyLevel _policyLevel;
+ private bool _declsec;
// constructors
}
}
+ internal PermissionSet (string xml)
+ : this ()
+ {
+ state = PermissionState.None;
+ if (xml != null) {
+ SecurityElement se = SecurityElement.FromString (xml);
+ FromXml (se);
+ }
+ }
+
+ // Light version for creating a (non unrestricted) PermissionSet with
+ // a single permission. This allows to relax most validations.
+ internal PermissionSet (IPermission perm)
+ : this ()
+ {
+ if (perm != null) {
+ // note: we do not copy IPermission like AddPermission
+ list.Add (perm);
+ }
+ }
+
// methods
public virtual IPermission AddPermission (IPermission perm)
// we can't add two permissions of the same type in a set
// so we remove an existing one, union with it and add it back
- IPermission existing = Remove (perm.GetType ());
+ IPermission existing = RemovePermission (perm.GetType ());
if (existing != null) {
perm = perm.Union (existing);
}
+ // note: Add doesn't copy
list.Add (perm);
return perm;
}
- [MonoTODO()]
+ [MonoTODO ("Imperative mode isn't supported")]
public virtual void Assert ()
{
+ new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
+
+ int count = this.Count;
+
+ // we (current frame) must have the permission to assert it to others
+ // otherwise we don't assert (but we don't throw an exception)
+ foreach (IPermission p in list) {
+ // note: we ignore non-CAS permissions
+ if (p is IStackWalk) {
+ if (!SecurityManager.IsGranted (p)) {
+ return;
+ }
+ } else
+ count--;
+ }
+
+ // note: we must ignore the stack modifiers for the non-CAS permissions
+ if (count > 0)
+ throw new NotSupportedException ("Currently only declarative Assert are supported.");
}
internal void Clear ()
}
}
- [MonoTODO ("Assert, Deny and PermitOnly aren't yet supported")]
+ [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
public virtual void Demand ()
{
- if (!SecurityManager.SecurityEnabled)
+ // Note: SecurityEnabled only applies to CAS permissions
+ // so we're not checking for it (yet)
+ if (IsEmpty ())
return;
- // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
- PermissionSet cas = this.Copy ();
- foreach (IPermission p in list) {
- Type t = p.GetType ();
- if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
- p.Demand ();
- // we wont have to process this one in the stack walk
- cas.Remove (t);
+ PermissionSet cas = this;
+ // avoid copy (if possible)
+ if (ContainsNonCodeAccessPermissions ()) {
+ // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
+ cas = this.Copy ();
+ foreach (IPermission p in list) {
+ Type t = p.GetType ();
+ if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
+ p.Demand ();
+ // we wont have to process this one in the stack walk
+ cas.RemovePermission (t);
+ }
}
}
- // don't start the walk if the permission set only contains non CAS permissions
- if (cas.Count == 0)
- return;
- Assembly a = null;
- StackTrace st = new StackTrace (1); // skip ourself
- StackFrame[] frames = st.GetFrames ();
- foreach (StackFrame sf in frames) {
- MethodBase mb = sf.GetMethod ();
- // declarative security checks, when present, must be checked
- // for each stack frame
- if ((MethodAttributes.HasSecurity & mb.Attributes) == MethodAttributes.HasSecurity) {
- // TODO
- }
- // however the "final" grant set is resolved by assembly, so
- // there's no need to check it every time (just when we're
- // changing assemblies between frames).
- Assembly af = mb.ReflectedType.Assembly;
- if (a != af) {
- a = af;
- if (!a.Demand (cas)) {
- // TODO add more details
- throw new SecurityException ("Demand failed");
- }
+ // don't start the stack walk if
+ // - the permission set only contains non CAS permissions; or
+ // - security isn't enabled (applis only to CAS!)
+ if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
+ CasOnlyDemand (_declsec ? 4 : 2);
+ }
+
+ // The number of frames to skip depends on who's calling
+ // - CodeAccessPermission.Demand (imperative)
+ // - PermissionSet.Demand (imperative)
+ // - SecurityManager.InternalDemand (declarative)
+ internal void CasOnlyDemand (int skip)
+ {
+ Assembly current = null;
+
+ // skip ourself, Demand and other security runtime methods
+ foreach (SecurityFrame sf in SecurityFrame.GetStack (skip)) {
+ if (ProcessFrame (sf, ref current))
+ return; // reached Assert
+ }
+
+ // Is there a CompressedStack to handle ?
+ CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
+ if ((stack != null) && !stack.IsEmpty ()) {
+ foreach (SecurityFrame frame in stack.List) {
+ if (ProcessFrame (frame, ref current))
+ return; // reached Assert
}
}
}
- [MonoTODO()]
+ [MonoTODO ("Imperative mode isn't supported")]
public virtual void Deny ()
{
+ foreach (IPermission p in list) {
+ // note: we ignore non-CAS permissions
+ if (p is IStackWalk) {
+ throw new NotSupportedException ("Currently only declarative Deny are supported.");
+ }
+ }
}
- // to be re-used by NamedPermissionSet (and other derived classes)
- internal void FromXml (SecurityElement et, string className)
+ [MonoTODO ("adjust class version with current runtime - unification")]
+ public virtual void FromXml (SecurityElement et)
{
if (et == null)
throw new ArgumentNullException ("et");
string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
throw new ArgumentException (msg, "et");
}
-// if (!et.Attribute ("class").EndsWith (className))
-// throw new ArgumentException ("not " + className);
-// version isn't checked
-// if (et.Attribute ("version") != "1")
-// throw new ArgumentException ("wrong version");
if (CodeAccessPermission.IsUnrestricted (et))
state = PermissionState.Unrestricted;
else
state = PermissionState.None;
- }
- [MonoTODO ("adjust class version with current runtime")]
- public virtual void FromXml (SecurityElement et)
- {
list.Clear ();
- FromXml (et, tagName);
if (et.Children != null) {
foreach (SecurityElement se in et.Children) {
string className = se.Attribute ("class");
- // TODO: adjust class version with current runtime
+ if (className == null) {
+ throw new ArgumentException (Locale.GetText (
+ "No permission class is specified."));
+ }
+ if (Resolver != null) {
+ // policy class names do not have to be fully qualified
+ className = Resolver.ResolveClassName (className);
+ }
+ // TODO: adjust class version with current runtime (unification)
// http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
Type classType = Type.GetType (className);
- object [] psNone = new object [1] { PermissionState.None };
- IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
- p.FromXml (se);
- list.Add (p);
+ if (classType != null) {
+ IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
+ p.FromXml (se);
+ list.Add (p);
+ }
+#if !NET_2_0
+ else {
+ string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
+ throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
+ }
+#endif
}
}
}
return true;
}
- [MonoTODO()]
+ [MonoTODO ("Imperative mode isn't supported")]
public virtual void PermitOnly ()
{
+ foreach (IPermission p in list) {
+ // note: we ignore non-CAS permissions
+ if (p is IStackWalk) {
+ throw new NotSupportedException ("Currently only declarative Deny are supported.");
+ }
+ }
}
public bool ContainsNonCodeAccessPermissions ()
if (inFormat == outFormat)
return inData;
+ PermissionSet ps = null;
+
if (inFormat == "BINARY") {
if (outFormat.StartsWith ("XML")) {
- // TODO - convert from binary format
- return inData;
+ using (MemoryStream ms = new MemoryStream (inData)) {
+ BinaryFormatter formatter = new BinaryFormatter ();
+ ps = (PermissionSet) formatter.Deserialize (ms);
+ ms.Close ();
+ }
+ string xml = ps.ToString ();
+ switch (outFormat) {
+ case "XML":
+ case "XMLASCII":
+ return Encoding.ASCII.GetBytes (xml);
+ case "XMLUNICODE":
+ return Encoding.Unicode.GetBytes (xml);
+ }
}
}
else if (inFormat.StartsWith ("XML")) {
if (outFormat == "BINARY") {
- // TODO - convert to binary format
- return inData;
+ string xml = null;
+ switch (inFormat) {
+ case "XML":
+ case "XMLASCII":
+ xml = Encoding.ASCII.GetString (inData);
+ break;
+ case "XMLUNICODE":
+ xml = Encoding.Unicode.GetString (inData);
+ break;
+ }
+ if (xml != null) {
+ ps = new PermissionSet (PermissionState.None);
+ ps.FromXml (SecurityElement.FromString (xml));
+
+ MemoryStream ms = new MemoryStream ();
+ BinaryFormatter formatter = new BinaryFormatter ();
+ formatter.Serialize (ms, ps);
+ ms.Close ();
+ return ms.ToArray ();
+ }
}
else if (outFormat.StartsWith ("XML")) {
string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
+#if NET_2_0
throw new XmlSyntaxException (msg);
+#else
+ throw new ArgumentException (msg);
+#endif
}
}
else {
if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
return null;
- // FIXME: in this case this optimization IS BAD because some permissions, like identity
- // permissions, do not implement the IUnrestrictedPermission interface. This can results
- // in case where (a N b) != (b N a)
- // MS has the same "bad optimization" - reported as FDBK14612
- if (other.IsUnrestricted ())
- return this.Copy ();
- if (this.IsUnrestricted ())
- return other.Copy ();
-
PermissionState state = PermissionState.None;
if (this.IsUnrestricted () && other.IsUnrestricted ())
state = PermissionState.Unrestricted;
PermissionSet interSet = new PermissionSet (state);
- foreach (IPermission p in other.list) {
+ if (state == PermissionState.Unrestricted) {
+ InternalIntersect (interSet, this, other, true);
+ InternalIntersect (interSet, other, this, true);
+ }
+ else if (this.IsUnrestricted ()) {
+ InternalIntersect (interSet, this, other, true);
+ }
+ else if (other.IsUnrestricted ()) {
+ InternalIntersect (interSet, other, this, true);
+ }
+ else {
+ InternalIntersect (interSet, this, other, false);
+ }
+ return interSet;
+ }
+
+ internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
+ {
+ foreach (IPermission p in b.list) {
// for every type in both list
- IPermission i = this.GetPermission (p.GetType ());
+ IPermission i = a.GetPermission (p.GetType ());
if (i != null) {
// add intersection for this type
- interSet.AddPermission (p.Intersect (i));
+ intersect.AddPermission (p.Intersect (i));
+ }
+ else if (unrestricted && (p is IUnrestrictedPermission)) {
+ intersect.AddPermission (p);
}
// or reject!
}
- return interSet;
}
public virtual bool IsEmpty ()
// note: Unrestricted isn't empty
if (state == PermissionState.Unrestricted)
return false;
- return ((list == null) || (list.Count == 0));
+ if ((list == null) || (list.Count == 0))
+ return true;
+ // the set may include some empty permissions
+ foreach (IPermission p in list) {
+ // empty == fully restricted == IsSubsetOg(null) == true
+ if (!p.IsSubsetOf (null))
+ return false;
+ }
+ return true;
}
public virtual bool IsUnrestricted ()
}
public virtual IPermission RemovePermission (Type permClass)
- {
- // FIXME: this is *not right* because we can't remove permissions not implementing
- // IUnrestrictedPermission interface (e.g. identity permissions) but compatible
- // with MS (FDBK14622)
- // Note: it also makes it unusable within the class (e.g. SetPermission)
- if (IsUnrestricted ())
- return null;
-
- return Remove (permClass);
- }
-
- internal IPermission Remove (Type permClass)
{
if (permClass == null)
return null;
public virtual IPermission SetPermission (IPermission perm)
{
+ if (perm == null)
+ return null;
if (perm is IUnrestrictedPermission)
state = PermissionState.None;
- Remove (perm.GetType ());
+ RemovePermission (perm.GetType ());
list.Add (perm);
return perm;
}
se.AddAttribute ("version", version.ToString ());
if (state == PermissionState.Unrestricted)
se.AddAttribute ("Unrestricted", "true");
- else {
- foreach (IPermission p in list)
- se.AddChild (p.ToXml ());
+
+ // required for permissions that do not implement IUnrestrictedPermission
+ foreach (IPermission p in list) {
+ se.AddChild (p.ToXml ());
}
return se;
}
get { return this; }
}
+ internal bool DeclarativeSecurity {
+ get { return _declsec; }
+ set { _declsec = value; }
+ }
+
[MonoTODO()]
void IDeserializationCallback.OnDeserialization (object sender)
{
}
#if NET_2_0
+ [ComVisible (false)]
public override bool Equals (object obj)
{
if (obj == null)
return true;
}
+ [ComVisible (false)]
public override int GetHashCode ()
{
- if (list.Count == 0)
- return (int) state;
-
- if (_hashcode == 0) {
- _hashcode = state.GetHashCode ();
- foreach (IPermission p in list) {
- _hashcode ^= p.GetHashCode ();
- }
- }
- return _hashcode;
+ return (list.Count == 0) ? (int) state : base.GetHashCode ();
}
[MonoTODO ("what's it doing here?")]
static public void RevertAssert ()
{
+ // FIXME: There's probably a reason this was added here ?
+ CodeAccessPermission.RevertAssert ();
}
#endif
+
+ // internal
+
+ internal PolicyLevel Resolver {
+ get { return _policyLevel; }
+ set { _policyLevel = value; }
+ }
+
+
+ internal void ImmediateCallerDemand ()
+ {
+ if (IsEmpty ())
+ return;
+
+ // skip ourself
+ SecurityFrame sf = new SecurityFrame (1); // FIXME skip
+ foreach (IPermission p in list) {
+ // note: this may contains non CAS permissions
+ if (p is CodeAccessPermission) {
+ if (SecurityManager.SecurityEnabled)
+ SecurityManager.IsGranted (sf.Assembly, p);
+ } else {
+ p.Demand ();
+ }
+ }
+ }
+
+ // Note: Non-CAS demands aren't affected by SecurityManager.SecurityEnabled
+ internal void ImmediateCallerNonCasDemand ()
+ {
+ if (IsEmpty ())
+ return;
+
+ // non CAS permissions (e.g. PrincipalPermission) requires direct call to Demand
+ foreach (IPermission p in list) {
+ p.Demand ();
+ }
+ }
+
+ internal bool ProcessFrame (SecurityFrame frame, ref Assembly current)
+ {
+ if (IsUnrestricted ()) {
+ // we request unrestricted
+ if (frame.Deny != null) {
+ // but have restrictions (some denied permissions)
+ CodeAccessPermission.ThrowSecurityException (this, "Deny", frame.Assembly,
+ frame.Method, SecurityAction.Demand, null);
+ } else if (frame.PermitOnly != null) {
+ // but have restrictions (onyl some permitted permissions)
+ CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame.Assembly,
+ frame.Method, SecurityAction.Demand, null);
+ }
+ }
+
+ foreach (CodeAccessPermission cap in list) {
+ if (cap.ProcessFrame (frame, ref current))
+ return true; // Assert reached - abort stack walk!
+ }
+ return false;
+ }
}
}