订阅域事件时出现C#AppDomain沙箱安全异常
我正在编写一个插件系统来在我的服务器应用程序(C#,.NET 4.0)中运行客户端提供的不可信代码。 为了做到这一点,我在新的沙箱AppDomain中运行每个插件。
然而,我坚持一个安全例外,我不明白其中的原因。 我已经制作了简化的控制台应用程序示例来说明问题:
namespace SandboxTest
{
class Program
{
static void Main( string[] args )
{
Sandbox sandbox = new Sandbox();
Console.ReadLine();
}
}
class Sandbox
{
AppDomain domain;
public Sandbox()
{
PermissionSet ps = new PermissionSet( PermissionState.None );
ps.AddPermission( new SecurityPermission( SecurityPermissionFlag.Execution ) );
try
{
domain = AppDomain.CreateDomain( "Sandbox", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, ps );
domain.AssemblyLoad += new AssemblyLoadEventHandler( domain_AssemblyLoad );
domain.AssemblyResolve += new ResolveEventHandler( domain_AssemblyResolve );
}
catch( Exception e )
{
Trace.WriteLine( e.ToString() );
throw e;
}
}
static Assembly domain_AssemblyResolve( object sender, ResolveEventArgs args )
{
return null;
}
static void domain_AssemblyLoad( object sender, AssemblyLoadEventArgs args )
{
}
}
}
在运行此代码时,我在domain.AssemblyLoad行中收到以下异常:
A first chance exception of type 'System.Security.SecurityException' occurred in SandboxTest.exe
'SandboxTest.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Configurationv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.CheckHelper(PermissionSet grantedSet, PermissionSet refusedSet, CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
at System.Security.CodeAccessSecurityEngine.CheckHelper(CompressedStack cs, PermissionSet grantedSet, PermissionSet refusedSet, CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, RuntimeAssembly asm, SecurityAction action)
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.DelegateSerializationHolder.GetDelegateSerializationInfo(SerializationInfo info, Type delegateType, Object target, MethodInfo method, Int32 targetIndex)
at System.MulticastDelegate.GetObjectData(SerializationInfo info, StreamingContext context)
at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String& typeName, String& assemName, String[]& fieldNames, Object[]& fieldValues)
at System.AppDomain.add_AssemblyLoad(AssemblyLoadEventHandler value)
at SandboxTest.Sandbox..ctor() in C:DevProjectsBotfieldSandboxTestProgram.cs:line 36
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.ReflectionPermission
The first permission that failed was:
<IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="MemberAccess"/>
The demand was for:
<IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="MemberAccess"/>
The granted set of the failing assembly was:
<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
</PermissionSet>
我最好的猜测是,有一些事件订阅代码在新的沙箱AppDomain中执行,没有必要的安全权限,但我不知道如何解决它,没有给沙盒AppDomain提供完全的反射容量。 有人有任何建议或解释吗?
简短的回答 :
将事件添加到事件AppDomain.AssemblyLoad的隐藏方法 - 由SecurityCriticalAttribute标记。 检查ILASM:
.method public hidebysig newslot specialname virtual final
instance void add_AssemblyLoad(class System.AssemblyLoadEventHandler 'value') cil managed
{
.custom instance void System.Security.SecurityCriticalAttribute::.ctor() = ( 01 00 00 00 )
// Code size 0 (0x0)
} // end of method AppDomain::add_AssemblyLoad
为了执行这个方法,你必须在FullTrust模式(你的沙箱域)中执行它。 故事结局。
长答案 :
您正在处理跨域通信。 意味着您的事件处理程序将在Sandbox域的空间中执行,然后使用注册到您的父域的远程处理。 您提供的代码需要反射许可,在该方法中使用哪种事件并不重要 - 安全性至关重要。
所以,如果你希望你的沙箱域,与你的父域的安全通信,你应该使用传统的.NET远程处理的方式,此代码将不需要任何额外的权限,并允许通知父域有关的事件发生在沙箱域:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics;
using System.Reflection;
namespace SandboxTest
{
class Program
{
static void Main(string[] args)
{
Sandbox sandbox = new Sandbox();
Console.ReadLine();
}
}
class Sandbox
{
AppDomain domain;
public Sandbox()
{
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
try
{
domain = AppDomain.CreateDomain("Sandbox", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, ps);
var tp = typeof(MyInit);
var obj = (MyInit)domain.CreateInstanceAndUnwrap(tp.Assembly.FullName, tp.FullName);
var myCallBack = new MyCallBack();
myCallBack.Generated += new EventHandler(myCallBack_Generated);
obj.Subscribe(myCallBack);
obj.GenerateCallBackEvent();
}
catch (Exception e)
{
Trace.WriteLine(e.ToString());
throw e;
}
}
void myCallBack_Generated(object sender, EventArgs e)
{
//Executed in parent domain
}
}
public class MyCallBack:MarshalByRefObject
{
public void GenerateEvent()
{
//Executed in parent domain, but triggered by sandbox domain
if (Generated != null) Generated(this, null);
}
//for parent domain only
public event EventHandler Generated;
}
public class MyInit:MarshalByRefObject
{
public MyInit()
{
}
MyCallBack callback;
public void Subscribe(MyCallBack callback)
{
//executed on sandbox domain
this.callback = callback;
}
public void GenerateCallBackEvent()
{
//executed on sandbox domain
callback.GenerateEvent();
}
}
}
链接地址: http://www.djcxy.com/p/55615.html
上一篇: C# AppDomain sandbox security exception when subscribing to domain events
下一篇: Possible to drag an HTML dom element & drop onto an SVG dom element?