diff options
Diffstat (limited to 'src/mscorlib/src/System/Security')
74 files changed, 6 insertions, 18813 deletions
diff --git a/src/mscorlib/src/System/Security/AccessControl/Enums.cs b/src/mscorlib/src/System/Security/AccessControl/Enums.cs deleted file mode 100644 index 20f5c5f91a..0000000000 --- a/src/mscorlib/src/System/Security/AccessControl/Enums.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System.Security.AccessControl -{ - [Flags] - public enum InheritanceFlags - { - None = 0x00, - ContainerInherit = 0x01, - ObjectInherit = 0x02, - } - - [Flags] - public enum PropagationFlags - { - None = 0x00, - NoPropagateInherit = 0x01, - InheritOnly = 0x02, - } - - [Flags] - public enum AuditFlags - { - None = 0x00, - Success = 0x01, - Failure = 0x02, - } - - [Flags] - public enum SecurityInfos - { - Owner = 0x00000001, - Group = 0x00000002, - DiscretionaryAcl = 0x00000004, - SystemAcl = 0x00000008, - - } - - - public enum ResourceType - { - Unknown = 0x00, - FileObject = 0x01, - Service = 0x02, - Printer = 0x03, - RegistryKey = 0x04, - LMShare = 0x05, - KernelObject = 0x06, - WindowObject = 0x07, - DSObject = 0x08, - DSObjectAll = 0x09, - ProviderDefined = 0x0A, - WmiGuidObject = 0x0B, - RegistryWow6432Key = 0x0C, - } - - [Flags] - public enum AccessControlSections { - None = 0, - Audit = 0x1, - Access = 0x2, - Owner = 0x4, - Group = 0x8, - All = 0xF - } - - [Flags] - public enum AccessControlActions { - None = 0 - } -} diff --git a/src/mscorlib/src/System/Security/Attributes.cs b/src/mscorlib/src/System/Security/Attributes.cs index e4ebc53053..f67a9f0ad1 100644 --- a/src/mscorlib/src/System/Security/Attributes.cs +++ b/src/mscorlib/src/System/Security/Attributes.cs @@ -19,7 +19,6 @@ namespace System.Security // Indicates that the target P/Invoke method(s) should skip the per-call // security checked for unmanaged code permission. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )] - [System.Runtime.InteropServices.ComVisible(true)] sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute { } @@ -27,7 +26,6 @@ namespace System.Security // UnverifiableCodeAttribute: // Indicates that the target module contains unverifiable code. [AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] sealed public class UnverifiableCodeAttribute : System.Attribute { } @@ -38,7 +36,6 @@ namespace System.Security // For v.1, this is valid only on Assemblies, but could be expanded to // include Module, Method, class [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )] - [System.Runtime.InteropServices.ComVisible(true)] sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute { private PartialTrustVisibilityLevel _visibilityLevel; diff --git a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs b/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs deleted file mode 100644 index 48539574af..0000000000 --- a/src/mscorlib/src/System/Security/BuiltInPermissionSets.cs +++ /dev/null @@ -1,255 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// - -using System; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Security.Permissions; -using Microsoft.Win32; - -namespace System.Security -{ - internal static class BuiltInPermissionSets - { - // - // Raw PermissionSet XML - the built in permission sets are expressed in XML form since they contain - // permissions from assemblies other than mscorlib. - // - - private static readonly string s_everythingXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""Everything"" - Description = """ + Environment.GetResourceString("Policy_PS_Everything") + @""" - <IPermission class = ""System.Data.OleDb.OleDbPermission, " + AssemblyRef.SystemData + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Data.SqlClient.SqlClientPermission, " + AssemblyRef.SystemData + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Diagnostics.PerformanceCounterPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Net.SocketPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Net.WebPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.DataProtectionPermission, " + AssemblyRef.SystemSecurity + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Diagnostics.EventLogPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.FileIOPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.KeyContainerPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.RegistryPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""Assertion, UnmanagedCode, Execution, ControlThread, ControlEvidence, ControlPolicy, ControlAppDomain, SerializationFormatter, ControlDomainPolicy, ControlPrincipal, RemotingConfiguration, Infrastructure, BindingRedirects"" /> - <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.StorePermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - </PermissionSet>"; - - private static readonly string s_executionXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""Execution"" - Description = """ + Environment.GetResourceString("Policy_PS_Execution") + @"""> - <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""Execution"" /> - </PermissionSet>"; - - private static readonly string s_fullTrustXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Unrestricted = ""true"" - Name = ""FullTrust"" - Description = """ + Environment.GetResourceString("Policy_PS_FullTrust") + @""" />"; - - private static readonly string s_internetXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""Internet"" - Description = """ + Environment.GetResourceString("Policy_PS_Internet") + @"""> - <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @""" - version = ""1"" - Level = ""SafePrinting"" /> - <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Access = ""Open"" /> - <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - UserQuota = ""1024000"" - Allowed = ""ApplicationIsolationByUser"" /> - <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""Execution"" /> - <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Window = ""SafeTopLevelWindows"" - Clipboard = ""OwnClipboard"" /> - </PermissionSet>"; - - private static readonly string s_localIntranetXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""LocalIntranet"" - Description = """ + Environment.GetResourceString("Policy_PS_LocalIntranet") + @""" > - <IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @""" - version = ""1"" - Level = ""DefaultPrinting"" /> - <IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Read = ""USERNAME"" /> - <IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - <IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Allowed = ""AssemblyIsolationByUser"" - UserQuota = ""9223372036854775807"" - Expiry = ""9223372036854775807"" - Permanent = ""true"" /> - <IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""ReflectionEmit, RestrictedMemberAccess"" /> - <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""Execution, Assertion, BindingRedirects "" /> - <IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @""" - version = ""1"" - Flags = ""RestrictedRegistrationAccess"" /> - <IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Unrestricted = ""true"" /> - </PermissionSet>"; - - private static readonly string s_nothingXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""Nothing"" - Description = """ + Environment.GetResourceString("Policy_PS_Nothing") + @""" />"; - - private static readonly string s_skipVerificationXml = - @"<PermissionSet class = ""System.Security.NamedPermissionSet"" - version = ""1"" - Name = ""SkipVerification"" - Description = """ + Environment.GetResourceString("Policy_PS_SkipVerification") + @"""> - <IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @""" - version = ""1"" - Flags = ""SkipVerification"" /> - </PermissionSet>"; - - // - // Built in permission set objects - // - - private static NamedPermissionSet s_everything; - private static NamedPermissionSet s_execution; - private static NamedPermissionSet s_fullTrust; - private static NamedPermissionSet s_internet; - private static NamedPermissionSet s_localIntranet; - private static NamedPermissionSet s_nothing; - private static NamedPermissionSet s_skipVerification; - - // - // Standard permission sets - // - - internal static NamedPermissionSet Everything - { - get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); } - } - - internal static NamedPermissionSet Execution - { - get { return GetOrDeserializePermissionSet(ref s_execution, s_executionXml); } - } - - internal static NamedPermissionSet FullTrust - { - get { return GetOrDeserializePermissionSet(ref s_fullTrust, s_fullTrustXml); } - } - - internal static NamedPermissionSet Internet - { - get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); } - } - - internal static NamedPermissionSet LocalIntranet - { - get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); } - } - - internal static NamedPermissionSet Nothing - { - get { return GetOrDeserializePermissionSet(ref s_nothing, s_nothingXml); } - } - - internal static NamedPermissionSet SkipVerification - { - get { return GetOrDeserializePermissionSet(ref s_skipVerification, s_skipVerificationXml); } - } - - // - // Utility methods to construct the permission set objects from the well known XML and any permission - // set extensions if necessary - // - - private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet( - ref NamedPermissionSet permissionSet, - string permissionSetXml) - { - Contract.Requires(!String.IsNullOrEmpty(permissionSetXml)); - return permissionSet.Copy() as NamedPermissionSet; - } - - private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet, - string permissionSetXml) - { - Debug.Assert(!String.IsNullOrEmpty(permissionSetXml)); - return permissionSet.Copy() as NamedPermissionSet; - } - } -} diff --git a/src/mscorlib/src/System/Security/CodeAccessPermission.cs b/src/mscorlib/src/System/Security/CodeAccessPermission.cs deleted file mode 100644 index 70504d902e..0000000000 --- a/src/mscorlib/src/System/Security/CodeAccessPermission.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.IO; - using System.Threading; - using System.Security; - using System.Security.Util; - using System.Security.Permissions; - using System.Runtime.CompilerServices; - using System.Collections; - using System.Text; - using System; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission; - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - abstract public class CodeAccessPermission - : IPermission, ISecurityEncodable, IStackWalk - { - // Static methods for manipulation of stack - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static void RevertAssert() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.RevertAssert(ref stackMark); - } - - [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() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.RevertDeny(ref stackMark); - } - - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static void RevertPermitOnly() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.RevertPermitOnly(ref stackMark); - } - - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static void RevertAll() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.RevertAll(ref stackMark); - } - - // - // Standard implementation of IPermission methods for - // code-access permissions. - // - - // 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). - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void Demand() - { - if (!this.CheckDemand( null )) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; - CodeAccessSecurityEngine.Check(this, ref stackMark); - } - } - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - internal static void Demand(PermissionType permissionType) - { - // The intent of the method is to be an internal mscorlib helper that Demands a specific permissiontype - // 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. - Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand"); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; - CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark); - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void Assert() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - CodeAccessSecurityEngine.Assert(this, ref stackMark); - } - - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - static internal void Assert(bool allPossible) - { - // The intent of the method is to be an internal mscorlib helper that easily asserts for all possible permissions - // 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. - Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert"); - - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.AssertAllPossible(ref stackMark); - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [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.")] - public void Deny() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - CodeAccessSecurityEngine.Deny(this, ref stackMark); - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void PermitOnly() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - CodeAccessSecurityEngine.PermitOnly(this, ref stackMark); - } - - // IPermission interfaces - - // We provide a default implementation of Union here. - // Any permission that doesn't provide its own representation - // of Union will get this one and trigger CompoundPermission - // We can take care of simple cases here... - - public virtual IPermission Union(IPermission other) { - // The other guy could be null - if (other == null) return(this.Copy()); - - // otherwise we don't support it. - throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" )); - } - - // - // HELPERS FOR IMPLEMENTING ABSTRACT METHODS - // - - // - // Protected helper - // - - internal bool VerifyType(IPermission perm) - { - // if perm is null, then obviously not of the same type - if ((perm == null) || (perm.GetType() != this.GetType())) { - return(false); - } else { - return(true); - } - } - - // The IPermission Interface - public abstract IPermission Copy(); - public abstract IPermission Intersect(IPermission target); - public abstract bool IsSubsetOf(IPermission target); - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals(Object obj) - { - IPermission perm = obj as IPermission; - if(obj != null && perm == null) - return false; - try { - if(!this.IsSubsetOf(perm)) - return false; - if(perm != null && !perm.IsSubsetOf(this)) - return false; - } - catch (ArgumentException) - { - // Any argument exception implies inequality - // Note that we require a try/catch block here because we have to deal with - // custom permissions that may throw exceptions indiscriminately. - return false; - } - return true; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - // This implementation is only to silence a compiler warning. - return base.GetHashCode(); - } - - - internal bool CheckDemand(CodeAccessPermission grant) - { - 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) - { - 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) - { - 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) - { - 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 deleted file mode 100644 index d86897c02e..0000000000 --- a/src/mscorlib/src/System/Security/CodeAccessSecurityEngine.cs +++ /dev/null @@ -1,400 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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; - using System.Threading; - using System.Security.Util; - using System.Collections; - using System.Runtime.CompilerServices; - using System.Security.Permissions; - using System.Reflection; - 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 - // KEEP IN SYNC WITH DEFINITIONS IN SECURITYPOLICY.H - [Serializable] - internal enum PermissionType - { - // special flags - SecurityUnmngdCodeAccess = 0, - SecuritySkipVerification = 1, - ReflectionTypeInfo = 2, - SecurityAssert = 3, - ReflectionMemberAccess = 4, - SecuritySerialization = 5, - ReflectionRestrictedMemberAccess = 6, - FullTrust = 7, - SecurityBindingRedirects = 8, - - // special permissions - UIPermission = 9, - EnvironmentPermission = 10, - FileDialogPermission = 11, - FileIOPermission = 12, - ReflectionPermission = 13, - SecurityPermission = 14, - - // additional special flags - SecurityControlEvidence = 16, - SecurityControlPrincipal = 17 - } - - internal static class CodeAccessSecurityEngine - { - - internal static SecurityPermission AssertPermission; - internal static PermissionToken AssertPermissionToken; - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark); - - [System.Diagnostics.Conditional( "_DEBUG" )] - private static void DEBUG_OUT( String str ) - { -#if _DEBUG - if (debug) - Console.WriteLine( str ); -#endif - } - -#if _DEBUG - private static bool debug = false; - private const String file = "d:\\foo\\debug.txt"; -#endif - - // static default constructor. This will be called before any of the static members are accessed. - static CodeAccessSecurityEngine() - { -#pragma warning disable 618 - AssertPermission = new SecurityPermission(SecurityPermissionFlag.Assertion); -#pragma warning restore 618 - AssertPermissionToken = PermissionToken.GetToken(AssertPermission); - } - -#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 - { - AssemblyName asmName = null; - Evidence asmEvidence = null; - if (asm != null) - { - // Assert here because reflection will check grants and if we fail the check, - // there will be an infinite recursion that overflows the stack. - PermissionSet.s_fullTrust.Assert(); - asmName = asm.GetName(); - } - throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed); - } - -#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 - { - 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); - else - { - AssemblyName asmName = new AssemblyName((String)assemblyOrString); - throw SecurityException.MakeSecurityException(asmName, null, granted, refused, rmh, action, demand, permThatFailed); - } - } - -#if FEATURE_COMPRESSEDSTACK - internal static void CheckSetHelper(CompressedStack cs, - PermissionSet grants, - PermissionSet refused, - PermissionSet demands, - RuntimeMethodHandleInternal rmh, - RuntimeAssembly asm, - SecurityAction action) - { - if (cs != null) - cs.CheckSetDemand(demands, rmh); - else - CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true); - } -#else // FEATURE_COMPRESSEDSTACK -#pragma warning disable 618 - internal static void CheckSetHelper(Object notUsed, - PermissionSet grants, - PermissionSet refused, - PermissionSet demands, - RuntimeMethodHandleInternal rmh, - RuntimeAssembly asm, - SecurityAction action) -#pragma warning restore 618 - { - // 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.) - 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 - -#pragma warning disable 618 - internal static bool CheckSetHelper(PermissionSet grants, - PermissionSet refused, - PermissionSet demands, - RuntimeMethodHandleInternal rmh, - Object assemblyOrString, - SecurityAction action, - bool throwException) -#pragma warning restore 618 - { - Debug.Assert(demands != null, "Should not reach here with a null demand set"); - - IPermission permThatFailed = null; - if (grants != null) - grants.CheckDecoded(demands); - if (refused != null) - refused.CheckDecoded(demands); - - bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); - - try - { - - // Check grant set - if (!demands.CheckDemand(grants, out permThatFailed)) - { - if (throwException) - ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed); - else - return false; - } - - // Check refused set - if (!demands.CheckDeny(refused, out permThatFailed)) - { - if (throwException) - ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed); - else - return false; - } - } - catch (SecurityException) - { - throw; - } - catch (Exception) - { - // Any exception besides a security exception in this code means that - // a permission was unable to properly handle what we asked of it. - // We will define this to mean that the demand failed. - if (throwException) - ThrowSecurityException(assemblyOrString, grants, refused, rmh, action, demands, permThatFailed); - else - return false; - } - finally - { - if (bThreadSecurity) - SecurityManager._SetThreadSecurity(true); - } - return true; - } -#if FEATURE_COMPRESSEDSTACK - internal static void CheckHelper(CompressedStack cs, - PermissionSet grantedSet, - PermissionSet refusedSet, - CodeAccessPermission demand, - PermissionToken permToken, - RuntimeMethodHandleInternal rmh, - RuntimeAssembly asm, - SecurityAction action) - { - if (cs != null) - cs.CheckDemand(demand, permToken, rmh); - else - CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true); - } -#else // FEATURE_COMPRESSEDSTACK -#pragma warning disable 618 - internal static void CheckHelper(Object notUsed, - PermissionSet grantedSet, - PermissionSet refusedSet, - CodeAccessPermission demand, - PermissionToken permToken, - RuntimeMethodHandleInternal rmh, - RuntimeAssembly asm, - SecurityAction action) -#pragma warning restore 618 - { - // 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.) - 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 -#pragma warning disable 618 - internal static bool CheckHelper(PermissionSet grantedSet, - PermissionSet refusedSet, - CodeAccessPermission demand, - PermissionToken permToken, - RuntimeMethodHandleInternal rmh, - Object assemblyOrString, - SecurityAction action, - bool throwException) -#pragma warning restore 618 - { - // We should never get here with a null demand - Debug.Assert(demand != null, "Should not reach here with a null demand"); - - if (permToken == null) - permToken = PermissionToken.GetToken(demand); - - if (grantedSet != null) - grantedSet.CheckDecoded(permToken.m_index); - if (refusedSet != null) - refusedSet.CheckDecoded(permToken.m_index); - - // If PermissionSet is null, then module does not have Permissions... Fail check. - - bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); - - try - { - if (grantedSet == null) - { - if (throwException) - ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand); - else - return false; - } - - else if (!grantedSet.IsUnrestricted()) - { - // 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. - - Debug.Assert(demand != null,"demand != null"); - - // Find the permission of matching type in the permission set. - - CodeAccessPermission grantedPerm = - (CodeAccessPermission)grantedSet.GetPermission(permToken); - - // Make sure the demand has been granted - if (!demand.CheckDemand( grantedPerm )) - { - if (throwException) - ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand); - else - return false; - } - } - - // Make the sure the permission is not refused. - - if (refusedSet != null) - { - CodeAccessPermission refusedPerm = - (CodeAccessPermission)refusedSet.GetPermission(permToken); - if (refusedPerm != null) - { - if (!refusedPerm.CheckDeny(demand)) - { - #if _DEBUG - if (debug) - DEBUG_OUT( "Permission found in refused set" ); - #endif - if (throwException) - ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand); - else - return false; - - } - } - - if (refusedSet.IsUnrestricted()) - { - if (throwException) - ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand); - else - return false; - } - } - } - catch (SecurityException) - { - throw; - } - catch (Exception) - { - // Any exception besides a security exception in this code means that - // a permission was unable to properly handle what we asked of it. - // We will define this to mean that the demand failed. - if (throwException) - ThrowSecurityException(assemblyOrString, grantedSet, refusedSet, rmh, action, demand, demand); - else - return false; - } - finally - { - if (bThreadSecurity) - SecurityManager._SetThreadSecurity(true); - } - - DEBUG_OUT( "Check passed" ); - return true; - } - - internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark) - { - } - - - internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark) - { - } - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern FrameSecurityDescriptor CheckNReturnSO(PermissionToken permToken, - CodeAccessPermission demand, - ref StackCrawlMark stackMark, - int create ); - - internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark) - { - } - - internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark) - { - } - - internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark) - { - } - -#if FEATURE_PLS - // Update the PLS used for optimization in the AppDomain: called from the VM - private static PermissionListSet UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms) { - if (adPLS == null) { - adPLS = new PermissionListSet(); - adPLS.UpdateDomainPLS(grantedPerms, refusedPerms); - return adPLS; - } else { - PermissionListSet newPLS = new PermissionListSet(); - newPLS.UpdateDomainPLS(adPLS); - newPLS.UpdateDomainPLS(grantedPerms, refusedPerms); - return newPLS; - } - } -#endif //FEATURE_PLS - } -} diff --git a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs b/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs deleted file mode 100644 index 0ef5afd282..0000000000 --- a/src/mscorlib/src/System/Security/FrameSecurityDescriptor.cs +++ /dev/null @@ -1,537 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Text; - using System.Runtime.CompilerServices; - using System.Threading; - using System; - using System.Collections; - using System.Security.Permissions; - 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; -#endif - //FrameSecurityDescriptor.cs - // - // Internal use only. - // DO NOT DOCUMENT - // - - [Serializable] - internal class FrameSecurityDescriptor - { - - /* EE has native FrameSecurityDescriptorObject definition in object.h - Make sure to update that structure as well, if you make any changes here. - */ - private PermissionSet m_assertions; // imperative asserts - private PermissionSet m_denials; // imperative denials - private PermissionSet m_restriction; // imperative permitonlys - private PermissionSet m_DeclarativeAssertions; - private PermissionSet m_DeclarativeDenials; - private PermissionSet m_DeclarativeRestrictions; - -#if !FEATURE_PAL - // 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 - [NonSerialized] - private SafeAccessTokenHandle m_callerToken; - [NonSerialized] - private SafeAccessTokenHandle m_impToken; -#endif - - private bool m_AssertFT; - private bool m_assertAllPossible; -#pragma warning disable 169 - private bool m_declSecComputed; // set from the VM to indicate that the declarative A/PO/D on this frame has been populated -#pragma warning restore 169 - - - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void IncrementOverridesCount(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void DecrementOverridesCount(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void IncrementAssertCount(); - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void DecrementAssertCount(); - - - // Default constructor. - internal FrameSecurityDescriptor() - { - //m_flags = 0; - } - //-----------------------------------------------------------+ - // H E L P E R - //-----------------------------------------------------------+ - - private PermissionSet CreateSingletonSet(IPermission perm) - { - PermissionSet permSet = new PermissionSet(false); - permSet.AddPermission(perm.Copy()); - return permSet; - } - - //-----------------------------------------------------------+ - // A S S E R T - //-----------------------------------------------------------+ - - internal bool HasImperativeAsserts() - { - // we store declarative actions in both fields, so check if they are different - return (m_assertions != null); - } - internal bool HasImperativeDenials() - { - // we store declarative actions in both fields, so check if they are different - return (m_denials != null); - } - internal bool HasImperativeRestrictions() - { - // we store declarative actions in both fields, so check if they are different - return (m_restriction != null); - } - internal void SetAssert(IPermission perm) - { - m_assertions = CreateSingletonSet(perm); - IncrementAssertCount(); - } - - internal void SetAssert(PermissionSet permSet) - { - m_assertions = permSet.Copy(); - m_AssertFT = m_AssertFT || m_assertions.IsUnrestricted(); - IncrementAssertCount(); - } - - internal PermissionSet GetAssertions(bool fDeclarative) - { - return (fDeclarative) ? m_DeclarativeAssertions : m_assertions; - } - - internal void SetAssertAllPossible() - { - m_assertAllPossible = true; - IncrementAssertCount(); - } - - internal bool GetAssertAllPossible() - { - return m_assertAllPossible; - } - - //-----------------------------------------------------------+ - // D E N Y - //-----------------------------------------------------------+ - - internal void SetDeny(IPermission perm) - { - m_denials = CreateSingletonSet(perm); - IncrementOverridesCount(); - } - - internal void SetDeny(PermissionSet permSet) - { - m_denials = permSet.Copy(); - IncrementOverridesCount(); - } - - internal PermissionSet GetDenials(bool fDeclarative) - { - return (fDeclarative) ? m_DeclarativeDenials: m_denials; - } - - //-----------------------------------------------------------+ - // R E S T R I C T - //-----------------------------------------------------------+ - - internal void SetPermitOnly(IPermission perm) - { - m_restriction = CreateSingletonSet(perm); - IncrementOverridesCount(); - } - - internal void SetPermitOnly(PermissionSet permSet) - { - // permSet must not be null - m_restriction = permSet.Copy(); - IncrementOverridesCount(); - } - - internal PermissionSet GetPermitOnly(bool fDeclarative) - { - - return (fDeclarative) ? m_DeclarativeRestrictions : m_restriction; - } -#if !FEATURE_PAL - //-----------------------------------------------------------+ - // SafeAccessTokenHandle (Impersonation + EH purposes) - //-----------------------------------------------------------+ - internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken) - { - m_callerToken = callerToken; - m_impToken = impToken; - } -#endif - //-----------------------------------------------------------+ - // R E V E R T - //-----------------------------------------------------------+ - - internal void RevertAssert() - { - if (m_assertions != null) - { - m_assertions = null; - DecrementAssertCount(); - } - - - if (m_DeclarativeAssertions != null) - { - m_AssertFT = m_DeclarativeAssertions.IsUnrestricted(); - } - else - { - m_AssertFT = false; - } - } - - internal void RevertAssertAllPossible() - { - if (m_assertAllPossible) - { - m_assertAllPossible = false; - DecrementAssertCount(); - } - } - - internal void RevertDeny() - { - if (HasImperativeDenials()) - { - DecrementOverridesCount(); - m_denials = null; - } - } - - internal void RevertPermitOnly() - { - if (HasImperativeRestrictions()) - { - DecrementOverridesCount(); - m_restriction= null;; - } - } - - internal void RevertAll() - { - RevertAssert(); - RevertAssertAllPossible(); - RevertDeny(); - RevertPermitOnly(); - } - - - //-----------------------------------------------------------+ - // Demand Evaluation - //-----------------------------------------------------------+ - - - // This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack - internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) - { - // imperative security - bool fContinue = CheckDemand2(demand, permToken, rmh, false); - if (fContinue == SecurityRuntime.StackContinue) - { - // declarative security - fContinue = CheckDemand2(demand, permToken, rmh, true); - } - return fContinue; - } - - internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative) - { - PermissionSet permSet; - - // If the demand is null, there is no need to continue - Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); - - // decode imperative - if (GetPermitOnly(fDeclarative) != null) - GetPermitOnly(fDeclarative).CheckDecoded(demand, permToken); - - if (GetDenials(fDeclarative) != null) - GetDenials(fDeclarative).CheckDecoded(demand, permToken); - - if (GetAssertions(fDeclarative) != null) - GetAssertions(fDeclarative).CheckDecoded(demand, permToken); - - // NOTE: See notes about exceptions and exception handling in FrameDescSetHelper - - bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); - - // Check Reduction - - try - { - permSet = GetPermitOnly(fDeclarative); - if (permSet != null) - { - CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); - - // If the permit only set does not contain the demanded permission, throw a security exception - if (perm == null) - { - if (!permSet.IsUnrestricted()) - throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand); - } - else - { - bool bNeedToThrow = true; - - try - { - bNeedToThrow = !demand.CheckPermitOnly(perm); - } - catch (ArgumentException) - { - } - - if (bNeedToThrow) - throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand); - } - } - - // Check Denials - - permSet = GetDenials(fDeclarative); - if (permSet != null) - { - CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); - - // If an unrestricted set was denied and the demand implements IUnrestricted - if (permSet.IsUnrestricted()) - throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand); - - // If the deny set does contain the demanded permission, throw a security exception - bool bNeedToThrow = true; - try - { - bNeedToThrow = !demand.CheckDeny(perm); - } - catch (ArgumentException) - { - } - if (bNeedToThrow) - throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand); - } - - if (GetAssertAllPossible()) - { - return SecurityRuntime.StackHalt; - } - - permSet = GetAssertions(fDeclarative); - // Check Assertions - if (permSet != null) - { - - CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); - - // If the assert set does contain the demanded permission, halt the stackwalk - - try - { - if (permSet.IsUnrestricted() || demand.CheckAssert(perm)) - { - return SecurityRuntime.StackHalt; - } - } - catch (ArgumentException) - { - } - } - - } - finally - { - if (bThreadSecurity) - SecurityManager._SetThreadSecurity(true); - } - - return SecurityRuntime.StackContinue; - } - - internal bool CheckSetDemand(PermissionSet demandSet, - out PermissionSet alteredDemandSet, - RuntimeMethodHandleInternal rmh) - { - // imperative security - PermissionSet altPset1 = null, altPset2 = null; - bool fContinue = CheckSetDemand2(demandSet, out altPset1, rmh, false); - if (altPset1 != null) - { - demandSet = altPset1; - } - - if (fContinue == SecurityRuntime.StackContinue) - { - // declarative security - fContinue = CheckSetDemand2(demandSet, out altPset2, rmh, true); - } - // Return the most recent altered set - // If both declarative and imperative asserts modified the demand set: return altPset2 - // Else if imperative asserts modified the demand set: return altPset1 - // else no alteration: return null - if (altPset2 != null) - alteredDemandSet = altPset2; - else if (altPset1 != null) - alteredDemandSet = altPset1; - else - alteredDemandSet = null; - - return fContinue; - } - - internal bool CheckSetDemand2(PermissionSet demandSet, - out PermissionSet alteredDemandSet, - RuntimeMethodHandleInternal rmh, bool fDeclarative) - { - PermissionSet permSet; - - // In the common case we are not going to alter the demand set, so just to - // be safe we'll set it to null up front. - alteredDemandSet = null; - - // There's some oddness in here to deal with exceptions. The general idea behind - // this is that we need some way of dealing with custom permissions that may not - // handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly - // (they don't support it, throw null reference exceptions, etc.). - - // An empty demand always succeeds. - if (demandSet == null || demandSet.IsEmpty()) - return SecurityRuntime.StackHalt; - - if (GetPermitOnly(fDeclarative) != null) - GetPermitOnly(fDeclarative).CheckDecoded( demandSet ); - if (GetDenials(fDeclarative) != null) - GetDenials(fDeclarative).CheckDecoded( demandSet ); - if (GetAssertions(fDeclarative) != null) - GetAssertions(fDeclarative).CheckDecoded( demandSet ); - - - bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); - - try - { - // In the case of permit only, we define an exception to be failure of the check - // and therefore we throw a security exception. - - permSet = GetPermitOnly(fDeclarative); - if (permSet != null) - { - IPermission permFailed = null; - bool bNeedToThrow = true; - - try - { - bNeedToThrow = !demandSet.CheckPermitOnly(permSet, out permFailed); - } - catch (ArgumentException) - { - } - if (bNeedToThrow) - throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed); - } - - // In the case of denial, we define an exception to be failure of the check - // and therefore we throw a security exception. - - permSet = GetDenials(fDeclarative); - - - if (permSet != null) - { - IPermission permFailed = null; - - bool bNeedToThrow = true; - - try - { - bNeedToThrow = !demandSet.CheckDeny(permSet, out permFailed); - } - catch (ArgumentException) - { - } - - if (bNeedToThrow) - throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed); - } - - // The assert case is more complex. Since asserts have the ability to "bleed through" - // (where part of a demand is handled by an assertion, but the rest is passed on to - // continue the stackwalk), we need to be more careful in handling the "failure" case. - // Therefore, if an exception is thrown in performing any operation, we make sure to keep - // that permission in the demand set thereby continuing the demand for that permission - // walking down the stack. - - if (GetAssertAllPossible()) - { - return SecurityRuntime.StackHalt; - } - - permSet = GetAssertions(fDeclarative); - if (permSet != null) - { - // If this frame asserts a superset of the demand set we're done - - if (demandSet.CheckAssertion( permSet )) - return SecurityRuntime.StackHalt; - - // Determine whether any of the demand set asserted. We do this by - // copying the demand set and removing anything in it that is asserted. - - if (!permSet.IsUnrestricted()) - { - PermissionSet.RemoveAssertedPermissionSet(demandSet, permSet, out alteredDemandSet); - } - } - - } - finally - { - if (bThreadSecurity) - SecurityManager._SetThreadSecurity(true); - } - - return SecurityRuntime.StackContinue; - } - } - -#if FEATURE_COMPRESSEDSTACK - // Used by the stack compressor to communicate a DynamicResolver to managed code during a stackwalk. - // The JIT will not actually place these on frames. - internal class FrameSecurityDescriptorWithResolver : FrameSecurityDescriptor - { - private System.Reflection.Emit.DynamicResolver m_resolver; - - public System.Reflection.Emit.DynamicResolver Resolver - { - get - { - return m_resolver; - } - } - } -#endif // FEATURE_COMPRESSEDSTACK -} diff --git a/src/mscorlib/src/System/Security/HostProtectionException.cs b/src/mscorlib/src/System/Security/HostProtectionException.cs deleted file mode 100644 index b08fccd1b3..0000000000 --- a/src/mscorlib/src/System/Security/HostProtectionException.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -/*============================================================================= -** -** -** Purpose: Exception class for HostProtection -** -** -=============================================================================*/ - -namespace System.Security -{ - using System.Security; - using System; - using System.Runtime.Serialization; - using System.Security.Permissions; - using System.Reflection; - using System.Text; - using System.Diagnostics.Contracts; - - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - public class HostProtectionException : SystemException - { - private HostProtectionResource m_protected; - private HostProtectionResource m_demanded; - - private const String ProtectedResourcesName = "ProtectedResources"; - private const String DemandedResourcesName = "DemandedResources"; - - public HostProtectionException() : base() - { - m_protected = HostProtectionResource.None; - m_demanded = HostProtectionResource.None; - } - - public HostProtectionException(string message) : base(message) - { - m_protected = HostProtectionResource.None; - m_demanded = HostProtectionResource.None; - } - - public HostProtectionException(string message, Exception e) : base(message, e) - { - m_protected = HostProtectionResource.None; - m_demanded = HostProtectionResource.None; - } - - protected HostProtectionException(SerializationInfo info, StreamingContext context) : base(info, context) - { - if (info==null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - m_protected = (HostProtectionResource)info.GetValue(ProtectedResourcesName, typeof(HostProtectionResource)); - m_demanded = (HostProtectionResource)info.GetValue(DemandedResourcesName, typeof(HostProtectionResource)); - } - - public HostProtectionException(string message, HostProtectionResource protectedResources, HostProtectionResource demandedResources) - : base(message) - { - SetErrorCode(__HResults.COR_E_HOSTPROTECTION); - m_protected = protectedResources; - m_demanded = demandedResources; - } - - // Called from the VM to create a HP Exception - private HostProtectionException(HostProtectionResource protectedResources, HostProtectionResource demandedResources) - : base(SecurityException.GetResString("HostProtection_HostProtection")) - { - SetErrorCode(__HResults.COR_E_HOSTPROTECTION); - m_protected = protectedResources; - m_demanded = demandedResources; - } - - - public HostProtectionResource ProtectedResources - { - get - { - return m_protected; - } - } - - public HostProtectionResource DemandedResources - { - get - { - return m_demanded; - } - } - - private String ToStringHelper(String resourceString, Object attr) - { - if (attr == null) - return String.Empty; - StringBuilder sb = new StringBuilder(); - sb.Append(Environment.NewLine); - sb.Append(Environment.NewLine); - sb.Append(Environment.GetResourceString( resourceString )); - sb.Append(Environment.NewLine); - sb.Append(attr); - return sb.ToString(); - } - - public override String ToString() - { - String protectedResStrValue = ToStringHelper("HostProtection_ProtectedResources", ProtectedResources); - StringBuilder sb = new StringBuilder(); - sb.Append(base.ToString()); - - sb.Append(protectedResStrValue); - sb.Append(ToStringHelper("HostProtection_DemandedResources", DemandedResources)); - - return sb.ToString(); - - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info==null) - throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); - - base.GetObjectData( info, context ); - - info.AddValue(ProtectedResourcesName, ProtectedResources, typeof(HostProtectionResource)); - info.AddValue(DemandedResourcesName, DemandedResources, typeof(HostProtectionResource)); - } - } -} diff --git a/src/mscorlib/src/System/Security/HostSecurityManager.cs b/src/mscorlib/src/System/Security/HostSecurityManager.cs deleted file mode 100644 index 53137983d3..0000000000 --- a/src/mscorlib/src/System/Security/HostSecurityManager.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// A HostSecurityManager gives a hosting application the chance to -// participate in the security decisions in the AppDomain. -// - -namespace System.Security -{ - using System.Collections; - using System.Reflection; - using System.Security; - using System.Security.Permissions; - using System.Security.Policy; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - - - [Serializable] - [Flags] - [System.Runtime.InteropServices.ComVisible(true)] - public enum HostSecurityManagerOptions { - None = 0x0000, - HostAppDomainEvidence = 0x0001, - [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.")] - HostPolicyLevel = 0x0002, - HostAssemblyEvidence = 0x0004, - HostDetermineApplicationTrust = 0x0008, - HostResolvePolicy = 0x0010, - AllFlags = 0x001F - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public class HostSecurityManager { - public HostSecurityManager () {} - - // The host can choose which events he wants to participate in. This property can be set when - // the host only cares about a subset of the capabilities exposed through the HostSecurityManager. - public virtual HostSecurityManagerOptions Flags { - get { - // We use AllFlags as the default. - return HostSecurityManagerOptions.AllFlags; - } - } - - public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) { - // The default implementation does not modify the input evidence. - return inputEvidence; - } - - public virtual Evidence ProvideAssemblyEvidence (Assembly loadedAssembly, Evidence inputEvidence) { - // The default implementation does not modify the input evidence. - return inputEvidence; - } - - /// <summary> - /// Determine what types of evidence the host might be able to supply for the AppDomain if requested - /// </summary> - /// <returns></returns> - public virtual Type[] GetHostSuppliedAppDomainEvidenceTypes() { - return null; - } - - /// <summary> - /// Determine what types of evidence the host might be able to supply for an assembly if requested - /// </summary> - public virtual Type[] GetHostSuppliedAssemblyEvidenceTypes(Assembly assembly) { - return null; - } - - /// <summary> - /// Ask the host to supply a specific type of evidence for the AppDomain - /// </summary> - public virtual EvidenceBase GenerateAppDomainEvidence(Type evidenceType) { - return null; - } - - /// <summary> - /// Ask the host to supply a specific type of evidence for an assembly - /// </summary> - public virtual EvidenceBase GenerateAssemblyEvidence(Type evidenceType, Assembly assembly) { - return null; - } - } -} diff --git a/src/mscorlib/src/System/Security/IEvidenceFactory.cs b/src/mscorlib/src/System/Security/IEvidenceFactory.cs deleted file mode 100644 index 592ab533be..0000000000 --- a/src/mscorlib/src/System/Security/IEvidenceFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - [System.Runtime.InteropServices.ComVisible(true)] - public interface IEvidenceFactory - { - } -} diff --git a/src/mscorlib/src/System/Security/IPermission.cs b/src/mscorlib/src/System/Security/IPermission.cs deleted file mode 100644 index 5477261fd7..0000000000 --- a/src/mscorlib/src/System/Security/IPermission.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// Defines the interface that all Permission objects must support. -// - -namespace System.Security -{ - -[System.Runtime.InteropServices.ComVisible(true)] - public interface IPermission : ISecurityEncodable - { - // NOTE: The constants that used to be defined here were moved to - // PermissionsEnum.cs due to CLS restrictions. - - // The integrity of the security system depends on a means to - // copy objects so that references to sensitive objects are not - // exposed outside of the runtime. Thus, all permissions must - // implement Copy. - // - // Makes an exact copy of the Permission. - IPermission Copy(); - - /* - * Methods to support the Installation, Registration, others... PolicyEngine - */ - - // Policy decisions and runtime mechanisms (for example, Deny) - // require a means to retrieve shared state between two - // permissions. If there is no shared state between two - // instances, then the method should return null. - // - // Could think of the method as GetCommonState, - // but leave it as Intersect to avoid gratuitous name changes. - // - // Returns a new permission with the permission-defined intersection - // of the two permissions. The intersection is generally defined as - // privilege parameters that are included by both 'this' and 'target'. - // Returns null if 'target' is null or is of wrong type. - // - IPermission Intersect(IPermission target); - - // The runtime policy manager also requires a means of combining the - // state contained within two permissions of the same type in a logical OR - // construct. (The Union of two permission of different type is not defined, - // except when one of the two is a CompoundPermission of internal type equal - // to the type of the other permission.) - // - - IPermission Union(IPermission target); - - // IsSubsetOf defines a standard mechanism for determining - // relative safety between two permission demands of the same type. - // If one demand x demands no more than some other demand y, then - // x.IsSubsetOf(y) should return true. In this case, if the - // demand for y is satisfied, then it is possible to assume that - // the demand for x would also be satisfied under the same - // circumstances. On the other hand, if x demands something that y - // does not, then x.IsSubsetOf(y) should return false; the fact - // that x is satisfied by the current security context does not - // also imply that the demand for y will also be satisfied. - // - // Returns true if 'this' Permission allows no more access than the - // argument. - // - bool IsSubsetOf(IPermission target); - - // The Demand method is the fundamental part of the IPermission - // interface from a component developer's perspective. The - // permission represents the demand that the developer wants - // satisfied, and Demand is the means to invoke the demand. - // For each type of permission, the mechanism to verify the - // demand will be different. However, to the developer, all - // permissions invoke that mechanism through the Demand interface. - // 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). - [DynamicSecurityMethodAttribute()] - void Demand(); - - } -} diff --git a/src/mscorlib/src/System/Security/ISecurityEncodable.cs b/src/mscorlib/src/System/Security/ISecurityEncodable.cs deleted file mode 100644 index 689b3e4b5f..0000000000 --- a/src/mscorlib/src/System/Security/ISecurityEncodable.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// All encodable security classes that support encoding need to -// implement this interface -// - -namespace System.Security -{ - [System.Runtime.InteropServices.ComVisible(true)] - public interface ISecurityEncodable - { - } -} diff --git a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs b/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs deleted file mode 100644 index 567e41e891..0000000000 --- a/src/mscorlib/src/System/Security/ISecurityPolicyEncodable.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// All encodable security classes that support encoding need to -// implement this interface -// - -namespace System.Security -{ - [System.Runtime.InteropServices.ComVisible(true)] - public interface ISecurityPolicyEncodable - { - } -} diff --git a/src/mscorlib/src/System/Security/IStackWalk.cs b/src/mscorlib/src/System/Security/IStackWalk.cs deleted file mode 100644 index 902fc35b61..0000000000 --- a/src/mscorlib/src/System/Security/IStackWalk.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - -[System.Runtime.InteropServices.ComVisible(true)] - public interface IStackWalk - { - [DynamicSecurityMethodAttribute()] - void Assert(); - - [DynamicSecurityMethodAttribute()] - void Demand(); - - [DynamicSecurityMethodAttribute()] - void Deny(); - - [DynamicSecurityMethodAttribute()] - void PermitOnly(); - } -} diff --git a/src/mscorlib/src/System/Security/NamedPermissionSet.cs b/src/mscorlib/src/System/Security/NamedPermissionSet.cs deleted file mode 100644 index 1bc166fde8..0000000000 --- a/src/mscorlib/src/System/Security/NamedPermissionSet.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// Extends PermissionSet to allow an associated name and description -// - -namespace System.Security -{ - using System; - using System.Security.Permissions; - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class NamedPermissionSet : PermissionSet - { - 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")) - return CreateFullTrustSet(); - else if (name.Equals("Nothing")) - return CreateNothingSet(); - else if (name.Equals("Execution")) - return CreateExecutionSet(); - else if (name.Equals("SkipVerification")) - return CreateSkipVerificationSet(); - else if (name.Equals("Internet")) - return CreateInternetSet(); - else - return null; - } - - private static PermissionSet CreateFullTrustSet() { - return new PermissionSet(PermissionState.Unrestricted); - } - - private static PermissionSet CreateNothingSet() { - return new PermissionSet(PermissionState.None); - } - - private static PermissionSet CreateExecutionSet() { - PermissionSet permSet = new PermissionSet(PermissionState.None); -#pragma warning disable 618 - permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); -#pragma warning restore 618 - return permSet; - } - - private static PermissionSet CreateSkipVerificationSet() { - PermissionSet permSet = new PermissionSet(PermissionState.None); -#pragma warning disable 618 - permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SkipVerification)); -#pragma warning restore 618 - return permSet; - } - - private static PermissionSet CreateInternetSet() { - PermissionSet permSet = new PermissionSet(PermissionState.None); - permSet.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open)); -#pragma warning disable 618 - permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); -#pragma warning restore 618 - permSet.AddPermission(new UIPermission(UIPermissionWindow.SafeTopLevelWindows, UIPermissionClipboard.OwnClipboard)); - return permSet; - - - } - } -} diff --git a/src/mscorlib/src/System/Security/PermissionListSet.cs b/src/mscorlib/src/System/Security/PermissionListSet.cs deleted file mode 100644 index 093542ad4e..0000000000 --- a/src/mscorlib/src/System/Security/PermissionListSet.cs +++ /dev/null @@ -1,535 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** -** -** Purpose: Holds state about A/G/R permissionsets in a callstack or appdomain -** (Replacement for PermissionListSet) -** -=============================================================================*/ - -namespace System.Security -{ - using System.Globalization; - using System.Reflection; - using System.Runtime.InteropServices; - using System.Security; - using System.Security.Permissions; - using System.Threading; - using System.Collections; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - sealed internal class PermissionListSet - { - // Only internal (public) methods are creation methods and demand evaluation methods. - // Scroll down to the end to see them. - private PermissionSetTriple m_firstPermSetTriple; - private ArrayList m_permSetTriples; -#if FEATURE_COMPRESSEDSTACK - private ArrayList m_zoneList; - private ArrayList m_originList; -#endif // FEATURE_COMPRESSEDSTACK - - internal PermissionListSet() {} - - private void EnsureTriplesListCreated() - { - if (m_permSetTriples == null) - { - m_permSetTriples = new ArrayList(); - if (m_firstPermSetTriple != null) - { - m_permSetTriples.Add(m_firstPermSetTriple); - m_firstPermSetTriple = null; - } - } - } - -#if FEATURE_PLS - internal void UpdateDomainPLS (PermissionListSet adPLS) { - if (adPLS != null && adPLS.m_firstPermSetTriple != null) - UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet); - } - - internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) { - Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null"); - if (m_firstPermSetTriple == null) - m_firstPermSetTriple = new PermissionSetTriple(); - - // update the grant and denied sets - m_firstPermSetTriple.UpdateGrant(grantSet); - m_firstPermSetTriple.UpdateRefused(deniedSet); - } -#endif // FEATURE_PLS - - private void Terminate(PermissionSetTriple currentTriple) - { - UpdateTripleListAndCreateNewTriple(currentTriple, null); - } - - private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls) - { -#if FEATURE_COMPRESSEDSTACK - this.UpdateZoneAndOrigin(pls); -#endif // FEATURE_COMPRESSEDSTACK - this.UpdatePermissions(currentTriple, pls); - this.UpdateTripleListAndCreateNewTriple(currentTriple, null); - } - - private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls) - { -#if FEATURE_COMPRESSEDSTACK - this.UpdateZoneAndOrigin(pls); -#endif // FEATURE_COMPRESSEDSTACK - return this.UpdatePermissions(currentTriple, pls); - } - - private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd) - { -#if FEATURE_COMPRESSEDSTACK - FrameSecurityDescriptorWithResolver fsdWithResolver = fsd as FrameSecurityDescriptorWithResolver; - if (fsdWithResolver != null) - { - return Update2(currentTriple, fsdWithResolver); - } -#endif // FEATURE_COMPRESSEDSTACK - - // check imperative - bool fHalt = Update2(currentTriple, fsd, false); - if (!fHalt) - { - // then declarative - fHalt = Update2(currentTriple, fsd, true); - } - return fHalt; - } - -#if FEATURE_COMPRESSEDSTACK - private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver) - { - System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver; - CompressedStack dynamicCompressedStack = resolver.GetSecurityContext(); - dynamicCompressedStack.CompleteConstruction(null); - return this.Update(currentTriple, dynamicCompressedStack.PLS); - } -#endif // FEATURE_COMPRESSEDSTACK - - private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative) - { - // Deny - PermissionSet deniedPset = fsd.GetDenials(fDeclarative); - if (deniedPset != null) - { - currentTriple.UpdateRefused(deniedPset); - } - - // permit only - PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative); - if (permitOnlyPset != null) - { - currentTriple.UpdateGrant(permitOnlyPset); - } - - // Assert all possible - if (fsd.GetAssertAllPossible()) - { - // If we have no grant set, it means that the only assembly we've seen on the stack so - // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the - // compressed stack is also FullTrust. - if (currentTriple.GrantSet == null) - currentTriple.GrantSet = PermissionSet.s_fullTrust; - - UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); - currentTriple.GrantSet = PermissionSet.s_fullTrust; - currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative)); - return true; - } - - // Assert - PermissionSet assertPset = fsd.GetAssertions(fDeclarative); - if (assertPset != null) - { - if (assertPset.IsUnrestricted()) - { - // If we have no grant set, it means that the only assembly we've seen on the stack so - // far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the - // compressed stack is also FullTrust. - if (currentTriple.GrantSet == null) - currentTriple.GrantSet = PermissionSet.s_fullTrust; - - UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples); - currentTriple.GrantSet = PermissionSet.s_fullTrust; - currentTriple.UpdateAssert(assertPset); - return true; - } - - PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset); - if (retTriple != null) - { - EnsureTriplesListCreated(); - m_permSetTriples.Add(retTriple); - } - } - - return false; - } - private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r) - { -#if FEATURE_COMPRESSEDSTACK - ZoneIdentityPermission z; - UrlIdentityPermission u; - currentTriple.UpdateGrant(in_g, out z, out u); - currentTriple.UpdateRefused(in_r); - AppendZoneOrigin(z, u); -#else // !FEATURE_COMPRESEDSTACK - currentTriple.UpdateGrant(in_g); - currentTriple.UpdateRefused(in_r); -#endif // FEATURE_COMPRESSEDSTACK - } - - // Called from the VM for HG CS construction - private void Update(PermissionSet in_g) - { - if (m_firstPermSetTriple == null) - m_firstPermSetTriple = new PermissionSetTriple(); - Update(m_firstPermSetTriple, in_g, null); - } - -#if FEATURE_COMPRESSEDSTACK - private void UpdateZoneAndOrigin(PermissionListSet pls) - { - if (pls != null) - { - if (this.m_zoneList == null && pls.m_zoneList != null && pls.m_zoneList.Count > 0) - this.m_zoneList = new ArrayList(); - UpdateArrayList(this.m_zoneList, pls.m_zoneList); - if (this.m_originList == null && pls.m_originList != null && pls.m_originList.Count > 0) - this.m_originList = new ArrayList(); - UpdateArrayList(this.m_originList, pls.m_originList); - } - } -#endif // FEATURE_COMPRESSEDSTACK - - private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls) - { - if (pls != null) - { - if (pls.m_permSetTriples != null) - { - // DCS has an AGR List. So we need to add the AGR List - UpdateTripleListAndCreateNewTriple(currentTriple,pls.m_permSetTriples); - } - else - { - // Common case: One AGR set - - PermissionSetTriple tmp_psTriple = pls.m_firstPermSetTriple; - PermissionSetTriple retTriple; - // First try and update currentTriple. Return value indicates if we can stop construction - if (currentTriple.Update(tmp_psTriple, out retTriple)) - return true; - // If we got a non-null retTriple, what it means is that compression failed, - // and we now have 2 triples to deal with: retTriple and currentTriple. - // retTriple has to be appended first. then currentTriple. - if (retTriple != null) - { - EnsureTriplesListCreated(); - // we just created a new triple...add the previous one (returned) to the list - m_permSetTriples.Add(retTriple); - } - } - } - else - { - // pls can be null only outside the loop in CreateCompressedState - UpdateTripleListAndCreateNewTriple(currentTriple, null); - } - - - return false; - - } - - - private void UpdateTripleListAndCreateNewTriple(PermissionSetTriple currentTriple, ArrayList tripleList) - { - if (!currentTriple.IsEmpty()) - { - if (m_firstPermSetTriple == null && m_permSetTriples == null) - { - m_firstPermSetTriple = new PermissionSetTriple(currentTriple); - } - else - { - EnsureTriplesListCreated(); - m_permSetTriples.Add(new PermissionSetTriple(currentTriple)); - } - currentTriple.Reset(); - } - if (tripleList != null) - { - EnsureTriplesListCreated(); - m_permSetTriples.AddRange(tripleList); - } - } - - private static void UpdateArrayList(ArrayList current, ArrayList newList) - { - if (newList == null) - return; - - for(int i=0;i < newList.Count; i++) - { - if (!current.Contains(newList[i])) - current.Add(newList[i]); - } - - } - -#if FEATURE_COMPRESSEDSTACK - private void AppendZoneOrigin(ZoneIdentityPermission z, UrlIdentityPermission u) - { - - if (z != null) - { - if (m_zoneList == null) - m_zoneList = new ArrayList(); - z.AppendZones(m_zoneList); - } - - if (u != null) - { - if (m_originList == null) - m_originList = new ArrayList(); - u.AppendOrigin(m_originList); - } - } - -[System.Runtime.InteropServices.ComVisible(true)] - // public(internal) interface begins... - // Creation functions - static internal PermissionListSet CreateCompressedState(CompressedStack cs, CompressedStack innerCS) - { - // function that completes the construction of the compressed stack if not done so already (bottom half for demand evaluation) - - bool bHaltConstruction = false; - if (cs.CompressedStackHandle == null) - return null; // FT case or Security off - - PermissionListSet pls = new PermissionListSet(); - PermissionSetTriple currentTriple = new PermissionSetTriple(); - int numDomains = CompressedStack.GetDCSCount(cs.CompressedStackHandle); - for (int i=numDomains-1; (i >= 0 && !bHaltConstruction) ; i--) - { - DomainCompressedStack dcs = CompressedStack.GetDomainCompressedStack(cs.CompressedStackHandle, i); - if (dcs == null) - continue; // we hit a FT Domain - if (dcs.PLS == null) - { - // We failed on some DCS - throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"))); - } - pls.UpdateZoneAndOrigin(dcs.PLS); - pls.Update(currentTriple, dcs.PLS); - bHaltConstruction = dcs.ConstructionHalted; - } - if (!bHaltConstruction) - { - PermissionListSet tmp_pls = null; - // Construction did not halt. - if (innerCS != null) - { - innerCS.CompleteConstruction(null); - tmp_pls = innerCS.PLS; - } - pls.Terminate(currentTriple, tmp_pls); - } - else - { - pls.Terminate(currentTriple); - } - - return pls; - } - - static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction) - { - PermissionListSet pls = new PermissionListSet(); - PermissionSetTriple currentTriple = new PermissionSetTriple(); - - PermissionSet tmp_g, tmp_r; - // Construct the descriptor list - int descCount = DomainCompressedStack.GetDescCount(unmanagedDCS); - bHaltConstruction = false; - for(int i=0; (i < descCount && !bHaltConstruction); i++) - { - FrameSecurityDescriptor fsd; - Assembly assembly; - if (DomainCompressedStack.GetDescriptorInfo(unmanagedDCS, i, out tmp_g, out tmp_r, out assembly, out fsd)) - { - // Got an FSD - bHaltConstruction = pls.Update(currentTriple, fsd); - } - else - { - pls.Update(currentTriple, tmp_g, tmp_r); - } - - } - if (!bHaltConstruction) - { - // domain - if (!DomainCompressedStack.IgnoreDomain(unmanagedDCS)) - { - DomainCompressedStack.GetDomainPermissionSets(unmanagedDCS, out tmp_g, out tmp_r); - pls.Update(currentTriple, tmp_g, tmp_r); - } - } - pls.Terminate(currentTriple); - - - // return the created object - return pls; - - } - static internal PermissionListSet CreateCompressedState_HG() - { - PermissionListSet pls = new PermissionListSet(); - CompressedStack.GetHomogeneousPLS(pls); - return pls; - } -#endif // #if FEATURE_COMPRESSEDSTACK - // Private Demand evaluation functions - only called from the VM - internal bool CheckDemandNoThrow(CodeAccessPermission demand) - { - // AppDomain permissions - no asserts. So there should only be one triple to work with - Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); - - - - PermissionToken permToken = null; - if (demand != null) - permToken = PermissionToken.GetToken(demand); - - return m_firstPermSetTriple.CheckDemandNoThrow(demand, permToken); - - - } - internal bool CheckSetDemandNoThrow(PermissionSet pSet) - { - // AppDomain permissions - no asserts. So there should only be one triple to work with - Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet"); - - - return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet); - } - - // Demand evauation functions - internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) - { - bool bRet = SecurityRuntime.StackContinue; - if (m_permSetTriples != null) - { - for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) - { - PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; - bRet = psTriple.CheckDemand(demand, permToken, rmh); - } - } - else if (m_firstPermSetTriple != null) - { - bRet = m_firstPermSetTriple.CheckDemand(demand, permToken, rmh); - } - - return bRet; - } - - internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh) - { - PermissionSet unused; - CheckSetDemandWithModification(pset, out unused, rmh); - return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk - } - - internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) - { - bool bRet = SecurityRuntime.StackContinue; - PermissionSet demandSet = pset; - alteredDemandSet = null; - if (m_permSetTriples != null) - { - for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++) - { - PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i]; - bRet = psTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); - if (alteredDemandSet != null) - demandSet = alteredDemandSet; - } - } - else if (m_firstPermSetTriple != null) - { - bRet = m_firstPermSetTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh); - } - - return bRet; - } - - /// <summary> - /// Check to see if the PLS satisfies a demand for the special permissions encoded in flags - /// </summary> - /// <param name="flags">set of flags to check (See PermissionType)</param> - private bool CheckFlags(int flags) - { - Debug.Assert(flags != 0, "Invalid permission flag demand"); - - bool check = true; - - if (m_permSetTriples != null) - { - for (int i = 0; i < m_permSetTriples.Count && check && flags != 0; i++) - { - check &= ((PermissionSetTriple)m_permSetTriples[i]).CheckFlags(ref flags); - } - } - else if (m_firstPermSetTriple != null) - { - check = m_firstPermSetTriple.CheckFlags(ref flags); - } - - return check; - } - - /// <summary> - /// Demand which succeeds if either a set of special permissions or a permission set is granted - /// to the call stack - /// </summary> - /// <param name="flags">set of flags to check (See PermissionType)</param> - /// <param name="grantSet">alternate permission set to check</param> - internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet) - { - if (CheckFlags(flags)) - return; - - CheckSetDemand(grantSet, RuntimeMethodHandleInternal.EmptyHandle); - } - -#if FEATURE_COMPRESSEDSTACK - internal void GetZoneAndOrigin(ArrayList zoneList, ArrayList originList, PermissionToken zoneToken, PermissionToken originToken) - { - if (m_zoneList != null) - zoneList.AddRange(m_zoneList); - if (m_originList != null) - originList.AddRange(m_originList); - } -#endif - } - -} diff --git a/src/mscorlib/src/System/Security/PermissionSet.cs b/src/mscorlib/src/System/Security/PermissionSet.cs deleted file mode 100644 index 11ca02a81e..0000000000 --- a/src/mscorlib/src/System/Security/PermissionSet.cs +++ /dev/null @@ -1,1605 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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; - using System.Threading; - using System.Security.Util; - using System.Collections; - using System.IO; - using System.Security.Permissions; - using System.Runtime.CompilerServices; - using System.Security.Policy; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION - using BindingFlags = System.Reflection.BindingFlags; - using System.Runtime.Serialization; - using System.Text; - using System.Globalization; - using System.Runtime.Versioning; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - internal enum SpecialPermissionSetFlag - { - // These also appear in clr/src/vm/permset.h - Regular = 0, - NoSet = 1, - EmptySet = 2, - SkipVerification = 3 - } - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - [System.Runtime.InteropServices.ComVisible(true)] - public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk -#if FEATURE_SERIALIZATION - , IDeserializationCallback -#endif - { -#if _DEBUG - internal static readonly bool debug; -#endif - - [System.Diagnostics.Conditional( "_DEBUG" )] - private static void DEBUG_WRITE(String str) { - #if _DEBUG - if (debug) Console.WriteLine(str); - #endif - } - - [System.Diagnostics.Conditional( "_DEBUG" )] - private static void DEBUG_COND_WRITE(bool exp, String str) - { - #if _DEBUG - if (debug && (exp)) Console.WriteLine(str); - #endif - } - - [System.Diagnostics.Conditional( "_DEBUG" )] - private static void DEBUG_PRINTSTACK(Exception e) - { - #if _DEBUG - if (debug) Console.WriteLine((e).StackTrace); - #endif - } - - // These members are accessed from EE using their hardcoded offset. - // Please update the PermissionSetObject in object.h if you make any changes - // to the fields here. !dumpobj will show the field layout - - // First the fields that are serialized x-appdomain (for perf reasons) - private bool m_Unrestricted; - [OptionalField(VersionAdded = 2)] - private bool m_allPermissionsDecoded = false; - - [OptionalField(VersionAdded = 2)] - internal TokenBasedSet m_permSet = null; - - // This is a workaround so that SQL can operate under default policy without actually - // granting permissions in assemblies that they disallow. - - [OptionalField(VersionAdded = 2)] - private bool m_ignoreTypeLoadFailures = false; - - // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the PermissionSet - [OptionalField(VersionAdded = 2)] - private String m_serializedPermissionSet; - - [NonSerialized] private bool m_CheckedForNonCas; - [NonSerialized] private bool m_ContainsCas; - [NonSerialized] private bool m_ContainsNonCas; - - // only used during non X-AD serialization to save the m_permSet value (which we dont want serialized) - [NonSerialized] private TokenBasedSet m_permSetSaved; - - // Following 4 fields are used only for serialization compat purposes: DO NOT USE THESE EVER! -#pragma warning disable 169 - private bool readableonly; - private TokenBasedSet m_unrestrictedPermSet; - private TokenBasedSet m_normalPermSet; - - [OptionalField(VersionAdded = 2)] - private bool m_canUnrestrictedOverride; -#pragma warning restore 169 - // END: Serialization-only fields - - internal static readonly PermissionSet s_fullTrust = new PermissionSet( true ); - -#if _DEBUG - [OnSerialized] - private void OnSerialized(StreamingContext context) - { - Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR"); - } -#endif // _DEBUG - - internal PermissionSet() - { - Reset(); - m_Unrestricted = true; - } - - internal PermissionSet(bool fUnrestricted) - : this() - { - SetUnrestricted(fUnrestricted); - } - - public PermissionSet(PermissionState state) - : this() - { - if (state == PermissionState.Unrestricted) - { - SetUnrestricted( true ); - } - else if (state == PermissionState.None) - { - SetUnrestricted( false ); - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public PermissionSet(PermissionSet permSet) - : this() - { - if (permSet == null) - { - Reset(); - return; - } - - m_Unrestricted = permSet.m_Unrestricted; - m_CheckedForNonCas = permSet.m_CheckedForNonCas; - m_ContainsCas = permSet.m_ContainsCas; - m_ContainsNonCas = permSet.m_ContainsNonCas; - m_ignoreTypeLoadFailures = permSet.m_ignoreTypeLoadFailures; - - if (permSet.m_permSet != null) - { - m_permSet = new TokenBasedSet(permSet.m_permSet); - - // now deep copy all permissions in set - for (int i = m_permSet.GetStartingIndex(); i <= m_permSet.GetMaxUsedIndex(); i++) - { - Object obj = m_permSet.GetItem(i); - IPermission perm = obj as IPermission; - - if (perm != null) - { - m_permSet.SetItem(i, perm.Copy()); - } - } - } - } - - public virtual void CopyTo(Array array, int index) - { - if (array == null) - throw new ArgumentNullException( nameof(array) ); - Contract.EndContractBlock(); - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - while (enumerator.MoveNext()) - { - array.SetValue(enumerator.Current , index++ ); - } - } - - - // private constructor that doesn't create any token based sets - private PermissionSet( Object trash, Object junk ) - { - m_Unrestricted = false; - } - - - // Returns an object appropriate for synchronizing access to this - // Array. - public virtual Object SyncRoot - { get { return this; } } - - // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized - // collection, you can use SyncRoot as an object to synchronize your - // collection with. You could also call GetSynchronized() - // to get a synchronized wrapper around the Array. - public virtual bool IsSynchronized - { get { return false; } } - - // Is this Collection ReadOnly? - public virtual bool IsReadOnly - { get {return false; } } - - // Reinitializes all state in PermissionSet - DO NOT null-out m_serializedPermissionSet - internal void Reset() - { - m_Unrestricted = false; - m_allPermissionsDecoded = true; - m_permSet = null; - - m_ignoreTypeLoadFailures = false; - - m_CheckedForNonCas = false; - m_ContainsCas = false; - m_ContainsNonCas = false; - m_permSetSaved = null; - - - } - - internal void CheckSet() - { - if (this.m_permSet == null) - this.m_permSet = new TokenBasedSet(); - } - - public bool IsEmpty() - { - if (m_Unrestricted) - return false; - - if (m_permSet == null || m_permSet.FastIsEmpty()) - return true; - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - while (enumerator.MoveNext()) - { - IPermission perm = (IPermission)enumerator.Current; - - if (!perm.IsSubsetOf( null )) - { - return false; - } - } - - return true; - } - - internal bool FastIsEmpty() - { - if (m_Unrestricted) - return false; - - if (m_permSet == null || m_permSet.FastIsEmpty()) - return true; - - return false; - } - - public virtual int Count - { - get - { - int count = 0; - - if (m_permSet != null) - count += m_permSet.GetCount(); - - return count; - } - } - - internal IPermission GetPermission(int index) - { - if (m_permSet == null) - return null; - Object obj = m_permSet.GetItem( index ); - if (obj == null) - return null; - return obj as IPermission; - } - - internal IPermission GetPermission(PermissionToken permToken) - { - if (permToken == null) - return null; - - return GetPermission( permToken.m_index ); - } - - internal IPermission GetPermission( IPermission perm ) - { - if (perm == null) - return null; - - return GetPermission(PermissionToken.GetToken( perm )); - } - - public IPermission SetPermission(IPermission perm) - { - return SetPermissionImpl(perm); - } - - // SetPermission overwrites a permission in a permissionset. - protected virtual IPermission SetPermissionImpl(IPermission perm) - { - // can't get token if perm is null - if (perm == null) - return null; - - PermissionToken permToken = PermissionToken.GetToken(perm); - - if ((permToken.m_type & PermissionTokenType.IUnrestricted) != 0) - { - // SetPermission Makes the Permission "Restricted" - m_Unrestricted = false; - } - - CheckSet(); - - IPermission currPerm = GetPermission( permToken.m_index ); - - m_CheckedForNonCas = false; - - // Should we copy here? - m_permSet.SetItem( permToken.m_index, perm ); - return perm; - } - - public IPermission AddPermission(IPermission perm) - { - return AddPermissionImpl(perm); - } - - protected virtual IPermission AddPermissionImpl(IPermission perm) - { - // can't get token if perm is null - if (perm == null) - return null; - - m_CheckedForNonCas = false; - - // If the permission set is unrestricted, then return an unrestricted instance - // of perm. - - PermissionToken permToken = PermissionToken.GetToken(perm); - - if (this.IsUnrestricted() && ((permToken.m_type & PermissionTokenType.IUnrestricted) != 0)) - { - Type perm_type = perm.GetType(); - Object[] objs = new Object[1]; - objs[0] = PermissionState.Unrestricted; - return (IPermission) Activator.CreateInstance(perm_type, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null ); - } - - CheckSet(); - IPermission currPerm = GetPermission(permToken.m_index); - - // If a Permission exists in this slot, then union it with perm - // Otherwise, just add perm. - - if (currPerm != null) { - IPermission ip_union = currPerm.Union(perm); - m_permSet.SetItem( permToken.m_index, ip_union ); - return ip_union; - } else { - // Should we copy here? - m_permSet.SetItem( permToken.m_index, perm ); - return perm; - } - - } - - private IPermission RemovePermission( int index ) - { - IPermission perm = GetPermission(index); - if (perm == null) - return null; - return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission - } - - // Make this internal soon. - internal void SetUnrestricted(bool unrestricted) - { - m_Unrestricted = unrestricted; - if (unrestricted) - { - // if this is to be an unrestricted permset, null the m_permSet member - m_permSet = null; - } - } - - public bool IsUnrestricted() - { - return m_Unrestricted; - } - - internal enum IsSubsetOfType - { - Normal, - CheckDemand, - CheckPermitOnly, - CheckAssertion, - } - - internal bool IsSubsetOfHelper(PermissionSet target, IsSubsetOfType type, out IPermission firstPermThatFailed, bool ignoreNonCas) - { - #if _DEBUG - if (debug) - DEBUG_WRITE("IsSubsetOf\n" + - "Other:\n" + - (target == null ? "<null>" : target.ToString()) + - "\nMe:\n" + - ToString()); - #endif - - firstPermThatFailed = null; - if (target == null || target.FastIsEmpty()) - { - if(this.IsEmpty()) - return true; - else - { - firstPermThatFailed = GetFirstPerm(); - return false; - } - } - else if (this.IsUnrestricted() && !target.IsUnrestricted()) - return false; - else if (this.m_permSet == null) - return true; - else - { - target.CheckSet(); - - for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i) - { - IPermission thisPerm = this.GetPermission(i); - if (thisPerm == null || thisPerm.IsSubsetOf(null)) - continue; - - IPermission targetPerm = target.GetPermission(i); -#if _DEBUG - PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized"); -#endif - - if (target.m_Unrestricted) - continue; - - // targetPerm can be null here, but that is fine since it thisPerm is a subset - // of empty/null then we can continue in the loop. - CodeAccessPermission cap = thisPerm as CodeAccessPermission; - if(cap == null) - { - if (!ignoreNonCas && !thisPerm.IsSubsetOf( targetPerm )) - { - firstPermThatFailed = thisPerm; - return false; - } - } - else - { - firstPermThatFailed = thisPerm; - switch(type) - { - case IsSubsetOfType.Normal: - if (!thisPerm.IsSubsetOf( targetPerm )) - return false; - break; - case IsSubsetOfType.CheckDemand: - if (!cap.CheckDemand( (CodeAccessPermission)targetPerm )) - return false; - break; - case IsSubsetOfType.CheckPermitOnly: - if (!cap.CheckPermitOnly( (CodeAccessPermission)targetPerm )) - return false; - break; - case IsSubsetOfType.CheckAssertion: - if (!cap.CheckAssert( (CodeAccessPermission)targetPerm )) - return false; - break; - } - firstPermThatFailed = null; - } - } - } - - return true; - } - - public bool IsSubsetOf(PermissionSet target) - { - IPermission perm; - return IsSubsetOfHelper(target, IsSubsetOfType.Normal, out perm, false); - } - - internal bool CheckDemand(PermissionSet target, out IPermission firstPermThatFailed) - { - return IsSubsetOfHelper(target, IsSubsetOfType.CheckDemand, out firstPermThatFailed, true); - } - - internal bool CheckPermitOnly(PermissionSet target, out IPermission firstPermThatFailed) - { - return IsSubsetOfHelper(target, IsSubsetOfType.CheckPermitOnly, out firstPermThatFailed, true); - } - - internal bool CheckAssertion(PermissionSet target) - { - IPermission perm; - return IsSubsetOfHelper(target, IsSubsetOfType.CheckAssertion, out perm, true); - } - - internal bool CheckDeny(PermissionSet deniedSet, out IPermission firstPermThatFailed) - { - firstPermThatFailed = null; - if (deniedSet == null || deniedSet.FastIsEmpty() || this.FastIsEmpty()) - return true; - - if(this.m_Unrestricted && deniedSet.m_Unrestricted) - return false; - - CodeAccessPermission permThis, permThat; - PermissionSetEnumeratorInternal enumThis = new PermissionSetEnumeratorInternal(this); - - while (enumThis.MoveNext()) - { - permThis = enumThis.Current as CodeAccessPermission; - if(permThis == null || permThis.IsSubsetOf(null)) - continue; // ignore non-CAS permissions in the grant set. - if (deniedSet.m_Unrestricted) - { - firstPermThatFailed = permThis; - return false; - } - permThat = (CodeAccessPermission)deniedSet.GetPermission(enumThis.GetCurrentIndex()); - if (!permThis.CheckDeny(permThat)) - { - firstPermThatFailed = permThis; - return false; - } - } - if(this.m_Unrestricted) - { - PermissionSetEnumeratorInternal enumThat = new PermissionSetEnumeratorInternal(deniedSet); - while (enumThat.MoveNext()) - { - if(enumThat.Current is IPermission) - return false; - } - } - return true; - } - - internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm ) - { - Debug.Assert( demandedPerm != null, "Expected non-null value" ); - - if (this.m_allPermissionsDecoded || this.m_permSet == null) - return; - - if (tokenDemandedPerm == null) - tokenDemandedPerm = PermissionToken.GetToken( demandedPerm ); - - Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" ); - - CheckDecoded( tokenDemandedPerm.m_index ); - } - - internal void CheckDecoded( int index ) - { - if (this.m_allPermissionsDecoded || this.m_permSet == null) - return; - - GetPermission(index); - } - - internal void CheckDecoded(PermissionSet demandedSet) - { - Debug.Assert(demandedSet != null, "Expected non-null value"); - - if (this.m_allPermissionsDecoded || this.m_permSet == null) - return; - - PermissionSetEnumeratorInternal enumerator = demandedSet.GetEnumeratorInternal(); - - while (enumerator.MoveNext()) - { - CheckDecoded(enumerator.GetCurrentIndex()); - } - } - - internal void InplaceIntersect( PermissionSet other ) - { - Exception savedException = null; - - m_CheckedForNonCas = false; - - if (this == other) - return; - - if (other == null || other.FastIsEmpty()) - { - // If the other is empty or null, make this empty. - Reset(); - return; - } - - if (this.FastIsEmpty()) - return; - - int maxMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex(); - int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex(); - - if (this.IsUnrestricted() && maxMax < otherMax) - { - maxMax = otherMax; - this.CheckSet(); - } - - if (other.IsUnrestricted()) - { - other.CheckSet(); - } - - for (int i = 0; i <= maxMax; ++i) - { - Object thisObj = this.m_permSet.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - - Object otherObj = other.m_permSet.GetItem( i ); - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - // There is no object in <this>, so intersection is empty except for IUnrestrictedPermissions - if (this.IsUnrestricted()) - { - { - PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - if ((token.m_type & PermissionTokenType.IUnrestricted) != 0) - { - this.m_permSet.SetItem( i, otherPerm.Copy() ); - Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - } - } - else if (otherObj == null) - { - if (other.IsUnrestricted()) - { - { - PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - if ((token.m_type & PermissionTokenType.IUnrestricted) == 0) - this.m_permSet.SetItem( i, null ); - } - } - else - { - this.m_permSet.SetItem( i, null ); - } - } - else - { - try - { - IPermission intersectPerm; - if (thisPerm == null) - intersectPerm = otherPerm; - else if(otherPerm == null) - intersectPerm = thisPerm; - else - intersectPerm = thisPerm.Intersect( otherPerm ); - this.m_permSet.SetItem( i, intersectPerm ); - } - catch (Exception e) - { - if (savedException == null) - savedException = e; - } - } - } - - this.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted; - - if (savedException != null) - throw savedException; - } - - public PermissionSet Intersect(PermissionSet other) - { - if (other == null || other.FastIsEmpty() || this.FastIsEmpty()) - { - return null; - } - - int thisMax = this.m_permSet == null ? -1 : this.m_permSet.GetMaxUsedIndex(); - int otherMax = other.m_permSet == null ? -1 : other.m_permSet.GetMaxUsedIndex(); - int minMax = thisMax < otherMax ? thisMax : otherMax; - - if (this.IsUnrestricted() && minMax < otherMax) - { - minMax = otherMax; - this.CheckSet(); - } - - if (other.IsUnrestricted() && minMax < thisMax) - { - minMax = thisMax; - other.CheckSet(); - } - - PermissionSet pset = new PermissionSet( false ); - - if (minMax > -1) - { - pset.m_permSet = new TokenBasedSet(); - } - - for (int i = 0; i <= minMax; ++i) - { - Object thisObj = this.m_permSet.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - Object otherObj = other.m_permSet.GetItem( i ); - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - if (this.m_Unrestricted) - { - 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() ); - Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - } - } - else if (otherObj == null) - { - if (other.m_Unrestricted) - { - 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() ); - Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - } - } - else - { - IPermission intersectPerm; - if (thisPerm == null) - intersectPerm = otherPerm; - else if(otherPerm == null) - intersectPerm = thisPerm; - else - intersectPerm = thisPerm.Intersect( otherPerm ); - pset.m_permSet.SetItem( i, intersectPerm ); - Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - - pset.m_Unrestricted = this.m_Unrestricted && other.m_Unrestricted; - if (pset.FastIsEmpty()) - return null; - else - return pset; - } - - internal void InplaceUnion( PermissionSet other ) - { - // Unions the "other" PermissionSet into this one. It can be optimized to do less copies than - // need be done by the traditional union (and we don't have to create a new PermissionSet). - - if (this == other) - return; - - // Quick out conditions, union doesn't change this PermissionSet - if (other == null || other.FastIsEmpty()) - return; - - m_CheckedForNonCas = false; - - this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted; - - if (this.m_Unrestricted) - { - // if the result of Union is unrestricted permset, null the m_permSet member - this.m_permSet = null; - return; - } - - - // If we reach here, result of Union is not unrestricted - // We have to union "normal" permission no matter what now. - int maxMax = -1; - if (other.m_permSet != null) - { - maxMax = other.m_permSet.GetMaxUsedIndex(); - this.CheckSet(); - } - // Save exceptions until the end - Exception savedException = null; - - for (int i = 0; i <= maxMax; ++i) - { - Object thisObj = this.m_permSet.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - - Object otherObj = other.m_permSet.GetItem( i ); - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - if (otherPerm != null) - { - PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i ); - if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !this.m_Unrestricted) - { - this.m_permSet.SetItem( i, otherPerm.Copy() ); - } - } - } - else if (otherObj == null) - { - continue; - } - else - { - try - { - IPermission unionPerm; - if(thisPerm == null) - unionPerm = otherPerm; - else if(otherPerm == null) - unionPerm = thisPerm; - else - unionPerm = thisPerm.Union( otherPerm ); - this.m_permSet.SetItem( i, unionPerm ); - } - catch (Exception e) - { - if (savedException == null) - savedException = e; - } - } - } - - if (savedException != null) - throw savedException; - } - - public PermissionSet Union(PermissionSet other) - { - // if other is null or empty, return a clone of myself - if (other == null || other.FastIsEmpty()) - { - return this.Copy(); - } - - if (this.FastIsEmpty()) - { - return other.Copy(); - } - - int maxMax = -1; - - PermissionSet pset = new PermissionSet(); - pset.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted; - if (pset.m_Unrestricted) - { - // if the result of Union is unrestricted permset, just return - return pset; - } - - // degenerate case where we look at both this.m_permSet and other.m_permSet - this.CheckSet(); - other.CheckSet(); - maxMax = this.m_permSet.GetMaxUsedIndex() > other.m_permSet.GetMaxUsedIndex() ? this.m_permSet.GetMaxUsedIndex() : other.m_permSet.GetMaxUsedIndex(); - pset.m_permSet = new TokenBasedSet(); - - - - for (int i = 0; i <= maxMax; ++i) - { - Object thisObj = this.m_permSet.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - - Object otherObj = other.m_permSet.GetItem( i ); - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - 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() ); - Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - } - else if (otherObj == null) - { - 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() ); - Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - } - else - { - IPermission unionPerm; - if(thisPerm == null) - unionPerm = otherPerm; - else if(otherPerm == null) - unionPerm = thisPerm; - else - unionPerm = thisPerm.Union( otherPerm ); - pset.m_permSet.SetItem( i, unionPerm ); - Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" ); - } - } - - return pset; - } - - // Treating the current permission set as a grant set, and the input set as - // a set of permissions to be denied, try to cancel out as many permissions - // from both sets as possible. For a first cut, any granted permission that - // is a safe subset of the corresponding denied permission can result in - // that permission being removed from both sides. - - internal void MergeDeniedSet(PermissionSet denied) - { - if (denied == null || denied.FastIsEmpty() || this.FastIsEmpty()) - return; - - m_CheckedForNonCas = false; - - // Check for the unrestricted case: FastIsEmpty() will return false if the PSet is unrestricted, but has no items - if (this.m_permSet == null || denied.m_permSet == null) - return; //nothing can be removed - - int maxIndex = denied.m_permSet.GetMaxUsedIndex() > this.m_permSet.GetMaxUsedIndex() ? this.m_permSet.GetMaxUsedIndex() : denied.m_permSet.GetMaxUsedIndex(); - for (int i = 0; i <= maxIndex; ++i) { - IPermission deniedPerm = denied.m_permSet.GetItem(i) as IPermission; - if (deniedPerm == null) - continue; - - IPermission thisPerm = this.m_permSet.GetItem(i) as IPermission; - - if (thisPerm == null && !this.m_Unrestricted) { - denied.m_permSet.SetItem(i, null); - continue; - } - - if (thisPerm != null && deniedPerm != null) { - if (thisPerm.IsSubsetOf(deniedPerm)) { - this.m_permSet.SetItem(i, null); - denied.m_permSet.SetItem(i, null); - } - } - } - } - - // Returns true if perm is contained in this - internal bool Contains(IPermission perm) - { - if (perm == null) - return true; - if (m_Unrestricted) - return true; - if (FastIsEmpty()) - return false; - - PermissionToken token = PermissionToken.GetToken(perm); - Object thisObj = this.m_permSet.GetItem( token.m_index ); - if (thisObj == null) - return perm.IsSubsetOf( null ); - - IPermission thisPerm = GetPermission(token.m_index); - if (thisPerm != null) - return perm.IsSubsetOf( thisPerm ); - else - return perm.IsSubsetOf( null ); - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals( Object obj ) - { - // Note: this method is designed to accept both PermissionSet and NamedPermissionSets. - // It will compare them based on the values in the base type, thereby ignoring the - // name and description of the named permission set. - - PermissionSet other = obj as PermissionSet; - - if (other == null) - return false; - - if (this.m_Unrestricted != other.m_Unrestricted) - return false; - - CheckSet(); - other.CheckSet(); - - DecodeAllPermissions(); - other.DecodeAllPermissions(); - - int maxIndex = Math.Max( this.m_permSet.GetMaxUsedIndex(), other.m_permSet.GetMaxUsedIndex() ); - - for (int i = 0; i <= maxIndex; ++i) - { - IPermission thisPerm = (IPermission)this.m_permSet.GetItem( i ); - IPermission otherPerm = (IPermission)other.m_permSet.GetItem( i ); - - if (thisPerm == null && otherPerm == null) - { - continue; - } - else if (thisPerm == null) - { - if (!otherPerm.IsSubsetOf( null )) - return false; - } - else if (otherPerm == null) - { - if (!thisPerm.IsSubsetOf( null )) - return false; - } - else - { - if (!thisPerm.Equals( otherPerm )) - return false; - } - } - - return true; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - int accumulator; - - accumulator = this.m_Unrestricted ? -1 : 0; - - if (this.m_permSet != null) - { - DecodeAllPermissions(); - - int maxIndex = this.m_permSet.GetMaxUsedIndex(); - - for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i) - { - IPermission perm = (IPermission)this.m_permSet.GetItem( i ); - if (perm != null) - { - accumulator = accumulator ^ perm.GetHashCode(); - } - } - } - - return accumulator; - } - - // 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). - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void Demand() - { - if (this.FastIsEmpty()) - return; // demanding the empty set always passes. - - ContainsNonCodeAccessPermissions(); - - if (m_ContainsCas) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; - CodeAccessSecurityEngine.Check(GetCasOnlySet(), ref stackMark); - } - if (m_ContainsNonCas) - { - DemandNonCAS(); - } - } - - internal void DemandNonCAS() - { - ContainsNonCodeAccessPermissions(); - - if (m_ContainsNonCas) - { - if (this.m_permSet != null) - { - CheckSet(); - for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i) - { - IPermission currPerm = GetPermission(i); - if (currPerm != null && !(currPerm is CodeAccessPermission)) - currPerm.Demand(); - } - } - } - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void Assert() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.Assert(this, ref stackMark); - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [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.")] - public void Deny() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.Deny(this, ref stackMark); - } - - // Metadata for this method should be flaged with REQ_SQ so that - // EE can allocate space on the stack frame for FrameSecurityDescriptor - - [DynamicSecurityMethodAttribute()] - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public void PermitOnly() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.PermitOnly(this, ref stackMark); - } - - internal IPermission GetFirstPerm() - { - IEnumerator enumerator = GetEnumerator(); - if(!enumerator.MoveNext()) - return null; - return enumerator.Current as IPermission; - } - - // Returns a deep copy - public virtual PermissionSet Copy() - { - return new PermissionSet(this); - } - - internal PermissionSet CopyWithNoIdentityPermissions() - { - // 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. - return new PermissionSet(this); - } - - public IEnumerator GetEnumerator() - { - return GetEnumeratorImpl(); - } - - protected virtual IEnumerator GetEnumeratorImpl() - { - return new PermissionSetEnumerator(this); - } - - internal PermissionSetEnumeratorInternal GetEnumeratorInternal() - { - return new PermissionSetEnumeratorInternal(this); - } - - private void NormalizePermissionSet() - { - // This function guarantees that all the permissions are placed at - // the proper index within the token based sets. This becomes necessary - // since these indices are dynamically allocated based on usage order. - - PermissionSet permSetTemp = new PermissionSet(false); - - permSetTemp.m_Unrestricted = this.m_Unrestricted; - - // Move all the normal permissions to the new permission set - - if (this.m_permSet != null) - { - for (int i = m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); ++i) - { - Object obj = this.m_permSet.GetItem(i); - IPermission perm = obj as IPermission; - if (perm != null) - permSetTemp.SetPermission( perm ); - } - } - - this.m_permSet = permSetTemp.m_permSet; - } - - private void DecodeAllPermissions() - { - if (m_permSet == null) - { - m_allPermissionsDecoded = true; - return; - } - - int maxIndex = m_permSet.GetMaxUsedIndex(); - for (int i = 0; i <= maxIndex; ++i) - { - // GetPermission has the side-effect of decoding the permission in the slot - GetPermission(i); - } - - m_allPermissionsDecoded = true; - } - - internal void FilterHostProtectionPermissions(HostProtectionResource fullTrustOnly, HostProtectionResource inaccessible) - { - HostProtectionPermission.protectedResources = fullTrustOnly; - HostProtectionPermission hpp = (HostProtectionPermission)GetPermission(HostProtectionPermission.GetTokenIndex()); - if(hpp == null) - return; - - HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly)); - if (newHpp == null) - { - RemovePermission(HostProtectionPermission.GetTokenIndex()); - } - else if (newHpp.Resources != hpp.Resources) - { - SetPermission(newHpp); - } - } - - // Determines whether the permission set contains any non-code access - // security permissions. - public bool ContainsNonCodeAccessPermissions() - { - if (m_CheckedForNonCas) - return m_ContainsNonCas; - - lock (this) - { - if (m_CheckedForNonCas) - return m_ContainsNonCas; - - m_ContainsCas = false; - m_ContainsNonCas = false; - - if (IsUnrestricted()) - m_ContainsCas = true; - - if (this.m_permSet != null) - { - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - while (enumerator.MoveNext() && (!m_ContainsCas || !m_ContainsNonCas)) - { - IPermission perm = enumerator.Current as IPermission; - - if (perm != null) - { - if (perm is CodeAccessPermission) - m_ContainsCas = true; - else - m_ContainsNonCas = true; - } - } - } - - m_CheckedForNonCas = true; - } - - return m_ContainsNonCas; - } - - // Returns a permission set containing only CAS-permissions. If possible - // this is just the input set, otherwise a new set is allocated. - private PermissionSet GetCasOnlySet() - { - if (!m_ContainsNonCas) - return this; - - if (IsUnrestricted()) - return this; - - PermissionSet pset = new PermissionSet(false); - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this); - - while (enumerator.MoveNext()) - { - IPermission perm = (IPermission)enumerator.Current; - - if (perm is CodeAccessPermission) - pset.AddPermission(perm); - } - - pset.m_CheckedForNonCas = true; - pset.m_ContainsCas = !pset.IsEmpty(); - pset.m_ContainsNonCas = false; - - return pset; - } - - // 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) - { - Debug.Assert(casPset == null || !casPset.IsReadOnly); - Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly); - - if (perm == null) - return; - - if (!separateCasFromNonCas || perm is CodeAccessPermission) - { - if(casPset == null) - casPset = new PermissionSet(false); - IPermission oldPerm = casPset.GetPermission(perm); - IPermission unionPerm = casPset.AddPermission(perm); - if (oldPerm != null && !oldPerm.IsSubsetOf( unionPerm )) - throw new NotSupportedException( Environment.GetResourceString( "NotSupported_DeclarativeUnion" ) ); - } - else - { - if(nonCasPset == null) - nonCasPset = new PermissionSet(false); - IPermission oldPerm = nonCasPset.GetPermission(perm); - IPermission unionPerm = nonCasPset.AddPermission( perm ); - if (oldPerm != null && !oldPerm.IsSubsetOf( unionPerm )) - throw new NotSupportedException( Environment.GetResourceString( "NotSupported_DeclarativeUnion" ) ); - } - } - - // Converts an array of SecurityAttributes to a PermissionSet - private static byte[] CreateSerialized(Object[] attrs, - bool serialize, - ref byte[] nonCasBlob, - out PermissionSet casPset, - HostProtectionResource fullTrustOnlyResources, - bool allowEmptyPermissionSets) - { - // Create two new (empty) sets. - casPset = null; - PermissionSet nonCasPset = null; - - // Most security attributes generate a single permission. The - // PermissionSetAttribute class generates an entire permission set we - // need to merge, however. - for (int i = 0; i < attrs.Length; i++) - { -#pragma warning disable 618 - 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) - { - PermissionSet pset = ((PermissionSetAttribute)attrs[i]).CreatePermissionSet(); - if (pset == null) - throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet" ) ); - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(pset); - - while (enumerator.MoveNext()) - { - IPermission perm = (IPermission)enumerator.Current; - MergePermission(perm, serialize, ref casPset, ref nonCasPset); - } - - if(casPset == null) - casPset = new PermissionSet(false); - if (pset.IsUnrestricted()) - casPset.SetUnrestricted(true); - } - else - { -#pragma warning disable 618 - IPermission perm = ((SecurityAttribute)attrs[i]).CreatePermission(); -#pragma warning restore 618 - MergePermission(perm, serialize, ref casPset, ref nonCasPset); - } - } - 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 - // declarative permission sets being NULL if they do not exist. When filtering the permission - // set if we end up with an empty set, we can the permission set NULL rather than returning the - // empty set in order to enable those optimizations. - // - - if(casPset != null) - { - casPset.FilterHostProtectionPermissions(fullTrustOnlyResources, HostProtectionResource.None); - casPset.ContainsNonCodeAccessPermissions(); // make sure all declarative PermissionSets are checked for non-CAS so we can just check the flag from native code - if (allowEmptyPermissionSets && casPset.IsEmpty()) - casPset = null; - } - if(nonCasPset != null) - { - nonCasPset.FilterHostProtectionPermissions(fullTrustOnlyResources, HostProtectionResource.None); - nonCasPset.ContainsNonCodeAccessPermissions(); // make sure all declarative PermissionSets are checked for non-CAS so we can just check the flag from native code - if (allowEmptyPermissionSets && nonCasPset.IsEmpty()) - nonCasPset = null; - } - - Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR"); - return null; - } - -#if FEATURE_SERIALIZATION - /// <internalonly/> - void IDeserializationCallback.OnDeserialization(Object sender) - { - NormalizePermissionSet(); - m_CheckedForNonCas = false; - } -#endif - - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static void RevertAssert() - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - SecurityRuntime.RevertAssert(ref stackMark); - } - - internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress) - { - Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here"); - PermissionSet retPs = null; - bFailedToCompress = false; - if (assertSet == null) - return null; - if (refusedSet != null) - { - if (refusedSet.IsUnrestricted()) - return null; // we're refusing everything...cannot assert anything now. - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(refusedSet); - while (enumerator.MoveNext()) - { - CodeAccessPermission refusedPerm = (CodeAccessPermission)enumerator.Current; - int i = enumerator.GetCurrentIndex(); - if (refusedPerm != null) - { - CodeAccessPermission perm - = (CodeAccessPermission)assertSet.GetPermission(i); - try - { - if (refusedPerm.Intersect(perm) != null) - { - if (refusedPerm.Equals(perm)) - { - if (retPs == null) - retPs = assertSet.Copy(); - - retPs.RemovePermission(i); - } - else - { - // Asserting a permission, part of which is already denied/refused - // cannot compress this assert - bFailedToCompress = true; - return assertSet; - } - } - } - catch (ArgumentException) - { - // Any exception during removing a refused set from assert set => we play it safe and not assert that perm - if (retPs == null) - retPs = assertSet.Copy(); - retPs.RemovePermission(i); - } - } - } - } - if (retPs != null) - return retPs; - return assertSet; - } - - internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet) - { - Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted"); - alteredDemandSet = null; - - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet); - while (enumerator.MoveNext()) - { - CodeAccessPermission demandDerm = (CodeAccessPermission)enumerator.Current; - int i = enumerator.GetCurrentIndex(); - if (demandDerm != null) - { - CodeAccessPermission assertPerm - = (CodeAccessPermission)assertSet.GetPermission(i); - try - { - if (demandDerm.CheckAssert(assertPerm)) - { - if (alteredDemandSet == null) - alteredDemandSet = demandSet.Copy(); - - alteredDemandSet.RemovePermission(i); - } - } - catch (ArgumentException) - { - } - } - } - return; - } - - internal static bool IsIntersectingAssertedPermissions(PermissionSet assertSet1, PermissionSet assertSet2) - { - bool isIntersecting = false; - if (assertSet1 != null && assertSet2 != null) - { - PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(assertSet2); - while (enumerator.MoveNext()) - { - CodeAccessPermission perm2 = (CodeAccessPermission)enumerator.Current; - int i = enumerator.GetCurrentIndex(); - if (perm2 != null) - { - CodeAccessPermission perm1 - = (CodeAccessPermission)assertSet1.GetPermission(i); - try - { - if (perm1 != null && !perm1.Equals(perm2)) - { - isIntersecting = true; // Same type of permission, but with different flags or something - cannot union them - } - } - catch (ArgumentException) - { - isIntersecting = true; //assume worst case - } - } - } - } - return isIntersecting; - - } - - // This is a workaround so that SQL can operate under default policy without actually - // granting permissions in assemblies that they disallow. - - internal bool IgnoreTypeLoadFailures - { - set { m_ignoreTypeLoadFailures = value; } - } - } -} diff --git a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs b/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs deleted file mode 100644 index 7b234e9cf4..0000000000 --- a/src/mscorlib/src/System/Security/PermissionSetEnumerator.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - //PermissionSetEnumerator.cs - - using System; - using System.Collections; - using TokenBasedSetEnumerator = System.Security.Util.TokenBasedSetEnumerator; - using TokenBasedSet = System.Security.Util.TokenBasedSet; - - internal class PermissionSetEnumerator : IEnumerator - { - PermissionSetEnumeratorInternal enm; - - public Object Current - { - get - { - return enm.Current; - } - } - - public bool MoveNext() - { - return enm.MoveNext(); - } - - public void Reset() - { - enm.Reset(); - } - - internal PermissionSetEnumerator(PermissionSet permSet) - { - enm = new PermissionSetEnumeratorInternal(permSet); - } - } - - internal struct PermissionSetEnumeratorInternal - { - private PermissionSet m_permSet; - private TokenBasedSetEnumerator enm; - - public Object Current - { - get - { - return enm.Current; - } - } - - internal PermissionSetEnumeratorInternal(PermissionSet permSet) - { - m_permSet = permSet; - enm = new TokenBasedSetEnumerator(permSet.m_permSet); - } - - public int GetCurrentIndex() - { - return enm.Index; - } - - public void Reset() - { - enm.Reset(); - } - - public bool MoveNext() - { - while (enm.MoveNext()) - { - Object obj = enm.Current; - IPermission perm = obj as IPermission; - if (perm != null) - { - enm.Current = perm; - return true; - } - } - return false; - } - } -} - diff --git a/src/mscorlib/src/System/Security/PermissionSetTriple.cs b/src/mscorlib/src/System/Security/PermissionSetTriple.cs deleted file mode 100644 index 56eb22996e..0000000000 --- a/src/mscorlib/src/System/Security/PermissionSetTriple.cs +++ /dev/null @@ -1,270 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** -** Purpose: Container class for holding an AppDomain's Grantset and Refused sets. -** Also used for CompressedStacks which brings in the third PermissionSet. -** Hence, the name PermissionSetTriple. -** -=============================================================================*/ - -namespace System.Security -{ - using IEnumerator = System.Collections.IEnumerator; - using System.Security; - using System.Security.Permissions; - using System.Runtime.InteropServices; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - - [Serializable] - sealed internal class PermissionSetTriple - { - static private volatile PermissionToken s_zoneToken; - static private volatile PermissionToken s_urlToken; - internal PermissionSet AssertSet; - internal PermissionSet GrantSet; - internal PermissionSet RefusedSet; - internal PermissionSetTriple() - { - Reset(); - } - internal PermissionSetTriple(PermissionSetTriple triple) - { - this.AssertSet = triple.AssertSet; - this.GrantSet = triple.GrantSet; - this.RefusedSet = triple.RefusedSet; - } - internal void Reset() - { - AssertSet = null; - GrantSet = null; - RefusedSet = null; - } - internal bool IsEmpty() - { - return (AssertSet == null && GrantSet == null && RefusedSet == null); - } - - private PermissionToken ZoneToken - { - get - { - if (s_zoneToken == null) - s_zoneToken = PermissionToken.GetToken(typeof(ZoneIdentityPermission)); - return s_zoneToken; - } - } - private PermissionToken UrlToken - { - get - { - if (s_urlToken == null) - s_urlToken = PermissionToken.GetToken(typeof(UrlIdentityPermission)); - return s_urlToken; - } - } - internal bool Update(PermissionSetTriple psTriple, out PermissionSetTriple retTriple) - { - retTriple = null; - retTriple = UpdateAssert(psTriple.AssertSet); - // Special case: unrestricted assert. Note: dcs.Assert.IsUnrestricted => dcs.Grant.IsUnrestricted - if (psTriple.AssertSet != null && psTriple.AssertSet.IsUnrestricted()) - { - return true; // stop construction - } - UpdateGrant(psTriple.GrantSet); - UpdateRefused(psTriple.RefusedSet); - return false; - } - - internal PermissionSetTriple UpdateAssert(PermissionSet in_a) - { - PermissionSetTriple retTriple = null; - if (in_a != 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; - - PermissionSet retPs; - if (GrantSet != null) - retPs = in_a.Intersect(GrantSet); // Restrict the assert to what we've already been granted - else - { - GrantSet = new PermissionSet(true); - retPs = in_a.Copy(); // Currently unrestricted Grant: assert the whole assert set - } - bool bFailedToCompress = false; - // removes anything that is already in the refused set from the assert set - if (RefusedSet != null) - { - retPs = PermissionSet.RemoveRefusedPermissionSet(retPs, RefusedSet, out bFailedToCompress); - } - if (!bFailedToCompress) - bFailedToCompress = PermissionSet.IsIntersectingAssertedPermissions(retPs, AssertSet); - if (bFailedToCompress) - { - retTriple = new PermissionSetTriple(this); - this.Reset(); - this.GrantSet = retTriple.GrantSet.Copy(); - } - - if (AssertSet == null) - AssertSet = retPs; - else - AssertSet.InplaceUnion(retPs); - - } - return retTriple; - } - internal void UpdateGrant(PermissionSet in_g, out ZoneIdentityPermission z,out UrlIdentityPermission u) - { - z = null; - u = null; - if (in_g != null) - { - if (GrantSet == null) - GrantSet = in_g.Copy(); - else - GrantSet.InplaceIntersect(in_g); - - z = (ZoneIdentityPermission)in_g.GetPermission(ZoneToken); - u = (UrlIdentityPermission)in_g.GetPermission(UrlToken); - } - } - - internal void UpdateGrant(PermissionSet in_g) - { - if (in_g != null) - { - if (GrantSet == null) - GrantSet = in_g.Copy(); - else - GrantSet.InplaceIntersect(in_g); - } - } - internal void UpdateRefused(PermissionSet in_r) - { - if (in_r != null) - { - if (RefusedSet == null) - RefusedSet = in_r.Copy(); - else - RefusedSet.InplaceUnion(in_r); - } - } - - - static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken) - { - if (pSet != null) - { - pSet.CheckDecoded(demand, permToken); - - CodeAccessPermission perm = (CodeAccessPermission)pSet.GetPermission(demand); - - // If the assert set does contain the demanded permission, halt the stackwalk - - try - { - if (pSet.IsUnrestricted() || demand.CheckAssert(perm)) - { - return SecurityRuntime.StackHalt; - } - } - catch (ArgumentException) - { - } - } - return SecurityRuntime.StackContinue; - } - - static bool CheckAssert(PermissionSet assertPset, PermissionSet demandSet, out PermissionSet newDemandSet) - { - newDemandSet = null; - if (assertPset!= null) - { - assertPset.CheckDecoded(demandSet); - // If this frame asserts a superset of the demand set we're done - - if (demandSet.CheckAssertion(assertPset)) - return SecurityRuntime.StackHalt; - PermissionSet.RemoveAssertedPermissionSet(demandSet, assertPset, out newDemandSet); - } - return SecurityRuntime.StackContinue; - } - - - internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) - { - if (CheckAssert(AssertSet, demand, permToken) == SecurityRuntime.StackHalt) - return SecurityRuntime.StackHalt; - -#pragma warning disable 618 - CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, rmh, null, SecurityAction.Demand, true); -#pragma warning restore 618 - - return SecurityRuntime.StackContinue; - } - internal bool CheckSetDemand(PermissionSet demandSet , out PermissionSet alteredDemandset, RuntimeMethodHandleInternal rmh) - { - alteredDemandset = null; - - if (CheckAssert(AssertSet, demandSet, out alteredDemandset) == SecurityRuntime.StackHalt) - return SecurityRuntime.StackHalt; - if (alteredDemandset != null) - demandSet = alteredDemandset; // note that this does not modify demandSet external to this function. -#pragma warning disable 618 - CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, rmh, null, SecurityAction.Demand, true); -#pragma warning restore 618 - - return SecurityRuntime.StackContinue; - - } - - internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken) - { - 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 - } - internal bool CheckSetDemandNoThrow(PermissionSet demandSet) - { - Debug.Assert(AssertSet == null, "AssertSet not null"); - -#pragma warning disable 618 - return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false); -#pragma warning restore 618 - } - /// <summary> - /// Check to see if the triple satisfies a demand for the permission represented by the flag. - /// </summary> - /// <remarks> - /// If the triple asserts for one of the bits in the flags, it is zeroed out. - /// </remarks> - /// <param name="flags">set of flags to check (See PermissionType)</param> - internal bool CheckFlags(ref int flags) - { - if (AssertSet != null) - { - // remove any permissions which were asserted for - int assertFlags = SecurityManager.GetSpecialFlags(AssertSet, null); - if ((flags & assertFlags) != 0) - flags = flags & ~assertFlags; - } - - return (SecurityManager.GetSpecialFlags(GrantSet, RefusedSet) & flags) == flags; - } - } -} - - diff --git a/src/mscorlib/src/System/Security/PermissionToken.cs b/src/mscorlib/src/System/Security/PermissionToken.cs deleted file mode 100644 index 5c6a322c1c..0000000000 --- a/src/mscorlib/src/System/Security/PermissionToken.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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; - using System.Security.Util; - using System.Security.Permissions; - using System.Reflection; - using System.Collections; - using System.Threading; - using System.Globalization; - using System.Runtime.CompilerServices; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Flags] - internal enum PermissionTokenType - { - Normal = 0x1, - IUnrestricted = 0x2, - DontKnow = 0x4, - BuiltIn = 0x8 - } - - [Serializable] - internal sealed class PermissionTokenKeyComparer : IEqualityComparer - { - private Comparer _caseSensitiveComparer; - private TextInfo _info; - - public PermissionTokenKeyComparer() - { - _caseSensitiveComparer = new Comparer(CultureInfo.InvariantCulture); - _info = CultureInfo.InvariantCulture.TextInfo; - } - - public int Compare(Object a, Object b) - { - String strA = a as String; - String strB = b as String; - - // if it's not a string then we just call the object comparer - if (strA == null || strB == null) - return _caseSensitiveComparer.Compare(a, b); - - int i = _caseSensitiveComparer.Compare(a,b); - if (i == 0) - return 0; - - if (SecurityManager.IsSameType(strA, strB)) - return 0; - - return i; - } - - public new bool Equals( Object a, Object b ) - { - if (a == b) return true; - if (a == null || b == null) return false; - return Compare( a, b ) == 0; - } - - // 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(nameof(obj)); - Contract.EndContractBlock(); - - String str = obj as String; - - if (str == null) - return obj.GetHashCode(); - - int iComma = str.IndexOf( ',' ); - if (iComma == -1) - iComma = str.Length; - - int accumulator = 0; - for (int i = 0; i < iComma; ++i) - { - accumulator = (accumulator << 7) ^ str[i] ^ (accumulator >> 25); - } - - return accumulator; - } - } - - [Serializable] - internal sealed class PermissionToken : ISecurityEncodable - { - private static readonly PermissionTokenFactory s_theTokenFactory; - private const string c_mscorlibName = System.CoreLib.Name; - internal int m_index; - internal volatile PermissionTokenType m_type; - static internal TokenBasedSet s_tokenSet = new TokenBasedSet(); - - internal static bool IsMscorlibClassName (string className) { - 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 - // an mscorlib.dll type so we should return true so the type can be matched with the - // right index in the TokenBasedSet. - int index = className.IndexOf(','); - if (index == -1) - return true; - - index = className.LastIndexOf(']'); - if (index == -1) - index = 0; - - // 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 (className[i] == 's' || className[i] == 'S') - { - if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0) - return true; - } - } - return false; - } - - static PermissionToken() - { - s_theTokenFactory = new PermissionTokenFactory( 4 ); - } - - internal PermissionToken() - { - } - - internal PermissionToken(int index, PermissionTokenType type, String strTypeName) - { - m_index = index; - m_type = type; - } - - public static PermissionToken GetToken(Type cls) - { - if (cls == null) - return null; - - return s_theTokenFactory.GetToken(cls, null); - } - - public static PermissionToken GetToken(IPermission perm) - { - if (perm == null) - return null; - - IBuiltInPermission ibPerm = perm as IBuiltInPermission; - - if (ibPerm != null) - return s_theTokenFactory.BuiltInGetToken( ibPerm.GetTokenIndex(), perm, null ); - else - return s_theTokenFactory.GetToken(perm.GetType(), perm); - } - - public static PermissionToken FindTokenByIndex( int i ) - { - return s_theTokenFactory.FindTokenByIndex( i ); - } - - public static bool IsTokenProperlyAssigned( IPermission perm, PermissionToken token ) - { - PermissionToken heldToken = GetToken( perm ); - if (heldToken.m_index != token.m_index) - return false; - - if (token.m_type != heldToken.m_type) - return false; - - if (perm.GetType().Module.Assembly == Assembly.GetExecutingAssembly() && - heldToken.m_index >= BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED) - return false; - - return true; - } - } - - // Package access only - internal class PermissionTokenFactory - { - private volatile int m_size; - private volatile int m_index; - private volatile Hashtable m_tokenTable; // Cache of tokens by class string name - private volatile Hashtable m_handleTable; // Cache of tokens by type handle (IntPtr) - private volatile Hashtable m_indexTable; // Cache of tokens by index - - - // We keep an array of tokens for our built-in permissions. - // This is ordered in terms of unrestricted perms first, normals - // second. Of course, all the ordering is based on the individual - // permissions sticking to the deal, so we do some simple boundary - // checking but mainly leave it to faith. - - private volatile PermissionToken[] m_builtIn; - - private const String s_unrestrictedPermissionInferfaceName = "System.Security.Permissions.IUnrestrictedPermission"; - - internal PermissionTokenFactory( int size ) - { - m_builtIn = new PermissionToken[BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED]; - - m_size = size; - m_index = BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED; - m_tokenTable = null; - m_handleTable = new Hashtable(size); - m_indexTable = new Hashtable(size); - } - - internal PermissionToken FindTokenByIndex( int i ) - { - PermissionToken token; - - if (i < BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED) - { - token = BuiltInGetToken( i, null, null ); - } - else - { - token = (PermissionToken)m_indexTable[i]; - } - - return token; - } - - internal PermissionToken GetToken(Type cls, IPermission perm) - { - Debug.Assert( cls != null, "Must pass in valid type" ); - - IntPtr typePtr = cls.TypeHandle.Value; - object tok = m_handleTable[typePtr]; - if (tok == null) - { - String typeStr = cls.AssemblyQualifiedName; - tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe - - if (tok == null) - { - lock (this) - { - if (m_tokenTable != null) - { - tok = m_tokenTable[typeStr]; // Make sure it wasn't just added - } - else - m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer()); - - if (tok == null) - { - if (perm != null) - { - tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr ); - } - else - { - if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null) - tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr ); - else - tok = new PermissionToken( m_index++, PermissionTokenType.Normal, typeStr ); - } - m_tokenTable.Add(typeStr, tok); - m_indexTable.Add(m_index - 1, tok); - PermissionToken.s_tokenSet.SetItem( ((PermissionToken)tok).m_index, tok ); - } - - if (!m_handleTable.Contains(typePtr)) - m_handleTable.Add( typePtr, tok ); - } - } - else - { - lock (this) - { - if (!m_handleTable.Contains(typePtr)) - m_handleTable.Add( typePtr, tok ); - } - } - } - - if ((((PermissionToken)tok).m_type & PermissionTokenType.DontKnow) != 0) - { - if (perm != null) - { - Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" ); - ((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted; - } - else - { - 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; - } - } - - return (PermissionToken)tok; - } - - internal PermissionToken GetToken(String typeStr) - { - Object tok = null; - tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe - if (tok == null) - { - lock (this) - { - if (m_tokenTable != null) - { - tok = m_tokenTable[typeStr]; // Make sure it wasn't just added - } - else - m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer()); - - if (tok == null) - { - tok = new PermissionToken( m_index++, PermissionTokenType.DontKnow, typeStr ); - m_tokenTable.Add(typeStr, tok); - m_indexTable.Add(m_index - 1, tok); - PermissionToken.s_tokenSet.SetItem(((PermissionToken)tok).m_index, tok); - } - } - } - - return (PermissionToken)tok; - } - - internal PermissionToken BuiltInGetToken( int index, IPermission perm, Type cls ) - { - PermissionToken token = Volatile.Read(ref m_builtIn[index]); - - if (token == null) - { - lock (this) - { - token = m_builtIn[index]; - - if (token == null) - { - PermissionTokenType permType = PermissionTokenType.DontKnow; - - if (perm != null) - { - permType = PermissionTokenType.IUnrestricted; - } - else if (cls != null) - { - permType = PermissionTokenType.IUnrestricted; - } - - token = new PermissionToken( index, permType | PermissionTokenType.BuiltIn, null ); - Volatile.Write(ref m_builtIn[index], token); - PermissionToken.s_tokenSet.SetItem( token.m_index, token ); - } - } - } - - if ((token.m_type & PermissionTokenType.DontKnow) != 0) - { - token.m_type = PermissionTokenType.BuiltIn; - - if (perm != null) - { - token.m_type |= PermissionTokenType.IUnrestricted; - } - else if (cls != null) - { - token.m_type |= PermissionTokenType.IUnrestricted; - } - else - { - token.m_type |= PermissionTokenType.DontKnow; - } - } - - return token; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs b/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs deleted file mode 100644 index 567fe513c0..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/EnvironmentPermission.cs +++ /dev/null @@ -1,347 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - using System.Security; - using System; - using SecurityElement = System.Security.SecurityElement; - using System.Security.Util; - using System.IO; - using System.Globalization; - using System.Diagnostics.Contracts; - - [Serializable] - [Flags] - [System.Runtime.InteropServices.ComVisible(true)] - public enum EnvironmentPermissionAccess - { - NoAccess = 0x00, - Read = 0x01, - Write = 0x02, - AllAccess = 0x03, - } - - [Serializable] - internal class EnvironmentStringExpressionSet : StringExpressionSet - { - public EnvironmentStringExpressionSet() - : base( true, null, false ) - { - } - - public EnvironmentStringExpressionSet( String str ) - : base( true, str, false ) - { - } - - protected override StringExpressionSet CreateNewEmpty() - { - return new EnvironmentStringExpressionSet(); - } - - protected override bool StringSubsetString( String left, String right, bool ignoreCase ) - { - return (ignoreCase?(String.Compare( left, right, StringComparison.OrdinalIgnoreCase) == 0): - (String.Compare( left, right, StringComparison.Ordinal) == 0)); - } - - protected override String ProcessWholeString( String str ) - { - return str; - } - - protected override String ProcessSingleString( String str ) - { - return str; - } - - public override string ToString() - { - // SafeCritical: we're not storing path information in the strings, so exposing them out is fine ... - // they're just the same strings that came in to the .ctor. - return base.UnsafeToString(); - } - } - -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class EnvironmentPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - private StringExpressionSet m_read; - private StringExpressionSet m_write; - private bool m_unrestricted; - - public EnvironmentPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - m_unrestricted = true; - else if (state == PermissionState.None) - m_unrestricted = false; - else - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - - public EnvironmentPermission( EnvironmentPermissionAccess flag, String pathList ) - { - SetPathList( flag, pathList ); - } - - public void SetPathList( EnvironmentPermissionAccess flag, String pathList ) - { - VerifyFlag( flag ); - - m_unrestricted = false; - - if ((flag & EnvironmentPermissionAccess.Read) != 0) - m_read = null; - - if ((flag & EnvironmentPermissionAccess.Write) != 0) - m_write = null; - - AddPathList( flag, pathList ); - } - - public void AddPathList( EnvironmentPermissionAccess flag, String pathList ) - { - VerifyFlag( flag ); - - if (FlagIsSet( flag, EnvironmentPermissionAccess.Read )) - { - if (m_read == null) - m_read = new EnvironmentStringExpressionSet(); - m_read.AddExpressions( pathList ); - } - - if (FlagIsSet( flag, EnvironmentPermissionAccess.Write )) - { - if (m_write == null) - m_write = new EnvironmentStringExpressionSet(); - m_write.AddExpressions( pathList ); - } - - } - - public String GetPathList( EnvironmentPermissionAccess flag ) - { - VerifyFlag( flag ); - ExclusiveFlag( flag ); - - if (FlagIsSet( flag, EnvironmentPermissionAccess.Read )) - { - if (m_read == null) - { - return ""; - } - return m_read.ToString(); - } - - if (FlagIsSet( flag, EnvironmentPermissionAccess.Write )) - { - if (m_write == null) - { - return ""; - } - return m_write.ToString(); - } - - /* not reached */ - - return ""; - } - - - private void VerifyFlag( EnvironmentPermissionAccess flag ) - { - if ((flag & ~EnvironmentPermissionAccess.AllAccess) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag)); - Contract.EndContractBlock(); - } - - private void ExclusiveFlag( EnvironmentPermissionAccess flag ) - { - if (flag == EnvironmentPermissionAccess.NoAccess) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - - if (((int)flag & ((int)flag-1)) != 0) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - Contract.EndContractBlock(); - } - - - private bool FlagIsSet( EnvironmentPermissionAccess flag, EnvironmentPermissionAccess question ) - { - return (flag & question) != 0; - } - - private bool IsEmpty() - { - return (!m_unrestricted && - (this.m_read == null || this.m_read.IsEmpty()) && - (this.m_write == null || this.m_write.IsEmpty())); - } - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public bool IsUnrestricted() - { - return m_unrestricted; - } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return this.IsEmpty(); - } - - try - { - EnvironmentPermission operand = (EnvironmentPermission)target; - if (operand.IsUnrestricted()) - return true; - else if (this.IsUnrestricted()) - return false; - else - return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) && - (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write ))); - } - catch (InvalidCastException) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - { - return null; - } - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - else if (this.IsUnrestricted()) - { - return target.Copy(); - } - - EnvironmentPermission operand = (EnvironmentPermission)target; - - if (operand.IsUnrestricted()) - { - return this.Copy(); - } - - StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read ); - StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write ); - - if ((intersectRead == null || intersectRead.IsEmpty()) && - (intersectWrite == null || intersectWrite.IsEmpty())) - { - return null; - } - - EnvironmentPermission intersectPermission = new EnvironmentPermission(PermissionState.None); - intersectPermission.m_unrestricted = false; - intersectPermission.m_read = intersectRead; - intersectPermission.m_write = intersectWrite; - - return intersectPermission; - } - - public override IPermission Union(IPermission other) - { - if (other == null) - { - return this.Copy(); - } - else if (!VerifyType(other)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - EnvironmentPermission operand = (EnvironmentPermission)other; - - if (this.IsUnrestricted() || operand.IsUnrestricted()) - { - return new EnvironmentPermission( PermissionState.Unrestricted ); - } - - StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read ); - StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write ); - - if ((unionRead == null || unionRead.IsEmpty()) && - (unionWrite == null || unionWrite.IsEmpty())) - { - return null; - } - - EnvironmentPermission unionPermission = new EnvironmentPermission(PermissionState.None); - unionPermission.m_unrestricted = false; - unionPermission.m_read = unionRead; - unionPermission.m_write = unionWrite; - - return unionPermission; - } - - public override IPermission Copy() - { - EnvironmentPermission copy = new EnvironmentPermission(PermissionState.None); - if (this.m_unrestricted) - { - copy.m_unrestricted = true; - } - else - { - copy.m_unrestricted = false; - if (this.m_read != null) - { - copy.m_read = this.m_read.Copy(); - } - if (this.m_write != null) - { - copy.m_write = this.m_write.Copy(); - } - - } - return copy; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return EnvironmentPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.EnvironmentPermissionIndex; - } - } - -} diff --git a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs deleted file mode 100644 index 98a7d54c68..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/FileDialogPermission.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - using System; - using System.Text; - using System.Security; - using System.Security.Util; - using System.IO; - using System.Runtime.Serialization; - using System.Reflection; - using System.Collections; - using System.Globalization; - using System.Diagnostics.Contracts; - -[Serializable] -[Flags] -[System.Runtime.InteropServices.ComVisible(true)] - public enum FileDialogPermissionAccess { - None = 0x00, - - Open = 0x01, - - Save = 0x02, - - OpenSave = Open | Save - - } - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public sealed class FileDialogPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { - FileDialogPermissionAccess access; - - public FileDialogPermission(PermissionState state) { - if (state == PermissionState.Unrestricted) { - SetUnrestricted(true); - } - else if (state == PermissionState.None) { - SetUnrestricted(false); - Reset(); - } - else { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public FileDialogPermission(FileDialogPermissionAccess access) { - VerifyAccess(access); - this.access = access; - } - - public FileDialogPermissionAccess Access { - get { - return access; - } - - set { - VerifyAccess(value); - access = value; - } - } - - public override IPermission Copy() { - return new FileDialogPermission(this.access); - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() { - return FileDialogPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() { - return BuiltInPermissionIndex.FileDialogPermissionIndex; - } - - public override IPermission Intersect(IPermission target) { - if (target == null) { - return null; - } - else if (!VerifyType(target)) { - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - } - - FileDialogPermission operand = (FileDialogPermission)target; - - FileDialogPermissionAccess intersectAccess = access & operand.Access; - - if (intersectAccess == FileDialogPermissionAccess.None) - return null; - else - return new FileDialogPermission(intersectAccess); - } - - public override bool IsSubsetOf(IPermission target) { - if (target == null) { - // Only safe subset if this is empty - return access == FileDialogPermissionAccess.None; - } - - try { - FileDialogPermission operand = (FileDialogPermission)target; - if (operand.IsUnrestricted()) { - return true; - } - else if (this.IsUnrestricted()) { - return false; - } - else { - int open = (int)(access & FileDialogPermissionAccess.Open); - int save = (int)(access & FileDialogPermissionAccess.Save); - int openTarget = (int)(operand.Access & FileDialogPermissionAccess.Open); - int saveTarget = (int)(operand.Access & FileDialogPermissionAccess.Save); - - return open <= openTarget && save <= saveTarget; - } - } - catch (InvalidCastException) { - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - } - - } - - public bool IsUnrestricted() { - return access == FileDialogPermissionAccess.OpenSave; - } - - void Reset() { - access = FileDialogPermissionAccess.None; - } - - void SetUnrestricted( bool unrestricted ) { - if (unrestricted) { - access = FileDialogPermissionAccess.OpenSave; - } - } - - public override IPermission Union(IPermission target) { - if (target == null) { - return this.Copy(); - } - else if (!VerifyType(target)) { - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - } - - FileDialogPermission operand = (FileDialogPermission)target; - return new FileDialogPermission(access | operand.Access); - } - - static void VerifyAccess(FileDialogPermissionAccess access) { - if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) { - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access)); - } - Contract.EndContractBlock(); - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs b/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs deleted file mode 100644 index 34b9f1ef80..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/FileIOPermission.cs +++ /dev/null @@ -1,1216 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Security.AccessControl; - using System.Security.Util; - using System.IO; - using System.Collections; - using System.Globalization; - using System.Runtime.Serialization; - using System.Runtime.Versioning; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - [Flags] - [System.Runtime.InteropServices.ComVisible(true)] - public enum FileIOPermissionAccess - { - NoAccess = 0x00, - Read = 0x01, - Write = 0x02, - Append = 0x04, - PathDiscovery = 0x08, - AllAccess = 0x0F, - } - - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - private FileIOAccess m_read; - private FileIOAccess m_write; - private FileIOAccess m_append; - private FileIOAccess m_pathDiscovery; - [OptionalField(VersionAdded = 2)] - private FileIOAccess m_viewAcl; - [OptionalField(VersionAdded = 2)] - private FileIOAccess m_changeAcl; - private bool m_unrestricted; - - public FileIOPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_unrestricted = true; - } - else if (state == PermissionState.None) - { - m_unrestricted = false; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public FileIOPermission( FileIOPermissionAccess access, String path ) - { - VerifyAccess( access ); - - String[] pathList = new String[] { path }; - AddPathList( access, pathList, false, true, false ); - } - - public FileIOPermission( FileIOPermissionAccess access, String[] pathList ) - { - VerifyAccess( access ); - - AddPathList( access, pathList, false, true, false ); - } - - internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath ) - { - VerifyAccess( access ); - - AddPathList( access, pathList, checkForDuplicates, needFullPath, true ); - } - - public void SetPathList( FileIOPermissionAccess access, String path ) - { - String[] pathList; - if(path == null) - pathList = new String[] {}; - else - pathList = new String[] { path }; - SetPathList( access, pathList, false ); - } - - public void SetPathList( FileIOPermissionAccess access, String[] pathList ) - { - SetPathList( access, pathList, true ); - } - - internal void SetPathList( FileIOPermissionAccess access, - String[] pathList, bool checkForDuplicates ) - { - SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates ); - } - - internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates ) - { - VerifyAccess( access ); - - if ((access & FileIOPermissionAccess.Read) != 0) - m_read = null; - - if ((access & FileIOPermissionAccess.Write) != 0) - m_write = null; - - if ((access & FileIOPermissionAccess.Append) != 0) - m_append = null; - - if ((access & FileIOPermissionAccess.PathDiscovery) != 0) - m_pathDiscovery = null; - - m_viewAcl = null; - m_changeAcl = null; - m_unrestricted = false; - - AddPathList( access, pathList, checkForDuplicates, true, true ); - } - - public void AddPathList( FileIOPermissionAccess access, String path ) - { - String[] pathList; - if(path == null) - pathList = new String[] {}; - else - pathList = new String[] { path }; - AddPathList( access, pathList, false, true, false ); - } - - public void AddPathList( FileIOPermissionAccess access, String[] pathList ) - { - AddPathList( access, pathList, true, true, true ); - } - - internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList ) - { - AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList ); - } - - internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList) - { - if (pathListOrig == null) - { - throw new ArgumentNullException( "pathList" ); - } - if (pathListOrig.Length == 0) - { - throw new ArgumentException( Environment.GetResourceString("Argument_EmptyPath" )); - } - Contract.EndContractBlock(); - - VerifyAccess(access); - - if (m_unrestricted) - return; - - String[] pathList = pathListOrig; - if(copyPathList) - { - // Make a copy of pathList (in case its value changes after we check for illegal chars) - pathList = new String[pathListOrig.Length]; - Array.Copy(pathListOrig, pathList, pathListOrig.Length); - } - - ArrayList pathArrayList = StringExpressionSet.CreateListFromExpressions(pathList, needFullPath); - - // If we need the full path the standard illegal characters will be checked in StringExpressionSet. - CheckIllegalCharacters(pathList, onlyCheckExtras: needFullPath); - - // StringExpressionSet will do minor normalization, trimming spaces and replacing alternate - // directory separators. It will make an attemt to expand short file names and will check - // for standard colon placement. - // - // If needFullPath is true it will call NormalizePath- which performs short name expansion - // and does the normal validity checks. - - if ((access & FileIOPermissionAccess.Read) != 0) - { - if (m_read == null) - { - m_read = new FileIOAccess(); - } - m_read.AddExpressions( pathArrayList, checkForDuplicates); - } - - if ((access & FileIOPermissionAccess.Write) != 0) - { - if (m_write == null) - { - m_write = new FileIOAccess(); - } - m_write.AddExpressions( pathArrayList, checkForDuplicates); - } - - if ((access & FileIOPermissionAccess.Append) != 0) - { - if (m_append == null) - { - m_append = new FileIOAccess(); - } - m_append.AddExpressions( pathArrayList, checkForDuplicates); - } - - if ((access & FileIOPermissionAccess.PathDiscovery) != 0) - { - if (m_pathDiscovery == null) - { - m_pathDiscovery = new FileIOAccess( true ); - } - m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates); - } - } - - public String[] GetPathList( FileIOPermissionAccess access ) - { - VerifyAccess( access ); - ExclusiveAccess( access ); - - if (AccessIsSet( access, FileIOPermissionAccess.Read )) - { - if (m_read == null) - { - return null; - } - return m_read.ToStringArray(); - } - - if (AccessIsSet( access, FileIOPermissionAccess.Write )) - { - if (m_write == null) - { - return null; - } - return m_write.ToStringArray(); - } - - if (AccessIsSet( access, FileIOPermissionAccess.Append )) - { - if (m_append == null) - { - return null; - } - return m_append.ToStringArray(); - } - - if (AccessIsSet( access, FileIOPermissionAccess.PathDiscovery )) - { - if (m_pathDiscovery == null) - { - return null; - } - return m_pathDiscovery.ToStringArray(); - } - - // not reached - - return null; - } - - public FileIOPermissionAccess AllLocalFiles - { - get - { - if (m_unrestricted) - return FileIOPermissionAccess.AllAccess; - - FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess; - - if (m_read != null && m_read.AllLocalFiles) - { - access |= FileIOPermissionAccess.Read; - } - - if (m_write != null && m_write.AllLocalFiles) - { - access |= FileIOPermissionAccess.Write; - } - - if (m_append != null && m_append.AllLocalFiles) - { - access |= FileIOPermissionAccess.Append; - } - - if (m_pathDiscovery != null && m_pathDiscovery.AllLocalFiles) - { - access |= FileIOPermissionAccess.PathDiscovery; - } - - return access; - } - - set - { - if ((value & FileIOPermissionAccess.Read) != 0) - { - if (m_read == null) - m_read = new FileIOAccess(); - - m_read.AllLocalFiles = true; - } - else - { - if (m_read != null) - m_read.AllLocalFiles = false; - } - - if ((value & FileIOPermissionAccess.Write) != 0) - { - if (m_write == null) - m_write = new FileIOAccess(); - - m_write.AllLocalFiles = true; - } - else - { - if (m_write != null) - m_write.AllLocalFiles = false; - } - - if ((value & FileIOPermissionAccess.Append) != 0) - { - if (m_append == null) - m_append = new FileIOAccess(); - - m_append.AllLocalFiles = true; - } - else - { - if (m_append != null) - m_append.AllLocalFiles = false; - } - - if ((value & FileIOPermissionAccess.PathDiscovery) != 0) - { - if (m_pathDiscovery == null) - m_pathDiscovery = new FileIOAccess( true ); - - m_pathDiscovery.AllLocalFiles = true; - } - else - { - if (m_pathDiscovery != null) - m_pathDiscovery.AllLocalFiles = false; - } - - } - } - - public FileIOPermissionAccess AllFiles - { - get - { - if (m_unrestricted) - return FileIOPermissionAccess.AllAccess; - - FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess; - - if (m_read != null && m_read.AllFiles) - { - access |= FileIOPermissionAccess.Read; - } - - if (m_write != null && m_write.AllFiles) - { - access |= FileIOPermissionAccess.Write; - } - - if (m_append != null && m_append.AllFiles) - { - access |= FileIOPermissionAccess.Append; - } - - if (m_pathDiscovery != null && m_pathDiscovery.AllFiles) - { - access |= FileIOPermissionAccess.PathDiscovery; - } - - return access; - } - - set - { - if (value == FileIOPermissionAccess.AllAccess) - { - m_unrestricted = true; - return; - } - - if ((value & FileIOPermissionAccess.Read) != 0) - { - if (m_read == null) - m_read = new FileIOAccess(); - - m_read.AllFiles = true; - } - else - { - if (m_read != null) - m_read.AllFiles = false; - } - - if ((value & FileIOPermissionAccess.Write) != 0) - { - if (m_write == null) - m_write = new FileIOAccess(); - - m_write.AllFiles = true; - } - else - { - if (m_write != null) - m_write.AllFiles = false; - } - - if ((value & FileIOPermissionAccess.Append) != 0) - { - if (m_append == null) - m_append = new FileIOAccess(); - - m_append.AllFiles = true; - } - else - { - if (m_append != null) - m_append.AllFiles = false; - } - - if ((value & FileIOPermissionAccess.PathDiscovery) != 0) - { - if (m_pathDiscovery == null) - m_pathDiscovery = new FileIOAccess( true ); - - m_pathDiscovery.AllFiles = true; - } - else - { - if (m_pathDiscovery != null) - m_pathDiscovery.AllFiles = false; - } - - } - } - - [Pure] - private static void VerifyAccess( FileIOPermissionAccess access ) - { - if ((access & ~FileIOPermissionAccess.AllAccess) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access)); - } - - [Pure] - private static void ExclusiveAccess( FileIOPermissionAccess access ) - { - if (access == FileIOPermissionAccess.NoAccess) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - - if (((int) access & ((int)access-1)) != 0) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - } - - private static void CheckIllegalCharacters(String[] str, bool onlyCheckExtras) - { -#if !PLATFORM_UNIX - for (int i = 0; i < str.Length; ++i) - { - // FileIOPermission doesn't allow for normalizing across various volume names. This means "C:\" and - // "\\?\C:\" won't be considered correctly. In addition there are many other aliases for the volume - // besides "C:" such as (in one concrete example) "\\?\Harddisk0Partition2\", "\\?\HarddiskVolume6\", - // "\\?\Volume{d1655348-0000-0000-0000-f01500000000}\", etc. - // - // We'll continue to explicitly block extended syntax here by disallowing wildcards no matter where - // they occur in the string (e.g. \\?\ isn't ok) - if (CheckExtraPathCharacters(str[i])) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars")); - - if (!onlyCheckExtras) - PathInternal.CheckInvalidPathChars(str[i]); - } -#else - // There are no "extras" on Unix - if (onlyCheckExtras) - return; - - for (int i = 0; i < str.Length; ++i) - { - PathInternal.CheckInvalidPathChars(str[i]); - } -#endif - } - -#if !PLATFORM_UNIX - /// <summary> - /// Check for ?,* and null, ignoring extended syntax. - /// </summary> - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private unsafe static bool CheckExtraPathCharacters(string path) - { - char currentChar; - for (int i = 0; i < path.Length; i++) - { - currentChar = path[i]; - - // We also check for null here as StringExpressionSet will trim it out. (Ensuring we still throw as we always have.) - if (currentChar == '*' || currentChar == '?' || currentChar == '\0') return true; - } - return false; - } -#endif - - private static bool AccessIsSet( FileIOPermissionAccess access, FileIOPermissionAccess question ) - { - return (access & question) != 0; - } - - private bool IsEmpty() - { - return (!m_unrestricted && - (this.m_read == null || this.m_read.IsEmpty()) && - (this.m_write == null || this.m_write.IsEmpty()) && - (this.m_append == null || this.m_append.IsEmpty()) && - (this.m_pathDiscovery == null || this.m_pathDiscovery.IsEmpty()) && - (this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) && - (this.m_changeAcl == null || this.m_changeAcl.IsEmpty())); - } - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public bool IsUnrestricted() - { - return m_unrestricted; - } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return this.IsEmpty(); - } - - FileIOPermission operand = target as FileIOPermission; - if (operand == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - - if (operand.IsUnrestricted()) - return true; - else if (this.IsUnrestricted()) - return false; - else - return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) && - (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) && - (this.m_append == null || this.m_append.IsSubsetOf( operand.m_append )) && - (this.m_pathDiscovery == null || this.m_pathDiscovery.IsSubsetOf( operand.m_pathDiscovery )) && - (this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) && - (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl ))); - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - { - return null; - } - - FileIOPermission operand = target as FileIOPermission; - - if (operand == null) - { - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - } - else if (this.IsUnrestricted()) - { - return target.Copy(); - } - - if (operand.IsUnrestricted()) - { - return this.Copy(); - } - - FileIOAccess intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read ); - FileIOAccess intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write ); - FileIOAccess intersectAppend = this.m_append == null ? null : this.m_append.Intersect( operand.m_append ); - FileIOAccess intersectPathDiscovery = this.m_pathDiscovery == null ? null : this.m_pathDiscovery.Intersect( operand.m_pathDiscovery ); - FileIOAccess intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl ); - FileIOAccess intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl ); - - if ((intersectRead == null || intersectRead.IsEmpty()) && - (intersectWrite == null || intersectWrite.IsEmpty()) && - (intersectAppend == null || intersectAppend.IsEmpty()) && - (intersectPathDiscovery == null || intersectPathDiscovery.IsEmpty()) && - (intersectViewAcl == null || intersectViewAcl.IsEmpty()) && - (intersectChangeAcl == null || intersectChangeAcl.IsEmpty())) - { - return null; - } - - FileIOPermission intersectPermission = new FileIOPermission(PermissionState.None); - intersectPermission.m_unrestricted = false; - intersectPermission.m_read = intersectRead; - intersectPermission.m_write = intersectWrite; - intersectPermission.m_append = intersectAppend; - intersectPermission.m_pathDiscovery = intersectPathDiscovery; - intersectPermission.m_viewAcl = intersectViewAcl; - intersectPermission.m_changeAcl = intersectChangeAcl; - - return intersectPermission; - } - - public override IPermission Union(IPermission other) - { - if (other == null) - { - return this.Copy(); - } - - FileIOPermission operand = other as FileIOPermission; - - if (operand == null) - { - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - } - - if (this.IsUnrestricted() || operand.IsUnrestricted()) - { - return new FileIOPermission( PermissionState.Unrestricted ); - } - - FileIOAccess unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read ); - FileIOAccess unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write ); - FileIOAccess unionAppend = this.m_append == null ? operand.m_append : this.m_append.Union( operand.m_append ); - FileIOAccess unionPathDiscovery = this.m_pathDiscovery == null ? operand.m_pathDiscovery : this.m_pathDiscovery.Union( operand.m_pathDiscovery ); - FileIOAccess unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl ); - FileIOAccess unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl ); - - if ((unionRead == null || unionRead.IsEmpty()) && - (unionWrite == null || unionWrite.IsEmpty()) && - (unionAppend == null || unionAppend.IsEmpty()) && - (unionPathDiscovery == null || unionPathDiscovery.IsEmpty()) && - (unionViewAcl == null || unionViewAcl.IsEmpty()) && - (unionChangeAcl == null || unionChangeAcl.IsEmpty())) - { - return null; - } - - FileIOPermission unionPermission = new FileIOPermission(PermissionState.None); - unionPermission.m_unrestricted = false; - unionPermission.m_read = unionRead; - unionPermission.m_write = unionWrite; - unionPermission.m_append = unionAppend; - unionPermission.m_pathDiscovery = unionPathDiscovery; - unionPermission.m_viewAcl = unionViewAcl; - unionPermission.m_changeAcl = unionChangeAcl; - - return unionPermission; - } - - public override IPermission Copy() - { - FileIOPermission copy = new FileIOPermission(PermissionState.None); - if (this.m_unrestricted) - { - copy.m_unrestricted = true; - } - else - { - copy.m_unrestricted = false; - if (this.m_read != null) - { - copy.m_read = this.m_read.Copy(); - } - if (this.m_write != null) - { - copy.m_write = this.m_write.Copy(); - } - if (this.m_append != null) - { - copy.m_append = this.m_append.Copy(); - } - if (this.m_pathDiscovery != null) - { - copy.m_pathDiscovery = this.m_pathDiscovery.Copy(); - } - if (this.m_viewAcl != null) - { - copy.m_viewAcl = this.m_viewAcl.Copy(); - } - if (this.m_changeAcl != null) - { - copy.m_changeAcl = this.m_changeAcl.Copy(); - } - } - return copy; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return FileIOPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.FileIOPermissionIndex; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals(Object obj) - { - FileIOPermission perm = obj as FileIOPermission; - if(perm == null) - return false; - - if(m_unrestricted && perm.m_unrestricted) - return true; - if(m_unrestricted != perm.m_unrestricted) - return false; - - if(m_read == null) - { - if(perm.m_read != null && !perm.m_read.IsEmpty()) - return false; - } - else if(!m_read.Equals(perm.m_read)) - return false; - - if(m_write == null) - { - if(perm.m_write != null && !perm.m_write.IsEmpty()) - return false; - } - else if(!m_write.Equals(perm.m_write)) - return false; - - if(m_append == null) - { - if(perm.m_append != null && !perm.m_append.IsEmpty()) - return false; - } - else if(!m_append.Equals(perm.m_append)) - return false; - - if(m_pathDiscovery == null) - { - if(perm.m_pathDiscovery != null && !perm.m_pathDiscovery.IsEmpty()) - return false; - } - else if(!m_pathDiscovery.Equals(perm.m_pathDiscovery)) - return false; - - if(m_viewAcl == null) - { - if(perm.m_viewAcl != null && !perm.m_viewAcl.IsEmpty()) - return false; - } - else if(!m_viewAcl.Equals(perm.m_viewAcl)) - return false; - - if(m_changeAcl == null) - { - if(perm.m_changeAcl != null && !perm.m_changeAcl.IsEmpty()) - return false; - } - else if(!m_changeAcl.Equals(perm.m_changeAcl)) - return false; - - return true; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - // This implementation is only to silence a compiler warning. - return base.GetHashCode(); - } - - /// <summary> - /// Call this method if you don't need a the FileIOPermission for anything other than calling Demand() once. - /// - /// This method tries to verify full access before allocating a FileIOPermission object. - /// If full access is there, then we still have to emulate the checks that creating the - /// FileIOPermission object would have performed. - /// - /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify - /// </summary> - internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false) - { - EmulateFileIOPermissionChecks(fullPath); - } - - /// <summary> - /// Call this method if you don't need a the FileIOPermission for anything other than calling Demand() once. - /// - /// This method tries to verify full access before allocating a FileIOPermission object. - /// If full access is there, then we still have to emulate the checks that creating the - /// FileIOPermission object would have performed. - /// - /// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify - /// - /// </summary> - internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true) - { - foreach (string fullPath in fullPathList) - { - EmulateFileIOPermissionChecks(fullPath); - } - } - - internal static void QuickDemand(PermissionState state) - { - // Should be a no-op without CAS - } - - /// <summary> - /// Perform the additional path checks that would normally happen when creating a FileIOPermission object. - /// </summary> - /// <param name="fullPath">A path that has already gone through GetFullPath or Normalize</param> - internal static void EmulateFileIOPermissionChecks(string fullPath) - { - // 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. - -#if !PLATFORM_UNIX - // Checking for colon / invalid characters on device paths blocks legitimate access to objects such as named pipes. - 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.) - if (PathInternal.HasWildCardCharacters(fullPath)) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars")); - } - - if (PathInternal.HasInvalidVolumeSeparator(fullPath)) - { - throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); - } - } -#endif // !PLATFORM_UNIX - } - } - - [Serializable] - internal sealed class FileIOAccess - { -#if !FEATURE_CASE_SENSITIVE_FILESYSTEM - private bool m_ignoreCase = true; -#else - private bool m_ignoreCase = false; -#endif // !FEATURE_CASE_SENSITIVE_FILESYSTEM - - private StringExpressionSet m_set; - private bool m_allFiles; - private bool m_allLocalFiles; - private bool m_pathDiscovery; - - private const String m_strAllFiles = "*AllFiles*"; - private const String m_strAllLocalFiles = "*AllLocalFiles*"; - - public FileIOAccess() - { - m_set = new StringExpressionSet( m_ignoreCase, true ); - m_allFiles = false; - m_allLocalFiles = false; - m_pathDiscovery = false; - } - - public FileIOAccess( bool pathDiscovery ) - { - m_set = new StringExpressionSet( m_ignoreCase, true ); - m_allFiles = false; - m_allLocalFiles = false; - m_pathDiscovery = pathDiscovery; - } - - public FileIOAccess( String value ) - { - if (value == null) - { - m_set = new StringExpressionSet( m_ignoreCase, true ); - m_allFiles = false; - m_allLocalFiles = false; - } - else if (value.Length >= m_strAllFiles.Length && String.Compare( m_strAllFiles, value, StringComparison.Ordinal) == 0) - { - m_set = new StringExpressionSet( m_ignoreCase, true ); - m_allFiles = true; - m_allLocalFiles = false; - } - else if (value.Length >= m_strAllLocalFiles.Length && String.Compare( m_strAllLocalFiles, 0, value, 0, m_strAllLocalFiles.Length, StringComparison.Ordinal) == 0) - { - m_set = new StringExpressionSet( m_ignoreCase, value.Substring( m_strAllLocalFiles.Length ), true ); - m_allFiles = false; - m_allLocalFiles = true; - } - else - { - m_set = new StringExpressionSet( m_ignoreCase, value, true ); - m_allFiles = false; - m_allLocalFiles = false; - } - m_pathDiscovery = false; - } - - public FileIOAccess( bool allFiles, bool allLocalFiles, bool pathDiscovery ) - { - m_set = new StringExpressionSet( m_ignoreCase, true ); - m_allFiles = allFiles; - m_allLocalFiles = allLocalFiles; - m_pathDiscovery = pathDiscovery; - } - - public FileIOAccess( StringExpressionSet set, bool allFiles, bool allLocalFiles, bool pathDiscovery ) - { - m_set = set; - m_set.SetThrowOnRelative( true ); - m_allFiles = allFiles; - m_allLocalFiles = allLocalFiles; - m_pathDiscovery = pathDiscovery; - } - - private FileIOAccess( FileIOAccess operand ) - { - m_set = operand.m_set.Copy(); - m_allFiles = operand.m_allFiles; - m_allLocalFiles = operand.m_allLocalFiles; - m_pathDiscovery = operand.m_pathDiscovery; - } - - public void AddExpressions(ArrayList values, bool checkForDuplicates) - { - m_allFiles = false; - m_set.AddExpressions(values, checkForDuplicates); - } - - public bool AllFiles - { - get - { - return m_allFiles; - } - - set - { - m_allFiles = value; - } - } - - public bool AllLocalFiles - { - get - { - return m_allLocalFiles; - } - - set - { - m_allLocalFiles = value; - } - } - - public bool PathDiscovery - { - set - { - m_pathDiscovery = value; - } - } - - public bool IsEmpty() - { - return !m_allFiles && !m_allLocalFiles && (m_set == null || m_set.IsEmpty()); - } - - public FileIOAccess Copy() - { - return new FileIOAccess( this ); - } - - public FileIOAccess Union( FileIOAccess operand ) - { - if (operand == null) - { - return this.IsEmpty() ? null : this.Copy(); - } - - Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); - - if (this.m_allFiles || operand.m_allFiles) - { - return new FileIOAccess( true, false, this.m_pathDiscovery ); - } - - return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery ); - } - - public FileIOAccess Intersect( FileIOAccess operand ) - { - if (operand == null) - { - return null; - } - - Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); - - if (this.m_allFiles) - { - if (operand.m_allFiles) - { - return new FileIOAccess( true, false, this.m_pathDiscovery ); - } - else - { - return new FileIOAccess( operand.m_set.Copy(), false, operand.m_allLocalFiles, this.m_pathDiscovery ); - } - } - else if (operand.m_allFiles) - { - return new FileIOAccess( this.m_set.Copy(), false, this.m_allLocalFiles, this.m_pathDiscovery ); - } - - StringExpressionSet intersectionSet = new StringExpressionSet( m_ignoreCase, true ); - - if (this.m_allLocalFiles) - { - String[] expressions = operand.m_set.UnsafeToStringArray(); - - if (expressions != null) - { - for (int i = 0; i < expressions.Length; ++i) - { - String root = GetRoot( expressions[i] ); - if (root != null && IsLocalDrive( GetRoot( root ) ) ) - { - intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false ); - } - } - } - } - - if (operand.m_allLocalFiles) - { - String[] expressions = this.m_set.UnsafeToStringArray(); - - if (expressions != null) - { - for (int i = 0; i < expressions.Length; ++i) - { - String root = GetRoot( expressions[i] ); - if (root != null && IsLocalDrive(GetRoot(root))) - { - intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false ); - } - } - } - } - - String[] regularIntersection = this.m_set.Intersect( operand.m_set ).UnsafeToStringArray(); - - if (regularIntersection != null) - intersectionSet.AddExpressions( regularIntersection, !intersectionSet.IsEmpty(), false ); - - return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery ); - } - - public bool IsSubsetOf( FileIOAccess operand ) - { - if (operand == null) - { - return this.IsEmpty(); - } - - if (operand.m_allFiles) - { - return true; - } - - 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 ))) - { - if (operand.m_allLocalFiles) - { - String[] expressions = m_set.UnsafeToStringArray(); - - for (int i = 0; i < expressions.Length; ++i) - { - String root = GetRoot( expressions[i] ); - if (root == null || !IsLocalDrive(GetRoot(root))) - { - return false; - } - } - } - else - { - return false; - } - } - - return true; - } - - private static String GetRoot( String path ) - { -#if !PLATFORM_UNIX - String str = path.Substring( 0, 3 ); - if (str.EndsWith( ":\\", StringComparison.Ordinal)) -#else - String str = path.Substring( 0, 1 ); - if(str == "/") -#endif // !PLATFORM_UNIX - { - return str; - } - else - { - return null; - } - } - - public override String ToString() - { - // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so - // we're only exposing out the same paths that we took as input. - if (m_allFiles) - { - return m_strAllFiles; - } - else - { - if (m_allLocalFiles) - { - String retstr = m_strAllLocalFiles; - - String tempStr = m_set.UnsafeToString(); - - if (tempStr != null && tempStr.Length > 0) - retstr += ";" + tempStr; - - return retstr; - } - else - { - return m_set.UnsafeToString(); - } - } - } - - public String[] ToStringArray() - { - // SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so - // we're only exposing out the same paths that we took as input. - return m_set.UnsafeToStringArray(); - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern bool IsLocalDrive(String path); - - public override bool Equals(Object obj) - { - FileIOAccess operand = obj as FileIOAccess; - if(operand == null) - return (IsEmpty() && obj == null); - Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" ); - if(m_pathDiscovery) - { - if(this.m_allFiles && operand.m_allFiles) - return true; - if(this.m_allLocalFiles == operand.m_allLocalFiles && - m_set.IsSubsetOf(operand.m_set) && - operand.m_set.IsSubsetOf(m_set)) // Watch Out: This calls StringExpressionSet.IsSubsetOf, unlike below - return true; - return false; - } - else - { - if(!this.IsSubsetOf(operand)) // Watch Out: This calls FileIOAccess.IsSubsetOf, unlike above - return false; - if(!operand.IsSubsetOf(this)) - return false; - return true; - } - } - - public override int GetHashCode() - { - // This implementation is only to silence a compiler warning. - return base.GetHashCode(); - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs deleted file mode 100644 index f93f26daa9..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/GACIdentityPermission.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Globalization; - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class GacIdentityPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { -#pragma warning disable 618 - public GacIdentityPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public override IPermission CreatePermission() - { - return new GacIdentityPermission(); - } - } - - - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class GacIdentityPermission : CodeAccessPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - public GacIdentityPermission(PermissionState state) - { - if (state != PermissionState.Unrestricted && state != PermissionState.None) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public GacIdentityPermission() - { - } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - - public override IPermission Copy() - { - return new GacIdentityPermission(); - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - return false; - if (!(target is GacIdentityPermission)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - return true; - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - if (!(target is GacIdentityPermission)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - return this.Copy(); - } - - public override IPermission Union(IPermission target) - { - if (target == null) - return this.Copy(); - if (!(target is GacIdentityPermission)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - return this.Copy(); - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return GacIdentityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.GacIdentityPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs deleted file mode 100644 index c4facbb67e..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/HostProtectionPermission.cs +++ /dev/null @@ -1,265 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.IO; - using System.Security.Util; - using System.Text; - using System.Threading; - using System.Runtime.Remoting; - using System.Security; - using System.Runtime.Serialization; - using System.Reflection; - using System.Globalization; - using System.Diagnostics.Contracts; - - // Keep this enum in sync with tools\ngen\ngen.cpp and inc\mscoree.idl - -[Serializable] - [Flags] - [System.Runtime.InteropServices.ComVisible(true)] - public enum HostProtectionResource - { - None = 0x0, - //-------------------------------- - Synchronization = 0x1, - SharedState = 0x2, - ExternalProcessMgmt = 0x4, - SelfAffectingProcessMgmt = 0x8, - ExternalThreading = 0x10, - SelfAffectingThreading = 0x20, - SecurityInfrastructure = 0x40, - UI = 0x80, - MayLeakOnAbort = 0x100, - //--------------------------------- - All = 0x1ff, - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )] - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - // 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] -#pragma warning disable 618 - sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private HostProtectionResource m_resources = HostProtectionResource.None; - - public HostProtectionAttribute() -#pragma warning disable 618 - : base( SecurityAction.LinkDemand ) -#pragma warning restore 618 - { - } - -#pragma warning disable 618 - public HostProtectionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { -#pragma warning disable 618 - if (action != SecurityAction.LinkDemand) -#pragma warning restore 618 - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag")); - Contract.EndContractBlock(); - } - - public HostProtectionResource Resources { - get { return m_resources; } - set { m_resources = value; } - } - - public bool Synchronization { - get { return (m_resources & HostProtectionResource.Synchronization) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.Synchronization : m_resources & ~HostProtectionResource.Synchronization); } - } - - public bool SharedState { - get { return (m_resources & HostProtectionResource.SharedState) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.SharedState : m_resources & ~HostProtectionResource.SharedState); } - } - - public bool ExternalProcessMgmt { - get { return (m_resources & HostProtectionResource.ExternalProcessMgmt) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.ExternalProcessMgmt : m_resources & ~HostProtectionResource.ExternalProcessMgmt); } - } - - public bool SelfAffectingProcessMgmt { - get { return (m_resources & HostProtectionResource.SelfAffectingProcessMgmt) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingProcessMgmt : m_resources & ~HostProtectionResource.SelfAffectingProcessMgmt); } - } - - public bool ExternalThreading { - get { return (m_resources & HostProtectionResource.ExternalThreading) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.ExternalThreading : m_resources & ~HostProtectionResource.ExternalThreading); } - } - - public bool SelfAffectingThreading { - get { return (m_resources & HostProtectionResource.SelfAffectingThreading) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.SelfAffectingThreading : m_resources & ~HostProtectionResource.SelfAffectingThreading); } - } - -[System.Runtime.InteropServices.ComVisible(true)] - public bool SecurityInfrastructure { - get { return (m_resources & HostProtectionResource.SecurityInfrastructure) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.SecurityInfrastructure : m_resources & ~HostProtectionResource.SecurityInfrastructure); } - } - - public bool UI { - get { return (m_resources & HostProtectionResource.UI) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.UI : m_resources & ~HostProtectionResource.UI); } - } - - public bool MayLeakOnAbort { - get { return (m_resources & HostProtectionResource.MayLeakOnAbort) != 0; } - set { m_resources = (value ? m_resources | HostProtectionResource.MayLeakOnAbort : m_resources & ~HostProtectionResource.MayLeakOnAbort); } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new HostProtectionPermission( PermissionState.Unrestricted ); - } - else - { - return new HostProtectionPermission( m_resources ); - } - } - } - - [Serializable] - sealed internal class HostProtectionPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // GLOBALS - // - //------------------------------------------------------ - - // This value is set by PermissionSet.FilterHostProtectionPermissions. It is only used for - // constructing a HostProtectionException object. Changing it will not affect HostProtection. - internal static volatile HostProtectionResource protectedResources = HostProtectionResource.None; - - //------------------------------------------------------ - // - // MEMBERS - // - //------------------------------------------------------ - private HostProtectionResource m_resources; - - //------------------------------------------------------ - // - // CONSTRUCTORS - // - //------------------------------------------------------ - public HostProtectionPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - Resources = HostProtectionResource.All; - else if (state == PermissionState.None) - Resources = HostProtectionResource.None; - else - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - - public HostProtectionPermission(HostProtectionResource resources) - { - Resources = resources; - } - - //------------------------------------------------------ - // - // IPermission interface implementation - // - //------------------------------------------------------ - public bool IsUnrestricted() - { - return Resources == HostProtectionResource.All; - } - - //------------------------------------------------------ - // - // Properties - // - //------------------------------------------------------ - public HostProtectionResource Resources - { - set - { - if(value < HostProtectionResource.None || value > HostProtectionResource.All) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)value)); - Contract.EndContractBlock(); - m_resources = value; - } - - get - { - return m_resources; - } - } - - //------------------------------------------------------ - // - // IPermission interface implementation - // - //------------------------------------------------------ - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - return m_resources == HostProtectionResource.None; - if(this.GetType() != target.GetType()) - throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); - return ((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources) == (uint)this.m_resources; - } - - public override IPermission Union(IPermission target) - { - if (target == null) - return(this.Copy()); - if(this.GetType() != target.GetType()) - throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); - HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources | (uint)((HostProtectionPermission)target).m_resources); - return new HostProtectionPermission(newResources); - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - if(this.GetType() != target.GetType()) - throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); - HostProtectionResource newResources = (HostProtectionResource)((uint)this.m_resources & (uint)((HostProtectionPermission)target).m_resources); - if(newResources == HostProtectionResource.None) - return null; - return new HostProtectionPermission(newResources); - } - - public override IPermission Copy() - { - return new HostProtectionPermission(m_resources); - } - - //------------------------------------------------------ - // - // OBJECT OVERRIDES - // - //------------------------------------------------------ - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return HostProtectionPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.HostProtectionPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs b/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs deleted file mode 100644 index 58b26bd9c4..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/IBuiltInPermission.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - internal interface IBuiltInPermission - { - int GetTokenIndex(); - } - - internal static class BuiltInPermissionIndex - { - internal const int NUM_BUILTIN_UNRESTRICTED = 10; - internal const int NUM_BUILTIN_NORMAL = 7; - - // Unrestricted permissions - - internal const int EnvironmentPermissionIndex = 0; - internal const int FileDialogPermissionIndex = 1; - internal const int FileIOPermissionIndex = 2; - internal const int IsolatedStorageFilePermissionIndex = 3; - internal const int ReflectionPermissionIndex = 4; - internal const int RegistryPermissionIndex = 5; - internal const int SecurityPermissionIndex = 6; - internal const int UIPermissionIndex = 7; - internal const int PrincipalPermissionIndex = 8; - internal const int HostProtectionPermissionIndex = 9; - - // Normal permissions - internal const int PublisherIdentityPermissionIndex = 0 + NUM_BUILTIN_UNRESTRICTED; - internal const int SiteIdentityPermissionIndex = 1 + NUM_BUILTIN_UNRESTRICTED; - internal const int StrongNameIdentityPermissionIndex = 2 + NUM_BUILTIN_UNRESTRICTED; - internal const int UrlIdentityPermissionIndex = 3 + NUM_BUILTIN_UNRESTRICTED; - internal const int ZoneIdentityPermissionIndex = 4 + NUM_BUILTIN_UNRESTRICTED; - internal const int GacIdentityPermissionIndex = 5 + NUM_BUILTIN_UNRESTRICTED; - internal const int KeyContainerPermissionIndex = 6 + NUM_BUILTIN_UNRESTRICTED; - } - - [Serializable] - internal enum BuiltInPermissionFlag - { - // Unrestricted permissions - - EnvironmentPermission = 0x1, - FileDialogPermission = 0x2, - FileIOPermission = 0x4, - IsolatedStorageFilePermission = 0x8, - ReflectionPermission = 0x10, - RegistryPermission = 0x20, - SecurityPermission = 0x40, - UIPermission = 0x80, - PrincipalPermission = 0x100, - - // Normal permissions - PublisherIdentityPermission = 0x200, - SiteIdentityPermission = 0x400, - StrongNameIdentityPermission = 0x800, - UrlIdentityPermission = 0x1000, - ZoneIdentityPermission = 0x2000, - KeyContainerPermission = 0x4000, - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs b/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs deleted file mode 100644 index 782df8012c..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/IUnrestrictedPermission.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - - using System; -[System.Runtime.InteropServices.ComVisible(true)] - public interface IUnrestrictedPermission - { - bool IsUnrestricted(); - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs deleted file mode 100644 index 42bc648c72..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/IsolatedStorageFilePermission.cs +++ /dev/null @@ -1,163 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// Purpose : This permission is used to controls/administer access to -// IsolatedStorageFile -// - -namespace System.Security.Permissions { - - using System.Globalization; - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - sealed public class IsolatedStorageFilePermission : IsolatedStoragePermission, IBuiltInPermission - { - public IsolatedStorageFilePermission(PermissionState state) - : base(state) { } - - internal IsolatedStorageFilePermission(IsolatedStorageContainment UsageAllowed, - long ExpirationDays, bool PermanentData) - : base(UsageAllowed, ExpirationDays, PermanentData) { } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public override IPermission Union(IPermission target) - { - if (target == null) - { - return this.Copy(); - } - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target; - - if (this.IsUnrestricted() || operand.IsUnrestricted()) - { - return new IsolatedStorageFilePermission( PermissionState.Unrestricted ); - } - else - { - IsolatedStorageFilePermission union; - union = new IsolatedStorageFilePermission( PermissionState.None ); - union.m_userQuota = max(m_userQuota,operand.m_userQuota); - union.m_machineQuota = max(m_machineQuota,operand.m_machineQuota); - union.m_expirationDays = max(m_expirationDays,operand.m_expirationDays); - union.m_permanentData = m_permanentData || operand.m_permanentData; - union.m_allowed = (IsolatedStorageContainment)max((long)m_allowed,(long)operand.m_allowed); - return union; - } - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return ((m_userQuota == 0) && - (m_machineQuota == 0) && - (m_expirationDays == 0) && - (m_permanentData == false) && - (m_allowed == IsolatedStorageContainment.None)); - } - - try - { - IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target; - - if (operand.IsUnrestricted()) - return true; - - return ((operand.m_userQuota >= m_userQuota) && - (operand.m_machineQuota >= m_machineQuota) && - (operand.m_expirationDays >= m_expirationDays) && - (operand.m_permanentData || !m_permanentData) && - (operand.m_allowed >= m_allowed)); - } - catch (InvalidCastException) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - IsolatedStorageFilePermission operand = (IsolatedStorageFilePermission)target; - - if(operand.IsUnrestricted()) - return Copy(); - else if(IsUnrestricted()) - return target.Copy(); - - IsolatedStorageFilePermission intersection; - intersection = new IsolatedStorageFilePermission( PermissionState.None ); - intersection.m_userQuota = min(m_userQuota,operand.m_userQuota); - intersection.m_machineQuota = min(m_machineQuota,operand.m_machineQuota); - intersection.m_expirationDays = min(m_expirationDays,operand.m_expirationDays); - intersection.m_permanentData = m_permanentData && operand.m_permanentData; - intersection.m_allowed = (IsolatedStorageContainment)min((long)m_allowed,(long)operand.m_allowed); - - if ((intersection.m_userQuota == 0) && - (intersection.m_machineQuota == 0) && - (intersection.m_expirationDays == 0) && - (intersection.m_permanentData == false) && - (intersection.m_allowed == IsolatedStorageContainment.None)) - return null; - - return intersection; - } - - public override IPermission Copy() - { - IsolatedStorageFilePermission copy ; - copy = new IsolatedStorageFilePermission(PermissionState.Unrestricted); - if(!IsUnrestricted()){ - copy.m_userQuota = m_userQuota; - copy.m_machineQuota = m_machineQuota; - copy.m_expirationDays = m_expirationDays; - copy.m_permanentData = m_permanentData; - copy.m_allowed = m_allowed; - } - return copy; - } - - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return IsolatedStorageFilePermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex; - } - } -} - diff --git a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs b/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs deleted file mode 100644 index 9f09a37098..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/IsolatedStoragePermission.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - - using System; - using System.IO; - using System.Security; - using System.Security.Util; - using System.Globalization; - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public enum IsolatedStorageContainment { - None = 0x00, - DomainIsolationByUser = 0x10, - ApplicationIsolationByUser = 0x15, - AssemblyIsolationByUser = 0x20, - DomainIsolationByMachine = 0x30, - AssemblyIsolationByMachine = 0x40, - ApplicationIsolationByMachine = 0x45, - DomainIsolationByRoamingUser = 0x50, - AssemblyIsolationByRoamingUser = 0x60, - ApplicationIsolationByRoamingUser = 0x65, - AdministerIsolatedStorageByUser = 0x70, - //AdministerIsolatedStorageByMachine = 0x80, - UnrestrictedIsolatedStorage = 0xF0 - }; - - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - abstract public class IsolatedStoragePermission - : CodeAccessPermission, IUnrestrictedPermission - { - - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - - /// <internalonly/> - internal long m_userQuota; - /// <internalonly/> - internal long m_machineQuota; - /// <internalonly/> - internal long m_expirationDays; - /// <internalonly/> - internal bool m_permanentData; - /// <internalonly/> - internal IsolatedStorageContainment m_allowed; - - //------------------------------------------------------ - // - // CONSTRUCTORS - // - //------------------------------------------------------ - - protected IsolatedStoragePermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_userQuota = Int64.MaxValue; - m_machineQuota = Int64.MaxValue; - m_expirationDays = Int64.MaxValue ; - m_permanentData = true; - m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage; - } - else if (state == PermissionState.None) - { - m_userQuota = 0; - m_machineQuota = 0; - m_expirationDays = 0; - m_permanentData = false; - m_allowed = IsolatedStorageContainment.None; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed, - long ExpirationDays, bool PermanentData) - - { - m_userQuota = 0; // typical demand won't include quota - m_machineQuota = 0; // typical demand won't include quota - m_expirationDays = ExpirationDays; - m_permanentData = PermanentData; - m_allowed = UsageAllowed; - } - - internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed, - long ExpirationDays, bool PermanentData, long UserQuota) - - { - m_machineQuota = 0; - m_userQuota = UserQuota; - m_expirationDays = ExpirationDays; - m_permanentData = PermanentData; - m_allowed = UsageAllowed; - } - - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - // 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; - } - } - - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public bool IsUnrestricted() - { - return m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage; - } - - - //------------------------------------------------------ - // - // INTERNAL METHODS - // - //------------------------------------------------------ - internal static long min(long x,long y) {return x>y?y:x;} - internal static long max(long x,long y) {return x<y?y:x;} - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs b/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs deleted file mode 100644 index b6ac8ece3c..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/PermissionAttributes.cs +++ /dev/null @@ -1,880 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - - using System.Security.Util; - using System.IO; - using System.Security.Policy; - using System.Text; - using System.Threading; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.Runtime.Serialization; -#if FEATURE_X509 - using System.Security.Cryptography.X509Certificates; -#endif - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - - [Serializable] - [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.")] - public enum SecurityAction - { - // Demand permission of all caller - Demand = 2, - - // Assert permission so callers don't need - Assert = 3, - - // Deny permissions so checks will fail - [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.")] - Deny = 4, - - // Reduce permissions so check will fail - PermitOnly = 5, - - // Demand permission of caller - LinkDemand = 6, - - // Demand permission of a subclass - InheritanceDemand = 7, - - // Request minimum permissions to run - [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - RequestMinimum = 8, - - // Request optional additional permissions - [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - RequestOptional = 9, - - // Refuse to be granted these permissions - [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] - RequestRefuse = 10, - } - - [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.")] - public abstract class SecurityAttribute : System.Attribute - { - /// <internalonly/> - internal SecurityAction m_action; - /// <internalonly/> - internal bool m_unrestricted; - - protected SecurityAttribute( SecurityAction action ) - { - m_action = action; - } - - public SecurityAction Action - { - get { return m_action; } - set { m_action = value; } - } - - public bool Unrestricted - { - get { return m_unrestricted; } - set { m_unrestricted = value; } - } - - abstract public IPermission CreatePermission(); - - internal static unsafe IntPtr FindSecurityAttributeTypeHandle(String typeName) - { - PermissionSet.s_fullTrust.Assert(); - Type t = Type.GetType(typeName, false, false); - if(t == null) - return IntPtr.Zero; - IntPtr typeHandle = t.TypeHandle.Value; - return typeHandle; - } - } - - [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.")] - public abstract class CodeAccessSecurityAttribute : SecurityAttribute - { - protected CodeAccessSecurityAttribute( SecurityAction action ) - : base( action ) - { - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class EnvironmentPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_read = null; - private String m_write = null; - -#pragma warning disable 618 - public EnvironmentPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Read { - get { return m_read; } - set { m_read = value; } - } - - public String Write { - get { return m_write; } - set { m_write = value; } - } - - public String All { - get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } - set { m_write = value; m_read = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new EnvironmentPermission(PermissionState.Unrestricted); - } - else - { - EnvironmentPermission perm = new EnvironmentPermission(PermissionState.None); - if (m_read != null) - perm.SetPathList( EnvironmentPermissionAccess.Read, m_read ); - if (m_write != null) - perm.SetPathList( EnvironmentPermissionAccess.Write, m_write ); - return perm; - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class FileDialogPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private FileDialogPermissionAccess m_access; - -#pragma warning disable 618 - public FileDialogPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public bool Open - { - get { return (m_access & FileDialogPermissionAccess.Open) != 0; } - set { m_access = value ? m_access | FileDialogPermissionAccess.Open : m_access & ~FileDialogPermissionAccess.Open; } - } - - public bool Save - { - get { return (m_access & FileDialogPermissionAccess.Save) != 0; } - set { m_access = value ? m_access | FileDialogPermissionAccess.Save : m_access & ~FileDialogPermissionAccess.Save; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new FileDialogPermission( PermissionState.Unrestricted ); - } - else - { - return new FileDialogPermission( m_access ); - } - } - } - - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class FileIOPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_read = null; - private String m_write = null; - private String m_append = null; - private String m_pathDiscovery = null; - private String m_viewAccess = null; - private String m_changeAccess = null; - [OptionalField(VersionAdded = 2)] private FileIOPermissionAccess m_allLocalFiles = FileIOPermissionAccess.NoAccess; - [OptionalField(VersionAdded = 2)] private FileIOPermissionAccess m_allFiles = FileIOPermissionAccess.NoAccess; - -#pragma warning disable 618 - public FileIOPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Read { - get { return m_read; } - set { m_read = value; } - } - - public String Write { - get { return m_write; } - set { m_write = value; } - } - - public String Append { - get { return m_append; } - set { m_append = value; } - } - - public String PathDiscovery { - get { return m_pathDiscovery; } - set { m_pathDiscovery = value; } - } - - public String ViewAccessControl { - get { return m_viewAccess; } - set { m_viewAccess = value; } - } - - public String ChangeAccessControl { - get { return m_changeAccess; } - set { m_changeAccess = value; } - } - - [Obsolete("Please use the ViewAndModify property instead.")] - public String All { - set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; } - get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } - } - - // Read, Write, Append, PathDiscovery, but no ACL-related permissions - public String ViewAndModify { - get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } - set { m_read = value; m_write = value; m_append = value; m_pathDiscovery = value; } - } - - public FileIOPermissionAccess AllFiles { - get { return m_allFiles; } - set { m_allFiles = value; } - } - - public FileIOPermissionAccess AllLocalFiles { - get { return m_allLocalFiles; } - set { m_allLocalFiles = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new FileIOPermission(PermissionState.Unrestricted); - } - else - { - FileIOPermission perm = new FileIOPermission(PermissionState.None); - if (m_read != null) - perm.SetPathList( FileIOPermissionAccess.Read, m_read ); - if (m_write != null) - perm.SetPathList( FileIOPermissionAccess.Write, m_write ); - if (m_append != null) - perm.SetPathList( FileIOPermissionAccess.Append, m_append ); - if (m_pathDiscovery != null) - perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery ); - - perm.AllFiles = m_allFiles; - perm.AllLocalFiles = m_allLocalFiles; - return perm; - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] -#pragma warning disable 618 - public sealed class KeyContainerPermissionAttribute : CodeAccessSecurityAttribute { -#pragma warning restore 618 - KeyContainerPermissionFlags m_flags = KeyContainerPermissionFlags.NoFlags; - private string m_keyStore; - private string m_providerName; - private int m_providerType = -1; - private string m_keyContainerName; - private int m_keySpec = -1; - -#pragma warning disable 618 - public KeyContainerPermissionAttribute(SecurityAction action) : base(action) {} -#pragma warning restore 618 - - public string KeyStore { - get { return m_keyStore; } - set { m_keyStore = value; } - } - - public string ProviderName { - get { return m_providerName; } - set { m_providerName = value; } - } - - public int ProviderType { - get { return m_providerType; } - set { m_providerType = value; } - } - - public string KeyContainerName { - get { return m_keyContainerName; } - set { m_keyContainerName = value; } - } - - public int KeySpec { - get { return m_keySpec; } - set { m_keySpec = value; } - } - - public KeyContainerPermissionFlags Flags { - get { return m_flags; } - set { m_flags = value; } - } - - public override IPermission CreatePermission() { - if (m_unrestricted) { - return new KeyContainerPermission(PermissionState.Unrestricted); - } else { - if (KeyContainerPermissionAccessEntry.IsUnrestrictedEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec)) - return new KeyContainerPermission(m_flags); - - // create a KeyContainerPermission with a single access entry. - KeyContainerPermission cp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); - KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(m_keyStore, m_providerName, m_providerType, m_keyContainerName, m_keySpec, m_flags); - cp.AccessEntries.Add(accessEntry); - return cp; - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class ReflectionPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private ReflectionPermissionFlag m_flag = ReflectionPermissionFlag.NoFlags; - -#pragma warning disable 618 - public ReflectionPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public ReflectionPermissionFlag Flags { - get { return m_flag; } - set { m_flag = value; } - } - - [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] - public bool TypeInformation { -#pragma warning disable 618 - get { return (m_flag & ReflectionPermissionFlag.TypeInformation) != 0; } - set { m_flag = value ? m_flag | ReflectionPermissionFlag.TypeInformation : m_flag & ~ReflectionPermissionFlag.TypeInformation; } -#pragma warning restore 618 - } - - public bool MemberAccess { - get { return (m_flag & ReflectionPermissionFlag.MemberAccess) != 0; } - set { m_flag = value ? m_flag | ReflectionPermissionFlag.MemberAccess : m_flag & ~ReflectionPermissionFlag.MemberAccess; } - } - - [Obsolete("This permission is no longer used by the CLR.")] - public bool ReflectionEmit { -#pragma warning disable 618 - get { return (m_flag & ReflectionPermissionFlag.ReflectionEmit) != 0; } - set { m_flag = value ? m_flag | ReflectionPermissionFlag.ReflectionEmit : m_flag & ~ReflectionPermissionFlag.ReflectionEmit; } -#pragma warning restore 618 - } - - public bool RestrictedMemberAccess - { - get { return (m_flag & ReflectionPermissionFlag.RestrictedMemberAccess) != 0; } - set { m_flag = value ? m_flag | ReflectionPermissionFlag.RestrictedMemberAccess : m_flag & ~ReflectionPermissionFlag.RestrictedMemberAccess; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new ReflectionPermission( PermissionState.Unrestricted ); - } - else - { - return new ReflectionPermission( m_flag ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class RegistryPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_read = null; - private String m_write = null; - private String m_create = null; - private String m_viewAcl = null; - private String m_changeAcl = null; - -#pragma warning disable 618 - public RegistryPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Read { - get { return m_read; } - set { m_read = value; } - } - - public String Write { - get { return m_write; } - set { m_write = value; } - } - - public String Create { - get { return m_create; } - set { m_create = value; } - } - - public String ViewAccessControl { - get { return m_viewAcl; } - set { m_viewAcl = value; } - } - - public String ChangeAccessControl { - get { return m_changeAcl; } - set { m_changeAcl = value; } - } - - // Read, Write, & Create, but no ACL's - public String ViewAndModify { - get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } - set { m_read = value; m_write = value; m_create = value; } - } - - [Obsolete("Please use the ViewAndModify property instead.")] - public String All { - get { throw new NotSupportedException( Environment.GetResourceString( "NotSupported_GetMethod" ) ); } - set { m_read = value; m_write = value; m_create = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new RegistryPermission( PermissionState.Unrestricted ); - } - else - { - RegistryPermission perm = new RegistryPermission(PermissionState.None); - if (m_read != null) - perm.SetPathList( RegistryPermissionAccess.Read, m_read ); - if (m_write != null) - perm.SetPathList( RegistryPermissionAccess.Write, m_write ); - if (m_create != null) - perm.SetPathList( RegistryPermissionAccess.Create, m_create ); - return perm; - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - // The csharp compiler requires these types to be public, but they are not used elsewhere. - [Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")] - sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute - { - private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags; - - public SecurityPermissionAttribute( SecurityAction action ) - : base( action ) - { - } - - public SecurityPermissionFlag Flags { - get { return m_flag; } - set { m_flag = value; } - } - - public bool Assertion { - get { return (m_flag & SecurityPermissionFlag.Assertion) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.Assertion : m_flag & ~SecurityPermissionFlag.Assertion; } - } - - public bool UnmanagedCode { - get { return (m_flag & SecurityPermissionFlag.UnmanagedCode) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.UnmanagedCode : m_flag & ~SecurityPermissionFlag.UnmanagedCode; } - } - - public bool SkipVerification { - get { return (m_flag & SecurityPermissionFlag.SkipVerification) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.SkipVerification : m_flag & ~SecurityPermissionFlag.SkipVerification; } - } - - public bool Execution { - get { return (m_flag & SecurityPermissionFlag.Execution) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.Execution : m_flag & ~SecurityPermissionFlag.Execution; } - } - - public bool ControlThread { - get { return (m_flag & SecurityPermissionFlag.ControlThread) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlThread : m_flag & ~SecurityPermissionFlag.ControlThread; } - } - - public bool ControlEvidence { - get { return (m_flag & SecurityPermissionFlag.ControlEvidence) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlEvidence : m_flag & ~SecurityPermissionFlag.ControlEvidence; } - } - - public bool ControlPolicy { - get { return (m_flag & SecurityPermissionFlag.ControlPolicy) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPolicy : m_flag & ~SecurityPermissionFlag.ControlPolicy; } - } - - public bool SerializationFormatter { - get { return (m_flag & SecurityPermissionFlag.SerializationFormatter) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.SerializationFormatter : m_flag & ~SecurityPermissionFlag.SerializationFormatter; } - } - - public bool ControlDomainPolicy { - get { return (m_flag & SecurityPermissionFlag.ControlDomainPolicy) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlDomainPolicy : m_flag & ~SecurityPermissionFlag.ControlDomainPolicy; } - } - - public bool ControlPrincipal { - get { return (m_flag & SecurityPermissionFlag.ControlPrincipal) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlPrincipal : m_flag & ~SecurityPermissionFlag.ControlPrincipal; } - } - - public bool ControlAppDomain { - get { return (m_flag & SecurityPermissionFlag.ControlAppDomain) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.ControlAppDomain : m_flag & ~SecurityPermissionFlag.ControlAppDomain; } - } - - public bool RemotingConfiguration { - get { return (m_flag & SecurityPermissionFlag.RemotingConfiguration) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; } - } - - [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; } - } - - public bool BindingRedirects { - get { return (m_flag & SecurityPermissionFlag.BindingRedirects) != 0; } - set { m_flag = value ? m_flag | SecurityPermissionFlag.BindingRedirects : m_flag & ~SecurityPermissionFlag.BindingRedirects; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new SecurityPermission( PermissionState.Unrestricted ); - } - else - { - return new SecurityPermission( m_flag ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class UIPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private UIPermissionWindow m_windowFlag = UIPermissionWindow.NoWindows; - private UIPermissionClipboard m_clipboardFlag = UIPermissionClipboard.NoClipboard; - -#pragma warning disable 618 - public UIPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public UIPermissionWindow Window { - get { return m_windowFlag; } - set { m_windowFlag = value; } - } - - public UIPermissionClipboard Clipboard { - get { return m_clipboardFlag; } - set { m_clipboardFlag = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new UIPermission( PermissionState.Unrestricted ); - } - else - { - return new UIPermission( m_windowFlag, m_clipboardFlag ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class ZoneIdentityPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private SecurityZone m_flag = SecurityZone.NoZone; - -#pragma warning disable 618 - public ZoneIdentityPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public SecurityZone Zone { - get { return m_flag; } - set { m_flag = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new ZoneIdentityPermission(PermissionState.Unrestricted); - } - else - { - return new ZoneIdentityPermission( m_flag ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class StrongNameIdentityPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_name = null; - private String m_version = null; - private String m_blob = null; - -#pragma warning disable 618 - public StrongNameIdentityPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Name - { - get { return m_name; } - set { m_name = value; } - } - - public String Version - { - get { return m_version; } - set { m_version = value; } - } - - public String PublicKey - { - get { return m_blob; } - set { m_blob = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new StrongNameIdentityPermission( PermissionState.Unrestricted ); - } - else - { - if (m_blob == null && m_name == null && m_version == null) - return new StrongNameIdentityPermission( PermissionState.None ); - - if (m_blob == null) - throw new ArgumentException( Environment.GetResourceString("ArgumentNull_Key")); - - StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob( m_blob ); - - if (m_version == null || m_version.Equals(String.Empty)) - return new StrongNameIdentityPermission( blob, m_name, null ); - else - return new StrongNameIdentityPermission( blob, m_name, new Version( m_version ) ); - } - } - } - - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class SiteIdentityPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_site = null; - -#pragma warning disable 618 - public SiteIdentityPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Site { - get { return m_site; } - set { m_site = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new SiteIdentityPermission( PermissionState.Unrestricted ); - } - else - { - if (m_site == null) - return new SiteIdentityPermission( PermissionState.None ); - - return new SiteIdentityPermission( m_site ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] -#pragma warning disable 618 - [Serializable] sealed public class UrlIdentityPermissionAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_url = null; - -#pragma warning disable 618 - public UrlIdentityPermissionAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - } - - public String Url { - get { return m_url; } - set { m_url = value; } - } - - public override IPermission CreatePermission() - { - if (m_unrestricted) - { - return new UrlIdentityPermission( PermissionState.Unrestricted ); - } - else - { - if (m_url == null) - return new UrlIdentityPermission( PermissionState.None ); - - return new UrlIdentityPermission( m_url ); - } - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] -#pragma warning disable 618 - sealed public class PermissionSetAttribute : CodeAccessSecurityAttribute -#pragma warning restore 618 - { - private String m_file; - private String m_name; - private bool m_unicode; - private String m_xml; - private String m_hex; - -#pragma warning disable 618 - public PermissionSetAttribute( SecurityAction action ) -#pragma warning restore 618 - : base( action ) - { - m_unicode = false; - } - - public String File { - get { return m_file; } - set { m_file = value; } - } - - public bool UnicodeEncoded { - get { return m_unicode; } - set { m_unicode = value; } - } - - public String Name { - get { return m_name; } - set { m_name = value; } - } - - public String XML { - get { return m_xml; } - set { m_xml = value; } - } - - public String Hex { - get { return m_hex; } - set { m_hex = value; } - } - - public override IPermission CreatePermission() - { - return null; - } - - public PermissionSet CreatePermissionSet() - { - if (m_unrestricted) - return new PermissionSet( PermissionState.Unrestricted ); - else if (m_name != null) - return NamedPermissionSet.GetBuiltInSet( m_name ); - else - return new PermissionSet( PermissionState.None ); - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/PermissionState.cs b/src/mscorlib/src/System/Security/Permissions/PermissionState.cs deleted file mode 100644 index ea0f1a0ac2..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/PermissionState.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// The Runtime policy manager. Maintains a set of IdentityMapper objects that map -// inbound evidence to groups. Resolves an identity into a set of permissions -// - -namespace System.Security.Permissions { - - using System; - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public enum PermissionState - { - Unrestricted = 1, - None = 0, - } - -} diff --git a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs b/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs deleted file mode 100644 index 1c9dd7696c..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/ReflectionPermission.cs +++ /dev/null @@ -1,274 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.IO; - using System.Security.Util; - using System.Text; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.Security; - using System.Reflection; - using System.Globalization; - using System.Diagnostics.Contracts; - - [ComVisible(true)] - [Flags] - [Serializable] - public enum ReflectionPermissionFlag - { - NoFlags = 0x00, - [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] - TypeInformation = 0x01, - MemberAccess = 0x02, - [Obsolete("This permission is no longer used by the CLR.")] - ReflectionEmit = 0x04, - [ComVisible(false)] - RestrictedMemberAccess = 0x08, - [Obsolete("This permission has been deprecated. Use PermissionState.Unrestricted to get full access.")] - AllFlags = 0x07 - } - - [ComVisible(true)] - [Serializable] - sealed public class ReflectionPermission - : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - // ReflectionPermissionFlag.AllFlags doesn't contain the new value RestrictedMemberAccess, - // but we cannot change its value now because that will break apps that have that old value baked in. - // We should use this const that truely contains "all" flags instead of ReflectionPermissionFlag.AllFlags. -#pragma warning disable 618 - internal const ReflectionPermissionFlag AllFlagsAndMore = ReflectionPermissionFlag.AllFlags | ReflectionPermissionFlag.RestrictedMemberAccess; -#pragma warning restore 618 - - private ReflectionPermissionFlag m_flags; - - // - // Public Constructors - // - - public ReflectionPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - SetUnrestricted( true ); - } - else if (state == PermissionState.None) - { - SetUnrestricted( false ); - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - // Parameters: - // - public ReflectionPermission(ReflectionPermissionFlag flag) - { - VerifyAccess(flag); - - SetUnrestricted(false); - m_flags = flag; - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED MODIFIERS - // - //------------------------------------------------------ - - - private void SetUnrestricted(bool unrestricted) - { - if (unrestricted) - { - m_flags = ReflectionPermission.AllFlagsAndMore; - } - else - { - Reset(); - } - } - - - private void Reset() - { - m_flags = ReflectionPermissionFlag.NoFlags; - } - - - public ReflectionPermissionFlag Flags - { - set - { - VerifyAccess(value); - - m_flags = value; - } - - get - { - return m_flags; - } - } - - - #if ZERO // Do not remove this code, useful for debugging - public override String ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("ReflectionPermission("); - if (IsUnrestricted()) - { - sb.Append("Unrestricted"); - } - else - { - if (GetFlag(ReflectionPermissionFlag.TypeInformation)) - sb.Append("TypeInformation; "); - if (GetFlag(ReflectionPermissionFlag.MemberAccess)) - sb.Append("MemberAccess; "); -#pragma warning disable 618 - if (GetFlag(ReflectionPermissionFlag.ReflectionEmit)) - sb.Append("ReflectionEmit; "); -#pragma warning restore 618 - } - - sb.Append(")"); - return sb.ToString(); - } - #endif - - - // - // CodeAccessPermission implementation - // - - public bool IsUnrestricted() - { - return m_flags == ReflectionPermission.AllFlagsAndMore; - } - - // - // IPermission implementation - // - - public override IPermission Union(IPermission other) - { - if (other == null) - { - return this.Copy(); - } - else if (!VerifyType(other)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - ReflectionPermission operand = (ReflectionPermission)other; - - if (this.IsUnrestricted() || operand.IsUnrestricted()) - { - return new ReflectionPermission( PermissionState.Unrestricted ); - } - else - { - ReflectionPermissionFlag flag_union = (ReflectionPermissionFlag)(m_flags | operand.m_flags); - return(new ReflectionPermission(flag_union)); - } - } - - - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return m_flags == ReflectionPermissionFlag.NoFlags; - } - - try - { - ReflectionPermission operand = (ReflectionPermission)target; - if (operand.IsUnrestricted()) - return true; - else if (this.IsUnrestricted()) - return false; - else - return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0; - } - catch (InvalidCastException) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - ReflectionPermission operand = (ReflectionPermission)target; - - ReflectionPermissionFlag newFlags = operand.m_flags & this.m_flags; - - if (newFlags == ReflectionPermissionFlag.NoFlags) - return null; - else - return new ReflectionPermission( newFlags ); - } - - public override IPermission Copy() - { - if (this.IsUnrestricted()) - { - return new ReflectionPermission(PermissionState.Unrestricted); - } - else - { - return new ReflectionPermission((ReflectionPermissionFlag)m_flags); - } - } - - - // - // IEncodable Interface - - private - void VerifyAccess(ReflectionPermissionFlag type) - { - if ((type & ~ReflectionPermission.AllFlagsAndMore) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type)); - Contract.EndContractBlock(); - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return ReflectionPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.ReflectionPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs b/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs deleted file mode 100644 index c0c51e94a2..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/RegistryPermission.cs +++ /dev/null @@ -1,363 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using SecurityElement = System.Security.SecurityElement; - using System.Security.AccessControl; - using System.Security.Util; - using System.IO; - using System.Globalization; - using System.Runtime.Serialization; - -[Serializable] - [Flags] -[System.Runtime.InteropServices.ComVisible(true)] - public enum RegistryPermissionAccess - { - NoAccess = 0x00, - Read = 0x01, - Write = 0x02, - Create = 0x04, - AllAccess = 0x07, - } - -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class RegistryPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - private StringExpressionSet m_read; - private StringExpressionSet m_write; - private StringExpressionSet m_create; - [OptionalField(VersionAdded = 2)] - private StringExpressionSet m_viewAcl; - [OptionalField(VersionAdded = 2)] - private StringExpressionSet m_changeAcl; - private bool m_unrestricted; - - - public RegistryPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_unrestricted = true; - } - else if (state == PermissionState.None) - { - m_unrestricted = false; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public RegistryPermission( RegistryPermissionAccess access, String pathList ) - { - SetPathList( access, pathList ); - } - - public void SetPathList( RegistryPermissionAccess access, String pathList ) - { - VerifyAccess( access ); - - m_unrestricted = false; - - if ((access & RegistryPermissionAccess.Read) != 0) - m_read = null; - - if ((access & RegistryPermissionAccess.Write) != 0) - m_write = null; - - if ((access & RegistryPermissionAccess.Create) != 0) - m_create = null; - - AddPathList( access, pathList ); - } - - public void AddPathList( RegistryPermissionAccess access, String pathList ) - { - AddPathList( access, AccessControlActions.None, pathList ); - } - - public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList ) - { - VerifyAccess( access ); - - if ((access & RegistryPermissionAccess.Read) != 0) - { - if (m_read == null) - m_read = new StringExpressionSet(); - m_read.AddExpressions( pathList ); - } - - if ((access & RegistryPermissionAccess.Write) != 0) - { - if (m_write == null) - m_write = new StringExpressionSet(); - m_write.AddExpressions( pathList ); - } - - if ((access & RegistryPermissionAccess.Create) != 0) - { - if (m_create == null) - m_create = new StringExpressionSet(); - m_create.AddExpressions( pathList ); - } - } - - public String GetPathList( RegistryPermissionAccess access ) - { - // SafeCritical: these are registry paths, which means we're not leaking file system information here - VerifyAccess( access ); - ExclusiveAccess( access ); - - if ((access & RegistryPermissionAccess.Read) != 0) - { - if (m_read == null) - { - return ""; - } - return m_read.UnsafeToString(); - } - - if ((access & RegistryPermissionAccess.Write) != 0) - { - if (m_write == null) - { - return ""; - } - return m_write.UnsafeToString(); - } - - if ((access & RegistryPermissionAccess.Create) != 0) - { - if (m_create == null) - { - return ""; - } - return m_create.UnsafeToString(); - } - - /* not reached */ - - return ""; - } - - private void VerifyAccess( RegistryPermissionAccess access ) - { - if ((access & ~RegistryPermissionAccess.AllAccess) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access)); - } - - private void ExclusiveAccess( RegistryPermissionAccess access ) - { - if (access == RegistryPermissionAccess.NoAccess) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - - if (((int) access & ((int)access-1)) != 0) - { - throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") ); - } - } - - private bool IsEmpty() - { - return (!m_unrestricted && - (this.m_read == null || this.m_read.IsEmpty()) && - (this.m_write == null || this.m_write.IsEmpty()) && - (this.m_create == null || this.m_create.IsEmpty()) && - (this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) && - (this.m_changeAcl == null || this.m_changeAcl.IsEmpty())); - } - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public bool IsUnrestricted() - { - return m_unrestricted; - } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return this.IsEmpty(); - } - - RegistryPermission operand = target as RegistryPermission; - if (operand == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - - if (operand.IsUnrestricted()) - return true; - else if (this.IsUnrestricted()) - return false; - else - return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) && - (this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) && - (this.m_create == null || this.m_create.IsSubsetOf( operand.m_create )) && - (this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) && - (this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl ))); - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - { - return null; - } - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - else if (this.IsUnrestricted()) - { - return target.Copy(); - } - - RegistryPermission operand = (RegistryPermission)target; - if (operand.IsUnrestricted()) - { - return this.Copy(); - } - - - StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read ); - StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write ); - StringExpressionSet intersectCreate = this.m_create == null ? null : this.m_create.Intersect( operand.m_create ); - StringExpressionSet intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl ); - StringExpressionSet intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl ); - - if ((intersectRead == null || intersectRead.IsEmpty()) && - (intersectWrite == null || intersectWrite.IsEmpty()) && - (intersectCreate == null || intersectCreate.IsEmpty()) && - (intersectViewAcl == null || intersectViewAcl.IsEmpty()) && - (intersectChangeAcl == null || intersectChangeAcl.IsEmpty())) - { - return null; - } - - RegistryPermission intersectPermission = new RegistryPermission(PermissionState.None); - intersectPermission.m_unrestricted = false; - intersectPermission.m_read = intersectRead; - intersectPermission.m_write = intersectWrite; - intersectPermission.m_create = intersectCreate; - intersectPermission.m_viewAcl = intersectViewAcl; - intersectPermission.m_changeAcl = intersectChangeAcl; - - return intersectPermission; - } - - public override IPermission Union(IPermission other) - { - if (other == null) - { - return this.Copy(); - } - else if (!VerifyType(other)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - RegistryPermission operand = (RegistryPermission)other; - - if (this.IsUnrestricted() || operand.IsUnrestricted()) - { - return new RegistryPermission( PermissionState.Unrestricted ); - } - - StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read ); - StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write ); - StringExpressionSet unionCreate = this.m_create == null ? operand.m_create : this.m_create.Union( operand.m_create ); - StringExpressionSet unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl ); - StringExpressionSet unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl ); - - if ((unionRead == null || unionRead.IsEmpty()) && - (unionWrite == null || unionWrite.IsEmpty()) && - (unionCreate == null || unionCreate.IsEmpty()) && - (unionViewAcl == null || unionViewAcl.IsEmpty()) && - (unionChangeAcl == null || unionChangeAcl.IsEmpty())) - { - return null; - } - - RegistryPermission unionPermission = new RegistryPermission(PermissionState.None); - unionPermission.m_unrestricted = false; - unionPermission.m_read = unionRead; - unionPermission.m_write = unionWrite; - unionPermission.m_create = unionCreate; - unionPermission.m_viewAcl = unionViewAcl; - unionPermission.m_changeAcl = unionChangeAcl; - - return unionPermission; - } - - - public override IPermission Copy() - { - RegistryPermission copy = new RegistryPermission(PermissionState.None); - if (this.m_unrestricted) - { - copy.m_unrestricted = true; - } - else - { - copy.m_unrestricted = false; - if (this.m_read != null) - { - copy.m_read = this.m_read.Copy(); - } - if (this.m_write != null) - { - copy.m_write = this.m_write.Copy(); - } - if (this.m_create != null) - { - copy.m_create = this.m_create.Copy(); - } - if (this.m_viewAcl != null) - { - copy.m_viewAcl = this.m_viewAcl.Copy(); - } - if (this.m_changeAcl != null) - { - copy.m_changeAcl = this.m_changeAcl.Copy(); - } - } - return copy; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return RegistryPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.RegistryPermissionIndex; - } - - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs deleted file mode 100644 index cf3002989d..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/SecurityPermission.cs +++ /dev/null @@ -1,270 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.IO; - using System.Security.Util; - using System.Text; - using System.Threading; - using System.Runtime.Remoting; - using System.Security; - using System.Runtime.Serialization; - using System.Reflection; - using System.Globalization; - using System.Diagnostics.Contracts; - - [Serializable] - [Flags] - [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.")] - public enum SecurityPermissionFlag - { - NoFlags = 0x00, - /* The following enum value is used in the EE (ASSERT_PERMISSION in security.cpp) - * Should this value change, make corresponding changes there - */ - Assertion = 0x01, - UnmanagedCode = 0x02, // Update vm\Security.h if you change this ! - SkipVerification = 0x04, // Update vm\Security.h if you change this ! - Execution = 0x08, - ControlThread = 0x10, - ControlEvidence = 0x20, - ControlPolicy = 0x40, - SerializationFormatter = 0x80, - ControlDomainPolicy = 0x100, - ControlPrincipal = 0x200, - ControlAppDomain = 0x400, - RemotingConfiguration = 0x800, - Infrastructure = 0x1000, - BindingRedirects = 0x2000, - AllFlags = 0x3fff, - } - -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class SecurityPermission - : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { -#pragma warning disable 618 - private SecurityPermissionFlag m_flags; -#pragma warning restore 618 - - // - // Public Constructors - // - - public SecurityPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - SetUnrestricted( true ); - } - else if (state == PermissionState.None) - { - SetUnrestricted( false ); - Reset(); - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - - // SecurityPermission - // -#pragma warning disable 618 - public SecurityPermission(SecurityPermissionFlag flag) -#pragma warning restore 618 - { - VerifyAccess(flag); - - SetUnrestricted(false); - m_flags = flag; - } - - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED MODIFIERS - // - //------------------------------------------------------ - - - private void SetUnrestricted(bool unrestricted) - { - if (unrestricted) - { -#pragma warning disable 618 - m_flags = SecurityPermissionFlag.AllFlags; -#pragma warning restore 618 - } - } - - private void Reset() - { -#pragma warning disable 618 - m_flags = SecurityPermissionFlag.NoFlags; -#pragma warning restore 618 - } - - -#pragma warning disable 618 - public SecurityPermissionFlag Flags -#pragma warning restore 618 - { - set - { - VerifyAccess(value); - - m_flags = value; - } - - get - { - return m_flags; - } - } - - // - // CodeAccessPermission methods - // - - /* - * IPermission interface implementation - */ - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - return m_flags == 0; - } - - SecurityPermission operand = target as SecurityPermission; - if (operand != null) - { - return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0; - } - else - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - } - - public override IPermission Union(IPermission target) { - if (target == null) return(this.Copy()); - if (!VerifyType(target)) { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - SecurityPermission sp_target = (SecurityPermission) target; - if (sp_target.IsUnrestricted() || IsUnrestricted()) { - return(new SecurityPermission(PermissionState.Unrestricted)); - } -#pragma warning disable 618 - SecurityPermissionFlag flag_union = (SecurityPermissionFlag)(m_flags | sp_target.m_flags); -#pragma warning restore 618 - return(new SecurityPermission(flag_union)); - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - SecurityPermission operand = (SecurityPermission)target; -#pragma warning disable 618 - SecurityPermissionFlag isectFlags = SecurityPermissionFlag.NoFlags; -#pragma warning restore 618 - - if (operand.IsUnrestricted()) - { - if (this.IsUnrestricted()) - return new SecurityPermission(PermissionState.Unrestricted); - else -#pragma warning disable 618 - isectFlags = (SecurityPermissionFlag)this.m_flags; -#pragma warning restore 618 - } - else if (this.IsUnrestricted()) - { -#pragma warning disable 618 - isectFlags = (SecurityPermissionFlag)operand.m_flags; -#pragma warning restore 618 - } - else - { -#pragma warning disable 618 - isectFlags = (SecurityPermissionFlag)m_flags & (SecurityPermissionFlag)operand.m_flags; -#pragma warning restore 618 - } - - if (isectFlags == 0) - return null; - else - return new SecurityPermission(isectFlags); - } - - public override IPermission Copy() - { - if (IsUnrestricted()) - return new SecurityPermission(PermissionState.Unrestricted); - else -#pragma warning disable 618 - return new SecurityPermission((SecurityPermissionFlag)m_flags); -#pragma warning restore 618 - } - - public bool IsUnrestricted() - { -#pragma warning disable 618 - return m_flags == SecurityPermissionFlag.AllFlags; -#pragma warning restore 618 - } - - private -#pragma warning disable 618 - void VerifyAccess(SecurityPermissionFlag type) -#pragma warning restore 618 - { -#pragma warning disable 618 - if ((type & ~SecurityPermissionFlag.AllFlags) != 0) -#pragma warning restore 618 - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type)); - Contract.EndContractBlock(); - } - - // - // Object Overrides - // - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return SecurityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.SecurityPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs deleted file mode 100644 index ff38d515a1..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/SiteIdentityPermission.cs +++ /dev/null @@ -1,251 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using SiteString = System.Security.Util.SiteString; - using System.Text; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - using System.Runtime.Serialization; - - [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_SERIALIZATION - [Serializable] -#endif - sealed public class SiteIdentityPermission : CodeAccessPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - [OptionalField(VersionAdded = 2)] - private bool m_unrestricted; - [OptionalField(VersionAdded = 2)] - private SiteString[] m_sites; - - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - - public SiteIdentityPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_unrestricted = true; - } - else if (state == PermissionState.None) - { - m_unrestricted = false; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public SiteIdentityPermission( String site ) - { - Site = site; - } - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - public String Site - { - set - { - m_unrestricted = false; - m_sites = new SiteString[1]; - m_sites[0] = new SiteString( value ); - } - - get - { - if(m_sites == null) - return ""; - if(m_sites.Length == 1) - return m_sites[0].ToString(); - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); - } - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - public override IPermission Copy() - { - SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None ); - perm.m_unrestricted = this.m_unrestricted; - if (this.m_sites != null) - { - perm.m_sites = new SiteString[this.m_sites.Length]; - int n; - for(n = 0; n < this.m_sites.Length; n++) - perm.m_sites[n] = (SiteString)this.m_sites[n].Copy(); - } - return perm; - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - if(m_unrestricted) - return false; - if(m_sites == null) - return true; - if(m_sites.Length == 0) - return true; - return false; - } - SiteIdentityPermission that = target as SiteIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(that.m_unrestricted) - return true; - if(m_unrestricted) - return false; - if(this.m_sites != null) - { - foreach(SiteString ssThis in this.m_sites) - { - bool bOK = false; - if(that.m_sites != null) - { - foreach(SiteString ssThat in that.m_sites) - { - if(ssThis.IsSubsetOf(ssThat)) - { - bOK = true; - break; - } - } - } - if(!bOK) - return false; - } - } - return true; - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - SiteIdentityPermission that = target as SiteIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted && that.m_unrestricted) - { - SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if(this.m_unrestricted) - return that.Copy(); - if(that.m_unrestricted) - return this.Copy(); - if(this.m_sites == null || that.m_sites == null || this.m_sites.Length == 0 || that.m_sites.Length == 0) - return null; - List<SiteString> alSites = new List<SiteString>(); - foreach(SiteString ssThis in this.m_sites) - { - foreach(SiteString ssThat in that.m_sites) - { - SiteString ssInt = (SiteString)ssThis.Intersect(ssThat); - if(ssInt != null) - alSites.Add(ssInt); - } - } - if(alSites.Count == 0) - return null; - SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None); - result.m_sites = alSites.ToArray(); - return result; - } - - public override IPermission Union(IPermission target) - { - if (target == null) - { - if((this.m_sites == null || this.m_sites.Length == 0) && !this.m_unrestricted) - return null; - return this.Copy(); - } - SiteIdentityPermission that = target as SiteIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted || that.m_unrestricted) - { - SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if (this.m_sites == null || this.m_sites.Length == 0) - { - if(that.m_sites == null || that.m_sites.Length == 0) - return null; - return that.Copy(); - } - if(that.m_sites == null || that.m_sites.Length == 0) - return this.Copy(); - List<SiteString> alSites = new List<SiteString>(); - foreach(SiteString ssThis in this.m_sites) - alSites.Add(ssThis); - foreach(SiteString ssThat in that.m_sites) - { - bool bDupe = false; - foreach(SiteString ss in alSites) - { - if(ssThat.Equals(ss)) - { - bDupe = true; - break; - } - } - if(!bDupe) - alSites.Add(ssThat); - } - SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None); - result.m_sites = alSites.ToArray(); - return result; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return SiteIdentityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.SiteIdentityPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs deleted file mode 100644 index f09d84de34..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/StrongNameIdentityPermission.cs +++ /dev/null @@ -1,401 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Security.Util; - using System.IO; - using String = System.String; - using Version = System.Version; - using System.Security.Policy; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - using System.Diagnostics.Contracts; - - // The only difference between this class and System.Security.Policy.StrongName is that this one - // allows m_name to be null. We should merge this class with System.Security.Policy.StrongName - [Serializable] - sealed internal class StrongName2 - { - public StrongNamePublicKeyBlob m_publicKeyBlob; - public String m_name; - public Version m_version; - - public StrongName2(StrongNamePublicKeyBlob publicKeyBlob, String name, Version version) - { - m_publicKeyBlob = publicKeyBlob; - m_name = name; - m_version = version; - } - - public StrongName2 Copy() - { - return new StrongName2(m_publicKeyBlob, m_name, m_version); - } - - public bool IsSubsetOf(StrongName2 target) - { - // This StrongName2 is a subset of the target if it's public key blob is null no matter what - if (this.m_publicKeyBlob == null) - return true; - - // Subsets are always false if the public key blobs do not match - if (!this.m_publicKeyBlob.Equals( target.m_publicKeyBlob )) - return false; - - // We use null in strings to represent the "Anything" state. - // Therefore, the logic to detect an individual subset is: - // - // 1. If the this string is null ("Anything" is a subset of any other). - // 2. If the this string and target string are the same (equality is sufficient for a subset). - // - // The logic is reversed here to discover things that are not subsets. - if (this.m_name != null) - { - if (target.m_name == null || !System.Security.Policy.StrongName.CompareNames( target.m_name, this.m_name )) - return false; - } - - if ((Object) this.m_version != null) - { - if ((Object) target.m_version == null || - target.m_version.CompareTo( this.m_version ) != 0) - { - return false; - } - } - - return true; - } - - public StrongName2 Intersect(StrongName2 target) - { - if (target.IsSubsetOf( this )) - return target.Copy(); - else if (this.IsSubsetOf( target )) - return this.Copy(); - else - return null; - } - - public bool Equals(StrongName2 target) - { - if (!target.IsSubsetOf(this)) - return false; - if (!this.IsSubsetOf(target)) - return false; - return true; - } - } - - - -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class StrongNameIdentityPermission : CodeAccessPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - - private bool m_unrestricted; - private StrongName2[] m_strongNames; - - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - - public StrongNameIdentityPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_unrestricted = true; - } - else if (state == PermissionState.None) - { - m_unrestricted = false; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version ) - { - if (blob == null) - throw new ArgumentNullException( nameof(blob) ); - if (name != null && name.Equals( "" )) - throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) ); - Contract.EndContractBlock(); - m_unrestricted = false; - m_strongNames = new StrongName2[1]; - m_strongNames[0] = new StrongName2(blob, name, version); - } - - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - public StrongNamePublicKeyBlob PublicKey - { - set - { - if (value == null) - throw new ArgumentNullException( nameof(PublicKey) ); - Contract.EndContractBlock(); - m_unrestricted = false; - if(m_strongNames != null && m_strongNames.Length == 1) - m_strongNames[0].m_publicKeyBlob = value; - else - { - m_strongNames = new StrongName2[1]; - m_strongNames[0] = new StrongName2(value, "", new Version()); - } - } - - get - { - if(m_strongNames == null || m_strongNames.Length == 0) - return null; - if(m_strongNames.Length > 1) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); - return m_strongNames[0].m_publicKeyBlob; - } - } - - public String Name - { - set - { - if (value != null && value.Length == 0) - throw new ArgumentException( Environment.GetResourceString("Argument_EmptyName" )); - Contract.EndContractBlock(); - m_unrestricted = false; - if(m_strongNames != null && m_strongNames.Length == 1) - m_strongNames[0].m_name = value; - else - { - m_strongNames = new StrongName2[1]; - m_strongNames[0] = new StrongName2(null, value, new Version()); - } - } - - get - { - if(m_strongNames == null || m_strongNames.Length == 0) - return ""; - if(m_strongNames.Length > 1) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); - return m_strongNames[0].m_name; - } - } - - public Version Version - { - set - { - m_unrestricted = false; - if(m_strongNames != null && m_strongNames.Length == 1) - m_strongNames[0].m_version = value; - else - { - m_strongNames = new StrongName2[1]; - m_strongNames[0] = new StrongName2(null, "", value); - } - } - - get - { - if(m_strongNames == null || m_strongNames.Length == 0) - return new Version(); - if(m_strongNames.Length > 1) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); - return m_strongNames[0].m_version; - } - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - - public override IPermission Copy() - { - StrongNameIdentityPermission perm = new StrongNameIdentityPermission(PermissionState.None); - perm.m_unrestricted = this.m_unrestricted; - if(this.m_strongNames != null) - { - perm.m_strongNames = new StrongName2[this.m_strongNames.Length]; - int n; - for(n = 0; n < this.m_strongNames.Length; n++) - perm.m_strongNames[n] = this.m_strongNames[n].Copy(); - } - return perm; - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - if(m_unrestricted) - return false; - if(m_strongNames == null) - return true; - if(m_strongNames.Length == 0) - return true; - return false; - } - StrongNameIdentityPermission that = target as StrongNameIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(that.m_unrestricted) - return true; - if(m_unrestricted) - return false; - if(this.m_strongNames != null) - { - foreach(StrongName2 snThis in m_strongNames) - { - bool bOK = false; - if(that.m_strongNames != null) - { - foreach(StrongName2 snThat in that.m_strongNames) - { - if(snThis.IsSubsetOf(snThat)) - { - bOK = true; - break; - } - } - } - if(!bOK) - return false; - } - } - return true; - } - - - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - StrongNameIdentityPermission that = target as StrongNameIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted && that.m_unrestricted) - { - StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if(this.m_unrestricted) - return that.Copy(); - if(that.m_unrestricted) - return this.Copy(); - if(this.m_strongNames == null || that.m_strongNames == null || this.m_strongNames.Length == 0 || that.m_strongNames.Length == 0) - return null; - List<StrongName2> alStrongNames = new List<StrongName2>(); - foreach(StrongName2 snThis in this.m_strongNames) - { - foreach(StrongName2 snThat in that.m_strongNames) - { - StrongName2 snInt = (StrongName2)snThis.Intersect(snThat); - if(snInt != null) - alStrongNames.Add(snInt); - } - } - if(alStrongNames.Count == 0) - return null; - StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None); - result.m_strongNames = alStrongNames.ToArray(); - return result; - } - - public override IPermission Union(IPermission target) - { - if (target == null) - { - if((this.m_strongNames == null || this.m_strongNames.Length == 0) && !this.m_unrestricted) - return null; - return this.Copy(); - } - StrongNameIdentityPermission that = target as StrongNameIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted || that.m_unrestricted) - { - StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if (this.m_strongNames == null || this.m_strongNames.Length == 0) - { - if(that.m_strongNames == null || that.m_strongNames.Length == 0) - return null; - return that.Copy(); - } - if(that.m_strongNames == null || that.m_strongNames.Length == 0) - return this.Copy(); - List<StrongName2> alStrongNames = new List<StrongName2>(); - foreach(StrongName2 snThis in this.m_strongNames) - alStrongNames.Add(snThis); - foreach(StrongName2 snThat in that.m_strongNames) - { - bool bDupe = false; - foreach(StrongName2 sn in alStrongNames) - { - if(snThat.Equals(sn)) - { - bDupe = true; - break; - } - } - if(!bDupe) - alStrongNames.Add(snThat); - } - StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None); - result.m_strongNames = alStrongNames.ToArray(); - return result; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return StrongNameIdentityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.StrongNameIdentityPermissionIndex; - } - - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs b/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs deleted file mode 100644 index 823eaba938..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/StrongNamePublicKeyBlob.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Security.Util; - using System.Diagnostics.Contracts; - - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] sealed public class StrongNamePublicKeyBlob - { - internal byte[] PublicKey; - - internal StrongNamePublicKeyBlob() - { - } - - public StrongNamePublicKeyBlob( byte[] publicKey ) - { - if (publicKey == null) - throw new ArgumentNullException( nameof(PublicKey) ); - Contract.EndContractBlock(); - - this.PublicKey = new byte[publicKey.Length]; - Array.Copy( publicKey, 0, this.PublicKey, 0, publicKey.Length ); - } - - internal StrongNamePublicKeyBlob( String publicKey ) - { - this.PublicKey = Hex.DecodeHexString( publicKey ); - } - - private static bool CompareArrays( byte[] first, byte[] second ) - { - if (first.Length != second.Length) - { - return false; - } - - int count = first.Length; - for (int i = 0; i < count; ++i) - { - if (first[i] != second[i]) - return false; - } - - return true; - } - - - internal bool Equals( StrongNamePublicKeyBlob blob ) - { - if (blob == null) - return false; - else - return CompareArrays( this.PublicKey, blob.PublicKey ); - } - - public override bool Equals( Object obj ) - { - if (obj == null || !(obj is StrongNamePublicKeyBlob)) - return false; - - return this.Equals( (StrongNamePublicKeyBlob)obj ); - } - - static private int GetByteArrayHashCode( byte[] baData ) - { - if (baData == null) - return 0; - - int accumulator = 0; - - for (int i = 0; i < baData.Length; ++i) - { - accumulator = (accumulator << 8) ^ (int)baData[i] ^ (accumulator >> 24); - } - - return accumulator; - } - - public override int GetHashCode() - { - return GetByteArrayHashCode( PublicKey ); - } - - public override String ToString() - { - return Hex.EncodeHexString( PublicKey ); - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs b/src/mscorlib/src/System/Security/Permissions/UIPermission.cs deleted file mode 100644 index 4abe801e41..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/UIPermission.cs +++ /dev/null @@ -1,327 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Security; - using System.Security.Util; - using System.IO; - using System.Runtime.Serialization; - using System.Reflection; - using System.Collections; - using System.Globalization; - using System.Diagnostics.Contracts; - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public enum UIPermissionWindow - { - // No window use allowed at all. - NoWindows = 0x0, - - // Only allow safe subwindow use (for embedded components). - SafeSubWindows = 0x01, - - // Safe top-level window use only (see specification for details). - SafeTopLevelWindows = 0x02, - - // All windows and all event may be used. - AllWindows = 0x03, - - } - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public enum UIPermissionClipboard - { - // No clipboard access is allowed. - NoClipboard = 0x0, - - // Paste from the same app domain only. - OwnClipboard = 0x1, - - // Any clipboard access is allowed. - AllClipboard = 0x2, - - } - - -[System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - sealed public class UIPermission - : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - - private UIPermissionWindow m_windowFlag; - private UIPermissionClipboard m_clipboardFlag; - - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - public UIPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - SetUnrestricted( true ); - } - else if (state == PermissionState.None) - { - SetUnrestricted( false ); - Reset(); - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public UIPermission(UIPermissionWindow windowFlag, UIPermissionClipboard clipboardFlag ) - { - VerifyWindowFlag( windowFlag ); - VerifyClipboardFlag( clipboardFlag ); - - m_windowFlag = windowFlag; - m_clipboardFlag = clipboardFlag; - } - - public UIPermission(UIPermissionWindow windowFlag ) - { - VerifyWindowFlag( windowFlag ); - - m_windowFlag = windowFlag; - } - - public UIPermission(UIPermissionClipboard clipboardFlag ) - { - VerifyClipboardFlag( clipboardFlag ); - - m_clipboardFlag = clipboardFlag; - } - - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - public UIPermissionWindow Window - { - set - { - VerifyWindowFlag(value); - - m_windowFlag = value; - } - - get - { - return m_windowFlag; - } - } - - public UIPermissionClipboard Clipboard - { - set - { - VerifyClipboardFlag(value); - - m_clipboardFlag = value; - } - - get - { - return m_clipboardFlag; - } - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS - // - //------------------------------------------------------ - - private static void VerifyWindowFlag(UIPermissionWindow flag) - { - if (flag < UIPermissionWindow.NoWindows || flag > UIPermissionWindow.AllWindows) - { - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag)); - } - Contract.EndContractBlock(); - } - - private static void VerifyClipboardFlag(UIPermissionClipboard flag) - { - if (flag < UIPermissionClipboard.NoClipboard || flag > UIPermissionClipboard.AllClipboard) - { - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag)); - } - Contract.EndContractBlock(); - } - - private void Reset() - { - m_windowFlag = UIPermissionWindow.NoWindows; - m_clipboardFlag = UIPermissionClipboard.NoClipboard; - } - - private void SetUnrestricted( bool unrestricted ) - { - if (unrestricted) - { - m_windowFlag = UIPermissionWindow.AllWindows; - m_clipboardFlag = UIPermissionClipboard.AllClipboard; - } - } - -#if false - //------------------------------------------------------ - // - // OBJECT METHOD OVERRIDES - // - //------------------------------------------------------ - public String ToString() - { - #if _DEBUG - StringBuilder sb = new StringBuilder(); - sb.Append("UIPermission("); - if (IsUnrestricted()) - { - sb.Append("Unrestricted"); - } - else - { - sb.Append(m_stateNameTableWindow[m_windowFlag]); - sb.Append(", "); - sb.Append(m_stateNameTableClipboard[m_clipboardFlag]); - } - - sb.Append(")"); - return sb.ToString(); - #else - return super.ToString(); - #endif - } -#endif - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public bool IsUnrestricted() - { - return m_windowFlag == UIPermissionWindow.AllWindows && m_clipboardFlag == UIPermissionClipboard.AllClipboard; - } - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - // Only safe subset if this is empty - return m_windowFlag == UIPermissionWindow.NoWindows && m_clipboardFlag == UIPermissionClipboard.NoClipboard; - } - - try - { - UIPermission operand = (UIPermission)target; - if (operand.IsUnrestricted()) - return true; - else if (this.IsUnrestricted()) - return false; - else - return this.m_windowFlag <= operand.m_windowFlag && this.m_clipboardFlag <= operand.m_clipboardFlag; - } - catch (InvalidCastException) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - { - return null; - } - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - UIPermission operand = (UIPermission)target; - UIPermissionWindow isectWindowFlags = m_windowFlag < operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag; - UIPermissionClipboard isectClipboardFlags = m_clipboardFlag < operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag; - if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard) - return null; - else - return new UIPermission(isectWindowFlags, isectClipboardFlags); - } - - public override IPermission Union(IPermission target) - { - if (target == null) - { - return this.Copy(); - } - else if (!VerifyType(target)) - { - throw new - ArgumentException( - Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) - ); - } - - UIPermission operand = (UIPermission)target; - UIPermissionWindow isectWindowFlags = m_windowFlag > operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag; - UIPermissionClipboard isectClipboardFlags = m_clipboardFlag > operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag; - if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard) - return null; - else - return new UIPermission(isectWindowFlags, isectClipboardFlags); - } - - public override IPermission Copy() - { - return new UIPermission(this.m_windowFlag, this.m_clipboardFlag); - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return UIPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.UIPermissionIndex; - } - - } - - -} diff --git a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs deleted file mode 100644 index 0883bf8979..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/URLIdentityPermission.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Security.Util; - using System.IO; - using System.Text; - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - using System.Runtime.Serialization; - using System.Diagnostics.Contracts; - - [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_SERIALIZATION - [Serializable] -#endif - sealed public class UrlIdentityPermission : CodeAccessPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - - [OptionalField(VersionAdded = 2)] - private bool m_unrestricted; - [OptionalField(VersionAdded = 2)] - private URLString[] m_urls; - - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - - public UrlIdentityPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_unrestricted = true; - } - else if (state == PermissionState.None) - { - m_unrestricted = false; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public UrlIdentityPermission( String site ) - { - if (site == null) - throw new ArgumentNullException( nameof(site) ); - Contract.EndContractBlock(); - Url = site; - } - - internal UrlIdentityPermission( URLString site ) - { - m_unrestricted = false; - m_urls = new URLString[1]; - m_urls[0] = site; - } - - // Internal function to append all the urls in m_urls to the input originList - internal void AppendOrigin(ArrayList originList) - { - if (m_urls == null) - originList.Add(""); - else - { - int n; - for(n = 0; n < this.m_urls.Length; n++) - originList.Add(m_urls[n].ToString()); - } - } - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - public String Url - { - set - { - m_unrestricted = false; - if(value == null || value.Length == 0) - m_urls = null; - else - { - m_urls = new URLString[1]; - m_urls[0] = new URLString( value ); - } - } - - get - { - if(m_urls == null) - return ""; - if(m_urls.Length == 1) - return m_urls[0].ToString(); - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); - } - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - - public override IPermission Copy() - { - UrlIdentityPermission perm = new UrlIdentityPermission( PermissionState.None ); - perm.m_unrestricted = this.m_unrestricted; - if (this.m_urls != null) - { - perm.m_urls = new URLString[this.m_urls.Length]; - int n; - for(n = 0; n < this.m_urls.Length; n++) - perm.m_urls[n] = (URLString)this.m_urls[n].Copy(); - } - return perm; - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - { - if(m_unrestricted) - return false; - if(m_urls == null) - return true; - if(m_urls.Length == 0) - return true; - return false; - } - UrlIdentityPermission that = target as UrlIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(that.m_unrestricted) - return true; - if(m_unrestricted) - return false; - if(this.m_urls != null) - { - foreach(URLString usThis in this.m_urls) - { - bool bOK = false; - if(that.m_urls != null) - { - foreach(URLString usThat in that.m_urls) - { - if(usThis.IsSubsetOf(usThat)) - { - bOK = true; - break; - } - } - } - if(!bOK) - return false; - } - } - return true; - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - UrlIdentityPermission that = target as UrlIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted && that.m_unrestricted) - { - UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if(this.m_unrestricted) - return that.Copy(); - if(that.m_unrestricted) - return this.Copy(); - if(this.m_urls == null || that.m_urls == null || this.m_urls.Length == 0 || that.m_urls.Length == 0) - return null; - List<URLString> alUrls = new List<URLString>(); - foreach(URLString usThis in this.m_urls) - { - foreach(URLString usThat in that.m_urls) - { - URLString usInt = (URLString)usThis.Intersect(usThat); - if(usInt != null) - alUrls.Add(usInt); - } - } - if(alUrls.Count == 0) - return null; - UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None); - result.m_urls = alUrls.ToArray(); - return result; - } - - public override IPermission Union(IPermission target) - { - if (target == null) - { - if((this.m_urls == null || this.m_urls.Length == 0) && !this.m_unrestricted) - return null; - return this.Copy(); - } - UrlIdentityPermission that = target as UrlIdentityPermission; - if(that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - if(this.m_unrestricted || that.m_unrestricted) - { - UrlIdentityPermission res = new UrlIdentityPermission(PermissionState.None); - res.m_unrestricted = true; - return res; - } - if (this.m_urls == null || this.m_urls.Length == 0) - { - if(that.m_urls == null || that.m_urls.Length == 0) - return null; - return that.Copy(); - } - if(that.m_urls == null || that.m_urls.Length == 0) - return this.Copy(); - List<URLString> alUrls = new List<URLString>(); - foreach(URLString usThis in this.m_urls) - alUrls.Add(usThis); - foreach(URLString usThat in that.m_urls) - { - bool bDupe = false; - foreach(URLString us in alUrls) - { - if(usThat.Equals(us)) - { - bDupe = true; - break; - } - } - if(!bDupe) - alUrls.Add(usThat); - } - UrlIdentityPermission result = new UrlIdentityPermission(PermissionState.None); - result.m_urls = alUrls.ToArray(); - return result; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return UrlIdentityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.UrlIdentityPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs b/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs deleted file mode 100644 index 9023c7eece..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/ZoneIdentityPermission.cs +++ /dev/null @@ -1,208 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Globalization; - using System.Runtime.Serialization; - using System.Collections; - using System.Collections.Generic; - using System.Diagnostics.Contracts; - - [System.Runtime.InteropServices.ComVisible(true)] -#if FEATURE_SERIALIZATION - [Serializable] -#endif - sealed public class ZoneIdentityPermission : CodeAccessPermission, IBuiltInPermission - { - //------------------------------------------------------ - // - // PRIVATE STATE DATA - // - //------------------------------------------------------ - - // Zone Enum Flag - // ----- ----- ----- - // NoZone -1 0x00 - // MyComputer 0 0x01 (1 << 0) - // Intranet 1 0x02 (1 << 1) - // Trusted 2 0x04 (1 << 2) - // Internet 3 0x08 (1 << 3) - // Untrusted 4 0x10 (1 << 4) - - private const uint AllZones = 0x1f; - [OptionalField(VersionAdded = 2)] - private uint m_zones; - - //------------------------------------------------------ - // - // PUBLIC CONSTRUCTORS - // - //------------------------------------------------------ - - public ZoneIdentityPermission(PermissionState state) - { - if (state == PermissionState.Unrestricted) - { - m_zones = AllZones; - } - else if (state == PermissionState.None) - { - m_zones = 0; - } - else - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - } - } - - public ZoneIdentityPermission( SecurityZone zone ) - { - this.SecurityZone = zone; - } - - internal ZoneIdentityPermission( uint zones ) - { - m_zones = (zones & AllZones); - } - - // Internal function to append all the Zone in this permission to the input ArrayList - internal void AppendZones(ArrayList zoneList) - { - int nEnum = 0; - uint nFlag; - for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) - { - if((m_zones & nFlag) != 0) - { - zoneList.Add((SecurityZone)nEnum); - } - nEnum++; - } - } - - //------------------------------------------------------ - // - // PUBLIC ACCESSOR METHODS - // - //------------------------------------------------------ - - public SecurityZone SecurityZone - { - set - { - VerifyZone( value ); - if(value == SecurityZone.NoZone) - m_zones = 0; - else - m_zones = (uint)1 << (int)value; - } - - get - { - SecurityZone z = SecurityZone.NoZone; - int nEnum = 0; - uint nFlag; - for(nFlag = 1; nFlag < AllZones; nFlag <<= 1) - { - if((m_zones & nFlag) != 0) - { - if(z == SecurityZone.NoZone) - z = (SecurityZone)nEnum; - else - return SecurityZone.NoZone; - } - nEnum++; - } - return z; - } - } - - //------------------------------------------------------ - // - // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS - // - //------------------------------------------------------ - - private static void VerifyZone( SecurityZone zone ) - { - if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) - { - throw new ArgumentException( Environment.GetResourceString("Argument_IllegalZone") ); - } - Contract.EndContractBlock(); - } - - - //------------------------------------------------------ - // - // CODEACCESSPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - //------------------------------------------------------ - // - // IPERMISSION IMPLEMENTATION - // - //------------------------------------------------------ - - - public override IPermission Copy() - { - return new ZoneIdentityPermission(this.m_zones); - } - - public override bool IsSubsetOf(IPermission target) - { - if (target == null) - return this.m_zones == 0; - - ZoneIdentityPermission that = target as ZoneIdentityPermission; - if (that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - return (this.m_zones & that.m_zones) == this.m_zones; - } - - public override IPermission Intersect(IPermission target) - { - if (target == null) - return null; - - ZoneIdentityPermission that = target as ZoneIdentityPermission; - if (that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - uint newZones = this.m_zones & that.m_zones; - if(newZones == 0) - return null; - return new ZoneIdentityPermission(newZones); - } - - public override IPermission Union(IPermission target) - { - if (target == null) - return this.m_zones != 0 ? this.Copy() : null; - - ZoneIdentityPermission that = target as ZoneIdentityPermission; - if (that == null) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - return new ZoneIdentityPermission(this.m_zones | that.m_zones); - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex() - { - return ZoneIdentityPermission.GetTokenIndex(); - } - - internal static int GetTokenIndex() - { - return BuiltInPermissionIndex.ZoneIdentityPermissionIndex; - } - - } -} diff --git a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs b/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs deleted file mode 100644 index d4f1c273c6..0000000000 --- a/src/mscorlib/src/System/Security/Permissions/keycontainerpermission.cs +++ /dev/null @@ -1,634 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - using System; - using System.Collections; - using System.Collections.Generic; -#if FEATURE_CRYPTO - using System.Security.Cryptography; -#endif - using System.Security.Util; - using System.Globalization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - -[Serializable] - [Flags] - [System.Runtime.InteropServices.ComVisible(true)] - public enum KeyContainerPermissionFlags { - NoFlags = 0x0000, - - Create = 0x0001, - Open = 0x0002, - Delete = 0x0004, - - Import = 0x0010, - Export = 0x0020, - - Sign = 0x0100, - Decrypt = 0x0200, - - ViewAcl = 0x1000, - ChangeAcl = 0x2000, - - AllFlags = 0x3337 - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class KeyContainerPermissionAccessEntry { - private string m_keyStore; - private string m_providerName; - private int m_providerType; - private string m_keyContainerName; - private int m_keySpec; - private KeyContainerPermissionFlags m_flags; - - internal KeyContainerPermissionAccessEntry(KeyContainerPermissionAccessEntry accessEntry) : - this (accessEntry.KeyStore, accessEntry.ProviderName, accessEntry.ProviderType, accessEntry.KeyContainerName, - accessEntry.KeySpec, accessEntry.Flags) { - } - - public KeyContainerPermissionAccessEntry(string keyContainerName, KeyContainerPermissionFlags flags) : - this (null, null, -1, keyContainerName, -1, flags) { - } - -#if FEATURE_CRYPTO - public KeyContainerPermissionAccessEntry(CspParameters parameters, KeyContainerPermissionFlags flags) : - this((parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore ? "Machine" : "User", - parameters.ProviderName, - parameters.ProviderType, - parameters.KeyContainerName, - parameters.KeyNumber, - flags) { - } -#endif - - public KeyContainerPermissionAccessEntry(string keyStore, string providerName, int providerType, - string keyContainerName, int keySpec, KeyContainerPermissionFlags flags) { - m_providerName = (providerName == null ? "*" : providerName); - m_providerType = providerType; - m_keyContainerName = (keyContainerName == null ? "*" : keyContainerName); - m_keySpec = keySpec; - KeyStore = keyStore; - Flags = flags; - } - - public string KeyStore { - get { - return m_keyStore; - } - set { - // Unrestricted entries are invalid; they should not be allowed. - if (IsUnrestrictedEntry(value, this.ProviderName, this.ProviderType, this.KeyContainerName, this.KeySpec)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry")); - - if (value == null) { - m_keyStore = "*"; - } else { - if (value != "User" && value != "Machine" && value != "*") - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKeyStore", value), nameof(value)); - m_keyStore = value; - } - } - } - - public string ProviderName { - get { - return m_providerName; - } - set { - // Unrestricted entries are invalid; they should not be allowed. - if (IsUnrestrictedEntry(this.KeyStore, value, this.ProviderType, this.KeyContainerName, this.KeySpec)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry")); - - if (value == null) - m_providerName = "*"; - else - m_providerName = value; - } - } - - public int ProviderType { - get { - return m_providerType; - } - set { - // Unrestricted entries are invalid; they should not be allowed. - if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, value, this.KeyContainerName, this.KeySpec)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry")); - - m_providerType = value; - } - } - - public string KeyContainerName { - get { - return m_keyContainerName; - } - set { - // Unrestricted entries are invalid; they should not be allowed. - if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, this.ProviderType, value, this.KeySpec)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry")); - - if (value == null) - m_keyContainerName = "*"; - else - m_keyContainerName = value; - } - } - - public int KeySpec { - get { - return m_keySpec; - } - set { - // Unrestricted entries are invalid; they should not be allowed. - if (IsUnrestrictedEntry(this.KeyStore, this.ProviderName, this.ProviderType, this.KeyContainerName, value)) - throw new ArgumentException(Environment.GetResourceString("Arg_InvalidAccessEntry")); - - m_keySpec = value; - } - } - - public KeyContainerPermissionFlags Flags { - get { - return m_flags; - } - set { - KeyContainerPermission.VerifyFlags(value); - m_flags = value; - } - } - - public override bool Equals (Object o) { - KeyContainerPermissionAccessEntry accessEntry = o as KeyContainerPermissionAccessEntry; - if (accessEntry == null) - return false; - - if (accessEntry.m_keyStore != m_keyStore) return false; - if (accessEntry.m_providerName != m_providerName) return false; - if (accessEntry.m_providerType != m_providerType) return false; - if (accessEntry.m_keyContainerName != m_keyContainerName) return false; - if (accessEntry.m_keySpec != m_keySpec) return false; - - return true; - } - - public override int GetHashCode () { - int hash = 0; - - hash |= (this.m_keyStore.GetHashCode() & 0x000000FF) << 24; - hash |= (this.m_providerName.GetHashCode() & 0x000000FF) << 16; - hash |= (this.m_providerType & 0x0000000F) << 12; - hash |= (this.m_keyContainerName.GetHashCode() & 0x000000FF) << 4; - hash |= (this.m_keySpec & 0x0000000F); - - return hash; - } - - internal bool IsSubsetOf (KeyContainerPermissionAccessEntry target) { - if (target.m_keyStore != "*" && this.m_keyStore != target.m_keyStore) - return false; - if (target.m_providerName != "*" && this.m_providerName != target.m_providerName) - return false; - if (target.m_providerType != -1 && this.m_providerType != target.m_providerType) - return false; - if (target.m_keyContainerName != "*" && this.m_keyContainerName != target.m_keyContainerName) - return false; - if (target.m_keySpec != -1 && this.m_keySpec != target.m_keySpec) - return false; - - return true; - } - - internal static bool IsUnrestrictedEntry (string keyStore, string providerName, int providerType, - string keyContainerName, int keySpec) { - if (keyStore != "*" && keyStore != null) return false; - if (providerName != "*" && providerName != null) return false; - if (providerType != -1) return false; - if (keyContainerName != "*" && keyContainerName != null) return false; - if (keySpec != -1) return false; - - return true; - } - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class KeyContainerPermissionAccessEntryCollection : ICollection { - private ArrayList m_list; - private KeyContainerPermissionFlags m_globalFlags; - - private KeyContainerPermissionAccessEntryCollection () {} - internal KeyContainerPermissionAccessEntryCollection (KeyContainerPermissionFlags globalFlags) { - m_list = new ArrayList(); - m_globalFlags = globalFlags; - } - - public KeyContainerPermissionAccessEntry this[int index] { - get { - if (index < 0) - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted")); - if (index >= Count) - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); - Contract.EndContractBlock(); - - return (KeyContainerPermissionAccessEntry)m_list[index]; - } - } - - public int Count { - get { - return m_list.Count; - } - } - - public int Add (KeyContainerPermissionAccessEntry accessEntry) { - if (accessEntry == null) - throw new ArgumentNullException(nameof(accessEntry)); - Contract.EndContractBlock(); - - int index = m_list.IndexOf(accessEntry); - if (index == -1) { - if (accessEntry.Flags != m_globalFlags) { - return m_list.Add(accessEntry); - } - else - return -1; - } else { - // We pick up the intersection of the 2 flags. This is the secure choice - // so we are opting for it. - ((KeyContainerPermissionAccessEntry)m_list[index]).Flags &= accessEntry.Flags; - return index; - } - } - - public void Clear () { - m_list.Clear(); - } - - public int IndexOf (KeyContainerPermissionAccessEntry accessEntry) { - return m_list.IndexOf(accessEntry); - } - - public void Remove (KeyContainerPermissionAccessEntry accessEntry) { - if (accessEntry == null) - throw new ArgumentNullException(nameof(accessEntry)); - Contract.EndContractBlock(); - m_list.Remove(accessEntry); - } - - public KeyContainerPermissionAccessEntryEnumerator GetEnumerator () { - return new KeyContainerPermissionAccessEntryEnumerator(this); - } - - /// <internalonly/> - IEnumerator IEnumerable.GetEnumerator () { - return new KeyContainerPermissionAccessEntryEnumerator(this); - } - - /// <internalonly/> - void ICollection.CopyTo (Array array, int index) { - if (array == null) - 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(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); - if (index + this.Count > array.Length) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); - Contract.EndContractBlock(); - - for (int i=0; i < this.Count; i++) { - array.SetValue(this[i], index); - index++; - } - } - - public void CopyTo (KeyContainerPermissionAccessEntry[] array, int index) { - ((ICollection)this).CopyTo(array, index); - } - - public bool IsSynchronized { - get { - return false; - } - } - - public Object SyncRoot { - get { - return this; - } - } - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class KeyContainerPermissionAccessEntryEnumerator : IEnumerator { - private KeyContainerPermissionAccessEntryCollection m_entries; - private int m_current; - - private KeyContainerPermissionAccessEntryEnumerator () {} - internal KeyContainerPermissionAccessEntryEnumerator (KeyContainerPermissionAccessEntryCollection entries) { - m_entries = entries; - m_current = -1; - } - - public KeyContainerPermissionAccessEntry Current { - get { - return m_entries[m_current]; - } - } - - /// <internalonly/> - Object IEnumerator.Current { - get { - return (Object) m_entries[m_current]; - } - } - - public bool MoveNext() { - if (m_current == ((int) m_entries.Count - 1)) - return false; - m_current++; - return true; - } - - public void Reset() { - m_current = -1; - } - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class KeyContainerPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { - private KeyContainerPermissionFlags m_flags; - private KeyContainerPermissionAccessEntryCollection m_accessEntries; - - public KeyContainerPermission (PermissionState state) { - if (state == PermissionState.Unrestricted) - m_flags = KeyContainerPermissionFlags.AllFlags; - else if (state == PermissionState.None) - m_flags = KeyContainerPermissionFlags.NoFlags; - else - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - } - - public KeyContainerPermission (KeyContainerPermissionFlags flags) { - VerifyFlags(flags); - m_flags = flags; - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - } - - public KeyContainerPermission (KeyContainerPermissionFlags flags, KeyContainerPermissionAccessEntry[] accessList) { - if (accessList == null) - throw new ArgumentNullException(nameof(accessList)); - Contract.EndContractBlock(); - - VerifyFlags(flags); - m_flags = flags; - m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags); - for (int index = 0; index < accessList.Length; index++) { - m_accessEntries.Add(accessList[index]); - } - } - - public KeyContainerPermissionFlags Flags { - get { - return m_flags; - } - } - - public KeyContainerPermissionAccessEntryCollection AccessEntries { - get { - return m_accessEntries; - } - } - - public bool IsUnrestricted () { - if (m_flags != KeyContainerPermissionFlags.AllFlags) - return false; - - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - if ((accessEntry.Flags & KeyContainerPermissionFlags.AllFlags) != KeyContainerPermissionFlags.AllFlags) - return false; - } - - return true; - } - - private bool IsEmpty () { - if (this.Flags == KeyContainerPermissionFlags.NoFlags) { - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - if (accessEntry.Flags != KeyContainerPermissionFlags.NoFlags) - return false; - } - return true; - } - return false; - } - - // - // IPermission implementation - // - - public override bool IsSubsetOf (IPermission target) { - if (target == null) - return IsEmpty(); - - if (!VerifyType(target)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - - KeyContainerPermission operand = (KeyContainerPermission) target; - - // since there are containers that are neither in the access list of the source, nor in the - // access list of the target, the source flags must be a subset of the target flags. - if ((this.m_flags & operand.m_flags) != this.m_flags) - return false; - - // Any entry in the source should have "applicable" flags in the destination that actually - // are less restrictive than the flags in the source. - - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - KeyContainerPermissionFlags targetFlags = GetApplicableFlags(accessEntry, operand); - if ((accessEntry.Flags & targetFlags) != accessEntry.Flags) - return false; - } - - // Any entry in the target should have "applicable" flags in the source that actually - // are more restrictive than the flags in the target. - - foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) { - KeyContainerPermissionFlags sourceFlags = GetApplicableFlags(accessEntry, this); - if ((sourceFlags & accessEntry.Flags) != sourceFlags) - return false; - } - - return true; - } - - public override IPermission Intersect (IPermission target) { - if (target == null) - return null; - - if (!VerifyType(target)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - - KeyContainerPermission operand = (KeyContainerPermission) target; - if (this.IsEmpty() || operand.IsEmpty()) - return null; - - KeyContainerPermissionFlags flags_intersect = operand.m_flags & this.m_flags; - KeyContainerPermission cp = new KeyContainerPermission(flags_intersect); - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - cp.AddAccessEntryAndIntersect(accessEntry, operand); - } - foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) { - cp.AddAccessEntryAndIntersect(accessEntry, this); - } - return cp.IsEmpty() ? null : cp; - } - - public override IPermission Union (IPermission target) { - if (target == null) - return this.Copy(); - - if (!VerifyType(target)) - throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); - - KeyContainerPermission operand = (KeyContainerPermission) target; - if (this.IsUnrestricted() || operand.IsUnrestricted()) - return new KeyContainerPermission(PermissionState.Unrestricted); - - KeyContainerPermissionFlags flags_union = (KeyContainerPermissionFlags) (m_flags | operand.m_flags); - KeyContainerPermission cp = new KeyContainerPermission(flags_union); - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - cp.AddAccessEntryAndUnion(accessEntry, operand); - } - foreach (KeyContainerPermissionAccessEntry accessEntry in operand.AccessEntries) { - cp.AddAccessEntryAndUnion(accessEntry, this); - } - return cp.IsEmpty() ? null : cp; - } - - public override IPermission Copy () { - if (this.IsEmpty()) - return null; - - KeyContainerPermission cp = new KeyContainerPermission((KeyContainerPermissionFlags)m_flags); - foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) { - cp.AccessEntries.Add(accessEntry); - } - return cp; - } - - /// <internalonly/> - int IBuiltInPermission.GetTokenIndex () { - return KeyContainerPermission.GetTokenIndex(); - } - - // - // private methods - // - - private void AddAccessEntries(SecurityElement securityElement) { - if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) { - IEnumerator elemEnumerator = securityElement.Children.GetEnumerator(); - while (elemEnumerator.MoveNext()) { - SecurityElement current = (SecurityElement) elemEnumerator.Current; - if (current != null) { - if (String.Equals(current.Tag, "AccessEntry")) { - int iMax = current.m_lAttributes.Count; - 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; - string keyContainerName = null; - int keySpec = -1; - KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags; - for (int i = 0; i < iMax; i += 2) { - String strAttrName = (String) current.m_lAttributes[i]; - String strAttrValue = (String) current.m_lAttributes[i+1]; - if (String.Equals(strAttrName, "KeyStore")) - keyStore = strAttrValue; - if (String.Equals(strAttrName, "ProviderName")) - providerName = strAttrValue; - else if (String.Equals(strAttrName, "ProviderType")) - providerType = Convert.ToInt32(strAttrValue, null); - else if (String.Equals(strAttrName, "KeyContainerName")) - keyContainerName = strAttrValue; - else if (String.Equals(strAttrName, "KeySpec")) - keySpec = Convert.ToInt32(strAttrValue, null); - else if (String.Equals(strAttrName, "Flags")) { - flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strAttrValue); - } - } - KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyStore, providerName, providerType, keyContainerName, keySpec, flags); - AccessEntries.Add(accessEntry); - } - } - } - } - } - - private void AddAccessEntryAndUnion (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) { - KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry); - newAccessEntry.Flags |= GetApplicableFlags(accessEntry, target); - AccessEntries.Add(newAccessEntry); - } - - private void AddAccessEntryAndIntersect (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) { - KeyContainerPermissionAccessEntry newAccessEntry = new KeyContainerPermissionAccessEntry(accessEntry); - newAccessEntry.Flags &= GetApplicableFlags(accessEntry, target); - AccessEntries.Add(newAccessEntry); - } - - // - // private/internal static methods. - // - - internal static void VerifyFlags (KeyContainerPermissionFlags flags) { - if ((flags & ~KeyContainerPermissionFlags.AllFlags) != 0) - throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flags)); - Contract.EndContractBlock(); - } - - private static KeyContainerPermissionFlags GetApplicableFlags (KeyContainerPermissionAccessEntry accessEntry, KeyContainerPermission target) { - KeyContainerPermissionFlags flags = KeyContainerPermissionFlags.NoFlags; - bool applyDefaultFlags = true; - - // If the entry exists in the target, return the flag of the target entry. - int index = target.AccessEntries.IndexOf(accessEntry); - if (index != -1) { - flags = ((KeyContainerPermissionAccessEntry)target.AccessEntries[index]).Flags; - return flags; - } - - // Intersect the flags in all the target entries that apply to the current access entry, - foreach (KeyContainerPermissionAccessEntry targetAccessEntry in target.AccessEntries) { - if (accessEntry.IsSubsetOf(targetAccessEntry)) { - if (applyDefaultFlags == false) { - flags &= targetAccessEntry.Flags; - } else { - flags = targetAccessEntry.Flags; - applyDefaultFlags = false; - } - } - } - - // If no target entry applies to the current entry, the default global flag applies. - if (applyDefaultFlags) - flags = target.Flags; - - return flags; - } - - private static int GetTokenIndex() { - return BuiltInPermissionIndex.KeyContainerPermissionIndex; - } - } -} diff --git a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs b/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs deleted file mode 100644 index 3d4e35adf4..0000000000 --- a/src/mscorlib/src/System/Security/Policy/ApplicationTrust.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System.Collections; - using System.Collections.Generic; - using System.Globalization; - using System.IO; - using System.Runtime.InteropServices; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization; - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION - using System.Runtime.Versioning; - using System.Security.Permissions; - using System.Security.Util; - using System.Text; - using System.Threading; - using System.Diagnostics.Contracts; - - [System.Runtime.InteropServices.ComVisible(true)] - public enum ApplicationVersionMatch { - MatchExactVersion, - MatchAllVersions - } - - [System.Runtime.InteropServices.ComVisible(true)] - [Serializable] - public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable - { - private PolicyStatement m_psDefaultGrant; - private IList<StrongName> m_fullTrustAssemblies; - - // Permission special flags for the default grant set in this ApplicationTrust. This should be - // updated in sync with any updates to the default grant set. - // - // In the general case, these values cannot be trusted - we only store a reference to the - // DefaultGrantSet, and return the reference directly, which means that code can update the - // permission set without our knowledge. That would lead to the flags getting out of sync with the - // grant set. - // - // However, we only care about these flags when we're creating a homogenous AppDomain, and in that - // case we control the ApplicationTrust object end-to-end, and know that the permission set will not - // change after the flags are calculated. - [NonSerialized] - private int m_grantSetSpecialFlags; - - public ApplicationTrust () : this (new PermissionSet(PermissionState.None)) - { - } - - internal ApplicationTrust (PermissionSet defaultGrantSet) - { - InitDefaultGrantSet(defaultGrantSet); - - m_fullTrustAssemblies = new List<StrongName>().AsReadOnly(); - } - - public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable<StrongName> fullTrustAssemblies) { - if (fullTrustAssemblies == null) { - throw new ArgumentNullException(nameof(fullTrustAssemblies)); - } - - InitDefaultGrantSet(defaultGrantSet); - - List<StrongName> fullTrustList = new List<StrongName>(); - foreach (StrongName strongName in fullTrustAssemblies) { - if (strongName == null) { - throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"), nameof(fullTrustAssemblies)); - } - - fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version)); - } - - m_fullTrustAssemblies = fullTrustList.AsReadOnly(); - } - - // Sets up the default grant set for all constructors. Extracted to avoid the cost of - // IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR) - private void InitDefaultGrantSet(PermissionSet defaultGrantSet) { - if (defaultGrantSet == null) { - throw new ArgumentNullException(nameof(defaultGrantSet)); - } - - // Creating a PolicyStatement copies the incoming permission set, so we don't have to worry - // about the PermissionSet parameter changing underneath us after we've calculated the - // permisison flags in the DefaultGrantSet setter. - DefaultGrantSet = new PolicyStatement(defaultGrantSet); - } - - public PolicyStatement DefaultGrantSet { - get { - if (m_psDefaultGrant == null) - return new PolicyStatement(new PermissionSet(PermissionState.None)); - return m_psDefaultGrant; - } - set { - if (value == null) { - m_psDefaultGrant = null; - m_grantSetSpecialFlags = 0; - } - else { - m_psDefaultGrant = value; - m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(m_psDefaultGrant.PermissionSet, null); - } - } - } - - public IList<StrongName> FullTrustAssemblies { - get { - return m_fullTrustAssemblies; - } - } - - public override EvidenceBase Clone() - { - return base.Clone(); - } - } -} diff --git a/src/mscorlib/src/System/Security/Policy/Evidence.cs b/src/mscorlib/src/System/Security/Policy/Evidence.cs deleted file mode 100644 index 22479dff6c..0000000000 --- a/src/mscorlib/src/System/Security/Policy/Evidence.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Runtime.InteropServices; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization; - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION - - /// <summary> - /// The Evidence class keeps track of information that can be used to make security decisions about - /// an assembly or an AppDomain. There are two types of evidence, one is supplied by the CLR or a - /// host, the other supplied by the assembly itself. - /// - /// We keep a dictionary that maps each type of possbile evidence to an EvidenceTypeDescriptor which - /// contains the evidence objects themselves if they exist as well as some extra metadata about that - /// type of evidence. This dictionary is fully populated with keys for host evidence at all times and - /// for assembly evidence the first time the application evidence is touched. This means that if a - /// Type key does not exist in the dictionary, then that particular type of evidence will never be - /// given to the assembly or AppDomain in question as host evidence. The only exception is if the - /// user later manually adds host evidence via the AddHostEvidence API. - /// - /// Assembly supplied evidence is created up front, however host supplied evidence may be lazily - /// created. In the lazy creation case, the Type will map to either an EvidenceTypeDescriptor that does - /// not contain any evidence data or null. As requests come in for that evidence, we'll populate the - /// EvidenceTypeDescriptor appropriately. - /// </summary> -#if FEATURE_SERIALIZATION - [Serializable] -#endif - [ComVisible(true)] - public sealed class Evidence - { - } -} diff --git a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs b/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs deleted file mode 100644 index 7fef1ded3c..0000000000 --- a/src/mscorlib/src/System/Security/Policy/EvidenceBase.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -#if FEATURE_SERIALIZATION -using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION -using System.Security.Permissions; - -namespace System.Security.Policy -{ - /// <summary> - /// Base class from which all objects to be used as Evidence must derive - /// </summary> - [ComVisible(true)] - [Serializable] - public abstract class EvidenceBase - { - protected EvidenceBase() - { -#if FEATURE_SERIALIZATION - // All objects to be used as evidence must be serializable. Make sure that any derived types - // are marked serializable to enforce this, since the attribute does not inherit down to derived - // classes. - if (!GetType().IsSerializable) - { - throw new InvalidOperationException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable")); - } -#endif // FEATURE_SERIALIZATION - } - - /// <remarks> - /// Since legacy evidence objects would be cloned by being serialized, the default implementation - /// of EvidenceBase will do the same. - /// </remarks> - public virtual EvidenceBase Clone() - { -#if FEATURE_SERIALIZATION - using (MemoryStream memoryStream = new MemoryStream()) - { - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(memoryStream, this); - - memoryStream.Position = 0; - return formatter.Deserialize(memoryStream) as EvidenceBase; - } -#else // !FEATURE_SERIALIZATION - throw new NotImplementedException(); -#endif // FEATURE_SERIALIZATION - } - } - - /// <summary> - /// Interface for types which wrap Whidbey evidence objects for compatibility with v4 evidence rules - /// </summary> - internal interface ILegacyEvidenceAdapter - { - object EvidenceObject { get; } - Type EvidenceType { get; } - } - - /// <summary> - /// Wrapper class to hold legacy evidence objects which do not derive from EvidenceBase, and allow - /// them to be held in the Evidence collection which expects to maintain lists of EvidenceBase only - /// </summary> - [Serializable] - internal sealed class LegacyEvidenceWrapper : EvidenceBase, ILegacyEvidenceAdapter - { - private object m_legacyEvidence; - - internal LegacyEvidenceWrapper(object legacyEvidence) - { - 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; - } - - public object EvidenceObject - { - get { return m_legacyEvidence; } - } - - public Type EvidenceType - { - get { return m_legacyEvidence.GetType(); } - } - - public override bool Equals(object obj) - { - return m_legacyEvidence.Equals(obj); - } - - public override int GetHashCode() - { - return m_legacyEvidence.GetHashCode(); - } - - public override EvidenceBase Clone() - { - return base.Clone(); - } - } - - /// <summary> - /// Pre-v4 versions of the runtime allow multiple pieces of evidence that all have the same type. - /// This type wraps those evidence objects into a single type of list, allowing legacy code to continue - /// to work with the Evidence collection that does not expect multiple evidences of the same type. - /// - /// This may not be limited to LegacyEvidenceWrappers, since it's valid for legacy code to add multiple - /// objects of built-in evidence to an Evidence collection. The built-in evidence now derives from - /// EvienceObject, so when the legacy code runs on v4, it may end up attempting to add multiple - /// Hash evidences for intsance. - /// </summary> - [Serializable] - internal sealed class LegacyEvidenceList : EvidenceBase, IEnumerable<EvidenceBase>, ILegacyEvidenceAdapter - { - private List<EvidenceBase> m_legacyEvidenceList = new List<EvidenceBase>(); - - public object EvidenceObject - { - get - { - // We'll choose the first item in the list to represent us if we're forced to return only - // one object. This can occur if multiple pieces of evidence are added via the legacy APIs, - // and then the new APIs are used to retrieve that evidence. - return m_legacyEvidenceList.Count > 0 ? m_legacyEvidenceList[0] : null; - } - } - - public Type EvidenceType - { - get - { - 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; - } - } - - public void Add(EvidenceBase evidence) - { - 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"); - Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList), - "Attempt to add a legacy evidence list to another legacy evidence list"); - - m_legacyEvidenceList.Add(evidence); - } - - public IEnumerator<EvidenceBase> GetEnumerator() - { - return m_legacyEvidenceList.GetEnumerator(); - } - - IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return m_legacyEvidenceList.GetEnumerator(); - } - - 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 deleted file mode 100644 index 8deb145102..0000000000 --- a/src/mscorlib/src/System/Security/Policy/EvidenceTypeDescriptor.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -using System; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Runtime.Serialization; - -namespace System.Security.Policy -{ - /// <summary> - /// Descriptor stored in the Evidence collection to detail the information we have about a type of - /// evidence. This descriptor also stores any evidence that's been generated of the specific type. - /// </summary> - [Serializable] - internal sealed class EvidenceTypeDescriptor - { - [NonSerialized] - private bool m_hostCanGenerate; - - [NonSerialized] - private bool m_generated; - - private EvidenceBase m_hostEvidence; - private EvidenceBase m_assemblyEvidence; - - // EvidenceTypeDescriptors are stored in Evidence indexed by the type they describe, so this - // information is redundant. We keep it around in checked builds to help debugging, but we can drop - // it from retial builds. -#if _DEBUG - [NonSerialized] - private Type m_evidenceType; -#endif // _DEBUG - - public EvidenceTypeDescriptor() - { - } - - /// <summary> - /// Make a deep copy of a type descriptor - /// </summary> - private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor) - { - Debug.Assert(descriptor != null); - - m_hostCanGenerate = descriptor.m_hostCanGenerate; - - if (descriptor.m_assemblyEvidence != null) - { - m_assemblyEvidence = descriptor.m_assemblyEvidence.Clone() as EvidenceBase; - } - if (descriptor.m_hostEvidence != null) - { - m_hostEvidence = descriptor.m_hostEvidence.Clone() as EvidenceBase; - } - -#if _DEBUG - m_evidenceType = descriptor.m_evidenceType; -#endif // _DEBUG - } - - /// <summary> - /// Evidence of this type supplied by the assembly - /// </summary> - public EvidenceBase AssemblyEvidence - { - get { return m_assemblyEvidence; } - - set - { - Debug.Assert(value != null); -#if _DEBUG - Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set"); -#endif - m_assemblyEvidence = value; - } - } - - /// <summary> - /// Flag indicating that we've already attempted to generate this type of evidence - /// </summary> - public bool Generated - { - get { return m_generated; } - - set - { - Debug.Assert(value, "Attempt to clear the Generated flag"); - m_generated = value; - } - } - - /// <summary> - /// Has the HostSecurityManager has told us that it can potentially generate evidence of this type - /// </summary> - public bool HostCanGenerate - { - get { return m_hostCanGenerate; } - - set - { - Debug.Assert(value, "Attempt to clear HostCanGenerate flag"); - m_hostCanGenerate = value; - } - } - - /// <summary> - /// Evidence of this type supplied by the CLR or the host - /// </summary> - public EvidenceBase HostEvidence - { - get { return m_hostEvidence; } - - set - { - Debug.Assert(value != null); -#if _DEBUG - Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set"); -#endif - m_hostEvidence = value; - } - } - -#if _DEBUG - /// <summary> - /// Verify that evidence being stored in this descriptor is of the correct type - /// </summary> - private bool CheckEvidenceType(EvidenceBase evidence) - { - Debug.Assert(evidence != null); - - ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter; - Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType; - - return m_evidenceType == null || m_evidenceType.IsAssignableFrom(storedType); - } -#endif // _DEBUG - - /// <summary> - /// Make a deep copy of this descriptor - /// </summary> - public EvidenceTypeDescriptor Clone() - { - return new EvidenceTypeDescriptor(this); - } - -#if _DEBUG - /// <summary> - /// Set the type that this evidence descriptor refers to. - /// </summary> - internal void SetEvidenceType(Type evidenceType) - { - Debug.Assert(evidenceType != null); - Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type"); - - m_evidenceType = evidenceType; - } -#endif // _DEBUG - } -} diff --git a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs b/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs deleted file mode 100644 index 8f8c07c9e4..0000000000 --- a/src/mscorlib/src/System/Security/Policy/IDelayEvaluatedEvidence.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 { - /// <summary> - /// Interface for evidence objects that support being "unverified". For instance, StrongName - /// evidence for a strong name signature which was not yet verified. This interface is used to - /// keep track of weather or not the evidence object was needed to compute a grant set. If it was, - /// then we can force verificaiton of the evidence object -- if not we can save time by not doing - /// any verification on it. (Since we didn't use it for policy resolution, it wouldn't have - /// mattered if the evidence was not present in the first place). - /// </summary> - internal interface IDelayEvaluatedEvidence { - /// <summary> - /// Is this evidence object verified yet? - /// </summary> - bool IsVerified - { - get; - } - - /// <summary> - /// Was this evidence object used during the course of policy evaluation? - /// </summary> - bool WasUsed { get; } - - /// <summary> - /// Mark the object as used - /// </summary> - void MarkUsed(); - } -} diff --git a/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs b/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs deleted file mode 100644 index a46f39602d..0000000000 --- a/src/mscorlib/src/System/Security/Policy/IIdentityPermissionFactory.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// All Identities will implement this interface. -// - -namespace System.Security.Policy { - using System.Runtime.Remoting; - using System; - using System.Security.Util; -[System.Runtime.InteropServices.ComVisible(true)] - public interface IIdentityPermissionFactory - { - IPermission CreateIdentityPermission( Evidence evidence ); - } - -} diff --git a/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs b/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs deleted file mode 100644 index 98467fe367..0000000000 --- a/src/mscorlib/src/System/Security/Policy/IRuntimeEvidenceFactory.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -using System; -using System.Collections.Generic; - -namespace System.Security.Policy -{ - /// <summary> - /// IRuntimeEvidenceFactory is implemented by runtime types which the CLR knows how to delay - /// generate evidence for. It is used by the Evidence class to get evidence on demand when we first - /// need it. - /// </summary> - internal interface IRuntimeEvidenceFactory - { - /// <summary> - /// Object which the evidence generated by this factory is used for - /// </summary> - IEvidenceFactory Target { get; } - - /// <summary> - /// Get the collection of evidence objects supplied by the factory itself, rather than by the - /// runtime. - /// </summary> - IEnumerable<EvidenceBase> GetFactorySuppliedEvidence(); - - /// <summary> - /// Generate a specific type of evidence for this object, returning null if the specified type of - /// evidence cannot be generated. - /// </summary> - EvidenceBase GenerateEvidence(Type evidenceType); - } -} diff --git a/src/mscorlib/src/System/Security/Policy/PolicyException.cs b/src/mscorlib/src/System/Security/Policy/PolicyException.cs deleted file mode 100644 index 68e87f780d..0000000000 --- a/src/mscorlib/src/System/Security/Policy/PolicyException.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// Use this class to throw a PolicyException -// - -namespace System.Security.Policy { - - using System; - using System.Runtime.Serialization; - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - public class PolicyException : SystemException - { - public PolicyException() - - : base(Environment.GetResourceString( "Policy_Default" )) { - HResult = __HResults.CORSEC_E_POLICY_EXCEPTION; - } - - public PolicyException(String message) - - : base(message) { - HResult = __HResults.CORSEC_E_POLICY_EXCEPTION; - } - - public PolicyException(String message, Exception exception) - - : base(message, exception) { - HResult = __HResults.CORSEC_E_POLICY_EXCEPTION; - } - - protected PolicyException(SerializationInfo info, StreamingContext context) : base (info, context) {} - - internal PolicyException(String message, int hresult) : base (message) - { - HResult = hresult; - } - - internal PolicyException(String message, int hresult, Exception exception) : base (message, exception) - { - HResult = hresult; - } - - } - -} diff --git a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs b/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs deleted file mode 100644 index 9b58ece9f1..0000000000 --- a/src/mscorlib/src/System/Security/Policy/PolicyStatement.cs +++ /dev/null @@ -1,246 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// Represents the policy associated with some piece of evidence -// -using System.Diagnostics.Contracts; -namespace System.Security.Policy { - - using System; - using System.Security; - using System.Security.Util; - using Math = System.Math; - using System.Collections; - using System.Collections.Generic; - using System.Security.Permissions; - using System.Text; - using System.Globalization; -[Serializable] - [Flags] -[System.Runtime.InteropServices.ComVisible(true)] - public enum PolicyStatementAttribute - { - Nothing = 0x0, - Exclusive = 0x01, - LevelFinal = 0x02, - All = 0x03, - } - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - sealed public class PolicyStatement : ISecurityPolicyEncodable, ISecurityEncodable - { - // The PermissionSet associated with this policy - internal PermissionSet m_permSet; - - // The bitfield of inheritance properties associated with this policy - internal PolicyStatementAttribute m_attributes; - - internal PolicyStatement() - { - m_permSet = null; - m_attributes = PolicyStatementAttribute.Nothing; - } - - public PolicyStatement( PermissionSet permSet ) - : this( permSet, PolicyStatementAttribute.Nothing ) - { - } - - public PolicyStatement( PermissionSet permSet, PolicyStatementAttribute attributes ) - { - if (permSet == null) - { - m_permSet = new PermissionSet( false ); - } - else - { - m_permSet = permSet.Copy(); - } - if (ValidProperties( attributes )) - { - m_attributes = attributes; - } - } - - private PolicyStatement( PermissionSet permSet, PolicyStatementAttribute attributes, bool copy ) - { - if (permSet != null) - { - if (copy) - m_permSet = permSet.Copy(); - else - m_permSet = permSet; - } - else - { - m_permSet = new PermissionSet( false ); - } - - m_attributes = attributes; - } - - public PermissionSet PermissionSet - { - get - { - lock (this) - { - return m_permSet.Copy(); - } - } - - set - { - lock (this) - { - if (value == null) - { - m_permSet = new PermissionSet( false ); - } - else - { - m_permSet = value.Copy(); - } - } - } - } - - internal void SetPermissionSetNoCopy( PermissionSet permSet ) - { - m_permSet = permSet; - } - - internal PermissionSet GetPermissionSetNoCopy() - { - lock (this) - { - return m_permSet; - } - } - - public PolicyStatementAttribute Attributes - { - get - { - return m_attributes; - } - - set - { - if (ValidProperties( value )) - { - m_attributes = value; - } - } - } - - public PolicyStatement Copy() - { - // The PolicyStatement .ctor will copy the permission set - return new PolicyStatement(m_permSet, Attributes, true); - } - - public String AttributeString - { - get - { - StringBuilder sb = new StringBuilder(); - - bool first = true; - - if (GetFlag((int) PolicyStatementAttribute.Exclusive )) - { - sb.Append( "Exclusive" ); - first = false; - } - if (GetFlag((int) PolicyStatementAttribute.LevelFinal )) - { - if (!first) - sb.Append( " " ); - sb.Append( "LevelFinal" ); - } - - return sb.ToString(); - } - } - - private static bool ValidProperties( PolicyStatementAttribute attributes ) - { - if ((attributes & ~(PolicyStatementAttribute.All)) == 0) - { - return true; - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidFlag" ) ); - } - } - - private bool GetFlag( int flag ) - { - return (flag & (int)m_attributes) != 0; - } - - /// <summary> - /// Union a child policy statement into this policy statement - /// </summary> - internal void InplaceUnion(PolicyStatement childPolicy) - { - BCLDebug.Assert(childPolicy != null, "childPolicy != null"); - - if (((Attributes & childPolicy.Attributes) & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive) - { - throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" )); - } - - // 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 - // is exclusive then it is the only code group which should have an effect on the resulting - // grant set and therefore our grant should be ignored. - if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive) - { - m_permSet = childPolicy.GetPermissionSetNoCopy(); - Attributes = childPolicy.Attributes; - } - else - { - m_permSet.InplaceUnion(childPolicy.GetPermissionSetNoCopy()); - Attributes = Attributes | childPolicy.Attributes; - } - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override bool Equals( Object obj ) - { - PolicyStatement other = obj as PolicyStatement; - - if (other == null) - return false; - - if (this.m_attributes != other.m_attributes) - return false; - - if (!Object.Equals( this.m_permSet, other.m_permSet )) - return false; - - return true; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public override int GetHashCode() - { - int accumulator = (int)this.m_attributes; - - if (m_permSet != null) - accumulator = accumulator ^ m_permSet.GetHashCode(); - - return accumulator; - } - - } -} - diff --git a/src/mscorlib/src/System/Security/Policy/Site.cs b/src/mscorlib/src/System/Security/Policy/Site.cs deleted file mode 100644 index 14a95e1666..0000000000 --- a/src/mscorlib/src/System/Security/Policy/Site.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// Site is an IIdentity representing internet sites. -// - -using System; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Globalization; -using System.Security.Permissions; -using System.Security.Util; - -namespace System.Security.Policy -{ - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class Site : EvidenceBase, IIdentityPermissionFactory - { - private SiteString m_name; - - public Site(String name) - { - if (name == null) - throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); - - m_name = new SiteString( name ); - } - - private Site(SiteString name) - { - Debug.Assert(name != null); - m_name = name; - } - - public static Site CreateFromUrl( String url ) - { - return new Site(ParseSiteFromUrl(url)); - } - - private static SiteString ParseSiteFromUrl( String name ) - { - URLString urlString = new URLString( name ); - - if (String.Compare( urlString.Scheme, "file", StringComparison.OrdinalIgnoreCase) == 0) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidSite" ) ); - - return new SiteString( new URLString( name ).Host ); - } - - public String Name - { - get { return m_name.ToString(); } - } - - internal SiteString GetSiteString() - { - return m_name; - } - - public IPermission CreateIdentityPermission( Evidence evidence ) - { - return new SiteIdentityPermission( Name ); - } - - public override bool Equals(Object o) - { - Site other = o as Site; - if (other == null) - { - return false; - } - - return String.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase); - } - - public override int GetHashCode() - { - return Name.GetHashCode(); - } - - public override EvidenceBase Clone() - { - return new Site(m_name); - } - - public Object Copy() - { - return Clone(); - } - - // INormalizeForIsolatedStorage is not implemented for startup perf - // equivalent to INormalizeForIsolatedStorage.Normalize() - internal Object Normalize() - { - return m_name.ToString().ToUpper(CultureInfo.InvariantCulture); - } - } -} diff --git a/src/mscorlib/src/System/Security/Policy/StrongName.cs b/src/mscorlib/src/System/Security/Policy/StrongName.cs deleted file mode 100644 index 999b478ba7..0000000000 --- a/src/mscorlib/src/System/Security/Policy/StrongName.cs +++ /dev/null @@ -1,171 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// StrongName is an IIdentity representing strong names. -// - -namespace System.Security.Policy { - using System.IO; - using System.Reflection; - using System.Security.Util; - using System.Security.Permissions; - using System.Diagnostics.Contracts; - using CultureInfo = System.Globalization.CultureInfo; - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class StrongName : EvidenceBase, IIdentityPermissionFactory, IDelayEvaluatedEvidence - { - private StrongNamePublicKeyBlob m_publicKeyBlob; - private String m_name; - private Version m_version; - - // Delay evaluated evidence is for policy resolution only, so it doesn't make sense to save that - // state away and then try to evaluate the strong name later. - [NonSerialized] - private RuntimeAssembly m_assembly = null; - - [NonSerialized] - private bool m_wasUsed = false; - - internal StrongName() {} - - public StrongName( StrongNamePublicKeyBlob blob, String name, Version version ) : this(blob, name, version, null) - { - } - - internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly) - { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (String.IsNullOrEmpty(name)) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName")); - - if (blob == null) - throw new ArgumentNullException(nameof(blob)); - - if (version == null) - throw new ArgumentNullException(nameof(version)); - Contract.EndContractBlock(); - - RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; - if (assembly != null && rtAssembly == null) - throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), nameof(assembly)); - - m_publicKeyBlob = blob; - m_name = name; - m_version = version; - m_assembly = rtAssembly; - } - - public StrongNamePublicKeyBlob PublicKey - { - get - { - return m_publicKeyBlob; - } - } - - public String Name - { - get - { - return m_name; - } - } - - public Version Version - { - get - { - return m_version; - } - } - - bool IDelayEvaluatedEvidence.IsVerified - { - get - { - return true; - } - } - - bool IDelayEvaluatedEvidence.WasUsed - { - get { return m_wasUsed; } - } - - void IDelayEvaluatedEvidence.MarkUsed() - { - m_wasUsed = true; - } - - internal static bool CompareNames( String asmName, String mcName ) - { - if (mcName.Length > 0 && mcName[mcName.Length-1] == '*' && mcName.Length - 1 <= asmName.Length) - return String.Compare( mcName, 0, asmName, 0, mcName.Length - 1, StringComparison.OrdinalIgnoreCase) == 0; - else - return String.Compare( mcName, asmName, StringComparison.OrdinalIgnoreCase) == 0; - } - - public IPermission CreateIdentityPermission( Evidence evidence ) - { - return new StrongNameIdentityPermission( m_publicKeyBlob, m_name, m_version ); - } - - public override EvidenceBase Clone() - { - return new StrongName(m_publicKeyBlob, m_name, m_version); - } - - public Object Copy() - { - return Clone(); - } - - public override bool Equals( Object o ) - { - StrongName that = (o as StrongName); - return (that != null) && - Equals( this.m_publicKeyBlob, that.m_publicKeyBlob ) && - Equals( this.m_name, that.m_name ) && - Equals( this.m_version, that.m_version ); - } - - public override int GetHashCode() - { - if (m_publicKeyBlob != null) - { - return m_publicKeyBlob.GetHashCode(); - } - else if (m_name != null || m_version != null) - { - return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode()); - } - else - { - return typeof( StrongName ).GetHashCode(); - } - } - - // INormalizeForIsolatedStorage is not implemented for startup perf - // equivalent to INormalizeForIsolatedStorage.Normalize() - internal Object Normalize() - { - MemoryStream ms = new MemoryStream(); - BinaryWriter bw = new BinaryWriter(ms); - - bw.Write(m_publicKeyBlob.PublicKey); - bw.Write(m_version.Major); - bw.Write(m_name); - - ms.Position = 0; - return ms; - } - } -} diff --git a/src/mscorlib/src/System/Security/Policy/URL.cs b/src/mscorlib/src/System/Security/Policy/URL.cs deleted file mode 100644 index 3541124ac6..0000000000 --- a/src/mscorlib/src/System/Security/Policy/URL.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// Url is an IIdentity representing url internet sites. -// - -namespace System.Security.Policy { - using System.IO; - using System.Security.Util; - using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission; - using System.Runtime.Serialization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public sealed class Url : EvidenceBase, IIdentityPermissionFactory - { - private URLString m_url; - - internal Url( String name, bool parsed ) - { - if (name == null) - throw new ArgumentNullException( nameof(name) ); - Contract.EndContractBlock(); - - m_url = new URLString( name, parsed ); - } - - public Url( String name ) - { - if (name == null) - throw new ArgumentNullException( nameof(name) ); - Contract.EndContractBlock(); - - m_url = new URLString( name ); - } - - private Url(Url url) - { - Debug.Assert(url != null); - m_url = url.m_url; - } - - public String Value - { - get { return m_url.ToString(); } - } - - internal URLString GetURLString() - { - return m_url; - } - - public IPermission CreateIdentityPermission( Evidence evidence ) - { - return new UrlIdentityPermission( m_url ); - } - - public override bool Equals(Object o) - { - Url other = o as Url; - if (other == null) - { - return false; - } - - return other.m_url.Equals(m_url); - } - - public override int GetHashCode() - { - return this.m_url.GetHashCode(); - } - - public override EvidenceBase Clone() - { - return new Url(this); - } - - public Object Copy() - { - return Clone(); - } - - // INormalizeForIsolatedStorage is not implemented for startup perf - // equivalent to INormalizeForIsolatedStorage.Normalize() - internal Object Normalize() - { - return m_url.NormalizeUrl(); - } - } -} diff --git a/src/mscorlib/src/System/Security/Policy/Zone.cs b/src/mscorlib/src/System/Security/Policy/Zone.cs deleted file mode 100644 index a9f5d84aeb..0000000000 --- a/src/mscorlib/src/System/Security/Policy/Zone.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// Zone is an IIdentity representing Internet/Intranet/MyComputer etc. -// - -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 - { - private SecurityZone m_zone; - - private static readonly String[] s_names = - {"MyComputer", "Intranet", "Trusted", "Internet", "Untrusted", "NoZone"}; - - public Zone(SecurityZone zone) - { - if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) - throw new ArgumentException( Environment.GetResourceString( "Argument_IllegalZone" ) ); - Contract.EndContractBlock(); - - m_zone = zone; - } - - private Zone(Zone zone) - { - Debug.Assert(zone != null); - m_zone = zone.m_zone; - } - - public IPermission CreateIdentityPermission( Evidence evidence ) - { - return new ZoneIdentityPermission( SecurityZone ); - } - - public SecurityZone SecurityZone - { - get - { - return m_zone; - } - } - - public override bool Equals(Object o) - { - Zone other = o as Zone; - if (other == null) - { - return false; - } - - return SecurityZone == other.SecurityZone; - } - - public override int GetHashCode() - { - return (int)SecurityZone; - } - - public override EvidenceBase Clone() - { - return new Zone(this); - } - - public Object Copy() - { - return Clone(); - } - - // INormalizeForIsolatedStorage is not implemented for startup perf - // equivalent to INormalizeForIsolatedStorage.Normalize() - internal Object Normalize() - { - return s_names[(int)SecurityZone]; - } - } -} diff --git a/src/mscorlib/src/System/Security/Principal/IIdentity.cs b/src/mscorlib/src/System/Security/Principal/IIdentity.cs deleted file mode 100644 index 2bda6c6e3d..0000000000 --- a/src/mscorlib/src/System/Security/Principal/IIdentity.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// All identities will implement this interface -// - -namespace System.Security.Principal -{ - using System.Runtime.Remoting; - using System; - using System.Security.Util; - -[System.Runtime.InteropServices.ComVisible(true)] - public interface IIdentity { - // Access to the name string - string Name { get; } - - // Access to Authentication 'type' info - string AuthenticationType { get; } - - // Determine if this represents the unauthenticated identity - bool IsAuthenticated { get; } - } -} diff --git a/src/mscorlib/src/System/Security/Principal/IPrincipal.cs b/src/mscorlib/src/System/Security/Principal/IPrincipal.cs deleted file mode 100644 index 449cfb50b2..0000000000 --- a/src/mscorlib/src/System/Security/Principal/IPrincipal.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -// -// -// All roles will implement this interface -// - -namespace System.Security.Principal -{ - using System.Runtime.Remoting; - using System; - using System.Security.Util; - -[System.Runtime.InteropServices.ComVisible(true)] - public interface IPrincipal { - // Retrieve the identity object - IIdentity Identity { get; } - - // Perform a check for a specific role - bool IsInRole (string role); - } -} diff --git a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs b/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs deleted file mode 100644 index 9eec46f774..0000000000 --- a/src/mscorlib/src/System/Security/Principal/TokenImpersonationLevel.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - public enum TokenImpersonationLevel - { - None = 0, - Anonymous = 1, - Identification = 2, - Impersonation = 3, - Delegation = 4 - } -} diff --git a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs b/src/mscorlib/src/System/Security/SafeSecurityHandles.cs deleted file mode 100644 index 9a84164460..0000000000 --- a/src/mscorlib/src/System/Security/SafeSecurityHandles.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -namespace Microsoft.Win32.SafeHandles { - using System; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using System.Security; - - // Introduce this handle to replace internal SafeTokenHandle, - // which is mainly used to hold Windows thread or process access token - public sealed class SafeAccessTokenHandle : SafeHandle - { - private SafeAccessTokenHandle() - : base(IntPtr.Zero, true) - { } - - // 0 is an Invalid Handle - public SafeAccessTokenHandle(IntPtr handle) - : base(IntPtr.Zero, true) - { - SetHandle(handle); - } - - public static SafeAccessTokenHandle InvalidHandle - { - get { return new SafeAccessTokenHandle(IntPtr.Zero); } - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero || handle == new IntPtr(-1); } - } - - protected override bool ReleaseHandle() - { - return Win32Native.CloseHandle(handle); - } - } - - internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeLsaLogonProcessHandle() : base (true) {} - - // 0 is an Invalid Handle - internal SafeLsaLogonProcessHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - internal static SafeLsaLogonProcessHandle InvalidHandle { - get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); } - } - - override protected bool ReleaseHandle() - { - // LsaDeregisterLogonProcess returns an NTSTATUS - return Win32Native.LsaDeregisterLogonProcess(handle) >= 0; - } - } - - internal sealed class SafeLsaMemoryHandle : SafeBuffer { - private SafeLsaMemoryHandle() : base(true) {} - - // 0 is an Invalid Handle - internal SafeLsaMemoryHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - internal static SafeLsaMemoryHandle InvalidHandle { - get { return new SafeLsaMemoryHandle( IntPtr.Zero ); } - } - - override protected bool ReleaseHandle() - { - return Win32Native.LsaFreeMemory(handle) == 0; - } - } - - internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeLsaPolicyHandle() : base(true) {} - - // 0 is an Invalid Handle - internal SafeLsaPolicyHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - internal static SafeLsaPolicyHandle InvalidHandle { - get { return new SafeLsaPolicyHandle( IntPtr.Zero ); } - } - - override protected bool ReleaseHandle() - { - return Win32Native.LsaClose(handle) == 0; - } - } - - internal sealed class SafeLsaReturnBufferHandle : SafeBuffer { - private SafeLsaReturnBufferHandle() : base (true) {} - - // 0 is an Invalid Handle - internal SafeLsaReturnBufferHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - internal static SafeLsaReturnBufferHandle InvalidHandle { - get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); } - } - - override protected bool ReleaseHandle() - { - // LsaFreeReturnBuffer returns an NTSTATUS - return Win32Native.LsaFreeReturnBuffer(handle) >= 0; - } - } - - internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeProcessHandle() : base (true) {} - - // 0 is an Invalid Handle - internal SafeProcessHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - internal static SafeProcessHandle InvalidHandle { - get { return new SafeProcessHandle(IntPtr.Zero); } - } - - override protected bool ReleaseHandle() - { - return Win32Native.CloseHandle(handle); - } - } - - internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeThreadHandle() : base (true) {} - - // 0 is an Invalid Handle - internal SafeThreadHandle(IntPtr handle) : base (true) { - SetHandle(handle); - } - - 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 deleted file mode 100644 index 674c04196f..0000000000 --- a/src/mscorlib/src/System/Security/SecurityContext.cs +++ /dev/null @@ -1,486 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** -** -** Purpose: Capture security context for a thread -** -** -===========================================================*/ -namespace System.Security -{ - using Microsoft.Win32; - using Microsoft.Win32.SafeHandles; - using System.Threading; - using System.Runtime.Remoting; - using System.Collections; - using System.Runtime.Serialization; - using System.Security.Permissions; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; -#if FEATURE_CORRUPTING_EXCEPTIONS - using System.Runtime.ExceptionServices; -#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 - public enum SecurityContextSource - { - CurrentAppDomain = 0, - CurrentAssembly - } - - internal enum SecurityContextDisableFlow - { - Nothing = 0, - WI = 0x1, - All = 0x3FFF - } - -#if FEATURE_COMPRESSEDSTACK - internal struct SecurityContextSwitcher: IDisposable - { - internal SecurityContext.Reader prevSC; // prev SC that we restore on an Undo - 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; - - public void Dispose() - { - Undo(); - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - internal bool UndoNoThrow() - { - try - { - Undo(); - } - catch - { - return false; - } - return true; - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - public void Undo() - { - if (currSC == null) - { - return; // mutiple Undo()s called on this switcher object - } - - if (currEC != null) - { - 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(); - } - else - { - // caller must have already restored the ExecutionContext - Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC)); - } - - currSC = null; // this will prevent the switcher object being used again - - bool bNoException = true; - - bNoException &= cssw.UndoNoThrow(); - - - if (!bNoException) - { - // Failfast since we can't continue safely... - System.Environment.FailFast(Environment.GetResourceString("ExecutionContext_UndoFailed")); - } - - } - } - - public sealed class SecurityContext : IDisposable - { - /*========================================================================= - ** Data accessed from managed code that needs to be defined in - ** SecurityContextObject to maintain alignment between the two classes. - ** DON'T CHANGE THESE UNLESS YOU MODIFY SecurityContextObject in vm\object.h - =========================================================================*/ - - private ExecutionContext _executionContext; - private volatile CompressedStack _compressedStack; - static private volatile SecurityContext _fullTrustSC; - - internal volatile bool isNewCapture = false; - internal volatile SecurityContextDisableFlow _disableFlow = SecurityContextDisableFlow.Nothing; - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - internal SecurityContext() - { - } - - internal struct Reader - { - SecurityContext m_sc; - - public Reader(SecurityContext sc) { m_sc = sc; } - - public SecurityContext DangerousGetRawSecurityContext() { return m_sc; } - - public bool IsNull { get { return m_sc == null; } } - public bool IsSame(SecurityContext sc) { return m_sc == sc; } - public bool IsSame(SecurityContext.Reader sc) { return m_sc == sc.m_sc; } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool IsFlowSuppressed(SecurityContextDisableFlow flags) - { - return (m_sc == null) ? false : ((m_sc._disableFlow & flags) == flags); - } - - public CompressedStack CompressedStack { get { return IsNull ? null : m_sc.CompressedStack; } } - - public WindowsIdentity WindowsIdentity - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { return IsNull ? null : m_sc.WindowsIdentity; } - } - } - - - static internal SecurityContext FullTrustSecurityContext - { - get - { - if (_fullTrustSC == null) - _fullTrustSC = CreateFullTrustSecurityContext(); - return _fullTrustSC; - } - } - - // link the security context to an ExecutionContext - internal ExecutionContext ExecutionContext - { - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - set - { - _executionContext = value; - } - } - - internal CompressedStack CompressedStack - { - get - { - return _compressedStack; - } - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - set - { - _compressedStack = value; - } - } - - public void Dispose() - { - } - - public static AsyncFlowControl SuppressFlow() - { - return SuppressFlow(SecurityContextDisableFlow.All); - } - - public static AsyncFlowControl SuppressFlowWindowsIdentity() - { - return SuppressFlow(SecurityContextDisableFlow.WI); - } - - internal static AsyncFlowControl SuppressFlow(SecurityContextDisableFlow flags) - { - if (IsFlowSuppressed(flags)) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes")); - } - - ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); - if (ec.SecurityContext == null) - ec.SecurityContext = new SecurityContext(); - AsyncFlowControl afc = new AsyncFlowControl(); - afc.Setup(flags); - return afc; - } - - public static void RestoreFlow() - { - SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext; - if (sc == null || sc._disableFlow == SecurityContextDisableFlow.Nothing) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow")); - } - sc._disableFlow = SecurityContextDisableFlow.Nothing; - } - - public static bool IsFlowSuppressed() - { - return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All); - } - - internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags) - { - return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags); - } - - // This method is special from a security perspective - the VM will not allow a stack walk to - // 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. - [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) - { - if (securityContext == null ) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext")); - } - Contract.EndContractBlock(); - - StackCrawlMark stackMark = StackCrawlMark.LookForMe; - - if (!securityContext.isNewCapture) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext")); - } - - securityContext.isNewCapture = false; - - ExecutionContext.Reader ec = Thread.CurrentThread.GetExecutionContextReader(); - - // Optimization: do the callback directly if both the current and target contexts are equal to the - // default full-trust security context - if ( SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) - && securityContext.IsDefaultFTSecurityContext()) - { - callback(state); - - if (GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) != null) - { - // If we enter here it means the callback did an impersonation - // that we need to revert. - // We don't need to revert any other security state since it is stack-based - // and automatically goes away when the callback returns. - WindowsIdentity.SafeRevertToSelf(ref stackMark); - // Ensure we have reverted to the state we entered in. - Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null); - } - } - else - { - RunInternal(securityContext, callback, state); - } - - } - internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state) - { - if (cleanupCode == null) - { - tryCode = new RuntimeHelpers.TryCode(runTryCode); - cleanupCode = new RuntimeHelpers.CleanupCode(runFinallyCode); - } - SecurityContextRunData runData = new SecurityContextRunData(securityContext, callBack, state); - RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, runData); - - } - - internal class SecurityContextRunData - { - internal SecurityContext sc; - internal ContextCallback callBack; - internal Object state; - internal SecurityContextSwitcher scsw; - internal SecurityContextRunData(SecurityContext securityContext, ContextCallback cb, Object state) - { - this.sc = securityContext; - this.callBack = cb; - this.state = state; - this.scsw = new SecurityContextSwitcher(); - } - } - - static internal void runTryCode(Object userData) - { - SecurityContextRunData rData = (SecurityContextRunData) userData; - rData.scsw = SetSecurityContext(rData.sc, Thread.CurrentThread.GetExecutionContextReader().SecurityContext, modifyCurrentExecutionContext: true); - rData.callBack(rData.state); - - } - - [PrePrepareMethod] - static internal void runFinallyCode(Object userData, bool exceptionThrown) - { - SecurityContextRunData rData = (SecurityContextRunData) userData; - rData.scsw.Undo(); - } - - static volatile internal RuntimeHelpers.TryCode tryCode; - static volatile internal RuntimeHelpers.CleanupCode cleanupCode; - - - - // Internal API that gets called from public SetSecurityContext and from SetExecutionContext - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - [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) - { - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return SetSecurityContext(sc, prevSecurityContext, modifyCurrentExecutionContext, ref stackMark); - } - -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - internal static SecurityContextSwitcher SetSecurityContext(SecurityContext sc, SecurityContext.Reader prevSecurityContext, bool modifyCurrentExecutionContext, ref StackCrawlMark stackMark) - { - // Save the flow state at capture and reset it in the SC. - SecurityContextDisableFlow _capturedFlowState = sc._disableFlow; - sc._disableFlow = SecurityContextDisableFlow.Nothing; - - //Set up the switcher object - SecurityContextSwitcher scsw = new SecurityContextSwitcher(); - scsw.currSC = sc; - scsw.prevSC = prevSecurityContext; - - if (modifyCurrentExecutionContext) - { - // save the current Execution Context - ExecutionContext currEC = Thread.CurrentThread.GetMutableExecutionContext(); - scsw.currEC = currEC; - currEC.SecurityContext = sc; - } - - if (sc != null) - { - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - scsw.cssw = CompressedStack.SetCompressedStack(sc.CompressedStack, prevSecurityContext.CompressedStack); - } - catch - { - scsw.UndoNoThrow(); - throw; - } - } - return scsw; - } - - /// <internalonly/> - public SecurityContext CreateCopy() - { - if (!isNewCapture) - { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext")); - } - - SecurityContext sc = new SecurityContext(); - sc.isNewCapture = true; - sc._disableFlow = _disableFlow; - - if (_compressedStack != null) - sc._compressedStack = _compressedStack.CreateCopy(); - - return sc; - } - - /// <internalonly/> - internal SecurityContext CreateMutableCopy() - { - Debug.Assert(!this.isNewCapture); - - SecurityContext sc = new SecurityContext(); - sc._disableFlow = this._disableFlow; - - if (this._compressedStack != null) - sc._compressedStack = this._compressedStack.CreateCopy(); - - return sc; - } - - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable - public static SecurityContext Capture( ) - { - // check to see if Flow is suppressed - if (IsFlowSuppressed()) - return null; - - StackCrawlMark stackMark= StackCrawlMark.LookForMyCaller; - SecurityContext sc = SecurityContext.Capture(Thread.CurrentThread.GetExecutionContextReader(), ref stackMark); - if (sc == null) - sc = CreateFullTrustSecurityContext(); - return sc; - } - - // create a clone from a non-existing SecurityContext - [MethodImpl(MethodImplOptions.AggressiveInlining)] - static internal SecurityContext Capture(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark) - { - // check to see if Flow is suppressed - if (currThreadEC.SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All)) - return null; - - // If we're in FT right now, return null - if (CurrentlyInDefaultFTSecurityContext(currThreadEC)) - return null; - - return CaptureCore(currThreadEC, ref stackMark); - } - - static private SecurityContext CaptureCore(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark) - { - SecurityContext sc = new SecurityContext(); - sc.isNewCapture = true; - - // Force create CompressedStack - sc.CompressedStack = CompressedStack.GetCompressedStack(ref stackMark); - return sc; - } - - static internal SecurityContext CreateFullTrustSecurityContext() - { - SecurityContext sc = new SecurityContext(); - sc.isNewCapture = true; - - // Force create CompressedStack - sc.CompressedStack = new CompressedStack(null); - return sc; - } - - internal bool IsDefaultFTSecurityContext() - { - return (CompressedStack == null || CompressedStack.CompressedStackHandle == null); - } - static internal bool CurrentlyInDefaultFTSecurityContext(ExecutionContext threadEC) - { - return (IsDefaultThreadSecurityInfo()); - } - - [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 deleted file mode 100644 index f57665b278..0000000000 --- a/src/mscorlib/src/System/Security/SecurityElement.cs +++ /dev/null @@ -1,875 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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; - using System.Collections; - using System.Collections.Generic; - using System.Security.Util; - using System.Text; - using System.Globalization; - using System.IO; - using System.Security.Permissions; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - internal enum SecurityElementType - { - Regular = 0, - Format = 1, - Comment = 2 - } - - - internal interface ISecurityElementFactory - { - SecurityElement CreateSecurityElement(); - - Object Copy(); - - String GetTag(); - - String Attribute( String attributeName ); - } - - [Serializable] -[System.Runtime.InteropServices.ComVisible(true)] - sealed public class SecurityElement : ISecurityElementFactory - { - internal String m_strTag; - internal String m_strText; - private ArrayList m_lChildren; - internal ArrayList m_lAttributes; - internal SecurityElementType m_type = SecurityElementType.Regular; - - private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' }; - private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' }; - private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' }; - private const String s_strIndent = " "; - - private const int c_AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute - private const int c_ChildrenTypical = 1; - - private static readonly String[] s_escapeStringPairs = new String[] - { - // these must be all once character escape sequences or a new escaping algorithm is needed - "<", "<", - ">", ">", - "\"", """, - "\'", "'", - "&", "&" - }; - - private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' }; - - //-------------------------- Constructors --------------------------- - - internal SecurityElement() - { - } - -////// ISecurityElementFactory implementation - - SecurityElement ISecurityElementFactory.CreateSecurityElement() - { - return this; - } - - String ISecurityElementFactory.GetTag() - { - return ((SecurityElement)this).Tag; - } - - Object ISecurityElementFactory.Copy() - { - return ((SecurityElement)this).Copy(); - } - - String ISecurityElementFactory.Attribute( String attributeName ) - { - return ((SecurityElement)this).Attribute( attributeName ); - } - - public SecurityElement( String tag ) - { - if (tag == null) - throw new ArgumentNullException( nameof(tag) ); - - if (!IsValidTag( tag )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) ); - Contract.EndContractBlock(); - - m_strTag = tag; - m_strText = null; - } - - public SecurityElement( String tag, String text ) - { - if (tag == null) - throw new ArgumentNullException( nameof(tag) ); - - if (!IsValidTag( tag )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) ); - - if (text != null && !IsValidText( text )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementText" ), text ) ); - Contract.EndContractBlock(); - - m_strTag = tag; - m_strText = text; - } - - //-------------------------- Properties ----------------------------- - - public String Tag - { - [Pure] - get - { - return m_strTag; - } - - set - { - if (value == null) - throw new ArgumentNullException( nameof(Tag) ); - - if (!IsValidTag( value )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) ); - Contract.EndContractBlock(); - - m_strTag = value; - } - } - - public Hashtable Attributes - { - get - { - if (m_lAttributes == null || m_lAttributes.Count == 0) - { - return null; - } - else - { - Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 ); - - int iMax = m_lAttributes.Count; - 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) - { - hashtable.Add( m_lAttributes[i], m_lAttributes[i+1]); - } - - return hashtable; - } - } - - set - { - if (value == null || value.Count == 0) - { - m_lAttributes = null; - } - else - { - ArrayList list = new ArrayList(value.Count); - - System.Collections.IDictionaryEnumerator enumerator = (System.Collections.IDictionaryEnumerator)value.GetEnumerator(); - - while (enumerator.MoveNext()) - { - String attrName = (String)enumerator.Key; - String attrValue = (String)enumerator.Value; - - if (!IsValidAttributeName( attrName )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), (String)enumerator.Current ) ); - - if (!IsValidAttributeValue( attrValue )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), (String)enumerator.Value ) ); - - list.Add(attrName); - list.Add(attrValue); - } - - m_lAttributes = list; - } - } - } - - public String Text - { - get - { - return Unescape( m_strText ); - } - - set - { - if (value == null) - { - m_strText = null; - } - else - { - if (!IsValidText( value )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) ); - - m_strText = value; - } - } - } - - public ArrayList Children - { - get - { - ConvertSecurityElementFactories(); - return m_lChildren; - } - - set - { - if (value != null) - { - IEnumerator enumerator = value.GetEnumerator(); - - while (enumerator.MoveNext()) - { - if (enumerator.Current == null) - throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Child" ) ); - } - } - - m_lChildren = value; - } - } - - internal void ConvertSecurityElementFactories() - { - if (m_lChildren == null) - return; - - for (int i = 0; i < m_lChildren.Count; ++i) - { - ISecurityElementFactory iseFactory = m_lChildren[i] as ISecurityElementFactory; - if (iseFactory != null && !(m_lChildren[i] is SecurityElement)) - m_lChildren[i] = iseFactory.CreateSecurityElement(); - } - } - - internal ArrayList InternalChildren - { - get - { - // Beware! This array list can contain SecurityElements and other ISecurityElementFactories. - // If you want to get a consistent SecurityElement view, call get_Children. - return m_lChildren; - } - } - - //-------------------------- Public Methods ----------------------------- - - internal void AddAttributeSafe( String name, String value ) - { - if (m_lAttributes == null) - { - m_lAttributes = new ArrayList( c_AttributesTypical ); - } - else - { - int iMax = m_lAttributes.Count; - 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) - { - String strAttrName = (String)m_lAttributes[i]; - - if (String.Equals(strAttrName, name)) - throw new ArgumentException( Environment.GetResourceString( "Argument_AttributeNamesMustBeUnique" ) ); - } - } - - m_lAttributes.Add(name); - m_lAttributes.Add(value); - } - - public void AddAttribute( String name, String value ) - { - if (name == null) - throw new ArgumentNullException( nameof(name) ); - - if (value == null) - throw new ArgumentNullException( nameof(value) ); - - if (!IsValidAttributeName( name )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) ); - - if (!IsValidAttributeValue( value )) - throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), value ) ); - Contract.EndContractBlock(); - - AddAttributeSafe( name, value ); - } - - public void AddChild( SecurityElement child ) - { - if (child == null) - throw new ArgumentNullException( nameof(child) ); - Contract.EndContractBlock(); - - if (m_lChildren == null) - m_lChildren = new ArrayList( c_ChildrenTypical ); - - m_lChildren.Add( child ); - } - - internal void AddChild( ISecurityElementFactory child ) - { - if (child == null) - throw new ArgumentNullException( nameof(child) ); - Contract.EndContractBlock(); - - if (m_lChildren == null) - m_lChildren = new ArrayList( c_ChildrenTypical ); - - m_lChildren.Add( child ); - } - - internal void AddChildNoDuplicates( ISecurityElementFactory child ) - { - if (child == null) - throw new ArgumentNullException( nameof(child) ); - Contract.EndContractBlock(); - - if (m_lChildren == null) - { - m_lChildren = new ArrayList( c_ChildrenTypical ); - m_lChildren.Add( child ); - } - else - { - for (int i = 0; i < m_lChildren.Count; ++i) - { - if (m_lChildren[i] == child) - return; - } - m_lChildren.Add( child ); - } - } - - public bool Equal( SecurityElement other ) - { - if (other == null) - return false; - - // Check if the tags are the same - if (!String.Equals(m_strTag, other.m_strTag)) - return false; - - // Check if the text is the same - if (!String.Equals(m_strText, other.m_strText)) - return false; - - // Check if the attributes are the same and appear in the same - // order. - - // Maybe we can get away by only checking the number of attributes - if (m_lAttributes == null || other.m_lAttributes == null) - { - if (m_lAttributes != other.m_lAttributes) - return false; - } - else - { - int iMax = m_lAttributes.Count; - 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; - - for (int i = 0; i < iMax; i++) - { - String lhs = (String)m_lAttributes[i]; - String rhs = (String)other.m_lAttributes[i]; - - if (!String.Equals(lhs, rhs)) - return false; - } - } - - // Finally we must check the child and make sure they are - // equal and in the same order - - // Maybe we can get away by only checking the number of children - if (m_lChildren == null || other.m_lChildren == null) - { - if (m_lChildren != other.m_lChildren) - return false; - } - else - { - if (m_lChildren.Count != other.m_lChildren.Count) - return false; - - this.ConvertSecurityElementFactories(); - other.ConvertSecurityElementFactories(); - - // Okay, we'll need to go through each one of them - IEnumerator lhs = m_lChildren.GetEnumerator(); - IEnumerator rhs = other.m_lChildren.GetEnumerator(); - - SecurityElement e1, e2; - while (lhs.MoveNext()) - { - rhs.MoveNext(); - e1 = (SecurityElement)lhs.Current; - e2 = (SecurityElement)rhs.Current; - if (e1 == null || !e1.Equal(e2)) - return false; - } - } - return true; - } - - [System.Runtime.InteropServices.ComVisible(false)] - public SecurityElement Copy() - { - SecurityElement element = new SecurityElement( this.m_strTag, this.m_strText ); - element.m_lChildren = this.m_lChildren == null ? null : new ArrayList( this.m_lChildren ); - element.m_lAttributes = this.m_lAttributes == null ? null : new ArrayList(this.m_lAttributes); - - return element; - } - - [Pure] - public static bool IsValidTag( String tag ) - { - if (tag == null) - return false; - - return tag.IndexOfAny( s_tagIllegalCharacters ) == -1; - } - - [Pure] - public static bool IsValidText( String text ) - { - if (text == null) - return false; - - return text.IndexOfAny( s_textIllegalCharacters ) == -1; - } - - [Pure] - public static bool IsValidAttributeName( String name ) - { - return IsValidTag( name ); - } - - [Pure] - public static bool IsValidAttributeValue( String value ) - { - if (value == null) - return false; - - return value.IndexOfAny( s_valueIllegalCharacters ) == -1; - } - - private static String GetEscapeSequence( char c ) - { - int iMax = s_escapeStringPairs.Length; - 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) - { - String strEscSeq = s_escapeStringPairs[i]; - String strEscValue = s_escapeStringPairs[i+1]; - - if (strEscSeq[0] == c) - return strEscValue; - } - - Debug.Assert( false, "Unable to find escape sequence for this character" ); - return c.ToString(); - } - - public static String Escape( String str ) - { - if (str == null) - return null; - - StringBuilder sb = null; - - int strLen = str.Length; - int index; // Pointer into the string that indicates the location of the current '&' character - int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed). - - - do - { - index = str.IndexOfAny( s_escapeChars, newIndex ); - - if (index == -1) - { - if (sb == null) - return str; - else - { - sb.Append( str, newIndex, strLen - newIndex ); - return sb.ToString(); - } - } - else - { - if (sb == null) - sb = new StringBuilder(); - - sb.Append( str, newIndex, index - newIndex ); - sb.Append( GetEscapeSequence( str[index] ) ); - - newIndex = ( index + 1 ); - } - } - while (true); - - // no normal exit is possible - } - - private static String GetUnescapeSequence( String str, int index, out int newIndex ) - { - int maxCompareLength = str.Length - index; - - int iMax = s_escapeStringPairs.Length; - 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) - { - String strEscSeq = s_escapeStringPairs[i]; - String strEscValue = s_escapeStringPairs[i+1]; - - int length = strEscValue.Length; - - if (length <= maxCompareLength && String.Compare( strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0) - { - newIndex = index + strEscValue.Length; - return strEscSeq; - } - } - - newIndex = index + 1; - return str[index].ToString(); - } - - - private static String Unescape( String str ) - { - if (str == null) - return null; - - StringBuilder sb = null; - - int strLen = str.Length; - int index; // Pointer into the string that indicates the location of the current '&' character - int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed). - - do - { - index = str.IndexOf( '&', newIndex ); - - if (index == -1) - { - if (sb == null) - return str; - else - { - sb.Append( str, newIndex, strLen - newIndex ); - return sb.ToString(); - } - } - else - { - if (sb == null) - sb = new StringBuilder(); - - sb.Append(str, newIndex, index - newIndex); - sb.Append( GetUnescapeSequence( str, index, out newIndex ) ); // updates the newIndex too - - } - } - while (true); - - // C# reports a warning if I leave this in, but I still kinda want to just in case. - // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" ); - // return str; - } - - private delegate void ToStringHelperFunc( Object obj, String str ); - - private static void ToStringHelperStringBuilder( Object obj, String str ) - { - ((StringBuilder)obj).Append( str ); - } - - public override String ToString () - { - StringBuilder sb = new StringBuilder(); - - ToString( "", sb, new ToStringHelperFunc( ToStringHelperStringBuilder ) ); - - return sb.ToString(); - } - - private void ToString( String indent, Object obj, ToStringHelperFunc func ) - { - // First add the indent - - // func( obj, indent ); - - // Add in the opening bracket and the tag. - - func( obj, "<" ); - - switch (m_type) - { - case SecurityElementType.Format: - func( obj, "?" ); - break; - - case SecurityElementType.Comment: - func( obj, "!" ); - break; - - default: - break; - } - - func( obj, m_strTag ); - - // If there are any attributes, plop those in. - - if (m_lAttributes != null && m_lAttributes.Count > 0) - { - func( obj, " " ); - - int iMax = m_lAttributes.Count; - 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) - { - String strAttrName = (String)m_lAttributes[i]; - String strAttrValue = (String)m_lAttributes[i+1]; - - func( obj, strAttrName ); - func( obj, "=\"" ); - func( obj, strAttrValue ); - func( obj, "\"" ); - - if (i != m_lAttributes.Count - 2) - { - if (m_type == SecurityElementType.Regular) - { - func( obj, Environment.NewLine ); - } - else - { - func( obj, " " ); - } - } - } - } - - if (m_strText == null && (m_lChildren == null || m_lChildren.Count == 0)) - { - // If we are a single tag with no children, just add the end of tag text. - - switch (m_type) - { - case SecurityElementType.Comment: - func( obj, ">" ); - break; - - case SecurityElementType.Format: - func( obj, " ?>" ); - break; - - default: - func( obj, "/>" ); - break; - } - func( obj, Environment.NewLine ); - } - else - { - // Close the current tag. - - func( obj, ">" ); - - // Output the text - - func( obj, m_strText ); - - // Output any children. - - if (m_lChildren != null) - { - this.ConvertSecurityElementFactories(); - - func( obj, Environment.NewLine ); - - // String childIndent = indent + s_strIndent; - - for (int i = 0; i < m_lChildren.Count; ++i) - { - ((SecurityElement)m_lChildren[i]).ToString( "", obj, func ); - } - - // In the case where we have children, the close tag will not be on the same line as the - // opening tag, so we need to indent. - - // func( obj, indent ); - } - - // Output the closing tag - - func( obj, "</" ); - func( obj, m_strTag ); - func( obj, ">" ); - func( obj, Environment.NewLine ); - } - } - - - - public String Attribute( String name ) - { - if (name == null) - throw new ArgumentNullException( nameof(name) ); - Contract.EndContractBlock(); - - // Note: we don't check for validity here because an - // if an invalid name is passed we simply won't find it. - - if (m_lAttributes == null) - return null; - - // Go through all the attribute and see if we know about - // the one we are asked for - - int iMax = m_lAttributes.Count; - 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) - { - String strAttrName = (String)m_lAttributes[i]; - - if (String.Equals(strAttrName, name)) - { - String strAttrValue = (String)m_lAttributes[i+1]; - - return Unescape(strAttrValue); - } - } - - // In the case where we didn't find it, we are expected to - // return null - return null; - } - - public SecurityElement SearchForChildByTag( String tag ) - { - // Go through all the children and see if we can - // find the one are are asked for (matching tags) - - if (tag == null) - throw new ArgumentNullException( nameof(tag) ); - Contract.EndContractBlock(); - - // Note: we don't check for a valid tag here because - // an invalid tag simply won't be found. - - if (m_lChildren == null) - return null; - - IEnumerator enumerator = m_lChildren.GetEnumerator(); - - while (enumerator.MoveNext()) - { - SecurityElement current = (SecurityElement)enumerator.Current; - - if (current != null && String.Equals(current.Tag, tag)) - return current; - } - return null; - } - - internal String SearchForTextOfLocalName(String strLocalName) - { - // Search on each child in order and each - // child's child, depth-first - - if (strLocalName == null) - throw new ArgumentNullException( nameof(strLocalName) ); - Contract.EndContractBlock(); - - // Note: we don't check for a valid tag here because - // an invalid tag simply won't be found. - - // First we check this. - - if (m_strTag == null) return null; - if (m_strTag.Equals( strLocalName ) || m_strTag.EndsWith( ":" + strLocalName, StringComparison.Ordinal )) - return Unescape( m_strText ); - if (m_lChildren == null) - return null; - - IEnumerator enumerator = m_lChildren.GetEnumerator(); - - while (enumerator.MoveNext()) - { - String current = ((SecurityElement)enumerator.Current).SearchForTextOfLocalName( strLocalName ); - - if (current != null) - return current; - } - return null; - } - - public String SearchForTextOfTag( String tag ) - { - // Search on each child in order and each - // child's child, depth-first - - if (tag == null) - throw new ArgumentNullException( nameof(tag) ); - Contract.EndContractBlock(); - - // Note: we don't check for a valid tag here because - // an invalid tag simply won't be found. - - // First we check this. - - if (String.Equals(m_strTag, tag)) - return Unescape( m_strText ); - if (m_lChildren == null) - return null; - - IEnumerator enumerator = m_lChildren.GetEnumerator(); - - this.ConvertSecurityElementFactories(); - - while (enumerator.MoveNext()) - { - String current = ((SecurityElement)enumerator.Current).SearchForTextOfTag( tag ); - - if (current != null) - return current; - } - return null; - } - } -} diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs index c76674cdb9..8811be82ff 100644 --- a/src/mscorlib/src/System/Security/SecurityException.cs +++ b/src/mscorlib/src/System/Security/SecurityException.cs @@ -18,30 +18,23 @@ namespace System.Security using System.Security; using System; using System.Runtime.Serialization; - using System.Security.Permissions; using System.Reflection; using System.Text; using System.Security.Policy; using System.IO; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION using System.Globalization; - using System.Security.Util; using System.Diagnostics.Contracts; - [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class SecurityException : SystemException { internal static string GetResString(string sResourceName) { - PermissionSet.s_fullTrust.Assert(); return Environment.GetResourceString(sResourceName); } #pragma warning disable 618 - internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) + internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, RuntimeMethodHandleInternal rmh, Object demand) #pragma warning restore 618 { return new SecurityException(GetResString("Arg_SecurityException")); @@ -66,16 +59,6 @@ namespace System.Security SetErrorCode(System.__HResults.COR_E_SECURITY); } - 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(){} - protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) @@ -88,22 +71,6 @@ namespace System.Security return base.ToString(); } - private bool CanAccessSensitiveInfo() - { - bool retVal = false; - try - { -#pragma warning disable 618 - new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy).Demand(); -#pragma warning restore 618 - retVal = true; - } - catch (SecurityException) - { - } - return retVal; - } - public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) diff --git a/src/mscorlib/src/System/Security/SecurityManager.cs b/src/mscorlib/src/System/Security/SecurityManager.cs deleted file mode 100644 index 933fe0be3d..0000000000 --- a/src/mscorlib/src/System/Security/SecurityManager.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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 -{ - using System; - using System.Security.Permissions; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - - [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] - public enum PolicyLevelType - { - User = 0, - Machine = 1, - Enterprise = 2, - AppDomain = 3 - } - - [System.Runtime.InteropServices.ComVisible(true)] - static public class SecurityManager - { - private static int[][] s_BuiltInPermissionIndexMap = { - new int[] { BuiltInPermissionIndex.EnvironmentPermissionIndex, (int) PermissionType.EnvironmentPermission }, - new int[] { BuiltInPermissionIndex.FileDialogPermissionIndex, (int) PermissionType.FileDialogPermission }, - new int[] { BuiltInPermissionIndex.FileIOPermissionIndex, (int) PermissionType.FileIOPermission }, - new int[] { BuiltInPermissionIndex.ReflectionPermissionIndex, (int) PermissionType.ReflectionPermission }, - new int[] { BuiltInPermissionIndex.SecurityPermissionIndex, (int) PermissionType.SecurityPermission }, - new int[] { BuiltInPermissionIndex.UIPermissionIndex, (int) PermissionType.UIPermission } - }; - - private static CodeAccessPermission[] s_UnrestrictedSpecialPermissionMap = { - new EnvironmentPermission(PermissionState.Unrestricted), - new FileDialogPermission(PermissionState.Unrestricted), - new FileIOPermission(PermissionState.Unrestricted), - new ReflectionPermission(PermissionState.Unrestricted), - new SecurityPermission(PermissionState.Unrestricted), - new UIPermission(PermissionState.Unrestricted) - }; - - internal static int GetSpecialFlags (PermissionSet grantSet, PermissionSet deniedSet) { - if ((grantSet != null && grantSet.IsUnrestricted()) && (deniedSet == null || deniedSet.IsEmpty())) { - return -1; - } - else { - SecurityPermission securityPermission = null; -#pragma warning disable 618 - SecurityPermissionFlag securityPermissionFlags = SecurityPermissionFlag.NoFlags; -#pragma warning restore 618 - ReflectionPermission reflectionPermission = null; - ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags; - - CodeAccessPermission[] specialPermissions = new CodeAccessPermission[6]; - if (grantSet != null) { - if (grantSet.IsUnrestricted()) { -#pragma warning disable 618 - securityPermissionFlags = SecurityPermissionFlag.AllFlags; -#pragma warning restore 618 - reflectionPermissionFlags = ReflectionPermission.AllFlagsAndMore; - for (int i = 0; i < specialPermissions.Length; i++) { - specialPermissions[i] = s_UnrestrictedSpecialPermissionMap[i]; - } - } - else { - securityPermission = grantSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission; - if (securityPermission != null) - securityPermissionFlags = securityPermission.Flags; - reflectionPermission = grantSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission; - if (reflectionPermission != null) - reflectionPermissionFlags = reflectionPermission.Flags; - for (int i = 0; i < specialPermissions.Length; i++) { - specialPermissions[i] = grantSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission; - } - } - } - - if (deniedSet != null) { - if (deniedSet.IsUnrestricted()) { -#pragma warning disable 618 - securityPermissionFlags = SecurityPermissionFlag.NoFlags; -#pragma warning restore 618 - reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags; - for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) { - specialPermissions[i] = null; - } - } - else { - securityPermission = deniedSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission; - if (securityPermission != null) - securityPermissionFlags &= ~securityPermission.Flags; - reflectionPermission = deniedSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission; - if (reflectionPermission != null) - reflectionPermissionFlags &= ~reflectionPermission.Flags; - for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) { - CodeAccessPermission deniedSpecialPermission = deniedSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission; - if (deniedSpecialPermission != null && !deniedSpecialPermission.IsSubsetOf(null)) - specialPermissions[i] = null; // we don't care about the exact value here. - } - } - } - int flags = MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags); - if (flags != -1) { - for (int i = 0; i < specialPermissions.Length; i++) { - if (specialPermissions[i] != null && ((IUnrestrictedPermission) specialPermissions[i]).IsUnrestricted()) - flags |= (1 << (int) s_BuiltInPermissionIndexMap[i][1]); - } - } - return flags; - } - } - -#pragma warning disable 618 - private static int MapToSpecialFlags (SecurityPermissionFlag securityPermissionFlags, ReflectionPermissionFlag reflectionPermissionFlags) { - int flags = 0; - if ((securityPermissionFlags & SecurityPermissionFlag.UnmanagedCode) == SecurityPermissionFlag.UnmanagedCode) - flags |= (1 << (int) PermissionType.SecurityUnmngdCodeAccess); - if ((securityPermissionFlags & SecurityPermissionFlag.SkipVerification) == SecurityPermissionFlag.SkipVerification) - flags |= (1 << (int) PermissionType.SecuritySkipVerification); - if ((securityPermissionFlags & SecurityPermissionFlag.Assertion) == SecurityPermissionFlag.Assertion) - flags |= (1 << (int) PermissionType.SecurityAssert); - if ((securityPermissionFlags & SecurityPermissionFlag.SerializationFormatter) == SecurityPermissionFlag.SerializationFormatter) - flags |= (1 << (int) PermissionType.SecuritySerialization); - if ((securityPermissionFlags & SecurityPermissionFlag.BindingRedirects) == SecurityPermissionFlag.BindingRedirects) - flags |= (1 << (int) PermissionType.SecurityBindingRedirects); - if ((securityPermissionFlags & SecurityPermissionFlag.ControlEvidence) == SecurityPermissionFlag.ControlEvidence) - flags |= (1 << (int) PermissionType.SecurityControlEvidence); - if ((securityPermissionFlags & SecurityPermissionFlag.ControlPrincipal) == SecurityPermissionFlag.ControlPrincipal) - flags |= (1 << (int) PermissionType.SecurityControlPrincipal); - - if ((reflectionPermissionFlags & ReflectionPermissionFlag.RestrictedMemberAccess) == ReflectionPermissionFlag.RestrictedMemberAccess) - flags |= (1 << (int)PermissionType.ReflectionRestrictedMemberAccess); - if ((reflectionPermissionFlags & ReflectionPermissionFlag.MemberAccess) == ReflectionPermissionFlag.MemberAccess) - flags |= (1 << (int) PermissionType.ReflectionMemberAccess); - - return flags; - } -#pragma warning restore 618 - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern bool IsSameType(String strLeft, String strRight); - - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool _SetThreadSecurity(bool bThreadSecurity); - - [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 deleted file mode 100644 index d037fe939d..0000000000 --- a/src/mscorlib/src/System/Security/SecurityRuntime.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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; - using System.Globalization; - using System.Threading; - using System.Reflection; - using System.Collections; - using System.Runtime.CompilerServices; - using System.Security.Permissions; - using System.Runtime.Versioning; - using System.Diagnostics.Contracts; - - internal class SecurityRuntime - { - private SecurityRuntime(){} - - // Returns the security object for the caller of the method containing - // 'stackMark' on its frame. - // - // THE RETURNED OBJECT IS THE LIVE RUNTIME OBJECT. BE CAREFUL WITH IT! - // - // Internal only, do not doc. - // - [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern - FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark, - bool create); - - // Constants used to return status to native - internal const bool StackContinue = true; - internal const bool StackHalt = false; - - // this method is a big perf hit, so don't call unnecessarily - internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh) - { - if (rmh.IsNullHandle()) - return null; - -#if _DEBUG - try - { -#endif - // Assert here because reflection will check grants and if we fail the check, - // there will be an infinite recursion that overflows the stack. - PermissionSet.s_fullTrust.Assert(); - return (System.RuntimeType.GetMethodBase(RuntimeMethodHandle.GetDeclaringType(rmh), rmh) as MethodInfo); -#if _DEBUG - } - catch(Exception) - { - return null; - } -#endif - } - - private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc, - PermissionSet demandSet, - out PermissionSet alteredDemandSet, - RuntimeMethodHandleInternal rmh) - { - return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh); - } - - private static bool FrameDescHelper(FrameSecurityDescriptor secDesc, - IPermission demandIn, - PermissionToken permToken, - RuntimeMethodHandleInternal rmh) - { - return secDesc.CheckDemand((CodeAccessPermission) demandIn, permToken, rmh); - } - -#if FEATURE_COMPRESSEDSTACK - private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver, - PermissionSet demandSet, - out PermissionSet alteredDemandSet, - RuntimeMethodHandleInternal rmh) - { - System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext(); - bool result; - try - { - result = creationStack.CheckSetDemandWithModificationNoHalt(demandSet, out alteredDemandSet, rmh); - } - catch (SecurityException ex) - { - throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex); - } - - return result; - } - - private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver, - IPermission demandIn, - PermissionToken permToken, - RuntimeMethodHandleInternal rmh) - { - System.Threading.CompressedStack creationStack = dynamicResolver.GetSecurityContext(); - bool result; - try - { - result = creationStack.CheckDemandNoHalt((CodeAccessPermission)demandIn, permToken, rmh); - } - catch (SecurityException ex) - { - throw new SecurityException(Environment.GetResourceString("Security_AnonymouslyHostedDynamicMethodCheckFailed"), ex); - } - return result; - } -#endif // FEATURE_COMPRESSEDSTACK - - // - // API for PermissionSets - // - - internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark) - { - } - - internal static void AssertAllPossible(ref StackCrawlMark stackMark) - { - } - - internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark) - { - } - - internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark) - { - } - - // - // Revert API - // - - internal static void RevertAssert(ref StackCrawlMark stackMark) - { - } - - internal static void RevertDeny(ref StackCrawlMark stackMark) - { - } - - internal static void RevertPermitOnly(ref StackCrawlMark stackMark) - { - } - - internal static void RevertAll(ref StackCrawlMark stackMark) - { - } - } -} - - diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs index 3c7f8bf49f..55dcce07c0 100644 --- a/src/mscorlib/src/System/Security/SecurityState.cs +++ b/src/mscorlib/src/System/Security/SecurityState.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; using System.Security; -using System.Security.Permissions; namespace System.Security { diff --git a/src/mscorlib/src/System/Security/SecurityZone.cs b/src/mscorlib/src/System/Security/SecurityZone.cs deleted file mode 100644 index a74b637846..0000000000 --- a/src/mscorlib/src/System/Security/SecurityZone.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// -// -// Enumeration of the zones code can come from -// - -namespace System.Security -{ - using System; - using System.Runtime.InteropServices; - - // The quick cache code depends on the values in this enumeration. Any change to this enumeration should - // be reflected in PolicyManager.GenerateQuickCache as well. - [ComVisible(true)] - [Serializable] - public enum SecurityZone - { - MyComputer = 0, - Intranet = 1, - Trusted = 2, - Internet = 3, - Untrusted = 4, - - NoZone = -1, // No Zone Information - } -} diff --git a/src/mscorlib/src/System/Security/Util/Config.cs b/src/mscorlib/src/System/Security/Util/Config.cs deleted file mode 100644 index afc9b8c336..0000000000 --- a/src/mscorlib/src/System/Security/Util/Config.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Util { - using System; - using System.Security.Util; - using System.Security.Policy; - using System.Security.Permissions; - using System.Collections; - using System.IO; - using System.Reflection; - using System.Globalization; - using System.Text; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION - using System.Threading; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Runtime.Versioning; - - // Duplicated in vm\COMSecurityConfig.h -[Serializable] -[Flags] - internal enum QuickCacheEntryType - { - FullTrustZoneMyComputer = 0x1000000, - FullTrustZoneIntranet = 0x2000000, - FullTrustZoneInternet = 0x4000000, - FullTrustZoneTrusted = 0x8000000, - FullTrustZoneUntrusted = 0x10000000, - FullTrustAll = 0x20000000, - } - - internal static class Config { - private static volatile string m_machineConfig; - private static volatile string m_userConfig; - - private static void GetFileLocales() - { - if (m_machineConfig == null) - { - string machineConfig = null; - GetMachineDirectory(JitHelpers.GetStringHandleOnStack(ref machineConfig)); - m_machineConfig = machineConfig; - } - if (m_userConfig == null) - { - string userConfig = null; - GetUserDirectory(JitHelpers.GetStringHandleOnStack(ref userConfig)); - m_userConfig = userConfig; - } - } - - internal static string MachineDirectory - { - get - { - GetFileLocales(); - return m_machineConfig; - } - } - - internal static string UserDirectory - { - get - { - GetFileLocales(); - return m_userConfig; - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void GetMachineDirectory(StringHandleOnStack retDirectory); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void GetUserDirectory(StringHandleOnStack retDirectory); - - [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 deleted file mode 100644 index 4ca1cf678b..0000000000 --- a/src/mscorlib/src/System/Security/Util/Hex.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/* - * - * Operations to convert to and from Hex - * - */ - -namespace System.Security.Util -{ - using System; - using System.Security; - using System.Diagnostics.Contracts; - internal static class Hex - { - // converts number to hex digit. Does not do any range checks. - static char HexDigit(int num) { - return (char)((num < 10) ? (num + '0') : (num + ('A' - 10))); - } - - public static String EncodeHexString(byte[] sArray) - { - String result = null; - - if(sArray != null) { - char[] hexOrder = new char[sArray.Length * 2]; - - int digit; - for(int i = 0, j = 0; i < sArray.Length; i++) { - digit = (int)((sArray[i] & 0xf0) >> 4); - hexOrder[j++] = HexDigit(digit); - digit = (int)(sArray[i] & 0x0f); - hexOrder[j++] = HexDigit(digit); - } - result = new String(hexOrder); - } - return result; - } - - internal static string EncodeHexStringFromInt(byte[] sArray) { - String result = null; - if(sArray != null) { - char[] hexOrder = new char[sArray.Length * 2]; - - int i = sArray.Length; - int digit, j=0; - while (i-- > 0) { - digit = (sArray[i] & 0xf0) >> 4; - hexOrder[j++] = HexDigit(digit); - digit = sArray[i] & 0x0f; - hexOrder[j++] = HexDigit(digit); - } - result = new String(hexOrder); - } - return result; - } - - public static int ConvertHexDigit(Char val) - { - if (val <= '9' && val >= '0') - return (val - '0'); - else if (val >= 'a' && val <= 'f') - return ((val - 'a') + 10); - else if (val >= 'A' && val <= 'F') - return ((val - 'A') + 10); - else - throw new ArgumentException( Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); - } - - - public static byte[] DecodeHexString(String hexString) - { - if (hexString == null) - throw new ArgumentNullException( nameof(hexString) ); - Contract.EndContractBlock(); - - bool spaceSkippingMode = false; - - int i = 0; - int length = hexString.Length; - - if ((length >= 2) && - (hexString[0] == '0') && - ( (hexString[1] == 'x') || (hexString[1] == 'X') )) - { - length = hexString.Length - 2; - i = 2; - } - - // Hex strings must always have 2N or (3N - 1) entries. - - if (length % 2 != 0 && length % 3 != 2) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHexFormat" ) ); - } - - byte[] sArray; - - if (length >=3 && hexString[i + 2] == ' ') - { - spaceSkippingMode = true; - - // Each hex digit will take three spaces, except the first (hence the plus 1). - sArray = new byte[length / 3 + 1]; - } - else - { - // Each hex digit will take two spaces - sArray = new byte[length / 2]; - } - - int digit; - int rawdigit; - for (int j = 0; i < hexString.Length; i += 2, j++) { - rawdigit = ConvertHexDigit(hexString[i]); - digit = ConvertHexDigit(hexString[i+1]); - sArray[j] = (byte) (digit | (rawdigit << 4)); - if (spaceSkippingMode) - i++; - } - return(sArray); - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs deleted file mode 100644 index 8a12235106..0000000000 --- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs +++ /dev/null @@ -1,752 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Util { - using System.Text; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Globalization; - using System.Runtime.Versioning; - using System.IO; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - internal class StringExpressionSet - { - // This field, as well as the expressions fields below are critical since they may contain - // canonicalized full path data potentially built out of relative data passed as input to the - // StringExpressionSet. Full trust code using the string expression set needs to ensure that before - // exposing this data out to partial trust, they protect against this. Possibilities include: - // - // 1. Using the throwOnRelative flag - // 2. Ensuring that the partial trust code has permission to see full path data - // 3. Not using this set for paths (eg EnvironmentStringExpressionSet) - // - protected ArrayList m_list; - protected bool m_ignoreCase; - protected String m_expressions; - protected String[] m_expressionsArray; - - protected bool m_throwOnRelative; - - protected static readonly char[] m_separators = { ';' }; - protected static readonly char[] m_trimChars = { ' ' }; -#if !PLATFORM_UNIX - protected static readonly char m_directorySeparator = '\\'; - protected static readonly char m_alternateDirectorySeparator = '/'; -#else - protected static readonly char m_directorySeparator = '/'; - protected static readonly char m_alternateDirectorySeparator = '\\'; -#endif // !PLATFORM_UNIX - - public StringExpressionSet() - : this( true, null, false ) - { - } - - public StringExpressionSet( String str ) - : this( true, str, false ) - { - } - - public StringExpressionSet( bool ignoreCase, bool throwOnRelative ) - : this( ignoreCase, null, throwOnRelative ) - { - } - - public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative ) - { - m_list = null; - m_ignoreCase = ignoreCase; - m_throwOnRelative = throwOnRelative; - if (str == null) - m_expressions = null; - else - AddExpressions( str ); - } - - protected virtual StringExpressionSet CreateNewEmpty() - { - return new StringExpressionSet(); - } - - public virtual StringExpressionSet Copy() - { - // SafeCritical: just copying this value around, not leaking it - - StringExpressionSet copy = CreateNewEmpty(); - if (this.m_list != null) - copy.m_list = new ArrayList(this.m_list); - - copy.m_expressions = this.m_expressions; - copy.m_ignoreCase = this.m_ignoreCase; - copy.m_throwOnRelative = this.m_throwOnRelative; - return copy; - } - - public void SetThrowOnRelative( bool throwOnRelative ) - { - this.m_throwOnRelative = throwOnRelative; - } - - private static String StaticProcessWholeString( String str ) - { - return str.Replace( m_alternateDirectorySeparator, m_directorySeparator ); - } - - private static String StaticProcessSingleString( String str ) - { - return str.Trim( m_trimChars ); - } - - protected virtual String ProcessWholeString( String str ) - { - return StaticProcessWholeString(str); - } - - protected virtual String ProcessSingleString( String str ) - { - return StaticProcessSingleString(str); - } - - public void AddExpressions( String str ) - { - if (str == null) - throw new ArgumentNullException( nameof(str) ); - Contract.EndContractBlock(); - if (str.Length == 0) - return; - - str = ProcessWholeString( str ); - - if (m_expressions == null) - m_expressions = str; - else - m_expressions = m_expressions + m_separators[0] + str; - - m_expressionsArray = null; - - // We have to parse the string and compute the list here. - // The logic in this class tries to delay this parsing but - // since operations like IsSubsetOf are called during - // demand evaluation, it is not safe to delay this step - // as that would cause concurring threads to update the object - // at the same time. The CheckList operation should ideally be - // removed from this class, but for the sake of keeping the - // changes to a minimum here, we simply make sure m_list - // cannot be null by parsing m_expressions eagerly. - - String[] arystr = Split( str ); - - if (m_list == null) - m_list = new ArrayList(); - - for (int index = 0; index < arystr.Length; ++index) - { - if (arystr[index] != null && !arystr[index].Equals( "" )) - { - String temp = ProcessSingleString( arystr[index] ); - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && !temp.Equals( "" )) - { - if (m_throwOnRelative) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp ); - } - - m_list.Add( temp ); - } - } - } - - Reduce(); - } - - public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath ) - { - AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates); - } - - public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) - { - Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); - - m_expressionsArray = null; - m_expressions = null; - - if (m_list != null) - m_list.AddRange(exprArrayList); - else - m_list = new ArrayList(exprArrayList); - - if (checkForDuplicates) - Reduce(); - } - - - internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath) - { - if (str == null) - { - 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( nameof(str) ); - - // Replace alternate directory separators - String oneString = StaticProcessWholeString( str[index] ); - - if (oneString != null && oneString.Length != 0) - { - // Trim leading and trailing spaces - String temp = StaticProcessSingleString( oneString); - - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && temp.Length != 0) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException(Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp, needFullPath ); - - retArrayList.Add( temp ); - } - } - } - - return retArrayList; - } - - protected void CheckList() - { - if (m_list == null && m_expressions != null) - { - CreateList(); - } - } - - protected String[] Split( String expressions ) - { - if (m_throwOnRelative) - { - List<String> tempList = new List<String>(); - - String[] quoteSplit = expressions.Split( '\"' ); - - for (int i = 0; i < quoteSplit.Length; ++i) - { - if (i % 2 == 0) - { - String[] semiSplit = quoteSplit[i].Split( ';' ); - - for (int j = 0; j < semiSplit.Length; ++j) - { - if (semiSplit[j] != null && !semiSplit[j].Equals( "" )) - tempList.Add( semiSplit[j] ); - } - } - else - { - tempList.Add( quoteSplit[i] ); - } - } - - String[] finalArray = new String[tempList.Count]; - - IEnumerator enumerator = tempList.GetEnumerator(); - - int index = 0; - while (enumerator.MoveNext()) - { - finalArray[index++] = (String)enumerator.Current; - } - - return finalArray; - } - else - { - return expressions.Split( m_separators ); - } - } - - - protected void CreateList() - { - String[] expressionsArray = Split( m_expressions ); - - m_list = new ArrayList(); - - for (int index = 0; index < expressionsArray.Length; ++index) - { - if (expressionsArray[index] != null && !expressionsArray[index].Equals( "" )) - { - String temp = ProcessSingleString( expressionsArray[index] ); - - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && !temp.Equals( "" )) - { - if (m_throwOnRelative) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp ); - } - - m_list.Add( temp ); - } - } - } - } - - public bool IsEmpty() - { - // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their - // contents - not the existence of the contents - if (m_list == null) - { - return m_expressions == null; - } - else - { - return m_list.Count == 0; - } - } - - public bool IsSubsetOf( StringExpressionSet ses ) - { - if (this.IsEmpty()) - return true; - - if (ses == null || ses.IsEmpty()) - return false; - - CheckList(); - ses.CheckList(); - - for (int index = 0; index < this.m_list.Count; ++index) - { - if (!StringSubsetStringExpression( (String)this.m_list[index], ses, m_ignoreCase )) - { - return false; - } - } - return true; - } - - public bool IsSubsetOfPathDiscovery( StringExpressionSet ses ) - { - if (this.IsEmpty()) - return true; - - if (ses == null || ses.IsEmpty()) - return false; - - CheckList(); - ses.CheckList(); - - for (int index = 0; index < this.m_list.Count; ++index) - { - if (!StringSubsetStringExpressionPathDiscovery( (String)this.m_list[index], ses, m_ignoreCase )) - { - return false; - } - } - return true; - } - - - public StringExpressionSet Union( StringExpressionSet ses ) - { - // If either set is empty, the union represents a copy of the other. - - if (ses == null || ses.IsEmpty()) - return this.Copy(); - - if (this.IsEmpty()) - return ses.Copy(); - - CheckList(); - ses.CheckList(); - - // Perform the union - // note: insert smaller set into bigger set to reduce needed comparisons - - StringExpressionSet bigger = ses.m_list.Count > this.m_list.Count ? ses : this; - StringExpressionSet smaller = ses.m_list.Count <= this.m_list.Count ? ses : this; - - StringExpressionSet unionSet = bigger.Copy(); - - unionSet.Reduce(); - - for (int index = 0; index < smaller.m_list.Count; ++index) - { - unionSet.AddSingleExpressionNoDuplicates( (String)smaller.m_list[index] ); - } - - unionSet.GenerateString(); - - return unionSet; - } - - - public StringExpressionSet Intersect( StringExpressionSet ses ) - { - // If either set is empty, the intersection is empty - - if (this.IsEmpty() || ses == null || ses.IsEmpty()) - return CreateNewEmpty(); - - CheckList(); - ses.CheckList(); - - // Do the intersection for real - - StringExpressionSet intersectSet = CreateNewEmpty(); - - for (int this_index = 0; this_index < this.m_list.Count; ++this_index) - { - for (int ses_index = 0; ses_index < ses.m_list.Count; ++ses_index) - { - if (StringSubsetString( (String)this.m_list[this_index], (String)ses.m_list[ses_index], m_ignoreCase )) - { - if (intersectSet.m_list == null) - { - intersectSet.m_list = new ArrayList(); - } - intersectSet.AddSingleExpressionNoDuplicates( (String)this.m_list[this_index] ); - } - else if (StringSubsetString( (String)ses.m_list[ses_index], (String)this.m_list[this_index], m_ignoreCase )) - { - if (intersectSet.m_list == null) - { - intersectSet.m_list = new ArrayList(); - } - intersectSet.AddSingleExpressionNoDuplicates( (String)ses.m_list[ses_index] ); - } - } - } - - intersectSet.GenerateString(); - - return intersectSet; - } - - protected void GenerateString() - { - // SafeCritical - moves critical data around, but doesn't expose it out - if (m_list != null) - { - StringBuilder sb = new StringBuilder(); - - IEnumerator enumerator = this.m_list.GetEnumerator(); - bool first = true; - - while (enumerator.MoveNext()) - { - if (!first) - sb.Append( m_separators[0] ); - else - first = false; - - String currentString = (String)enumerator.Current; - if (currentString != null) - { - int indexOfSeparator = currentString.IndexOf( m_separators[0] ); - - if (indexOfSeparator != -1) - sb.Append( '\"' ); - - sb.Append( currentString ); - - if (indexOfSeparator != -1) - sb.Append( '\"' ); - } - } - - m_expressions = sb.ToString(); - } - else - { - m_expressions = null; - } - } - - // We don't override ToString since that API must be either transparent or safe citical. If the - // 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. - public string UnsafeToString() - { - CheckList(); - - Reduce(); - - GenerateString(); - - return m_expressions; - } - - public String[] UnsafeToStringArray() - { - if (m_expressionsArray == null && m_list != null) - { - m_expressionsArray = (String[])m_list.ToArray(typeof(String)); - } - - return m_expressionsArray; - } - - - //------------------------------- - // protected static helper functions - //------------------------------- - - private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase ) - { - for (int index = 0; index < right.m_list.Count; ++index) - { - if (StringSubsetString( left, (String)right.m_list[index], ignoreCase )) - { - return true; - } - } - return false; - } - - private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase ) - { - for (int index = 0; index < right.m_list.Count; ++index) - { - if (StringSubsetStringPathDiscovery( left, (String)right.m_list[index], ignoreCase )) - { - return true; - } - } - return false; - } - - - protected virtual bool StringSubsetString( String left, String right, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (right == null || left == null || right.Length == 0 || left.Length == 0 || - right.Length > left.Length) - { - return false; - } - else if (right.Length == left.Length) - { - // if they are equal in length, just do a normal compare - return String.Compare( right, left, strComp) == 0; - } - else if (left.Length - right.Length == 1 && left[left.Length-1] == m_directorySeparator) - { - return String.Compare( left, 0, right, 0, right.Length, strComp) == 0; - } - else if (right[right.Length-1] == m_directorySeparator) - { - // right is definitely a directory, just do a substring compare - return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; - } - else if (left[right.Length] == m_directorySeparator) - { - // left is hinting at being a subdirectory on right, do substring compare to make find out - return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; - } - else - { - return false; - } - } - - protected static bool StringSubsetStringPathDiscovery( String left, String right, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (right == null || left == null || right.Length == 0 || left.Length == 0) - { - return false; - } - else if (right.Length == left.Length) - { - // if they are equal in length, just do a normal compare - return String.Compare( right, left, strComp) == 0; - } - else - { - String shortString, longString; - - if (right.Length < left.Length) - { - shortString = right; - longString = left; - } - else - { - shortString = left; - longString = right; - } - - if (String.Compare( shortString, 0, longString, 0, shortString.Length, strComp) != 0) - { - return false; - } - -#if !PLATFORM_UNIX - if (shortString.Length == 3 && - shortString.EndsWith( ":\\", StringComparison.Ordinal ) && - ((shortString[0] >= 'A' && shortString[0] <= 'Z') || - (shortString[0] >= 'a' && shortString[0] <= 'z'))) -#else - if (shortString.Length == 1 && shortString[0]== m_directorySeparator) -#endif // !PLATFORM_UNIX - return true; - - return longString[shortString.Length] == m_directorySeparator; - } - } - - - //------------------------------- - // protected helper functions - //------------------------------- - - protected void AddSingleExpressionNoDuplicates( String expression ) - { - // SafeCritical: We're not exposing out the string sets, just allowing modification of them - int index = 0; - - m_expressionsArray = null; - m_expressions = null; - - if (this.m_list == null) - this.m_list = new ArrayList(); - - while (index < this.m_list.Count) - { - if (StringSubsetString( (String)this.m_list[index], expression, m_ignoreCase )) - { - this.m_list.RemoveAt( index ); - } - else if (StringSubsetString( expression, (String)this.m_list[index], m_ignoreCase )) - { - return; - } - else - { - index++; - } - } - this.m_list.Add( expression ); - } - - protected void Reduce() - { - CheckList(); - - if (this.m_list == null) - return; - - int j; - - for (int i = 0; i < this.m_list.Count - 1; i++) - { - j = i + 1; - - while (j < this.m_list.Count) - { - if (StringSubsetString( (String)this.m_list[j], (String)this.m_list[i], m_ignoreCase )) - { - this.m_list.RemoveAt( j ); - } - else if (StringSubsetString( (String)this.m_list[i], (String)this.m_list[j], m_ignoreCase )) - { - // write the value at j into position i, delete the value at position j and keep going. - this.m_list[i] = this.m_list[j]; - this.m_list.RemoveAt( j ); - j = i + 1; - } - else - { - j++; - } - } - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath ); - - internal static String CanonicalizePath( String path ) - { - return CanonicalizePath( path, true ); - } - - internal static string CanonicalizePath(string path, bool needFullPath) - { - if (needFullPath) - { - string newPath = Path.GetFullPath(path); - if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal)) - { - if (newPath.EndsWith(m_directorySeparator)) - { - newPath += "."; - } - else - { - newPath += m_directorySeparator + "."; - } - } - path = newPath; - } -#if !PLATFORM_UNIX - else if (path.IndexOf('~') != -1) - { - // GetFullPathInternal() will expand 8.3 file names - string longPath = null; - GetLongPathName(path, JitHelpers.GetStringHandleOnStack(ref longPath)); - path = (longPath != null) ? longPath : path; - } - - // This blocks usage of alternate data streams and some extended syntax paths (\\?\C:\). Checking after - // normalization allows valid paths such as " C:\" to be considered ok (as it will become "C:\"). - if (path.IndexOf(':', 2) != -1) - throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); -#endif // !PLATFORM_UNIX - - return path; - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs deleted file mode 100644 index 8589fa7c42..0000000000 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs +++ /dev/null @@ -1,443 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Util -{ - using System; - using System.Collections; - using System.Security.Permissions; - using System.Runtime.Serialization; - using System.Threading; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Diagnostics.CodeAnalysis; - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal class TokenBasedSet - { - - - // Following 3 fields are used only for serialization compat purposes: DO NOT USE THESE EVER! -#pragma warning disable 414 - private int m_initSize = 24; - private int m_increment = 8; -#pragma warning restore 414 - private Object[] m_objSet; - // END -> Serialization only fields - - [OptionalField(VersionAdded = 2)] - private volatile Object m_Obj; - [OptionalField(VersionAdded = 2)] - private volatile Object[] m_Set; - - private int m_cElt; - private volatile int m_maxIndex; - - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - OnDeserializedInternal(); - } - private void OnDeserializedInternal() - { - if (m_objSet != null) //v1.x case - { - if (m_cElt == 1) - m_Obj = m_objSet[m_maxIndex]; - else - m_Set = m_objSet; - m_objSet = null; - } - // Nothing to do for the v2.0 and beyond case - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - //Nothing special for the v2 and beyond case - - // for the v1.x case, we need to create m_objSet if necessary - if (m_cElt == 1) - { - m_objSet = new Object[m_maxIndex+1]; - m_objSet[m_maxIndex] = m_Obj; - } - else if (m_cElt > 0) - { - // Array case: - m_objSet = m_Set; - } - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_objSet = null; - - } - } - - - internal bool MoveNext(ref TokenBasedSetEnumerator e) - { - switch (m_cElt) - { - case 0: - return false; - - case 1: - if (e.Index == -1) - { - e.Index = m_maxIndex; - e.Current = m_Obj; - return true; - } - else - { - e.Index = (short)(m_maxIndex+1); - e.Current = null; - return false; - } - - default: - while (++e.Index <= m_maxIndex) - { - e.Current = Volatile.Read(ref m_Set[e.Index]); - - if (e.Current != null) - return true; - } - - e.Current = null; - return false; - } - } - - internal TokenBasedSet() - { - Reset(); - } - - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] - internal TokenBasedSet(TokenBasedSet tbSet) - { - if (tbSet == null) - { - Reset(); - return; - } - - if (tbSet.m_cElt > 1) - { - Object[] aObj = tbSet.m_Set; - int aLen = aObj.Length; - - Object[] aNew = new Object[aLen]; - System.Array.Copy(aObj, 0, aNew, 0, aLen); - - m_Set = aNew; - } - else - { - m_Obj = tbSet.m_Obj; - } - - m_cElt = tbSet.m_cElt; - m_maxIndex = tbSet.m_maxIndex; - } - - internal void Reset() - { - m_Obj = null; - m_Set = null; - m_cElt = 0; - m_maxIndex = -1; - } - - internal void SetItem(int index, Object item) - { - Object[] aObj = null; - - if (item == null) - { - RemoveItem(index); - return; - } - - switch (m_cElt) - { - case 0: - // on the first item, we don't create an array, we merely remember it's index and value - // this this the 99% case - m_cElt = 1; - m_maxIndex = (short)index; - m_Obj = item; - break; - - case 1: - // we have to decide if a 2nd item has indeed been added and create the array - // if it has - if (index == m_maxIndex) - { - // replacing the one existing item - m_Obj = item; - } - else - { - // adding a second distinct permission - Object objSaved = m_Obj; - int iMax = Math.Max(m_maxIndex, index); - - aObj = new Object[iMax+1]; - aObj[m_maxIndex] = objSaved; - aObj[index] = item; - m_maxIndex = (short)iMax; - m_cElt = 2; - m_Set = aObj; - m_Obj = null; - } - break; - - default: - // this is the general case code for when there is really an array - - aObj = m_Set; - - // we are now adding an item, check if we need to grow - - if (index >= aObj.Length) - { - Object[] newset = new Object[index+1]; - System.Array.Copy(aObj, 0, newset, 0, m_maxIndex+1); - m_maxIndex = (short)index; - newset[index] = item; - m_Set = newset; - m_cElt++; - } - else - { - if (aObj[index] == null) - m_cElt++; - - aObj[index] = item; - - if (index > m_maxIndex) - m_maxIndex = (short)index; - } - break; - } - } - - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] - internal Object GetItem(int index) - { - switch (m_cElt) - { - case 0: - return null; - - case 1: - if (index == m_maxIndex) - return m_Obj; - else - return null; - default: - if (index < m_Set.Length) - return Volatile.Read(ref m_Set[index]); - else - return null; - } - } - - internal Object RemoveItem(int index) - { - Object ret = null; - - switch (m_cElt) - { - case 0: - ret = null; - break; - - case 1: - if (index != m_maxIndex) - { - // removing a permission we don't have ignore it - ret = null; - } - else - { - // removing the permission we have at the moment - ret = m_Obj; - Reset(); - } - break; - - default: - // this is the general case code for when there is really an array - - // we are removing an item - if (index < m_Set.Length && (ret = Volatile.Read(ref m_Set[index])) != null) - { - // ok we really deleted something at this point - - Volatile.Write(ref m_Set[index], null); - m_cElt--; - - if (index == m_maxIndex) - ResetMaxIndex(m_Set); - - // collapse the array - if (m_cElt == 1) - { - m_Obj = Volatile.Read(ref m_Set[m_maxIndex]); - m_Set = null; - } - } - break; - } - - return ret; - } - - private void ResetMaxIndex(Object[] aObj) - { - int i; - - // Start at the end of the array, and - // scan backwards for the first non-null - // slot. That is the new maxIndex. - for (i = aObj.Length - 1; i >= 0; i--) - { - if (aObj[i] != null) - { - m_maxIndex = (short)i; - return; - } - } - - m_maxIndex = -1; - } - internal int GetStartingIndex() - { - if (m_cElt <= 1) - return m_maxIndex; - return 0; - } - internal int GetCount() - { - return m_cElt; - } - - internal int GetMaxUsedIndex() - { - return m_maxIndex; - } - - internal bool FastIsEmpty() - { - return m_cElt == 0; - } - - // Used to merge two distinct TokenBasedSets (used currently only in PermissionSet Deserialization) - internal TokenBasedSet SpecialUnion(TokenBasedSet other) - { - // This gets called from PermissionSet.OnDeserialized and it's possible that the TokenBasedSets have - // not been subjected to VTS callbacks yet - OnDeserializedInternal(); - TokenBasedSet unionSet = new TokenBasedSet(); - int maxMax; - if (other != null) - { - other.OnDeserializedInternal(); - maxMax = this.GetMaxUsedIndex() > other.GetMaxUsedIndex() ? this.GetMaxUsedIndex() : other.GetMaxUsedIndex(); - } - else - maxMax = this.GetMaxUsedIndex(); - - for (int i = 0; i <= maxMax; ++i) - { - Object thisObj = this.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - - Object otherObj = (other != null)?other.GetItem( i ):null; - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - PermissionToken token = PermissionToken.GetToken(otherPerm); - - if (token == null) - { - throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); - } - - unionSet.SetItem(token.m_index, otherPerm); - } - else if (otherObj == null) - { - PermissionToken token = PermissionToken.GetToken(thisPerm); - if (token == null) - { - throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); - } - unionSet.SetItem( token.m_index, thisPerm); - } - else - { - Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); - } - } - return unionSet; - } - - internal void SpecialSplit(ref TokenBasedSet unrestrictedPermSet, ref TokenBasedSet normalPermSet, bool ignoreTypeLoadFailures) - { - int maxIndex = GetMaxUsedIndex(); - - for (int i = GetStartingIndex(); i <= maxIndex; ++i) - { - Object obj = GetItem( i ); - if (obj != null) - { - IPermission perm = obj as IPermission; - PermissionToken token = PermissionToken.GetToken(perm); - - if (perm == null || token == null) - continue; - - if (perm is IUnrestrictedPermission) - { - // Add to unrestrictedPermSet - if (unrestrictedPermSet == null) - unrestrictedPermSet = new TokenBasedSet(); - unrestrictedPermSet.SetItem(token.m_index, perm); - } - else - { - // Add to normalPermSet - if (normalPermSet == null) - normalPermSet = new TokenBasedSet(); - normalPermSet.SetItem(token.m_index, perm); - } - - } - - } - - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs deleted file mode 100644 index 9c868d3c53..0000000000 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Util -{ - using System; - using System.Collections; - - internal struct TokenBasedSetEnumerator - { - public Object Current; - public int Index; - - private TokenBasedSet _tb; - - public bool MoveNext() - { - return _tb != null ? _tb.MoveNext(ref this) : false; - } - - public void Reset() - { - Index = -1; - Current = null; - } - - public TokenBasedSetEnumerator(TokenBasedSet tb) - { - Index = -1; - Current = null; - _tb = tb; - } - } -} - diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs index 83f9ce483f..4ec353876a 100644 --- a/src/mscorlib/src/System/Security/Util/URLString.cs +++ b/src/mscorlib/src/System/Security/Util/URLString.cs @@ -22,368 +22,8 @@ namespace System.Security.Util { using System.IO; using System.Diagnostics.Contracts; -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal sealed class URLString : SiteString + internal static class URLString { - private String m_protocol; - [OptionalField(VersionAdded = 2)] - private String m_userpass; - private SiteString m_siteString; - private int m_port; -#if !PLATFORM_UNIX - private LocalSiteString m_localSite; -#endif // !PLATFORM_UNIX - private DirectoryString m_directory; - - private const String m_defaultProtocol = "file"; - - [OptionalField(VersionAdded = 2)] - private bool m_parseDeferred; - [OptionalField(VersionAdded = 2)] - private String m_urlOriginal; - [OptionalField(VersionAdded = 2)] - private bool m_parsedOriginal; - - [OptionalField(VersionAdded = 3)] - private bool m_isUncShare; - - // legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility. - private String m_fullurl; - - - [OnDeserialized] - public void OnDeserialized(StreamingContext ctx) - { - - if (m_urlOriginal == null) - { - // pre-v2 deserialization. Need to fix-up fields here - m_parseDeferred = false; - m_parsedOriginal = false; // Dont care what this value is - never used - m_userpass = ""; - m_urlOriginal = m_fullurl; - m_fullurl = null; - } - } - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - DoDeferredParse(); - m_fullurl = m_urlOriginal; - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_fullurl = null; - } - } - - public URLString() - { - m_protocol = ""; - m_userpass = ""; - m_siteString = new SiteString(); - m_port = -1; -#if !PLATFORM_UNIX - m_localSite = null; -#endif // !PLATFORM_UNIX - m_directory = new DirectoryString(); - m_parseDeferred = false; - } - - private void DoDeferredParse() - { - if (m_parseDeferred) - { - ParseString(m_urlOriginal, m_parsedOriginal); - m_parseDeferred = false; - } - } - - public URLString(string url) : this(url, false, false) {} - public URLString(string url, bool parsed) : this(url, parsed, false) {} - - internal URLString(string url, bool parsed, bool doDeferredParsing) - { - m_port = -1; - m_userpass = ""; - DoFastChecks(url); - m_urlOriginal = url; - m_parsedOriginal = parsed; - m_parseDeferred = true; - if (doDeferredParsing) - DoDeferredParse(); - } - - // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL) - private String UnescapeURL(String url) - { - StringBuilder intermediate = StringBuilderCache.Acquire(url.Length); - int Rindex = 0; // index into temp that gives the rest of the string to be processed - int index; - int braIndex = -1; - int ketIndex = -1; - braIndex = url.IndexOf('[',Rindex); - if (braIndex != -1) - ketIndex = url.IndexOf(']', braIndex); - - do - { - index = url.IndexOf( '%', Rindex); - - if (index == -1) - { - intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex)); - break; - } - // if we hit a '%' in the middle of an IPv6 address, dont process that - if (index > braIndex && index < ketIndex) - { - intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1)); - Rindex = ketIndex+1; - continue; - } - - if (url.Length - index < 2) // Check that there is at least 1 char after the '%' - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - if (url[index+1] == 'u' || url[index+1] == 'U') - { - if (url.Length - index < 6) // example: "%u004d" is 6 chars long - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - // We have a unicode character specified in hex - - try - { - char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 | - Hex.ConvertHexDigit( url[index+3] ) << 8 | - Hex.ConvertHexDigit( url[index+4] ) << 4 | - Hex.ConvertHexDigit( url[index+5] )); - intermediate = intermediate.Append(url, Rindex, index - Rindex); - intermediate = intermediate.Append(c); - } - catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - Rindex = index + 6 ; //update the 'seen' length - } - else - { - // we have a hex character. - - if (url.Length - index < 3) // example: "%4d" is 3 chars long - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - try - { - char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] )); - - intermediate = intermediate.Append(url, Rindex, index - Rindex); - intermediate = intermediate.Append(c); - } - catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - Rindex = index + 3; // update the 'seen' length - } - - } - while (true); - return StringBuilderCache.GetStringAndRelease(intermediate); - } - - // Helper Function for ParseString: - // Search for the end of the protocol info and grab the actual protocol string - // ex. http://www.microsoft.com/complus would have a protocol string of http - private String ParseProtocol(String url) - { - String temp; - int index = url.IndexOf( ':' ); - - if (index == 0) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else if (index == -1) - { - m_protocol = m_defaultProtocol; - temp = url; - } - else if (url.Length > index + 1) - { - if (index == m_defaultProtocol.Length && - String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0) - { - m_protocol = m_defaultProtocol; - temp = url.Substring( index + 1 ); - - // Since an explicit file:// URL could be immediately followed by a host name, we will be - // conservative and assume that it is on a share rather than a potentally relative local - // URL. - m_isUncShare = true; - } - else if (url[index+1] != '\\') - { -#if !PLATFORM_UNIX - if (url.Length > index + 2 && - url[index+1] == '/' && - url[index+2] == '/') -#else - if (url.Length > index + 1 && - url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that -#endif // !PLATFORM_UNIX - { - m_protocol = url.Substring( 0, index ); - - for (int i = 0; i < m_protocol.Length; ++i) - { - char c = m_protocol[i]; - - if ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - (c == '+') || - (c == '.') || - (c == '-')) - { - continue; - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - } -#if !PLATFORM_UNIX - temp = url.Substring( index + 3 ); -#else - // In UNIX, we don't know how many characters we'll have to skip past. - // Skip past \, /, and : - // - for ( int j=index ; j<url.Length ; j++ ) - { - if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' ) - { - index = j; - break; - } - } - - temp = url.Substring( index ); -#endif // !PLATFORM_UNIX - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - } - else - { - m_protocol = m_defaultProtocol; - temp = url; - } - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - return temp; - } - - private String ParsePort(String url) - { - String temp = url; - char[] separators = new char[] { ':', '/' }; - int Rindex = 0; - int userpassIndex = temp.IndexOf('@'); - if (userpassIndex != -1) { - if (temp.IndexOf('/',0,userpassIndex) == -1) { - // this is a user:pass type of string - m_userpass = temp.Substring(0,userpassIndex); - Rindex = userpassIndex + 1; - } - } - - int braIndex = -1; - int ketIndex = -1; - int portIndex = -1; - braIndex = url.IndexOf('[',Rindex); - if (braIndex != -1) - ketIndex = url.IndexOf(']', braIndex); - if (ketIndex != -1) - { - // IPv6 address...ignore the IPv6 block when searching for the port - portIndex = temp.IndexOfAny(separators,ketIndex); - } - else - { - portIndex = temp.IndexOfAny(separators,Rindex); - } - - - - if (portIndex != -1 && temp[portIndex] == ':') - { - // make sure it really is a port, and has a number after the : - if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' ) - { - int tempIndex = temp.IndexOf( '/', Rindex); - - if (tempIndex == -1) - { - m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture ); - - if (m_port < 0) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - temp = temp.Substring( Rindex, portIndex - Rindex ); - } - else if (tempIndex > portIndex) - { - m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture ); - temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex ); - } - else - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else { - // Chop of the user/pass portion if any - temp = temp.Substring(Rindex); - } - - return temp; - } - - // This does three things: - // 1. It makes the following modifications to the start of the string: - // a. \\?\ and \\?/ => <empty> - // b. \\.\ and \\./ => <empty> - // 2. If isFileUrl is true, converts all slashes to front slashes and strips leading - // front slashes. See comment by code. - // 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH. - // This is done to prevent security issues due to canonicalization truncations. - // Remove this method when the Path class supports "\\?\" - internal static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl) - { - return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl); - } - internal static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl) { bool isUncShare = false; @@ -417,7 +57,8 @@ namespace System.Security.Util { } else { - if (isFileUrl) { + if (isFileUrl) + { // We need to handle an indefinite number of leading front slashes for file URLs since we could // get something like: // file://\\?\ @@ -449,14 +90,14 @@ namespace System.Security.Util { { int slashCount = 0; bool seenFirstBackslash = false; - + while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\')) { // Look for sets of consecutive backslashes. We can't just look for these at the start // of the string, since file:// might come first. Instead, once we see the first \, look // for a second one following it. if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\') - { + { seenFirstBackslash = true; if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\') isUncShare = true; @@ -493,873 +134,5 @@ namespace System.Security.Util { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } } - - // Do any misc massaging of data in the URL - private String PreProcessURL(String url, bool isFileURL) - { - -#if !PLATFORM_UNIX - if (isFileURL) { - // Remove when the Path class supports "\\?\" - url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare); - } - else { - url = url.Replace('\\', '/'); - } - return url; -#else - // Remove superfluous '/' - // For UNIX, the file path would look something like: - // file:///home/johndoe/here - // file:/home/johndoe/here - // file:../johndoe/here - // file:~/johndoe/here - String temp = url; - int nbSlashes = 0; - while(nbSlashes<temp.Length && '/'==temp[nbSlashes]) - nbSlashes++; - - // if we get a path like file:///directory/name we need to convert - // this to /directory/name. - if(nbSlashes > 2) - temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1)); - else if (2 == nbSlashes) /* it's a relative path */ - temp = temp.Substring(nbSlashes, temp.Length - nbSlashes); - return temp; -#endif // !PLATFORM_UNIX - - } - - private void ParseFileURL(String url) - { - - String temp = url; -#if !PLATFORM_UNIX - int index = temp.IndexOf( '/'); - - if (index != -1 && - ((index == 2 && - temp[index-1] != ':' && - temp[index-1] != '|') || - index != 2) && - index != temp.Length - 1) - { - // Also, if it is a UNC share, we want m_localSite to - // be of the form "computername/share", so if the first - // fileEnd character found is a slash, do some more parsing - // to find the proper end character. - - int tempIndex = temp.IndexOf( '/', index+1); - - if (tempIndex != -1) - index = tempIndex; - else - index = -1; - } - - String localSite; - if (index == -1) - localSite = temp; - else - localSite = temp.Substring(0,index); - - if (localSite.Length == 0) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - int i; - bool spacesAllowed; - - if (localSite[0] == '\\' && localSite[1] == '\\') - { - spacesAllowed = true; - i = 2; - } - else - { - i = 0; - spacesAllowed = false; - } - - bool useSmallCharToUpper = true; - - for (; i < localSite.Length; ++i) - { - char c = localSite[i]; - - if ((c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9') || - (c == '-') || (c == '/') || - (c == ':') || (c == '|') || - (c == '.') || (c == '*') || - (c == '$') || (spacesAllowed && c == ' ')) - { - continue; - } - else - { - useSmallCharToUpper = false; - break; - } - } - - if (useSmallCharToUpper) - localSite = String.SmallCharToUpper( localSite ); - else - localSite = localSite.ToUpper(CultureInfo.InvariantCulture); - - m_localSite = new LocalSiteString( localSite ); - - if (index == -1) - { - if (localSite[localSite.Length-1] == '*') - m_directory = new DirectoryString( "*", false ); - else - m_directory = new DirectoryString(); - } - else - { - String directoryString = temp.Substring( index + 1 ); - if (directoryString.Length == 0) - { - m_directory = new DirectoryString(); - } - else - { - m_directory = new DirectoryString( directoryString, true); - } - } -#else // !PLATFORM_UNIX - m_directory = new DirectoryString( temp, true); -#endif // !PLATFORM_UNIX - - m_siteString = null; - return; - } - - private void ParseNonFileURL(String url) - { - String temp = url; - int index = temp.IndexOf('/'); - - if (index == -1) - { -#if !PLATFORM_UNIX - m_localSite = null; // for drive letter -#endif // !PLATFORM_UNIX - m_siteString = new SiteString( temp ); - m_directory = new DirectoryString(); - } - else - { -#if !PLATFORM_UNIX - String site = temp.Substring( 0, index ); - m_localSite = null; - m_siteString = new SiteString( site ); - - String directoryString = temp.Substring( index + 1 ); - - if (directoryString.Length == 0) - { - m_directory = new DirectoryString(); - } - else - { - m_directory = new DirectoryString( directoryString, false ); - } -#else - String directoryString = temp.Substring( index + 1 ); - String site = temp.Substring( 0, index ); - m_directory = new DirectoryString( directoryString, false ); - m_siteString = new SiteString( site ); -#endif //!PLATFORM_UNIX - } - return; - } - - void DoFastChecks( String url ) - { - if (url == null) - { - throw new ArgumentNullException( nameof(url) ); - } - Contract.EndContractBlock(); - - if (url.Length == 0) - { - throw new FormatException(Environment.GetResourceString("Format_StringZeroLength")); - } - } - - // NOTE: - // 1. We support URLs that follow the common Internet scheme syntax - // (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs. - // 2. In the general case we parse of the site and create a SiteString out of it - // (which supports our wildcarding scheme). In the case of files we don't support - // wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear - // in file urls so we just keep that info in a separate string and set the - // SiteString to null. - // - // ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null - // ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" - // ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" - void ParseString( String url, bool parsed ) - { - // If there are any escaped hex or unicode characters in the url, translate those - // into the proper character. - - if (!parsed) - { - url = UnescapeURL(url); - } - - // Identify the protocol and strip the protocol info from the string, if present. - String temp = ParseProtocol(url); - - bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0); - - // handle any special preocessing...removing extra characters, etc. - temp = PreProcessURL(temp, fileProtocol); - - if (fileProtocol) - { - ParseFileURL(temp); - } - else - { - // Check if there is a port number and parse that out. - temp = ParsePort(temp); - ParseNonFileURL(temp); - // Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check - // that the hostname satisfies these two protocols. DNS-only checking can theoretically be added - // here but that would break all the programs that use '_' (which is fairly common, yet illegal). - // If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName(). - } - - - } - - public String Scheme - { - get - { - DoDeferredParse(); - - return m_protocol; - } - } - - public String Host - { - get - { - DoDeferredParse(); - - if (m_siteString != null) - { - return m_siteString.ToString(); - } - else - { -#if !PLATFORM_UNIX - return m_localSite.ToString(); -#else - return ""; -#endif // !PLATFORM_UNIX - } - } - } - - public String Port - { - get - { - DoDeferredParse(); - - if (m_port == -1) - return null; - else - return m_port.ToString(CultureInfo.InvariantCulture); - } - } - - public String Directory - { - get - { - DoDeferredParse(); - - return m_directory.ToString(); - } - } - - /// <summary> - /// Make a best guess at determining if this is URL refers to a file with a relative path. Since - /// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a - /// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some - /// meaningless membership conditions rather than reject meaningful ones). - /// - /// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a - /// UNC share. - /// - /// If both of the above are true, then the heuristics we'll use to detect an absolute URL are: - /// 1. A host name which is: - /// a. greater than one character and ends in a colon (representing the drive letter) OR - /// b. ends with a * (so we match any file with the given prefix if any) - /// 2. Has a directory name (cannot be simply file://c:) - /// </summary> - public bool IsRelativeFileUrl - { - get - { - DoDeferredParse(); - - if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare) - { -#if !PLATFORM_UNIX - string host = m_localSite != null ? m_localSite.ToString() : null; - // If the host name ends with the * character, treat this as an absolute URL since the * - // could represent the rest of the full path. - if (host.EndsWith('*')) - return false; -#endif // !PLATFORM_UNIX - string directory = m_directory != null ? m_directory.ToString() : null; - -#if !PLATFORM_UNIX - return host == null || host.Length < 2 || !host.EndsWith(':') || - String.IsNullOrEmpty(directory); -#else - return String.IsNullOrEmpty(directory); -#endif // !PLATFORM_UNIX - - } - - // Since this is not a local URL, it cannot be relative - return false; - } - } - - public String GetFileName() - { - DoDeferredParse(); - -#if !PLATFORM_UNIX - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - return null; - - String intermediateDirectory = this.Directory.Replace( '/', '\\' ); - - String directory = this.Host.Replace( '/', '\\' ); - - int directorySlashIndex = directory.IndexOf( '\\' ); - if (directorySlashIndex == -1) - { - if (directory.Length != 2 || - !(directory[1] == ':' || directory[1] == '|')) - { - directory = "\\\\" + directory; - } - } - else if (directorySlashIndex != 2 || - (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) - { - directory = "\\\\" + directory; - } - - directory += "\\" + intermediateDirectory; - - return directory; -#else - // In Unix, directory contains the full pathname - // (this is what we get in Win32) - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) - return null; - - return this.Directory; -#endif // !PLATFORM_UNIX - } - - - public String GetDirectoryName() - { - DoDeferredParse(); - -#if !PLATFORM_UNIX - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) - return null; - - String intermediateDirectory = this.Directory.Replace( '/', '\\' ); - - int slashIndex = 0; - for (int i = intermediateDirectory.Length; i > 0; i--) - { - if (intermediateDirectory[i-1] == '\\') - { - slashIndex = i; - break; - } - } - - String directory = this.Host.Replace( '/', '\\' ); - - int directorySlashIndex = directory.IndexOf( '\\' ); - if (directorySlashIndex == -1) - { - if (directory.Length != 2 || - !(directory[1] == ':' || directory[1] == '|')) - { - directory = "\\\\" + directory; - } - } - else if (directorySlashIndex > 2 || - (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) - { - directory = "\\\\" + directory; - } - - directory += "\\"; - - if (slashIndex > 0) - { - directory += intermediateDirectory.Substring( 0, slashIndex ); - } - - return directory; -#else - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - return null; - - String directory = this.Directory.ToString(); - int slashIndex = 0; - for (int i = directory.Length; i > 0; i--) - { - if (directory[i-1] == '/') - { - slashIndex = i; - break; - } - } - - if (slashIndex > 0) - { - directory = directory.Substring( 0, slashIndex ); - } - - return directory; -#endif // !PLATFORM_UNIX - } - - public override SiteString Copy() - { - return new URLString( m_urlOriginal, m_parsedOriginal ); - } - - public override bool IsSubsetOf( SiteString site ) - { - if (site == null) - { - return false; - } - - URLString url = site as URLString; - - if (url == null) - { - return false; - } - - DoDeferredParse(); - url.DoDeferredParse(); - - URLString normalUrl1 = this.SpecialNormalizeUrl(); - URLString normalUrl2 = url.SpecialNormalizeUrl(); - - if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 && - normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory )) - { -#if !PLATFORM_UNIX - if (normalUrl1.m_localSite != null) - { - // We do a little extra processing in here for local files since we allow - // both <drive_letter>: and <drive_letter>| forms of urls. - - return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ); - } - else -#endif // !PLATFORM_UNIX - { - if (normalUrl1.m_port != normalUrl2.m_port) - return false; - - return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ); - } - } - else - { - return false; - } - } - - public override String ToString() - { - return m_urlOriginal; - } - - public override bool Equals(Object o) - { - DoDeferredParse(); - - if (o == null || !(o is URLString)) - return false; - else - return this.Equals( (URLString)o ); - } - - public override int GetHashCode() - { - DoDeferredParse(); - - TextInfo info = CultureInfo.InvariantCulture.TextInfo; - int accumulator = 0; - - if (this.m_protocol != null) - accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol ); - -#if !PLATFORM_UNIX - if (this.m_localSite != null) - { - accumulator = accumulator ^ this.m_localSite.GetHashCode(); - } - else - { - accumulator = accumulator ^ this.m_siteString.GetHashCode(); - } - accumulator = accumulator ^ this.m_directory.GetHashCode(); -#else - accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal); -#endif // !PLATFORM_UNIX - - - - return accumulator; - } - - public bool Equals( URLString url ) - { - return CompareUrls( this, url ); - } - - public static bool CompareUrls( URLString url1, URLString url2 ) - { - if (url1 == null && url2 == null) - return true; - - if (url1 == null || url2 == null) - return false; - - url1.DoDeferredParse(); - url2.DoDeferredParse(); - - URLString normalUrl1 = url1.SpecialNormalizeUrl(); - URLString normalUrl2 = url2.SpecialNormalizeUrl(); - - // Compare protocol (case insensitive) - - if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0) - return false; - - // Do special processing for file urls - - if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) - { -#if !PLATFORM_UNIX - if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) || - !normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite )) - return false; -#else - return url1.IsSubsetOf( url2 ) && - url2.IsSubsetOf( url1 ); -#endif // !PLATFORM_UNIX - } - else - { - if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0) - return false; - - if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) || - !normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString )) - return false; - - if (url1.m_port != url2.m_port) - return false; - } - - if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) || - !normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory )) - return false; - - return true; - } - - internal String NormalizeUrl() - { - DoDeferredParse(); - StringBuilder builtUrl = StringBuilderCache.Acquire(); - - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) - { -#if !PLATFORM_UNIX - builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString()); -#else - builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString()); -#endif // !PLATFORM_UNIX - } - else - { - builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString()); - - if (m_port != -1) - builtUrl = builtUrl.AppendFormat("{0}",m_port); - - builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString()); - } - - return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture); - } - -#if !PLATFORM_UNIX - internal URLString SpecialNormalizeUrl() - { - // Under WinXP, file protocol urls can be mapped to - // drives that aren't actually file protocol underneath - // due to drive mounting. This code attempts to figure - // out what a drive is mounted to and create the - // url is maps to. - - DoDeferredParse(); - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - { - return this; - } - else - { - String localSite = m_localSite.ToString(); - - if (localSite.Length == 2 && - (localSite[1] == '|' || - localSite[1] == ':')) - { - String deviceName = null; - GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName)); - - if (deviceName != null) - { - if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1) - { - URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() ); - u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL - return u; - } - else - { - URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() ); - u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL - return u; - } - } - else - return this; - } - else - { - return this; - } - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName ); - -#else - internal URLString SpecialNormalizeUrl() - { - return this; - } -#endif // !PLATFORM_UNIX - - } - - - [Serializable] - internal class DirectoryString : SiteString - { - private bool m_checkForIllegalChars; - - private new static char[] m_separators = { '/' }; - - // From KB #Q177506, file/folder illegal characters are \ / : * ? " < > | - protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' }; - - public DirectoryString() - { - m_site = ""; - m_separatedSite = new ArrayList(); - } - - public DirectoryString( String directory, bool checkForIllegalChars ) - { - m_site = directory; - m_checkForIllegalChars = checkForIllegalChars; - m_separatedSite = CreateSeparatedString(directory); - } - - private ArrayList CreateSeparatedString(String directory) - { - if (directory == null || directory.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - String[] separatedArray = directory.Split(m_separators); - - for (int index = 0; index < separatedArray.Length; ++index) - { - if (separatedArray[index] == null || separatedArray[index].Equals( "" )) - { - // this case is fine, we just ignore it the extra separators. - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - list.Add( separatedArray[index] ); - } - else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - public virtual bool IsSubsetOf( DirectoryString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase ) - { - if (operand == null) - { - return false; - } - else if (operand.m_separatedSite.Count == 0) - { - return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else if (this.m_separatedSite.Count == 0) - { - return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else - { - return base.IsSubsetOf( operand, ignoreCase ); - } - } - } - -#if !PLATFORM_UNIX - [Serializable] - internal class LocalSiteString : SiteString - { - private new static char[] m_separators = { '/' }; - - public LocalSiteString( String site ) - { - m_site = site.Replace( '|', ':'); - - if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - - m_separatedSite = CreateSeparatedString(m_site); - } - - private ArrayList CreateSeparatedString(String directory) - { - if (directory == null || directory.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - String[] separatedArray = directory.Split(m_separators); - - for (int index = 0; index < separatedArray.Length; ++index) - { - if (separatedArray[index] == null || separatedArray[index].Equals( "" )) - { - if (index < 2 && - directory[index] == '/') - { - list.Add( "//" ); - } - else if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - list.Add( separatedArray[index] ); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - public virtual bool IsSubsetOf( LocalSiteString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase ) - { - if (operand == null) - { - return false; - } - else if (operand.m_separatedSite.Count == 0) - { - return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else if (this.m_separatedSite.Count == 0) - { - return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else - { - return base.IsSubsetOf( operand, ignoreCase ); - } - } } -#endif // !PLATFORM_UNIX } diff --git a/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/mscorlib/src/System/Security/Util/XMLUtil.cs deleted file mode 100644 index 3a1aaa3b09..0000000000 --- a/src/mscorlib/src/System/Security/Util/XMLUtil.cs +++ /dev/null @@ -1,435 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** PURPOSE: Helpers for XML input & output -** -===========================================================*/ -namespace System.Security.Util { - - using System; - using System.Security; - using System.Security.Permissions; - using System.Security.Policy; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.IO; - using System.Text; - using System.Runtime.CompilerServices; - using PermissionState = System.Security.Permissions.PermissionState; - using BindingFlags = System.Reflection.BindingFlags; - using Assembly = System.Reflection.Assembly; - using System.Threading; - using System.Globalization; - using System.Reflection; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - internal static class XMLUtil - { - // - // Warning: Element constructors have side-effects on their - // third argument. - // - - private const String BuiltInPermission = "System.Security.Permissions."; - - public static SecurityElement - NewPermissionElement (IPermission ip) - { - return NewPermissionElement (ip.GetType ().FullName) ; - } - - public static SecurityElement - NewPermissionElement (String name) - { - SecurityElement ecr = new SecurityElement( "Permission" ); - ecr.AddAttribute( "class", name ); - return ecr; - } - - public static void - AddClassAttribute( SecurityElement element, Type type, String typename ) - { - // Replace any quotes with apostrophes so that we can include quoted materials - // within classnames. Notably the assembly name member 'loc' uses a quoted string. - - // NOTE: this makes assumptions as to what reflection is expecting for a type string - // it will need to be updated if reflection changes what it wants. - - if ( typename == null ) - typename = type.FullName; - Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); - element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) ); - } - - internal static bool ParseElementForAssemblyIdentification(SecurityElement el, - out String className, - out String assemblyName, // for example "WindowsBase" - out String assemblyVersion) - { - - className = null; - assemblyName = null; - assemblyVersion = null; - - String fullClassName = el.Attribute( "class" ); - - if (fullClassName == null) - { - return false; - } - if (fullClassName.IndexOf('\'') >= 0) - { - fullClassName = fullClassName.Replace( '\'', '\"' ); - } - - int commaIndex = fullClassName.IndexOf( ',' ); - int namespaceClassNameLength; - - // If the classname is tagged with assembly information, find where - // the assembly information begins. - - if (commaIndex == -1) - { - return false; - } - - namespaceClassNameLength = commaIndex; - className = fullClassName.Substring(0, namespaceClassNameLength); - String assemblyFullName = fullClassName.Substring(commaIndex + 1); - AssemblyName an = new AssemblyName(assemblyFullName); - assemblyName = an.Name; - assemblyVersion = an.Version.ToString(); - return true; - } - private static bool - ParseElementForObjectCreation( SecurityElement el, - String requiredNamespace, - out String className, - out int classNameStart, - out int classNameLength ) - { - className = null; - classNameStart = 0; - classNameLength = 0; - - int requiredNamespaceLength = requiredNamespace.Length; - - String fullClassName = el.Attribute( "class" ); - - if (fullClassName == null) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) ); - } - - if (fullClassName.IndexOf('\'') >= 0) - { - fullClassName = fullClassName.Replace( '\'', '\"' ); - } - - if (!PermissionToken.IsMscorlibClassName( fullClassName )) - { - return false; - } - - int commaIndex = fullClassName.IndexOf( ',' ); - int namespaceClassNameLength; - - // If the classname is tagged with assembly information, find where - // the assembly information begins. - - if (commaIndex == -1) - { - namespaceClassNameLength = fullClassName.Length; - } - else - { - namespaceClassNameLength = commaIndex; - } - - // Only if the length of the class name is greater than the namespace info - // on our requiredNamespace do we continue - // with our check. - - if (namespaceClassNameLength > requiredNamespaceLength) - { - // Make sure we are in the required namespace. - if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal)) - { - className = fullClassName; - classNameLength = namespaceClassNameLength - requiredNamespaceLength; - classNameStart = requiredNamespaceLength; - return true; - } - } - - return false; - } - - public static IPermission - CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures) - { - if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) ) - throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameLength; - int classNameStart; - - if (!ParseElementForObjectCreation( el, - BuiltInPermission, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - // We have a built in permission, figure out which it is. - - // UIPermission - // FileIOPermission - // SecurityPermission - // PrincipalPermission - // ReflectionPermission - // FileDialogPermission - // EnvironmentPermission - // GacIdentityPermission - // UrlIdentityPermission - // SiteIdentityPermission - // ZoneIdentityPermission - // KeyContainerPermission - // UnsafeForHostPermission - // HostProtectionPermission - // StrongNameIdentityPermission - // RegistryPermission - // PublisherIdentityPermission - - switch (classNameLength) - { - case 12: - // UIPermission - if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UIPermission( permState ); - else - goto USEREFLECTION; - - case 16: - // FileIOPermission - if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileIOPermission( permState ); - else - goto USEREFLECTION; - - case 18: - // RegistryPermission - // SecurityPermission - if (className[classNameStart] == 'R') - { - if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new RegistryPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SecurityPermission( permState ); - else - goto USEREFLECTION; - } - case 20: - // ReflectionPermission - // FileDialogPermission - if (className[classNameStart] == 'R') - { - if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ReflectionPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileDialogPermission( permState ); - else - goto USEREFLECTION; - } - - case 21: - // EnvironmentPermission - // UrlIdentityPermission - // GacIdentityPermission - if (className[classNameStart] == 'E') - { - if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new EnvironmentPermission( permState ); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'U') - { - if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UrlIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new GacIdentityPermission( permState ); - else - goto USEREFLECTION; - } - case 22: - // SiteIdentityPermission - // ZoneIdentityPermission - // KeyContainerPermission - if (className[classNameStart] == 'S') - { - if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SiteIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'Z') - { - if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ZoneIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new KeyContainerPermission( permState ); - else - goto USEREFLECTION; - } - case 24: - // HostProtectionPermission - if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new HostProtectionPermission( permState ); - else - goto USEREFLECTION; - case 28: - // StrongNameIdentityPermission - if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new StrongNameIdentityPermission( permState ); - else - goto USEREFLECTION; - default: - goto USEREFLECTION; - } - -USEREFLECTION: - - Object[] objs = new Object[1]; - objs[0] = permState; - - Type permClass = null; - IPermission perm = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - permClass = GetClassFromElement(el, ignoreTypeLoadFailures); - if (permClass == null) - return null; - if (!(typeof(IPermission).IsAssignableFrom(permClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") ); - - perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null ); - - return perm; - } - - internal static Type - GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) - { - String className = el.Attribute( "class" ); - - if (className == null) - { - if (ignoreTypeLoadFailures) - return null; - else - throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") ); - } - - if (ignoreTypeLoadFailures) - { - try - { - return Type.GetType(className, false, false); - } - catch (SecurityException) - { - return null; - } - } - else - return Type.GetType(className, true, false); - } - - public static bool - IsPermissionElement (IPermission ip, - SecurityElement el) - { - if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission")) - return false; - - return true; - } - - public static bool - IsUnrestricted (SecurityElement el) - { - String sUnrestricted = el.Attribute( "Unrestricted" ); - - if (sUnrestricted == null) - return false; - - return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" ); - } - - - public static String BitFieldEnumToString( Type type, Object value ) - { - int iValue = (int)value; - - if (iValue == 0) - return Enum.GetName( type, 0 ); - - StringBuilder result = StringBuilderCache.Acquire(); - bool first = true; - int flag = 0x1; - - for (int i = 1; i < 32; ++i) - { - if ((flag & iValue) != 0) - { - String sFlag = Enum.GetName( type, flag ); - - if (sFlag == null) - continue; - - if (!first) - { - result.Append( ", " ); - } - - result.Append( sFlag ); - first = false; - } - - flag = flag << 1; - } - - return StringBuilderCache.GetStringAndRelease(result); - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/sitestring.cs b/src/mscorlib/src/System/Security/Util/sitestring.cs deleted file mode 100644 index 28f23742ec..0000000000 --- a/src/mscorlib/src/System/Security/Util/sitestring.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Util { - using System; - using System.Collections; - using System.Globalization; - using System.Diagnostics.Contracts; - - [Serializable] - internal class SiteString - { - protected String m_site; - protected ArrayList m_separatedSite; - - protected static char[] m_separators = { '.' }; - - protected internal SiteString() - { - // Only call this in derived classes when you know what you're doing. - } - - public SiteString( String site ) - { - m_separatedSite = CreateSeparatedSite( site ); - m_site = site; - } - - private SiteString(String site, ArrayList separatedSite) - { - m_separatedSite = separatedSite; - m_site = site; - } - - private static ArrayList CreateSeparatedSite(String site) - { - if (site == null || site.Length == 0) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - int braIndex = -1; - int ketIndex = -1; - braIndex = site.IndexOf('['); - if (braIndex == 0) - ketIndex = site.IndexOf(']', braIndex+1); - - if (ketIndex != -1) - { - // Found an IPv6 address. Special case that - String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1); - list.Add(ipv6Addr); - return list; - } - - // Regular hostnames or IPv4 addresses - // We dont need to do this for IPv4 addresses, but it's easier to do it anyway - String[] separatedArray = site.Split( m_separators ); - - for (int index = separatedArray.Length-1; index > -1; --index) - { - if (separatedArray[index] == null) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - else if (separatedArray[index].Equals( "" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != 0) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - list.Add( separatedArray[index] ); - } - else if (!AllLegalCharacters( separatedArray[index] )) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - // KB# Q188997 - http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q188997& gives the list of allowed characters in - // a NETBIOS name. DNS names are a subset of that (alphanumeric or '-'). - private static bool AllLegalCharacters( String str ) - { - for (int i = 0; i < str.Length; ++i) - { - char c = str[i]; - - if (IsLegalDNSChar(c) || - IsNetbiosSplChar(c)) - { - continue; - } - else - { - return false; - } - } - - return true; - } - - private static bool IsLegalDNSChar(char c) - { - if ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - (c == '-')) - return true; - else - return false; - } - private static bool IsNetbiosSplChar(char c) - { - // ! @ # $ % ^ & ( ) - _ ' { } . ~ are OK - switch (c) { - case '-': - case '_': - case '@': - case '!': - case '#': - case '$': - case '%': - case '^': - case '&': - case '(': - case ')': - case '\'': - case '{': - case '}': - case '.': - case '~': - return true; - default: - return false; - } - } - - public override String ToString() - { - return m_site; - } - - public override bool Equals(Object o) - { - if (o == null || !(o is SiteString)) - return false; - else - return this.Equals( (SiteString)o, true ); - } - - public override int GetHashCode() - { - TextInfo info = CultureInfo.InvariantCulture.TextInfo; - - return info.GetCaseInsensitiveHashCode( this.m_site ); - } - - internal bool Equals( SiteString ss, bool ignoreCase ) - { - if (this.m_site == null) - return ss.m_site == null; - if (ss.m_site == null) - return false; - return this.IsSubsetOf(ss, ignoreCase) && ss.IsSubsetOf(this, ignoreCase); - } - - - public virtual SiteString Copy() - { - return new SiteString( m_site, m_separatedSite ); - } - - public virtual bool IsSubsetOf( SiteString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( SiteString operand, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (operand == null) - { - return false; - } - else if (this.m_separatedSite.Count == operand.m_separatedSite.Count && - this.m_separatedSite.Count == 0) - { - return true; - } - else if (this.m_separatedSite.Count < operand.m_separatedSite.Count - 1) - { - return false; - } - else if (this.m_separatedSite.Count > operand.m_separatedSite.Count && - operand.m_separatedSite.Count > 0 && - !operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")) - { - return false; - } - else if (String.Compare( this.m_site, operand.m_site, strComp) == 0) - { - return true; - } - - for (int index = 0; index < operand.m_separatedSite.Count - 1; ++index) - { - if (String.Compare((String)this.m_separatedSite[index], (String)operand.m_separatedSite[index], strComp) != 0) - { - return false; - } - } - - if (this.m_separatedSite.Count < operand.m_separatedSite.Count) - { - return operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"); - } - else if (this.m_separatedSite.Count == operand.m_separatedSite.Count) - { - // last item must be the same or operand must have a * in its last item - return (String.Compare((String)this.m_separatedSite[this.m_separatedSite.Count - 1], - (String)operand.m_separatedSite[this.m_separatedSite.Count - 1], - strComp ) == 0 || - operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")); - - } - else - return true; - } - - - - public virtual SiteString Intersect( SiteString operand ) - { - if (operand == null) - { - return null; - } - else if (this.IsSubsetOf( operand )) - { - return this.Copy(); - } - else if (operand.IsSubsetOf( this )) - { - return operand.Copy(); - } - else - { - return null; - } - } - - public virtual SiteString Union( SiteString operand ) - { - if (operand == null) - { - return this; - } - else if (this.IsSubsetOf( operand )) - { - return operand.Copy(); - } - else if (operand.IsSubsetOf( this )) - { - return this.Copy(); - } - else - { - return null; - } - } - } -} diff --git a/src/mscorlib/src/System/Security/VerificationException.cs b/src/mscorlib/src/System/Security/VerificationException.cs index b0823cac01..5defbd6603 100644 --- a/src/mscorlib/src/System/Security/VerificationException.cs +++ b/src/mscorlib/src/System/Security/VerificationException.cs @@ -9,7 +9,6 @@ namespace System.Security { using System; using System.Runtime.Serialization; - [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class VerificationException : SystemException { public VerificationException() diff --git a/src/mscorlib/src/System/Security/securestring.cs b/src/mscorlib/src/System/Security/securestring.cs deleted file mode 100644 index 548126f4d0..0000000000 --- a/src/mscorlib/src/System/Security/securestring.cs +++ /dev/null @@ -1,751 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// 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.Security.Cryptography; - using System.Runtime.InteropServices; -#if FEATURE_CORRUPTING_EXCEPTIONS - using System.Runtime.ExceptionServices; -#endif // FEATURE_CORRUPTING_EXCEPTIONS - using System.Text; - using Microsoft.Win32; - using System.Runtime.CompilerServices; - using System.Security.Permissions; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using Microsoft.Win32.SafeHandles; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - public sealed class SecureString: IDisposable { - [System.Security.SecurityCritical] // auto-generated - private SafeBSTRHandle m_buffer; - [ContractPublicPropertyName("Length")] - private int m_length; - private bool m_readOnly; - private bool m_encrypted; - - static bool supportedOnCurrentPlatform = EncryptionSupported(); - - const int BlockSize = (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE /2; // a char is two bytes - const int MaxLength = 65536; - const uint ProtectionScope = Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS; - - [System.Security.SecuritySafeCritical] // auto-generated - static SecureString() - { - } - - [System.Security.SecurityCritical] // auto-generated - unsafe static bool EncryptionSupported() { - // check if the enrypt/decrypt function is supported on current OS - bool supported = true; - try { - Win32Native.SystemFunction041( - SafeBSTRHandle.Allocate(null , (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE), - Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE, - Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS); - } - catch (EntryPointNotFoundException) { - supported = false; - } - return supported; - } - - [System.Security.SecurityCritical] // auto-generated - internal SecureString(SecureString str) { - AllocateBuffer(str.BufferLength); - SafeBSTRHandle.Copy(str.m_buffer, this.m_buffer); - m_length = str.m_length; - m_encrypted = str.m_encrypted; - } - - - [System.Security.SecuritySafeCritical] // auto-generated - public SecureString() { - CheckSupportedOnCurrentPlatform(); - - // allocate the minimum block size for calling protectMemory - AllocateBuffer(BlockSize); - m_length = 0; - } - - - [System.Security.SecurityCritical] // auto-generated -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - private unsafe void InitializeSecureString(char* value, int length) - { - CheckSupportedOnCurrentPlatform(); - - AllocateBuffer(length); - m_length = length; - - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - m_buffer.AcquirePointer(ref bufferPtr); - Buffer.Memcpy(bufferPtr, (byte*)value, length * 2); - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally - { - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - - ProtectMemory(); - } - - [System.Security.SecurityCritical] // auto-generated - [CLSCompliant(false)] - public unsafe SecureString(char* value, int length) { - if( value == null) { - throw new ArgumentNullException(nameof(value)); - } - - if( length < 0) { - throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); - } - - if( length > MaxLength) { - throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Length")); - } - Contract.EndContractBlock(); - - // Refactored since HandleProcessCorruptedStateExceptionsAttribute applies to methods only (yet). - InitializeSecureString(value, length); - } - - public int Length { - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - get { - EnsureNotDisposed(); - return m_length; - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - public void AppendChar(char c) { - EnsureNotDisposed(); - EnsureNotReadOnly(); - - EnsureCapacity(m_length + 1); - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - UnProtectMemory(); - m_buffer.Write<char>((uint)m_length * sizeof(char), c); - m_length++; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - } - } - - // clears the current contents. Only available if writable - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - public void Clear() { - EnsureNotDisposed(); - EnsureNotReadOnly(); - - m_length = 0; - m_buffer.ClearBuffer(); - m_encrypted = false; - } - - // Do a deep-copy of the SecureString - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - public SecureString Copy() { - EnsureNotDisposed(); - return new SecureString(this); - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - public void Dispose() { - if(m_buffer != null && !m_buffer.IsInvalid) { - m_buffer.Close(); - m_buffer = null; - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - public void InsertAt( int index, char c ) { - if( index < 0 || index > m_length) { - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); - } - Contract.EndContractBlock(); - - EnsureNotDisposed(); - EnsureNotReadOnly(); - - EnsureCapacity(m_length + 1); - - unsafe { - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try { - UnProtectMemory(); - m_buffer.AcquirePointer(ref bufferPtr); - char* pBuffer = (char*)bufferPtr; - - for (int i = m_length; i > index; i--) { - pBuffer[i] = pBuffer[i - 1]; - } - pBuffer[index] = c; - ++m_length; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - public bool IsReadOnly() { - EnsureNotDisposed(); - return m_readOnly; - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] - public void MakeReadOnly() { - EnsureNotDisposed(); - m_readOnly = true; - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - public void RemoveAt( int index ) { - EnsureNotDisposed(); - EnsureNotReadOnly(); - - if( index < 0 || index >= m_length) { - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); - } - - unsafe - { - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - UnProtectMemory(); - m_buffer.AcquirePointer(ref bufferPtr); - char* pBuffer = (char*)bufferPtr; - - for (int i = index; i < m_length - 1; i++) - { - pBuffer[i] = pBuffer[i + 1]; - } - pBuffer[--m_length] = (char)0; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally - { - ProtectMemory(); - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - } - } - - [System.Security.SecuritySafeCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - public void SetAt( int index, char c ) { - if( index < 0 || index >= m_length) { - throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString")); - } - Contract.EndContractBlock(); - Debug.Assert(index <= Int32.MaxValue / sizeof(char)); - - EnsureNotDisposed(); - EnsureNotReadOnly(); - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - UnProtectMemory(); - m_buffer.Write<char>((uint)index * sizeof(char), c); - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - } - } - - private int BufferLength { - [System.Security.SecurityCritical] // auto-generated - get { - Debug.Assert(m_buffer != null, "Buffer is not initialized!"); - return m_buffer.Length; - } - } - - [System.Security.SecurityCritical] // auto-generated - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - private void AllocateBuffer(int size) { - uint alignedSize = GetAlignedSize(size); - - m_buffer = SafeBSTRHandle.Allocate(null, alignedSize); - if (m_buffer.IsInvalid) { - throw new OutOfMemoryException(); - } - } - - private void CheckSupportedOnCurrentPlatform() { - if( !supportedOnCurrentPlatform) { - throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString")); - } - Contract.EndContractBlock(); - } - - [System.Security.SecurityCritical] // auto-generated - private void EnsureCapacity(int capacity) { - if( capacity > MaxLength) { - throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity")); - } - Contract.EndContractBlock(); - - if( capacity <= m_buffer.Length) { - return; - } - - SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(null, GetAlignedSize(capacity)); - - if (newBuffer.IsInvalid) { - throw new OutOfMemoryException(); - } - - SafeBSTRHandle.Copy(m_buffer, newBuffer); - m_buffer.Close(); - m_buffer = newBuffer; - } - - [System.Security.SecurityCritical] // auto-generated - private void EnsureNotDisposed() { - if( m_buffer == null) { - throw new ObjectDisposedException(null); - } - Contract.EndContractBlock(); - } - - private void EnsureNotReadOnly() { - if( m_readOnly) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); - } - Contract.EndContractBlock(); - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - private static uint GetAlignedSize( int size) { - 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 - alignedSize += BlockSize; - } - return alignedSize; - } - - [System.Security.SecurityCritical] // auto-generated - private unsafe int GetAnsiByteCount() { - const uint CP_ACP = 0; - const uint WC_NO_BEST_FIT_CHARS = 0x00000400; - - uint flgs = WC_NO_BEST_FIT_CHARS; - uint DefaultCharUsed = (uint)'?'; - - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try { - m_buffer.AcquirePointer(ref bufferPtr); - - return Win32Native.WideCharToMultiByte( - CP_ACP, - flgs, - (char*) bufferPtr, - m_length, - null, - 0, - IntPtr.Zero, - new IntPtr((void*)&DefaultCharUsed)); - } - finally { - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - } - - [System.Security.SecurityCritical] // auto-generated - private unsafe void GetAnsiBytes( byte * ansiStrPtr, int byteCount) { - const uint CP_ACP = 0; - const uint WC_NO_BEST_FIT_CHARS = 0x00000400; - - uint flgs = WC_NO_BEST_FIT_CHARS; - uint DefaultCharUsed = (uint)'?'; - - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try { - m_buffer.AcquirePointer(ref bufferPtr); - - Win32Native.WideCharToMultiByte( - CP_ACP, - flgs, - (char*) bufferPtr, - m_length, - ansiStrPtr, - byteCount - 1, - IntPtr.Zero, - new IntPtr((void*)&DefaultCharUsed)); - - *(ansiStrPtr + byteCount - 1) = (byte)0; - } - finally { - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - } - - [System.Security.SecurityCritical] // auto-generated - [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] - private void ProtectMemory() { - 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; - } - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - // RtlEncryptMemory return an NTSTATUS - int status = Win32Native.SystemFunction040(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope); - if (status < 0) { // non-negative numbers indicate success -#if FEATURE_CORECLR - throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status)); -#else - throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status)); -#endif - } - m_encrypted = true; - } - } - - [System.Security.SecurityCritical] // auto-generated - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - internal unsafe IntPtr ToBSTR() { - EnsureNotDisposed(); - int length = m_length; - IntPtr ptr = IntPtr.Zero; - IntPtr result = IntPtr.Zero; - byte* bufferPtr = null; - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - ptr = Win32Native.SysAllocStringLen(null, length); - } - - if (ptr == IntPtr.Zero) { - throw new OutOfMemoryException(); - } - - UnProtectMemory(); - m_buffer.AcquirePointer(ref bufferPtr); - Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2); - result = ptr; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - if( result == IntPtr.Zero) { - // If we failed for any reason, free the new buffer - if (ptr != IntPtr.Zero) { - Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2)); - Win32Native.SysFreeString(ptr); - } - } - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - return result; - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - internal unsafe IntPtr ToUniStr(bool allocateFromHeap) { - EnsureNotDisposed(); - int length = m_length; - IntPtr ptr = IntPtr.Zero; - IntPtr result = IntPtr.Zero; - byte* bufferPtr = null; - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - if( allocateFromHeap) { - ptr = Marshal.AllocHGlobal((length + 1) * 2); - } - else { - ptr = Marshal.AllocCoTaskMem((length + 1) * 2); - } - } - - if (ptr == IntPtr.Zero) { - throw new OutOfMemoryException(); - } - - UnProtectMemory(); - m_buffer.AcquirePointer(ref bufferPtr); - Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2); - char * endptr = (char *) ptr.ToPointer(); - *(endptr + length) = '\0'; - result = ptr; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - - if( result == IntPtr.Zero) { - // If we failed for any reason, free the new buffer - if (ptr != IntPtr.Zero) { - Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2)); - if( allocateFromHeap) { - Marshal.FreeHGlobal(ptr); - } - else { - Marshal.FreeCoTaskMem(ptr); - } - } - } - - if (bufferPtr != null) - m_buffer.ReleasePointer(); - } - return result; - } - - [System.Security.SecurityCritical] // auto-generated - [MethodImplAttribute(MethodImplOptions.Synchronized)] -#if FEATURE_CORRUPTING_EXCEPTIONS - [HandleProcessCorruptedStateExceptions] -#endif // FEATURE_CORRUPTING_EXCEPTIONS - internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) { - EnsureNotDisposed(); - - IntPtr ptr = IntPtr.Zero; - IntPtr result = IntPtr.Zero; - int byteCount = 0; - RuntimeHelpers.PrepareConstrainedRegions(); - try { - // GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted. - UnProtectMemory(); - - // allocating an extra char for terminating zero - byteCount = GetAnsiByteCount() + 1; - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - if( allocateFromHeap) { - ptr = Marshal.AllocHGlobal(byteCount); - } - else { - ptr = Marshal.AllocCoTaskMem(byteCount); - } - } - - if (ptr == IntPtr.Zero) { - throw new OutOfMemoryException(); - } - - GetAnsiBytes((byte *)ptr.ToPointer(), byteCount); - result = ptr; - } - catch (Exception) { - ProtectMemory(); - throw; - } - finally { - ProtectMemory(); - if( result == IntPtr.Zero) { - // If we failed for any reason, free the new buffer - if (ptr != IntPtr.Zero) { - Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount); - if( allocateFromHeap) { - Marshal.FreeHGlobal(ptr); - } - else { - Marshal.FreeCoTaskMem(ptr); - } - } - } - - } - return result; - } - - [System.Security.SecurityCritical] // auto-generated - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - private void UnProtectMemory() { - 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; - } - - RuntimeHelpers.PrepareConstrainedRegions(); - try { - } - finally { - if (m_encrypted) { - // RtlEncryptMemory return an NTSTATUS - int status = Win32Native.SystemFunction041(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope); - if (status < 0) - { // non-negative numbers indicate success -#if FEATURE_CORECLR - throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status)); -#else - throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status)); -#endif - } - m_encrypted = false; - } - } - } - } - - [System.Security.SecurityCritical] // auto-generated - [SuppressUnmanagedCodeSecurityAttribute()] - internal sealed class SafeBSTRHandle : SafeBuffer { - internal SafeBSTRHandle () : base(true) {} - - internal static SafeBSTRHandle Allocate(String src, uint len) - { - SafeBSTRHandle bstr = SysAllocStringLen(src, len); - bstr.Initialize(len * sizeof(char)); - return bstr; - } - - [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)] - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - private static extern SafeBSTRHandle SysAllocStringLen(String src, uint len); // BSTR - - [System.Security.SecurityCritical] - override protected bool ReleaseHandle() - { - Win32Native.ZeroMemory(handle, (UIntPtr) (Win32Native.SysStringLen(handle) * 2)); - Win32Native.SysFreeString(handle); - return true; - } - - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - internal unsafe void ClearBuffer() { - byte* bufferPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - AcquirePointer(ref bufferPtr); - Win32Native.ZeroMemory((IntPtr)bufferPtr, (UIntPtr) (Win32Native.SysStringLen((IntPtr)bufferPtr) * 2)); - } - finally - { - if (bufferPtr != null) - ReleasePointer(); - } - } - - - internal unsafe int Length { - get { - return (int) Win32Native.SysStringLen(this); - } - } - - internal unsafe static void Copy(SafeBSTRHandle source, SafeBSTRHandle target) { - byte* sourcePtr = null, targetPtr = null; - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - source.AcquirePointer(ref sourcePtr); - target.AcquirePointer(ref targetPtr); - - 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); - } - finally - { - if (sourcePtr != null) - source.ReleasePointer(); - if (targetPtr != null) - target.ReleasePointer(); - } - } - } -} - |