c# - 受限 AppDomain 中的代码访问安全异常

标签 c# appdomain code-access-security

目标:我需要在权限非常有限的 AppDomain 中运行一些代码 - 它应该无法访问任何花哨或不安全的东西,除了少数我在别处定义的辅助方法。

我所做的:我正在创建一个具有所需基本权限的沙箱 AppDomain,并创建一个运行代码的代理对象:

static AppDomain CreateSandbox()
{
    var e = new Evidence();
    e.AddHostEvidence(new Zone(SecurityZone.Internet));

    var ps = SecurityManager.GetStandardSandbox(e);
    var security = new SecurityPermission(SecurityPermissionFlag.Execution);

    ps.AddPermission(security);

    var setup = new AppDomainSetup { 
        ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) 
    };
    return AppDomain.CreateDomain("Sandbox" + DateTime.Now, null, setup, ps);
}

public class Proxy : MarshalByRefObject
{
    public Proxy() { }

    public DoStuff()
    {
       // perform custom operation requiring permission
       HelperAssembly.HelperMethods.Method1();

       // do other stuff with low permission level
       ...
       ...
       ...   
    }
}

我已将辅助方法放入专用的强命名程序集,并使用 [SecuritySafeCritical] 标记它们及其容器类:

// HelperAssembly.dll

namespace HelperAssembly
{
    [SecuritySafeCritical]
    public class HelperMethods
    {
        [SecuritySafeCritical]
        public static void Method1()
        {
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)
                .Assert();
            try
            {
                // logic requiring unmanaged code
                ...
            }
            finally
            {
                CodeAccessSecurity.RevertAll();
            }

        }
    }
}

然后,我在沙箱 AppDomain 中加载助手程序集并运行 Proxy.DoStuff(),期望它执行助手方法并继续运行:

var appDomain = CreateSandbox();

appDomain.Load(typeof(HelperAssembly.HelperMethods).Assembly.FullName);

var proxy = (Proxy)sandbox.CreateInstance(
    typeof(Proxy).Assembly.FullName, 
    typeof(Proxy).FullName).Unwrap();

proxy.DoStuff();

但是,运行代码会导致辅助方法中的 Assert() 行发生异常:

Unhandled Exception: System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods

这种行为的原因是什么?我怎样才能实现我想要做的事情?据我了解,不受信任的 AppDomain 中的代码是安全透明的,而辅助程序集中的代码是安全关键的,这意味着它应该能够使用 Assert() 请求权限。

我显然遗漏了一 block 拼图,因此需要对代码访问安全性有更好理解的人来解释出了什么问题。感谢您的帮助。

最佳答案

您的“受信任”程序集需要具有 AllowPartiallyTrustedCallers 属性才能跨程序集边界调用 SecuritySafeCritical。在调用 CreateDomain 时,还必须将它添加到 fullTrustAssemblies

关于c# - 受限 AppDomain 中的代码访问安全异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19212821/

相关文章:

c# - 重写 Equals 和 GetHashCode 不一定会重写相等重载运算符

c# - AspNet.Security.OpenIdConnect.Server。刷新 token

c# - 列出存储在 AppDomain 中的所有自定义数据

code-access-security - 防止代码盗窃 - Chaperon 或类似的东西

java - 反射机制是否破坏了java中的安全性?请解释

c# - 使用已安装产品的升级代码获取产品版本

c# - 打印图像的 boolean 转换器,只需打印图像名称 c#

c# - ASP .NET 5 应用程序部署

c# - 是否可以限制应用程序域的性能或设置配额?

c# - 沙箱 AppDomain 跨程序集异常处理