GuardAPI Logo
GuardAPI

Fix Command Injection in Spring Boot

Command injection remains a critical RCE vector in Spring Boot applications. It occurs when untrusted user input is concatenated into system commands executed via Runtime.exec() or ProcessBuilder. To mitigate this, you must treat OS commands as APIs with distinct arguments, never as raw strings to be interpreted by a shell.

The Vulnerable Pattern

@GetMapping("/debug/ping")
public String ping(@RequestParam String ip) throws IOException {
    // CRITICAL VULNERABILITY: Input concatenation allows shell metacharacters
    // Example payload: ?ip=127.0.0.1;cat+/etc/passwd
    Process process = Runtime.getRuntime().exec("ping -c 1 " + ip);
    return new String(process.getInputStream().readAllBytes());
}

The Secure Implementation

The vulnerability stems from the shell's ability to chain commands. When using Runtime.exec(String), the JVM attempts to tokenize the string, but it doesn't adequately sanitize shell-specific characters. By switching to ProcessBuilder(List), each element in the list is treated as a literal argument passed directly to the OS's execve() system call, bypassing shell evaluation entirely. For maximum security, replace OS calls with native Java APIs (e.g., java.net.InetAddress) whenever possible.

@GetMapping("/debug/ping")
public String ping(@RequestParam String ip) throws IOException {
    // MITIGATION: Use ProcessBuilder with a List of arguments.
    // This prevents shell interpretation of metacharacters like ';', '&', or '|'.
    ProcessBuilder pb = new ProcessBuilder("ping", "-c", "1", ip);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    return new String(process.getInputStream().readAllBytes());
}
System Alert • ID: 3590
Target: Spring Boot API
Potential Vulnerability

Your Spring Boot API might be exposed to Command Injection

74% of Spring Boot apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.