4

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; }
}
  • who are the users? are they going to learn c#? – Alex Buyny Feb 13 '19 at 23:39
  • The users would be analysts who'd be using it to write simple functions in a general syntax (if/else, add, subtract, multiply, etc) that would then be run over a large number of inputs. – matt.rothmeyer Feb 15 '19 at 22:05
  • This sounds like a hard problem to solve. I'd consider making functions AWS lambda or similar, and making some admin UI in you application to create those lambdas if needed. The functions will call your application's API or data store and get only the values that you want exposed. You will be able to limit memory / monitor things far easier as well. – Alex Buyny Feb 17 '19 at 18:25

0 Answers0