You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 77 Next »

The exec() method of the java.lang.Runtime class and the related ProcessBuilder.start() method can be used to invoke external programs. These programs may require input to be sent to their input stream, and they may also produce output on their output stream or error stream. Incorrect handling of such external programs can cause unexpected exceptions, denial of service, and other security problems.

A process that tries to read input on an empty input stream will block until input is supplied. Consequently, input must be supplied when invoking such a process.

Output from an external process can exhaust the available buffer for the output or error stream. When this occurs, it can block the external process as well, preventing any forward progress for both the Java program and the external processes. Note that many platforms limit the buffer size available for the output streams. Consequently, when invoking an external process, if the process sends any data to its output stream, the process's output stream must be emptied. And if the process sends any data to its error stream, the error stream must also be emptied.

Noncompliant Code Example (exitValue())

This noncompliant code example invokes a hypothetical cross-platform notepad application using the external command notemaker. The notemaker application does not read its input stream, but sends output to both its output stream and error stream.

This noncompliant code example invokes notemaker using the exec() method, which returns an object of a subclass of the abstract class java.lang.Process. The exitValue() method returns the exit value for processes that have terminated, but it throws an IllegalThreadStateException when invoked on an active process. Because this noncompliant example program fails to wait for the notemaker process to terminate, the call to exitValue() is likely to throw an IllegalThreadStateException.

public class Exec {
  public static void main(String args[]) throws IOException {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("notemaker");
    int exitVal = proc.exitValue();
  }
}

Noncompliant Code Example (waitFor())

In this noncompliant code example, the waitFor() method blocks the calling thread until the the notemaker process terminates. This prevents the IllegalThreadStateException from the previous example. However, the example program may experience an arbitrary delay before termination. Output from the notemaker process can exhaust the available buffer for the output or error stream because neither stream is read while waiting for the process to complete. If either buffer becomes full, it can block the notemaker process as well, preventing all progress for both the notemaker process and the Java program.

public class Exec {
  public static void main(String args[]) throws IOException {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("notemaker");
    int exitVal = proc.waitFor();
  }
}

Noncompliant Code Example (Input Stream)

This noncompliant code example properly empties the input stream from the process, thereby preventing the input stream buffer from becoming full and blocking. However, it ignores the error stream, which can also fill and cause the process to block.

public class Exec {
  public static void main(String args[]) throws IOException, InterruptedException {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("notemaker");
    InputStream is = proc.getInputStream();
    int c;
    while ((c = is.read()) != -1) {
      System.out.print((char) c);
    }
    int exitVal = proc.waitFor();   
  }
}

Compliant Solution (redirectErrorStream())

This compliant solution redirects the process's error stream to its input stream. Consequently, the program can empty the single output stream without fear of blockage.

public class Exec {
  public static void main(String args[]) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("notemaker");
    pb = pb.redirectErrorStream(true);
    Process proc = pb.start();
    InputStream is = proc.getInputStream();
    int c;
    while ((c = is.read()) != -1) {
      System.out.print((char) c);
    }
    int exitVal = proc.waitFor();   
  }
}

Compliant Solution (Input Stream and Error Stream)

This compliant solution spawns two threads to consume the input stream and error stream. Consequently, the process cannot block indefinitely on those streams.

When the output and error streams are handled separately, they must be emptied independently. Failure to do so can cause the program to block indefinitely.

class StreamGobbler extends Thread {
  InputStream is;
  PrintStream os;

  StreamGobbler(InputStream is, PrintStream os) {
    this.is = is;
    this.os = os;
  }

  public void run() {
    try {
    int c;
    while ((c = is.read()) != -1)
      os.print((char) c);
    } catch (IOException x) {
      // handle error
    }
  }
}
	
public class Exec {
  public static void main(String[] args) throws IOException, InterruptedException {
	
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("notemaker");

    // Any error message?
    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), System.err);
	
    // Any output?
    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), System.out);
	
    errorGobbler.start();
    outputGobbler.start();
	
    // Any error?
    int exitVal = proc.waitFor();
    errorGobbler.join();   // Handle condition where the
    outputGobbler.join();  // process ends before the threads finish 
  }
}

Exceptions

FIO07-EX0: Failure to supply input to a process that never reads input from its input stream is harmless, and can be beneficial. Failure to empty the output or error streams of a process that never sends output to its output or error streams is similarly harmless, or even beneficial. Consequently, programs are permitted to ignore the input, output, or error streams when, and only when, the process is guaranteed those streams.

Risk Assessment

Misuse of the exec() method can result in runtime exceptions and in denial of service vulnerabilities.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO07-J

low

probable

medium

P4

L3

Related Vulnerabilities

GROOVY-3275

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ff5ef0f4-432a-4876-8080-391d1b9eca74"><ac:plain-text-body><![CDATA[

[[API 06

AA. Bibliography#API 06]]

method [exec()

http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String)]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e9cc0b2b-0052-4da1-a172-c0526cc94a27"><ac:plain-text-body><![CDATA[

[[Daconta 00

AA. Bibliography#Daconta 00]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0c5ea427-26a4-4ef1-9d4e-1addbc95a96f"><ac:plain-text-body><![CDATA[

[[Daconta 03

AA. Bibliography#Daconta 03]]

Pitfall 1

]]></ac:plain-text-body></ac:structured-macro>


FIO06-J. Do not create multiple buffered wrappers on a single InputStream      12. Input Output (FIO)      FIO08-J. Use an int to capture the return value of functions that read a character or byte

  • No labels