From db20f3f1bb8595633a7e16c8900fd401a453a6b5 Mon Sep 17 00:00:00 2001 From: Jiyoung Yun Date: Tue, 27 Dec 2016 16:46:08 +0900 Subject: Imported Upstream version 1.0.0.9127 --- .../src/System/Security/AccessControl/Enums.cs | 6 - src/mscorlib/src/System/Security/Attributes.cs | 11 +- .../src/System/Security/BuiltInPermissionSets.cs | 103 +- .../src/System/Security/CodeAccessPermission.cs | 69 +- .../System/Security/CodeAccessSecurityEngine.cs | 468 +---- .../src/System/Security/FrameSecurityDescriptor.cs | 31 +- .../src/System/Security/HostProtectionException.cs | 5 +- .../src/System/Security/HostSecurityManager.cs | 131 +- .../src/System/Security/IEvidenceFactory.cs | 15 +- .../src/System/Security/ISecurityEncodable.cs | 18 +- .../System/Security/ISecurityPolicyEncodable.cs | 17 +- .../src/System/Security/NamedPermissionSet.cs | 202 +-- .../src/System/Security/PermissionListSet.cs | 29 +- src/mscorlib/src/System/Security/PermissionSet.cs | 1100 +----------- .../src/System/Security/PermissionSetEnumerator.cs | 14 - .../src/System/Security/PermissionSetTriple.cs | 20 +- .../src/System/Security/PermissionToken.cs | 202 +-- .../Security/Permissions/EnvironmentPermission.cs | 60 +- .../Security/Permissions/FileDialogPermission.cs | 33 +- .../Security/Permissions/FileIOPermission.cs | 304 +--- .../Security/Permissions/GACIdentityPermission.cs | 16 - .../Permissions/HostProtectionPermission.cs | 34 - .../Permissions/IsolatedStorageFilePermission.cs | 13 - .../Permissions/IsolatedStoragePermission.cs | 91 - .../Security/Permissions/PermissionAttributes.cs | 314 +--- .../Security/Permissions/ReflectionPermission.cs | 39 - .../Security/Permissions/RegistryPermission.cs | 131 -- .../Security/Permissions/SecurityPermission.cs | 96 +- .../Security/Permissions/SiteIdentityPermission.cs | 108 -- .../Permissions/StrongNameIdentityPermission.cs | 90 +- .../Permissions/StrongNamePublicKeyBlob.cs | 2 +- .../System/Security/Permissions/UIPermission.cs | 44 - .../Security/Permissions/URLIdentityPermission.cs | 111 +- .../Security/Permissions/ZoneIdentityPermission.cs | 101 -- .../Security/Permissions/keycontainerpermission.cs | 72 +- .../src/System/Security/Policy/ApplicationTrust.cs | 573 +----- .../src/System/Security/Policy/Evidence.cs | 1865 -------------------- .../src/System/Security/Policy/EvidenceBase.cs | 31 +- .../Security/Policy/EvidenceTypeDescriptor.cs | 20 +- .../Security/Policy/IDelayEvaluatedEvidence.cs | 1 - .../src/System/Security/Policy/PolicyStatement.cs | 302 +--- src/mscorlib/src/System/Security/Policy/Site.cs | 29 +- .../src/System/Security/Policy/StrongName.cs | 59 +- src/mscorlib/src/System/Security/Policy/URL.cs | 29 +- src/mscorlib/src/System/Security/Policy/Zone.cs | 66 +- .../Security/Principal/TokenImpersonationLevel.cs | 9 +- .../src/System/Security/SafeSecurityHandles.cs | 16 - .../src/System/Security/SecurityContext.cs | 238 +-- .../src/System/Security/SecurityElement.cs | 100 +- .../src/System/Security/SecurityException.cs | 608 +------ .../src/System/Security/SecurityManager.cs | 524 +----- .../src/System/Security/SecurityRuntime.cs | 156 +- src/mscorlib/src/System/Security/SecurityState.cs | 10 +- src/mscorlib/src/System/Security/Util/Config.cs | 48 - src/mscorlib/src/System/Security/Util/Hex.cs | 2 +- .../System/Security/Util/StringExpressionSet.cs | 41 +- .../src/System/Security/Util/TokenBasedSet.cs | 32 +- src/mscorlib/src/System/Security/Util/URLString.cs | 17 +- src/mscorlib/src/System/Security/Util/XMLUtil.cs | 272 +-- src/mscorlib/src/System/Security/securestring.cs | 31 +- 60 files changed, 327 insertions(+), 8852 deletions(-) (limited to 'src/mscorlib/src/System/Security') diff --git a/src/mscorlib/src/System/Security/AccessControl/Enums.cs b/src/mscorlib/src/System/Security/AccessControl/Enums.cs index c52176a29b..20f5c5f91a 100644 --- a/src/mscorlib/src/System/Security/AccessControl/Enums.cs +++ b/src/mscorlib/src/System/Security/AccessControl/Enums.cs @@ -70,12 +70,6 @@ namespace System.Security.AccessControl [Flags] public enum AccessControlActions { -#if FEATURE_MACL - None = 0, - View = 1, - Change = 2 -#else None = 0 -#endif } } diff --git a/src/mscorlib/src/System/Security/Attributes.cs b/src/mscorlib/src/System/Security/Attributes.cs index d2229227a5..e4ebc53053 100644 --- a/src/mscorlib/src/System/Security/Attributes.cs +++ b/src/mscorlib/src/System/Security/Attributes.cs @@ -57,14 +57,12 @@ namespace System.Security NotVisibleByDefault = 1 } -#if !FEATURE_CORECLR [Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")] public enum SecurityCriticalScope { Explicit = 0, Everything = 0x1 } -#endif // FEATURE_CORECLR // SecurityCriticalAttribute // Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.) @@ -84,12 +82,10 @@ namespace System.Security { #pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat -#if !FEATURE_CORECLR - private SecurityCriticalScope _val; -#endif // FEATURE_CORECLR + private SecurityCriticalScope _val; + public SecurityCriticalAttribute () {} -#if !FEATURE_CORECLR public SecurityCriticalAttribute(SecurityCriticalScope scope) { _val = scope; @@ -101,7 +97,6 @@ namespace System.Security return _val; } } -#endif // FEATURE_CORECLR #pragma warning restore 618 } @@ -167,7 +162,6 @@ namespace System.Security public SecurityTransparentAttribute () {} } -#if !FEATURE_CORECLR public enum SecurityRuleSet : byte { None = 0, @@ -205,5 +199,4 @@ namespace System.Security get { return m_ruleSet; } } } -#endif // !FEATURE_CORECLR } diff --git a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs index e29dec3b06..48539574af 100644 --- a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs +++ b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs @@ -6,6 +6,7 @@ // using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security.Permissions; using Microsoft.Win32; @@ -180,30 +181,6 @@ namespace System.Security Flags = ""SkipVerification"" /> "; -#if FEATURE_CAS_POLICY - private const string s_wpfExtensionXml = - @" - - - "; - - private const string s_wpfExtensionUnrestrictedXml = - @" - - - "; -#endif //FEATURE_CAS_POLICY - // // Built in permission set objects // @@ -222,11 +199,7 @@ namespace System.Security internal static NamedPermissionSet Everything { - get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionUnrestrictedXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); } } internal static NamedPermissionSet Execution @@ -241,20 +214,12 @@ namespace System.Security internal static NamedPermissionSet Internet { - get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); } } internal static NamedPermissionSet LocalIntranet { - get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml -#if FEATURE_CAS_POLICY - , s_wpfExtensionXml -#endif // FEATURE_CAS_POLICY - ); } + get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); } } internal static NamedPermissionSet Nothing @@ -272,71 +237,19 @@ namespace System.Security // set extensions if necessary // - private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(ref NamedPermissionSet permissionSet, - string permissionSetXml -#if FEATURE_CAS_POLICY - ,string extensionXml -#endif // FEATURE_CAS_POLICY - ) + private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet( + ref NamedPermissionSet permissionSet, + string permissionSetXml) { Contract.Requires(!String.IsNullOrEmpty(permissionSetXml)); -#if FEATURE_CAS_POLICY - Contract.Requires(!String.IsNullOrEmpty(extensionXml)); -#endif // FEATURE_CAS_POLICY - - if (permissionSet == null) - { -#if FEATURE_CAS_POLICY - SecurityElement securityElement = SecurityElement.FromString(permissionSetXml); - NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement); - - PermissionSet extensions = GetPermissionSetExtensions(extensionXml); - deserializedPermissionSet.InplaceUnion(extensions); - - permissionSet = deserializedPermissionSet; -#endif // FEATURE_CAS_POLICY - } - return permissionSet.Copy() as NamedPermissionSet; } private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet, string permissionSetXml) { - Contract.Assert(!String.IsNullOrEmpty(permissionSetXml)); - -#if FEATURE_CAS_POLICY - if (permissionSet == null) - { - SecurityElement securityElement = SecurityElement.FromString(permissionSetXml); - NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement); - - permissionSet = deserializedPermissionSet; - } -#endif // FEATURE_CAS_POLICY - + Debug.Assert(!String.IsNullOrEmpty(permissionSetXml)); return permissionSet.Copy() as NamedPermissionSet; } - -#if FEATURE_CAS_POLICY - private static PermissionSet GetPermissionSetExtensions(string extensionXml) - { - Contract.Requires(!String.IsNullOrEmpty(extensionXml)); - - SecurityElement se = SecurityElement.FromString(extensionXml); - - // Return the permission set extension only if WPF is in the present framework profile. - // XMLUtil.GetClassFromElement() helps do the quickest check, with no exception thrown and - // minimal parsing. - SecurityElement firstPermission = (SecurityElement)se.Children[0]; - if (System.Security.Util.XMLUtil.GetClassFromElement(firstPermission, /*ignoreTypeLoadFailures*/true) != null) - { - PermissionSet extensions = new NamedPermissionSet(se); - return extensions; - } - - return null; - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/mscorlib/src/System/Security/CodeAccessPermission.cs index 61334c22bd..70504d902e 100644 --- a/src/mscorlib/src/System/Security/CodeAccessPermission.cs +++ b/src/mscorlib/src/System/Security/CodeAccessPermission.cs @@ -13,20 +13,16 @@ namespace System.Security using System.Collections; using System.Text; using System; - using System.Diagnostics; + using System.Diagnostics; using System.Diagnostics.Contracts; using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission; [Serializable] -#if !FEATURE_CORECLR - [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )] -#endif [System.Runtime.InteropServices.ComVisible(true)] abstract public class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk { // Static methods for manipulation of stack - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static void RevertAssert() { @@ -34,7 +30,6 @@ namespace System.Security SecurityRuntime.RevertAssert(ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static void RevertDeny() @@ -43,7 +38,6 @@ namespace System.Security SecurityRuntime.RevertDeny(ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static void RevertPermitOnly() { @@ -51,7 +45,6 @@ namespace System.Security SecurityRuntime.RevertPermitOnly(ref stackMark); } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static void RevertAll() { @@ -66,7 +59,6 @@ namespace System.Security // Mark this method as requiring a security object on the caller's frame // so the caller won't be inlined (which would mess up stack crawling). - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void Demand() @@ -78,7 +70,6 @@ namespace System.Security } } - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static void Demand(PermissionType permissionType) @@ -87,7 +78,7 @@ namespace System.Security // without having to create objects. // The security annotation fxcop rule that flags all methods with a Demand() has logic // which checks for methods named Demand in types that implement IPermission or IStackWalk. - Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand"); + Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark); @@ -96,7 +87,6 @@ namespace System.Security // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void Assert() @@ -106,7 +96,6 @@ namespace System.Security } - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static internal void Assert(bool allPossible) @@ -115,7 +104,7 @@ namespace System.Security // without having to new a PermissionSet. // The security annotation fxcop rule that flags all methods with an Assert() has logic // which checks for methods named Assert in types that implement IPermission or IStackWalk. - Contract.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert"); + Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; SecurityRuntime.AssertAllPossible(ref stackMark); @@ -124,7 +113,6 @@ namespace System.Security // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] @@ -137,7 +125,6 @@ namespace System.Security // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void PermitOnly() @@ -160,48 +147,6 @@ namespace System.Security // otherwise we don't support it. throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" )); } - -#if FEATURE_CAS_POLICY - static internal SecurityElement CreatePermissionElement( IPermission perm, String permname ) - { - SecurityElement root = new SecurityElement( "IPermission" ); - XMLUtil.AddClassAttribute( root, perm.GetType(), permname ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( perm.GetType().FullName.Equals( permname ), "Incorrect class name passed in! Was: " + permname + " Should be " + perm.GetType().FullName); - - root.AddAttribute( "version", "1" ); - return root; - } - - static internal void ValidateElement( SecurityElement elem, IPermission perm ) - { - if (elem == null) - throw new ArgumentNullException( "elem" ); - Contract.EndContractBlock(); - - if (!XMLUtil.IsPermissionElement( perm, elem )) - throw new ArgumentException( Environment.GetResourceString( "Argument_NotAPermissionElement")); - - String version = elem.Attribute( "version" ); - - if (version != null && !version.Equals( "1" )) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXMLBadVersion") ); - } - - abstract public SecurityElement ToXml(); - abstract public void FromXml( SecurityElement elem ); - - // - // Unimplemented interface methods - // (as a reminder only) - // - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY // // HELPERS FOR IMPLEMENTING ABSTRACT METHODS @@ -258,26 +203,26 @@ namespace System.Security internal bool CheckDemand(CodeAccessPermission grant) { - Contract.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" ); + Debug.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" ); return IsSubsetOf( grant ); } internal bool CheckPermitOnly(CodeAccessPermission permitted) { - Contract.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); + Debug.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); return IsSubsetOf( permitted ); } internal bool CheckDeny(CodeAccessPermission denied) { - Contract.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" ); + Debug.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" ); IPermission intersectPerm = Intersect(denied); return (intersectPerm == null || intersectPerm.IsSubsetOf(null)); } internal bool CheckAssert(CodeAccessPermission asserted) { - Contract.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); + Debug.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" ); return IsSubsetOf( asserted ); } } diff --git a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs index 2a1cf9a0ea..d86897c02e 100644 --- a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs +++ b/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs @@ -15,6 +15,7 @@ namespace System.Security { using System.Globalization; using System.Security.Policy; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // Used in DemandInternal, to remember the result of previous demands @@ -52,40 +53,22 @@ namespace System.Security { internal static SecurityPermission AssertPermission; internal static PermissionToken AssertPermissionToken; - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark); - [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.Conditional( "_DEBUG" )] private static void DEBUG_OUT( String str ) { -#if _DEBUG +#if _DEBUG if (debug) - { -#if !FEATURE_CORECLR - if (to_file) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append( str ); - sb.Append ((char)13) ; - sb.Append ((char)10) ; - PolicyManager.DebugOut( file, sb.ToString() ); - } - else -#endif - Console.WriteLine( str ); - } -#endif + Console.WriteLine( str ); +#endif } - -#if _DEBUG + +#if _DEBUG private static bool debug = false; -#if !FEATURE_CORECLR - private static readonly bool to_file = false; -#endif private const String file = "d:\\foo\\debug.txt"; -#endif +#endif // static default constructor. This will be called before any of the static members are accessed. static CodeAccessSecurityEngine() @@ -96,7 +79,6 @@ namespace System.Security { AssertPermissionToken = PermissionToken.GetToken(AssertPermission); } - [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 private static void ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 @@ -109,20 +91,15 @@ namespace System.Security { // there will be an infinite recursion that overflows the stack. PermissionSet.s_fullTrust.Assert(); asmName = asm.GetName(); -#if FEATURE_CAS_POLICY - if(asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain - asmEvidence = asm.Evidence; -#endif // FEATURE_CAS_POLICY } throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed); } - [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 private static void ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 { - Contract.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here"); + Debug.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here"); if (assemblyOrString == null || assemblyOrString is RuntimeAssembly) ThrowSecurityException((RuntimeAssembly)assemblyOrString, granted, refused, rmh, action, demand, permThatFailed); @@ -134,7 +111,6 @@ namespace System.Security { } #if FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated internal static void CheckSetHelper(CompressedStack cs, PermissionSet grants, PermissionSet refused, @@ -149,9 +125,6 @@ namespace System.Security { CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true); } #else // FEATURE_COMPRESSEDSTACK - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif #pragma warning disable 618 internal static void CheckSetHelper(Object notUsed, PermissionSet grants, @@ -165,14 +138,13 @@ namespace System.Security { // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object, // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.) - Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); + Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true); } #endif // FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 internal static bool CheckSetHelper(PermissionSet grants, PermissionSet refused, @@ -183,19 +155,7 @@ namespace System.Security { bool throwException) #pragma warning restore 618 { - - Contract.Assert(demands != null, "Should not reach here with a null demand set"); -#if _DEBUG && FEATURE_CAS_POLICY - if (debug) - { - DEBUG_OUT("Granted: "); - DEBUG_OUT(grants.ToXml().ToString()); - DEBUG_OUT("Refused: "); - DEBUG_OUT(refused != null ? refused.ToXml().ToString() : ""); - DEBUG_OUT("Demanded: "); - DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : ""); - } -#endif // _DEBUG && FEATURE_CAS_POLICY + Debug.Assert(demands != null, "Should not reach here with a null demand set"); IPermission permThatFailed = null; if (grants != null) @@ -248,7 +208,6 @@ namespace System.Security { return true; } #if FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated internal static void CheckHelper(CompressedStack cs, PermissionSet grantedSet, PermissionSet refusedSet, @@ -264,9 +223,6 @@ namespace System.Security { CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true); } #else // FEATURE_COMPRESSEDSTACK - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif #pragma warning disable 618 internal static void CheckHelper(Object notUsed, PermissionSet grantedSet, @@ -281,11 +237,10 @@ namespace System.Security { // To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object, // we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be // corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.) - Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); + Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack"); CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true); } #endif // FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 internal static bool CheckHelper(PermissionSet grantedSet, PermissionSet refusedSet, @@ -298,19 +253,7 @@ namespace System.Security { #pragma warning restore 618 { // We should never get here with a null demand - Contract.Assert(demand != null, "Should not reach here with a null demand"); - -#if _DEBUG && FEATURE_CAS_POLICY - if (debug) - { - DEBUG_OUT("Granted: "); - DEBUG_OUT(grantedSet.ToXml().ToString()); - DEBUG_OUT("Refused: "); - DEBUG_OUT(refusedSet != null ? refusedSet.ToXml().ToString() : ""); - DEBUG_OUT("Demanded: "); - DEBUG_OUT(demand.ToString()); - } -#endif // _DEBUG && FEATURE_CAS_POLICY + Debug.Assert(demand != null, "Should not reach here with a null demand"); if (permToken == null) permToken = PermissionToken.GetToken(demand); @@ -339,7 +282,7 @@ namespace System.Security { // If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted // variety, we need to do the proper callback. - Contract.Assert(demand != null,"demand != null"); + Debug.Assert(demand != null,"demand != null"); // Find the permission of matching type in the permission set. @@ -411,420 +354,35 @@ namespace System.Security { return true; } -#if FEATURE_CAS_POLICY - /// - /// Demand for the grant set of an assembly - /// - /// - /// Managed half of SecurityStackWalk::DemandGrantSet. - /// - [System.Security.SecurityCritical] // auto-generated - private static void CheckGrantSetHelper(PermissionSet grantSet) - { - Contract.Assert(grantSet != null, "Missing grant set"); - grantSet.CopyWithNoIdentityPermissions().Demand(); - } - - /// - /// Perform a security demand which succeeds if either a compatibilty permission is granted to the - /// call stack, or restricted member access and the grant set of the target of the reflection - /// operation is granted. - /// - /// compatibility permission to check - /// grant set of the reflection target - [System.Security.SecurityCritical] // auto-generated - internal static void ReflectionTargetDemandHelper(PermissionType permission, PermissionSet targetGrant) - { - ReflectionTargetDemandHelper((int)permission, targetGrant); - } - - /// - /// Perform a security demand which succeeds if either a compatibilty permission is granted to the - /// call stack, or restricted member access and the grant set of the target of the reflection - /// operation is granted. - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand. - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static void ReflectionTargetDemandHelper(int permission, PermissionSet targetGrant) - { - // Capture a compressed stack so that we can make both permission checks without walking the stack - // multiple times. - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - CompressedStack cs = CompressedStack.GetCompressedStack(ref stackMark); - - ReflectionTargetDemandHelper(permission, targetGrant, cs); - } - - /// - /// Perform a reflection target demand against a given access context - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - /// access context to do the demand against - [System.Security.SecurityCritical] // auto-generated - private static void ReflectionTargetDemandHelper(int permission, - PermissionSet targetGrant, - Resolver accessContext) - { - ReflectionTargetDemandHelper(permission, targetGrant, accessContext.GetSecurityContext()); - } - - /// - /// Perform a reflection target demand against a given compressed stack - /// - /// - /// Managed half of SecurityStackWalk::ReflectionTargetDemand - /// - /// compatibility permission to check (See PermissionType) - /// grant set of the reflection target - /// compressed stack to do the demand against - [System.Security.SecurityCritical] // auto-generated - private static void ReflectionTargetDemandHelper(int permission, - PermissionSet targetGrant, - CompressedStack securityContext) - { - Contract.Assert(securityContext != null, "securityContext != null"); - - // We need to remove all identity permissions from the grant set of the target, otherwise the - // disjunctive demand will fail unless we're reflecting on the same assembly. - PermissionSet demandSet = null; - if (targetGrant == null) - { - demandSet = new PermissionSet(PermissionState.Unrestricted); - } - else - { - demandSet = targetGrant.CopyWithNoIdentityPermissions(); - demandSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); - } - - securityContext.DemandFlagsOrGrantSet((1 << (int)permission), demandSet); - } - - [System.Security.SecurityCritical] // auto-generated - internal static void GetZoneAndOriginHelper( CompressedStack cs, PermissionSet grantSet, PermissionSet refusedSet, ArrayList zoneList, ArrayList originList ) - { - if (cs != null) - cs.GetZoneAndOrigin(zoneList, originList, PermissionToken.GetToken(typeof(ZoneIdentityPermission)), PermissionToken.GetToken(typeof(UrlIdentityPermission))); - else - { - ZoneIdentityPermission zone = (ZoneIdentityPermission)grantSet.GetPermission( typeof( ZoneIdentityPermission ) ); - UrlIdentityPermission url = (UrlIdentityPermission)grantSet.GetPermission( typeof( UrlIdentityPermission ) ); - - if (zone != null) - zoneList.Add( zone.SecurityZone ); - - if (url != null) - originList.Add( url.Url ); - } - } - - [System.Security.SecurityCritical] // auto-generated - internal static void GetZoneAndOrigin( ref StackCrawlMark mark, out ArrayList zone, out ArrayList origin ) - { - zone = new ArrayList(); - origin = new ArrayList(); - - GetZoneAndOriginInternal( zone, origin, ref mark); - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void GetZoneAndOriginInternal(ArrayList zoneList, - ArrayList originList, - ref StackCrawlMark stackMark); - - [System.Security.SecurityCritical] // auto-generated - internal static void CheckAssembly(RuntimeAssembly asm, CodeAccessPermission demand ) - { - Contract.Assert( asm != null, "Must pass in a good assembly" ); - Contract.Assert( demand != null, "Must pass in a good demand" ); - - PermissionSet granted, refused; - asm.GetGrantSet( out granted, out refused ); -#pragma warning disable 618 - CheckHelper( granted, refused, demand, PermissionToken.GetToken(demand), RuntimeMethodHandleInternal.EmptyHandle, asm, SecurityAction.Demand, true ); -#pragma warning restore 618 - } - - // Check - Used to initiate a code-access security check. - // This method invokes a stack walk after skipping to the frame - // referenced by stackMark. - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void Check (Object demand, - ref StackCrawlMark stackMark, - bool isPermSet); - - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool QuickCheckForAllDemands(); - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool AllDomainsHomogeneousWithNoStackModifiers(); -#endif // FEATURE_CAS_POLICY - - [System.Security.SecurityCritical] // auto-generated internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - Check(cap, - ref stackMark, - false); -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - Check(permSet, - ref stackMark, - true); -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern FrameSecurityDescriptor CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, ref StackCrawlMark stackMark, int create ); - [System.Security.SecurityCritical] // auto-generated internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Make sure the caller of assert has the permission to assert - //WARNING: The placement of the call here is just right to check - // the appropriate frame. - - // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission - // you need to change the last parameter to a zero. - Contract.Assert(AssertPermissionToken != null && AssertPermission != null, "Assert Permission not setup correctly"); - FrameSecurityDescriptor secObj = CheckNReturnSO(AssertPermissionToken, - AssertPermission, - ref stackMark, - 1 ); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeAsserts()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssert(cap); - } -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Deny is only valid in legacy mode - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny")); - } - - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeDenials()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetDeny(cap); - } -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - // This can happen when you create delegates over functions that need the REQ_SQ - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeRestrictions()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetPermitOnly(cap); - } -#endif // FEATURE_CAS_POLICY - } - -#if FEATURE_CAS_POLICY - // Called from the VM to do a pre-domain initialization check of the security state of the - // AppDomain. This method looks at the state of the security of an AppDomain before it is - // completely initialized - so the output of this method does not always match what will be true - // when the domain is completely initialized. Instead, it is used to read what the input parameters - // to the domain setup say about the domain. - private static void PreResolve(out bool isFullyTrusted, out bool isHomogeneous) - { - // - // There are three main cases: - // 1. The AppDomain has an explict ApplicationTrust - we can use this to read the input state - // of the AppDomain. - // 2. The AppDomain is using legacy CAS policy - this means we can't tell much about the - // domain itself without a full policy resolution. - // 3. The domain is a standard v4+ AppDomain - these are always full trust and homogenous by - // default. - // - - // If the AppDomain is setup with an ApplicationTrust then it is always homogenous and we can - // tell its grant set right from the ApplicaitonTrust - ApplicationTrust domainTrust = AppDomain.CurrentDomain.SetupInformation.ApplicationTrust; - if (domainTrust != null) - { - isFullyTrusted = domainTrust.DefaultGrantSet.PermissionSet.IsUnrestricted(); - isHomogeneous = true; - return; - } - - // Otherwise, see if the domain is being configured on input to use legacy CAS policy - if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy || AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - isFullyTrusted = false; - isHomogeneous = false; - return; - } - - // If none of the above is true, then we must be a standard AppDomain - isFullyTrusted = true; - isHomogeneous = true; - } - - // Called from the VM when either a HostSecurityManager or simple sandbox domain can determine the - // grant set of an assembly - private static PermissionSet ResolveGrantSet(Evidence evidence, out int specialFlags, bool checkExecutionPermission) - { - Contract.Assert(evidence != null); - Contract.Assert(!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); // This API does not do CAS policy resolution - - PermissionSet grantSet = null; - if (!TryResolveGrantSet(evidence, out grantSet)) - { - // If we couldn't figure out a grant set from the domain or the host, then we treat the - // assembly as fully trusted. - grantSet = new PermissionSet(PermissionState.Unrestricted); - } - - // Make sure the grant set includes the ability to execute code if that has been requested. - if (checkExecutionPermission) - { - SecurityPermission executionPermission = new SecurityPermission(SecurityPermissionFlag.Execution); - if (!grantSet.Contains(executionPermission)) - { - throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), - System.__HResults.CORSEC_E_NO_EXEC_PERM); - } - } - - specialFlags = SecurityManager.GetSpecialFlags(grantSet, null); - return grantSet; - } - - // Consult the host and the current AppDomain if it is homogenous to determine what the grant set - // of an assembly is. This API returns true if it was able to determine a grant set for the evidence, - // false if it cannot and other policy needs to be applied. - [SecuritySafeCritical] - internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet) - { - Contract.Assert(evidence != null); - - HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager; - - // GAC assemblies always are fully trusted - if (evidence.GetHostEvidence() != null) - { - grantSet = new PermissionSet(PermissionState.Unrestricted); - return true; - } - // If the host wants to participate in policy resolution, then our next option is to ask it for - // a grant set - else if ((securityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy) - { - PermissionSet hostGrantSet = securityManager.ResolvePolicy(evidence); - - if (hostGrantSet == null) - { - throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", securityManager.GetType().FullName)); - } - - // If we're in a homogenous domain, we don't want to allow the host to create multiple - // levels of permissions within the domain. So, if we see the host return something other - // than full trust or the homogenous grant set, we reject the grant set. - if (AppDomain.CurrentDomain.IsHomogenous) - { - // Some hosts, such as ASP.NET, return Nothing as a way of saying that the assembly should - // not be allowed to run in the AppDomain. Reject that with a specific - // no-execution-allowed-here exception message, rather than the return value validation - // exception message we'd hit below. - if (hostGrantSet.IsEmpty()) - { - throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission")); - } - - PermissionSet homogenousGrantSet = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet; - bool isValidGrantSet = hostGrantSet.IsUnrestricted() || - (hostGrantSet.IsSubsetOf(homogenousGrantSet) && homogenousGrantSet.IsSubsetOf(hostGrantSet)); - - if (!isValidGrantSet) - { - throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", securityManager.GetType().FullName)); - } - } - - grantSet = hostGrantSet; - return true; - } - // If we're in a homogenous domain, we can get the grant set directly from the application trust - else if (AppDomain.CurrentDomain.IsHomogenous) - { - grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence); - return true; - } - // Otherwise we have no way to figure out what the grant set is - else - { - grantSet = null; - return false; - } } -#endif // FEATURE_CAS_POLICY #if FEATURE_PLS // Update the PLS used for optimization in the AppDomain: called from the VM - [System.Security.SecurityCritical] // auto-generated private static PermissionListSet UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms) { if (adPLS == null) { adPLS = new PermissionListSet(); diff --git a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs index 8f25bda617..0ef5afd282 100644 --- a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs +++ b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs @@ -12,6 +12,7 @@ namespace System.Security { using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; #if !FEATURE_PAL using Microsoft.Win32.SafeHandles; @@ -40,10 +41,8 @@ namespace System.Security { // if this frame contains a call to any WindowsIdentity.Impersonate(), // we save the previous SafeTokenHandles here (in the next two fields) // Used during exceptionstackwalks to revert impersonation before calling filters - [System.Security.SecurityCritical] // auto-generated [NonSerialized] private SafeAccessTokenHandle m_callerToken; - [System.Security.SecurityCritical] // auto-generated [NonSerialized] private SafeAccessTokenHandle m_impToken; #endif @@ -56,16 +55,12 @@ namespace System.Security { - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void IncrementOverridesCount(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void DecrementOverridesCount(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void IncrementAssertCount(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void DecrementAssertCount(); @@ -105,14 +100,12 @@ namespace System.Security { // we store declarative actions in both fields, so check if they are different return (m_restriction != null); } - [System.Security.SecurityCritical] // auto-generated internal void SetAssert(IPermission perm) { m_assertions = CreateSingletonSet(perm); IncrementAssertCount(); } - [System.Security.SecurityCritical] // auto-generated internal void SetAssert(PermissionSet permSet) { m_assertions = permSet.Copy(); @@ -125,7 +118,6 @@ namespace System.Security { return (fDeclarative) ? m_DeclarativeAssertions : m_assertions; } - [System.Security.SecurityCritical] // auto-generated internal void SetAssertAllPossible() { m_assertAllPossible = true; @@ -141,19 +133,12 @@ namespace System.Security { // D E N Y //-----------------------------------------------------------+ - [System.Security.SecurityCritical] // auto-generated internal void SetDeny(IPermission perm) { -#if FEATURE_CAS_POLICY - BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode"); -#endif // FEATURE_CAS_POLICY - m_denials = CreateSingletonSet(perm); IncrementOverridesCount(); - } - [System.Security.SecurityCritical] // auto-generated internal void SetDeny(PermissionSet permSet) { m_denials = permSet.Copy(); @@ -169,14 +154,12 @@ namespace System.Security { // R E S T R I C T //-----------------------------------------------------------+ - [System.Security.SecurityCritical] // auto-generated internal void SetPermitOnly(IPermission perm) { m_restriction = CreateSingletonSet(perm); IncrementOverridesCount(); } - [System.Security.SecurityCritical] // auto-generated internal void SetPermitOnly(PermissionSet permSet) { // permSet must not be null @@ -193,7 +176,6 @@ namespace System.Security { //-----------------------------------------------------------+ // SafeAccessTokenHandle (Impersonation + EH purposes) //-----------------------------------------------------------+ - [System.Security.SecurityCritical] // auto-generated internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken) { m_callerToken = callerToken; @@ -204,7 +186,6 @@ namespace System.Security { // R E V E R T //-----------------------------------------------------------+ - [System.Security.SecurityCritical] // auto-generated internal void RevertAssert() { if (m_assertions != null) @@ -224,7 +205,6 @@ namespace System.Security { } } - [System.Security.SecurityCritical] // auto-generated internal void RevertAssertAllPossible() { if (m_assertAllPossible) @@ -234,7 +214,6 @@ namespace System.Security { } } - [System.Security.SecurityCritical] // auto-generated internal void RevertDeny() { if (HasImperativeDenials()) @@ -244,7 +223,6 @@ namespace System.Security { } } - [System.Security.SecurityCritical] // auto-generated internal void RevertPermitOnly() { if (HasImperativeRestrictions()) @@ -254,7 +232,6 @@ namespace System.Security { } } - [System.Security.SecurityCritical] // auto-generated internal void RevertAll() { RevertAssert(); @@ -270,7 +247,6 @@ namespace System.Security { // This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { // imperative security @@ -283,13 +259,12 @@ namespace System.Security { return fContinue; } - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative) { PermissionSet permSet; // If the demand is null, there is no need to continue - Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); + Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); // decode imperative if (GetPermitOnly(fDeclarative) != null) @@ -397,7 +372,6 @@ namespace System.Security { return SecurityRuntime.StackContinue; } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand(PermissionSet demandSet, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) @@ -429,7 +403,6 @@ namespace System.Security { return fContinue; } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand2(PermissionSet demandSet, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh, bool fDeclarative) diff --git a/src/mscorlib/src/System/Security/HostProtectionException.cs b/src/mscorlib/src/System/Security/HostProtectionException.cs index 83f005fe9b..b08fccd1b3 100644 --- a/src/mscorlib/src/System/Security/HostProtectionException.cs +++ b/src/mscorlib/src/System/Security/HostProtectionException.cs @@ -53,7 +53,7 @@ namespace System.Security protected HostProtectionException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info==null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); m_protected = (HostProtectionResource)info.GetValue(ProtectedResourcesName, typeof(HostProtectionResource)); @@ -120,11 +120,10 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); base.GetObjectData( info, context ); diff --git a/src/mscorlib/src/System/Security/HostSecurityManager.cs b/src/mscorlib/src/System/Security/HostSecurityManager.cs index 46d5552478..53137983d3 100644 --- a/src/mscorlib/src/System/Security/HostSecurityManager.cs +++ b/src/mscorlib/src/System/Security/HostSecurityManager.cs @@ -9,13 +9,9 @@ // participate in the security decisions in the AppDomain. // -namespace System.Security { +namespace System.Security +{ using System.Collections; -#if FEATURE_CLICKONCE - using System.Deployment.Internal.Isolation; - using System.Deployment.Internal.Isolation.Manifest; - using System.Runtime.Hosting; -#endif using System.Reflection; using System.Security; using System.Security.Permissions; @@ -24,7 +20,7 @@ namespace System.Security { using System.Diagnostics.Contracts; -[Serializable] + [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum HostSecurityManagerOptions { @@ -38,11 +34,7 @@ namespace System.Security { AllFlags = 0x001F } - [System.Security.SecurityCritical] // auto-generated_required [Serializable] -#if !FEATURE_CORECLR - [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)] -#endif [System.Runtime.InteropServices.ComVisible(true)] public class HostSecurityManager { public HostSecurityManager () {} @@ -56,20 +48,6 @@ namespace System.Security { } } -#if FEATURE_CAS_POLICY - // provide policy for the AppDomain. - [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public virtual PolicyLevel DomainPolicy { - get { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - return null; - } - } -#endif public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) { // The default implementation does not modify the input evidence. return inputEvidence; @@ -80,109 +58,6 @@ namespace System.Security { return inputEvidence; } -#if FEATURE_CLICKONCE - [System.Security.SecurityCritical] // auto-generated - [SecurityPermissionAttribute(SecurityAction.Assert, Unrestricted=true)] - public virtual ApplicationTrust DetermineApplicationTrust(Evidence applicationEvidence, Evidence activatorEvidence, TrustManagerContext context) - { - if (applicationEvidence == null) - throw new ArgumentNullException("applicationEvidence"); - Contract.EndContractBlock(); - - // This method looks for a trust decision for the ActivationContext in three locations, in order - // of preference: - // - // 1. Supplied by the host in the AppDomainSetup. If the host supplied a decision this way, it - // will be in the applicationEvidence. - // 2. Reuse the ApplicationTrust from the current AppDomain - // 3. Ask the TrustManager for a trust decision - - // get the activation context from the application evidence. - // The default HostSecurityManager does not examine the activatorEvidence - // but other security managers could use it to figure out the - // evidence of the domain attempting to activate the application. - - ActivationArguments activationArgs = applicationEvidence.GetHostEvidence(); - if (activationArgs == null) - throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence")); - - ActivationContext actCtx = activationArgs.ActivationContext; - if (actCtx == null) - throw new ArgumentException(Environment.GetResourceString("Policy_MissingActivationContextInAppEvidence")); - - // Make sure that any ApplicationTrust we find applies to the ActivationContext we're - // creating the new AppDomain for. - ApplicationTrust appTrust = applicationEvidence.GetHostEvidence(); - if (appTrust != null && - !CmsUtils.CompareIdentities(appTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion)) - { - appTrust = null; - } - - // If there was not a trust decision supplied in the Evidence, we can reuse the existing trust - // decision from this domain if its identity matches the ActivationContext of the new domain. - // Otherwise consult the TrustManager for a trust decision - if (appTrust == null) - { - if (AppDomain.CurrentDomain.ApplicationTrust != null && - CmsUtils.CompareIdentities(AppDomain.CurrentDomain.ApplicationTrust.ApplicationIdentity, activationArgs.ApplicationIdentity, ApplicationVersionMatch.MatchExactVersion)) - { - appTrust = AppDomain.CurrentDomain.ApplicationTrust; - } - else - { - appTrust = ApplicationSecurityManager.DetermineApplicationTrustInternal(actCtx, context); - } - } - - // If the trust decision allows the application to run, then it should also have a permission set - // which is at least the permission set the application requested. - ApplicationSecurityInfo appRequest = new ApplicationSecurityInfo(actCtx); - if (appTrust != null && - appTrust.IsApplicationTrustedToRun && - !appRequest.DefaultRequestSet.IsSubsetOf(appTrust.DefaultGrantSet.PermissionSet)) - { - throw new InvalidOperationException(Environment.GetResourceString("Policy_AppTrustMustGrantAppRequest")); - } - - return appTrust; - } -#endif // FEATURE_CLICKONCE - -#if FEATURE_CAS_POLICY - // Query the CLR to see what it would have granted a specific set of evidence - public virtual PermissionSet ResolvePolicy(Evidence evidence) - { - if (evidence == null) - throw new ArgumentNullException("evidence"); - Contract.EndContractBlock(); - - // - // If the evidence is from the GAC then the result is full trust. - // In a homogenous domain, then the application trust object provides the grant set. - // When CAS policy is disabled, the result is full trust. - // Otherwise, the result comes from evaluating CAS policy. - // - - if (evidence.GetHostEvidence() != null) - { - return new PermissionSet(PermissionState.Unrestricted); - } - else if (AppDomain.CurrentDomain.IsHomogenous) - { - return AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence); - } - else if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - return new PermissionSet(PermissionState.Unrestricted); - } - else - { - return SecurityManager.PolicyManager.CodeGroupResolve(evidence, false); - } - } -#endif - /// /// Determine what types of evidence the host might be able to supply for the AppDomain if requested /// diff --git a/src/mscorlib/src/System/Security/IEvidenceFactory.cs b/src/mscorlib/src/System/Security/IEvidenceFactory.cs index 93f82a6420..592ab533be 100644 --- a/src/mscorlib/src/System/Security/IEvidenceFactory.cs +++ b/src/mscorlib/src/System/Security/IEvidenceFactory.cs @@ -2,19 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security { - using System.Runtime.Remoting; - using System; - using System.Security.Policy; -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface IEvidenceFactory { -#if FEATURE_CAS_POLICY - Evidence Evidence - { - get; - } -#endif // FEATURE_CAS_POLICY } - } diff --git a/src/mscorlib/src/System/Security/ISecurityEncodable.cs b/src/mscorlib/src/System/Security/ISecurityEncodable.cs index 9915da3696..689b3e4b5f 100644 --- a/src/mscorlib/src/System/Security/ISecurityEncodable.cs +++ b/src/mscorlib/src/System/Security/ISecurityEncodable.cs @@ -8,22 +8,10 @@ // implement this interface // -namespace System.Security { - - using System; - using System.Security.Util; - - -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface ISecurityEncodable { -#if FEATURE_CAS_POLICY - SecurityElement ToXml(); - - void FromXml( SecurityElement e ); -#endif // FEATURE_CAS_POLICY } - } - - diff --git a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs index b1c8d1654f..567e41e891 100644 --- a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs +++ b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs @@ -8,21 +8,10 @@ // implement this interface // -namespace System.Security { - - using System; - using System.Security.Util; - using System.Security.Policy; - - -[System.Runtime.InteropServices.ComVisible(true)] +namespace System.Security +{ + [System.Runtime.InteropServices.ComVisible(true)] public interface ISecurityPolicyEncodable { -#if FEATURE_CAS_POLICY - SecurityElement ToXml( PolicyLevel level ); - - void FromXml( SecurityElement e, PolicyLevel level ); -#endif // FEATURE_CAS_POLICY } - } diff --git a/src/mscorlib/src/System/Security/NamedPermissionSet.cs b/src/mscorlib/src/System/Security/NamedPermissionSet.cs index fba76749a1..1bc166fde8 100644 --- a/src/mscorlib/src/System/Security/NamedPermissionSet.cs +++ b/src/mscorlib/src/System/Security/NamedPermissionSet.cs @@ -7,212 +7,19 @@ // Extends PermissionSet to allow an associated name and description // -namespace System.Security { - +namespace System.Security +{ using System; - using System.Security.Util; using System.Security.Permissions; - using System.Runtime.Serialization; - using System.Diagnostics.Contracts; -#if !FEATURE_CAS_POLICY - using Microsoft.Win32; - using System.Collections; - using System.Globalization; - using System.IO; - using System.Reflection; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.Runtime.Versioning; - using System.Text; - -#else // FEATURE_CAS_POLICY - - using System.Threading; - -#endif // FEATURE_CAS_POLICY - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public sealed class NamedPermissionSet : PermissionSet { -#if FEATURE_CAS_POLICY - // The name of this PermissionSet - private String m_name; - - // The description of this PermissionSet - private String m_description; - [OptionalField(VersionAdded = 2)] - internal String m_descrResource; - - internal NamedPermissionSet() - : base() - { - } - - public NamedPermissionSet( String name ) - : base() - { - CheckName( name ); - m_name = name; - } - - public NamedPermissionSet( String name, PermissionState state) - : base( state ) - { - CheckName( name ); - m_name = name; - } - - - public NamedPermissionSet( String name, PermissionSet permSet ) - : base( permSet ) - { - CheckName( name ); - m_name = name; - } - - public NamedPermissionSet( NamedPermissionSet permSet ) - : base( permSet ) - { - m_name = permSet.m_name; - m_description = permSet.Description; - } - - internal NamedPermissionSet(SecurityElement permissionSetXml) - : base(PermissionState.None) - { - Contract.Assert(permissionSetXml != null); - FromXml(permissionSetXml); - } - - public String Name { - get { return m_name; } - set { CheckName( value ); m_name = value; } - } - - private static void CheckName( String name ) - { - if (name == null || name.Equals( "" )) - throw new ArgumentException( Environment.GetResourceString( "Argument_NPMSInvalidName" )); - Contract.EndContractBlock(); - } - - public String Description { - get - { - if(m_descrResource != null) - { - m_description = Environment.GetResourceString(m_descrResource); - m_descrResource = null; - } - return m_description; - } - - set - { - m_description = value; - m_descrResource = null; - } - } - - public override PermissionSet Copy() - { - return new NamedPermissionSet( this ); - } - - public NamedPermissionSet Copy( String name ) - { - NamedPermissionSet set = new NamedPermissionSet( this ); - set.Name = name; - return set; - } - - public override SecurityElement ToXml() - { - SecurityElement elem = base.ToXml("System.Security.NamedPermissionSet"); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.NamedPermissionSet" ), "Class name changed!" ); - - if (m_name != null && !m_name.Equals( "" )) - { - elem.AddAttribute( "Name", SecurityElement.Escape( m_name ) ); - } - - if (Description != null && !Description.Equals( "" )) - { - elem.AddAttribute( "Description", SecurityElement.Escape( Description ) ); - } - - return elem; - } - - public override void FromXml( SecurityElement et ) - { - FromXml( et, false, false ); - } - - internal override void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures ) - { - if (et == null) - throw new ArgumentNullException( "et" ); - Contract.EndContractBlock(); - - String elem; - - elem = et.Attribute( "Name" ); - m_name = elem == null ? null : elem; - - elem = et.Attribute( "Description" ); - m_description = (elem == null ? "" : elem); - m_descrResource = null; - - base.FromXml( et, allowInternalOnly, ignoreTypeLoadFailures ); - } - - internal void FromXmlNameOnly( SecurityElement et ) + internal static PermissionSet GetBuiltInSet(string name) { - // This function gets only the name for the permission set, ignoring all other info. - - String elem; - - elem = et.Attribute( "Name" ); - m_name = (elem == null ? null : elem); - } - - // NamedPermissionSet Equals should have the exact semantic as PermissionSet. - // We explicitly override them here to make sure that no one accidently - // changes this. - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals( Object obj ) - { - return base.Equals( obj ); - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - return base.GetHashCode(); - } - - private static Object s_InternalSyncObject; - private static Object InternalSyncObject { - get { - if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); - } - return s_InternalSyncObject; - } - } -#else // FEATURE_CAS_POLICY - - internal static PermissionSet GetBuiltInSet(string name) { // Used by PermissionSetAttribute to create one of the built-in, // immutable permission sets. - if (name == null) return null; else if (name.Equals("FullTrust")) @@ -264,6 +71,5 @@ namespace System.Security { } -#endif // !FEATURE_CAS_POLICY } } diff --git a/src/mscorlib/src/System/Security/PermissionListSet.cs b/src/mscorlib/src/System/Security/PermissionListSet.cs index 7eb13a72cf..093542ad4e 100644 --- a/src/mscorlib/src/System/Security/PermissionListSet.cs +++ b/src/mscorlib/src/System/Security/PermissionListSet.cs @@ -23,6 +23,7 @@ namespace System.Security using System.Threading; using System.Collections; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -53,15 +54,13 @@ namespace System.Security } #if FEATURE_PLS - [System.Security.SecurityCritical] // auto-generated internal void UpdateDomainPLS (PermissionListSet adPLS) { if (adPLS != null && adPLS.m_firstPermSetTriple != null) UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet); } - [System.Security.SecurityCritical] // auto-generated internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) { - Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null"); + Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null"); if (m_firstPermSetTriple == null) m_firstPermSetTriple = new PermissionSetTriple(); @@ -76,7 +75,6 @@ namespace System.Security UpdateTripleListAndCreateNewTriple(currentTriple, null); } - [System.Security.SecurityCritical] // auto-generated private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls) { #if FEATURE_COMPRESSEDSTACK @@ -86,7 +84,6 @@ namespace System.Security this.UpdateTripleListAndCreateNewTriple(currentTriple, null); } - [System.Security.SecurityCritical] // auto-generated private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls) { #if FEATURE_COMPRESSEDSTACK @@ -95,7 +92,6 @@ namespace System.Security return this.UpdatePermissions(currentTriple, pls); } - [System.Security.SecurityCritical] // auto-generated private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd) { #if FEATURE_COMPRESSEDSTACK @@ -117,7 +113,6 @@ namespace System.Security } #if FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver) { System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver; @@ -127,7 +122,6 @@ namespace System.Security } #endif // FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative) { // Deny @@ -187,7 +181,6 @@ namespace System.Security return false; } - [System.Security.SecurityCritical] // auto-generated private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r) { #if FEATURE_COMPRESSEDSTACK @@ -203,7 +196,6 @@ namespace System.Security } // Called from the VM for HG CS construction - [System.Security.SecurityCritical] // auto-generated private void Update(PermissionSet in_g) { if (m_firstPermSetTriple == null) @@ -226,7 +218,6 @@ namespace System.Security } #endif // FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] // auto-generated private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls) { if (pls != null) @@ -322,7 +313,6 @@ namespace System.Security } } -[System.Security.SecurityCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] // public(internal) interface begins... // Creation functions @@ -370,7 +360,6 @@ namespace System.Security return pls; } - [System.Security.SecurityCritical] // auto-generated static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction) { PermissionListSet pls = new PermissionListSet(); @@ -411,7 +400,6 @@ namespace System.Security return pls; } - [System.Security.SecurityCritical] // auto-generated static internal PermissionListSet CreateCompressedState_HG() { PermissionListSet pls = new PermissionListSet(); @@ -420,11 +408,10 @@ namespace System.Security } #endif // #if FEATURE_COMPRESSEDSTACK // Private Demand evaluation functions - only called from the VM - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemandNoThrow(CodeAccessPermission demand) { // AppDomain permissions - no asserts. So there should only be one triple to work with - Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); + Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); @@ -436,18 +423,16 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemandNoThrow(PermissionSet pSet) { // AppDomain permissions - no asserts. So there should only be one triple to work with - Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); + Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet); } // Demand evauation functions - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; @@ -467,7 +452,6 @@ namespace System.Security return bRet; } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh) { PermissionSet unused; @@ -475,7 +459,6 @@ namespace System.Security return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk } - [System.Security.SecurityCritical] internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) { bool bRet = SecurityRuntime.StackContinue; @@ -503,10 +486,9 @@ namespace System.Security /// Check to see if the PLS satisfies a demand for the special permissions encoded in flags /// /// set of flags to check (See PermissionType) - [System.Security.SecurityCritical] // auto-generated private bool CheckFlags(int flags) { - Contract.Assert(flags != 0, "Invalid permission flag demand"); + Debug.Assert(flags != 0, "Invalid permission flag demand"); bool check = true; @@ -531,7 +513,6 @@ namespace System.Security /// /// set of flags to check (See PermissionType) /// alternate permission set to check - [System.Security.SecurityCritical] // auto-generated internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet) { if (CheckFlags(flags)) diff --git a/src/mscorlib/src/System/Security/PermissionSet.cs b/src/mscorlib/src/System/Security/PermissionSet.cs index e36f0752ad..11ca02a81e 100644 --- a/src/mscorlib/src/System/Security/PermissionSet.cs +++ b/src/mscorlib/src/System/Security/PermissionSet.cs @@ -21,6 +21,7 @@ namespace System.Security { using System.Text; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -35,9 +36,6 @@ namespace System.Security { #if FEATURE_SERIALIZATION [Serializable] -#endif -#if !FEATURE_CORECLR - [StrongNameIdentityPermissionAttribute(SecurityAction.InheritanceDemand, Name = "mscorlib", PublicKey = "0x" + AssemblyRef.EcmaPublicKeyFull)] #endif [System.Runtime.InteropServices.ComVisible(true)] public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk @@ -114,71 +112,13 @@ namespace System.Security { internal static readonly PermissionSet s_fullTrust = new PermissionSet( true ); -#if FEATURE_REMOTING - [OnDeserializing] - private void OnDeserializing(StreamingContext ctx) - { - Reset(); - } - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - if (m_serializedPermissionSet != null) - { - // Whidbey non X-AD case - FromXml(SecurityElement.FromString(m_serializedPermissionSet)); - } - else if (m_normalPermSet != null) - { - // Everett non X-AD case - m_permSet = m_normalPermSet.SpecialUnion(m_unrestrictedPermSet); - } - else if (m_unrestrictedPermSet != null) - { - // Everett non X-AD case - m_permSet = m_unrestrictedPermSet.SpecialUnion(m_normalPermSet); - } - - m_serializedPermissionSet = null; - m_normalPermSet = null; - m_unrestrictedPermSet = null; - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermissionSet = ToString(); // For v2.x and beyond - if (m_permSet != null) - m_permSet.SpecialSplit(ref m_unrestrictedPermSet, ref m_normalPermSet, m_ignoreTypeLoadFailures); - m_permSetSaved = m_permSet; - m_permSet = null; - } - } -#endif // !FEATURE_REMOTING - -#if FEATURE_REMOTING || _DEBUG +#if _DEBUG [OnSerialized] private void OnSerialized(StreamingContext context) { -#if FEATURE_REMOTING - if ((context.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermissionSet = null; - m_permSet = m_permSetSaved; - m_permSetSaved = null; - m_unrestrictedPermSet = null; - m_normalPermSet = null; - } -#else // !FEATURE_REMOTING - Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR"); -#endif // !FEATURE_REMOTING + Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR"); } -#endif // FEATURE_REMOTING || _DEBUG +#endif // _DEBUG internal PermissionSet() { @@ -233,19 +173,11 @@ namespace System.Security { { Object obj = m_permSet.GetItem(i); IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory elem = obj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY + if (perm != null) { m_permSet.SetItem(i, perm.Copy()); } -#if FEATURE_CAS_POLICY - else if (elem != null) - { - m_permSet.SetItem(i, elem.Copy()); - } -#endif // FEATURE_CAS_POLICY } } } @@ -253,7 +185,7 @@ namespace System.Security { public virtual void CopyTo(Array array, int index) { if (array == null) - throw new ArgumentNullException( "array" ); + throw new ArgumentNullException( nameof(array) ); Contract.EndContractBlock(); PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); @@ -365,19 +297,7 @@ namespace System.Security { Object obj = m_permSet.GetItem( index ); if (obj == null) return null; - IPermission perm = obj as IPermission; - if (perm != null) - return perm; -#if FEATURE_CAS_POLICY - perm = CreatePermission(obj, index); -#endif // FEATURE_CAS_POLICY - if (perm == null) - return null; - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), - "PermissionToken was improperly assigned" ); - Contract.Assert( PermissionToken.GetToken( perm ).m_index == index, - "Assigning permission to incorrect index in tokenbasedset" ); - return perm; + return obj as IPermission; } internal IPermission GetPermission(PermissionToken permToken) @@ -396,21 +316,6 @@ namespace System.Security { return GetPermission(PermissionToken.GetToken( perm )); } -#if FEATURE_CAS_POLICY - public IPermission GetPermission(Type permClass) - { - return GetPermissionImpl(permClass); - } - - protected virtual IPermission GetPermissionImpl(Type permClass) - { - if (permClass == null) - return null; - - return GetPermission(PermissionToken.FindToken(permClass)); - } -#endif // FEATURE_CAS_POLICY - public IPermission SetPermission(IPermission perm) { return SetPermissionImpl(perm); @@ -494,29 +399,6 @@ namespace System.Security { return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission } -#if FEATURE_CAS_POLICY - public IPermission RemovePermission(Type permClass) - { - return RemovePermissionImpl(permClass); - } - - protected virtual IPermission RemovePermissionImpl(Type permClass) - { - if (permClass == null) - { - return null; - } - - PermissionToken permToken = PermissionToken.FindToken(permClass); - if (permToken == null) - { - return null; - } - - return RemovePermission(permToken.m_index); - } -#endif // FEATURE_CAS_POLICY - // Make this internal soon. internal void SetUnrestricted(bool unrestricted) { @@ -527,12 +409,12 @@ namespace System.Security { m_permSet = null; } } - + public bool IsUnrestricted() { return m_Unrestricted; } - + internal enum IsSubsetOfType { Normal, @@ -580,7 +462,7 @@ namespace System.Security { IPermission targetPerm = target.GetPermission(i); #if _DEBUG PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); + Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); #endif if (target.m_Unrestricted) @@ -692,7 +574,7 @@ namespace System.Security { internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm ) { - Contract.Assert( demandedPerm != null, "Expected non-null value" ); + Debug.Assert( demandedPerm != null, "Expected non-null value" ); if (this.m_allPermissionsDecoded || this.m_permSet == null) return; @@ -700,7 +582,7 @@ namespace System.Security { if (tokenDemandedPerm == null) tokenDemandedPerm = PermissionToken.GetToken( demandedPerm ); - Contract.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" ); + Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" ); CheckDecoded( tokenDemandedPerm.m_index ); } @@ -715,7 +597,7 @@ namespace System.Security { internal void CheckDecoded(PermissionSet demandedSet) { - Contract.Assert(demandedSet != null, "Expected non-null value"); + Debug.Assert(demandedSet != null, "Expected non-null value"); if (this.m_allPermissionsDecoded || this.m_permSet == null) return; @@ -728,37 +610,6 @@ namespace System.Security { } } -#if FEATURE_CAS_POLICY - static internal void SafeChildAdd( SecurityElement parent, ISecurityElementFactory child, bool copy ) - { - if (child == parent) - return; - if (child.GetTag().Equals( "IPermission" ) || child.GetTag().Equals( "Permission" )) - { - parent.AddChild( child ); - } - else if (parent.Tag.Equals( child.GetTag() )) - { - Contract.Assert( child is SecurityElement, "SecurityElement expected" ); - SecurityElement elChild = (SecurityElement)child; - Contract.Assert( elChild.InternalChildren != null, - "Non-permission elements should have children" ); - - for (int i = 0; i < elChild.InternalChildren.Count; ++i) - { - ISecurityElementFactory current = (ISecurityElementFactory)elChild.InternalChildren[i]; - Contract.Assert( !current.GetTag().Equals( parent.Tag ), - "Illegal to insert a like-typed element" ); - parent.AddChildNoDuplicates( current ); - } - } - else - { - parent.AddChild( (ISecurityElementFactory)(copy ? child.Copy() : child) ); - } - } -#endif // FEATURE_CAS_POLICY - internal void InplaceIntersect( PermissionSet other ) { Exception savedException = null; @@ -796,81 +647,24 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - // If we already have an intersection node, just add another child - if (thisElem.GetTag().Equals( s_str_PermissionIntersection ) || - thisElem.GetTag().Equals( s_str_PermissionUnrestrictedIntersection )) - { - Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" ); - SafeChildAdd( (SecurityElement)thisElem, otherElem, true ); - } - // If either set is unrestricted, intersect the nodes unrestricted - else - { - bool copyOther = true; - if (this.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, thisElem, false ); - thisElem = newElemUU; - } - if (other.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, otherElem, true ); - otherElem = newElemUU; - copyOther = false; - } - - SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - - SafeChildAdd( newElem, thisElem, false ); - SafeChildAdd( newElem, otherElem, copyOther ); - this.m_permSet.SetItem( i, newElem ); - } - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { // There is no object in , so intersection is empty except for IUnrestrictedPermissions if (this.IsUnrestricted()) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElem, otherElem, true ); - this.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { this.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -879,16 +673,6 @@ namespace System.Security { { if (other.IsUnrestricted()) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, false ); - this.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) == 0) @@ -902,13 +686,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - try { IPermission intersectPerm; @@ -968,71 +745,23 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY - Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - bool copyOther = true; - bool copyThis = true; - SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - if (this.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, thisElem, true ); - copyThis = false; - thisElem = newElemUU; - } - if (other.IsUnrestricted()) - { - SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElemUU, otherElem, true ); - copyOther = false; - otherElem = newElemUU; - } - - SafeChildAdd( newElem, otherElem, copyOther ); - SafeChildAdd( newElem, thisElem, copyThis ); - pset.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { if (this.m_Unrestricted) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", otherElem.Attribute( "class" ) ); - SafeChildAdd( newElem, otherElem, true ); - pset.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { pset.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } @@ -1041,37 +770,19 @@ namespace System.Security { { if (other.m_Unrestricted) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, true ); - pset.m_permSet.SetItem( i, newElem ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (thisPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) { pset.m_permSet.SetItem( i, thisPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - IPermission intersectPerm; if (thisPerm == null) intersectPerm = otherPerm; @@ -1080,7 +791,7 @@ namespace System.Security { else intersectPerm = thisPerm.Intersect( otherPerm ); pset.m_permSet.SetItem( i, intersectPerm ); - Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } @@ -1102,13 +813,9 @@ namespace System.Security { // Quick out conditions, union doesn't change this PermissionSet if (other == null || other.FastIsEmpty()) return; - - - m_CheckedForNonCas = false; - + m_CheckedForNonCas = false; - this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted; if (this.m_Unrestricted) @@ -1124,7 +831,7 @@ namespace System.Security { int maxMax = -1; if (other.m_permSet != null) { - maxMax = other.m_permSet.GetMaxUsedIndex(); + maxMax = other.m_permSet.GetMaxUsedIndex(); this.CheckSet(); } // Save exceptions until the end @@ -1134,52 +841,15 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - if (thisElem.GetTag().Equals( s_str_PermissionUnion ) || - thisElem.GetTag().Equals( s_str_PermissionUnrestrictedUnion )) - { - Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" ); - SafeChildAdd( (SecurityElement)thisElem, otherElem, true ); - } - else - { - SecurityElement newElem; - if (this.IsUnrestricted() || other.IsUnrestricted()) - newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - else - newElem = new SecurityElement( s_str_PermissionUnion ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, false ); - SafeChildAdd( newElem, otherElem, true ); - this.m_permSet.SetItem( i, newElem ); - } - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - this.m_permSet.SetItem( i, otherElem.Copy() ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); @@ -1195,13 +865,6 @@ namespace System.Security { } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - try { IPermission unionPerm; @@ -1260,82 +923,39 @@ namespace System.Security { { Object thisObj = this.m_permSet.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = other.m_permSet.GetItem( i ); IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; -#if FEATURE_CAS_POLICY - if (thisElem != null && otherElem != null) - { - SecurityElement newElem; - if (this.IsUnrestricted() || other.IsUnrestricted()) - newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion ); - else - newElem = new SecurityElement( s_str_PermissionUnion ); - newElem.AddAttribute( "class", thisElem.Attribute( "class" ) ); - SafeChildAdd( newElem, thisElem, true ); - SafeChildAdd( newElem, otherElem, true ); - pset.m_permSet.SetItem( i, newElem ); - } - else -#endif // FEATURE_CAS_POLICY if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - pset.m_permSet.SetItem( i, otherElem.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - else -#endif // FEATURE_CAS_POLICY if (otherPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted) { pset.m_permSet.SetItem( i, otherPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } else if (otherObj == null) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - pset.m_permSet.SetItem( i, thisElem.Copy() ); - } - else -#endif // FEATURE_CAS_POLICY if (thisPerm != null) { PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted) { pset.m_permSet.SetItem( i, thisPerm.Copy() ); - Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } } else { -#if FEATURE_CAS_POLICY - if (thisElem != null) - thisPerm = this.CreatePermission(thisElem, i); - if (otherElem != null) - otherPerm = other.CreatePermission(otherElem, i); -#endif // FEATURE_CAS_POLICY - IPermission unionPerm; if(thisPerm == null) unionPerm = otherPerm; @@ -1344,10 +964,10 @@ namespace System.Security { else unionPerm = thisPerm.Union( otherPerm ); pset.m_permSet.SetItem( i, unionPerm ); - Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); + Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); } } - + return pset; } @@ -1492,7 +1112,6 @@ namespace System.Security { // Mark this method as requiring a security object on the caller's frame // so the caller won't be inlined (which would mess up stack crawling). - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void Demand() @@ -1513,7 +1132,6 @@ namespace System.Security { } } - [System.Security.SecurityCritical] // auto-generated internal void DemandNonCAS() { ContainsNonCodeAccessPermissions(); @@ -1536,7 +1154,6 @@ namespace System.Security { // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void Assert() @@ -1548,7 +1165,6 @@ namespace System.Security { // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] @@ -1561,7 +1177,6 @@ namespace System.Security { // Metadata for this method should be flaged with REQ_SQ so that // EE can allocate space on the stack frame for FrameSecurityDescriptor - [System.Security.SecuritySafeCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public void PermitOnly() @@ -1588,21 +1203,7 @@ namespace System.Security { { // Explicitly make a new PermissionSet, rather than copying, since we may have a // ReadOnlyPermissionSet which cannot have identity permissions removed from it in a true copy. - PermissionSet copy = new PermissionSet(this); - - // There's no easy way to distinguish an identity permission from any other CodeAccessPermission, - // so remove them directly. -#if FEATURE_CAS_POLICY - copy.RemovePermission(typeof(GacIdentityPermission)); -#if FEATURE_X509 - copy.RemovePermission(typeof(PublisherIdentityPermission)); -#endif - copy.RemovePermission(typeof(StrongNameIdentityPermission)); - copy.RemovePermission(typeof(UrlIdentityPermission)); - copy.RemovePermission(typeof(ZoneIdentityPermission)); -#endif // FEATURE_CAS_POLICY - - return copy; + return new PermissionSet(this); } public IEnumerator GetEnumerator() @@ -1620,13 +1221,6 @@ namespace System.Security { return new PermissionSetEnumeratorInternal(this); } -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - private void NormalizePermissionSet() { // This function guarantees that all the permissions are placed at @@ -1645,12 +1239,6 @@ namespace System.Security { { Object obj = this.m_permSet.GetItem(i); IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory elem = obj as ISecurityElementFactory; - - if (elem != null) - perm = CreatePerm( elem ); -#endif // FEATURE_CAS_POLICY if (perm != null) permSetTemp.SetPermission( perm ); } @@ -1659,29 +1247,6 @@ namespace System.Security { this.m_permSet = permSetTemp.m_permSet; } -#if FEATURE_CAS_POLICY - private bool DecodeXml(byte[] data, HostProtectionResource fullTrustOnlyResources, HostProtectionResource inaccessibleResources ) - { - if (data != null && data.Length > 0) - { - FromXml( new Parser( data, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() ); - } - - FilterHostProtectionPermissions(fullTrustOnlyResources, inaccessibleResources); - - // We call this method from unmanaged to code a set we are going to use declaratively. In - // this case, all the lazy evaluation for partial policy resolution is wasted since we'll - // need to decode all of these shortly to make the demand for whatever. Therefore, we - // pay that price now so that we can calculate whether all the permissions in the set - // implement the IUnrestrictedPermission interface (the common case) for use in some - // unmanaged optimizations. - - DecodeAllPermissions(); - - return true; - } -#endif // FEATURE_CAS_POLICY - private void DecodeAllPermissions() { if (m_permSet == null) @@ -1710,11 +1275,7 @@ namespace System.Security { HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly)); if (newHpp == null) { -#if FEATURE_CAS_POLICY - RemovePermission(typeof(HostProtectionPermission)); -#else // !FEATURE_CAS_POLICY RemovePermission(HostProtectionPermission.GetTokenIndex()); -#endif // FEATURE_CAS_POLICY } else if (newHpp.Resources != hpp.Resources) { @@ -1722,539 +1283,8 @@ namespace System.Security { } } -#if FEATURE_CAS_POLICY - public virtual void FromXml( SecurityElement et ) - { - FromXml( et, false, false ); - } - - internal static bool IsPermissionTag( String tag, bool allowInternalOnly ) - { - if (tag.Equals( s_str_Permission ) || - tag.Equals( s_str_IPermission )) - { - return true; - } - - if (allowInternalOnly && - (tag.Equals( s_str_PermissionUnion ) || - tag.Equals( s_str_PermissionIntersection ) || - tag.Equals( s_str_PermissionUnrestrictedIntersection ) || - tag.Equals( s_str_PermissionUnrestrictedUnion))) - { - return true; - } - - return false; - } - - internal virtual void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures ) - { - if (et == null) - throw new ArgumentNullException("et"); - - if (!et.Tag.Equals(s_str_PermissionSet)) - throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "PermissionSet", this.GetType().FullName) ); - Contract.EndContractBlock(); - - Reset(); - m_ignoreTypeLoadFailures = ignoreTypeLoadFailures; - m_allPermissionsDecoded = false; - m_Unrestricted = XMLUtil.IsUnrestricted( et ); - - if (et.InternalChildren != null) - { - int childCount = et.InternalChildren.Count; - for (int i = 0; i < childCount; ++i) - { - SecurityElement elem = (SecurityElement)et.Children[i]; - - if (IsPermissionTag( elem.Tag, allowInternalOnly )) - { - String className = elem.Attribute( "class" ); - - PermissionToken token; - Object objectToInsert; - - if (className != null) - { - token = PermissionToken.GetToken( className ); - if (token == null) - { - objectToInsert = CreatePerm( elem ); -#if _DEBUG - PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert( tokenDebug != null && (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" ); -#endif - if (objectToInsert != null) - { - Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(), - "PermissionToken.GetToken returned null for non-mscorlib permission" ); - token = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" ); - } - } - else - { - objectToInsert = elem; - } - } - else - { - IPermission ip = CreatePerm( elem ); - if (ip == null) - { - token = null; - objectToInsert = null; - } - else - { - token = PermissionToken.GetToken( ip ); - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ), - "PermissionToken was improperly assigned" ); - objectToInsert = ip; - } - } - - if (token != null && objectToInsert != null) - { - if (m_permSet == null) - m_permSet = new TokenBasedSet(); - - if (this.m_permSet.GetItem( token.m_index ) != null) - { - // If there is already something in that slot, let's union them - // together. - - IPermission permInSlot; - - if (this.m_permSet.GetItem( token.m_index ) is IPermission) - permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index ); - else - permInSlot = CreatePerm( (SecurityElement)this.m_permSet.GetItem( token.m_index ) ); - - if (objectToInsert is IPermission) - objectToInsert = ((IPermission)objectToInsert).Union( permInSlot ); - else - objectToInsert = CreatePerm( (SecurityElement)objectToInsert ).Union( permInSlot ); - } - - if(m_Unrestricted && objectToInsert is IPermission) - objectToInsert = null; - - this.m_permSet.SetItem( token.m_index, objectToInsert ); - } - } - } - } - } - - internal virtual void FromXml( SecurityDocument doc, int position, bool allowInternalOnly ) - { - if (doc == null) - throw new ArgumentNullException("doc"); - Contract.EndContractBlock(); - - if (!doc.GetTagForElement( position ).Equals(s_str_PermissionSet)) - throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "PermissionSet", this.GetType().FullName) ); - - Reset(); - m_allPermissionsDecoded = false; - Exception savedException = null; - String strUnrestricted = doc.GetAttributeForElement( position, "Unrestricted" ); - if (strUnrestricted != null) - m_Unrestricted = strUnrestricted.Equals( "True" ) || strUnrestricted.Equals( "true" ) || strUnrestricted.Equals( "TRUE" ); - else - m_Unrestricted = false; - - ArrayList childrenIndices = doc.GetChildrenPositionForElement( position ); - int childCount = childrenIndices.Count; - for (int i = 0; i < childCount; ++i) - { - int childIndex = (int)childrenIndices[i]; - if (IsPermissionTag( doc.GetTagForElement( childIndex ), allowInternalOnly )) - { - try - { - String className = doc.GetAttributeForElement( childIndex, "class" ); - - PermissionToken token; - Object objectToInsert; - - if (className != null) - { - token = PermissionToken.GetToken( className ); - if (token == null) - { - objectToInsert = CreatePerm( doc.GetElement( childIndex, true ) ); - - if (objectToInsert != null) - { -#if _DEBUG - PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert((tokenDebug != null), "PermissionToken.GetToken returned null "); - Contract.Assert( (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" ); -#endif - Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(), - "PermissionToken.GetToken returned null for non-mscorlib permission" ); - token = PermissionToken.GetToken( (IPermission)objectToInsert ); - Contract.Assert((token != null), "PermissionToken.GetToken returned null "); - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" ); - } - } - else - { - objectToInsert = ((ISecurityElementFactory)new SecurityDocumentElement(doc, childIndex)).CreateSecurityElement(); - } - } - else - { - IPermission ip = CreatePerm( doc.GetElement( childIndex, true ) ); - if (ip == null) - { - token = null; - objectToInsert = null; - } - else - { - token = PermissionToken.GetToken( ip ); - Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ), - "PermissionToken was improperly assigned" ); - objectToInsert = ip; - } - } - - if (token != null && objectToInsert != null) - { - if (m_permSet == null) - m_permSet = new TokenBasedSet(); - - IPermission permInSlot = null; - if (this.m_permSet.GetItem( token.m_index ) != null) - { - // If there is already something in that slot, let's union them - // together. - - if (this.m_permSet.GetItem( token.m_index ) is IPermission) - permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index ); - else - permInSlot = CreatePerm( this.m_permSet.GetItem( token.m_index ) ); - } - - if (permInSlot != null) - { - if (objectToInsert is IPermission) - objectToInsert = permInSlot.Union((IPermission)objectToInsert); - else - objectToInsert = permInSlot.Union(CreatePerm( objectToInsert )); - } - - if(m_Unrestricted && objectToInsert is IPermission) - objectToInsert = null; - - this.m_permSet.SetItem( token.m_index, objectToInsert ); - } - } - catch (Exception e) - { -#if _DEBUG - if (debug) - DEBUG_WRITE( "error while decoding permission set =\n" + e.ToString() ); -#endif - if (savedException == null) - savedException = e; - - } - } - } - - if (savedException != null) - throw savedException; - - } - - private IPermission CreatePerm(Object obj) - { - return CreatePerm(obj, m_ignoreTypeLoadFailures); - } - - internal static IPermission CreatePerm(Object obj, bool ignoreTypeLoadFailures) - { - SecurityElement el = obj as SecurityElement; - ISecurityElementFactory isf = obj as ISecurityElementFactory; - if (el == null && isf != null) - { - el = isf.CreateSecurityElement(); - } - - IEnumerator enumerator; - IPermission finalPerm = null; - - switch (el.Tag) - { - case s_str_PermissionUnion: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures); - - if (finalPerm != null) - finalPerm = finalPerm.Union( tempPerm ); - else - finalPerm = tempPerm; - } - break; - - case s_str_PermissionIntersection: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures); - - if (finalPerm != null) - finalPerm = finalPerm.Intersect( tempPerm ); - else - finalPerm = tempPerm; - - if (finalPerm == null) - return null; - } - break; - - case s_str_PermissionUnrestrictedUnion: - enumerator = el.Children.GetEnumerator(); - bool first = true; - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures ); - - if (tempPerm == null) - continue; - - PermissionToken token = PermissionToken.GetToken( tempPerm ); - - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" ); - - if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) - { - finalPerm = XMLUtil.CreatePermission( GetPermissionElement((SecurityElement)enumerator.Current), PermissionState.Unrestricted, ignoreTypeLoadFailures ); - first = false; - break; - } - else - { - Contract.Assert( tempPerm != null, "We should only come here if we have a real permission" ); - if (first) - finalPerm = tempPerm; - else - finalPerm = tempPerm.Union( finalPerm ); - first = false; - } - } - break; - - case s_str_PermissionUnrestrictedIntersection: - enumerator = el.Children.GetEnumerator(); - while (enumerator.MoveNext()) - { - IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures ); - - if (tempPerm == null) - return null; - - PermissionToken token = PermissionToken.GetToken( tempPerm ); - - Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" ); - - if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) - { - if (finalPerm != null) - finalPerm = tempPerm.Intersect( finalPerm ); - else - finalPerm = tempPerm; - } - else - { - finalPerm = null; - } - - if (finalPerm == null) - return null; - } - break; - - case "IPermission": - case "Permission": - finalPerm = el.ToPermission(ignoreTypeLoadFailures); - break; - - default: - Contract.Assert( false, "Unrecognized case found during permission creation" ); - break; - } - - return finalPerm; - } - - internal IPermission CreatePermission(Object obj, int index) - { - IPermission perm = CreatePerm(obj); - if(perm == null) - return null; - - // See if the PermissionSet.m_Unrestricted flag covers this permission - if(m_Unrestricted) - perm = null; - - // Store the decoded result - CheckSet(); - m_permSet.SetItem(index, perm); - - // Do some consistency checks - Contract.Assert(perm == null || PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), "PermissionToken was improperly assigned"); - if (perm != null) - { - PermissionToken permToken = PermissionToken.GetToken(perm); - if (permToken != null && permToken.m_index != index) - throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet")); - } - - - return perm; - } - - private static SecurityElement GetPermissionElement( SecurityElement el ) - { - switch (el.Tag) - { - case "IPermission": - case "Permission": - return el; - } - IEnumerator enumerator = el.Children.GetEnumerator(); - if (enumerator.MoveNext()) - return GetPermissionElement((SecurityElement)enumerator.Current); - Contract.Assert( false, "No Permission or IPermission tag found" ); - return null; - } - - internal static SecurityElement CreateEmptyPermissionSetXml() - { - - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", "System.Security.PermissionSet" ); - - elTrunk.AddAttribute( "version", "1" ); - return elTrunk; - - } - // internal helper which takes in the hardcoded permission name to avoid lookup at runtime - // can be called from classes that derive from PermissionSet - internal SecurityElement ToXml(String permName) - { - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", permName ); - - elTrunk.AddAttribute( "version", "1" ); - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - if (m_Unrestricted) - { - elTrunk.AddAttribute(s_str_Unrestricted, "true" ); - } - - while (enumerator.MoveNext()) - { - IPermission perm = (IPermission)enumerator.Current; - - if (!m_Unrestricted) - elTrunk.AddChild( perm.ToXml() ); - } - return elTrunk; - } - - internal SecurityElement InternalToXml() - { - SecurityElement elTrunk = new SecurityElement("PermissionSet"); - elTrunk.AddAttribute( "class", this.GetType().FullName); - elTrunk.AddAttribute( "version", "1" ); - - if (m_Unrestricted) - { - elTrunk.AddAttribute(s_str_Unrestricted, "true" ); - } - - if (this.m_permSet != null) - { - int maxIndex = this.m_permSet.GetMaxUsedIndex(); - - for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i) - { - Object obj = this.m_permSet.GetItem( i ); - if (obj != null) - { - if (obj is IPermission) - { - if (!m_Unrestricted) - elTrunk.AddChild( ((IPermission)obj).ToXml() ); - } - else - { - elTrunk.AddChild( (SecurityElement)obj ); - } - } - - } - } - return elTrunk ; - } - - public virtual SecurityElement ToXml() - { - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.PermissionSet" ), "Class name changed! Was: System.Security.PermissionSet Should be:" + this.GetType().FullName); - - return ToXml("System.Security.PermissionSet"); - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY && FEATURE_SERIALIZATION - internal - byte[] EncodeXml() - { - MemoryStream ms = new MemoryStream(); - BinaryWriter writer = new BinaryWriter( ms, Encoding.Unicode ); - writer.Write( this.ToXml().ToString() ); - writer.Flush(); - - // The BinaryWriter is going to place - // two bytes indicating a Unicode stream. - // We want to chop those off before returning - // the bytes out. - - ms.Position = 2; - int countBytes = (int)ms.Length - 2; - byte[] retval = new byte[countBytes]; - ms.Read( retval, 0, retval.Length ); - return retval; - } - - /// - [Obsolete("This method is obsolete and shoud no longer be used.")] - public static byte[] ConvertPermissionSet(String inFormat, byte[] inData, String outFormat) - { - // Since this method has shipped and is public, we cannot remove it without being a breaking change - throw new NotImplementedException(); - } -#endif - // Determines whether the permission set contains any non-code access // security permissions. - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif public bool ContainsNonCodeAccessPermissions() { if (m_CheckedForNonCas) @@ -2324,59 +1354,11 @@ namespace System.Security { return pset; } -#if FEATURE_CAS_POLICY - private const String s_str_PermissionSet = "PermissionSet"; - private const String s_str_Permission = "Permission"; - private const String s_str_IPermission = "IPermission"; - private const String s_str_Unrestricted = "Unrestricted"; - private const String s_str_PermissionUnion = "PermissionUnion"; - private const String s_str_PermissionIntersection = "PermissionIntersection"; - private const String s_str_PermissionUnrestrictedUnion = "PermissionUnrestrictedUnion"; - private const String s_str_PermissionUnrestrictedIntersection = "PermissionUnrestrictedIntersection"; - - // This method supports v1.x security attrbutes only - we'll require legacy CAS policy mode - // to be enabled for that to work. -#pragma warning disable 618 - // Internal routine used to setup a special security context - // for creating and manipulated security custom attributes - // that we use when the Runtime is hosted. - [System.Security.SecurityCritical] // auto-generated - private static void SetupSecurity() - { - PolicyLevel level = PolicyLevel.CreateAppDomainLevel(); - - CodeGroup rootGroup = new UnionCodeGroup( new AllMembershipCondition(), level.GetNamedPermissionSet( "Execution" ) ); - - StrongNamePublicKeyBlob microsoftBlob = new StrongNamePublicKeyBlob( AssemblyRef.MicrosoftPublicKeyFull ); - CodeGroup microsoftGroup = new UnionCodeGroup( new StrongNameMembershipCondition( microsoftBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) ); - - StrongNamePublicKeyBlob ecmaBlob = new StrongNamePublicKeyBlob( AssemblyRef.EcmaPublicKeyFull ); - CodeGroup ecmaGroup = new UnionCodeGroup( new StrongNameMembershipCondition( ecmaBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) ); - - CodeGroup gacGroup = new UnionCodeGroup( new GacMembershipCondition(), level.GetNamedPermissionSet( "FullTrust" ) ); - - rootGroup.AddChild( microsoftGroup ); - rootGroup.AddChild( ecmaGroup ); - rootGroup.AddChild( gacGroup ); - - level.RootCodeGroup = rootGroup; - - try - { - AppDomain.CurrentDomain.SetAppDomainPolicy( level ); - } - catch (PolicyException) - { - } - } -#endif -#pragma warning restore 618 - // Internal routine used by CreateSerialized to add a permission to the set private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset) { - Contract.Assert(casPset == null || !casPset.IsReadOnly); - Contract.Assert(nonCasPset == null || !nonCasPset.IsReadOnly); + Debug.Assert(casPset == null || !casPset.IsReadOnly); + Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly); if (perm == null) return; @@ -2402,9 +1384,6 @@ namespace System.Security { } // Converts an array of SecurityAttributes to a PermissionSet - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif private static byte[] CreateSerialized(Object[] attrs, bool serialize, ref byte[] nonCasBlob, @@ -2422,7 +1401,7 @@ namespace System.Security { for (int i = 0; i < attrs.Length; i++) { #pragma warning disable 618 - Contract.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions"); + Debug.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions"); #pragma warning restore 618 if (attrs[i] is PermissionSetAttribute) { @@ -2451,7 +1430,7 @@ namespace System.Security { MergePermission(perm, serialize, ref casPset, ref nonCasPset); } } - Contract.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true"); + Debug.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true"); // // Filter HostProtection permission. In the VM, some optimizations are done based upon these @@ -2475,22 +1454,8 @@ namespace System.Security { nonCasPset = null; } - // Serialize the set(s). - byte[] casBlob = null; - nonCasBlob = null; -#if FEATURE_CAS_POLICY - if(serialize) - { - if(casPset != null) - casBlob = casPset.EncodeXml(); - if(nonCasPset != null) - nonCasBlob = nonCasPset.EncodeXml(); - } -#else // FEATURE_CAS_POLICY - Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); -#endif // FEATURE_CAS_POLICY - - return casBlob; + Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); + return null; } #if FEATURE_SERIALIZATION @@ -2502,7 +1467,6 @@ namespace System.Security { } #endif - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static void RevertAssert() { @@ -2512,7 +1476,7 @@ namespace System.Security { internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress) { - Contract.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here"); + Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here"); PermissionSet retPs = null; bFailedToCompress = false; if (assertSet == null) @@ -2568,7 +1532,7 @@ namespace System.Security { internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet) { - Contract.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted"); + Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted"); alteredDemandSet = null; PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet); diff --git a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs index 55b56cb570..7b234e9cf4 100644 --- a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs +++ b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs @@ -81,20 +81,6 @@ namespace System.Security enm.Current = perm; return true; } - -#if FEATURE_CAS_POLICY - SecurityElement elem = obj as SecurityElement; - - if (elem != null) - { - perm = m_permSet.CreatePermission(elem, enm.Index); - if (perm != null) - { - enm.Current = perm; - return true; - } - } -#endif // FEATURE_CAS_POLICY } return false; } diff --git a/src/mscorlib/src/System/Security/PermissionSetTriple.cs b/src/mscorlib/src/System/Security/PermissionSetTriple.cs index f1527ac4b1..56eb22996e 100644 --- a/src/mscorlib/src/System/Security/PermissionSetTriple.cs +++ b/src/mscorlib/src/System/Security/PermissionSetTriple.cs @@ -19,6 +19,7 @@ namespace System.Security using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -53,7 +54,6 @@ namespace System.Security private PermissionToken ZoneToken { - [System.Security.SecurityCritical] // auto-generated get { if (s_zoneToken == null) @@ -63,7 +63,6 @@ namespace System.Security } private PermissionToken UrlToken { - [System.Security.SecurityCritical] // auto-generated get { if (s_urlToken == null) @@ -71,7 +70,6 @@ namespace System.Security return s_urlToken; } } - [System.Security.SecurityCritical] // auto-generated internal bool Update(PermissionSetTriple psTriple, out PermissionSetTriple retTriple) { retTriple = null; @@ -86,13 +84,12 @@ namespace System.Security return false; } - [System.Security.SecurityCritical] // auto-generated internal PermissionSetTriple UpdateAssert(PermissionSet in_a) { PermissionSetTriple retTriple = null; if (in_a != null) { - Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null"); + Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null"); // if we're already asserting in_a, nothing to do if (in_a.IsSubsetOf(AssertSet)) return null; @@ -128,7 +125,6 @@ namespace System.Security } return retTriple; } - [System.Security.SecurityCritical] // auto-generated internal void UpdateGrant(PermissionSet in_g, out ZoneIdentityPermission z,out UrlIdentityPermission u) { z = null; @@ -145,7 +141,6 @@ namespace System.Security } } - [System.Security.SecurityCritical] // auto-generated internal void UpdateGrant(PermissionSet in_g) { if (in_g != null) @@ -168,7 +163,6 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken) { if (pSet != null) @@ -193,7 +187,6 @@ namespace System.Security return SecurityRuntime.StackContinue; } - [System.Security.SecurityCritical] // auto-generated static bool CheckAssert(PermissionSet assertPset, PermissionSet demandSet, out PermissionSet newDemandSet) { newDemandSet = null; @@ -210,7 +203,6 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { if (CheckAssert(AssertSet, demand, permToken) == SecurityRuntime.StackHalt) @@ -222,7 +214,6 @@ namespace System.Security return SecurityRuntime.StackContinue; } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand(PermissionSet demandSet , out PermissionSet alteredDemandset, RuntimeMethodHandleInternal rmh) { alteredDemandset = null; @@ -239,18 +230,16 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken) { - Contract.Assert(AssertSet == null, "AssertSet not null"); + Debug.Assert(AssertSet == null, "AssertSet not null"); #pragma warning disable 618 return CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false); #pragma warning restore 618 } - [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemandNoThrow(PermissionSet demandSet) { - Contract.Assert(AssertSet == null, "AssertSet not null"); + Debug.Assert(AssertSet == null, "AssertSet not null"); #pragma warning disable 618 return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false); @@ -263,7 +252,6 @@ namespace System.Security /// If the triple asserts for one of the bits in the flags, it is zeroed out. /// /// set of flags to check (See PermissionType) - [System.Security.SecurityCritical] // auto-generated internal bool CheckFlags(ref int flags) { if (AssertSet != null) diff --git a/src/mscorlib/src/System/Security/PermissionToken.cs b/src/mscorlib/src/System/Security/PermissionToken.cs index e78c0f1a93..5c6a322c1c 100644 --- a/src/mscorlib/src/System/Security/PermissionToken.cs +++ b/src/mscorlib/src/System/Security/PermissionToken.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security { +namespace System.Security +{ using System; using System.Security.Util; using System.Security.Permissions; @@ -11,6 +12,7 @@ namespace System.Security { using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; + using System.Diagnostics; using System.Diagnostics.Contracts; [Flags] @@ -34,7 +36,6 @@ namespace System.Security { _info = CultureInfo.InvariantCulture.TextInfo; } - [System.Security.SecuritySafeCritical] // auto-generated public int Compare(Object a, Object b) { String strA = a as String; @@ -64,7 +65,7 @@ namespace System.Security { // The data structure consuming this will be responsible for dealing with null objects as keys. public int GetHashCode(Object obj) { - if (obj == null) throw new ArgumentNullException("obj"); + if (obj == null) throw new ArgumentNullException(nameof(obj)); Contract.EndContractBlock(); String str = obj as String; @@ -90,20 +91,13 @@ namespace System.Security { internal sealed class PermissionToken : ISecurityEncodable { private static readonly PermissionTokenFactory s_theTokenFactory; -#if FEATURE_CAS_POLICY - private static volatile ReflectionPermission s_reflectPerm = null; -#endif // FEATURE_CAS_POLICY - private const string c_mscorlibName = System.CoreLib.Name; internal int m_index; internal volatile PermissionTokenType m_type; -#if FEATURE_CAS_POLICY - internal String m_strTypeName; -#endif // FEATURE_CAS_POLICY static internal TokenBasedSet s_tokenSet = new TokenBasedSet(); internal static bool IsMscorlibClassName (string className) { - Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(), + Debug.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(), System.CoreLib.Name+" name mismatch" ); // If the class name does not look like a fully qualified name, we cannot simply determine if it's @@ -119,11 +113,7 @@ namespace System.Security { // Search for the string 'mscorlib' in the classname. If we find it, we will conservatively assume it's an mscorlib.dll type and load it. for (int i = index; i < className.Length; i++) { -#if FEATURE_CORECLR - if (className[i] == 's' || className[i] == 'S') -#else - if (className[i] == 'm' || className[i] == 'M') -#endif + if (className[i] == 's' || className[i] == 'S') { if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0) return true; @@ -145,39 +135,14 @@ namespace System.Security { { m_index = index; m_type = type; -#if FEATURE_CAS_POLICY - m_strTypeName = strTypeName; -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated public static PermissionToken GetToken(Type cls) { if (cls == null) return null; - -#if FEATURE_CAS_POLICY - if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null) - { - if (s_reflectPerm == null) - s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted); - s_reflectPerm.Assert(); - MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic ); - Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" ); - - // GetTokenIndex needs to be invoked without any security checks, since doing a security check - // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the - // token. - RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo; - Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo"); - int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null); - return s_theTokenFactory.BuiltInGetToken(token, null, cls); - } - else -#endif // FEATURE_CAS_POLICY - { - return s_theTokenFactory.GetToken(cls, null); - } + + return s_theTokenFactory.GetToken(cls, null); } public static PermissionToken GetToken(IPermission perm) @@ -193,82 +158,6 @@ namespace System.Security { return s_theTokenFactory.GetToken(perm.GetType(), perm); } -#if FEATURE_CAS_POLICY - public static PermissionToken GetToken(String typeStr) - { - return GetToken( typeStr, false ); - } - -#if _DEBUG - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - private static void GetTokenHelper(String typeStr) - { - new PermissionSet(PermissionState.Unrestricted).Assert(); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - Type type = RuntimeTypeHandle.GetTypeByName( typeStr.Trim().Replace( '\'', '\"' ), ref stackMark); - Contract.Assert( (type == null) || (type.Module.Assembly != System.Reflection.Assembly.GetExecutingAssembly()) || (typeStr.IndexOf("mscorlib", StringComparison.Ordinal) < 0), - "We should not go through this path for mscorlib based permissions" ); - } -#endif - - public static PermissionToken GetToken(String typeStr, bool bCreateMscorlib) - { - if (typeStr == null) - return null; - - if (IsMscorlibClassName( typeStr )) - { - if (!bCreateMscorlib) - { - return null; - } - else - { - return FindToken( Type.GetType( typeStr ) ); - } - } - else - { - PermissionToken token = s_theTokenFactory.GetToken(typeStr); -#if _DEBUG - GetTokenHelper(typeStr); -#endif - return token; - } - } - - [SecuritySafeCritical] - public static PermissionToken FindToken( Type cls ) - { - if (cls == null) - return null; - -#if FEATURE_CAS_POLICY - if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null) - { - if (s_reflectPerm == null) - s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted); - s_reflectPerm.Assert(); - MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic ); - Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" ); - - // GetTokenIndex needs to be invoked without any security checks, since doing a security check - // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the - // token. - RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo; - Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo"); - int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null); - return s_theTokenFactory.BuiltInGetToken(token, null, cls); - } - else -#endif // FEATURE_CAS_POLICY - { - return s_theTokenFactory.FindToken( cls ); - } - } -#endif // FEATURE_CAS_POLICY - public static PermissionToken FindTokenByIndex( int i ) { return s_theTokenFactory.FindTokenByIndex( i ); @@ -289,41 +178,6 @@ namespace System.Security { return true; } - -#if FEATURE_CAS_POLICY - public SecurityElement ToXml() - { - Contract.Assert( (m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when ToXml is called" ); - SecurityElement elRoot = new SecurityElement( "PermissionToken" ); - if ((m_type & PermissionTokenType.BuiltIn) != 0) - elRoot.AddAttribute( "Index", "" + this.m_index ); - else - elRoot.AddAttribute( "Name", SecurityElement.Escape( m_strTypeName ) ); - elRoot.AddAttribute("Type", m_type.ToString("F")); - return elRoot; - } - - public void FromXml(SecurityElement elRoot) - { - // For the most part there is no parameter checking here since this is an - // internal class and the serialization/deserialization path is controlled. - - if (!elRoot.Tag.Equals( "PermissionToken" )) - Contract.Assert( false, "Tried to deserialize non-PermissionToken element here" ); - - String strName = elRoot.Attribute( "Name" ); - PermissionToken realToken; - if (strName != null) - realToken = GetToken( strName, true ); - else - realToken = FindTokenByIndex( Int32.Parse( elRoot.Attribute( "Index" ), CultureInfo.InvariantCulture ) ); - - this.m_index = realToken.m_index; - this.m_type = (PermissionTokenType) Enum.Parse(typeof(PermissionTokenType), elRoot.Attribute("Type")); - Contract.Assert((this.m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when FromXml is called."); - this.m_strTypeName = realToken.m_strTypeName; - } -#endif // FEATURE_CAS_POLICY } // Package access only @@ -357,33 +211,6 @@ namespace System.Security { m_indexTable = new Hashtable(size); } -#if FEATURE_CAS_POLICY - [SecuritySafeCritical] - internal PermissionToken FindToken( Type cls ) - { - IntPtr typePtr = cls.TypeHandle.Value; - PermissionToken tok = (PermissionToken)m_handleTable[typePtr]; - - if (tok != null) - return tok; - - if (m_tokenTable == null) - return null; - - tok = (PermissionToken)m_tokenTable[cls.AssemblyQualifiedName]; - - if (tok != null) - { - lock (this) - { - m_handleTable.Add(typePtr, tok); - } - } - - return tok; - } -#endif // FEATURE_CAS_POLICY - internal PermissionToken FindTokenByIndex( int i ) { PermissionToken token; @@ -400,10 +227,9 @@ namespace System.Security { return token; } - [SecuritySafeCritical] internal PermissionToken GetToken(Type cls, IPermission perm) { - Contract.Assert( cls != null, "Must pass in valid type" ); + Debug.Assert( cls != null, "Must pass in valid type" ); IntPtr typePtr = cls.TypeHandle.Value; object tok = m_handleTable[typePtr]; @@ -459,22 +285,16 @@ namespace System.Security { { if (perm != null) { - Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); + Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; -#if FEATURE_CAS_POLICY - ((PermissionToken)tok).m_strTypeName = perm.GetType().AssemblyQualifiedName; -#endif // FEATURE_CAS_POLICY } else { - Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" ); + Debug.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" ); if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null) ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; else ((PermissionToken)tok).m_type = PermissionTokenType.Normal; -#if FEATURE_CAS_POLICY - ((PermissionToken)tok).m_strTypeName = cls.AssemblyQualifiedName; -#endif // FEATURE_CAS_POLICY } } diff --git a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs index 8208ed3fb0..567fe513c0 100644 --- a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs @@ -56,7 +56,6 @@ namespace System.Security.Permissions { return str; } - [SecuritySafeCritical] public override string ToString() { // SafeCritical: we're not storing path information in the strings, so exposing them out is fine ... @@ -103,7 +102,6 @@ namespace System.Security.Permissions { AddPathList( flag, pathList ); } - [System.Security.SecuritySafeCritical] // auto-generated public void AddPathList( EnvironmentPermissionAccess flag, String pathList ) { VerifyFlag( flag ); @@ -204,7 +202,6 @@ namespace System.Security.Permissions { // //------------------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsSubsetOf(IPermission target) { if (target == null) @@ -232,7 +229,6 @@ namespace System.Security.Permissions { } } - [System.Security.SecuritySafeCritical] // auto-generated public override IPermission Intersect(IPermission target) { if (target == null) @@ -275,7 +271,6 @@ namespace System.Security.Permissions { return intersectPermission; } - [System.Security.SecuritySafeCritical] // auto-generated public override IPermission Union(IPermission other) { if (other == null) @@ -334,61 +329,8 @@ namespace System.Security.Permissions { } } - return copy; + return copy; } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.EnvironmentPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - - String et; - - if (XMLUtil.IsUnrestricted(esd)) - { - m_unrestricted = true; - return; - } - - m_unrestricted = false; - m_read = null; - m_write = null; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new EnvironmentStringExpressionSet( et ); - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new EnvironmentStringExpressionSet( et ); - } - - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs index 6d6c221cc9..98a7d54c68 100644 --- a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs @@ -66,22 +66,6 @@ namespace System.Security.Permissions { return new FileDialogPermission(this.access); } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) { - CodeAccessPermission.ValidateElement(esd, this); - if (XMLUtil.IsUnrestricted(esd)) { - SetUnrestricted(true); - return; - } - - access = FileDialogPermissionAccess.None; - - string accessXml = esd.Attribute("Access"); - if (accessXml != null) - access = (FileDialogPermissionAccess)Enum.Parse(typeof(FileDialogPermissionAccess), accessXml); - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { return FileDialogPermission.GetTokenIndex(); @@ -152,21 +136,6 @@ namespace System.Security.Permissions { } } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileDialogPermission" ); - if (!IsUnrestricted()) { - if (access != FileDialogPermissionAccess.None) { - esd.AddAttribute("Access", Enum.GetName(typeof(FileDialogPermissionAccess), access)); - } - } - else { - esd.AddAttribute("Unrestricted", "true"); - } - return esd; - } -#endif // FEATURE_CAS_POLICY - public override IPermission Union(IPermission target) { if (target == null) { return this.Copy(); @@ -177,7 +146,7 @@ namespace System.Security.Permissions { FileDialogPermission operand = (FileDialogPermission)target; return new FileDialogPermission(access | operand.Access); - } + } static void VerifyAccess(FileDialogPermissionAccess access) { if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) { diff --git a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs index b4d4141f82..34b9f1ef80 100644 --- a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs @@ -2,13 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Security.Permissions { +namespace System.Security.Permissions +{ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.AccessControl; using System.Security.Util; using System.IO; @@ -16,11 +14,12 @@ namespace System.Security.Permissions { using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; -[Serializable] + [Serializable] [Flags] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public enum FileIOPermissionAccess { NoAccess = 0x00, @@ -30,9 +29,8 @@ namespace System.Security.Permissions { PathDiscovery = 0x08, AllAccess = 0x0F, } - - -[System.Runtime.InteropServices.ComVisible(true)] + + [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { @@ -62,7 +60,6 @@ namespace System.Security.Permissions { } } - [System.Security.SecuritySafeCritical] // auto-generated public FileIOPermission( FileIOPermissionAccess access, String path ) { VerifyAccess( access ); @@ -71,7 +68,6 @@ namespace System.Security.Permissions { AddPathList( access, pathList, false, true, false ); } - [System.Security.SecuritySafeCritical] // auto-generated public FileIOPermission( FileIOPermissionAccess access, String[] pathList ) { VerifyAccess( access ); @@ -79,24 +75,6 @@ namespace System.Security.Permissions { AddPathList( access, pathList, false, true, false ); } -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] // auto-generated - public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path ) - { - VerifyAccess( access ); - - String[] pathList = new String[] { path }; - AddPathList( access, control, pathList, false, true, false ); - } - - [System.Security.SecuritySafeCritical] // auto-generated - public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList ) - : this( access, control, pathList, true, true ) - { - } -#endif - - [System.Security.SecurityCritical] // auto-generated internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath ) { VerifyAccess( access ); @@ -104,16 +82,6 @@ namespace System.Security.Permissions { AddPathList( access, pathList, checkForDuplicates, needFullPath, true ); } -#if FEATURE_MACL - [System.Security.SecurityCritical] // auto-generated - internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath ) - { - VerifyAccess( access ); - - AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true ); - } -#endif - public void SetPathList( FileIOPermissionAccess access, String path ) { String[] pathList; @@ -135,7 +103,6 @@ namespace System.Security.Permissions { SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates ); } - [System.Security.SecuritySafeCritical] // auto-generated internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates ) { VerifyAccess( access ); @@ -152,26 +119,13 @@ namespace System.Security.Permissions { if ((access & FileIOPermissionAccess.PathDiscovery) != 0) m_pathDiscovery = null; -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - m_viewAcl = null; - - if ((control & AccessControlActions.Change) != 0) - m_changeAcl = null; -#else m_viewAcl = null; m_changeAcl = null; -#endif - m_unrestricted = false; -#if FEATURE_MACL - AddPathList( access, control, pathList, checkForDuplicates, true, true ); -#else + AddPathList( access, pathList, checkForDuplicates, true, true ); -#endif } - [System.Security.SecuritySafeCritical] // auto-generated public void AddPathList( FileIOPermissionAccess access, String path ) { String[] pathList; @@ -182,19 +136,16 @@ namespace System.Security.Permissions { AddPathList( access, pathList, false, true, false ); } - [System.Security.SecuritySafeCritical] // auto-generated public void AddPathList( FileIOPermissionAccess access, String[] pathList ) { AddPathList( access, pathList, true, true, true ); } - [System.Security.SecurityCritical] // auto-generated internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList ) { AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList ); } - [System.Security.SecurityCritical] // auto-generated internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList) { if (pathListOrig == null) @@ -267,29 +218,8 @@ namespace System.Security.Permissions { } m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates); } - -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - { - if (m_viewAcl == null) - { - m_viewAcl = new FileIOAccess(); - } - m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates); - } - - if ((control & AccessControlActions.Change) != 0) - { - if (m_changeAcl == null) - { - m_changeAcl = new FileIOAccess(); - } - m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates); - } -#endif } - - [SecuritySafeCritical] + public String[] GetPathList( FileIOPermissionAccess access ) { VerifyAccess( access ); @@ -335,7 +265,6 @@ namespace System.Security.Permissions { return null; } - public FileIOPermissionAccess AllLocalFiles { @@ -558,7 +487,7 @@ namespace System.Security.Permissions { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars")); if (!onlyCheckExtras) - Path.CheckInvalidPathChars(str[i]); + PathInternal.CheckInvalidPathChars(str[i]); } #else // There are no "extras" on Unix @@ -567,7 +496,7 @@ namespace System.Security.Permissions { for (int i = 0; i < str.Length; ++i) { - Path.CheckInvalidPathChars(str[i]); + PathInternal.CheckInvalidPathChars(str[i]); } #endif } @@ -785,123 +714,6 @@ namespace System.Security.Permissions { } return copy; } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) ); - } - if (this.m_append != null && !this.m_append.IsEmpty()) - { - esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) ); - } - if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty()) - { - esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) ); - } - if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty()) - { - esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) ); - } - if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty()) - { - esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) ); - } - - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - [System.Security.SecuritySafeCritical] // auto-generated - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - String et; - - if (XMLUtil.IsUnrestricted(esd)) - { - m_unrestricted = true; - return; - } - - - m_unrestricted = false; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new FileIOAccess( et ); - } - else - { - m_read = null; - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new FileIOAccess( et ); - } - else - { - m_write = null; - } - - et = esd.Attribute( "Append" ); - if (et != null) - { - m_append = new FileIOAccess( et ); - } - else - { - m_append = null; - } - - et = esd.Attribute( "PathDiscovery" ); - if (et != null) - { - m_pathDiscovery = new FileIOAccess( et ); - m_pathDiscovery.PathDiscovery = true; - } - else - { - m_pathDiscovery = null; - } - - et = esd.Attribute( "ViewAcl" ); - if (et != null) - { - m_viewAcl = new FileIOAccess( et ); - } - else - { - m_viewAcl = null; - } - - et = esd.Attribute( "ChangeAcl" ); - if (et != null) - { - m_changeAcl = new FileIOAccess( et ); - } - else - { - m_changeAcl = null; - } - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() @@ -993,19 +805,9 @@ namespace System.Security.Permissions { /// /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify /// - [System.Security.SecuritySafeCritical] internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false) { -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand(); - } - else -#endif - { - EmulateFileIOPermissionChecks(fullPath); - } + EmulateFileIOPermissionChecks(fullPath); } /// @@ -1018,67 +820,19 @@ namespace System.Security.Permissions { /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify /// /// - [System.Security.SecuritySafeCritical] internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true) { -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, fullPathList, checkForDuplicates, needFullPath).Demand(); - } - else -#endif + foreach (string fullPath in fullPathList) { - foreach (string fullPath in fullPathList) - { - EmulateFileIOPermissionChecks(fullPath); - } + EmulateFileIOPermissionChecks(fullPath); } } - [System.Security.SecuritySafeCritical] internal static void QuickDemand(PermissionState state) { // Should be a no-op without CAS -#if FEATURE_CAS_POLICY - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(state).Demand(); - } -#endif - } - -#if FEATURE_MACL - [System.Security.SecuritySafeCritical] - internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string fullPath, bool checkForDuplicates = false, bool needFullPath = true) - { - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, control, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand(); - } - else - { - EmulateFileIOPermissionChecks(fullPath); - } } - [System.Security.SecuritySafeCritical] - internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string[] fullPathList, bool checkForDuplicates = true, bool needFullPath = true) - { - if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) - { - new FileIOPermission(access, control, fullPathList, checkForDuplicates, needFullPath).Demand(); - } - else - { - foreach (string fullPath in fullPathList) - { - EmulateFileIOPermissionChecks(fullPath); - } - } - } -#endif - /// /// Perform the additional path checks that would normally happen when creating a FileIOPermission object. /// @@ -1088,18 +842,10 @@ namespace System.Security.Permissions { // Callers should have already made checks for invalid path format via normalization. This method will only make the // additional checks needed to throw the same exceptions that would normally throw when using FileIOPermission. // These checks are done via CheckIllegalCharacters() and StringExpressionSet in AddPathList() above. - // - // We have to check the beginning as some paths may be passed in as path + @"\.", which will be normalized away. - BCLDebug.Assert( - fullPath.StartsWith(Path.NormalizePath(fullPath, fullCheck: false), StringComparison.OrdinalIgnoreCase), - string.Format("path isn't normalized: {0}", fullPath)); +#if !PLATFORM_UNIX // Checking for colon / invalid characters on device paths blocks legitimate access to objects such as named pipes. - if ( -#if FEATURE_PATHCOMPAT - AppContextSwitches.UseLegacyPathHandling || -#endif - !PathInternal.IsDevice(fullPath)) + if (!PathInternal.IsDevice(fullPath)) { // GetFullPath already checks normal invalid path characters. We need to just check additional (wildcard) characters here. // (By calling the standard helper we can allow extended paths \\?\ through when the support is enabled.) @@ -1113,6 +859,7 @@ namespace System.Security.Permissions { throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); } } +#endif // !PLATFORM_UNIX } } @@ -1149,7 +896,6 @@ namespace System.Security.Permissions { m_pathDiscovery = pathDiscovery; } - [System.Security.SecurityCritical] // auto-generated public FileIOAccess( String value ) { if (value == null) @@ -1204,7 +950,6 @@ namespace System.Security.Permissions { m_pathDiscovery = operand.m_pathDiscovery; } - [System.Security.SecurityCritical] // auto-generated public void AddExpressions(ArrayList values, bool checkForDuplicates) { m_allFiles = false; @@ -1255,7 +1000,6 @@ namespace System.Security.Permissions { return new FileIOAccess( this ); } - [System.Security.SecuritySafeCritical] // auto-generated public FileIOAccess Union( FileIOAccess operand ) { if (operand == null) @@ -1263,7 +1007,7 @@ namespace System.Security.Permissions { return this.IsEmpty() ? null : this.Copy(); } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (this.m_allFiles || operand.m_allFiles) { @@ -1273,7 +1017,6 @@ namespace System.Security.Permissions { return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery ); } - [System.Security.SecuritySafeCritical] // auto-generated public FileIOAccess Intersect( FileIOAccess operand ) { if (operand == null) @@ -1281,7 +1024,7 @@ namespace System.Security.Permissions { return null; } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (this.m_allFiles) { @@ -1343,7 +1086,6 @@ namespace System.Security.Permissions { return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery ); } - [System.Security.SecuritySafeCritical] // auto-generated public bool IsSubsetOf( FileIOAccess operand ) { if (operand == null) @@ -1356,7 +1098,7 @@ namespace System.Security.Permissions { return true; } - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set ))) { @@ -1400,7 +1142,6 @@ namespace System.Security.Permissions { } } - [SecuritySafeCritical] public override String ToString() { // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so @@ -1429,7 +1170,6 @@ namespace System.Security.Permissions { } } - [SecuritySafeCritical] public String[] ToStringArray() { // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so @@ -1437,18 +1177,16 @@ namespace System.Security.Permissions { return m_set.UnsafeToStringArray(); } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern bool IsLocalDrive(String path); - [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { FileIOAccess operand = obj as FileIOAccess; if(operand == null) return (IsEmpty() && obj == null); - Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); + Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); if(m_pathDiscovery) { if(this.m_allFiles && operand.m_allFiles) diff --git a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs index 5c209afb9d..f93f26daa9 100644 --- a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Globalization; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] @@ -92,19 +89,6 @@ namespace System.Security.Permissions return this.Copy(); } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.GacIdentityPermission" ); - return securityElement; - } - - public override void FromXml(SecurityElement securityElement) - { - CodeAccessPermission.ValidateElement(securityElement, this); - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs index 85be61a00d..c4facbb67e 100644 --- a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs @@ -41,11 +41,9 @@ namespace System.Security.Permissions [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )] [System.Runtime.InteropServices.ComVisible(true)] [Serializable] -#if FEATURE_CORECLR // This needs to be in the asmmeta to enable SecAnnotate to successfully resolve and run the security rules. It gets marked // as internal by BCLRewriter so we are simply marking it as FriendAccessAllowed so it stays in the asmmeta. [System.Runtime.CompilerServices.FriendAccessAllowedAttribute] -#endif // FEATURE_CORECLR #pragma warning disable 618 sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute #pragma warning restore 618 @@ -247,38 +245,6 @@ namespace System.Security.Permissions return new HostProtectionPermission(m_resources); } -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // XML - // - //------------------------------------------------------ - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, this.GetType().FullName ); - if(IsUnrestricted()) - esd.AddAttribute( "Unrestricted", "true" ); - else - esd.AddAttribute( "Resources", XMLUtil.BitFieldEnumToString( typeof( HostProtectionResource ), Resources ) ); - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - Resources = HostProtectionResource.All; - else - { - String resources = esd.Attribute( "Resources" ); - if (resources == null) - Resources = HostProtectionResource.None; - else - Resources = (HostProtectionResource)Enum.Parse( typeof( HostProtectionResource ), resources ); - } - } -#endif // FEATURE_CAS_POLICY - //------------------------------------------------------ // // OBJECT OVERRIDES diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs index 1e11b4aa7f..42bc648c72 100644 --- a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs @@ -158,19 +158,6 @@ namespace System.Security.Permissions { { return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex; } - - //------------------------------------------------------ - // - // IsolatedStoragePermission OVERRIDES - // - //------------------------------------------------------ -#if FEATURE_CAS_POLICY - [System.Runtime.InteropServices.ComVisible(false)] - public override SecurityElement ToXml() - { - return base.ToXml( "System.Security.Permissions.IsolatedStorageFilePermission" ); - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs index 308adbdab3..9f09a37098 100644 --- a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs @@ -32,9 +32,6 @@ namespace System.Security.Permissions { [Serializable] -#if !FEATURE_CORECLR - [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )] -#endif [System.Runtime.InteropServices.ComVisible(true)] abstract public class IsolatedStoragePermission : CodeAccessPermission, IUnrestrictedPermission @@ -182,93 +179,5 @@ namespace System.Security.Permissions { //------------------------------------------------------ internal static long min(long x,long y) {return x>y?y:x;} internal static long max(long x,long y) {return x0) - { - esd.AddAttribute(_strUserQuota, (m_userQuota).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_machineQuota>0) - { - esd.AddAttribute(_strMachineQuota, (m_machineQuota).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_expirationDays>0) - { - esd.AddAttribute( _strExpiry, (m_expirationDays).ToString(CultureInfo.InvariantCulture)) ; - } - if (m_permanentData) - { - esd.AddAttribute(_strPermDat, (m_permanentData).ToString()) ; - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - - m_allowed = IsolatedStorageContainment.None; // default if no match - - if (XMLUtil.IsUnrestricted(esd)) - { - m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage; - } - else - { - String allowed = esd.Attribute( "Allowed" ); - - if (allowed != null) - m_allowed = (IsolatedStorageContainment)Enum.Parse( typeof( IsolatedStorageContainment ), allowed ); - } - - if (m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage) - { - m_userQuota = Int64.MaxValue; - m_machineQuota = Int64.MaxValue; - m_expirationDays = Int64.MaxValue ; - m_permanentData = true; - } - else - { - String param; - param = esd.Attribute (_strUserQuota) ; - m_userQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strMachineQuota) ; - m_machineQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strExpiry) ; - m_expirationDays = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ; - param = esd.Attribute (_strPermDat) ; - m_permanentData = param != null ? (Boolean.Parse(param)) : false ; - } - } -#endif // FEATURE_CAS_POLICY } } diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs index f14fb0d1b3..b6ac8ece3c 100644 --- a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs +++ b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs @@ -8,9 +8,6 @@ namespace System.Security.Permissions using System.Security.Util; using System.IO; using System.Security.Policy; -#if FEATURE_MACL - using System.Security.AccessControl; -#endif using System.Text; using System.Threading; using System.Runtime.InteropServices; @@ -23,11 +20,9 @@ namespace System.Security.Permissions using System.Diagnostics.Contracts; [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityAction is no longer accessible to application code.")] -#endif public enum SecurityAction { // Demand permission of all caller @@ -62,14 +57,11 @@ namespace System.Security.Permissions RequestRefuse = 10, } - -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [Serializable] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityAttribute is no longer accessible to application code.")] -#endif public abstract class SecurityAttribute : System.Attribute { /// @@ -96,7 +88,6 @@ namespace System.Security.Permissions abstract public IPermission CreatePermission(); - [System.Security.SecurityCritical] // auto-generated internal static unsafe IntPtr FindSecurityAttributeTypeHandle(String typeName) { PermissionSet.s_fullTrust.Assert(); @@ -108,13 +99,11 @@ namespace System.Security.Permissions } } -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [Serializable] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("CodeAccessSecurityAttribute is no longer accessible to application code.")] -#endif public abstract class CodeAccessSecurityAttribute : SecurityAttribute { protected CodeAccessSecurityAttribute( SecurityAction action ) @@ -307,12 +296,6 @@ namespace System.Security.Permissions perm.SetPathList( FileIOPermissionAccess.Append, m_append ); if (m_pathDiscovery != null) perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery ); -#if FEATURE_MACL - if (m_viewAccess != null) - perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.View, new String[] { m_viewAccess }, false ); - if (m_changeAccess != null) - perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.Change, new String[] { m_changeAccess }, false ); -#endif perm.AllFiles = m_allFiles; perm.AllLocalFiles = m_allLocalFiles; @@ -384,59 +367,6 @@ namespace System.Security.Permissions } } -#if !FEATURE_CORECLR - // PrincipalPermissionAttribute currently derives from - // CodeAccessSecurityAttribute, even though it's not related to code access - // security. This is because compilers are currently looking for - // CodeAccessSecurityAttribute as a direct parent class rather than - // SecurityAttribute as the root class. - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class PrincipalPermissionAttribute : CodeAccessSecurityAttribute - { - private String m_name = null; - private String m_role = null; - private bool m_authenticated = true; - - public PrincipalPermissionAttribute( SecurityAction action ) - : base( action ) - { - } - - public String Name - { - get { return m_name; } - set { m_name = value; } - } - - public String Role - { - get { return m_role; } - set { m_role = value; } - } - - public bool Authenticated - { - get { return m_authenticated; } - set { m_authenticated = value; } - } - - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new PrincipalPermission( PermissionState.Unrestricted ); - } - else - { - return new PrincipalPermission( m_name, m_role, m_authenticated ); - } - } - } -#endif // !FEATURE_CORECLR - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] [System.Runtime.InteropServices.ComVisible(true)] [Serializable] @@ -570,24 +500,16 @@ namespace System.Security.Permissions perm.SetPathList( RegistryPermissionAccess.Write, m_write ); if (m_create != null) perm.SetPathList( RegistryPermissionAccess.Create, m_create ); -#if FEATURE_MACL - if (m_viewAcl != null) - perm.SetPathList( AccessControlActions.View, m_viewAcl ); - if (m_changeAcl != null) - perm.SetPathList( AccessControlActions.Change, m_changeAcl ); -#endif return perm; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] [Serializable] -#if !FEATURE_CAS_POLICY // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")] -#endif sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute { private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags; @@ -662,7 +584,7 @@ namespace System.Security.Permissions set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; } } -[System.Runtime.InteropServices.ComVisible(true)] + [System.Runtime.InteropServices.ComVisible(true)] public bool Infrastructure { get { return (m_flag & SecurityPermissionFlag.Infrastructure) != 0; } set { m_flag = value ? m_flag | SecurityPermissionFlag.Infrastructure : m_flag & ~SecurityPermissionFlag.Infrastructure; } @@ -893,170 +815,6 @@ namespace System.Security.Permissions } } } - -#if FEATURE_X509 && FEATURE_CAS_POLICY - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class PublisherIdentityPermissionAttribute : CodeAccessSecurityAttribute - { - private String m_x509cert = null; - private String m_certFile = null; - private String m_signedFile = null; - - public PublisherIdentityPermissionAttribute( SecurityAction action ) - : base( action ) - { - m_x509cert = null; - m_certFile = null; - m_signedFile = null; - } - - public String X509Certificate { - get { return m_x509cert; } - set { m_x509cert = value; } - } - - public String CertFile { - get { return m_certFile; } - set { m_certFile = value; } - } - - public String SignedFile { - get { return m_signedFile; } - set { m_signedFile = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new PublisherIdentityPermission( PermissionState.Unrestricted ); - } - else - { - if (m_x509cert != null) - { - return new PublisherIdentityPermission( new X509Certificate( System.Security.Util.Hex.DecodeHexString( m_x509cert ) ) ); - } - else if (m_certFile != null) - { - return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile( m_certFile ) ); - } - else if (m_signedFile != null) - { - return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile( m_signedFile ) ); - } - else - { - return new PublisherIdentityPermission( PermissionState.None ); - } - } - } - } -#endif // #if FEATURE_X509 && FEATURE_CAS_POLICY - -#if !FEATURE_CORECLR -[Serializable] -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor - | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, - AllowMultiple=true, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute - { - /// - internal long m_userQuota; -#if false - /// - internal long m_machineQuota; - /// - internal long m_expirationDays; - /// - internal bool m_permanentData; -#endif - /// - internal IsolatedStorageContainment m_allowed; - protected IsolatedStoragePermissionAttribute(SecurityAction action) : base(action) - { - } - - // properties - public long UserQuota { - set{ - m_userQuota = value; - } - get{ - return m_userQuota; - } - } -#if false - internal long MachineQuota { - set{ - m_machineQuota = value; - } - get{ - return m_machineQuota; - } - } - internal long ExpirationDays { - set{ - m_expirationDays = value; - } - get{ - return m_expirationDays; - } - } - internal bool PermanentData { - set{ - m_permanentData = value; - } - get{ - return m_permanentData; - } - } -#endif - public IsolatedStorageContainment UsageAllowed { - set{ - m_allowed = value; - } - get{ - return m_allowed; - } - } - - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor - | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, - AllowMultiple=true, Inherited=false)] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class IsolatedStorageFilePermissionAttribute : IsolatedStoragePermissionAttribute - { - public IsolatedStorageFilePermissionAttribute(SecurityAction action) : base(action) - { - - } - public override IPermission CreatePermission() - { - IsolatedStorageFilePermission p; - if (m_unrestricted) { - p = new IsolatedStorageFilePermission - (PermissionState.Unrestricted); - } else { - p = new IsolatedStorageFilePermission(PermissionState.None); - p.UserQuota = m_userQuota; - p.UsageAllowed = m_allowed; -#if false - p.PermanentData = m_permanentData; - p.MachineQuota = m_machineQuota; - p.ExpirationDays = m_expirationDays; -#endif - } - return p; - } - } -#endif // FEATURE_CORECLR [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] [System.Runtime.InteropServices.ComVisible(true)] @@ -1109,66 +867,12 @@ namespace System.Security.Permissions return null; } -#if FEATURE_CAS_POLICY - private PermissionSet BruteForceParseStream(Stream stream) - { - Encoding[] encodings = new Encoding[] { Encoding.UTF8, - Encoding.ASCII, - Encoding.Unicode }; - - StreamReader reader = null; - Exception exception = null; - - for (int i = 0; reader == null && i < encodings.Length; ++i) - { - try - { - stream.Position = 0; - reader = new StreamReader( stream, encodings[i] ); - - return ParsePermissionSet( new Parser(reader) ); - } - catch (Exception e1) - { - if (exception == null) - exception = e1; - } - } - - throw exception; - } - - private PermissionSet ParsePermissionSet(Parser parser) - { - SecurityElement e = parser.GetTopElement(); - PermissionSet permSet = new PermissionSet( PermissionState.None ); - permSet.FromXml( e ); - - return permSet; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated -#endif public PermissionSet CreatePermissionSet() { if (m_unrestricted) return new PermissionSet( PermissionState.Unrestricted ); else if (m_name != null) -#if FEATURE_CAS_POLICY - return PolicyLevel.GetBuiltInSet( m_name ); -#else return NamedPermissionSet.GetBuiltInSet( m_name ); -#endif // FEATURE_CAS_POLICY -#if FEATURE_CAS_POLICY - else if (m_xml != null) - return ParsePermissionSet( new Parser(m_xml.ToCharArray()) ); - else if (m_hex != null) - return BruteForceParseStream( new MemoryStream(Util.Hex.DecodeHexString(m_hex)) ); - else if (m_file != null) - return BruteForceParseStream( new FileStream( m_file, FileMode.Open, FileAccess.Read) ); -#endif // FEATURE_CAS_POLICY else return new PermissionSet( PermissionState.None ); } diff --git a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs index 2bc3c08ff9..1c9dd7696c 100644 --- a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs @@ -259,45 +259,6 @@ namespace System.Security.Permissions throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type)); Contract.EndContractBlock(); } - -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // PUBLIC ENCODING METHODS - // - //------------------------------------------------------ - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ReflectionPermission" ); - if (!IsUnrestricted()) - { - esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( ReflectionPermissionFlag ), m_flags ) ); - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - m_flags = ReflectionPermission.AllFlagsAndMore; - return; - } - - Reset () ; - SetUnrestricted (false) ; - - String flags = esd.Attribute( "Flags" ); - if (flags != null) - m_flags = (ReflectionPermissionFlag)Enum.Parse( typeof( ReflectionPermissionFlag ), flags ); - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs index bf801d625b..c0c51e94a2 100644 --- a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs @@ -59,14 +59,6 @@ namespace System.Security.Permissions SetPathList( access, pathList ); } -#if FEATURE_MACL - public RegistryPermission( RegistryPermissionAccess access, AccessControlActions control, String pathList ) - { - m_unrestricted = false; - AddPathList( access, control, pathList ); - } -#endif - public void SetPathList( RegistryPermissionAccess access, String pathList ) { VerifyAccess( access ); @@ -85,27 +77,11 @@ namespace System.Security.Permissions AddPathList( access, pathList ); } -#if FEATURE_MACL - internal void SetPathList( AccessControlActions control, String pathList ) - { - m_unrestricted = false; - - if ((control & AccessControlActions.View) != 0) - m_viewAcl = null; - - if ((control & AccessControlActions.Change) != 0) - m_changeAcl = null; - - AddPathList( RegistryPermissionAccess.NoAccess, control, pathList ); - } -#endif - public void AddPathList( RegistryPermissionAccess access, String pathList ) { AddPathList( access, AccessControlActions.None, pathList ); } - [System.Security.SecuritySafeCritical] // auto-generated public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList ) { VerifyAccess( access ); @@ -130,25 +106,8 @@ namespace System.Security.Permissions m_create = new StringExpressionSet(); m_create.AddExpressions( pathList ); } - -#if FEATURE_MACL - if ((control & AccessControlActions.View) != 0) - { - if (m_viewAcl == null) - m_viewAcl = new StringExpressionSet(); - m_viewAcl.AddExpressions( pathList ); - } - - if ((control & AccessControlActions.Change) != 0) - { - if (m_changeAcl == null) - m_changeAcl = new StringExpressionSet(); - m_changeAcl.AddExpressions( pathList ); - } -#endif } - [SecuritySafeCritical] public String GetPathList( RegistryPermissionAccess access ) { // SafeCritical: these are registry paths, which means we're not leaking file system information here @@ -233,7 +192,6 @@ namespace System.Security.Permissions // //------------------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated public override bool IsSubsetOf(IPermission target) { if (target == null) @@ -257,7 +215,6 @@ namespace System.Security.Permissions (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl ))); } - [System.Security.SecuritySafeCritical] // auto-generated public override IPermission Intersect(IPermission target) { if (target == null) @@ -309,7 +266,6 @@ namespace System.Security.Permissions return intersectPermission; } - [System.Security.SecuritySafeCritical] // auto-generated public override IPermission Union(IPermission other) { if (other == null) @@ -391,93 +347,6 @@ namespace System.Security.Permissions } return copy; } - -#if FEATURE_CAS_POLICY - [SecuritySafeCritical] - public override SecurityElement ToXml() - { - // SafeCritical: our string expression sets don't contain paths, so there's no information that - // needs to be guarded in them. - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.RegistryPermission" ); - if (!IsUnrestricted()) - { - if (this.m_read != null && !this.m_read.IsEmpty()) - { - esd.AddAttribute( "Read", SecurityElement.Escape( m_read.UnsafeToString() ) ); - } - if (this.m_write != null && !this.m_write.IsEmpty()) - { - esd.AddAttribute( "Write", SecurityElement.Escape( m_write.UnsafeToString() ) ); - } - if (this.m_create != null && !this.m_create.IsEmpty()) - { - esd.AddAttribute( "Create", SecurityElement.Escape( m_create.UnsafeToString() ) ); - } - if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty()) - { - esd.AddAttribute( "ViewAccessControl", SecurityElement.Escape( m_viewAcl.UnsafeToString() ) ); - } - if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty()) - { - esd.AddAttribute( "ChangeAccessControl", SecurityElement.Escape( m_changeAcl.UnsafeToString() ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - String et; - - if (XMLUtil.IsUnrestricted( esd )) - { - m_unrestricted = true; - return; - } - - m_unrestricted = false; - m_read = null; - m_write = null; - m_create = null; - m_viewAcl = null; - m_changeAcl = null; - - et = esd.Attribute( "Read" ); - if (et != null) - { - m_read = new StringExpressionSet( et ); - } - - et = esd.Attribute( "Write" ); - if (et != null) - { - m_write = new StringExpressionSet( et ); - } - - et = esd.Attribute( "Create" ); - if (et != null) - { - m_create = new StringExpressionSet( et ); - } - - et = esd.Attribute( "ViewAccessControl" ); - if (et != null) - { - m_viewAcl = new StringExpressionSet( et ); - } - - et = esd.Attribute( "ChangeAccessControl" ); - if (et != null) - { - m_changeAcl = new StringExpressionSet( et ); - } - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs index b359cc530d..cf3002989d 100644 --- a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs @@ -16,13 +16,11 @@ namespace System.Security.Permissions using System.Globalization; using System.Diagnostics.Contracts; -[Serializable] + [Serializable] [Flags] -[System.Runtime.InteropServices.ComVisible(true)] -#if !FEATURE_CAS_POLICY + [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityPermissionFlag is no longer accessible to application code.")] -#endif public enum SecurityPermissionFlag { NoFlags = 0x00, @@ -254,99 +252,9 @@ namespace System.Security.Permissions Contract.EndContractBlock(); } -#if FEATURE_CAS_POLICY - //------------------------------------------------------ - // - // PUBLIC ENCODING METHODS - // - //------------------------------------------------------ - - private const String _strHeaderAssertion = "Assertion"; - private const String _strHeaderUnmanagedCode = "UnmanagedCode"; - private const String _strHeaderExecution = "Execution"; - private const String _strHeaderSkipVerification = "SkipVerification"; - private const String _strHeaderControlThread = "ControlThread"; - private const String _strHeaderControlEvidence = "ControlEvidence"; - private const String _strHeaderControlPolicy = "ControlPolicy"; - private const String _strHeaderSerializationFormatter = "SerializationFormatter"; - private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy"; - private const String _strHeaderControlPrincipal = "ControlPrincipal"; - private const String _strHeaderControlAppDomain = "ControlAppDomain"; - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" ); - if (!IsUnrestricted()) - { - esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) ); - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - m_flags = SecurityPermissionFlag.AllFlags; - return; - } - - Reset () ; - SetUnrestricted (false) ; - - String flags = esd.Attribute( "Flags" ); - - if (flags != null) - m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags ); - } -#endif // FEATURE_CAS_POLICY - // // Object Overrides // - - #if ZERO // Do not remove this code, usefull for debugging - public override String ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("SecurityPermission("); - if (IsUnrestricted()) - { - sb.Append("Unrestricted"); - } - else - { - if (GetFlag(SecurityPermissionFlag.Assertion)) - sb.Append("Assertion; "); - if (GetFlag(SecurityPermissionFlag.UnmanagedCode)) - sb.Append("UnmangedCode; "); - if (GetFlag(SecurityPermissionFlag.SkipVerification)) - sb.Append("SkipVerification; "); - if (GetFlag(SecurityPermissionFlag.Execution)) - sb.Append("Execution; "); - if (GetFlag(SecurityPermissionFlag.ControlThread)) - sb.Append("ControlThread; "); - if (GetFlag(SecurityPermissionFlag.ControlEvidence)) - sb.Append("ControlEvidence; "); - if (GetFlag(SecurityPermissionFlag.ControlPolicy)) - sb.Append("ControlPolicy; "); - if (GetFlag(SecurityPermissionFlag.SerializationFormatter)) - sb.Append("SerializationFormatter; "); - if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy)) - sb.Append("ControlDomainPolicy; "); - if (GetFlag(SecurityPermissionFlag.ControlPrincipal)) - sb.Append("ControlPrincipal; "); - } - - sb.Append(")"); - return sb.ToString(); - } - #endif /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs index 6050b580df..ff38d515a1 100644 --- a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using SiteString = System.Security.Util.SiteString; using System.Text; using System.Collections; @@ -31,55 +28,6 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private SiteString[] m_sites; -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission - [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private SiteString m_site; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else if (m_site != null) //v1.x case where we read the m_site value - { - m_unrestricted = false; - m_sites = new SiteString[1]; - m_sites[0] = m_site; - m_site = null; - } - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - if (m_sites != null && m_sites.Length == 1) // for the v1.x case - m_site = m_sites[0]; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_site = null; - } - } -#endif // FEATURE_REMOTING - //------------------------------------------------------ // // PUBLIC CONSTRUCTORS @@ -150,8 +98,6 @@ namespace System.Security.Permissions // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ - - public override IPermission Copy() { SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None ); @@ -291,60 +237,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) - { - m_unrestricted = false; - m_sites = null; - CodeAccessPermission.ValidateElement( esd, this ); - String unr = esd.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elem = esd.Attribute( "Site" ); - List al = new List(); - if(elem != null) - al.Add(new SiteString( elem )); - ArrayList alChildren = esd.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elem = child.Attribute( "Site" ); - if(elem != null) - al.Add(new SiteString( elem )); - } - } - if(al.Count != 0) - m_sites = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SiteIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_sites != null) - { - if (m_sites.Length == 1) - esd.AddAttribute( "Site", m_sites[0].ToString() ); - else - { - int n; - for(n = 0; n < m_sites.Length; n++) - { - SecurityElement child = new SecurityElement("Site"); - child.AddAttribute( "Site", m_sites[n].ToString() ); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs index 5f5de0ef80..f09d84de34 100644 --- a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.Util; using System.IO; using String = System.String; @@ -135,7 +132,7 @@ namespace System.Security.Permissions public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version ) { if (blob == null) - throw new ArgumentNullException( "blob" ); + throw new ArgumentNullException( nameof(blob) ); if (name != null && name.Equals( "" )) throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) ); Contract.EndContractBlock(); @@ -156,7 +153,7 @@ namespace System.Security.Permissions set { if (value == null) - throw new ArgumentNullException( "PublicKey" ); + throw new ArgumentNullException( nameof(PublicKey) ); Contract.EndContractBlock(); m_unrestricted = false; if(m_strongNames != null && m_strongNames.Length == 1) @@ -389,89 +386,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement e) - { - m_unrestricted = false; - m_strongNames = null; - CodeAccessPermission.ValidateElement( e, this ); - String unr = e.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elBlob = e.Attribute("PublicKeyBlob"); - String elName = e.Attribute("Name"); - String elVersion = e.Attribute("AssemblyVersion"); - StrongName2 sn; - List al = new List(); - if(elBlob != null || elName != null || elVersion != null) - { - sn = new StrongName2( - (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), - elName, - (elVersion == null ? null : new Version(elVersion))); - al.Add(sn); - } - ArrayList alChildren = e.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elBlob = child.Attribute("PublicKeyBlob"); - elName = child.Attribute("Name"); - elVersion = child.Attribute("AssemblyVersion"); - if(elBlob != null || elName != null || elVersion != null) - { - sn = new StrongName2( - (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)), - elName, - (elVersion == null ? null : new Version(elVersion))); - al.Add(sn); - } - } - } - if(al.Count != 0) - m_strongNames = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.StrongNameIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_strongNames != null) - { - if (m_strongNames.Length == 1) - { - if (m_strongNames[0].m_publicKeyBlob != null) - esd.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[0].m_publicKeyBlob.PublicKey)); - if (m_strongNames[0].m_name != null) - esd.AddAttribute("Name", m_strongNames[0].m_name); - if ((Object)m_strongNames[0].m_version != null) - esd.AddAttribute("AssemblyVersion", m_strongNames[0].m_version.ToString()); - } - else - { - int n; - for(n = 0; n < m_strongNames.Length; n++) - { - SecurityElement child = new SecurityElement("StrongName"); - if (m_strongNames[n].m_publicKeyBlob != null) - child.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[n].m_publicKeyBlob.PublicKey)); - if (m_strongNames[n].m_name != null) - child.AddAttribute("Name", m_strongNames[n].m_name); - if ((Object)m_strongNames[n].m_version != null) - child.AddAttribute("AssemblyVersion", m_strongNames[n].m_version.ToString()); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs index e0aacaf80c..823eaba938 100644 --- a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs +++ b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs @@ -20,7 +20,7 @@ namespace System.Security.Permissions public StrongNamePublicKeyBlob( byte[] publicKey ) { if (publicKey == null) - throw new ArgumentNullException( "PublicKey" ); + throw new ArgumentNullException( nameof(PublicKey) ); Contract.EndContractBlock(); this.PublicKey = new byte[publicKey.Length]; diff --git a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs index bb122b734c..4abe801e41 100644 --- a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs @@ -309,50 +309,6 @@ namespace System.Security.Permissions { return new UIPermission(this.m_windowFlag, this.m_clipboardFlag); } - -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" ); - if (!IsUnrestricted()) - { - if (m_windowFlag != UIPermissionWindow.NoWindows) - { - esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) ); - } - if (m_clipboardFlag != UIPermissionClipboard.NoClipboard) - { - esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) ); - } - } - else - { - esd.AddAttribute( "Unrestricted", "true" ); - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - CodeAccessPermission.ValidateElement( esd, this ); - if (XMLUtil.IsUnrestricted( esd )) - { - SetUnrestricted( true ); - return; - } - - m_windowFlag = UIPermissionWindow.NoWindows; - m_clipboardFlag = UIPermissionClipboard.NoClipboard; - - String window = esd.Attribute( "Window" ); - if (window != null) - m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window ); - - String clipboard = esd.Attribute( "Clipboard" ); - if (clipboard != null) - m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard ); - } -#endif // FEATURE_CAS_POLICY /// int IBuiltInPermission.GetTokenIndex() diff --git a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs index e62449cf3e..0883bf8979 100644 --- a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs @@ -5,9 +5,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Security.Util; using System.IO; using System.Text; @@ -31,58 +28,8 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private bool m_unrestricted; - [OptionalField(VersionAdded = 2)] - private URLString[] m_urls; - -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private URLString m_url; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else if (m_url != null) //v1.x case where we read the m_site value - { - m_unrestricted = false; - m_urls = new URLString[1]; - m_urls[0] = m_url; - m_url = null; - } - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - if (m_urls != null && m_urls.Length == 1) // for the v1.x case - m_url = m_urls[0]; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_url = null; - } - } -#endif // FEATURE_REMOTING + private URLString[] m_urls; //------------------------------------------------------ // @@ -110,7 +57,7 @@ namespace System.Security.Permissions public UrlIdentityPermission( String site ) { if (site == null) - throw new ArgumentNullException( "site" ); + throw new ArgumentNullException( nameof(site) ); Contract.EndContractBlock(); Url = site; } @@ -323,60 +270,6 @@ namespace System.Security.Permissions return result; } -#if FEATURE_CAS_POLICY - public override void FromXml(SecurityElement esd) - { - m_unrestricted = false; - m_urls = null; - CodeAccessPermission.ValidateElement( esd, this ); - String unr = esd.Attribute( "Unrestricted" ); - if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) - { - m_unrestricted = true; - return; - } - String elem = esd.Attribute( "Url" ); - List al = new List(); - if(elem != null) - al.Add(new URLString( elem, true )); - ArrayList alChildren = esd.Children; - if(alChildren != null) - { - foreach(SecurityElement child in alChildren) - { - elem = child.Attribute( "Url" ); - if(elem != null) - al.Add(new URLString( elem, true )); - } - } - if(al.Count != 0) - m_urls = al.ToArray(); - } - - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UrlIdentityPermission" ); - if (m_unrestricted) - esd.AddAttribute( "Unrestricted", "true" ); - else if (m_urls != null) - { - if (m_urls.Length == 1) - esd.AddAttribute( "Url", m_urls[0].ToString() ); - else - { - int n; - for(n = 0; n < m_urls.Length; n++) - { - SecurityElement child = new SecurityElement("Url"); - child.AddAttribute( "Url", m_urls[n].ToString() ); - esd.AddChild(child); - } - } - } - return esd; - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs index 803bd34cf1..9023c7eece 100644 --- a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs @@ -8,9 +8,6 @@ namespace System.Security.Permissions { using System; -#if FEATURE_CAS_POLICY - using SecurityElement = System.Security.SecurityElement; -#endif // FEATURE_CAS_POLICY using System.Globalization; using System.Runtime.Serialization; using System.Collections; @@ -42,57 +39,6 @@ namespace System.Security.Permissions [OptionalField(VersionAdded = 2)] private uint m_zones; -#if FEATURE_REMOTING - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission - [OptionalField(VersionAdded = 2)] - private String m_serializedPermission; - - // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes - private SecurityZone m_zone = SecurityZone.NoZone; - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - // v2.0 and beyond XML case - if (m_serializedPermission != null) - { - FromXml(SecurityElement.FromString(m_serializedPermission)); - m_serializedPermission = null; - } - else //v1.x case where we read the m_zone value - { - SecurityZone = m_zone; - m_zone = SecurityZone.NoZone; - } - } - - - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case - m_zone = SecurityZone; - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_serializedPermission = null; - m_zone = SecurityZone.NoZone; - } - } -#endif // FEATURE_REMOTING - //------------------------------------------------------ // // PUBLIC CONSTRUCTORS @@ -247,53 +193,6 @@ namespace System.Security.Permissions return new ZoneIdentityPermission(this.m_zones | that.m_zones); } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml() - { - SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" ); - if (SecurityZone != SecurityZone.NoZone) - { - esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) ); - } - else - { - int nEnum = 0; - uint nFlag; - for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) - { - if((m_zones & nFlag) != 0) - { - SecurityElement child = new SecurityElement("Zone"); - child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) ); - esd.AddChild(child); - } - nEnum++; - } - } - return esd; - } - - public override void FromXml(SecurityElement esd) - { - m_zones = 0; - CodeAccessPermission.ValidateElement( esd, this ); - String eZone = esd.Attribute( "Zone" ); - if (eZone != null) - SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone ); - if(esd.Children != null) - { - foreach(SecurityElement child in esd.Children) - { - eZone = child.Attribute( "Zone" ); - int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone ); - if(enm == (int)SecurityZone.NoZone) - continue; - m_zones |= ((uint)1 << enm); - } - } - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex() { diff --git a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs index 9691c03da3..d4f1c273c6 100644 --- a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs +++ b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs @@ -11,6 +11,7 @@ namespace System.Security.Permissions { #endif using System.Security.Util; using System.Globalization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -88,7 +89,7 @@ namespace System.Security.Permissions { m_keyStore = "*"; } else { if (value != "User" && value != "Machine" && value != "*") - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), nameof(value)); m_keyStore = value; } } @@ -232,7 +233,7 @@ namespace System.Security.Permissions { if (index < 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted")); if (index >= Count) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return (KeyContainerPermissionAccessEntry)m_list[index]; @@ -247,7 +248,7 @@ namespace System.Security.Permissions { public int Add (KeyContainerPermissionAccessEntry accessEntry) { if (accessEntry == null) - throw new ArgumentNullException("accessEntry"); + throw new ArgumentNullException(nameof(accessEntry)); Contract.EndContractBlock(); int index = m_list.IndexOf(accessEntry); @@ -275,7 +276,7 @@ namespace System.Security.Permissions { public void Remove (KeyContainerPermissionAccessEntry accessEntry) { if (accessEntry == null) - throw new ArgumentNullException("accessEntry"); + throw new ArgumentNullException(nameof(accessEntry)); Contract.EndContractBlock(); m_list.Remove(accessEntry); } @@ -292,11 +293,11 @@ namespace System.Security.Permissions { /// void ICollection.CopyTo (Array array, int index) { if (array == null) - throw new ArgumentNullException("array"); + throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0 || index >= array.Length) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); if (index + this.Count > array.Length) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); @@ -385,7 +386,7 @@ namespace System.Security.Permissions { public KeyContainerPermission (KeyContainerPermissionFlags flags, KeyContainerPermissionAccessEntry[] accessList) { if (accessList == null) - throw new ArgumentNullException("accessList"); + throw new ArgumentNullException(nameof(accessList)); Contract.EndContractBlock(); VerifyFlags(flags); @@ -525,61 +526,6 @@ namespace System.Security.Permissions { return cp; } -#if FEATURE_CAS_POLICY - public override SecurityElement ToXml () { - SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement(this, "System.Security.Permissions.KeyContainerPermission"); - if (!IsUnrestricted()) { - securityElement.AddAttribute("Flags", m_flags.ToString()); - if (AccessEntries.Count > 0) { - SecurityElement al = new SecurityElement("AccessList"); - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - SecurityElement entryElem = new SecurityElement("AccessEntry"); - entryElem.AddAttribute("KeyStore", accessEntry.KeyStore); - entryElem.AddAttribute("ProviderName", accessEntry.ProviderName); - entryElem.AddAttribute("ProviderType", accessEntry.ProviderType.ToString(null, null)); - entryElem.AddAttribute("KeyContainerName", accessEntry.KeyContainerName); - entryElem.AddAttribute("KeySpec", accessEntry.KeySpec.ToString(null, null)); - entryElem.AddAttribute("Flags", accessEntry.Flags.ToString()); - al.AddChild(entryElem); - } - securityElement.AddChild(al); - } - } else - securityElement.AddAttribute("Unrestricted", "true"); - - return securityElement; - } - - public override void FromXml (SecurityElement securityElement) { - CodeAccessPermission.ValidateElement(securityElement, this); - if (XMLUtil.IsUnrestricted(securityElement)) { - m_flags = KeyContainerPermissionFlags.AllFlags; - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - return; - } - - m_flags = KeyContainerPermissionFlags.NoFlags; - string strFlags = securityElement.Attribute("Flags"); - if (strFlags != null) { - KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strFlags); - VerifyFlags(flags); - m_flags = flags; - } - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - - if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) { - IEnumerator enumerator = securityElement.Children.GetEnumerator(); - while (enumerator.MoveNext()) { - SecurityElement current = (SecurityElement) enumerator.Current; - if (current != null) { - if (String.Equals(current.Tag, "AccessList")) - AddAccessEntries(current); - } - } - } - } -#endif // FEATURE_CAS_POLICY - /// int IBuiltInPermission.GetTokenIndex () { return KeyContainerPermission.GetTokenIndex(); @@ -597,7 +543,7 @@ namespace System.Security.Permissions { if (current != null) { if (String.Equals(current.Tag, "AccessEntry")) { int iMax = current.m_lAttributes.Count; - Contract.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly"); + Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly"); string keyStore = null; string providerName = null; int providerType = -1; diff --git a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs index 57b216e462..3d4e35adf4 100644 --- a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs +++ b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs @@ -2,20 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -// // // This class encapsulates security decisions about an application. // -namespace System.Security.Policy { +namespace System.Security.Policy +{ using System.Collections; using System.Collections.Generic; -#if FEATURE_CLICKONCE - using System.Deployment.Internal.Isolation; - using System.Deployment.Internal.Isolation.Manifest; -#endif using System.Globalization; using System.IO; using System.Runtime.InteropServices; @@ -40,14 +34,6 @@ namespace System.Security.Policy { [Serializable] public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable { -#if FEATURE_CLICKONCE - private ApplicationIdentity m_appId; - private bool m_appTrustedToRun; - private bool m_persist; - - private object m_extraInfo; - private SecurityElement m_elExtraInfo; -#endif private PolicyStatement m_psDefaultGrant; private IList m_fullTrustAssemblies; @@ -65,11 +51,6 @@ namespace System.Security.Policy { [NonSerialized] private int m_grantSetSpecialFlags; -#if FEATURE_CLICKONCE - public ApplicationTrust (ApplicationIdentity applicationIdentity) : this () { - ApplicationIdentity = applicationIdentity; - } -#endif public ApplicationTrust () : this (new PermissionSet(PermissionState.None)) { } @@ -83,7 +64,7 @@ namespace System.Security.Policy { public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable fullTrustAssemblies) { if (fullTrustAssemblies == null) { - throw new ArgumentNullException("fullTrustAssemblies"); + throw new ArgumentNullException(nameof(fullTrustAssemblies)); } InitDefaultGrantSet(defaultGrantSet); @@ -91,7 +72,7 @@ namespace System.Security.Policy { List fullTrustList = new List(); foreach (StrongName strongName in fullTrustAssemblies) { if (strongName == null) { - throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), "fullTrustAssemblies"); + throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), nameof(fullTrustAssemblies)); } fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version)); @@ -104,7 +85,7 @@ namespace System.Security.Policy { // IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR) private void InitDefaultGrantSet(PermissionSet defaultGrantSet) { if (defaultGrantSet == null) { - throw new ArgumentNullException("defaultGrantSet"); + throw new ArgumentNullException(nameof(defaultGrantSet)); } // Creating a PolicyStatement copies the incoming permission set, so we don't have to worry @@ -113,19 +94,6 @@ namespace System.Security.Policy { DefaultGrantSet = new PolicyStatement(defaultGrantSet); } -#if FEATURE_CLICKONCE - public ApplicationIdentity ApplicationIdentity { - get { - return m_appId; - } - set { - if (value == null) - throw new ArgumentNullException("value", Environment.GetResourceString("Argument_InvalidAppId")); - Contract.EndContractBlock(); - m_appId = value; - } - } -#endif public PolicyStatement DefaultGrantSet { get { if (m_psDefaultGrant == null) @@ -149,541 +117,10 @@ namespace System.Security.Policy { return m_fullTrustAssemblies; } } -#if FEATURE_CLICKONCE - public bool IsApplicationTrustedToRun { - get { - return m_appTrustedToRun; - } - set { - m_appTrustedToRun = value; - } - } - - public bool Persist { - get { - return m_persist; - } - set { - m_persist = value; - } - } - - public object ExtraInfo { - get { - if (m_elExtraInfo != null) { - m_extraInfo = ObjectFromXml(m_elExtraInfo); - m_elExtraInfo = null; - } - return m_extraInfo; - } - set { - m_elExtraInfo = null; - m_extraInfo = value; - } - } -#endif //FEATURE_CLICKONCE - -#if FEATURE_CAS_POLICY - public SecurityElement ToXml () { - SecurityElement elRoot = new SecurityElement("ApplicationTrust"); - elRoot.AddAttribute("version", "1"); - -#if FEATURE_CLICKONCE - if (m_appId != null) { - elRoot.AddAttribute("FullName", SecurityElement.Escape(m_appId.FullName)); - } - if (m_appTrustedToRun) { - elRoot.AddAttribute("TrustedToRun", "true"); - } - if (m_persist) { - elRoot.AddAttribute("Persist", "true"); - } -#endif // FEATURE_CLICKONCE - - if (m_psDefaultGrant != null) { - SecurityElement elDefaultGrant = new SecurityElement("DefaultGrant"); - elDefaultGrant.AddChild(m_psDefaultGrant.ToXml()); - elRoot.AddChild(elDefaultGrant); - } - if (m_fullTrustAssemblies.Count > 0) { - SecurityElement elFullTrustAssemblies = new SecurityElement("FullTrustAssemblies"); - foreach (StrongName fullTrustAssembly in m_fullTrustAssemblies) { - elFullTrustAssemblies.AddChild(fullTrustAssembly.ToXml()); - } - elRoot.AddChild(elFullTrustAssemblies); - } - -#if FEATURE_CLICKONCE - if (ExtraInfo != null) { - elRoot.AddChild(ObjectToXml("ExtraInfo", ExtraInfo)); - } -#endif // FEATURE_CLICKONCE - return elRoot; - } - - public void FromXml (SecurityElement element) { - if (element == null) - throw new ArgumentNullException("element"); - if (String.Compare(element.Tag, "ApplicationTrust", StringComparison.Ordinal) != 0) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); - -#if FEATURE_CLICKONCE - m_appTrustedToRun = false; - string isAppTrustedToRun = element.Attribute("TrustedToRun"); - if (isAppTrustedToRun != null && String.Compare(isAppTrustedToRun, "true", StringComparison.Ordinal) == 0) { - m_appTrustedToRun = true; - } - - m_persist = false; - string persist = element.Attribute("Persist"); - if (persist != null && String.Compare(persist, "true", StringComparison.Ordinal) == 0) { - m_persist = true; - } - - m_appId = null; - string fullName = element.Attribute("FullName"); - if (fullName != null && fullName.Length > 0) { - m_appId = new ApplicationIdentity(fullName); - } -#endif // FEATURE_CLICKONCE - - m_psDefaultGrant = null; - m_grantSetSpecialFlags = 0; - SecurityElement elDefaultGrant = element.SearchForChildByTag("DefaultGrant"); - if (elDefaultGrant != null) { - SecurityElement elDefaultGrantPS = elDefaultGrant.SearchForChildByTag("PolicyStatement"); - if (elDefaultGrantPS != null) { - PolicyStatement ps = new PolicyStatement(null); - ps.FromXml(elDefaultGrantPS); - m_psDefaultGrant = ps; - m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(ps.PermissionSet, null); - } - } - - List fullTrustAssemblies = new List(); - SecurityElement elFullTrustAssemblies = element.SearchForChildByTag("FullTrustAssemblies"); - if (elFullTrustAssemblies != null && elFullTrustAssemblies.InternalChildren != null) { - IEnumerator enumerator = elFullTrustAssemblies.Children.GetEnumerator(); - while (enumerator.MoveNext()) { - StrongName fullTrustAssembly = new StrongName(); - fullTrustAssembly.FromXml(enumerator.Current as SecurityElement); - fullTrustAssemblies.Add(fullTrustAssembly); - } - } - - m_fullTrustAssemblies = fullTrustAssemblies.AsReadOnly(); - -#if FEATURE_CLICKONCE - m_elExtraInfo = element.SearchForChildByTag("ExtraInfo"); -#endif // FEATURE_CLICKONCE - } - -#if FEATURE_CLICKONCE - private static SecurityElement ObjectToXml (string tag, Object obj) { - BCLDebug.Assert(obj != null, "You need to pass in an object"); - - ISecurityEncodable encodableObj = obj as ISecurityEncodable; - - SecurityElement elObject; - if (encodableObj != null) { - elObject = encodableObj.ToXml(); - if (!elObject.Tag.Equals(tag)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); - } - MemoryStream stream = new MemoryStream(); - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(stream, obj); - byte[] array = stream.ToArray(); - - elObject = new SecurityElement(tag); - elObject.AddAttribute("Data", Hex.EncodeHexString(array)); - return elObject; - } - - private static Object ObjectFromXml (SecurityElement elObject) { - BCLDebug.Assert(elObject != null, "You need to pass in a security element"); - - if (elObject.Attribute("class") != null) { - ISecurityEncodable encodableObj = XMLUtil.CreateCodeGroup(elObject) as ISecurityEncodable; - if (encodableObj != null) { - encodableObj.FromXml(elObject); - return encodableObj; - } - } - - string objectData = elObject.Attribute("Data"); - MemoryStream stream = new MemoryStream(Hex.DecodeHexString(objectData)); - BinaryFormatter formatter = new BinaryFormatter(); - return formatter.Deserialize(stream); - } -#endif // FEATURE_CLICKONCE -#endif // FEATURE_CAS_POLICY - -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] -#pragma warning restore 618 - [SecuritySafeCritical] public override EvidenceBase Clone() { return base.Clone(); } } - -#if FEATURE_CLICKONCE - [System.Security.SecurityCritical] // auto-generated_required - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class ApplicationTrustCollection : ICollection { - private const string ApplicationTrustProperty = "ApplicationTrust"; - private const string InstallerIdentifier = "{60051b8f-4f12-400a-8e50-dd05ebd438d1}"; - private static Guid ClrPropertySet = new Guid("c989bb7a-8385-4715-98cf-a741a8edb823"); - - // The CLR specific constant install reference. - private static object s_installReference = null; - private static StoreApplicationReference InstallReference { - get { - if (s_installReference == null) { - Interlocked.CompareExchange(ref s_installReference, - new StoreApplicationReference( - IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, - InstallerIdentifier, - null), - null); - } - return (StoreApplicationReference) s_installReference; - } - } - - private object m_appTrusts = null; - private ArrayList AppTrusts { - [System.Security.SecurityCritical] // auto-generated - get { - if (m_appTrusts == null) { - ArrayList appTrusts = new ArrayList(); - if (m_storeBounded) { - RefreshStorePointer(); - // enumerate the user store and populate the collection - StoreDeploymentMetadataEnumeration deplEnum = m_pStore.EnumInstallerDeployments(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, null); - foreach (IDefinitionAppId defAppId in deplEnum) { - StoreDeploymentMetadataPropertyEnumeration metadataEnum = m_pStore.EnumInstallerDeploymentProperties(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, defAppId); - foreach (StoreOperationMetadataProperty appTrustProperty in metadataEnum) { - string appTrustXml = appTrustProperty.Value; - if (appTrustXml != null && appTrustXml.Length > 0) { - SecurityElement seTrust = SecurityElement.FromString(appTrustXml); - ApplicationTrust appTrust = new ApplicationTrust(); - appTrust.FromXml(seTrust); - appTrusts.Add(appTrust); - } - } - } - } - Interlocked.CompareExchange(ref m_appTrusts, appTrusts, null); - } - return m_appTrusts as ArrayList; - } - } - - private bool m_storeBounded = false; - private Store m_pStore = null; // Component store interface pointer. - - // Only internal constructors are exposed. - [System.Security.SecurityCritical] // auto-generated - internal ApplicationTrustCollection () : this(false) {} - internal ApplicationTrustCollection (bool storeBounded) { - m_storeBounded = storeBounded; - } - - [System.Security.SecurityCritical] // auto-generated - private void RefreshStorePointer () { - // Refresh store pointer. - if (m_pStore != null) - Marshal.ReleaseComObject(m_pStore.InternalStore); - m_pStore = IsolationInterop.GetUserStore(); - } - - public int Count - { - [System.Security.SecuritySafeCritical] // overrides public transparent member - get { - return AppTrusts.Count; - } - } - - public ApplicationTrust this[int index] { - [System.Security.SecurityCritical] // auto-generated - get { - return AppTrusts[index] as ApplicationTrust; - } - } - - public ApplicationTrust this[string appFullName] { - [System.Security.SecurityCritical] // auto-generated - get { - ApplicationIdentity identity = new ApplicationIdentity(appFullName); - ApplicationTrustCollection appTrusts = Find(identity, ApplicationVersionMatch.MatchExactVersion); - if (appTrusts.Count > 0) - return appTrusts[0]; - return null; - } - } - - [System.Security.SecurityCritical] // auto-generated - private void CommitApplicationTrust(ApplicationIdentity applicationIdentity, string trustXml) { - StoreOperationMetadataProperty[] properties = new StoreOperationMetadataProperty[] { - new StoreOperationMetadataProperty(ClrPropertySet, ApplicationTrustProperty, trustXml) - }; - - IEnumDefinitionIdentity idenum = applicationIdentity.Identity.EnumAppPath(); - IDefinitionIdentity[] asbId = new IDefinitionIdentity[1]; - IDefinitionIdentity deplId = null; - if (idenum.Next(1, asbId) == 1) - deplId = asbId[0]; - - IDefinitionAppId defAppId = IsolationInterop.AppIdAuthority.CreateDefinition(); - defAppId.SetAppPath(1, new IDefinitionIdentity[] {deplId}); - defAppId.put_Codebase(applicationIdentity.CodeBase); - - using (StoreTransaction storeTxn = new StoreTransaction()) { - storeTxn.Add(new StoreOperationSetDeploymentMetadata(defAppId, InstallReference, properties)); - RefreshStorePointer(); - m_pStore.Transact(storeTxn.Operations); - } - - m_appTrusts = null; // reset the app trusts in the collection. - } - - [System.Security.SecurityCritical] // auto-generated - public int Add (ApplicationTrust trust) { - if (trust == null) - throw new ArgumentNullException("trust"); - if (trust.ApplicationIdentity == null) - throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity")); - Contract.EndContractBlock(); - - // Add the trust decision of the application to the fusion store. - if (m_storeBounded) { - CommitApplicationTrust(trust.ApplicationIdentity, trust.ToXml().ToString()); - return -1; - } else { - return AppTrusts.Add(trust); - } - } - - [System.Security.SecurityCritical] // auto-generated - public void AddRange (ApplicationTrust[] trusts) { - if (trusts == null) - throw new ArgumentNullException("trusts"); - Contract.EndContractBlock(); - - int i=0; - try { - for (; i - [System.Security.SecuritySafeCritical] // overrides public transparent member - IEnumerator IEnumerable.GetEnumerator() - { - return new ApplicationTrustEnumerator(this); - } - - /// - [System.Security.SecuritySafeCritical] // overrides public transparent member - void ICollection.CopyTo(Array array, int index) { - if (array == null) - throw new ArgumentNullException("array"); - if (array.Rank != 1) - throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); - if (index < 0 || index >= array.Length) - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); - if (array.Length - index < this.Count) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); - Contract.EndContractBlock(); - - for (int i=0; i < this.Count; i++) { - array.SetValue(this[i], index++); - } - } - - public void CopyTo (ApplicationTrust[] array, int index) { - ((ICollection)this).CopyTo(array, index); - } - - public bool IsSynchronized { - [System.Security.SecuritySafeCritical] // overrides public transparent member - get - { - return false; - } - } - - public object SyncRoot { - [System.Security.SecuritySafeCritical] // overrides public transparent member - get - { - return this; - } - } - } - - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class ApplicationTrustEnumerator : IEnumerator { - [System.Security.SecurityCritical] // auto-generated - private ApplicationTrustCollection m_trusts; - private int m_current; - - private ApplicationTrustEnumerator() {} - [System.Security.SecurityCritical] // auto-generated - internal ApplicationTrustEnumerator(ApplicationTrustCollection trusts) { - m_trusts = trusts; - m_current = -1; - } - - public ApplicationTrust Current { - [System.Security.SecuritySafeCritical] // auto-generated - get { - return m_trusts[m_current]; - } - } - - /// - object IEnumerator.Current { - [System.Security.SecuritySafeCritical] // auto-generated - get { - return (object) m_trusts[m_current]; - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - public bool MoveNext() { - if (m_current == ((int) m_trusts.Count - 1)) - return false; - m_current++; - return true; - } - - public void Reset() { - m_current = -1; - } - } -#endif // FEATURE_CLICKONCE } diff --git a/src/mscorlib/src/System/Security/Policy/Evidence.cs b/src/mscorlib/src/System/Security/Policy/Evidence.cs index 8bf8aa7e92..22479dff6c 100644 --- a/src/mscorlib/src/System/Security/Policy/Evidence.cs +++ b/src/mscorlib/src/System/Security/Policy/Evidence.cs @@ -2,28 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - namespace System.Security.Policy { - using System; - using System.Collections; - using System.Collections.Generic; - using System.Configuration.Assemblies; - using System.Diagnostics.Contracts; - using System.IO; - using System.Reflection; - using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using System.Runtime.Remoting; #if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; #endif // FEATURE_SERIALIZATION - using System.Security.Permissions; - using System.Security.Util; - using System.Threading; - using Microsoft.Win32.SafeHandles; /// /// The Evidence class keeps track of information that can be used to make security decisions about @@ -48,1856 +33,6 @@ namespace System.Security.Policy #endif [ComVisible(true)] public sealed class Evidence -#if FEATURE_CAS_POLICY - : ICollection -#endif // FEATURE_CAS_POLICY { -#if !FEATURE_CORECLR && FEATURE_RWLOCK -#if FEATURE_SERIALIZATION - [OptionalField(VersionAdded = 4)] - private Dictionary m_evidence; - - [OptionalField(VersionAdded = 4)] - private bool m_deserializedTargetEvidence; - - // These fields are only used to deserialize v2.0 serialized versions of Evidence. It will be null - // after the seriailzation process is complete, and should not be used. -#pragma warning disable 414 - private volatile ArrayList m_hostList; - private volatile ArrayList m_assemblyList; -#pragma warning restore 414 -#else // !FEATURE_SERIALIZATION - private Dictionary m_evidence; -#endif // FEATURE_SERIALIZATION - - [NonSerialized] - private ReaderWriterLock m_evidenceLock; - - [NonSerialized] - private uint m_version; - - [NonSerialized] - private IRuntimeEvidenceFactory m_target; - - private bool m_locked; - - // If this evidence collection is a clone where we may need to backpatch to the original, this will - // reference the collection it was cloned from. See - // code:System.Security.Policy.Evidence#BackpatchGeneratedEvidence - [NonSerialized] - private WeakReference m_cloneOrigin; - - private static volatile Type[] s_runtimeEvidenceTypes; - - /// - /// Set of actions that we could perform if we detect that we are attempting to add evidence - /// when we already have evidence of that type stored. - /// - private enum DuplicateEvidenceAction - { - Throw, // Throw an exception - Merge, // Create a list of all the evidence objects - SelectNewObject // The newly added object wins - } - -#if FEATURE_CAS_POLICY - public Evidence() - { - m_evidence = new Dictionary(); - m_evidenceLock = new ReaderWriterLock(); - } -#endif // FEATURE_CAS_POLICY - - /// - /// Create a deep copy of an evidence object - /// - public Evidence(Evidence evidence) - { - m_evidence = new Dictionary(); - - if (evidence != null) - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(evidence, EvidenceLockHolder.LockType.Reader)) - { - foreach (KeyValuePair evidenceType in evidence.m_evidence) - { - EvidenceTypeDescriptor cloneDescriptor = evidenceType.Value; - if (cloneDescriptor != null) - { - cloneDescriptor = cloneDescriptor.Clone(); - } - - m_evidence[evidenceType.Key] = cloneDescriptor; - } - - m_target = evidence.m_target; - m_locked = evidence.m_locked; -#if FEATURE_SERIALIZATION - m_deserializedTargetEvidence = evidence.m_deserializedTargetEvidence; -#endif // FEATURE_SERIALIZATION - - // see code:System.Security.Policy.Evidence#BackpatchGeneratedEvidence - if (evidence.Target != null) - { - m_cloneOrigin = new WeakReference(evidence); - } - } - } - - // see code:System.Security.Policy.Evidence#EvidenceLock - m_evidenceLock = new ReaderWriterLock(); - } - - [Obsolete("This constructor is obsolete. Please use the constructor which takes arrays of EvidenceBase instead.")] - public Evidence(object[] hostEvidence, object[] assemblyEvidence) - { - m_evidence = new Dictionary(); - - // This is a legacy evidence entry point, so we add through the legacy add APIs in order to get - // proper legacy wrapping and merge behavior. -#pragma warning disable 618 - if (hostEvidence != null) - { - foreach (object hostEvidenceObject in hostEvidence) - { - AddHost(hostEvidenceObject); - } - } - - if (assemblyEvidence != null) - { - foreach (object assemblyEvidenceObject in assemblyEvidence) - { - AddAssembly(assemblyEvidenceObject); - } - } -#pragma warning restore 618 - - // see code:System.Security.Policy.Evidence#EvidenceLock - m_evidenceLock = new ReaderWriterLock(); - } - - public Evidence(EvidenceBase[] hostEvidence, EvidenceBase[] assemblyEvidence) - { - m_evidence = new Dictionary(); - - if (hostEvidence != null) - { - foreach (EvidenceBase hostEvidenceObject in hostEvidence) - { - AddHostEvidence(hostEvidenceObject, GetEvidenceIndexType(hostEvidenceObject), DuplicateEvidenceAction.Throw); - } - } - - if (assemblyEvidence != null) - { - foreach (EvidenceBase assemblyEvidenceObject in assemblyEvidence) - { - AddAssemblyEvidence(assemblyEvidenceObject, GetEvidenceIndexType(assemblyEvidenceObject), DuplicateEvidenceAction.Throw); - } - } - - // see code:System.Security.Policy.Evidence#EvidenceLock - m_evidenceLock = new ReaderWriterLock(); - } - - /// - /// Create an empty evidence collection which will contain evidence for a specific assembly or - /// AppDomain - /// - [SecuritySafeCritical] - internal Evidence(IRuntimeEvidenceFactory target) - { - Contract.Assert(target != null); - - m_evidence = new Dictionary(); - m_target = target; - - // Setup the types of evidence that the CLR can generate for a target as keys in the dictionary - foreach (Type runtimeEvidenceType in RuntimeEvidenceTypes) - { - BCLDebug.Assert(typeof(EvidenceBase).IsAssignableFrom(runtimeEvidenceType), "All runtime evidence types should be EvidenceBases"); - m_evidence[runtimeEvidenceType] = null; - } - - QueryHostForPossibleEvidenceTypes(); - - // see code:System.Security.Policy.Evidence#EvidenceLock - m_evidenceLock = new ReaderWriterLock(); - } - - internal static Type[] RuntimeEvidenceTypes - { - get - { - if (s_runtimeEvidenceTypes == null) - { - Type[] runtimeEvidenceTypes = new Type[] - { -#if FEATURE_CLICKONCE - typeof(System.Runtime.Hosting.ActivationArguments), -#endif // FEATURE_CLICKONCE -#if FEATURE_CAS_POLICY - typeof(ApplicationDirectory), -#endif // FEATURE_CAS_POLICY - typeof(ApplicationTrust), -#if FEATURE_CAS_POLICY - typeof(GacInstalled), - typeof(Hash), - typeof(Publisher), -#endif // FEATURE_CAS_POLICY - typeof(Site), - typeof(StrongName), - typeof(Url), - typeof(Zone) - }; - -#if FEATURE_CAS_POLICY - // We only supply permission request evidence in legacy CAS mode - if (AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { -#pragma warning disable 618 // We need to generate PermissionRequestEvidence in compatibility mode - int l = runtimeEvidenceTypes.Length; - Array.Resize(ref runtimeEvidenceTypes, l+1); - runtimeEvidenceTypes[l] = typeof(PermissionRequestEvidence); -#pragma warning restore 618 - } -#endif // FEATURE_CAS_POLICY - - s_runtimeEvidenceTypes = runtimeEvidenceTypes; - } - - return s_runtimeEvidenceTypes; - } - } - - // - // #EvidenceLock - // - // Evidence synchronization locking wrappers. In the case where the lock has not yet been created, - // we know that we're in the process of constructing the evidence collection and therefore we can - // act as though the evidence is locked. If there is a lock in place, then just delegate back to it. - // - // The nested EvidenceLockHolder and EvidenceUpgradeLockHolder utility classes can be used to wrap - // these methods when acquiring and releasing the evidence lock. - // - - // Millisecond timeout when waiting to acquire the evidence lock - private const int LockTimeout = 5000; - - private bool IsReaderLockHeld - { - get { return m_evidenceLock == null || m_evidenceLock.IsReaderLockHeld; } - } - - private bool IsWriterLockHeld - { - get { return m_evidenceLock == null || m_evidenceLock.IsWriterLockHeld; } - } - - private void AcquireReaderLock() - { - Contract.Assert(m_evidenceLock == null || !IsReaderLockHeld); - - if (m_evidenceLock != null) - { - m_evidenceLock.AcquireReaderLock(LockTimeout); - } - } - - private void AcquireWriterlock() - { - Contract.Assert(m_evidenceLock == null || !IsWriterLockHeld); - - if (m_evidenceLock != null) - { - m_evidenceLock.AcquireWriterLock(LockTimeout); - } - } - - private void DowngradeFromWriterLock(ref LockCookie lockCookie) - { - Contract.Assert(IsWriterLockHeld); - if (m_evidenceLock != null) - { - m_evidenceLock.DowngradeFromWriterLock(ref lockCookie); - } - } - - private LockCookie UpgradeToWriterLock() - { - Contract.Assert(IsReaderLockHeld); - return m_evidenceLock != null ? m_evidenceLock.UpgradeToWriterLock(LockTimeout) : new LockCookie(); - } - - private void ReleaseReaderLock() - { - Contract.Assert(IsReaderLockHeld); - - if (m_evidenceLock != null) - { - m_evidenceLock.ReleaseReaderLock(); - } - } - - private void ReleaseWriterLock() - { - Contract.Assert(IsWriterLockHeld); - - if (m_evidenceLock != null) - { - m_evidenceLock.ReleaseWriterLock(); - } - } - - [Obsolete("This method is obsolete. Please use AddHostEvidence instead.")] - [SecuritySafeCritical] - public void AddHost(object id) - { - if (id == null) - throw new ArgumentNullException("id"); - if (!id.GetType().IsSerializable) - throw new ArgumentException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"), "id"); - Contract.EndContractBlock(); - - if (m_locked) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - } - - EvidenceBase evidence = WrapLegacyEvidence(id); - Type evidenceIndex = GetEvidenceIndexType(evidence); - - // Whidbey allowed for multiple types of the same evidence, so if we're being called via the Whidbey - // APIs, then allow the evidences to merge together. - AddHostEvidence(evidence, evidenceIndex, DuplicateEvidenceAction.Merge); - } - - [Obsolete("This method is obsolete. Please use AddAssemblyEvidence instead.")] - public void AddAssembly(object id) - { - if (id == null) - throw new ArgumentNullException("id"); - if (!id.GetType().IsSerializable) - throw new ArgumentException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"), "id"); - Contract.EndContractBlock(); - - EvidenceBase evidence = WrapLegacyEvidence(id); - Type evidenceIndex = GetEvidenceIndexType(evidence); - - // Whidbey allowed for multiple types of the same evidence, so if we're being called via the Whidbey - // APIs, then allow the evidences to merge together. - AddAssemblyEvidence(evidence, evidenceIndex, DuplicateEvidenceAction.Merge); - } - - /// - /// Add a piece of evidence to the assembly supplied evidence list. This method will disallow adding - /// evidence if there is already evidence of that type in the assembly list. - /// - [ComVisible(false)] - public void AddAssemblyEvidence(T evidence) where T : EvidenceBase - { - if (evidence == null) - throw new ArgumentNullException("evidence"); - Contract.EndContractBlock(); - - // Index the evidence under the type that the Add function was called with, unless we were given - // a plain EvidenceBase or a wrapped legacy evidence. In that case, we need to index under a - // more specific type. - Type evidenceType = typeof(T); - if (typeof(T) == typeof(EvidenceBase) || evidence is ILegacyEvidenceAdapter) - { - evidenceType = GetEvidenceIndexType(evidence); - } - - AddAssemblyEvidence(evidence, evidenceType, DuplicateEvidenceAction.Throw); - } - - private void AddAssemblyEvidence(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction) - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - AddAssemblyEvidenceNoLock(evidence, evidenceType, duplicateAction); - } - } - - private void AddAssemblyEvidenceNoLock(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction) - { - Contract.Assert(IsWriterLockHeld); - Contract.Assert(evidence != null); - Contract.Assert(evidenceType != null); - - // We need to make sure that any target supplied evidence is deserialized before adding to the - // Assembly collection in order to preserve the semantics that the evidence objects supplied by - // the target are the original versions and evidence objects added via the APIs are the duplicates. - DeserializeTargetEvidence(); - - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType, true); - - ++m_version; - if (descriptor.AssemblyEvidence == null) - { - descriptor.AssemblyEvidence = evidence; - } - else - { - descriptor.AssemblyEvidence = HandleDuplicateEvidence(descriptor.AssemblyEvidence, - evidence, - duplicateAction); - } - } - - /// - /// Add a piece of evidence to the host supplied evidence list. This method will disallow adding - /// evidence if there is already evidence of that type in the host list. - /// - [ComVisible(false)] - public void AddHostEvidence(T evidence) where T : EvidenceBase - { - if (evidence == null) - throw new ArgumentNullException("evidence"); - Contract.EndContractBlock(); - - // Index the evidence under the type that the Add function was called with, unless we were given - // a plain EvidenceBase or a wrapped legacy evidence. In that case, we need to index under a - // more specific type. - Type evidenceType = typeof(T); - if (typeof(T) == typeof(EvidenceBase) || evidence is ILegacyEvidenceAdapter) - { - evidenceType = GetEvidenceIndexType(evidence); - } - - AddHostEvidence(evidence, evidenceType, DuplicateEvidenceAction.Throw); - } - - [SecuritySafeCritical] - private void AddHostEvidence(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction) - { - Contract.Assert(evidence != null); - Contract.Assert(evidenceType != null); - - if (Locked) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - } - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - AddHostEvidenceNoLock(evidence, evidenceType, duplicateAction); - } - } - - /// - /// Add evidence to the host supplied evidence collection without acquiring the evidence lock or - /// checking to make sure that the caller has permission to bypass locked evidence. - /// - private void AddHostEvidenceNoLock(EvidenceBase evidence, Type evidenceType, DuplicateEvidenceAction duplicateAction) - { - Contract.Assert(IsWriterLockHeld); - Contract.Assert(evidence != null); - Contract.Assert(evidenceType != null); - - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType, true); - - ++m_version; - if (descriptor.HostEvidence == null) - { - descriptor.HostEvidence = evidence; - } - else - { - descriptor.HostEvidence = HandleDuplicateEvidence(descriptor.HostEvidence, - evidence, - duplicateAction); - } - } - - /// - /// Ask the host for the types of evidence that it might provide if it is asked. - /// - /// This should only be called when setting up the Evidence collection to interact with the - /// host, and should not be used once that connection is established and the evidence has been - /// made available to user code. - /// - [SecurityCritical] - private void QueryHostForPossibleEvidenceTypes() - { -#if FEATURE_CAS_POLICY - Contract.Assert(IsWriterLockHeld); - - // First check to see if we have a HostSecurityManager - if (AppDomain.CurrentDomain.DomainManager != null) - { - HostSecurityManager hsm = AppDomain.CurrentDomain.DomainManager.HostSecurityManager; - if (hsm != null) - { - Type[] hostSuppliedTypes = null; - - AppDomain targetDomain = m_target.Target as AppDomain; - Assembly targetAssembly = m_target.Target as Assembly; - - // - // If the HostSecurityManager wants to supply evidence for the type of target that we have, - // then ask it what types of evidence it might supply. - // - - if (targetAssembly != null && - (hsm.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) == HostSecurityManagerOptions.HostAssemblyEvidence) - { - hostSuppliedTypes = hsm.GetHostSuppliedAssemblyEvidenceTypes(targetAssembly); - } - else if (targetDomain != null && - (hsm.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence) - { - hostSuppliedTypes = hsm.GetHostSuppliedAppDomainEvidenceTypes(); - } - - // - // Finally, mark the descriptor for each of the types that the host can supply to indicate - // we should ask the host to generate them if we're asked. - // - - if (hostSuppliedTypes != null) - { - foreach (Type hostEvidenceType in hostSuppliedTypes) - { - EvidenceTypeDescriptor evidenceDescriptor = GetEvidenceTypeDescriptor(hostEvidenceType, true); - evidenceDescriptor.HostCanGenerate = true; - } - } - } - } -#endif // FEATURE_CAS_POLICY - } - - internal bool IsUnmodified - { - get { return m_version == 0; } - } - - /// - /// Set or check to see if the evidence is locked. Locked evidence cannot have its host supplied - /// evidence list be modified without a successful demand for ControlEvidence. Any code can lock - /// evidence, but only code with ControlEvidence may unlock it. - /// - /// This lock is not the same as the synchronization lock that gates access to the evidence collection. - /// - public bool Locked - { - get - { - return m_locked; - } - - [SecuritySafeCritical] - set - { - if (!value) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - - m_locked = false; - } - else - { - m_locked = true; - } - } - } - - /// - /// Target of any delay generated evidence objects - /// - internal IRuntimeEvidenceFactory Target - { - get { return m_target; } - - // - // There are two retargeting scenarios supported: - // - // 1. A PEFileEvidenceFactory is being upgraded to an AssemblyEvidenceFactory and we don't want - // to throw away any already generated evidence. - // 2. A detached evidence collection is being applied to an AppDomain and that domain has a - // HostSecurityManager. In that case, we want to attach the target to the AppDomain to - // allow the HostSecurityManager to get callbacks for delay generated evidence. - // - - [SecurityCritical] - set - { -#if FEATURE_CAS_POLICY - Contract.Assert((m_target != null && m_target is PEFileEvidenceFactory && value != null && value is AssemblyEvidenceFactory) || - (m_target == null && value != null && value is AppDomainEvidenceFactory), - "Evidence retargeting should only be from PEFile -> Assembly or detached -> AppDomain."); -#endif // FEATURE_CAS_POLICY - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - m_target = value; - - // Since we've updated what we're pointing at, we need to query the host to determine what - // types of evidence that it can generate for this new target. - QueryHostForPossibleEvidenceTypes(); - } - } - } - - /// - /// Get the type that would be used to index into the evidence dictionary for this object - /// - private static Type GetEvidenceIndexType(EvidenceBase evidence) - { - Contract.Assert(evidence != null); - - // - // Legacy wrapper evidence types should be indexed via the type of evidence that they're wrapping - // so check to see if we have one of those; otherwise just return the type itself. - // - - ILegacyEvidenceAdapter adapter = evidence as ILegacyEvidenceAdapter; - return adapter == null ? evidence.GetType() : adapter.EvidenceType; - } - - /// - /// Get the type descriptor for a specific type of evidence. This method should be used instead - /// of accessing the dictionary directly as it will handle the case where a new descriptor needs - /// to be created. - /// - internal EvidenceTypeDescriptor GetEvidenceTypeDescriptor(Type evidenceType) - { - return GetEvidenceTypeDescriptor(evidenceType, false); - } - - /// - /// Get the type descriptor for a specific type of evidence, optionally creating a descriptor if - /// we did not yet know about this type of evidence. This method should be used instead of - /// accessing the dictionary directly as it will handle the case where a new descriptor needs - /// to be created. - /// - private EvidenceTypeDescriptor GetEvidenceTypeDescriptor(Type evidenceType, bool addIfNotExist) - { - Contract.Assert(IsReaderLockHeld || IsWriterLockHeld); - Contract.Assert(evidenceType != null); - - // If we don't know about the type being indexed and we don't want to add it then exit out - EvidenceTypeDescriptor descriptor = null; - if (!m_evidence.TryGetValue(evidenceType, out descriptor) && !addIfNotExist) - { - return null; - } - - // If we haven't yet created a descriptor for this type then create one now - if (descriptor == null) - { - descriptor = new EvidenceTypeDescriptor(); -#if _DEBUG - descriptor.SetEvidenceType(evidenceType); -#endif // _DEBUG - - bool upgradedLock = false; - LockCookie upgradeCookie = new LockCookie(); - try - { - if (!IsWriterLockHeld) - { - upgradeCookie = UpgradeToWriterLock(); - upgradedLock = true; - } - - m_evidence[evidenceType] = descriptor; - } - finally - { - if (upgradedLock) - DowngradeFromWriterLock(ref upgradeCookie); - } - } - - return descriptor; - } - - /// - /// This method is called if a piece of evidence is added but another piece of evidence of the same - /// type already existed. We have different strategies depending on compatibility concerns of the - /// calling code. - /// - private static EvidenceBase HandleDuplicateEvidence(EvidenceBase original, - EvidenceBase duplicate, - DuplicateEvidenceAction action) - { - Contract.Assert(original != null); - Contract.Assert(duplicate != null); - Contract.Assert(original.GetType() == duplicate.GetType() || original.GetType() == typeof(LegacyEvidenceList)); - - switch (action) - { - // Throw - duplicate evidence is not allowed (Arrowhead behavior), so throw an exception - case DuplicateEvidenceAction.Throw: - throw new InvalidOperationException(Environment.GetResourceString("Policy_DuplicateEvidence", duplicate.GetType().FullName)); - - // SelectNewObject - MergeWithNoDuplicates behavior - the duplicate object wins - case DuplicateEvidenceAction.SelectNewObject: - return duplicate; - - // Merge - compat behavior. Merge the old and new evidence into a list so that both may exist - case DuplicateEvidenceAction.Merge: - - LegacyEvidenceList list = original as LegacyEvidenceList; - if (list == null) - { - list = new LegacyEvidenceList(); - list.Add(original); - } - - list.Add(duplicate); - return list; - - default: - BCLDebug.Assert(false, "Uknown DuplicateEvidenceAction"); - return null; - } - } - - /// - /// Wrap evidence we recieved through a legacy API to ensure that it is stored in an EvidenceBase - /// - private static EvidenceBase WrapLegacyEvidence(object evidence) - { - Contract.Assert(evidence != null); - - EvidenceBase wrappedEvidence = evidence as EvidenceBase; - if (wrappedEvidence == null) - { - wrappedEvidence = new LegacyEvidenceWrapper(evidence); - } - - return wrappedEvidence; - } - - /// - /// Upwrap evidence stored in a legacy adapter. - /// - /// This is only necessary for the case where multiple objects derived from EvidenceBase is - /// are added via the legacy APIs and are then retrieved via GetHostEvidence. This may occur if - /// a legacy application adds CLR supplied evidence types via the old APIs and a new application - /// consumes the resulting evidence. - /// - private static object UnwrapEvidence(EvidenceBase evidence) - { - ILegacyEvidenceAdapter adapter = evidence as ILegacyEvidenceAdapter; - return adapter == null ? evidence : adapter.EvidenceObject; - } - - /// - /// Merge two evidence collections together. Note that this will cause all of the lazily - /// generated evidence for the input collection to be generated, as well as causing any lazily - /// generated evidence that both collections share to be generated in the target. - /// - [SecuritySafeCritical] - public void Merge(Evidence evidence) - { - if (evidence == null) - { - return; - } - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - bool checkedLock = false; - IEnumerator hostEnumerator = evidence.GetHostEnumerator(); - while (hostEnumerator.MoveNext()) - { - if (Locked && !checkedLock) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - checkedLock = true; - } - - // If we could potentially have evidence of the type about to be merged into our host list, - // then make sure that we generate that evidence before merging. This will prevent the - // newly merged evidence from masking the value that we would have generated on our own. - Type hostEvidenceType = hostEnumerator.Current.GetType(); - if (m_evidence.ContainsKey(hostEvidenceType)) - { - GetHostEvidenceNoLock(hostEvidenceType); - } - - EvidenceBase hostEvidence = WrapLegacyEvidence(hostEnumerator.Current); - AddHostEvidenceNoLock(hostEvidence, - GetEvidenceIndexType(hostEvidence), - DuplicateEvidenceAction.Merge); - } - - // Add each piece of assembly evidence. We don't need to deserialize our copy of the - // evidence because AddAssemblyEvidenceNoLock will do this for us. - IEnumerator assemblyEnumerator = evidence.GetAssemblyEnumerator(); - while (assemblyEnumerator.MoveNext()) - { - EvidenceBase assemblyEvidence = WrapLegacyEvidence(assemblyEnumerator.Current); - AddAssemblyEvidenceNoLock(assemblyEvidence, - GetEvidenceIndexType(assemblyEvidence), - DuplicateEvidenceAction.Merge); - } - } - } - - /// - /// Same as merge, except only one instance of any one evidence type is allowed. When duplicates - /// are found, the evidence in the input argument will have priority. Note this will force the - /// entire input evidence to be generated, and does not check for locked evidence - /// - internal void MergeWithNoDuplicates(Evidence evidence) - { - if (evidence == null) - { - return; - } - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - IEnumerator hostEnumerator = evidence.GetHostEnumerator(); - while (hostEnumerator.MoveNext()) - { - EvidenceBase hostEvidence = WrapLegacyEvidence(hostEnumerator.Current); - AddHostEvidenceNoLock(hostEvidence, - GetEvidenceIndexType(hostEvidence), - DuplicateEvidenceAction.SelectNewObject); - } - - IEnumerator assemblyEnumerator = evidence.GetAssemblyEnumerator(); - while (assemblyEnumerator.MoveNext()) - { - EvidenceBase assemblyEvidence = WrapLegacyEvidence(assemblyEnumerator.Current); - AddAssemblyEvidenceNoLock(assemblyEvidence, - GetEvidenceIndexType(assemblyEvidence), - DuplicateEvidenceAction.SelectNewObject); - } - } - } - -#if FEATURE_SERIALIZATION - /// - /// Do a full serialization of the evidence, which requires that we generate all of the evidence - /// we can and disconnect ourselves from the host and source assembly. - /// - [ComVisible(false)] - [OnSerializing] - [SecurityCritical] - [PermissionSet(SecurityAction.Assert, Unrestricted = true)] - private void OnSerializing(StreamingContext context) - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - // First, force all of the host evidence that might be lazily generated to be created - foreach (Type evidenceType in new List(m_evidence.Keys)) - { - GetHostEvidenceNoLock(evidenceType); - } - - // Also ensure that all serialized assembly evidence has been created - DeserializeTargetEvidence(); - } - - // Fill in legacy evidence lists. We can't guarantee thread-safety here using locks - // because we can't put a lock in the serialization code that will read the lists. - // The best we can do is prevent another thread from seeing a half-populated list. - // Therefore, we assign the lists after we've populated them fully (and declare them volatile.) - ArrayList hostList = new ArrayList(); - IEnumerator hostEnumerator = GetHostEnumerator(); - while (hostEnumerator.MoveNext()) - { - hostList.Add(hostEnumerator.Current); - } - m_hostList = hostList; - - ArrayList assemblyList = new ArrayList(); - IEnumerator assemblyEnumerator = GetAssemblyEnumerator(); - while (assemblyEnumerator.MoveNext()) - { - assemblyList.Add(assemblyEnumerator.Current); - } - m_assemblyList = assemblyList; - } - - /// - /// Finish deserializing legacy evidence - /// - [ComVisible(false)] - [OnDeserialized] - [SecurityCritical] - private void OnDeserialized(StreamingContext context) - { - // Look at host and assembly evidence lists only if we serialized using Whidbey. - if (m_evidence == null) - { - m_evidence = new Dictionary(); - - // Whidbey evidence may need to be wrapped or added to a LegacyEvidenceList, so we go - // through the legacy APIs to add them. -#pragma warning disable 618 - if (m_hostList != null) - { - foreach (object evidenceObject in m_hostList) - { - if (evidenceObject != null) - { - AddHost(evidenceObject); - } - } - - m_hostList = null; - } - - if (m_assemblyList != null) - { - foreach (object evidenceObject in m_assemblyList) - { - if (evidenceObject != null) - { - AddAssembly(evidenceObject); - } - } - - m_assemblyList = null; - } -#pragma warning restore 618 - } - - // see code:System.Security.Policy.Evidence#EvidenceLock - m_evidenceLock = new ReaderWriterLock(); - } -#endif // FEATURE_SERIALIZATION - - /// - /// Load any serialized evidence out of the target assembly into our evidence collection. - /// - /// We allow entry to this method with only a reader lock held, since most of the time we will - /// not need to write to the evidence dictionary. If we haven't yet deserialized the target - /// evidence, then we will upgrade to a writer lock at that point. - /// - private void DeserializeTargetEvidence() - { -#if FEATURE_SERIALIZATION - Contract.Assert(IsReaderLockHeld || IsWriterLockHeld); - - if (m_target != null && !m_deserializedTargetEvidence) - { - bool upgradedLock = false; - LockCookie lockCookie = new LockCookie(); - try - { - if (!IsWriterLockHeld) - { - lockCookie = UpgradeToWriterLock(); - upgradedLock = true; - } - - // Set this to true here because AddAssemblyEvidenceNoLock will attempt to reenter this - // method creating possible infinite recursion. - m_deserializedTargetEvidence = true; - - foreach (EvidenceBase targetEvidence in m_target.GetFactorySuppliedEvidence()) - { - AddAssemblyEvidenceNoLock(targetEvidence, GetEvidenceIndexType(targetEvidence), DuplicateEvidenceAction.Throw); - } - } - finally - { - if (upgradedLock) - DowngradeFromWriterLock(ref lockCookie); - } - } -#endif // FEATURE_SERIALIZATION - } - -#if FEATURE_SERIALIZATION - /// - /// Serialize out raw evidence objects which have already been generated, ignoring any evidence - /// which might be present but has not yet been created for this assembly. - /// - /// This is used for indexing into the security policy cache, since we know that once policy is - /// resolved, the relevent membership conditions will have checked for any applicable evidence - /// and therefore after poliyc resolution this evidence collection will contain any evidence - /// objects necessary to arrive at its grant set. - /// - [SecurityCritical] - internal byte[] RawSerialize() - { - try - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - // Filter out any evidence which is not yet generated - Dictionary generatedEvidence = new Dictionary(); - foreach (KeyValuePair evidenceType in m_evidence) - { - if (evidenceType.Value != null && evidenceType.Value.HostEvidence != null) - { - generatedEvidence[evidenceType.Key] = evidenceType.Value.HostEvidence; - } - } - - using (MemoryStream serializationStream = new MemoryStream()) - { - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(serializationStream, generatedEvidence); - return serializationStream.ToArray(); - } - } - } - catch (SecurityException) - { - // We're running in a context where it's not safe to serialize the evidence out. In this case - // Simply decline to cache the result of the policy evaluation - return null; - } - } -#endif // FEATURE_SERIALIZATION - - // - // ICollection implementation. All ICollection interface members are potentially much more - // expensive in Arrowhead then they were downlevel. They should not be used if the standard Get and - // Add methods will work instead. - // - - [Obsolete("Evidence should not be treated as an ICollection. Please use the GetHostEnumerator and GetAssemblyEnumerator methods rather than using CopyTo.")] - public void CopyTo(Array array, int index) - { - if (array == null) - throw new ArgumentNullException("array"); - if (index < 0 || index > array.Length - Count) - throw new ArgumentOutOfRangeException("index"); - Contract.EndContractBlock(); - - int currentIndex = index; - - IEnumerator hostEnumerator = GetHostEnumerator(); - while (hostEnumerator.MoveNext()) - { - array.SetValue(hostEnumerator.Current, currentIndex); - ++currentIndex; - } - - IEnumerator assemblyEnumerator = GetAssemblyEnumerator(); - while (assemblyEnumerator.MoveNext()) - { - array.SetValue(assemblyEnumerator.Current, currentIndex); - ++currentIndex; - } - } - - public IEnumerator GetHostEnumerator() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Host); - } - } - - public IEnumerator GetAssemblyEnumerator() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - DeserializeTargetEvidence(); - return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Assembly); - } - } - - /// - /// Get an enumerator that can iterate over the raw evidence objects stored for the assembly - /// - internal RawEvidenceEnumerator GetRawAssemblyEvidenceEnumerator() - { - Contract.Assert(IsReaderLockHeld); - DeserializeTargetEvidence(); - return new RawEvidenceEnumerator(this, new List(m_evidence.Keys), false); - } - - /// - /// Get an enumerator that can iterate over the raw evidence objects stored for the host - /// - /// - internal RawEvidenceEnumerator GetRawHostEvidenceEnumerator() - { - Contract.Assert(IsReaderLockHeld); - return new RawEvidenceEnumerator(this, new List(m_evidence.Keys), true); - } - - [Obsolete("GetEnumerator is obsolete. Please use GetAssemblyEnumerator and GetHostEnumerator instead.")] - public IEnumerator GetEnumerator() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - return new EvidenceEnumerator(this, EvidenceEnumerator.Category.Host | EvidenceEnumerator.Category.Assembly); - } - } - - /// - /// Get a specific type of assembly supplied evidence - /// - [ComVisible(false)] - public T GetAssemblyEvidence() where T : EvidenceBase - { - return UnwrapEvidence(GetAssemblyEvidence(typeof(T))) as T; - } - - internal EvidenceBase GetAssemblyEvidence(Type type) - { - Contract.Assert(type != null); - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - return GetAssemblyEvidenceNoLock(type); - } - } - - private EvidenceBase GetAssemblyEvidenceNoLock(Type type) - { - Contract.Assert(IsReaderLockHeld || IsWriterLockHeld); - Contract.Assert(type != null); - - DeserializeTargetEvidence(); - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(type); - if (descriptor != null) - { - return descriptor.AssemblyEvidence; - } - - return null; - } - - /// - /// Get a specific type of host supplied evidence - /// - [ComVisible(false)] - public T GetHostEvidence() where T : EvidenceBase - { - return UnwrapEvidence(GetHostEvidence(typeof(T))) as T; - } - - /// - /// Get a specific type of evidence from the host which may not have been verified yet. If the - /// evidence was not verified, then don't mark it as being used yet. - /// - internal T GetDelayEvaluatedHostEvidence() where T : EvidenceBase, IDelayEvaluatedEvidence - { - return UnwrapEvidence(GetHostEvidence(typeof(T), false)) as T; - } - - internal EvidenceBase GetHostEvidence(Type type) - { - Contract.Assert(type != null); - - return GetHostEvidence(type, true); - } - - [SecuritySafeCritical] - private EvidenceBase GetHostEvidence(Type type, bool markDelayEvaluatedEvidenceUsed) - { - Contract.Assert(type != null); - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - EvidenceBase evidence = GetHostEvidenceNoLock(type); - - if (markDelayEvaluatedEvidenceUsed) - { - IDelayEvaluatedEvidence delayEvidence = evidence as IDelayEvaluatedEvidence; - if (delayEvidence != null) - { - delayEvidence.MarkUsed(); - } - } - - return evidence; - } - } - - /// - /// Get host supplied evidence from the collection - /// - /// We attempt to find host evdience in the following order: - /// - /// 1. Already generated or explicitly supplied evidence - /// 2. Evidence supplied by the CLR host - /// 3. Evidence supplied by the CLR itself - /// - [SecurityCritical] - private EvidenceBase GetHostEvidenceNoLock(Type type) - { - Contract.Assert(IsReaderLockHeld || IsWriterLockHeld); - Contract.Assert(type != null); - - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(type); - - // If the evidence descriptor doesn't exist for the host evidence type than the evidence doesn't - // exist and neither the host nor the runtime can produce it. - if (descriptor == null) - { - return null; - } - - // If the evidence has already been generated or if it was explicitly provided then return that - if (descriptor.HostEvidence != null) - { - return descriptor.HostEvidence; - } - - // If we have a target, then the host or the runtime might be able to generate this type of - // evidence on demand. - if (m_target != null && !descriptor.Generated) - { - using (EvidenceUpgradeLockHolder lockHolder = new EvidenceUpgradeLockHolder(this)) - { - // Make sure that we don't attempt to generate this type of evidencea again if we fail to - // generate it now. - descriptor.Generated = true; - - EvidenceBase generatedEvidence = GenerateHostEvidence(type, descriptor.HostCanGenerate); - if (generatedEvidence != null) - { - descriptor.HostEvidence = generatedEvidence; - - // - // #BackpatchGeneratedEvidence - // - // If we were cloned from another evidence collection propigate any generated evidence - // back to the original collection. Since Assembly and AppDomain both clone their - // evidence before giving it to users, this prevents us from having to regenerate - // evidence types on each clone that gets created. Note that we do not want to do this - // backpatching if the origin already has evidence of this type or if it has had - // this type of evidence removed from its collection. - // - - Evidence cloneOrigin = m_cloneOrigin != null ? m_cloneOrigin.Target as Evidence : null; - if (cloneOrigin != null) - { - BCLDebug.Assert(cloneOrigin.Target != null && cloneOrigin.Target == Target, - "Attempt to backpatch evidence to a collection with a different target."); - - using (EvidenceLockHolder cloneLockHolder = new EvidenceLockHolder(cloneOrigin, EvidenceLockHolder.LockType.Writer)) - { - EvidenceTypeDescriptor cloneDescriptor = cloneOrigin.GetEvidenceTypeDescriptor(type); - if (cloneDescriptor != null && cloneDescriptor.HostEvidence == null) - { - cloneDescriptor.HostEvidence = generatedEvidence.Clone() as EvidenceBase; - } - } - } - - } - - return generatedEvidence; - } - } - - // The evidence could not be generated and was not found - return null; - } - - /// - /// Attempt to generate host evidence on demand via calls to the runtime host or the evidence facotry - /// - [SecurityCritical] - private EvidenceBase GenerateHostEvidence(Type type, bool hostCanGenerate) - { - Contract.Assert(type != null); - Contract.Assert(IsWriterLockHeld); - -#if FEATURE_CAS_POLICY - // First let the host generate the evidence if it can. - if (hostCanGenerate) - { - AppDomain targetDomain = m_target.Target as AppDomain; - Assembly targetAssembly = m_target.Target as Assembly; - - EvidenceBase hostEvidence = null; - if (targetDomain != null) - { - hostEvidence = AppDomain.CurrentDomain.HostSecurityManager.GenerateAppDomainEvidence(type); - } - else if (targetAssembly != null) - { - hostEvidence = AppDomain.CurrentDomain.HostSecurityManager.GenerateAssemblyEvidence(type, targetAssembly); - } - - // If the host generated the evidence, verify that it generated the evidence we expected - // and use that. - if (hostEvidence != null) - { - if (!type.IsAssignableFrom(hostEvidence.GetType())) - { - string hostType = AppDomain.CurrentDomain.HostSecurityManager.GetType().FullName; - string recievedType = hostEvidence.GetType().FullName; - string requestedType = type.FullName; - - throw new InvalidOperationException(Environment.GetResourceString("Policy_IncorrectHostEvidence", hostType, recievedType, requestedType)); - } - - return hostEvidence; - } - } -#endif // FEATURE_CAS_POLICY - - // Finally, check to see if the CLR can generate the evidence - return m_target.GenerateEvidence(type); - } - - [Obsolete("Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to iterate over the evidence to collect a count.")] - public int Count - { - get - { - int count = 0; - - IEnumerator hostEvidence = GetHostEnumerator(); - while (hostEvidence.MoveNext()) - { - ++count; - } - - IEnumerator assemblyEvidence = GetAssemblyEnumerator(); - while (assemblyEvidence.MoveNext()) - { - ++count; - } - - return count; - } - } - - /// - /// Get the number of pieces of evidence which are currently generated, without causing any - /// lazily generated evidence to be created. - /// - [ComVisible(false)] - internal int RawCount - { - get - { - int count = 0; - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - foreach (Type evidenceType in new List(m_evidence.Keys)) - { - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(evidenceType); - - if (descriptor != null) - { - if (descriptor.AssemblyEvidence != null) - { - ++count; - } - if (descriptor.HostEvidence != null) - { - ++count; - } - } - } - } - - return count; - } - } - - public Object SyncRoot - { - get { return this; } - } - - public bool IsSynchronized - { - get { return true; } - } - - public bool IsReadOnly - { - get { return false; } - } - -#if FEATURE_CAS_POLICY - [ComVisible(false)] - public Evidence Clone() - { - return new Evidence(this); - } -#endif // FEATURE_CAS_POLICY - - [ComVisible(false)] - [SecuritySafeCritical] - public void Clear() - { - if (Locked) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - } - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - ++m_version; - m_evidence.Clear(); - } - } - - [ComVisible(false)] - [SecuritySafeCritical] - public void RemoveType(Type t) - { - if (t == null) - throw new ArgumentNullException("t"); - Contract.EndContractBlock(); - - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Writer)) - { - EvidenceTypeDescriptor descriptor = GetEvidenceTypeDescriptor(t); - if (descriptor != null) - { - ++m_version; - - // If we've locked this evidence collection, we need to do the lock check in the case that - // either we have host evidence, or that the host might generate it, since removing the - // evidence will cause us to bypass the host's ability to ever generate the evidence. - if (Locked && (descriptor.HostEvidence != null || descriptor.HostCanGenerate)) - { - new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); - } - - m_evidence.Remove(t); - } - } - } - - /// - /// Mark all of the already generated evidence in the collection as having been used during a - /// policy evaluation. - /// - internal void MarkAllEvidenceAsUsed() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - foreach (KeyValuePair evidenceType in m_evidence) - { - if (evidenceType.Value != null) - { - IDelayEvaluatedEvidence hostEvidence = evidenceType.Value.HostEvidence as IDelayEvaluatedEvidence; - if (hostEvidence != null) - { - hostEvidence.MarkUsed(); - } - - IDelayEvaluatedEvidence assemblyEvidence = evidenceType.Value.AssemblyEvidence as IDelayEvaluatedEvidence; - if (assemblyEvidence != null) - { - assemblyEvidence.MarkUsed(); - } - } - } - } - } - -#if FEATURE_CAS_POLICY - /// - /// Determine if delay evaluated strong name evidence is contained in this collection, and if so - /// if it was used during policy evaluation. - /// - /// This method is called from the VM in SecurityPolicy::WasStrongNameEvidenceUsed - /// This class should be used as an adapter layer to allow the public facing EvidenceEnumerator to - /// be able to get the evidence values out of an Evidence class. It is tightly coupled with the - /// internal data structures holding the evidence objects in the Evidence class. - /// - private bool WasStrongNameEvidenceUsed() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(this, EvidenceLockHolder.LockType.Reader)) - { - EvidenceTypeDescriptor snTypeDescriptor = GetEvidenceTypeDescriptor(typeof(StrongName)); - if (snTypeDescriptor != null) - { - IDelayEvaluatedEvidence snEvidence = snTypeDescriptor.HostEvidence as IDelayEvaluatedEvidence; - return snEvidence != null && snEvidence.WasUsed; - } - - return false; - } - } -#endif // FEATURE_CAS_POLICY - - /// - /// Utility class to wrap acquiring a lock onto the evidence collection - /// - private class EvidenceLockHolder : IDisposable - { - private Evidence m_target; - private LockType m_lockType; - - public enum LockType - { - Reader, - Writer - } - - public EvidenceLockHolder(Evidence target, LockType lockType) - { - Contract.Assert(target != null); - Contract.Assert(lockType == LockType.Reader || lockType == LockType.Writer); - - m_target = target; - m_lockType = lockType; - - if (m_lockType == LockType.Reader) - { - m_target.AcquireReaderLock(); - } - else - { - m_target.AcquireWriterlock(); - } - } - - public void Dispose() - { - if (m_lockType == LockType.Reader && m_target.IsReaderLockHeld) - { - m_target.ReleaseReaderLock(); - } - else if (m_lockType == LockType.Writer && m_target.IsWriterLockHeld) - { - m_target.ReleaseWriterLock(); - } - } - } - - /// - /// Utility class to wrap upgrading an acquired reader lock to a writer lock and then - /// downgrading it back to a reader lock. - /// - private class EvidenceUpgradeLockHolder : IDisposable - { - private Evidence m_target; - private LockCookie m_cookie; - - public EvidenceUpgradeLockHolder(Evidence target) - { - Contract.Assert(target != null); - - m_target = target; - m_cookie = m_target.UpgradeToWriterLock(); - } - - public void Dispose() - { - if (m_target.IsWriterLockHeld) - { - m_target.DowngradeFromWriterLock(ref m_cookie); - } - } - } - - /// - /// Enumerator that iterates directly over the evidence type map, returning back the evidence objects - /// that are contained in it. This enumerator will generate any lazy evaluated evidence it finds, - /// but it does not attempt to deal with legacy evidence adapters. - /// - /// This class should be used as an adapter layer to allow the public facing EvidenceEnumerator to - /// be able to get the evidence values out of an Evidence class. It is tightly coupled with the - /// internal data structures holding the evidence objects in the Evidence class. - /// - internal sealed class RawEvidenceEnumerator : IEnumerator - { - private Evidence m_evidence; - private bool m_hostEnumerator; // true to enumerate host evidence, false to enumerate assembly evidence - private uint m_evidenceVersion; - - private Type[] m_evidenceTypes; - private int m_typeIndex; - private EvidenceBase m_currentEvidence; - - private static volatile List s_expensiveEvidence; - - public RawEvidenceEnumerator(Evidence evidence, IEnumerable evidenceTypes, bool hostEnumerator) - { - Contract.Assert(evidence != null); - Contract.Assert(evidenceTypes != null); - - m_evidence = evidence; - m_hostEnumerator = hostEnumerator; - m_evidenceTypes = GenerateEvidenceTypes(evidence, evidenceTypes, hostEnumerator); - m_evidenceVersion = evidence.m_version; - - Reset(); - } - - public EvidenceBase Current - { - get - { - if (m_evidence.m_version != m_evidenceVersion) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); - - return m_currentEvidence; - } - } - - object IEnumerator.Current - { - get - { - if (m_evidence.m_version != m_evidenceVersion) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); - - return m_currentEvidence; - } - } - - /// - /// List of types of evidence that we would like to avoid generating if possible - /// - private static List ExpensiveEvidence - { - get - { - if (s_expensiveEvidence == null) - { - List expensiveEvidence = new List(); -#if FEATURE_CAS_POLICY - expensiveEvidence.Add(typeof(Hash)); - expensiveEvidence.Add(typeof(Publisher)); -#endif // FEATURE_CAS_POLICY - s_expensiveEvidence = expensiveEvidence; - -#if _DEBUG - List runtimeTypes = new List(Evidence.RuntimeEvidenceTypes); - foreach (Type expensiveType in s_expensiveEvidence) - { - BCLDebug.Assert(runtimeTypes.Contains(expensiveType), - "Evidence type not generated by the runtime found in expensive evidence type list"); - } -#endif // _DEBUG - } - - return s_expensiveEvidence; - } - } - - public void Dispose() - { - return; - } - - /// - /// Generate the array of types of evidence that could have values for - /// - private static Type[] GenerateEvidenceTypes(Evidence evidence, - IEnumerable evidenceTypes, - bool hostEvidence) - { - Contract.Assert(evidence != null); - Contract.Assert(evidenceTypes != null); - - // - // Sort the evidence being generated into three categories, which we enumerate in order: - // 1. Evidence which has already been generated - // 2. Evidence which is relatively inexpensive to generate - // 3. Evidence which is expensive to generate. - // - // This allows us to be as efficient as possible in case the user of the enumerator stops the - // enumeration before we step up to the next more expensive category. - // - - List alreadyGeneratedList = new List(); - List inexpensiveList = new List(); - List expensiveList = new List(ExpensiveEvidence.Count); - - // Iterate over the evidence types classifying into the three groups. We need to copy the list - // here since GetEvidenceTypeDescriptor will potentially update the evidence dictionary, which - // evidenceTypes iterates over. - foreach (Type evidenceType in evidenceTypes) - { - EvidenceTypeDescriptor descriptor = evidence.GetEvidenceTypeDescriptor(evidenceType); - BCLDebug.Assert(descriptor != null, "descriptor != null"); - - bool alreadyGenerated = (hostEvidence && descriptor.HostEvidence != null) || - (!hostEvidence && descriptor.AssemblyEvidence != null); - - if (alreadyGenerated) - { - alreadyGeneratedList.Add(evidenceType); - } - else if (ExpensiveEvidence.Contains(evidenceType)) - { - expensiveList.Add(evidenceType); - } - else - { - inexpensiveList.Add(evidenceType); - } - } - - Type[] enumerationTypes = new Type[alreadyGeneratedList.Count + inexpensiveList.Count + expensiveList.Count]; - alreadyGeneratedList.CopyTo(enumerationTypes, 0); - inexpensiveList.CopyTo(enumerationTypes, alreadyGeneratedList.Count); - expensiveList.CopyTo(enumerationTypes, alreadyGeneratedList.Count + inexpensiveList.Count); - - return enumerationTypes; - } - - [SecuritySafeCritical] - public bool MoveNext() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(m_evidence, EvidenceLockHolder.LockType.Reader)) - { - if (m_evidence.m_version != m_evidenceVersion) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); - - m_currentEvidence = null; - - // Iterate over the possible types of evidence that we could have until we find one that - // really exists, or we run out of posibilities. - do - { - ++m_typeIndex; - - if (m_typeIndex < m_evidenceTypes.Length) - { - if (m_hostEnumerator) - { - m_currentEvidence = m_evidence.GetHostEvidenceNoLock(m_evidenceTypes[m_typeIndex]); - } - else - { - m_currentEvidence = m_evidence.GetAssemblyEvidenceNoLock(m_evidenceTypes[m_typeIndex]); - } - } - } - while (m_typeIndex < m_evidenceTypes.Length && m_currentEvidence == null); - } - - return m_currentEvidence != null; - } - - public void Reset() - { - if (m_evidence.m_version != m_evidenceVersion) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); - - m_typeIndex = -1; - m_currentEvidence = null; - } - } - - private sealed class EvidenceEnumerator : IEnumerator - { - private Evidence m_evidence; - private Category m_category; - private Stack m_enumerators; - - private object m_currentEvidence; - - [Flags] - internal enum Category - { - Host = 0x1, // Enumerate only host supplied evidence - Assembly = 0x2 // Enumerate only assembly supplied evidence - } - - internal EvidenceEnumerator(Evidence evidence, Category category) - { - Contract.Assert(evidence != null); - Contract.Assert(evidence.IsReaderLockHeld); - - m_evidence = evidence; - m_category = category; - ResetNoLock(); - } - - public bool MoveNext() - { - IEnumerator currentEnumerator = CurrentEnumerator; - - // No more enumerators means we can't go any further - if (currentEnumerator == null) - { - m_currentEvidence = null; - return false; - } - - // See if the current enumerator can continue - if (currentEnumerator.MoveNext()) - { - // - // If we've found an adapter for legacy evidence, we need to unwrap it for it to be the - // current enumerator's value. For wrapped evidence, this is a simple unwrap, for a list of - // evidence, we need to make that the current enumerator and get its first value. - // - - LegacyEvidenceWrapper legacyWrapper = currentEnumerator.Current as LegacyEvidenceWrapper; - LegacyEvidenceList legacyList = currentEnumerator.Current as LegacyEvidenceList; - - if (legacyWrapper != null) - { - m_currentEvidence = legacyWrapper.EvidenceObject; - } - else if (legacyList != null) - { - IEnumerator legacyListEnumerator = legacyList.GetEnumerator(); - m_enumerators.Push(legacyListEnumerator); - MoveNext(); - } - else - { - m_currentEvidence = currentEnumerator.Current; - } - - BCLDebug.Assert(m_currentEvidence != null, "m_currentEvidence != null"); - return true; - } - else - { - // If we've reached the end of the current enumerator, move to the next one and try again - m_enumerators.Pop(); - return MoveNext(); - } - } - - public object Current - { - get { return m_currentEvidence; } - } - - private IEnumerator CurrentEnumerator - { - get - { - return m_enumerators.Count > 0 ? m_enumerators.Peek() as IEnumerator : null; - } - } - - public void Reset() - { - using (EvidenceLockHolder lockHolder = new EvidenceLockHolder(m_evidence, EvidenceLockHolder.LockType.Reader)) - { - ResetNoLock(); - } - } - - private void ResetNoLock() - { - Contract.Assert(m_evidence != null); - Contract.Assert(m_evidence.IsReaderLockHeld); - - m_currentEvidence = null; - m_enumerators = new Stack(); - - if ((m_category & Category.Host) == Category.Host) - { - m_enumerators.Push(m_evidence.GetRawHostEvidenceEnumerator()); - } - if ((m_category & Category.Assembly) == Category.Assembly) - { - m_enumerators.Push(m_evidence.GetRawAssemblyEvidenceEnumerator()); - } - } - } -#endif //!FEATURE_CORECLR && FEATURE_RWLOCK } } diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs index f142ebea2a..7fef1ded3c 100644 --- a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs +++ b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs @@ -7,6 +7,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; @@ -22,9 +23,6 @@ namespace System.Security.Policy /// [ComVisible(true)] [Serializable] -#pragma warning disable 618 - [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 public abstract class EvidenceBase { protected EvidenceBase() @@ -44,11 +42,6 @@ namespace System.Security.Policy /// Since legacy evidence objects would be cloned by being serialized, the default implementation /// of EvidenceBase will do the same. /// -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)] - [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 - [SecuritySafeCritical] public virtual EvidenceBase Clone() { #if FEATURE_SERIALIZATION @@ -86,9 +79,9 @@ namespace System.Security.Policy internal LegacyEvidenceWrapper(object legacyEvidence) { - Contract.Assert(legacyEvidence != null); - Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper"); - Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable"); + Debug.Assert(legacyEvidence != null); + Debug.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper"); + Debug.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable"); m_legacyEvidence = legacyEvidence; } @@ -113,10 +106,6 @@ namespace System.Security.Policy return m_legacyEvidence.GetHashCode(); } -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] -#pragma warning restore 618 - [SecuritySafeCritical] public override EvidenceBase Clone() { return base.Clone(); @@ -153,7 +142,7 @@ namespace System.Security.Policy { get { - Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are"); + Debug.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are"); ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter; return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType; @@ -162,10 +151,10 @@ namespace System.Security.Policy public void Add(EvidenceBase evidence) { - Contract.Assert(evidence != null); - Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType), + Debug.Assert(evidence != null); + Debug.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType), "LegacyEvidenceList must be homogeonous"); - Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList), + Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList), "Attempt to add a legacy evidence list to another legacy evidence list"); m_legacyEvidenceList.Add(evidence); @@ -181,10 +170,6 @@ namespace System.Security.Policy return m_legacyEvidenceList.GetEnumerator(); } -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] -#pragma warning restore 618 - [SecuritySafeCritical] public override EvidenceBase Clone() { return base.Clone(); diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs index bccf39218b..8deb145102 100644 --- a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs +++ b/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs @@ -41,7 +41,7 @@ namespace System.Security.Policy /// private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor) { - Contract.Assert(descriptor != null); + Debug.Assert(descriptor != null); m_hostCanGenerate = descriptor.m_hostCanGenerate; @@ -68,9 +68,9 @@ namespace System.Security.Policy set { - Contract.Assert(value != null); + Debug.Assert(value != null); #if _DEBUG - Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set"); + Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set"); #endif m_assemblyEvidence = value; } @@ -85,7 +85,7 @@ namespace System.Security.Policy set { - Contract.Assert(value, "Attempt to clear the Generated flag"); + Debug.Assert(value, "Attempt to clear the Generated flag"); m_generated = value; } } @@ -99,7 +99,7 @@ namespace System.Security.Policy set { - Contract.Assert(value, "Attempt to clear HostCanGenerate flag"); + Debug.Assert(value, "Attempt to clear HostCanGenerate flag"); m_hostCanGenerate = value; } } @@ -113,9 +113,9 @@ namespace System.Security.Policy set { - Contract.Assert(value != null); + Debug.Assert(value != null); #if _DEBUG - Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set"); + Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set"); #endif m_hostEvidence = value; } @@ -127,7 +127,7 @@ namespace System.Security.Policy /// private bool CheckEvidenceType(EvidenceBase evidence) { - Contract.Assert(evidence != null); + Debug.Assert(evidence != null); ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter; Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType; @@ -150,8 +150,8 @@ namespace System.Security.Policy /// internal void SetEvidenceType(Type evidenceType) { - Contract.Assert(evidenceType != null); - Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type"); + Debug.Assert(evidenceType != null); + Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type"); m_evidenceType = evidenceType; } diff --git a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs index 5bd36485db..8f8c07c9e4 100644 --- a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs +++ b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs @@ -18,7 +18,6 @@ namespace System.Security.Policy { /// bool IsVerified { - [System.Security.SecurityCritical] get; } diff --git a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs index 72c07d1246..9b58ece9f1 100644 --- a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs +++ b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs @@ -35,14 +35,6 @@ namespace System.Security.Policy { // The PermissionSet associated with this policy internal PermissionSet m_permSet; -#if FEATURE_CAS_POLICY - // Evidence which was not verified but which was required to generate this policy statement. - // This is not serialized, since once we serialize we lose the ability to verify the evidence, - // meaning that restoring this state is meaningless. - [NonSerialized] - private List m_dependentEvidence; -#endif - // The bitfield of inheritance properties associated with this policy internal PolicyStatementAttribute m_attributes; @@ -144,20 +136,13 @@ namespace System.Security.Policy { } } } - + public PolicyStatement Copy() { - PolicyStatement copy = new PolicyStatement(m_permSet, Attributes, true); // The PolicyStatement .ctor will copy the permission set -#if FEATURE_CAS_POLICY - if (HasDependentEvidence) - { - copy.m_dependentEvidence = new List(m_dependentEvidence); - } -#endif - - return copy; + // The PolicyStatement .ctor will copy the permission set + return new PolicyStatement(m_permSet, Attributes, true); } - + public String AttributeString { get @@ -199,44 +184,6 @@ namespace System.Security.Policy { return (flag & (int)m_attributes) != 0; } -#if FEATURE_CAS_POLICY - /// - /// Gets all of the delay evaluated evidence which needs to be verified before this policy can - /// be used. - /// - internal IEnumerable DependentEvidence - { - get - { - BCLDebug.Assert(HasDependentEvidence, "HasDependentEvidence"); - return m_dependentEvidence.AsReadOnly(); - } - } - - /// - /// Determine if this policy dependent upon the evaluation of any delay evaluated evidence - /// - internal bool HasDependentEvidence - { - get { return m_dependentEvidence != null && m_dependentEvidence.Count > 0; } - } - - /// - /// Add evidence which this policy statement is depending upon being verified to be valid. - /// - internal void AddDependentEvidence(IDelayEvaluatedEvidence dependentEvidence) - { - BCLDebug.Assert(dependentEvidence != null, "dependentEvidence != null"); - - if (m_dependentEvidence == null) - { - m_dependentEvidence = new List(); - } - - m_dependentEvidence.Add(dependentEvidence); - } -#endif - /// /// Union a child policy statement into this policy statement /// @@ -249,27 +196,6 @@ namespace System.Security.Policy { throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" )); } -#if FEATURE_CAS_POLICY - // If our code group generated a grant set based upon unverified evidence, or it generated a grant - // set strictly less than that of a child group based upon unverified evidence, we need to keep - // track of any unverified evidence our child group has. - if (childPolicy.HasDependentEvidence) - { - bool childEvidenceNeedsVerification = m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) && - !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(m_permSet); - - if (HasDependentEvidence || childEvidenceNeedsVerification) - { - if (m_dependentEvidence == null) - { - m_dependentEvidence = new List(); - } - - m_dependentEvidence.AddRange(childPolicy.DependentEvidence); - } - } -#endif - // We need to merge together our grant set and attributes. The result of this merge is // dependent upon if we're merging a child marked exclusive or not. If the child is not // exclusive, we need to union in its grant set and or in its attributes. However, if the child @@ -287,226 +213,6 @@ namespace System.Security.Policy { } } -#if FEATURE_CAS_POLICY - - public SecurityElement ToXml() - { - return ToXml( null ); - } - - public void FromXml( SecurityElement et ) - { - FromXml( et, null ); - } - - public SecurityElement ToXml( PolicyLevel level ) - { - return ToXml( level, false ); - } - - internal SecurityElement ToXml( PolicyLevel level, bool useInternal ) - { - SecurityElement e = new SecurityElement( "PolicyStatement" ); - e.AddAttribute( "version", "1" ); - if (m_attributes != PolicyStatementAttribute.Nothing) - e.AddAttribute( "Attributes", XMLUtil.BitFieldEnumToString( typeof( PolicyStatementAttribute ), m_attributes ) ); - - lock (this) - { - if (m_permSet != null) - { - if (m_permSet is NamedPermissionSet) - { - // If the named permission set exists in the parent level of this - // policy struct, then just save the name of the permission set. - // Otherwise, serialize it like normal. - - NamedPermissionSet namedPermSet = (NamedPermissionSet)m_permSet; - if (level != null && level.GetNamedPermissionSet( namedPermSet.Name ) != null) - { - e.AddAttribute( "PermissionSetName", namedPermSet.Name ); - } - else - { - if (useInternal) - e.AddChild( namedPermSet.InternalToXml() ); - else - e.AddChild( namedPermSet.ToXml() ); - } - } - else - { - if (useInternal) - e.AddChild( m_permSet.InternalToXml() ); - else - e.AddChild( m_permSet.ToXml() ); - } - } - } - - return e; - } - - [System.Security.SecuritySafeCritical] // auto-generated - public void FromXml( SecurityElement et, PolicyLevel level ) - { - FromXml( et, level, false ); - } - - [System.Security.SecurityCritical] // auto-generated - internal void FromXml( SecurityElement et, PolicyLevel level, bool allowInternalOnly ) - { - if (et == null) - throw new ArgumentNullException( "et" ); - - if (!et.Tag.Equals( "PolicyStatement" )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "PolicyStatement", this.GetType().FullName ) ); - Contract.EndContractBlock(); - - m_attributes = (PolicyStatementAttribute) 0; - - String strAttributes = et.Attribute( "Attributes" ); - - if (strAttributes != null) - m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes ); - - lock (this) - { - m_permSet = null; - - if (level != null) - { - String permSetName = et.Attribute( "PermissionSetName" ); - - if (permSetName != null) - { - m_permSet = level.GetNamedPermissionSetInternal( permSetName ); - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - if (m_permSet == null) - { - // There is no provided level, it is not a named permission set, or - // the named permission set doesn't exist in the provided level, - // so just create the class through reflection and decode normally. - - SecurityElement e = et.SearchForChildByTag( "PermissionSet" ); - - if (e != null) - { - String className = e.Attribute( "class" ); - - if (className != null && (className.Equals( "NamedPermissionSet" ) || - className.Equals( "System.Security.NamedPermissionSet" ))) - m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None ); - else - m_permSet = new PermissionSet( PermissionState.None ); - - try - { - m_permSet.FromXml( e, allowInternalOnly, true ); - } - catch - { - // ignore any exceptions from the decode process. - // Note: we go ahead and use the permission set anyway. This should be safe since - // the decode process should never give permission beyond what a proper decode would have - // given. - } - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) ); - } - } - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - [System.Security.SecurityCritical] // auto-generated - internal void FromXml( SecurityDocument doc, int position, PolicyLevel level, bool allowInternalOnly ) - { - if (doc == null) - throw new ArgumentNullException( "doc" ); - Contract.EndContractBlock(); - - if (!doc.GetTagForElement( position ).Equals( "PolicyStatement" )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), "PolicyStatement", this.GetType().FullName ) ); - - m_attributes = (PolicyStatementAttribute) 0; - - String strAttributes = doc.GetAttributeForElement( position, "Attributes" ); - - if (strAttributes != null) - m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes ); - - lock (this) - { - m_permSet = null; - - if (level != null) - { - String permSetName = doc.GetAttributeForElement( position, "PermissionSetName" ); - - if (permSetName != null) - { - m_permSet = level.GetNamedPermissionSetInternal( permSetName ); - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } - - - if (m_permSet == null) - { - // There is no provided level, it is not a named permission set, or - // the named permission set doesn't exist in the provided level, - // so just create the class through reflection and decode normally. - - ArrayList childPositions = doc.GetChildrenPositionForElement( position ); - int positionPermissionSet = -1; - - for (int i = 0; i < childPositions.Count; ++i) - { - if (doc.GetTagForElement( (int)childPositions[i] ).Equals( "PermissionSet" )) - { - positionPermissionSet = (int)childPositions[i]; - } - } - - if (positionPermissionSet != -1) - { - String className = doc.GetAttributeForElement( positionPermissionSet, "class" ); - - if (className != null && (className.Equals( "NamedPermissionSet" ) || - className.Equals( "System.Security.NamedPermissionSet" ))) - m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None ); - else - m_permSet = new PermissionSet( PermissionState.None ); - - m_permSet.FromXml( doc, positionPermissionSet, allowInternalOnly ); - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) ); - } - } - - if (m_permSet == null) - m_permSet = new PermissionSet( PermissionState.None ); - } - } -#endif // FEATURE_CAS_POLICY - - [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals( Object obj ) { diff --git a/src/mscorlib/src/System/Security/Policy/Site.cs b/src/mscorlib/src/System/Security/Policy/Site.cs index e7c6cd3d83..14a95e1666 100644 --- a/src/mscorlib/src/System/Security/Policy/Site.cs +++ b/src/mscorlib/src/System/Security/Policy/Site.cs @@ -10,6 +10,7 @@ // using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Security.Permissions; @@ -26,7 +27,7 @@ namespace System.Security.Policy public Site(String name) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); m_name = new SiteString( name ); @@ -34,7 +35,7 @@ namespace System.Security.Policy private Site(SiteString name) { - Contract.Assert(name != null); + Debug.Assert(name != null); m_name = name; } @@ -94,30 +95,6 @@ namespace System.Security.Policy return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement elem = new SecurityElement( "System.Security.Policy.Site" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Site" ), "Class name changed!" ); - - elem.AddAttribute( "version", "1" ); - - if(m_name != null) - elem.AddChild( new SecurityElement( "Name", m_name.ToString() ) ); - - return elem; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/mscorlib/src/System/Security/Policy/StrongName.cs b/src/mscorlib/src/System/Security/Policy/StrongName.cs index c49f2b0674..999b478ba7 100644 --- a/src/mscorlib/src/System/Security/Policy/StrongName.cs +++ b/src/mscorlib/src/System/Security/Policy/StrongName.cs @@ -42,20 +42,20 @@ namespace System.Security.Policy { internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly) { if (name == null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (String.IsNullOrEmpty(name)) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName")); if (blob == null) - throw new ArgumentNullException("blob"); + throw new ArgumentNullException(nameof(blob)); if (version == null) - throw new ArgumentNullException("version"); + throw new ArgumentNullException(nameof(version)); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; if (assembly != null && rtAssembly == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); + throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly)); m_publicKeyBlob = blob; m_name = name; @@ -89,14 +89,9 @@ namespace System.Security.Policy { bool IDelayEvaluatedEvidence.IsVerified { - [System.Security.SecurityCritical] // auto-generated get { -#if FEATURE_CAS_POLICY - return m_assembly != null ? m_assembly.IsStrongNameVerified : true; -#else // !FEATURE_CAS_POLICY return true; -#endif // FEATURE_CAS_POLICY } } @@ -133,52 +128,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement root = new SecurityElement( "StrongName" ); - root.AddAttribute( "version", "1" ); - - if (m_publicKeyBlob != null) - root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) ); - - if (m_name != null) - root.AddAttribute( "Name", m_name ); - - if (m_version != null) - root.AddAttribute( "Version", m_version.ToString() ); - - return root; - } - - internal void FromXml (SecurityElement element) - { - if (element == null) - throw new ArgumentNullException("element"); - if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); - Contract.EndContractBlock(); - - m_publicKeyBlob = null; - m_version = null; - - string key = element.Attribute("Key"); - if (key != null) - m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key)); - - m_name = element.Attribute("Name"); - - string version = element.Attribute("Version"); - if (version != null) - m_version = new Version(version); - } - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - public override bool Equals( Object o ) { StrongName that = (o as StrongName); diff --git a/src/mscorlib/src/System/Security/Policy/URL.cs b/src/mscorlib/src/System/Security/Policy/URL.cs index d3ad4f8724..3541124ac6 100644 --- a/src/mscorlib/src/System/Security/Policy/URL.cs +++ b/src/mscorlib/src/System/Security/Policy/URL.cs @@ -14,6 +14,7 @@ namespace System.Security.Policy { using System.Security.Util; using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -25,7 +26,7 @@ namespace System.Security.Policy { internal Url( String name, bool parsed ) { if (name == null) - throw new ArgumentNullException( "name" ); + throw new ArgumentNullException( nameof(name) ); Contract.EndContractBlock(); m_url = new URLString( name, parsed ); @@ -34,7 +35,7 @@ namespace System.Security.Policy { public Url( String name ) { if (name == null) - throw new ArgumentNullException( "name" ); + throw new ArgumentNullException( nameof(name) ); Contract.EndContractBlock(); m_url = new URLString( name ); @@ -42,7 +43,7 @@ namespace System.Security.Policy { private Url(Url url) { - Contract.Assert(url != null); + Debug.Assert(url != null); m_url = url.m_url; } @@ -87,28 +88,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement root = new SecurityElement( "System.Security.Policy.Url" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Url" ), "Class name changed!" ); - - root.AddAttribute( "version", "1" ); - - if (m_url != null) - root.AddChild( new SecurityElement( "Url", m_url.ToString() ) ); - - return root; - } - - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/mscorlib/src/System/Security/Policy/Zone.cs index c999abe340..a9f5d84aeb 100644 --- a/src/mscorlib/src/System/Security/Policy/Zone.cs +++ b/src/mscorlib/src/System/Security/Policy/Zone.cs @@ -9,23 +9,21 @@ // Zone is an IIdentity representing Internet/Intranet/MyComputer etc. // -namespace System.Security.Policy { +namespace System.Security.Policy +{ using System.Security.Util; using ZoneIdentityPermission = System.Security.Permissions.ZoneIdentityPermission; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class Zone : EvidenceBase, IIdentityPermissionFactory { -#if FEATURE_CAS_POLICY - [OptionalField(VersionAdded = 2)] - private String m_url; -#endif // FEATURE_CAS_POLICY private SecurityZone m_zone; private static readonly String[] s_names = @@ -42,36 +40,10 @@ namespace System.Security.Policy { private Zone(Zone zone) { - Contract.Assert(zone != null); - -#if FEATURE_CAS_POLICY - m_url = zone.m_url; -#endif // FEATURE_CAS_POLICY + Debug.Assert(zone != null); m_zone = zone.m_zone; } -#if FEATURE_CAS_POLICY - private Zone(String url) - { - m_url = url; - m_zone = SecurityZone.NoZone; - } - - public static Zone CreateFromUrl( String url ) - { - if (url == null) - throw new ArgumentNullException( "url" ); - Contract.EndContractBlock(); - - return new Zone( url ); - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private extern static SecurityZone _CreateFromUrl( String url ); -#endif // FEATURE_CAS_POLICY - public IPermission CreateIdentityPermission( Evidence evidence ) { return new ZoneIdentityPermission( SecurityZone ); @@ -79,14 +51,8 @@ namespace System.Security.Policy { public SecurityZone SecurityZone { - [System.Security.SecuritySafeCritical] // auto-generated get { -#if FEATURE_CAS_POLICY - if (m_url != null) - m_zone = _CreateFromUrl( m_url ); -#endif // FEATURE_CAS_POLICY - return m_zone; } } @@ -117,30 +83,6 @@ namespace System.Security.Policy { return Clone(); } -#if FEATURE_CAS_POLICY - internal SecurityElement ToXml() - { - SecurityElement elem = new SecurityElement( "System.Security.Policy.Zone" ); - // If you hit this assert then most likely you are trying to change the name of this class. - // This is ok as long as you change the hard coded string above and change the assert below. - Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Zone" ), "Class name changed!" ); - - elem.AddAttribute( "version", "1" ); - if (SecurityZone != SecurityZone.NoZone) - elem.AddChild( new SecurityElement( "Zone", s_names[(int)SecurityZone] ) ); - else - elem.AddChild( new SecurityElement( "Zone", s_names[s_names.Length-1] ) ); - return elem; - } -#endif // FEATURE_CAS_POLICY - -#if FEATURE_CAS_POLICY - public override String ToString() - { - return ToXml().ToString(); - } -#endif // FEATURE_CAS_POLICY - // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() diff --git a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs index fa77ac50f9..9eec46f774 100644 --- a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs +++ b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs @@ -2,15 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - namespace System.Security.Principal { -#if !FEATURE_CORECLR - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] -#endif - public enum TokenImpersonationLevel { + public enum TokenImpersonationLevel + { None = 0, Anonymous = 1, Identification = 2, diff --git a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs index ea9cd4be0f..9a84164460 100644 --- a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs +++ b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs @@ -11,7 +11,6 @@ namespace Microsoft.Win32.SafeHandles { // Introduce this handle to replace internal SafeTokenHandle, // which is mainly used to hold Windows thread or process access token - [SecurityCritical] public sealed class SafeAccessTokenHandle : SafeHandle { private SafeAccessTokenHandle() @@ -27,24 +26,20 @@ namespace Microsoft.Win32.SafeHandles { public static SafeAccessTokenHandle InvalidHandle { - [SecurityCritical] get { return new SafeAccessTokenHandle(IntPtr.Zero); } } public override bool IsInvalid { - [SecurityCritical] get { return handle == IntPtr.Zero || handle == new IntPtr(-1); } } - [SecurityCritical] protected override bool ReleaseHandle() { return Win32Native.CloseHandle(handle); } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLsaLogonProcessHandle() : base (true) {} @@ -57,7 +52,6 @@ namespace Microsoft.Win32.SafeHandles { get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); } } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { // LsaDeregisterLogonProcess returns an NTSTATUS @@ -65,7 +59,6 @@ namespace Microsoft.Win32.SafeHandles { } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaMemoryHandle : SafeBuffer { private SafeLsaMemoryHandle() : base(true) {} @@ -78,14 +71,12 @@ namespace Microsoft.Win32.SafeHandles { get { return new SafeLsaMemoryHandle( IntPtr.Zero ); } } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.LsaFreeMemory(handle) == 0; } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLsaPolicyHandle() : base(true) {} @@ -98,14 +89,12 @@ namespace Microsoft.Win32.SafeHandles { get { return new SafeLsaPolicyHandle( IntPtr.Zero ); } } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.LsaClose(handle) == 0; } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeLsaReturnBufferHandle : SafeBuffer { private SafeLsaReturnBufferHandle() : base (true) {} @@ -118,7 +107,6 @@ namespace Microsoft.Win32.SafeHandles { get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); } } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { // LsaFreeReturnBuffer returns an NTSTATUS @@ -126,7 +114,6 @@ namespace Microsoft.Win32.SafeHandles { } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeProcessHandle() : base (true) {} @@ -139,14 +126,12 @@ namespace Microsoft.Win32.SafeHandles { get { return new SafeProcessHandle(IntPtr.Zero); } } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.CloseHandle(handle); } } - [System.Security.SecurityCritical] // auto-generated internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeThreadHandle() : base (true) {} @@ -155,7 +140,6 @@ namespace Microsoft.Win32.SafeHandles { SetHandle(handle); } - [System.Security.SecurityCritical] override protected bool ReleaseHandle() { return Win32Native.CloseHandle(handle); diff --git a/src/mscorlib/src/System/Security/SecurityContext.cs b/src/mscorlib/src/System/Security/SecurityContext.cs index e422a312df..674c04196f 100644 --- a/src/mscorlib/src/System/Security/SecurityContext.cs +++ b/src/mscorlib/src/System/Security/SecurityContext.cs @@ -12,14 +12,11 @@ ** ===========================================================*/ namespace System.Security -{ +{ using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Threading; using System.Runtime.Remoting; -#if FEATURE_IMPERSONATION - using System.Security.Principal; -#endif using System.Collections; using System.Runtime.Serialization; using System.Security.Permissions; @@ -30,6 +27,7 @@ namespace System.Security #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // This enum must be kept in sync with the SecurityContextSource enum in the VM @@ -46,15 +44,6 @@ namespace System.Security All = 0x3FFF } -#if FEATURE_IMPERSONATION - internal enum WindowsImpersonationFlowMode { - IMP_FASTFLOW = 0, - IMP_NOFLOW = 1, - IMP_ALWAYSFLOW = 2, - IMP_DEFAULT = IMP_FASTFLOW - } -#endif - #if FEATURE_COMPRESSEDSTACK internal struct SecurityContextSwitcher: IDisposable { @@ -62,17 +51,12 @@ namespace System.Security internal SecurityContext currSC; //current SC - SetSecurityContext that created the switcher set this on the Thread internal ExecutionContext currEC; // current ExecutionContext on Thread internal CompressedStackSwitcher cssw; -#if FEATURE_IMPERSONATION - internal WindowsImpersonationContext wic; -#endif - [System.Security.SecuritySafeCritical] // overrides public transparent member public void Dispose() { Undo(); } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] @@ -90,7 +74,6 @@ namespace System.Security return true; } - [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] @@ -104,8 +87,8 @@ namespace System.Security if (currEC != null) { - Contract.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread"); - Contract.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch"); + Debug.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread"); + Debug.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch"); // restore the saved security context currEC.SecurityContext = prevSC.DangerousGetRawSecurityContext(); @@ -113,26 +96,13 @@ namespace System.Security else { // caller must have already restored the ExecutionContext - Contract.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC)); + Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC)); } currSC = null; // this will prevent the switcher object being used again bool bNoException = true; -#if FEATURE_IMPERSONATION - try - { - if (wic != null) - bNoException &= wic.UndoNoThrow(); - } - catch - { - // Failfast since we can't continue safely... - bNoException &= cssw.UndoNoThrow(); - System.Environment.FailFast(Environment.GetResourceString("ExecutionContext_UndoFailed")); - - } -#endif + bNoException &= cssw.UndoNoThrow(); @@ -144,15 +114,9 @@ namespace System.Security } } - public sealed class SecurityContext : IDisposable { -#if FEATURE_IMPERSONATION - // Note that only one of the following variables will be true. The way we set up the flow mode in the g_pConfig guarantees this. - static bool _LegacyImpersonationPolicy = (GetImpersonationFlowMode() == WindowsImpersonationFlowMode.IMP_NOFLOW); - static bool _alwaysFlowImpersonationPolicy = (GetImpersonationFlowMode() == WindowsImpersonationFlowMode.IMP_ALWAYSFLOW); -#endif /*========================================================================= ** Data accessed from managed code that needs to be defined in ** SecurityContextObject to maintain alignment between the two classes. @@ -160,9 +124,6 @@ namespace System.Security =========================================================================*/ private ExecutionContext _executionContext; -#if FEATURE_IMPERSONATION - private volatile WindowsIdentity _windowsIdentity; -#endif private volatile CompressedStack _compressedStack; static private volatile SecurityContext _fullTrustSC; @@ -204,7 +165,6 @@ namespace System.Security static internal SecurityContext FullTrustSecurityContext { - [System.Security.SecurityCritical] // auto-generated get { if (_fullTrustSC == null) @@ -222,27 +182,7 @@ namespace System.Security _executionContext = value; } } - -#if FEATURE_IMPERSONATION - - - internal WindowsIdentity WindowsIdentity - { - get - { - return _windowsIdentity; - } - set - { - // Note, we do not dispose of the existing windows identity, since some code such as remoting - // relies on reusing that identity. If you are not going to reuse the existing identity, then - // you should dispose of the existing identity before resetting it. - _windowsIdentity = value; - } - } -#endif // FEATURE_IMPERSONATION - internal CompressedStack CompressedStack { get @@ -258,25 +198,18 @@ namespace System.Security public void Dispose() { -#if FEATURE_IMPERSONATION - if (_windowsIdentity != null) - _windowsIdentity.Dispose(); -#endif // FEATURE_IMPERSONATION } - [System.Security.SecurityCritical] // auto-generated_required public static AsyncFlowControl SuppressFlow() { return SuppressFlow(SecurityContextDisableFlow.All); } - [System.Security.SecurityCritical] // auto-generated_required public static AsyncFlowControl SuppressFlowWindowsIdentity() { return SuppressFlow(SecurityContextDisableFlow.WI); } - [SecurityCritical] internal static AsyncFlowControl SuppressFlow(SecurityContextDisableFlow flags) { if (IsFlowSuppressed(flags)) @@ -292,7 +225,6 @@ namespace System.Security return afc; } - [SecuritySafeCritical] public static void RestoreFlow() { SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext; @@ -307,13 +239,7 @@ namespace System.Security { return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All); } -#if FEATURE_IMPERSONATION - public static bool IsWindowsIdentityFlowSuppressed() - { - return (_LegacyImpersonationPolicy|| SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.WI)); - } -#endif - [SecuritySafeCritical] + internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags) { return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags); @@ -323,7 +249,6 @@ namespace System.Security // continue past the call to SecurityContext.Run. If you change the signature to this method, or // provide an alternate way to do a SecurityContext.Run make sure to update // SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new method. - [System.Security.SecurityCritical] // auto-generated_required [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static void Run(SecurityContext securityContext, ContextCallback callback, Object state) @@ -360,7 +285,7 @@ namespace System.Security // and automatically goes away when the callback returns. WindowsIdentity.SafeRevertToSelf(ref stackMark); // Ensure we have reverted to the state we entered in. - Contract.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null); + Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null); } } else @@ -369,7 +294,6 @@ namespace System.Security } } - [System.Security.SecurityCritical] // auto-generated internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state) { if (cleanupCode == null) @@ -397,7 +321,6 @@ namespace System.Security } } - [System.Security.SecurityCritical] // auto-generated static internal void runTryCode(Object userData) { SecurityContextRunData rData = (SecurityContextRunData) userData; @@ -406,7 +329,6 @@ namespace System.Security } - [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] static internal void runFinallyCode(Object userData, bool exceptionThrown) { @@ -421,7 +343,6 @@ namespace System.Security // Internal API that gets called from public SetSecurityContext and from SetExecutionContext [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - [System.Security.SecurityCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal static SecurityContextSwitcher SetSecurityContext(SecurityContext sc, SecurityContext.Reader prevSecurityContext, bool modifyCurrentExecutionContext) @@ -430,7 +351,6 @@ namespace System.Security return SetSecurityContext(sc, prevSecurityContext, modifyCurrentExecutionContext, ref stackMark); } - [System.Security.SecurityCritical] // auto-generated #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] #endif // FEATURE_CORRUPTING_EXCEPTIONS @@ -458,22 +378,6 @@ namespace System.Security RuntimeHelpers.PrepareConstrainedRegions(); try { -#if FEATURE_IMPERSONATION - scsw.wic = null; - if (!_LegacyImpersonationPolicy) - { - if (sc.WindowsIdentity != null) - { - scsw.wic = sc.WindowsIdentity.Impersonate(ref stackMark); - } - else if ( ((_capturedFlowState & SecurityContextDisableFlow.WI) == 0) - && prevSecurityContext.WindowsIdentity != null) - { - // revert impersonation if there was no WI flow supression at capture and we're currently impersonating - scsw.wic = WindowsIdentity.SafeRevertToSelf(ref stackMark); - } - } -#endif scsw.cssw = CompressedStack.SetCompressedStack(sc.CompressedStack, prevSecurityContext.CompressedStack); } catch @@ -486,7 +390,6 @@ namespace System.Security } /// - [System.Security.SecuritySafeCritical] // auto-generated public SecurityContext CreateCopy() { if (!isNewCapture) @@ -498,11 +401,6 @@ namespace System.Security sc.isNewCapture = true; sc._disableFlow = _disableFlow; -#if FEATURE_IMPERSONATION - if (WindowsIdentity != null) - sc._windowsIdentity = new WindowsIdentity(WindowsIdentity.AccessToken); -#endif //FEATURE_IMPERSONATION - if (_compressedStack != null) sc._compressedStack = _compressedStack.CreateCopy(); @@ -510,26 +408,19 @@ namespace System.Security } /// - [System.Security.SecuritySafeCritical] // auto-generated internal SecurityContext CreateMutableCopy() { - Contract.Assert(!this.isNewCapture); + Debug.Assert(!this.isNewCapture); SecurityContext sc = new SecurityContext(); sc._disableFlow = this._disableFlow; -#if FEATURE_IMPERSONATION - if (this.WindowsIdentity != null) - sc._windowsIdentity = new WindowsIdentity(this.WindowsIdentity.AccessToken); -#endif //FEATURE_IMPERSONATION - if (this._compressedStack != null) sc._compressedStack = this._compressedStack.CreateCopy(); return sc; } - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static SecurityContext Capture( ) { @@ -545,7 +436,6 @@ namespace System.Security } // create a clone from a non-existing SecurityContext - [System.Security.SecurityCritical] // auto-generated [MethodImpl(MethodImplOptions.AggressiveInlining)] static internal SecurityContext Capture(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark) { @@ -560,125 +450,26 @@ namespace System.Security return CaptureCore(currThreadEC, ref stackMark); } - [System.Security.SecurityCritical] // auto-generated static private SecurityContext CaptureCore(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark) { SecurityContext sc = new SecurityContext(); sc.isNewCapture = true; -#if FEATURE_IMPERSONATION - // Force create WindowsIdentity - if (!IsWindowsIdentityFlowSuppressed()) - { - WindowsIdentity currentIdentity = GetCurrentWI(currThreadEC); - if (currentIdentity != null) - sc._windowsIdentity = new WindowsIdentity(currentIdentity.AccessToken); - } - else - { - sc._disableFlow = SecurityContextDisableFlow.WI; - } -#endif // FEATURE_IMPERSONATION - // Force create CompressedStack sc.CompressedStack = CompressedStack.GetCompressedStack(ref stackMark); return sc; } - [System.Security.SecurityCritical] // auto-generated + static internal SecurityContext CreateFullTrustSecurityContext() { SecurityContext sc = new SecurityContext(); sc.isNewCapture = true; - -#if FEATURE_IMPERSONATION - if (IsWindowsIdentityFlowSuppressed()) - { - sc._disableFlow = SecurityContextDisableFlow.WI; - } -#endif // FEATURE_IMPERSONATION - // Force create CompressedStack sc.CompressedStack = new CompressedStack(null); return sc; } -#if FEATURE_IMPERSONATION - - static internal bool AlwaysFlowImpersonationPolicy { get { return _alwaysFlowImpersonationPolicy; } } - - // Check to see if we have a WI on the thread and return if we do - [System.Security.SecurityCritical] // auto-generated - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static internal WindowsIdentity GetCurrentWI(ExecutionContext.Reader threadEC) - { - return GetCurrentWI(threadEC, _alwaysFlowImpersonationPolicy); - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static internal WindowsIdentity GetCurrentWI(ExecutionContext.Reader threadEC, bool cachedAlwaysFlowImpersonationPolicy) - { - Contract.Assert(cachedAlwaysFlowImpersonationPolicy == _alwaysFlowImpersonationPolicy); - if (cachedAlwaysFlowImpersonationPolicy) - { - // Examine the threadtoken at the cost of a kernel call if the user has set the IMP_ALWAYSFLOW mode - return WindowsIdentity.GetCurrentInternal(TokenAccessLevels.MaximumAllowed, true); - } - - return threadEC.SecurityContext.WindowsIdentity; - } - - [System.Security.SecurityCritical] - static internal void RestoreCurrentWI(ExecutionContext.Reader currentEC, ExecutionContext.Reader prevEC, WindowsIdentity targetWI, bool cachedAlwaysFlowImpersonationPolicy) - { - Contract.Assert(currentEC.IsSame(Thread.CurrentThread.GetExecutionContextReader())); - Contract.Assert(cachedAlwaysFlowImpersonationPolicy == _alwaysFlowImpersonationPolicy); - - // NOTE: cachedAlwaysFlowImpersonationPolicy is a perf optimization to avoid always having to access a static variable here. - if (cachedAlwaysFlowImpersonationPolicy || prevEC.SecurityContext.WindowsIdentity != targetWI) - { - // - // Either we're always flowing, or the target WI was obtained from the current EC in the first place. - // - Contract.Assert(_alwaysFlowImpersonationPolicy || currentEC.SecurityContext.WindowsIdentity == targetWI); - - RestoreCurrentWIInternal(targetWI); - } - } - - [System.Security.SecurityCritical] - static private void RestoreCurrentWIInternal(WindowsIdentity targetWI) - { - int hr = Win32.RevertToSelf(); - if (hr < 0) - Environment.FailFast(Win32Native.GetMessage(hr)); - - if (targetWI != null) - { - SafeAccessTokenHandle tokenHandle = targetWI.AccessToken; - if (tokenHandle != null && !tokenHandle.IsInvalid) - { - hr = Win32.ImpersonateLoggedOnUser(tokenHandle); - if (hr < 0) - Environment.FailFast(Win32Native.GetMessage(hr)); - } - } - } - - [System.Security.SecurityCritical] // auto-generated - internal bool IsDefaultFTSecurityContext() - { - return (WindowsIdentity == null && (CompressedStack == null || CompressedStack.CompressedStackHandle == null)); - } - [System.Security.SecurityCritical] // auto-generated - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static internal bool CurrentlyInDefaultFTSecurityContext(ExecutionContext.Reader threadEC) - { - return (IsDefaultThreadSecurityInfo() && GetCurrentWI(threadEC) == null); - } -#else - internal bool IsDefaultFTSecurityContext() { return (CompressedStack == null || CompressedStack.CompressedStackHandle == null); @@ -687,16 +478,9 @@ namespace System.Security { return (IsDefaultThreadSecurityInfo()); } -#endif -#if FEATURE_IMPERSONATION - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - internal extern static WindowsImpersonationFlowMode GetImpersonationFlowMode(); -#endif - [System.Security.SecurityCritical] // auto-generated + [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal extern static bool IsDefaultThreadSecurityInfo(); - } #endif // FEATURE_COMPRESSEDSTACK } diff --git a/src/mscorlib/src/System/Security/SecurityElement.cs b/src/mscorlib/src/System/Security/SecurityElement.cs index aa63029422..f57665b278 100644 --- a/src/mscorlib/src/System/Security/SecurityElement.cs +++ b/src/mscorlib/src/System/Security/SecurityElement.cs @@ -14,6 +14,7 @@ namespace System.Security using System.Globalization; using System.IO; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; internal enum SecurityElementType @@ -93,23 +94,10 @@ namespace System.Security return ((SecurityElement)this).Attribute( attributeName ); } -////////////// - -#if FEATURE_CAS_POLICY - public static SecurityElement FromString( String xml ) - { - if (xml == null) - throw new ArgumentNullException( "xml" ); - Contract.EndContractBlock(); - - return new Parser( xml ).GetTopElement(); - } -#endif // FEATURE_CAS_POLICY - public SecurityElement( String tag ) { if (tag == null) - throw new ArgumentNullException( "tag" ); + throw new ArgumentNullException( nameof(tag) ); if (!IsValidTag( tag )) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) ); @@ -122,7 +110,7 @@ namespace System.Security public SecurityElement( String tag, String text ) { if (tag == null) - throw new ArgumentNullException( "tag" ); + throw new ArgumentNullException( nameof(tag) ); if (!IsValidTag( tag )) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) ); @@ -148,7 +136,7 @@ namespace System.Security set { if (value == null) - throw new ArgumentNullException( "Tag" ); + throw new ArgumentNullException( nameof(Tag) ); if (!IsValidTag( value )) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) ); @@ -171,7 +159,7 @@ namespace System.Security Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 ); int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -296,7 +284,7 @@ namespace System.Security else { int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -314,10 +302,10 @@ namespace System.Security public void AddAttribute( String name, String value ) { if (name == null) - throw new ArgumentNullException( "name" ); + throw new ArgumentNullException( nameof(name) ); if (value == null) - throw new ArgumentNullException( "value" ); + throw new ArgumentNullException( nameof(value) ); if (!IsValidAttributeName( name )) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) ); @@ -332,7 +320,7 @@ namespace System.Security public void AddChild( SecurityElement child ) { if (child == null) - throw new ArgumentNullException( "child" ); + throw new ArgumentNullException( nameof(child) ); Contract.EndContractBlock(); if (m_lChildren == null) @@ -344,7 +332,7 @@ namespace System.Security internal void AddChild( ISecurityElementFactory child ) { if (child == null) - throw new ArgumentNullException( "child" ); + throw new ArgumentNullException( nameof(child) ); Contract.EndContractBlock(); if (m_lChildren == null) @@ -356,7 +344,7 @@ namespace System.Security internal void AddChildNoDuplicates( ISecurityElementFactory child ) { if (child == null) - throw new ArgumentNullException( "child" ); + throw new ArgumentNullException( nameof(child) ); Contract.EndContractBlock(); if (m_lChildren == null) @@ -400,7 +388,7 @@ namespace System.Security else { int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); if (iMax != other.m_lAttributes.Count) return false; @@ -495,7 +483,7 @@ namespace System.Security private static String GetEscapeSequence( char c ) { int iMax = s_escapeStringPairs.Length; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -506,7 +494,7 @@ namespace System.Security return strEscValue; } - Contract.Assert( false, "Unable to find escape sequence for this character" ); + Debug.Assert( false, "Unable to find escape sequence for this character" ); return c.ToString(); } @@ -557,7 +545,7 @@ namespace System.Security int maxCompareLength = str.Length - index; int iMax = s_escapeStringPairs.Length; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -616,7 +604,7 @@ namespace System.Security while (true); // C# reports a warning if I leave this in, but I still kinda want to just in case. - // Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" ); + // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" ); // return str; } @@ -626,11 +614,6 @@ namespace System.Security { ((StringBuilder)obj).Append( str ); } - - private static void ToStringHelperStreamWriter( Object obj, String str ) - { - ((StreamWriter)obj).Write( str ); - } public override String ToString () { @@ -641,16 +624,11 @@ namespace System.Security return sb.ToString(); } - internal void ToWriter( StreamWriter writer ) - { - ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) ); - } - private void ToString( String indent, Object obj, ToStringHelperFunc func ) { // First add the indent - // func( obj, indent ); + // func( obj, indent ); // Add in the opening bracket and the tag. @@ -679,7 +657,7 @@ namespace System.Security func( obj, " " ); int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -770,7 +748,7 @@ namespace System.Security public String Attribute( String name ) { if (name == null) - throw new ArgumentNullException( "name" ); + throw new ArgumentNullException( nameof(name) ); Contract.EndContractBlock(); // Note: we don't check for validity here because an @@ -783,7 +761,7 @@ namespace System.Security // the one we are asked for int iMax = m_lAttributes.Count; - Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); + Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" ); for (int i = 0; i < iMax; i += 2) { @@ -808,7 +786,7 @@ namespace System.Security // find the one are are asked for (matching tags) if (tag == null) - throw new ArgumentNullException( "tag" ); + throw new ArgumentNullException( nameof(tag) ); Contract.EndContractBlock(); // Note: we don't check for a valid tag here because @@ -829,45 +807,13 @@ namespace System.Security return null; } -#if FEATURE_CAS_POLICY - internal IPermission ToPermission(bool ignoreTypeLoadFailures) - { - IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures ); - if (ip == null) - return null; - ip.FromXml(this); - - // Get the permission token here to ensure that the token - // type is updated appropriately now that we've loaded the type. - PermissionToken token = PermissionToken.GetToken( ip ); - Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned"); - - return ip; - } - - [System.Security.SecurityCritical] // auto-generated - internal Object ToSecurityObject() - { - switch (m_strTag) - { - case "PermissionSet": - PermissionSet pset = new PermissionSet(PermissionState.None); - pset.FromXml(this); - return pset; - - default: - return ToPermission(false); - } - } -#endif // FEATURE_CAS_POLICY - internal String SearchForTextOfLocalName(String strLocalName) { // Search on each child in order and each // child's child, depth-first if (strLocalName == null) - throw new ArgumentNullException( "strLocalName" ); + throw new ArgumentNullException( nameof(strLocalName) ); Contract.EndContractBlock(); // Note: we don't check for a valid tag here because @@ -899,7 +845,7 @@ namespace System.Security // child's child, depth-first if (tag == null) - throw new ArgumentNullException( "tag" ); + throw new ArgumentNullException( nameof(tag) ); Contract.EndContractBlock(); // Note: we don't check for a valid tag here because diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs index 9fbd8023d2..c76674cdb9 100644 --- a/src/mscorlib/src/System/Security/SecurityException.cs +++ b/src/mscorlib/src/System/Security/SecurityException.cs @@ -34,589 +34,60 @@ namespace System.Security [Serializable] public class SecurityException : SystemException { -#if FEATURE_CAS_POLICY - private String m_debugString; // NOTE: If you change the name of this field, you'll have to update SOS as well! - private SecurityAction m_action; - [NonSerialized] private Type m_typeOfPermissionThatFailed; - private String m_permissionThatFailed; - private String m_demanded; - private String m_granted; - private String m_refused; - private String m_denied; - private String m_permitOnly; - private AssemblyName m_assemblyName; - private byte[] m_serializedMethodInfo; - private String m_strMethodInfo; - private SecurityZone m_zone; - private String m_url; - - private const String ActionName = "Action"; - private const String FirstPermissionThatFailedName = "FirstPermissionThatFailed"; - private const String DemandedName = "Demanded"; - private const String GrantedSetName = "GrantedSet"; - private const String RefusedSetName = "RefusedSet"; - private const String DeniedName = "Denied"; - private const String PermitOnlyName = "PermitOnly"; - private const String Assembly_Name = "Assembly"; - private const String MethodName_Serialized = "Method"; - private const String MethodName_String = "Method_String"; - private const String ZoneName = "Zone"; - private const String UrlName = "Url"; -#endif // #if FEATURE_CAS_POLICY - - [System.Security.SecuritySafeCritical] // auto-generated internal static string GetResString(string sResourceName) { PermissionSet.s_fullTrust.Assert(); return Environment.GetResourceString(sResourceName); } - [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 { -#if FEATURE_CAS_POLICY - // See if we need to throw a HostProtectionException instead - HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission; - if(hostProtectionPerm != null) - return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources); - - // Produce relevant strings - String message = ""; - MethodInfo method = null; - try - { - if(granted == null && refused == null && demand == null) - { - message = GetResString("Security_NoAPTCA"); - } - else - { - if(demand != null && demand is IPermission) - message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName ); - else if (permThatFailed != null) - message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName); - else - message = GetResString("Security_GenericNoType"); - } - - method = SecurityRuntime.GetMethodInfo(rmh); - } - catch(Exception e) - { - // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a Contract.Assert in this case or it will lock up the thread.) - if(e is System.Threading.ThreadAbortException) - throw; - } - -/* catch(System.Threading.ThreadAbortException) - { - // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.) - throw; - } - catch - { - } -*/ - // make the exception object - return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence); -#else return new SecurityException(GetResString("Arg_SecurityException")); -#endif - } -#if FEATURE_CAS_POLICY - private static byte[] ObjectToByteArray(Object obj) - { - if(obj == null) - return null; - MemoryStream stream = new MemoryStream(); - BinaryFormatter formatter = new BinaryFormatter(); - try { - formatter.Serialize(stream, obj); - byte[] array = stream.ToArray(); - return array; - } catch (NotSupportedException) { - // Serialization of certain methods is not supported (namely - // global methods, since they have no representation outside of - // a module scope). - return null; - } - } - - private static Object ByteArrayToObject(byte[] array) - { - if(array == null || array.Length == 0) - return null; - MemoryStream stream = new MemoryStream(array); - BinaryFormatter formatter = new BinaryFormatter(); - Object obj = formatter.Deserialize(stream); - return obj; - } -#endif // FEATURE_CAS_POLICY - - public SecurityException() + public SecurityException() : base(GetResString("Arg_SecurityException")) { SetErrorCode(System.__HResults.COR_E_SECURITY); } - - public SecurityException(String message) - : base(message) - { - // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.) - SetErrorCode(System.__HResults.COR_E_SECURITY); - } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(String message, Type type ) + public SecurityException(String message) : base(message) { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - m_typeOfPermissionThatFailed = type; - } - - // *** Don't use this constructor internally *** - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(String message, Type type, String state ) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); + // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.) SetErrorCode(System.__HResults.COR_E_SECURITY); - m_typeOfPermissionThatFailed = type; - m_demanded = state; } -#endif //FEATURE_CAS_POLICY - public SecurityException(String message, Exception inner) + public SecurityException(String message, Exception inner) : base(message, inner) { SetErrorCode(System.__HResults.COR_E_SECURITY); } -#if FEATURE_CAS_POLICY - // *** Don't use this constructor internally *** - [System.Security.SecurityCritical] // auto-generated - internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj ) - : base(GetResString("Arg_SecurityException")) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - if (grantedSetObj != null) - m_granted = grantedSetObj.ToXml().ToString(); - if (refusedSetObj != null) - m_refused = refusedSetObj.ToXml().ToString(); - } - - // *** Don't use this constructor internally *** - [System.Security.SecurityCritical] // auto-generated - internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj ) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - if (grantedSetObj != null) - m_granted = grantedSetObj.ToXml().ToString(); - if (refusedSetObj != null) - m_refused = refusedSetObj.ToXml().ToString(); - } - - [System.Security.SecuritySafeCritical] // auto-generated - protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context) - { - if (info==null) - throw new ArgumentNullException("info"); - Contract.EndContractBlock(); - - try - { - m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction)); - m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String)); - m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String)); - m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String)); - m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String)); - m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String)); - m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String)); - m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName)); - m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[])); - m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String)); - m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone)); - m_url = (String)info.GetValueNoThrow(UrlName, typeof(String)); - } - catch - { - m_action = 0; - m_permissionThatFailed = ""; - m_demanded = ""; - m_granted = ""; - m_refused = ""; - m_denied = ""; - m_permitOnly = ""; - m_assemblyName = null; - m_serializedMethodInfo = null; - m_strMethodInfo = null; - m_zone = SecurityZone.NoZone; - m_url = ""; - } - } - - // ------------------------------------------ - // | For failures due to insufficient grant | - // ------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - Action = action; - if(permThatFailed != null) - m_typeOfPermissionThatFailed = permThatFailed.GetType(); - FirstPermissionThatFailed = permThatFailed; - Demanded = demanded; - m_granted = (grant == null ? "" : grant.ToXml().ToString()); - m_refused = (refused == null ? "" : refused.ToXml().ToString()); - m_denied = ""; - m_permitOnly = ""; - m_assemblyName = assemblyName; - Method = method; - m_url = ""; - m_zone = SecurityZone.NoZone; - if(evidence != null) - { - Url url = evidence.GetHostEvidence(); - if(url != null) - m_url = url.GetURLString().ToString(); - Zone zone = evidence.GetHostEvidence(); - if(zone != null) - m_zone = zone.SecurityZone; - } - m_debugString = this.ToString(true, false); - } - - // ------------------------------------------ - // | For failures due to deny or PermitOnly | - // ------------------------------------------ - [System.Security.SecuritySafeCritical] // auto-generated - public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) - : base(message) - { - PermissionSet.s_fullTrust.Assert(); - SetErrorCode(System.__HResults.COR_E_SECURITY); - Action = SecurityAction.Demand; - if(permThatFailed != null) - m_typeOfPermissionThatFailed = permThatFailed.GetType(); - FirstPermissionThatFailed = permThatFailed; - Demanded = demanded; - m_granted = ""; - m_refused = ""; - DenySetInstance = deny; - PermitOnlySetInstance = permitOnly; - m_assemblyName = null; - Method = method; - m_zone = SecurityZone.NoZone; - m_url = ""; - m_debugString = this.ToString(true, false); - } - - - - - - - - - - - - [System.Runtime.InteropServices.ComVisible(false)] - public SecurityAction Action - { - get - { - return m_action; - } - - set - { - m_action = value; - } - } - - public Type PermissionType - { - [System.Security.SecuritySafeCritical] // auto-generated - get - { - if(m_typeOfPermissionThatFailed == null) - { - Object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); - if(ob == null) - ob = XMLUtil.XmlStringToSecurityObject(m_demanded); - if(ob != null) - m_typeOfPermissionThatFailed = ob.GetType(); - } - return m_typeOfPermissionThatFailed; - } - - set - { - m_typeOfPermissionThatFailed = value; - } - } - - public IPermission FirstPermissionThatFailed - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); - } - - set - { - m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value); - } - } - - public String PermissionState - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_demanded; - } - - set - { - m_demanded = value; - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object Demanded - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_demanded); - } - - set - { - m_demanded = XMLUtil.SecurityObjectToXmlString(value); - } - } - - public String GrantedSet - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_granted; - } - - set - { - m_granted = value; - } - } - - public String RefusedSet - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_refused; - } - - set - { - m_refused = value; - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object DenySetInstance - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_denied); - } - - set - { - m_denied = XMLUtil.SecurityObjectToXmlString(value); - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public Object PermitOnlySetInstance - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return XMLUtil.XmlStringToSecurityObject(m_permitOnly); - } - - set - { - m_permitOnly = XMLUtil.SecurityObjectToXmlString(value); - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public AssemblyName FailedAssemblyInfo - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_assemblyName; - } - - set - { - m_assemblyName = value; - } - } - - private MethodInfo getMethod() - { - return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo); - } - - [System.Runtime.InteropServices.ComVisible(false)] - public MethodInfo Method - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return getMethod(); - } - - set - { - RuntimeMethodInfo m = value as RuntimeMethodInfo; - m_serializedMethodInfo = ObjectToByteArray(m); - if (m != null) - { - m_strMethodInfo = m.ToString(); - } - } - } - - public SecurityZone Zone - { - get - { - return m_zone; - } - - set - { - m_zone = value; - } - } - - public String Url - { - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] - get - { - return m_url; - } - - set - { - m_url = value; - } - } - - private void ToStringHelper(StringBuilder sb, String resourceString, Object attr) - { - if (attr == null) - return; - String attrString = attr as String; - if (attrString == null) - attrString = attr.ToString(); - if (attrString.Length == 0) - return; - sb.Append(Environment.NewLine); - sb.Append(GetResString(resourceString)); - sb.Append(Environment.NewLine); - sb.Append(attrString); - } - - [System.Security.SecurityCritical] // auto-generated - private String ToString(bool includeSensitiveInfo, bool includeBaseInfo) - { - PermissionSet.s_fullTrust.Assert(); - StringBuilder sb = new StringBuilder(); - - if(includeBaseInfo) - sb.Append(base.ToString()); - if(Action > 0) - ToStringHelper(sb, "Security_Action", Action); - ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType); - if(includeSensitiveInfo) - { - ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed); - ToStringHelper(sb, "Security_Demanded", m_demanded); - ToStringHelper(sb, "Security_GrantedSet", m_granted); - ToStringHelper(sb, "Security_RefusedSet", m_refused); - ToStringHelper(sb, "Security_Denied", m_denied); - ToStringHelper(sb, "Security_PermitOnly", m_permitOnly); - ToStringHelper(sb, "Security_Assembly", m_assemblyName); - ToStringHelper(sb, "Security_Method", m_strMethodInfo); - } - if(m_zone != SecurityZone.NoZone) - ToStringHelper(sb, "Security_Zone", m_zone); - if(includeSensitiveInfo) - ToStringHelper(sb, "Security_Url", m_url); - return sb.ToString(); - } -#else // FEATURE_CAS_POLICY - internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj ) + internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj) : this(){} #pragma warning disable 618 internal SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) #pragma warning restore 618 : this(){} - + internal SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) : this(){} - [System.Security.SecuritySafeCritical] // auto-generated protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); } - public override String ToString() - { - return base.ToString(); - } - -#endif // FEATURE_CAS_POLICY + public override String ToString() + { + return base.ToString(); + } - [System.Security.SecurityCritical] // auto-generated private bool CanAccessSensitiveInfo() { bool retVal = false; @@ -627,41 +98,46 @@ namespace System.Security #pragma warning restore 618 retVal = true; } - catch(SecurityException) + catch (SecurityException) { } return retVal; - } -#if FEATURE_CAS_POLICY - [System.Security.SecuritySafeCritical] // auto-generated - public override String ToString() - { - return ToString(CanAccessSensitiveInfo(), true); } -#endif //FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated_required + public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info==null) - throw new ArgumentNullException("info"); + if (info == null) + throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); - base.GetObjectData( info, context ); -#if FEATURE_CAS_POLICY + base.GetObjectData(info, context); + } - info.AddValue(ActionName, m_action, typeof(SecurityAction)); - info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(String)); - info.AddValue(DemandedName, m_demanded, typeof(String)); - info.AddValue(GrantedSetName, m_granted, typeof(String)); - info.AddValue(RefusedSetName, m_refused, typeof(String)); - info.AddValue(DeniedName, m_denied, typeof(String)); - info.AddValue(PermitOnlyName, m_permitOnly, typeof(String)); - info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName)); - info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[])); - info.AddValue(MethodName_String, m_strMethodInfo, typeof(String)); - info.AddValue(ZoneName, m_zone, typeof(SecurityZone)); - info.AddValue(UrlName, m_url, typeof(String)); -#endif // FEATURE_CAS_POLICY + // Stubs for surface area compatibility only + public SecurityException(String message, Type type) + : base(message) + { + SetErrorCode(System.__HResults.COR_E_SECURITY); + PermissionType = type; } + + public SecurityException(string message, System.Type type, string state) + : base(message) + { + SetErrorCode(System.__HResults.COR_E_SECURITY); + PermissionType = type; + PermissionState = state; + } + + public object Demanded { get; set; } + public object DenySetInstance { get; set; } + public System.Reflection.AssemblyName FailedAssemblyInfo { get; set; } + public string GrantedSet { get; set; } + public System.Reflection.MethodInfo Method { get; set; } + public string PermissionState { get; set; } + public System.Type PermissionType { get; set; } + public object PermitOnlySetInstance { get; set; } + public string RefusedSet { get; set; } + public string Url { get; set; } } } diff --git a/src/mscorlib/src/System/Security/SecurityManager.cs b/src/mscorlib/src/System/Security/SecurityManager.cs index 5c46dfcbfc..933fe0be3d 100644 --- a/src/mscorlib/src/System/Security/SecurityManager.cs +++ b/src/mscorlib/src/System/Security/SecurityManager.cs @@ -2,32 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -// // // The SecurityManager class provides a general purpose API for interacting // with the security system. // -namespace System.Security { +namespace System.Security +{ using System; - using System.Security.Util; - using System.Security.Policy; using System.Security.Permissions; - using System.Collections; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -#if FEATURE_CLICKONCE - using System.Runtime.Hosting; -#endif // FEATURE_CLICKONCE - using System.Text; - using System.Threading; - using System.Reflection; - using System.IO; - using System.Globalization; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] @@ -40,504 +25,8 @@ namespace System.Security { } [System.Runtime.InteropServices.ComVisible(true)] - static public class SecurityManager { -#if FEATURE_CAS_POLICY - private static volatile SecurityPermission executionSecurityPermission = null; - - private static PolicyManager polmgr = new PolicyManager(); - internal static PolicyManager PolicyManager { - get { - return polmgr; - } - } - - // - // Public APIs - // - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - [Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework. Please use the PermissionSet property of either AppDomain or Assembly instead.")] - public static bool IsGranted( IPermission perm ) - { - if (perm == null) - return true; - - PermissionSet granted = null, denied = null; - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - GetGrantedPermissions( JitHelpers.GetObjectHandleOnStack(ref granted), - JitHelpers.GetObjectHandleOnStack(ref denied), - JitHelpers.GetStackCrawlMarkHandle(ref stackMark) ); - return granted.Contains( perm ) && (denied == null || !denied.Contains( perm )); - } - - // Get a sandbox permission set that the CLR considers safe to grant an application with the given - // evidence. Note that this API is not a policy API, but rather a host helper API so that a host can - // determine if an application's requested permission set is reasonable. This is esentially just a - // hard coded mapping of Zone -> Sandbox and is not configurable in any way. - public static PermissionSet GetStandardSandbox(Evidence evidence) - { - if (evidence == null) - throw new ArgumentNullException("evidence"); - Contract.EndContractBlock(); - - // - // The top-level switch for grant set is based upon Zone - // MyComputer -> FullTrust - // Intranet -> LocalIntranet - // Trusted -> Internet - // Internet -> Internet - // All else -> Nothing - // - // Both the Internet and LocalIntranet zones can have permission set extensions applied to them - // if there is Activation. - // - - Zone zone = evidence.GetHostEvidence(); - if (zone == null) - { - return new PermissionSet(PermissionState.None); - } -#if FEATURE_CAS_POLICY - else if (zone.SecurityZone == SecurityZone.MyComputer) - { - return new PermissionSet(PermissionState.Unrestricted); - } - else if (zone.SecurityZone == SecurityZone.Intranet) - { - PermissionSet intranetGrantSet = BuiltInPermissionSets.LocalIntranet; - - // We also need to add in same site web and file IO permission - PolicyStatement webPolicy = - new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence); - PolicyStatement filePolicy = - new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery).Resolve(evidence); - - if (webPolicy != null) - { - intranetGrantSet.InplaceUnion(webPolicy.PermissionSet); - } - if (filePolicy != null) - { - intranetGrantSet.InplaceUnion(filePolicy.PermissionSet); - } - - return intranetGrantSet; - } - else if (zone.SecurityZone == SecurityZone.Internet || - zone.SecurityZone == SecurityZone.Trusted) - { - PermissionSet internetGrantSet = BuiltInPermissionSets.Internet; - - // We also need to add in same site web permission - PolicyStatement webPolicy = - new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence); - - if (webPolicy != null) - { - internetGrantSet.InplaceUnion(webPolicy.PermissionSet); - } - - return internetGrantSet; - } -#endif // FEATURE_CAS_POLICY - else - { - return new PermissionSet(PermissionState.None); - } - } - - /// - [System.Security.SecurityCritical] // auto-generated_required - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - static public void GetZoneAndOrigin( out ArrayList zone, out ArrayList origin ) - { - StackCrawlMark mark = StackCrawlMark.LookForMyCaller; - CodeAccessSecurityEngine.GetZoneAndOrigin( ref mark, out zone, out origin ); - } - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )] - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public PolicyLevel LoadPolicyLevelFromFile(string path, PolicyLevelType type) - { - if (path == null) - throw new ArgumentNullException( "path" ); - Contract.EndContractBlock(); - - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - // We need to retain V1.x compatibility by throwing the same exception type. - if (!File.InternalExists(path)) - throw new ArgumentException( Environment.GetResourceString("Argument_PolicyFileDoesNotExist")); - - String fullPath = Path.GetFullPath( path ); - - FileIOPermission perm = new FileIOPermission( PermissionState.None ); - perm.AddPathList( FileIOPermissionAccess.Read, fullPath ); - perm.AddPathList( FileIOPermissionAccess.Write, fullPath ); - perm.Demand(); - - using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { - using (StreamReader reader = new StreamReader(stream)) { - return LoadPolicyLevelFromStringHelper(reader.ReadToEnd(), path, type); - } - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )] - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public PolicyLevel LoadPolicyLevelFromString(string str, PolicyLevelType type) - { - return LoadPolicyLevelFromStringHelper(str, null, type); - } - - private static PolicyLevel LoadPolicyLevelFromStringHelper (string str, string path, PolicyLevelType type) - { - if (str == null) - throw new ArgumentNullException( "str" ); - Contract.EndContractBlock(); - - PolicyLevel level = new PolicyLevel(type, path); - - Parser parser = new Parser( str ); - SecurityElement elRoot = parser.GetTopElement(); - if (elRoot == null) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "configuration" ) ); - - SecurityElement elMscorlib = elRoot.SearchForChildByTag( "mscorlib" ); - if (elMscorlib == null) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "mscorlib" ) ); - - SecurityElement elSecurity = elMscorlib.SearchForChildByTag( "security" ); - if (elSecurity == null) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "security" ) ); - - SecurityElement elPolicy = elSecurity.SearchForChildByTag( "policy" ); - if (elPolicy == null) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "policy" ) ); - - SecurityElement elPolicyLevel = elPolicy.SearchForChildByTag( "PolicyLevel" ); - if (elPolicyLevel != null) - level.FromXml( elPolicyLevel ); - else - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "PolicyLevel" ) ); - - return level; - } - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )] - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public void SavePolicyLevel( PolicyLevel level ) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - PolicyManager.EncodeLevel( level ); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public PermissionSet ResolvePolicy(Evidence evidence, - PermissionSet reqdPset, - PermissionSet optPset, - PermissionSet denyPset, - out PermissionSet denied) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - return ResolvePolicy(evidence, reqdPset, optPset, denyPset, out denied, true); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public PermissionSet ResolvePolicy(Evidence evidence) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - // If we aren't passed any evidence, just make an empty object - if (evidence == null) - { - evidence = new Evidence(); - } - - return polmgr.Resolve(evidence); - } - - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public PermissionSet ResolvePolicy( Evidence[] evidences ) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - if (evidences == null || evidences.Length == 0) - evidences = new Evidence[] { null }; - - PermissionSet retval = ResolvePolicy( evidences[0] ); - if (retval == null) - return null; - - for (int i = 1; i < evidences.Length; ++i) - { - retval = retval.Intersect( ResolvePolicy( evidences[i] ) ); - if (retval == null || retval.IsEmpty()) - return retval; - } - - return retval; - } - -#if FEATURE_CAS_POLICY - // Determine if the current thread would require a security context capture if the security state of - // the thread needs to be re-created at a later point in time. This can be used, for instance, if - // sensitive data is being obtained after security demands succeed, and that data is to be cached. - // If there is an Assert up the stack, then we wouldn't want to cache the data without capturing the - // corresponding security context to go along with it - otherwise we risk leaking data obtained - // under an assert to code which may no longer be running with that assert in place. - // - // A return value of false indicates that the CLR guarantees all of the following conditions are true: - // 1. No partial trust AppDomains are on the stack - // 2. No partial trust assemblies are on the stack - // 3. There are no currently active PermitOnly or Deny modifiers on the stack - // - // A return value of true means only that the CLR cannot guarantee that all of the conditions are - // true, and not that one of the conditions really is false. - // - // IMPORTANT: The above means is only reliable in the false return case. If we say that the thread - // does not require a context capture, then that answer is guaranteed to be correct. However, we may - // say that the thread does require a capture when it does not actually strictly need to capture the - // state. This is fine, as being overly conservative when capturing context will not lead to - // security holes; being overly agresssive in avoding the capture could lead to holes however. - // - // This API is SecurityCritical because its main use is to optimize away unnecessary security - // context captures, which means that the code using it is security sensitive and needs to be audited. - [SecurityCritical] - public static bool CurrentThreadRequiresSecurityContextCapture() - { - // If we know that the thread is not made up of entirely full trust code, and that there are no - // security stack modifiers on the thread, then there is no need to capture a security context. - return !CodeAccessSecurityEngine.QuickCheckForAllDemands(); - } -#endif // FEATURE_CAS_POLICY - - // - // This method resolves the policy for the specified evidence, but it - // ignores the AppDomain level even when one is available in the current policy. - // - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public static PermissionSet ResolveSystemPolicy (Evidence evidence) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - if (PolicyManager.IsGacAssembly(evidence)) - { - return new PermissionSet(PermissionState.Unrestricted); - } - - return polmgr.CodeGroupResolve(evidence, true); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - static public IEnumerator ResolvePolicyGroups(Evidence evidence) - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - return polmgr.ResolveCodeGroups(evidence); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public static IEnumerator PolicyHierarchy() - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - return polmgr.PolicyHierarchy(); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )] - [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - public static void SavePolicy() - { - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit")); - } - - polmgr.Save(); - } - - - [System.Security.SecurityCritical] // auto-generated - private static PermissionSet ResolveCasPolicy(Evidence evidence, - PermissionSet reqdPset, - PermissionSet optPset, - PermissionSet denyPset, - out PermissionSet denied, - out int securitySpecialFlags, - bool checkExecutionPermission) - { - Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); - - CodeAccessPermission.Assert(true); - - PermissionSet granted = ResolvePolicy(evidence, - reqdPset, - optPset, - denyPset, - out denied, - checkExecutionPermission); - - securitySpecialFlags = SecurityManager.GetSpecialFlags(granted, denied); - return granted; - } - - [System.Security.SecurityCritical] // auto-generated - static private PermissionSet ResolvePolicy(Evidence evidence, - PermissionSet reqdPset, - PermissionSet optPset, - PermissionSet denyPset, - out PermissionSet denied, - bool checkExecutionPermission) - { - Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); - - if (executionSecurityPermission == null) - executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution); - - PermissionSet requested = null; - PermissionSet optional; - PermissionSet allowed; - - Exception savedException = null; - - // We don't want to recurse back into here as a result of a - // stackwalk during resolution. So simply assert full trust (this - // implies that custom permissions cannot use any permissions that - // don't implement IUnrestrictedPermission. - // PermissionSet.s_fullTrust.Assert(); - - // The requested set is the union of the minimal request and the - // optional request. Minimal request defaults to empty, optional - // is "AllPossible" (includes any permission that can be defined) - // which is symbolized by null. - optional = optPset; - - if (reqdPset == null) - requested = optional; - else - // If optional is null, the requested set becomes null/"AllPossible". - requested = optional == null ? null : reqdPset.Union(optional); - - // Make sure that the right to execute is requested (if this feature is - // enabled). - - if (requested != null && !requested.IsUnrestricted()) - requested.AddPermission( executionSecurityPermission ); - - // If we aren't passed any evidence, just make an empty object - if (evidence == null) - { - evidence = new Evidence(); - } - - allowed = polmgr.Resolve(evidence); - // Intersect the grant with the RequestOptional - if (requested != null) - allowed.InplaceIntersect(requested); - - // Check that we were granted the right to execute. - if (checkExecutionPermission) - { - if (!allowed.Contains(executionSecurityPermission) || - (denyPset != null && denyPset.Contains(executionSecurityPermission))) - { - throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"), - System.__HResults.CORSEC_E_NO_EXEC_PERM, - savedException); - } - } - - // Check that we were granted at least the minimal set we asked for. Do - // this before pruning away any overlap with the refused set so that - // users have the flexability of defining minimal permissions that are - // only expressable as set differences (e.g. allow access to "C:\" but - // disallow "C:\Windows"). - if (reqdPset != null && !reqdPset.IsSubsetOf(allowed)) - { - BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled"); - throw new PolicyException(Environment.GetResourceString( "Policy_NoRequiredPermission" ), - System.__HResults.CORSEC_E_MIN_GRANT_FAIL, - savedException ); - } - - // Remove any granted permissions that are safe subsets of some denied - // permission. The remaining denied permissions (if any) are returned - // along with the modified grant set for use in checks. - if (denyPset != null) - { - BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled"); - denied = denyPset.Copy(); - allowed.MergeDeniedSet(denied); - if (denied.IsEmpty()) - denied = null; - } - else - denied = null; - - allowed.IgnoreTypeLoadFailures = true; - - return allowed; - } - - [Obsolete("Because execution permission checks can no longer be turned off, the CheckExecutionRights property no longer has any effect.")] - static public bool CheckExecutionRights - { - get { return true; } - - set - { - // The setter for this property is a no-op since execution checking can no longer be turned off - } - } - - [Obsolete("Because security can no longer be turned off, the SecurityEnabled property no longer has any effect.")] - public static bool SecurityEnabled - { - get { return true; } - - set - { - // The setter for this property is a no-op since security cannot be turned off - } - } -#endif // #if FEATURE_CAS_POLICY - + static public class SecurityManager + { private static int[][] s_BuiltInPermissionIndexMap = { new int[] { BuiltInPermissionIndex.EnvironmentPermissionIndex, (int) PermissionType.EnvironmentPermission }, new int[] { BuiltInPermissionIndex.FileDialogPermissionIndex, (int) PermissionType.FileDialogPermission }, @@ -653,17 +142,14 @@ namespace System.Security { return flags; } #pragma warning restore 618 - - [System.Security.SecurityCritical] // auto-generated + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern bool IsSameType(String strLeft, String strRight); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool _SetThreadSecurity(bool bThreadSecurity); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void GetGrantedPermissions(ObjectHandleOnStack retGranted, ObjectHandleOnStack retDenied, StackCrawlMarkHandle stackMark); diff --git a/src/mscorlib/src/System/Security/SecurityRuntime.cs b/src/mscorlib/src/System/Security/SecurityRuntime.cs index 9d776affd3..d037fe939d 100644 --- a/src/mscorlib/src/System/Security/SecurityRuntime.cs +++ b/src/mscorlib/src/System/Security/SecurityRuntime.cs @@ -4,7 +4,8 @@ // -namespace System.Security { +namespace System.Security +{ using System; using System.Globalization; using System.Threading; @@ -26,7 +27,6 @@ namespace System.Security { // // Internal only, do not doc. // - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark, @@ -37,7 +37,6 @@ namespace System.Security { internal const bool StackHalt = false; // this method is a big perf hit, so don't call unnecessarily - [System.Security.SecurityCritical] // auto-generated internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh) { if (rmh.IsNullHandle()) @@ -60,7 +59,6 @@ namespace System.Security { #endif } - [System.Security.SecurityCritical] // auto-generated private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, out PermissionSet alteredDemandSet, @@ -69,7 +67,6 @@ namespace System.Security { return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh); } - [System.Security.SecurityCritical] // auto-generated private static bool FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demandIn, PermissionToken permToken, @@ -79,7 +76,6 @@ namespace System.Security { } #if FEATURE_COMPRESSEDSTACK - [System.Security.SecurityCritical] private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver, PermissionSet demandSet, out PermissionSet alteredDemandSet, @@ -99,7 +95,6 @@ namespace System.Security { return result; } - [System.Security.SecurityCritical] private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver, IPermission demandIn, PermissionToken permToken, @@ -122,176 +117,41 @@ namespace System.Security { // // API for PermissionSets // - - [System.Security.SecurityCritical] // auto-generated + internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission - // you need to change the fourth parameter to a zero. - FrameSecurityDescriptor secObj = CodeAccessSecurityEngine.CheckNReturnSO( - CodeAccessSecurityEngine.AssertPermissionToken, - CodeAccessSecurityEngine.AssertPermission, - ref stackMark, - 1 ); - - Contract.Assert(secObj != null,"Failure in SecurityRuntime.Assert() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeAsserts()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssert(permSet); - } -#endif // FEATURE_CAS_POLICY } - - [System.Security.SecurityCritical] // auto-generated + internal static void AssertAllPossible(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.AssertAllPossible() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.GetAssertAllPossible()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetAssertAllPossible(); - } -#endif // FEATURE_CAS_POLICY } - - [System.Security.SecurityCritical] // auto-generated + internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - // Deny is only valid in legacy mode - if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) - { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny")); - } - - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.Deny() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeDenials()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetDeny(permSet); - } -#endif // FEATURE_CAS_POLICY } - - [System.Security.SecurityCritical] // auto-generated + internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = - SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true); - - Contract.Assert(secObj != null, "Failure in SecurityRuntime.PermitOnly() - secObj != null"); - if (secObj == null) - { - // Security: REQ_SQ flag is missing. Bad compiler ? - System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } - else - { - if (secObj.HasImperativeRestrictions()) - throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) ); - - secObj.SetPermitOnly(permSet); - } -#endif // FEATURE_CAS_POLICY } - + // // Revert API // - - [System.Security.SecurityCritical] // auto-generated + internal static void RevertAssert(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertAssert(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void RevertDeny(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertDeny(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void RevertPermitOnly(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertPermitOnly(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } - [System.Security.SecurityCritical] // auto-generated internal static void RevertAll(ref StackCrawlMark stackMark) { -#if FEATURE_CAS_POLICY - FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false); - if (secObj != null) - { - secObj.RevertAll(); - } - else - { - throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor")); - } -#endif // FEATURE_CAS_POLICY } } } diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs index bd23acd813..3c7f8bf49f 100644 --- a/src/mscorlib/src/System/Security/SecurityState.cs +++ b/src/mscorlib/src/System/Security/SecurityState.cs @@ -7,25 +7,17 @@ using System.Security.Permissions; namespace System.Security { - [System.Security.SecurityCritical] // auto-generated_required -#pragma warning disable 618 - [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 public abstract class SecurityState { protected SecurityState(){} - [System.Security.SecurityCritical] // auto-generated public bool IsStateAvailable() { AppDomainManager domainManager = AppDomainManager.CurrentAppDomainManager; -#if FEATURE_CORECLR + // CheckSecuritySettings only when appdomainManager is present. So if there is no // appDomain Manager return true as by default coreclr runs in fulltrust. return domainManager != null ? domainManager.CheckSecuritySettings(this) : true; -#else - return domainManager != null ? domainManager.CheckSecuritySettings(this) : false; -#endif } // override this function and throw the appropriate public abstract void EnsureState(); diff --git a/src/mscorlib/src/System/Security/Util/Config.cs b/src/mscorlib/src/System/Security/Util/Config.cs index 988a39a9d6..afc9b8c336 100644 --- a/src/mscorlib/src/System/Security/Util/Config.cs +++ b/src/mscorlib/src/System/Security/Util/Config.cs @@ -37,7 +37,6 @@ namespace System.Security.Util { private static volatile string m_machineConfig; private static volatile string m_userConfig; - [System.Security.SecurityCritical] // auto-generated private static void GetFileLocales() { if (m_machineConfig == null) @@ -56,7 +55,6 @@ namespace System.Security.Util { internal static string MachineDirectory { - [System.Security.SecurityCritical] // auto-generated get { GetFileLocales(); @@ -66,7 +64,6 @@ namespace System.Security.Util { internal static string UserDirectory { - [System.Security.SecurityCritical] // auto-generated get { GetFileLocales(); @@ -74,57 +71,12 @@ namespace System.Security.Util { } } -#if FEATURE_CAS_POLICY - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern int SaveDataByte(string path, [In] byte[] data, int length); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern bool RecoverData(ConfigId id); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern void SetQuickCache(ConfigId id, QuickCacheEntryType quickCacheFlags); - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern bool GetCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, ObjectHandleOnStack retData); - - [System.Security.SecurityCritical] // auto-generated - internal static bool GetCacheEntry(ConfigId id, int numKey, byte[] key, out byte[] data) - { - byte[] retData = null; - bool ret = GetCacheEntry(id, numKey, key, key.Length, JitHelpers.GetObjectHandleOnStack(ref retData)); - - data = retData; - return ret; - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void AddCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, byte[] data, int dataLength); - - [System.Security.SecurityCritical] // auto-generated - internal static void AddCacheEntry(ConfigId id, int numKey, byte[] key, byte[] data) - { - AddCacheEntry(id, numKey, key, key.Length, data, data.Length); - } - - [System.Security.SecurityCritical] // auto-generated - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern void ResetCacheData(ConfigId id); -#endif - - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void GetMachineDirectory(StringHandleOnStack retDirectory); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void GetUserDirectory(StringHandleOnStack retDirectory); - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern bool WriteToEventLog(string message); } diff --git a/src/mscorlib/src/System/Security/Util/Hex.cs b/src/mscorlib/src/System/Security/Util/Hex.cs index 709744f2a2..4ca1cf678b 100644 --- a/src/mscorlib/src/System/Security/Util/Hex.cs +++ b/src/mscorlib/src/System/Security/Util/Hex.cs @@ -73,7 +73,7 @@ namespace System.Security.Util public static byte[] DecodeHexString(String hexString) { if (hexString == null) - throw new ArgumentNullException( "hexString" ); + throw new ArgumentNullException( nameof(hexString) ); Contract.EndContractBlock(); bool spaceSkippingMode = false; diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs index 19937f5ae6..8a12235106 100644 --- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs +++ b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs @@ -12,6 +12,7 @@ namespace System.Security.Util { using System.Globalization; using System.Runtime.Versioning; using System.IO; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -26,12 +27,9 @@ namespace System.Security.Util { // 2. Ensuring that the partial trust code has permission to see full path data // 3. Not using this set for paths (eg EnvironmentStringExpressionSet) // - [SecurityCritical] protected ArrayList m_list; protected bool m_ignoreCase; - [SecurityCritical] protected String m_expressions; - [SecurityCritical] protected String[] m_expressionsArray; protected bool m_throwOnRelative; @@ -61,7 +59,6 @@ namespace System.Security.Util { { } - [System.Security.SecuritySafeCritical] // auto-generated public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative ) { m_list = null; @@ -78,7 +75,6 @@ namespace System.Security.Util { return new StringExpressionSet(); } - [SecuritySafeCritical] public virtual StringExpressionSet Copy() { // SafeCritical: just copying this value around, not leaking it @@ -118,11 +114,10 @@ namespace System.Security.Util { return StaticProcessSingleString(str); } - [System.Security.SecurityCritical] // auto-generated public void AddExpressions( String str ) { if (str == null) - throw new ArgumentNullException( "str" ); + throw new ArgumentNullException( nameof(str) ); Contract.EndContractBlock(); if (str.Length == 0) return; @@ -165,7 +160,7 @@ namespace System.Security.Util { { if (m_throwOnRelative) { - if (Path.IsRelative(temp)) + if (PathInternal.IsPartiallyQualified(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } @@ -181,16 +176,14 @@ namespace System.Security.Util { Reduce(); } - [System.Security.SecurityCritical] // auto-generated public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath ) { AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates); } - [System.Security.SecurityCritical] // auto-generated public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) { - Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); + Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); m_expressionsArray = null; m_expressions = null; @@ -205,19 +198,18 @@ namespace System.Security.Util { } - [System.Security.SecurityCritical] // auto-generated internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath) { if (str == null) { - throw new ArgumentNullException( "str" ); + throw new ArgumentNullException( nameof(str) ); } Contract.EndContractBlock(); ArrayList retArrayList = new ArrayList(); for (int index = 0; index < str.Length; ++index) { if (str[index] == null) - throw new ArgumentNullException( "str" ); + throw new ArgumentNullException( nameof(str) ); // Replace alternate directory separators String oneString = StaticProcessWholeString( str[index] ); @@ -249,7 +241,6 @@ namespace System.Security.Util { return retArrayList; } - [System.Security.SecurityCritical] // auto-generated protected void CheckList() { if (m_list == null && m_expressions != null) @@ -303,7 +294,6 @@ namespace System.Security.Util { } - [System.Security.SecurityCritical] // auto-generated protected void CreateList() { String[] expressionsArray = Split( m_expressions ); @@ -325,7 +315,7 @@ namespace System.Security.Util { { if (m_throwOnRelative) { - if (Path.IsRelative(temp)) + if (PathInternal.IsPartiallyQualified(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } @@ -339,7 +329,6 @@ namespace System.Security.Util { } } - [SecuritySafeCritical] public bool IsEmpty() { // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their @@ -354,7 +343,6 @@ namespace System.Security.Util { } } - [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOf( StringExpressionSet ses ) { if (this.IsEmpty()) @@ -376,7 +364,6 @@ namespace System.Security.Util { return true; } - [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOfPathDiscovery( StringExpressionSet ses ) { if (this.IsEmpty()) @@ -399,7 +386,6 @@ namespace System.Security.Util { } - [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Union( StringExpressionSet ses ) { // If either set is empty, the union represents a copy of the other. @@ -434,7 +420,6 @@ namespace System.Security.Util { } - [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Intersect( StringExpressionSet ses ) { // If either set is empty, the intersection is empty @@ -477,7 +462,6 @@ namespace System.Security.Util { return intersectSet; } - [SecuritySafeCritical] protected void GenerateString() { // SafeCritical - moves critical data around, but doesn't expose it out @@ -522,7 +506,6 @@ namespace System.Security.Util { // expressions contain paths that were canonicalized and expanded from the input that would cause // information disclosure, so we instead only expose this out to trusted code that can ensure they // either don't leak the information or required full path information. - [SecurityCritical] public string UnsafeToString() { CheckList(); @@ -534,7 +517,6 @@ namespace System.Security.Util { return m_expressions; } - [SecurityCritical] public String[] UnsafeToStringArray() { if (m_expressionsArray == null && m_list != null) @@ -550,7 +532,6 @@ namespace System.Security.Util { // protected static helper functions //------------------------------- - [SecurityCritical] private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) @@ -563,7 +544,6 @@ namespace System.Security.Util { return false; } - [SecurityCritical] private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) @@ -661,7 +641,6 @@ namespace System.Security.Util { // protected helper functions //------------------------------- - [SecuritySafeCritical] protected void AddSingleExpressionNoDuplicates( String expression ) { // SafeCritical: We're not exposing out the string sets, just allowing modification of them @@ -691,7 +670,6 @@ namespace System.Security.Util { this.m_list.Add( expression ); } - [System.Security.SecurityCritical] // auto-generated protected void Reduce() { CheckList(); @@ -726,23 +704,20 @@ namespace System.Security.Util { } } - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath ); - [System.Security.SecurityCritical] // auto-generated internal static String CanonicalizePath( String path ) { return CanonicalizePath( path, true ); } - [System.Security.SecurityCritical] // auto-generated internal static string CanonicalizePath(string path, bool needFullPath) { if (needFullPath) { - string newPath = Path.GetFullPathInternal(path); + string newPath = Path.GetFullPath(path); if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal)) { if (newPath.EndsWith(m_directorySeparator)) diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs index 590a909662..8589fa7c42 100644 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs +++ b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs @@ -9,6 +9,7 @@ namespace System.Security.Util using System.Security.Permissions; using System.Runtime.Serialization; using System.Threading; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -368,31 +369,17 @@ namespace System.Security.Util { Object thisObj = this.GetItem( i ); IPermission thisPerm = thisObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY Object otherObj = (other != null)?other.GetItem( i ):null; IPermission otherPerm = otherObj as IPermission; -#if FEATURE_CAS_POLICY - ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory; -#endif // FEATURE_CAS_POLICY if (thisObj == null && otherObj == null) continue; - - + if (thisObj == null) { -#if FEATURE_CAS_POLICY - if (otherElem != null) - { - otherPerm = PermissionSet.CreatePerm(otherElem, false); - } -#endif // FEATURE_CAS_POLICY - PermissionToken token = PermissionToken.GetToken(otherPerm); - + if (token == null) { throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); @@ -402,13 +389,6 @@ namespace System.Security.Util } else if (otherObj == null) { -#if FEATURE_CAS_POLICY - if (thisElem != null) - { - thisPerm = PermissionSet.CreatePerm(thisElem, false); - } -#endif // FEATURE_CAS_POLICY - PermissionToken token = PermissionToken.GetToken(thisPerm); if (token == null) { @@ -418,7 +398,7 @@ namespace System.Security.Util } else { - Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); + Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); } } return unionSet; @@ -434,10 +414,6 @@ namespace System.Security.Util if (obj != null) { IPermission perm = obj as IPermission; -#if FEATURE_CAS_POLICY - if (perm == null) - perm = PermissionSet.CreatePerm(obj, ignoreTypeLoadFailures); -#endif // FEATURE_CAS_POLICY PermissionToken token = PermissionToken.GetToken(perm); if (perm == null || token == null) diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs index 51ae24cf4a..83f9ce483f 100644 --- a/src/mscorlib/src/System/Security/Util/URLString.cs +++ b/src/mscorlib/src/System/Security/Util/URLString.cs @@ -484,10 +484,11 @@ namespace System.Security.Util { private static void CheckPathTooLong(StringBuilder path) { if (path.Length >= ( -#if FEATURE_PATHCOMPAT - AppContextSwitches.BlockLongPaths ? PathInternal.MaxShortPath : -#endif +#if PLATFORM_UNIX + Interop.Sys.MaxPath)) +#else PathInternal.MaxLongPath)) +#endif { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } @@ -513,7 +514,7 @@ namespace System.Security.Util { // file:/home/johndoe/here // file:../johndoe/here // file:~/johndoe/here - String temp = url; + String temp = url; int nbSlashes = 0; while(nbSlashes" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameLength; - int classNameStart; - - if (!ParseElementForObjectCreation( el, - BuiltInCodeGroup, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - switch (classNameLength) - { - case 12: - // NetCodeGroup - if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new NetCodeGroup(); - else - goto USEREFLECTION; - - case 13: - // FileCodeGroup - if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileCodeGroup(); - else - goto USEREFLECTION; - case 14: - // UnionCodeGroup - if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UnionCodeGroup(); - else - goto USEREFLECTION; - - case 19: - // FirstMatchCodeGroup - if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FirstMatchCodeGroup(); - else - goto USEREFLECTION; - - default: - goto USEREFLECTION; - } - -USEREFLECTION: - Type groupClass = null; - CodeGroup group = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - groupClass = GetClassFromElement(el, true); - if (groupClass == null) - return null; - if (!(typeof(CodeGroup).IsAssignableFrom(groupClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") ); - - group = (CodeGroup) Activator.CreateInstance(groupClass, true); - - Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(), - "This path should not get called for mscorlib based classes" ); - - return group; - } -#pragma warning restore 618 - - [System.Security.SecurityCritical] // auto-generated - internal static IMembershipCondition - CreateMembershipCondition( SecurityElement el ) - { - if (el == null || !el.Tag.Equals("IMembershipCondition")) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameStart; - int classNameLength; - - if (!ParseElementForObjectCreation( el, - BuiltInMembershipCondition, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - // We have a built in membership condition, figure out which it is. - - // Here's the list of built in membership conditions as of 9/17/2002 - // System.Security.Policy.AllMembershipCondition - // System.Security.Policy.URLMembershipCondition - // System.Security.Policy.SHA1MembershipCondition - // System.Security.Policy.SiteMembershipCondition - // System.Security.Policy.ZoneMembershipCondition - // System.Security.Policy.PublisherMembershipCondition - // System.Security.Policy.StrongNameMembershipCondition - // System.Security.Policy.ApplicationMembershipCondition - // System.Security.Policy.DomainApplicationMembershipCondition - // System.Security.Policy.ApplicationDirectoryMembershipCondition - - switch (classNameLength) - { - case 22: - // AllMembershipCondition - // URLMembershipCondition - if (className[classNameStart] == 'A') - { - if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new AllMembershipCondition(); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UrlMembershipCondition(); - else - goto USEREFLECTION; - } - - case 23: - // HashMembershipCondition - // SiteMembershipCondition - // ZoneMembershipCondition - if (className[classNameStart] == 'H') - { - if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new HashMembershipCondition(); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'S') - { - if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SiteMembershipCondition(); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ZoneMembershipCondition(); - else - goto USEREFLECTION; - } - - case 28: - // PublisherMembershipCondition - if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new PublisherMembershipCondition(); - else - goto USEREFLECTION; - - case 29: - // StrongNameMembershipCondition - if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new StrongNameMembershipCondition(); - else - goto USEREFLECTION; - - case 39: - // ApplicationDirectoryMembershipCondition - if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ApplicationDirectoryMembershipCondition(); - else - goto USEREFLECTION; - - default: - goto USEREFLECTION; - } - -USEREFLECTION: - Type condClass = null; - IMembershipCondition cond = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - condClass = GetClassFromElement(el, true); - if (condClass == null) - return null; - if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") ); - - cond = (IMembershipCondition) Activator.CreateInstance(condClass, true); - - return cond; - } -#endif //#if FEATURE_CAS_POLICY internal static Type GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) { @@ -624,7 +364,7 @@ USEREFLECTION: { try { - return Type.GetType(className, false, false); + return Type.GetType(className, false, false); } catch (SecurityException) { @@ -632,7 +372,7 @@ USEREFLECTION: } } else - return Type.GetType(className, true, false); + return Type.GetType(className, true, false); } public static bool diff --git a/src/mscorlib/src/System/Security/securestring.cs b/src/mscorlib/src/System/Security/securestring.cs index b53d0db5b4..548126f4d0 100644 --- a/src/mscorlib/src/System/Security/securestring.cs +++ b/src/mscorlib/src/System/Security/securestring.cs @@ -14,6 +14,7 @@ namespace System.Security { using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; + using System.Diagnostics; using System.Diagnostics.Contracts; public sealed class SecureString: IDisposable { @@ -105,15 +106,15 @@ namespace System.Security { [CLSCompliant(false)] public unsafe SecureString(char* value, int length) { if( value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if( length < 0) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if( length > MaxLength) { - throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Length")); + throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Length")); } Contract.EndContractBlock(); @@ -192,7 +193,7 @@ namespace System.Security { #endif // FEATURE_CORRUPTING_EXCEPTIONS public void InsertAt( int index, char c ) { if( index < 0 || index > m_length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); } Contract.EndContractBlock(); @@ -251,7 +252,7 @@ namespace System.Security { EnsureNotReadOnly(); if( index < 0 || index >= m_length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); } unsafe @@ -290,10 +291,10 @@ namespace System.Security { #endif // FEATURE_CORRUPTING_EXCEPTIONS public void SetAt( int index, char c ) { if( index < 0 || index >= m_length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); } Contract.EndContractBlock(); - Contract.Assert(index <= Int32.MaxValue / sizeof(char)); + Debug.Assert(index <= Int32.MaxValue / sizeof(char)); EnsureNotDisposed(); EnsureNotReadOnly(); @@ -315,7 +316,7 @@ namespace System.Security { private int BufferLength { [System.Security.SecurityCritical] // auto-generated get { - Contract.Assert(m_buffer != null, "Buffer is not initialized!"); + Debug.Assert(m_buffer != null, "Buffer is not initialized!"); return m_buffer.Length; } } @@ -341,7 +342,7 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated private void EnsureCapacity(int capacity) { if( capacity > MaxLength) { - throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity")); + throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity")); } Contract.EndContractBlock(); @@ -377,7 +378,7 @@ namespace System.Security { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static uint GetAlignedSize( int size) { - Contract.Assert(size >= 0, "size must be non-negative"); + Debug.Assert(size >= 0, "size must be non-negative"); uint alignedSize = ((uint)size / BlockSize) * BlockSize; if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize @@ -449,8 +450,8 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] private void ProtectMemory() { - Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); - Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); + Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); + Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); if( m_length == 0 || m_encrypted) { return; @@ -650,8 +651,8 @@ namespace System.Security { [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void UnProtectMemory() { - Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); - Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); + Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!"); + Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!"); if( m_length == 0) { return; @@ -733,7 +734,7 @@ namespace System.Security { source.AcquirePointer(ref sourcePtr); target.AcquirePointer(ref targetPtr); - Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!"); + Debug.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!"); Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2); } -- cgit v1.2.3