[.net] Need help with permissions on dynamic code

Started by
1 comment, last by Enfekted 19 years, 4 months ago
I'm writing a little application that takes a C# script, compiles it, and then executes it. I'd like to use the CSharpCodeProvider class to handle all parsing and compiling, but it creates a security problem. The CSharpCodeProvider automatically makes the "System" assembly available to the script, which also allows it to include System.IO classes. This could run into problems with the script deleting files. (see example code below) Also, I think the script could access Kernel32 memory functions and cause havok with that as well. I would like to allow the use of some 'System' functions (like the collections), but want to disable anything that would allow a script to damage the computer the script is being run on. Worse case, I'd like disable the 'System' assembly entirly for scripts and only allow the script to access a custom assembly I'll create for collections and anything else the script may need. The answer to this may also lie in the Evidence class, but the documentation on this is sketchy. Anyone have any ideas? Thanks!

CSharpCodeProvider coder = new CSharpCodeProvider();
ICodeCompiler compiler = coder.CreateCompiler();

// Assume source was set by some user
string source = "using System;\n" +
	"namespace MyNamespace {\n" +
	"class MyClass { \n" +
	"public void DoEvil() { System.IO.Directory.Delete( "c:\", true );" +
	"} }";

CompilerResults results = compiler.CompileAssemblyFromSource( new CompilerParameters(), source );

if ( results.Errors.Count == 0 )
{
	object BadObj = results.CompiledAssembly.CreateInstance( "MyNamespace.MyClass" );
	(string)BadObj.GetType().InvokeMember( "DoEvil", BindingFlags.InvokeMethod, null, BadObj, new object[] { } );
}

Advertisement
Hiya!
I've seen cool stuff on this before - you need to sandbox the compiler and therefore the generated code, read this:
http://www.gamedev.net/community/forums/topic.asp?topic_id=264462

EDIT: did html wrong and it made my link into a clickie!
Thanks DrGUI, that's a huge help!

This topic is closed to new replies.

Advertisement