Command & Path Injection
OS command injection, path traversal, and the principle of never passing user input to the shell
Skills taught: websecurity.command-injection, websecurity.path-traversal, websecurity.shell-escape, websecurity.file-access
OS command injection
Command injection happens when user input is passed to a shell command. The attacker injects shell operators (; | && ||) to run additional commands. Unlike SQL injection (which is limited to the database), command injection gives attackers access to the entire operating system: read any file, create users, download malware, pivot to internal services. It's catastrophic.
import { exec, execFile } from 'child_process';
// VULNERABLE — user input passed to shell
app.post('/convert', (req, res) => {
const filename = req.body.filename; // e.g., 'report.pdf'
// Attack: filename = 'report.pdf; cat /etc/passwd; echo '
// Shell executes: convert report.pdf; cat /etc/passwd; echo output.png
// /etc/passwd is now returned to the attacker
exec(`convert ${filename} output.png`, (err, stdout) => {
res.send(stdout);
});
});
// SAFE APPROACH 1 — execFile (bypasses shell entirely)
app.post('/convert', (req, res) => {
const filename = req.body.filename;
// Validate input first — only allow safe filenames
if (!/^[\w\-]+\.pdf$/.test(filename)) {
return res.status(400).json({ error: 'Invalid filename' });
}
// execFile passes arguments as an array — no shell interpretation
// ';' in the filename becomes a literal argument, not a shell separator
execFile('convert', [filename, 'output.png'], (err, stdout) => {
if (err) return res.status(500).json({ error: 'Conversion failed' });
res.send(stdout);
});
});
// SAFE APPROACH 2 — avoid shell commands entirely
// Use native Node.js libraries instead of shelling out:
// Instead of: exec('ffmpeg -i video.mp4 ...')
// Use: fluent-ffmpeg library
// Instead of: exec('convert image.png ...')
// Use: sharp library
// Instead of: exec('zip archive.zip files/')
// Use: archiver library
// Rule: if there's a native library, use it — no shell needed
Path traversal
import path from 'path';
import fs from 'fs';
// VULNERABLE — user controls file path
app.get('/files/:filename', (req, res) => {
const filename = req.params.filename;
// Attack: filename = '../../etc/passwd'
// Reads: /app/uploads/../../etc/passwd → /etc/passwd
// Returns the system password file!
const filePath = `/app/uploads/${filename}`;
res.sendFile(filePath);
});
// SAFE — resolve and validate the path stays within allowed directory
const UPLOAD_DIR = path.resolve('/app/uploads');
app.get('/files/:filename', (req, res) => {
const filename = req.params.filename;
// path.resolve() handles ../ and symlinks
const requestedPath = path.resolve(UPLOAD_DIR, filename);
// CRITICAL CHECK: does the resolved path start with the allowed directory?
if (!requestedPath.startsWith(UPLOAD_DIR + path.sep)) {
// '../' attack detected — reject
return res.status(403).json({ error: 'Access denied' });
}
// Safe to serve
res.sendFile(requestedPath);
});
// ADDITIONAL: validate filename characters
function isSafeFilename(name: string): boolean {
// Only allow alphanumeric, dash, underscore, dot
// Block: ../, /, \, null bytes, %00
return /^[\w\-\.]+$/.test(name) && !name.includes('..');
}
SHELL METACHARACTERS to watch for in shell-adjacent contexts:
; (command separator)
| (pipe to another command)
&& (run second if first succeeds)
|| (run second if first fails)
$() (command substitution)
`` (backtick command substitution)
> (redirect output to file)
< (read from file)
& (run in background)
* (glob expansion)
? (glob expansion)
! (history expansion in bash)
PATH TRAVERSAL sequences:
../ (parent directory, Unix)
..\\ (parent directory, Windows)
%2e%2e%2f (URL-encoded ../)
%252e%252e (double-encoded ../)
..%c0%af (overlong UTF-8 encoding of /)
NULL BYTE INJECTION:
filename%00.jpg → may be interpreted as 'filename' by some languages
Terminates string in C-based functions while passing extension check
Warning: Never use exec() with user input. Always use execFile() (which takes an array of arguments, bypassing the shell) or, better, a native library that doesn't invoke the OS shell at all. The same rule applies to Python's subprocess.call(shell=True), PHP's exec(), and Ruby's backtick operator. If you must call a shell command with user-derived data, use a proper shell-escaping library (shell-quote in npm) — but prefer eliminating the shell call entirely.
Frequently Asked Questions
Is command injection really common in Node.js apps?
Less common than SQL injection or XSS, but it appears in image conversion, PDF generation, file processing, and any feature that shells out to a system tool. It's especially dangerous in developer tools, admin panels, and CI/CD systems where the attacker may already have some level of access. Severity is typically critical — code execution on the server is the worst outcome in web security.