Fix Command Injection in Javalin
Command Injection in Javalin occurs when untrusted input from request contexts (ctx) is passed directly to system shells. This typically involves using `Runtime.getRuntime().exec()` with string concatenation, allowing an attacker to append malicious commands (e.g., `; rm -rf /`) to legitimate parameters, resulting in Remote Code Execution (RCE).
The Vulnerable Pattern
import io.javalin.Javalin; import java.io.*;
public class App { public static void main(String[] args) { Javalin app = Javalin.create().start(8080); app.get(“/lookup”, ctx -> { String domain = ctx.queryParam(“domain”); // VULNERABLE: Direct concatenation into a shell command Process p = Runtime.getRuntime().exec(“nslookup ” + domain); InputStream is = p.getInputStream(); ctx.result(new String(is.readAllBytes())); }); } }
The Secure Implementation
To fix command injection, you must break the shell's ability to interpret metacharacters. First, avoid `Runtime.exec(String)` which triggers a shell. Instead, use `ProcessBuilder` and pass arguments as a `List
import io.javalin.Javalin; import java.util.regex.Pattern; import java.util.List;public class App { private static final Pattern ALLOWED_CHARS = Pattern.compile(”^[a-zA-Z0-9.-]+$”);
public static void main(String[] args) { Javalin app = Javalin.create().start(8080); app.get("/lookup", ctx -> { String domain = ctx.queryParam("domain"); // 1. Input Validation: Only allow known safe characters if (domain == null || !ALLOWED_CHARS.matcher(domain).matches()) { ctx.status(400).result("Illegal input detected."); return; } // 2. Parameterization: Use ProcessBuilder with a list of arguments // This avoids shell interpolation entirely ProcessBuilder pb = new ProcessBuilder("nslookup", domain); Process p = pb.start(); ctx.result(new String(p.getInputStream().readAllBytes())); }); }
}
Your Javalin API
might be exposed to Command Injection
74% of Javalin 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.