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(...);
You can sign an assembly in two different but complementary ways: with a strong name or by using SignTool.exe (Sign Tool). Signing an assembly with a strong name adds public key encryption to the file containing the assembly manifest.
Using Strong Names The primary way to protect your assemblies from attack is to attach a strong name. Strong names are pairs of keys (strings of numbers)—one private and one public. The private key is held inside the assembly and is inaccessible.
The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.
C# Assembly is a standard library developed for . NET. Common Language Runtime, CLR, MSIL, Microsoft Intermediate Language, Just In Time Compilers, JIT, Framework Class Library, FCL, Common Language Specification, CLS, Common Type System, CTS, Garbage Collector, GC.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With