Unsanitized input is run as code Critical

Running scripts generated from unsanitized inputs (for example, evaluating expressions that include user-provided strings) can lead to malicious behavior and inadvertently running code remotely.

Detector ID
java/code-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public void evaluateJavaScriptNoncompliant(HttpServletRequest request) throws ScriptException {
2    final String parameter = request.getParameter("parameter");
3    ScriptEngineManager manager = new ScriptEngineManager();
4    ScriptEngine engine = manager.getEngineByName("JavaScript");
5    // Noncompliant: user-supplied parameter evaluated as a script.
6    engine.eval(parameter);
7}

Compliant example

1public void evaluateJavaScriptCompliant(HttpServletRequest request) throws ScriptException {
2    final String parameter = request.getParameter("parameter");
3    ScriptEngineManager manager = new ScriptEngineManager();
4    ScriptEngine engine = manager.getEngineByName("JavaScript");
5    // Compliant: user-supplied parameter must be in allow-list to be evaluated.
6    if (!parameter.matches("[\\w]+")) {
7        // String does not match allow-listed characters
8        throw new IllegalArgumentException();
9    }
10    engine.eval(parameter);
11}