c#沙盒环境
本文关键字:环境 | 更新日期: 2023-09-27 18:15:36
我正在Visual Studio中做一个小沙箱项目。下面是我的代码:
namespace Andromeda.PCTools
{
public partial class Sandbox : MetroForm
{
private AppDomain sandbox;
public Sandbox()
{
InitializeComponent();
}
private void Sandbox_Load(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Applications|*.exe", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
listBoxItems.Items.Add(ofd.FileName);
}
}
}
private void removeSelectedToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listBoxItems.SelectedItems.Count != 0)
{
while (listBoxItems.SelectedIndex != -1)
{
listBoxItems.Items.RemoveAt(listBoxItems.SelectedIndex);
}
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
AppDomainSetup setup = new AppDomainSetup();
Evidence ev = new Evidence();
//ev.AddHostEvidence(new Zone(SecurityZone.Internet));
PermissionSet internetPS = SecurityManager.GetStandardSandbox(ev);
setup.ApplicationBase = Path.GetFullPath(Application.StartupPath);
//StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();
sandbox = AppDomain.CreateDomain(listBoxItems.SelectedItem.ToString(), ev, setup, ps);
try
{
sandbox.ExecuteAssembly(listBoxItems.SelectedItem.ToString());
btnLoad.Enabled = false;
btnUnload.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show("The following error occurred!'n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnUnload_Click(object sender, EventArgs e)
{
try
{
AppDomain.Unload(sandbox);
btnLoad.Enabled = true;
btnUnload.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show("The following error occurred!'n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
但是我得到以下错误:
抛出异常:'System.Security. 'Andromeda中的安全异常. 4.0.exe("请求类型为‘System.Security.Permissions’的权限。FileIOPermission mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089'失败了。")
您授予沙盒程序集执行权限,但是您还需要向权限集中添加一个FileIOPermission
,从而授予它访问文件系统的权限。试试以下命令:
ps.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
选择如何适当地配置IO权限。在我的例子中,它是不受限制的,但这是一个沙盒。您可以选择将其锁定一点:)根据需要选择合适的构造函数。