Fix Command Injection in Fastify
Command Injection in Fastify applications occurs when untrusted user input is concatenated into system shell commands. This creates a Critical RCE (Remote Code Execution) vector. In Node.js, functions like `child_process.exec` spawn a shell by default, making them extremely dangerous if input isn't strictly controlled. To secure the application, you must avoid shell execution and use parameterized APIs or strict allow-listing.
The Vulnerable Pattern
const { exec } = require('child_process');
fastify.get(‘/lookup’, async (request, reply) => { const { domain } = request.query; // VULNERABLE: Direct concatenation into a shell-spawning function exec(nslookup ${domain}, (error, stdout, stderr) => { if (error) return reply.send(error); reply.send({ result: stdout }); }); });
The Secure Implementation
The vulnerable example uses `exec`, which invokes `/bin/sh` (or `cmd.exe`), allowing an attacker to append commands using shell metacharacters like `;`, `&`, or `|` (e.g., `?domain=google.com; cat /etc/passwd`). The secure implementation replaces `exec` with `execFile`. Unlike `exec`, `execFile` executes the binary directly without a shell intermediary, treating the entire input string as a literal argument rather than a command to be parsed. Additionally, strict regex validation is applied as a Defense-in-Depth measure to ensure the input conforms to expected patterns before reaching the system layer.
const { execFile } = require('child_process');fastify.get(‘/lookup’, async (request, reply) => { const { domain } = request.query;
// 1. Strict Input Validation (Regex for domain format) if (!/^[a-zA-Z0-9.-]+$/.test(domain)) { return reply.code(400).send({ error: ‘Invalid domain format’ }); }
// 2. SECURE: Use execFile which does NOT spawn a shell // Arguments are passed as an array, preventing shell metacharacter injection execFile(‘nslookup’, [domain], (error, stdout, stderr) => { if (error) return reply.send({ error: ‘Lookup failed’ }); reply.send({ result: stdout }); }); });
Your Fastify API
might be exposed to Command Injection
74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.