flawopen.com/Command Injection/Kotlin

Command Injection in Kotlin

Critical CWE-78 Draft — pending review
ELI5

Imagine asking someone to mail a package. If they let the sender write 'Deliver to Bob AND rob the bank' on the label and the delivery person does both, that is command injection.

Key terms on this page
ProcessBuilder
The idiomatic Kotlin/JVM API for process execution, passing arguments as a List<String> without a shell.
Runtime.getRuntime().exec()
Legacy Java/Kotlin API prone to command injection when combined with string templates.

What's happening

In Kotlin applications (Ktor, Spring Boot with Kotlin, or Android), string templates ("cmd $userInput") passed to Runtime.getRuntime().exec() cause command injection.

Real-world impact

Android root utilities and backend Ktor services have suffered privilege escalation when executing su commands or system utilities with unvalidated intent extras.

Common Vulnerabilities and Exposures (CVE) database.

Vulnerable vs. fixed

VULNERABLE
// 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))
}
FIXED
// 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()
}

Why the fix works

ProcessBuilder passes the command and its arguments as discrete strings to the kernel, preventing shell interpretation.

Gotchas

Android su root execution

Executing su -c "$command" in rooted Android environments re-introduces full shell command injection. Always parameterize and restrict root access.

Common misconceptions

"Kotlin null safety prevents injection"

Null safety ensures variables are non-null; it does not check if the non-null string contains malicious shell characters.

How to check if you're affected

grep -rn "Runtime.getRuntime().exec" --include="*.kt" .
Run detekt with security rulesets in your Gradle build.

Prevention checklist

FAQ

Is ProcessBuilder available on Android?

Yes, java.lang.ProcessBuilder is supported on all Android API levels.

References

View in: Python JavaScript Go Java PHP C# Ruby C/C++ Rust Kotlin Swift Solidity (N/A)
Also see: SQL Injection XSS Path Traversal Insecure Deserialization