'How to defend app and system from uploaded C# code

Currently, I have the WEB API that will check uploaded code from the client and run it. It is the platform for testing. For example, there is a test for users:

Create a function with the name Sum. It will sum to integer numbers. Use this template:

public class Class1
{
    //TODO: Create Sum function here
}

When the user uploads his code, WEB API compiles and creates Assembly using roslyn After that, it will run this code and check that function Sum using reflection. For example,

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");
            }
        }

It is working fine, but there is a porblem. When User will upload dangerous code it will cause a lots of problems. For example, if user upload code that cause stackoverflow exception, outofmemory exception, code that deletes some files, format disk, change users password .....

So, How can I defend my system from this kind of problems?



Solution 1:[1]

I would try the following idea if @MickyD's answer is not applicable because .net version things he mentioned, or you do not trust or do not want to learn all the .net cas stuff:

Copy the uploaded code into a container like Docker or virtual machine running on upload service's side. Exec the untrusted code inside the container and retrieve results. Then use the container's capabilities to rollback it to initial state.

Before rollback you can also examine it's state to detect any bad behavior like file changes, registry hacks, etc.

This solution uses considerably more resources than the .net vm way @MickyD mentioned but it is much more safer too because the code running in container wont have any access to the host except what you explicit gave it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cly