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.
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}
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}