4

我正在尝试运行用户在我的服务器中上传的不受信任的代码。我的用户想要编写在服务器上执行的简单函数,如下所示:

public class HelloWorldPlugin
{
    public string GetResult(string input)
    {
        //return System.IO.Directory.GetCurrentDirectory();
        return "Hello " + input;
    }
}

更新:由于资源需求,我不允许使用 docker 或类似的隔离解决方案。

步骤是:

  • 定义允许的程序集和类型

  • 编译用户代码

  • 在单独的AssemblyLoadContext中加载已编译的程序集

  • 执行用户功能

  • 处置资源

我简化了我的代码如下:

public class PluginLoader : IDisposable
{
    private AssemblyLoadContext assemblyLoadContext;
    private Assembly assembly;
    private byte[] bytes;

    public void Load(string id, string code, IEnumerable<string> allowedAssemblyNames, IEnumerable<Type> allowedTypes)
    {
        var _references = new List<MetadataReference>();
        foreach (var assemblyName in allowedAssemblyNames)
        {
            _references.Add(MetadataReference.CreateFromFile(RuntimeEnvironment.GetRuntimeDirectory() + assemblyName + ".dll"));
        }

        foreach (var type in allowedTypes)
        {
            _references.Add(MetadataReference.CreateFromFile(type.Assembly.Location));
        }

        var options = new CSharpCompilationOptions(
            OutputKind.DynamicallyLinkedLibrary,
            reportSuppressedDiagnostics: true,
            optimizationLevel: OptimizationLevel.Release,
            generalDiagnosticOption: ReportDiagnostic.Error,
            allowUnsafe: false);

        var syntaxTree = CSharpSyntaxTree.ParseText(code, options: new CSharpParseOptions(LanguageVersion.Latest, kind: SourceCodeKind.Regular));
        var compilation = CSharpCompilation.Create(id, new[] { syntaxTree }, _references, options);

        assemblyLoadContext = new AssemblyLoadContext(id, true);

        using (var ms = new MemoryStream())
        {
            var result = compilation.Emit(ms);
            if (result.Success)
            {
                ms.Seek(0, SeekOrigin.Begin);
                bytes = ms.ToArray();
                ms.Seek(0, SeekOrigin.Begin);
                assembly = assemblyLoadContext.LoadFromStream(ms);
            }
        }

    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public string Run(string typeName, string methodName, string input)
    {
        var instance = assembly.CreateInstance(typeName);
        MethodInfo theMethod = instance.GetType().GetMethod(methodName);
        return (string) theMethod.Invoke(instance, new[] { input });
    }

    public void Dispose()
    {
        assemblyLoadContext.Unload();
        assemblyLoadContext = null;
        bytes = null;
        assembly = null;
    }
}

测试代码是:

    var allowedAssemblies = new[] { "System", "System.Linq", "System.Linq.Expressions" };
    var allowedTypes = new Type[] { typeof(object) };
    string result;

    using (var loader = new PluginLoader())
    {
        loader.Load("MyCustomPlugin", code, allowedAssemblies, allowedTypes);
        result= loader.Run("HelloWorldPlugin", "GetResult", "World!");
    }

    Console.WriteLine(result);
    Console.ReadLine();

我知道用户可能可以访问 IO、网络……这是巨大的威胁。我尝试使用System.IO.Directory.GetCurrentDirectory():因为我没有将 System.IO 程序集添加到 allowedAssemblies 它在编译部分引发异常。我还尝试通过反射获取当前用户身份和一些基本作品,所有这些作品都引发了异常。

如果我在编译之前限制允许的引用,用户如何执行危险代码来访问资源?除了连续循环执行(while True loop)之外还有哪些威胁?

4

0 回答 0