Fix Command Injection in Nuxt
Command injection in Nuxt (Nitro) occurs when untrusted user input is passed directly to system-level execution sinks like 'child_process.exec'. This allows an attacker to break out of the intended command context and execute arbitrary OS commands with the permissions of the Node.js process. In a Nuxt SSR environment, this results in full server compromise.
The Vulnerable Pattern
// server/api/diagnostics.ts import { exec } from 'child_process';export default defineEventHandler(async (event) => { const { domain } = getQuery(event);
// CRITICAL VULNERABILITY: User input is concatenated into a shell command return new Promise((resolve) => { exec(nslookup ${domain}, (error, stdout) => { resolve({ output: stdout }); }); }); });
The Secure Implementation
The vulnerable example uses 'exec', which invokes a system shell (/bin/sh or cmd.exe) to parse the string. An attacker could provide a payload like 'google.com; cat /etc/passwd', leading to data exfiltration. The secure version replaces 'exec' with 'spawn'. Unlike 'exec', 'spawn' does not spin up a shell by default; it treats the second argument as a literal array of strings, ensuring the input is never interpreted as a command separator or operator. Additionally, we implement a regex allow-list to ensure the input conforms to expected patterns before it ever touches the process layer.
// server/api/diagnostics.ts import { spawn } from 'child_process';export default defineEventHandler(async (event) => { const { domain } = getQuery(event);
// 1. Strict Input Validation (Allow-listing) if (typeof domain !== ‘string’ || !/^[a-zA-Z0-9.-]+$/.test(domain)) { throw createError({ statusCode: 400, statusMessage: ‘Invalid Domain Format’ }); }
// 2. Use spawn() with an arguments array to prevent shell interpretation return new Promise((resolve) => { const child = spawn(‘nslookup’, [domain]); let output = ”;
child.stdout.on('data', (data) => { output += data; }); child.on('close', () => resolve({ output }));
}); });
Your Nuxt API
might be exposed to Command Injection
74% of Nuxt 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.