Do not use eval()
ID |
javascript.no_use_eval |
Severity |
low |
Resource |
Risky Values |
Language |
JavaScript |
Tags |
CWE:95, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1 |
Description
Avoid dynamic evaluation of code, such as eval(code)
.
If the user has control over evaluated code (because the code is concatenated with user data), this leads to 'script injection' vulnerabilities, which could end in well-known security attacks.
Rationale
In modern applications it is common to use eval() when converting a JSON-encoded value to retrieve a JavaScript object, but it is a terrible idea from a security perspective, unless it is performed with proper checks against potential misuse.
A better way to do this is with JSON.parse()
for parsing JSON and not evaluating it directly as a JSON object. Otherwise, an attacker may craft a payload that will execute arbitrary JavaScript code.
This detector will report any usage of the eval() function.
The following is an example of a use of eval():
var handleProduct = function(o) {
// FLAW - do no deserialize the response that way !
let productData = eval('(' + o.responseText + ')');
render(productData);
}
Using eval() to parse JSON strings is unsafe and can lead to security vulnerabilities, such as code injection.
Remediation
Replace the call to eval() with a more specific function, such as JSON parser, or a safer deserializer.
In case you need dynamic code execution, limit the options available to the user. For example, the user input could be used to choose from a fixed list of functions.
To fix the previous example:
var handleProduct = function(o) {
// FIXED
let productData = JSON.parse(o.responseText);
render(productData);
}
A much safer approach is to use JSON.parse()
, which is specifically designed for parsing JSON strings.
References
-
CWE-95 : Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection').
-
OWASP Top 10 2021 - A03 : Injection.
-
OWASP Code Injection explained.