Security
Command Injection in Java: How to Prevent It
Command injection in Java occurs when user input is passed to Runtime.exec() with shell involvement. An attacker can inject shell metacharacters to execute arbitrary commands.
❌ Vulnerable Runtime.exec()
public String pingHost(String hostname) throws IOException {
Process p = Runtime.getRuntime().exec(
new String[]{"sh", "-c", "ping -c 1 " + hostname}
);
return readOutput(p);
}✅ Safe with ProcessBuilder
public String pingHost(String hostname) throws IOException {
if (!hostname.matches('[a-zA-Z0-9.\-]+')) {
throw new IllegalArgumentException('Invalid hostname');
}
ProcessBuilder pb = new ProcessBuilder('ping', '-c', '1', hostname);
pb.redirectErrorStream(true);
return readOutput(pb.start());
}💡
Pro tip: Never use Runtime.exec(String) — the single-string form invokes a shell. Always use the array form or ProcessBuilder with separate arguments.
Paste this code into LearnCodeGuide
Detect Java vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Java Code →