I am using Microsoft.CSharp.CSharpCodeProvider to programmatically compile an assembly & run some functions from the external .cs file.
But is there a way to forbid those functions from making any changes to the file system and etc. (I need to run them in some kind of a sandbox)?
I was thinking of adding "-nostdlib" option to the CompilerParameters so the resulting assembly will not be able to access System.IO.File and other classes. But I still need System.Object, System.ValueType, etc.
Right now I am getting these errors:
error CS0518: The predefined type `System.Object' is not defined or imported
error CS0518: The predefined type `System.ValueType' is not defined or imported
error CS0518: The predefined type `System.Attribute' is not defined or imported
error CS0518: The predefined type `System.Int32' is not defined or imported
... (too many of them)
How can I add those classes without those which can seriously harm the system (like System.IO.File, System.IO.Directory, System.Net.(something), System.Threading.(something)? )
Or, maybe there are easier ways? Thank you.
By importing the base
Systemtypes such asSystem.ObjectorSystem.Int32you import everything contained along in mscorlib.dll such asSystem.IO.Stream. You can't simply configure the import to not include some types in the assembly. As far as I know, your only way is to build your own stdlib - or build your own compiler but that's another story.Hopefully thanks to the Mono project it should not be too difficult. You can pull the latest sources on GitHub. More specifically, have a look at the corlib folder. From that simply remove everything you don't want your users to use. Finally adding your custom
mscorlib.dllto theReferencedAssembliesand setting/nostdlibshould be enough.If you like being hardcore, you can try to achieve that using Cecil. Using this wonderful library you can easily lookup for types, remove them and save the patched assembly.
Another way around would be to inspect your loaded assembly for blacklisted types prior it's execution. It's not so trivial but Cecil can probably help. Have a look at this question : .NET Reflection: Find used types
Whatever you choose, good luck and have fun :)