GuardAPI Logo
GuardAPI

Fix Command Injection in Sails

Command injection in Sails.js occurs when untrusted input flows into shell execution sinks like child_process.exec. Attackers leverage shell metacharacters to execute arbitrary system commands with the privileges of the Node.js process. To kill this bug, you must stop using shell interpretation for user-supplied data.

The Vulnerable Pattern

// api/controllers/ReportController.js
const { exec } = require('child_process');

module.exports = { generate: async function(req, res) { const reportId = req.param(‘id’); // VULNERABLE: String interpolation into exec() spawns a shell // Attack payload: ?id=123; cat /etc/passwd exec(generate-report --id ${reportId}, (err, stdout, stderr) => { if (err) return res.serverError(err); return res.ok(stdout); }); } };

The Secure Implementation

The vulnerability stems from child_process.exec, which invokes /bin/sh (or cmd.exe) to parse the command string. This allows shell metacharacters (;, |, &, `) to be interpreted as command separators. The fix replaces exec with child_process.execFile or spawn. These methods execute the binary directly and pass the arguments as an array to the OS execve() system call, preventing the shell from ever seeing or interpreting the payload. Additionally, strict regex validation ensures input conforms to expected formats before it reaches the sink.

// api/controllers/ReportController.js
const { execFile } = require('child_process');

module.exports = { generate: async function(req, res) { const reportId = req.param(‘id’);

// 1. Validate input strictly
if (!/^[0-9]+$/.test(reportId)) {
  return res.badRequest('Invalid ID format');
}

// 2. SECURE: execFile bypasses the shell and treats arguments as literal strings
execFile('generate-report', ['--id', reportId], (err, stdout, stderr) => {
  if (err) return res.serverError(err);
  return res.ok(stdout);
});

} };

System Alert • ID: 6969
Target: Sails API
Potential Vulnerability

Your Sails API might be exposed to Command Injection

74% of Sails 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.