如何保护应用程序和系统免受上传的c#代码



目前,我有WEB API,将检查从客户端上传的代码并运行它。它是测试的平台。例如,有一个针对用户的测试:

Create a function with the name Sum. It will sum to integer numbers. Use this template:
public class Class1
{
//TODO: Create Sum function here
}

当用户上传他的代码时,WEB API使用roslyn编译并创建Assembly之后,它将运行这段代码并使用反射检查函数Sum。例如,

void CheckFunctionSumm(Assembly assemblyCompiledFromUsersCode)
{
var classFromAssembly = assemblyCompiledFromUsersCode.GetType("Class1");
if (classFromAssembly != null)
{
var method = classFromAssembly.GetMethod("Sum");
if (method != null)
{
var classInstanse = Activator.CreateInstance(classFromAssembly);
int? result = method.Invoke(classInstanse, new object[] { 10, 20 }) as int?;
if (result != 30)
{
throw new Exception("Function is not correct");
}
}
}
else
{
throw new Exception("Class1 is missing");
}
}

工作正常,但是有一个问题。当用户上传危险的代码时,会导致很多问题。例如用户上传的代码会导致stackoverflow异常、outofmemory异常、删除部分文件的代码、格式化磁盘、修改用户密码.....

那么,我该如何保护我的系统不受这种问题的影响呢?

如果@MickyD的答案不适用,因为他提到的。net版本的事情,或者你不相信或不想学习所有。net cas的东西,我会尝试以下想法:

将上传的代码复制到容器中,如Docker或运行在上传服务端的虚拟机。执行容器内的不受信任代码并检索结果。然后使用容器的功能将其回滚到初始状态。

在回滚之前,您还可以检查它的状态,以检测任何不良行为,如文件更改,注册表攻击等。

这个解决方案比@MickyD提到的。net vm方式使用更多的资源,但它也更安全,因为在容器中运行的代码不会访问主机,除非你显式地给它。

最新更新