Command Injection — Security

Apa itu Command Injection? Command Injection terjadi ketika aplikasi menjalankan perintah sistem operasi dengan menyertakan input pengguna tanpa sanitasi. Penye

Apa itu Command Injection?

Command Injection terjadi ketika aplikasi menjalankan perintah sistem operasi dengan menyertakan input pengguna tanpa sanitasi. Penyerang bisa menyisipkan perintah tambahan yang dieksekusi oleh server.

Contoh Vulnerability

// Node.js — VULNERABLE
const { exec } = require("child_process");
app.get("/ping", (req, res) => {
    const host = req.query.host;
    exec(`ping -c 3 ${host}`, (err, stdout) => {
        res.send(stdout);
    });
});

// Serangan:
// GET /ping?host=google.com; cat /etc/passwd
// Perintah yang dieksekusi: ping -c 3 google.com; cat /etc/passwd

Operator Shell yang Berbahaya

Cara Mencegah Command Injection

1. Hindari Penggunaan Shell Commands

Gunakan library atau API native daripada menjalankan perintah shell:

// Buruk: menggunakan shell command
exec(`convert ${inputFile} ${outputFile}`);

// Baik: menggunakan library
const sharp = require("sharp");
await sharp(inputFile).toFile(outputFile);

2. Gunakan execFile sebagai Pengganti exec

// Buruk: exec menjalankan melalui shell
exec(`ping -c 3 ${host}`);

// Baik: execFile tidak melalui shell, argumen terpisah
const { execFile } = require("child_process");
execFile("ping", ["-c", "3", host], (err, stdout) => {
    res.send(stdout);
});

3. Whitelist Input

// Validasi input terhadap whitelist
const allowedHosts = ["google.com", "cloudflare.com"];
if (!allowedHosts.includes(host)) {
    return res.status(400).send("Host not allowed");
}

4. Escape Input

Jika harus menggunakan shell, escape input dengan benar. Di PHP, gunakan escapeshellarg() untuk meng-escape argumen shell:

// PHP: escape shell argument
$host = escapeshellarg($userInput);
$output = shell_exec("ping -c 3 " . $host);

Namun tetap lebih baik menghindari shell commands sepenuhnya.

Yang akan kamu pelajari