目标:我需要在权限非常有限的 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
...
...
...
} …Run Code Online (Sandbox Code Playgroud)