How to determine if access code security is enabled in library code

In .NET 4, Code Access Security (CAS) is deprecated. Whenever you call a method that implicitly uses it, it fails with NotSupportedException, which can be resolved using a configuration configuration that causes it to fall back to the old behavior.

We have a shared library that is used in both .NET 3.5 and .NET 4, so we need to determine whether to use the CAS method.

For example, in .NET 3.5 I have to call:

Assembly.Load(string, Evidence);

While in .NET 4 I want to call

Assembly.Load(string);

The call Load(string, Evidence)causes a NotSupportedException.

Of course this works, but I would like to know if there is a better way:

try
{
    asm = Assembly.Load(someString, someEvidence);
}
catch(NotSupportedException)
{
    asm = Assembly.Load(someString);
}
+3
3

HI, Environment.Version.Major Environment.Version.Minor .

Version v = Environment.Version;
if (Environment.Version.Major <= 3)
{
    //DO 3.5 here
}
else if (Environment.Version.Major >= 4)
{
     //DO 4 here
}

, .

: , , CAS .NET.

+2

.

    public static Assembly LoadAssembly(string assembly, Evidence evidence)
    {
        Assembly asm;
        MethodInfo load = 
            typeof(Assembly).GetMethod("Load", 
                                        new Type[] {typeof(string), typeof(Evidence)});

        if (Attribute.IsDefined(load, typeof(ObsoleteAttribute)))
        {
            asm = Assembly.Load(assembly);
        }
        else
        {
            asm = Assembly.Load(assembly, evidence);
        }
        return asm;
    }

.

using System;
using System.Reflection;
using System.Security.Policy;

, - .

private static bool? _isEvidenceObsolete = null;
public static Assembly AssemblyLoader(string assembly, Evidence evidence)
{
    Assembly asm;
    if (!_isEvidenceObsolete.HasValue)
    {
        MethodInfo load =
           typeof(Assembly).GetMethod("Load",
                                       new Type[] { typeof(string), typeof(Evidence) });
        _isEvidenceObsolete = Attribute.IsDefined(load, typeof(ObsoleteAttribute));
    }

    if (_isEvidenceObsolete.Value)
    {
        asm = Assembly.Load(assembly);
    }
    else
    {
        asm = Assembly.Load(assembly, evidence);
    }
    return asm;
}

: , . , .

:

Catch Exception: 45331
Reflection: 58
Static Reflection: 1

, :

public static void BenchmarkLoaders()
{
    Stopwatch timer = new Stopwatch();

    // Benchmark catching Exceptions
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported notSupported = new NotSupported();
        try
        {
            notSupported.ThrowException("Obsoleted Method Call");
        }
        catch (NotSupportedException nse)
        {
            //Do something
        }
    }
    timer.Stop();
    Console.WriteLine("Catch Exception: {0}", timer.ElapsedMilliseconds);
    timer.Reset();

    // Benchmark Reflection
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported notSupported = new NotSupported();

        notSupported.ReflectAssembly();
    }
    timer.Stop();
    Console.WriteLine("Reflection: {0}", timer.ElapsedMilliseconds);
    timer.Reset();


    // Benchmark Static Reflection
    timer.Start();
    for (int i = 0; i < 10000; i++)
    {
        NotSupported.ReflectAssemblyStatic();
    }
    timer.Stop();
    Console.WriteLine("Static Reflection: {0}", timer.ElapsedMilliseconds);
    timer.Reset();

}

NotSupported.

public class NotSupported
{
    public void ThrowException(string message)
    {
        throw new NotSupportedException(message);
    }

    public void ReflectAssembly()
    {
        MethodInfo load = 
            typeof(Assembly).GetMethod("Load", 
                                        new Type[] { typeof(string), typeof(Evidence) });

        if (Attribute.IsDefined(load, typeof(ObsoleteAttribute)))
        {
            // Do something
        }
    }

    private static bool? _isEvidenceObsolete = null;
    public static void ReflectAssemblyStatic()
    {
        Assembly asm;
        if (!_isEvidenceObsolete.HasValue)
        {
            MethodInfo load =
               typeof(Assembly).GetMethod("Load",
                                           new Type[] { typeof(string), typeof(Evidence) });
            _isEvidenceObsolete = Attribute.IsDefined(load, typeof(ObsoleteAttribute));
        }

        if (_isEvidenceObsolete.Value)
        {
            //Do Stuff
        }
    }
}

, , .

+1

The recipient for the System.Security.HostSecurityManager.DomainPolicy property is a public, easy method that will end quickly in .NET 4.0 if the legacy CAS policy switch is not applied. You might want to consider creating a helper class that will allow you to avoid losing the cost of a potential exception more than once. eg:.

internal static class CasPolicyHelper
{
    private static bool? _isCasPolicyEnabled;

    internal static bool IsCasPolicyEnabled
    {
        get
        {
            if (_isCasPolicyEnabled == null)
            {
                HostSecurityManager hostSecurityManager = new HostSecurityManager();
                try
                {
                    PolicyLevel level = hostSecurityManager.DomainPolicy;
                    _isCasPolicyEnabled = true;
                }
                catch (NotSupportedException)
                {
                    _isCasPolicyEnabled = false;
                }
            }

            return _isCasPolicyEnabled.Value;
        }
    }
}
0
source

Source: https://habr.com/ru/post/1738694/


All Articles