GuardAPI Logo
GuardAPI

Fix Command Injection in Express

Command injection in Node.js/Express occurs when an application passes unvalidated user input to a system shell. This allows an attacker to execute arbitrary system commands with the privileges of the Node process. If you are using child_process.exec, you are likely vulnerable.

The Vulnerable Pattern

const { exec } = require('child_process');

app.get(‘/network/ping’, (req, res) => { const { target } = req.query; // VULNERABLE: String concatenation into a shell command exec(ping -c 4 ${target}, (error, stdout, stderr) => { if (error) return res.status(500).send(error.message); res.send(stdout); }); });

The Secure Implementation

The vulnerability lies in 'child_process.exec', which spawns a shell (/bin/sh or cmd.exe) to execute the command string. An attacker can inject shell metacharacters like ';', '&&', or '|' (e.g., 'google.com; cat /etc/passwd'). To fix this, use 'execFile' or 'spawn'. These functions do not spawn a shell by default; the command and its arguments are passed directly to the OS as a list of strings, neutralizing any attempt to chain commands. Additionally, always implement strict input validation using a whitelist of allowed characters.

const { execFile } = require('child_process');

app.get(‘/network/ping’, (req, res) => { const { target } = req.query;

// 1. Input Validation: Only allow valid IP/Hostname patterns if (!/^[a-zA-Z0-9.-]+$/.test(target)) { return res.status(400).send(‘Invalid target’); }

// 2. Use execFile: It bypasses the shell and executes the binary directly // Arguments are passed as an array, preventing shell metacharacter injection execFile(‘/bin/ping’, [‘-c’, ‘4’, target], (error, stdout, stderr) => { if (error) return res.status(500).send(error.message); res.send(stdout); }); });

System Alert • ID: 5750
Target: Express API
Potential Vulnerability

Your Express API might be exposed to Command Injection

74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.