Skip to content

Dynamic Code Execution

What does this mean ?

Any externally given values used to create the code should be neutralized by applications that execute code dynamically. If this is not done, an attacker may be able to run arbitrary code.

What can happen ?

This might allow for a variety of dangerous attacks, such as accessing/modifying critical information or gaining complete system access.

Recommendation

Whitelisting of permissible values or casting to safe types should be used as a mitigating approach.

Sample Code

Vulnerable :

protected void uSafe1(HttpServletRequest req, HttpServletResponse resp) throws ScriptException {
    String code = req.getParameter("code");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval(code);
}

protected void uSafe2(HttpServletRequest req, HttpServletResponse resp) throws ScriptException {
    Test test = new Test();
    String a = test.testACase(req);
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval(a);
}

Non Vulnerable :

protected void safe1(HttpServletRequest req, HttpServletResponse resp) throws IOException, ScriptException {
    String code = req.getParameter("code");

    // Match the code against a whitelist
    if (!whiteList.contains(code))
        throw new IOException();

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval(code);
}

protected void safe2(HttpServletRequest req, HttpServletResponse resp) throws ScriptException {
    Test test = new Test();
    String a = test.testACase2(req);

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval(a);
}

References