Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities:

It is dangerous to let external sources either:

This rule marks for review each occurence of such dynamic code execution. The goal is to guide security code reviews.

Ask Yourself Whether

You are at risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Regarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the code in a sandboxed environment. Use jails, firewalls and whatever means your operating system and programming language provide (example: Security Managers in java, iframes and same-origin policy for javascript in a web browser).

Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way.

As for the use of reflection, it should be strictly controlled as it can lead to many vulnerabilities. Never let an untrusted source decide what code to run. If you have to do it anyway, create a list of allowed code and choose among this list.

Questionable Code Example

public class Reflection {

    public static void run(java.lang.ClassLoader loader, String className, String methodName, String fieldName,
            Class<?> parameterTypes)
            throws NoSuchMethodException, SecurityException, ClassNotFoundException, NoSuchFieldException {

        Class<?> clazz = Class.forName(className); // Questionable
        clazz.getMethod(methodName, parameterTypes); // Questionable
        clazz.getMethods(); // Questionable
        clazz.getField(fieldName); // Questionable
        clazz.getFields(); // Questionable
        clazz.getDeclaredField(fieldName); // Questionable
        clazz.getDeclaredFields(); // Questionable
        clazz.getDeclaredClasses(); // Questionable

        loader.loadClass(className); // Questionable
    }
}

Exceptions

Calling reflection methods with a hard-coded type name, method name or field name will not raise an issue.

See