简体   繁体   中英

Assembly.CreateInstance and security

I'm toying around with the idea of using C#'s ability to compile code on-demand as the basis of a scripting language. I was wondering, how can I sandbox the scripts that I am executing so that they cannot access the file system, network, etc. Basically, I want restricted permissions on the script being run.

Steps that I take:

CompilerResults r = CSharpCodeProvider.CompileAssemblyFromSource(source);

Assembly a = r.CompiledAssembly;

IScript s = a.CreateInstance(...);

s.EntryPoint(...);

The recommended approach for this is to execute the suspect code in a sandboxed appdomain . Several reasons are given at http://blogs.msdn.com/b/shawnfa/archive/2006/04/19/579066.aspx , and an even more important one is that most of the other potential approaches are deprecated as of .NET 4.0.

Edit: disregard that, it's not safe!

Check out System.Security.Permissions.SecurityPermission (and subclasses like FileIOPermission ) and this tutorial . If you want to temporary deny code from doing unsafe actions, you can use statements like this:

NamedPermissionSet ps = new NamedPermissionSet("Nothing");
ps.Deny();
CallYourScriptHere();
CodeAccessPermission.RevertAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM