完全受信任程序集内的代码权限评估失败

时间:2014-06-26 13:13:15

标签: c# .net sandbox code-access-security

我想使用来自我的'沙盒'类工作者的反射,并抓住我无法解释的行为。

  • 如果我在创建时不在FullTrustList中添加当前程序集 appdomain,然后代码运行正常。
  • 如果我在FullTrustList中添加当前程序集,那么 PropertyInfo.GetValue抛出SecurityException。它需要完整 信任,但在appdomain内我有限制的授权集。

问题可以通过PermissionSet.Assert()来解决,但它看起来像脏黑客。

有谁知道为什么代码权限评估在两种情况下都不同?

public static class Security
{
    public static void Fail()
    {
        var name = Guid.NewGuid().ToString();

        var appSetup = new AppDomainSetup
            {
                ApplicationName = name,
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };

        // add permissions
        var permissions = new PermissionSet(PermissionState.None);
        permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
        permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
        permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

        var type = typeof(Worker);
        // get strong name to add assembly in full-trusted
        var sn1 = type.Assembly.Evidence.GetHostEvidence<StrongName>();

        var domain = AppDomain.CreateDomain(name, null, appSetup, permissions, sn1);
        var worker = (Worker) Activator.CreateInstanceFrom(domain,
                                                           type.Assembly.ManifestModule
                                                                          .FullyQualifiedName,
                                                           type.FullName).Unwrap();
        try
        {
            worker.TryReflect();
        }
        catch (SecurityException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    private class Worker : MarshalByRefObject
    {
        public static int Prop1 { get; private set; }

        public void TryReflect()
        {
            var prop = typeof (Worker).GetProperty("Prop1");
            // exception is thrown here:
            var val = prop.GetValue(null);
        }
    }
}

示例在这里https://www.sendspace.com/file/svdzhk

0 个答案:

没有答案