Skip to content

Improper control of generation of code ('Code Injection')

Description

The application executes an argument using a `ScriptEngine`'s `eval` method, which may allow for direct OS commands to be executed. Never pass user-supplied input directly to the `eval` function. If possible, hardcode all JavaScript code or use a lookup table to resolve user input to known values. If none of these techniques are possible, use `javax.script.Bindings` to pass input to the script engine.

Examples

Insecure Code

java
ScriptEngine engine = new ScriptEngineManager().getEngineByName("ECMAScript");
engine.eval("var greeting='Hello '+userInput; greeting;", new String(userInput));

Secure Code

java
ScriptEngine engine = new ScriptEngineManager().getEngineByName("ECMAScript");
Bindings bindings = engine.createBindings();
bindings.put("userInput", new String(userInput));
engine.eval("var greeting='Hello '+userInput; greeting;", bindings);

Remediation

Use `javax.script.Bindings` to pass input to the script engine, forcing the values to be String, and execute the script with the bindings.

Rule Details

FieldValue
IDCODE-0719
CategoryInjection
SeverityCRITICAL
CWECWE-94
ConfidenceHIGH
ImpactHIGH
LikelihoodMEDIUM
ExploitabilityEASY
TagsCode Injection, Script Engine
OWASPA1:2017-Injection, A03:2021-Injection