gpt4 book ai didi

具有 SecuritySafeCritical 函数的 C# 完全信任的程序集仍然抛出安全异常

转载 作者:太空狗 更新时间:2023-10-30 00:58:04 25 4
gpt4 key购买 nike

我正在尝试创建一个沙盒 AppDomain 来加载扩展/插件。我有一个 MarshalByRefObject,它在 appdomain 中实例化以加载 dll。我在尝试加载 dll 时收到 SecurityExceptions,我无法弄清楚如何绕过它们,同时仍然限制第三方代码可以做什么。我所有的项目都是 .net 4。

InDomainLoader 类在完全信任的域中,该方法被标记为 SecuritySafeCritical。从我读过的所有内容来看,我认为这应该可行。

这是我创建 AppDomain 并跳入其中的 Loader 类:

public class Loader
{
public void Load(string dll, string typeName)
{
Log.PrintSecurity();

// Create new AppDomain
var setup = AppDomain.CurrentDomain.SetupInformation;
var permissions = new PermissionSet(null);
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
var strongname = typeof(InDomainLoader).Assembly.Evidence.GetHostEvidence<StrongName>();
var strongname2 = typeof(IPlugin).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomain domain = AppDomain.CreateDomain("plugin", null, setup, permissions, strongname, strongname2);

// Create instance
var loader = (InDomainLoader)domain.CreateInstanceAndUnwrap(
typeof (InDomainLoader).Assembly.FullName, typeof (InDomainLoader).FullName);

// Jump into domain
loader.Load(dll, typeName);
}
}

这是在域中运行的引导加载程序:

public class InDomainLoader : MarshalByRefObject
{
[SecuritySafeCritical]
public void Load(string dll, string typeName)
{
Log.PrintSecurity();

var assembly = Assembly.LoadFrom(dll); // <!-- SecurityException!
var pluginType = assembly.GetType(typeName);

var demoRepository = new DemoRepository();
var plugin = (IPlugin)Activator.CreateInstance(pluginType, demoRepository);
Console.WriteLine(plugin.Run());
}
}

一些日志记录语句告诉我程序集的 IsFullyTrusted 是 true 并且该方法同时将 IsSecurityCriticalIsSecuritySafeCritical 设置为 true, IsSecurityTransparent 为假。

我将整个项目压缩到 http://davidhogue.com/files/PluginLoader.zip以防万一让这更容易。

如果有人有任何想法,我将不胜感激。我在这里似乎陷入了死胡同。

最佳答案

好吧,首先您可能不应该将函数标记为 SecuritySafeCritical,因为这意味着不受信任的调用者可以调用您,而您可能并不真正想要这样做(并不是说这应该是一个主要问题)。

至于你的问题,问题是默认情况下你仍然没有任何特殊权限运行,通常简单的程序集加载方法是你创建你自己的 AppDomainSetup 并将它的 ApplicationBase 指向某种插件目录(这通常不是一个坏主意),然后您可以使用普通的 Assembly.Load("AssemblyName") 从基础中加载。但是,如果您必须加载任意文件,则需要为插件 dll(完整路径)断言 FileIOPermission,即

private Assembly LoadAssemblyFromFile(string file)
{
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, file);
perm.Assert();

return Assembly.LoadFile(file);
}

关于具有 SecuritySafeCritical 函数的 C# 完全信任的程序集仍然抛出安全异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3704981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com