Fix Command Injection in Ktor
Command Injection in Ktor occurs when untrusted input from parameters, headers, or bodies is concatenated into system commands. This yields Remote Code Execution (RCE). Stop using 'Runtime.exec(String)' with user data. It triggers a shell that interprets control characters like semicolons, pipes, and backticks. To secure your app, bypass the shell entirely and use ProcessBuilder with an explicit argument list.
The Vulnerable Pattern
get("/check-host") {
val target = call.parameters["target"]
// VULNERABLE: Direct string concatenation into a shell command
val command = "nslookup $target"
val process = Runtime.getRuntime().exec(command)
val output = process.inputStream.bufferedReader().readText()
call.respondText(output)
}
The Secure Implementation
The vulnerable example is susceptible to payloads like 'google.com; cat /etc/passwd'. Because 'Runtime.exec(String)' invokes a shell to parse the string, the semicolon terminates the first command and executes the second. The secure version uses 'ProcessBuilder' with a List of strings. In this mode, the OS treats the second element strictly as an argument to the 'nslookup' binary, not as a shell command. Even if the input contains shell metacharacters, they are passed as literal text to the target binary, neutralizing the injection vector.
get("/check-host") { val target = call.parameters["target"] ?: return@get call.respond(HttpStatusCode.BadRequest)// 1. Strict Validation: Allow only expected characters (e.g., alphanumeric and dots) if (!target.matches(Regex("^[a-zA-Z0-9.-]+$"))) { return@get call.respond(HttpStatusCode.BadRequest, "Illegal characters detected") } // 2. Secure Execution: Use ProcessBuilder with a List to avoid shell interpretation val process = ProcessBuilder("nslookup", target) .directory(File("/tmp")) .start() val output = process.inputStream.bufferedReader().readText() call.respondText(output)
}
Your Ktor API
might be exposed to Command Injection
74% of Ktor apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.