My client wants to add the ability for users to define small scripts that can be used to run various calculations in a pre-existing web application. Currently, we're exploring using CSharpScripts in Microsoft.CodeAnalysis.Scripting.CSharp to dynamically compile and execute user functions.
I'd like the ability to sandbox these scripts. Specifically, I'd like to place limits on the resources (memory, etc) a script can use, as well as limit what libraries or values a script can access (eg I don't want a user making web service calls in their script). I want to avoid the case where a user writes code that negatively impacts the rest of the application.
I've included some example code below
private static Script<double> GetCompiledScript(string userFunction)
{
var options = ScriptOptions.Default.AddReferences(References).AddImports(Imports);
var script = CSharpScript.Create<double>(expression, options, typeof(Globals));
script.Compile();
return script;
}
public static String[] Imports => new[]
{
"System",
"System.Linq",
"System.Collections.Generic"
};
public static Assembly[] References => new[]
{
typeof(System.Object).GetTypeInfo().Assembly,
typeof(System.Linq.Enumerable).GetTypeInfo().Assembly,
};
public class Globals
{
public Dictionary<string, double> vars { get; set; }
}