Server-side JavaScript injection
Description
This vulnerability occurs when user-supplied input is incorporated into JavaScript code that is dynamically evaluated on the server side (typically in Node.js environments). When user input is not properly validated or sanitized before being passed to evaluation functions like eval(), Function(), or similar constructs, attackers can inject and execute arbitrary JavaScript code on the server. This is particularly dangerous in server-side JavaScript environments where code execution has direct access to system resources, databases, and sensitive application logic.
Remediation
To remediate this vulnerability, follow these steps:
1. Eliminate dynamic code evaluation: Remove all uses of eval(), Function(), and similar constructs that execute strings as code. Refactor your code to use safer alternatives.
2. For JSON parsing, use safe methods:
// Unsafe - DO NOT USE
var data = eval('(' + userInput + ')');
// Safe alternative
var data = JSON.parse(userInput);3. Validate and sanitize all user input: Implement strict input validation using allowlists for expected values, data types, and formats. Reject any input that doesn't conform to expected patterns.
4. Use parameterized approaches: Instead of concatenating user input into code strings, use data structures and function parameters:
// Unsafe
eval('processData("' + userInput + '")');
// Safe
processData(userInput);5. Apply the principle of least privilege: Run your Node.js application with minimal necessary permissions to limit the impact of potential code execution.