Fix Command Injection in Polka
Polka's minimalist design puts security squarely on the developer. Command injection occurs when untrusted input from 'req.params', 'req.query', or 'req.body' is passed to system execution functions like 'child_process.exec' without sanitization. If you're concatenating strings into a shell, you're giving attackers an arbitrary code execution (RCE) primitive.
The Vulnerable Pattern
const polka = require('polka'); const { exec } = require('child_process');
polka() .get(‘/network/lookup’, (req, res) => { const { domain } = req.query; // VULNERABLE: Direct string concatenation into a shell context exec(nslookup ${domain}, (err, stdout, stderr) => { res.end(stdout || stderr); }); }) .listen(3000);
The Secure Implementation
The vulnerability exists because 'exec' spawns a shell (/bin/sh or cmd.exe) to run the command, interpreting characters like ';', '&', and '|'. An attacker providing 'google.com; cat /etc/passwd' would trigger both commands. To fix this: First, use 'spawn' instead of 'exec' because 'spawn' passes arguments directly to the binary's argv array, bypassing shell evaluation. Second, always implement a strict regex whitelist to ensure the input matches the expected format before it ever touches a sub-process.
const polka = require('polka'); const { spawn } = require('child_process');polka() .get(‘/network/lookup’, (req, res) => { const { domain } = req.query;
// 1. Strict Input Validation (Whitelist) if (!/^[a-zA-Z0-9.-]+$/.test(domain)) { res.statusCode = 400; return res.end('Invalid input'); } // 2. Use spawn with an arguments array (prevents shell interpretation) const child = spawn('nslookup', [domain]); let output = ''; child.stdout.on('data', (data) => { output += data; }); child.on('close', () => res.end(output));
}) .listen(3000);
Your Polka API
might be exposed to Command Injection
74% of Polka 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.