flawopen.com/command-injection/Kotlin
Learn how to fix Command Injection (CWE-78) in Kotlin. Side-by-side vulnerable vs secure code examples for ProcessBuilder with immutable list arguments.
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.
// String template with Runtime.exec
fun checkHost(host: String) {
// Input: "8.8.8.8; id"
val cmd = "ping -c 1 $host"
Runtime.getRuntime().exec(arrayOf("sh", "-c", cmd))
}
// ProcessBuilder with discrete list of arguments
fun checkHost(host: String) {
// host is isolated as a single argument
val command = listOf("ping", "-c", "1", host)
ProcessBuilder(command).start()
}