0

how to fix the following code in sonar perspective. it throws the following error

This usage of java/lang/Runtime.exec([Ljava/lang/String;)Ljava/lang/Process; can be vulnerable to Command Injection

The following is the code

String commandArr[] = new String[] {"curl", "-v", "-X", "put", "--user", drUserName + ":" + drPwd, "-H", "Content-Type:text/plain",
            "-H","X-ATT-DR-META:"+metaData, "--data", response.toString(), "--post301", "--location-trusted", feedFile};

    String command = Arrays.toString(commandArr);
    int returnCode = -1;
    try {
        returnCode = obj.executeCommand(commandArr);
    } catch{...}

Having issue in the following code

private int executeCommand(String[] command) {  
    int returnCode = -1;
    final String Msg = "HTTP/1.1 204 No Content";
    boolean isMsg= false; Process proc;
    try {
        proc = Runtime.getRuntime().exec(command); //sonar issue
        returnCode = proc.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (!isMsg) {
                if (line.contains(Msg)) {
                    isMsg= true;
                }
            }
        }
    } catch (Exception e) {...} 
    .....
    .....
    return returnCode;
}

Can somebody help?

Iris_geek
  • 393
  • 5
  • 19

1 Answers1

0

According to owasp.org page on Java command injection, using Runtime.exec opens your application to command injection:

Command injection vulnerabilities allow an attacker to inject arbitrary system commands into an application. The commands execute at the same privilege level as the Java application and provides an attacker with functionality similar to a system shell.

The best practice according to OWASP for addressing Runtime.exec command injection is that:

Developers should avoid invoking the shell using Runtime.exec in order to call operating system specific commands and should use Java APIs instead.

So in your case, instead of using Runtime.exec to execute cURL to perform the PUT HTTP operation, you might want to consider using a Java library to carry out the same operation. For instance, something from the answers of the question REST clients for Java should do the trick.

Thomas Kabassis
  • 1,326
  • 1
  • 12
  • 17