Assembly.CreateInstance and Security

I love the idea of ​​using C # to compile code on demand as the basis for a scripting language. I was wondering how I can process the scripts that I execute so that they cannot access the file system, network, etc. Basically, I want limited permissions to run the script.

The steps that I take:

CompilerResults r = CSharpCodeProvider.CompileAssemblyFromSource(source); Assembly a = r.CompiledAssembly; IScript s = a.CreateInstance(...); s.EntryPoint(...); 
+6
source share
2 answers

The recommended approach for this is to execute suspicious code in an isolated appdomain . Several reasons are given at http://blogs.msdn.com/b/shawnfa/archive/2006/04/19/579066.aspx , and more importantly, most other potential approaches are deprecated with .NET 4.0.

+2
source

Edit: ignore this, it is unsafe!

Check out System.Security.Permissions.SecurityPermission (and subclasses of type FileIOPermission ) and this tutorial . If you want to temporarily prevent code from doing unsafe actions, you can use the following expressions:

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

Source: https://habr.com/ru/post/902696/


All Articles