0

在 ASP.NET 应用程序中,我想创建一个 AppDomain,在其中运行不受信任的代码。但是,在初始化和展开我的程序集加载器时,会引发关于我没有传入的类型的异常。它是来自 web 请求 ( HttpContext.Current.User) 的当前用户,我认为它可以通过 LocalCallContext 提供。我不希望当前用户对不受信任的代码可用,实际上我希望不受信任的代码根本没有上下文。所以我想我可以传入一个显式的 CallContext,但似乎没有这样的事情。我将如何实现这一目标?

不受信任的代码是用户提供的 Razor 模板,将通过 RazorEngine 执行。

Evidence evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
PermissionSet permissionSet = SecurityManager.GetStandardSandbox(evidence);
FileIOPermission permission = new FileIOPermission(PermissionState.None);
FileIOPermissionAccess access = FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery;
permission.AddPathList(access, typeof(AssemblyLoader).Assembly.Location);
permissionSet.AddPermission(permission);

// We have to load ourself with full trust
StrongName loaderAssembly = typeof(AssemblyLoader).Assembly.Evidence.GetHostEvidence<StrongName>();
StrongName razorEngineAssembly = typeof(RazorEngineService).Assembly.Evidence.GetHostEvidence<StrongName>();
StrongName razorAssembly = typeof(RazorTemplateEngine).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomainSetup appDomainSetup = new AppDomainSetup
{
    ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
};
AppDomain sandBoxDomain = AppDomain.CreateDomain("Razor Template Sandbox", null, appDomainSetup, permissionSet, loaderAssembly, razorEngineAssembly, razorAssembly);

AssemblyLoader loader = (AssemblyLoader)sandBoxDomain.CreateInstanceFromAndUnwrap(typeof(AssemblyLoader).Assembly.Location, typeof(AssemblyLoader).FullName);

最后一行抛出这个异常,UnrelatedAssembly.SomeType是 my 的类型HttpContext.Current.User

System.Runtime.Serialization.SerializationException: 'Type is not resolved for member 'UnrelatedAssembly.SomeType,UnrelatedAssembly, Version=1.9.0.0, Culture=neutral, PublicKeyToken=null'.'
4

1 回答 1

0

我通过抑制执行上下文的流程并从单独的线程运行目标应用程序域中的所有代码来解决了这个问题的一部分。这看起来像这样:

var flow = ExecutionContext.SuppressFlow();
try
{
    return Task.Factory.StartNew(() =>
    {
        Thread.CurrentPrincipal = null;
        // setup app domain / run code in other app domain here
        return ....;
    }).Result;
}
finally
{
    flow.Undo();
}
于 2018-09-02T18:18:26.593 回答