Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

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}