flawopen.com/command-injection/Java
Learn how to fix Command Injection (CWE-78) in Java. Side-by-side vulnerable vs secure code examples for ProcessBuilder and Runtime.getRuntime().exec() argument vectors.
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.
// Runtime.exec with string concatenation
public class PingService {
public void ping(String host) throws Exception {
// Attacker input: "127.0.0.1; whoami"
String command = "sh -c ping -c 1 " + host;
Process process = Runtime.getRuntime().exec(command);
}
}
// ProcessBuilder with discrete argument list
public class PingService {
public void ping(String host) throws Exception {
// host is strictly isolated as an argument
List<String> command = List.of("ping", "-c", "1", host);
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
}
}