GuardAPI Logo
GuardAPI

Fix Command Injection in Micronaut

Command injection in Micronaut occurs when untrusted input flows into a system shell without sanitization. In Java-based microservices, this typically happens via ProcessBuilder or Runtime.exec. Exploitation allows attackers to execute arbitrary OS commands under the context of the application user, leading to full system compromise. If you're concatenating strings into shell commands, you've already lost.

The Vulnerable Pattern

@Controller("/api")
public class NetworkController {
    @Get("/lookup")
    public String dnsLookup(@QueryValue String host) throws IOException {
        // CRITICAL VULNERABILITY: Shell metacharacters in 'host' (e.g., '; rm -rf /') will execute
        Process process = Runtime.getRuntime().exec("nslookup " + host);
        return new String(process.getInputStream().readAllBytes());
    }
}

The Secure Implementation

The vulnerability stems from passing a raw string to the OS shell, which interprets special characters (;, &, |, $). The secure implementation fixes this by: 1. Implementing a strict Regex allowlist to ensure the input contains only expected characters. 2. Using ProcessBuilder's constructor that accepts a List of strings. This bypasses shell interpretation entirely, treating the 'host' variable as a literal argument to the binary rather than part of a command string. Whenever possible, use native Java libraries (like java.net.InetAddress) instead of spawning OS processes.

@Controller("/api")
public class NetworkController {
    private static final Pattern ALLOWED_CHARS = Pattern.compile("^[a-zA-Z0-9.-]+$");
@Get("/lookup")
public String dnsLookup(@QueryValue String host) throws IOException {
    // 1. Strict Allowlist Validation
    if (host == null || !ALLOWED_CHARS.matcher(host).matches()) {
        throw new IllegalArgumentException("Invalid hostname format");
    }

    // 2. Use ProcessBuilder with an argument list to prevent shell interpolation
    ProcessBuilder pb = new ProcessBuilder("nslookup", host);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    
    return new String(process.getInputStream().readAllBytes());
}

}

System Alert • ID: 1205
Target: Micronaut API
Potential Vulnerability

Your Micronaut API might be exposed to Command Injection

74% of Micronaut 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.