Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

External programs are commonly invoked to perform a function required by the overall system. This practice is a form of reuse and might even be considered a crude form of component-based software engineering. Command and argument injection vulnerabilities occur when an application fails to sanitize untrusted input and uses it in the execution of external programs.

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the Runtime.getRuntime() method. The semantics of Runtime.exec() are poorly defined, so it is best not to rely on its behavior any more than necessary, but typically it invokes the command directly without a shell. If you want a shell, you can use /bin/sh -c on POSIX or cmd.exe on Windows. The variants of exec() that take the command line as a single string split it using a StringTokenizer. On Windows, these tokens are concatenated back into a single argument string before being executed.

Consequently, command injection attacks cannot succeed unless a command interpreter is explicitly invoked. However, argument injection attacks can occur when arguments have spaces, double quotes, and so forth, or when they start with a - or / to indicate a switch.

Any string data that originates from outside the program's trust boundary must be sanitized before being executed as a command on the current platform.

Noncompliant Code Example (Windows)

This noncompliant code example provides a directory listing using the dir command. It is implemented using Runtime.exec() to invoke the Windows dir command.

Code Block
bgColor#FFcccc
class DirList {
  public static void main(String[] args) throws Exception {
    String dir
Wiki Markup
Every Java application has a single instance of class {{Runtime}} that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the {{getRuntime()}} method. The {{exec()}} method executes the specified string command by invoking an implementation-defined command processor, such as a UNIX shell or {{CMD.EXE}} in Windows NT and later.

External programs are commonly invoked to perform a function required by the overall system. This is a form of reuse and might even be considered a crude form of component-based software engineering.

Command interpreters, such as the POSIX command-language interpreter {{sh}} and the Windows {{CMD.EXE}}, however, provide functionality in addition to executing a simple command.

OS command injection vulnerabilities occur when an application fails to sanitize untrusted input and uses it in the execution of arbitrary system commands (with carefully chosen arguments) or of an external program.  This is a specific instance of the guideline [IDS01-J. Sanitize data passed across a trust boundary]. Any string data that originates from outside the program's trust boundary must be sanitized before being executed as a command on the current platform.

h2. Noncompliant Code Example

A weakness in a privileged program caused by relying on untrusted sources such as the environment (see guideline [ENV06-J. Provide a trusted environment and sanitize all inputs]) can result in the execution of a command or of a program that has privileges beyond those possessed by a typical user.

This noncompliant code example attempts to send a message to an email address supplied by an untrusted user. Because untrusted data originating from the environment (see guideline [ENV06-J. Provide a trusted environment and sanitize all inputs]) without sanitization this code is susceptible to a command injection attack.

{code:bgColor=#FFcccc}  
String address = System.getProperty("emaildir");
if (address == null) {
  // handle error
}

Runtime runtimert = Runtime.getRuntime();
    Process proc = runtimert.exec("mailcmd.exe /C dir " + addressdir); 
{code}

If an attacker supplies the following valueint forresult the {{"email"}} environment variable:

{code}
noboday@nowhere.com ; useradd attacker
{code}

the command executed is actually two commands:

{code}
mail noboday@nowhere.com ;
useradd attacker
{code}

which causes a new account to be created for the attacker.

h2. Compliant Solution (Sanitization)

This compliant solution sanitizes the email address by permitting only a handful of correct characters to appear. 

{code:bgColor=#ccccff}
String address = System.getProperty("email");
if (address == null) {
  // handle error
}
if (!Pattern.matches("[0-9A-Za-z@.]+", address)) {
  // Handle error
}

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mail " + address); 
{code}

Although this is a compliant solution, the sanitization method is weak because:
* it will reject valid email addresses
* it doesn't require any syntax or regular expression pattern matching (for example, using the regular expression "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b") to validate the input. 
* email validation is complicated.  You can actually purchase or acquire an entire component / subsystem for email address validation, for example the Apache {{[Class EmailValidator|http://commons.apache.org/validator/api-1.3.1/org/apache/commons/validator/EmailValidator.html]}} 
* The command interpreter invoked is system dependent, so is difficult to say that this solution will not allow command injection in every environment in which a Java program might run.

h2. Compliant Solution (Parametrization)

A further improvement to the previous compliant solution is to parametrize the call to the {{exec()}} method. There are six forms of the {{exec()}} method, most of which are convenience methods for the following method:  

{code}
 public Process exec(String[] cmdarray,
    = proc.waitFor();
    if (result != 0) {
      System.out.println("process error: " + result);
    }
    InputStream in = (result == 0) ? proc.getInputStream() :
                                     proc.getErrorStream();
    int c;
    while ((c = in.read()) != -1) {
      System.out.print((char) c);
    }
  }
}

Because Runtime.exec() receives unsanitized data originating from the environment, this code is susceptible to a command injection attack.

An attacker can exploit this program using the following command:

Code Block
java -Ddir='dummy & echo bad' Java

The command executed is actually two commands:

Code Block
cmd.exe /C dir dummy & echo bad

which first attempts to list a nonexistent dummy folder and then prints bad to the console.

Noncompliant Code Example (POSIX)

This noncompliant code example provides the same functionality but uses the POSIX ls command. The only difference from the Windows version is the argument passed to Runtime.exec().

Code Block
bgColor#FFcccc
class DirList {
  public static void main(String[] args) throws Exception {
    String dir = System.getProperty("dir");
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir});
    int result = proc.waitFor();
    if (result != 0) {
      System.out.println("process error: " + result);
    }
    InputStream in = (result == 0) ? proc.getInputStream() :
                String[] envp,
                    File dir)proc.getErrorStream();
    int c;
    while ((c = in.read()) != throws-1) IOException
{code}

Using  any form of the {{exec()}} method where the first argument is an array containing the command to call and its arguments is generally safer because the command itself does not contain untrusted data.  

{code:bgColor=#ccccff}
String address = System.getProperty("email");
if (address == null) {
  // handle error
}
 System.out.print((char) c);
    }
  }
}

The attacker can supply the same command shown in the previous noncompliant code example with similar effects. The command executed is actually

Code Block
sh -c 'ls dummy & echo bad'

Compliant Solution (Sanitization)

This compliant solution sanitizes the untrusted user input by permitting only a small group of whitelisted characters in the argument that will be passed to Runtime.exec(); all other characters are excluded.

Code Block
bgColor#ccccff
// ...
if (!Pattern.matches("[0-9A-Za-z@.]+", addressdir)) {
  // Handle error
}
// ...

Although it is a compliant solution, this sanitization approach rejects valid directories. Also, because the command interpreter invoked is system dependent, it is difficult to establish that this solution prevents command injections on every platform on which a Java program might run.

Compliant Solution (Restricted User Choice)

This compliant solution prevents command injection by passing only trusted strings to Runtime.exec(). The user has control over which string is used but cannot provide string data directly to Runtime.exec().

Code Block
bgColor#ccccff
// ...
String dir
String[] command = {"mail", address};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command, null, null); 
{code}

In some cases, this can still result in an argument injection attack.

h2. Compliant Solution (Not passing untrusted data to the {{exec()}} method)

This compliant solution prevents command injection by requiring the user to select one of a predefined group of addresses. This prevents untrusted data from being added to the command.

{code:bgColor=#ccccff}
String address = null;

int filenamenumber = Integer.parseInt(System.getpropertygetProperty("addressdir")); // onlyOnly allow integer choices
switch (filenamenumber) {
  case 1: 
    addressdir = "root@localhostdata1";
    break; // Option 1
  case 2: 
    addressdir = "postmaster@localhostdata2";
    break; // Option 2
  default: // invalidInvalid
    break; 
}
if (addressdir == null) {
  // handleHandle error
}

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mail " + address); 
{code}


h2. Risk Assessment

OS command injection can cause arbitrary programs to be executed.

|| Guideline || Severity || Likelihood || Remediation Cost || Priority || Level ||
| IDS06-J | high | probable | medium | {color:red}{*}P12{*}{color} | {color:red}{*}L1{*}{color} |



h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+MSC32-J].



h2. Bibliography

\[[Chess 2007|AA. Bibliography#Chess 07]\] Chapter 5: Handling Input, "Command Injection"
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 78|http://cwe.mitre.org/data/definitions/78.html] "Failure to Preserve OS Command Structure (aka 'OS Command Injection')"
\[[OWASP 2005|AA. Bibliography#OWASP 05]\] [Reviewing Code for OS Injection|http://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection]
\[[Permissions 2008|AA. Bibliography#Permissions 08]\] [Permissions in the Java™ SE 6 Development Kit (JDK)|http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html], Sun Microsystems, Inc. (2008)

----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|IDS05-J. Library methods should validate their parameters]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|13. Input Validation and Data Sanitization (IDS)]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|IDS07-J. Prevent SQL Injection]

This compliant solution hard codes the directories that may be listed.

This solution can quickly become unmanageable if you have many available directories. A more scalable solution is to read all the permitted directories from a properties file into a java.util.Properties object.

Compliant Solution (Avoid Runtime.exec())

When the task performed by executing a system command can be accomplished by some other means, it is almost always advisable to do so. This compliant solution uses the File.list() method to provide a directory listing, eliminating the possibility of command or argument injection attacks.

Code Block
bgColor#ccccff
import java.io.File;

class DirList {
  public static void main(String[] args) throws Exception {
    File dir = new File(System.getProperty("dir"));
    if (!dir.isDirectory()) {
      System.out.println("Not a directory");
    } else {
      for (String file : dir.list()) {
        System.out.println(file);
      }
    }
  }
}

Risk Assessment

Passing untrusted, unsanitized data to the Runtime.exec() method can result in command and argument injection attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

IDS07-J

High

Probable

Medium

P12

L1

Automated Detection

ToolVersionCheckerDescription
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Tainting CheckerTrust and security errors (see Chapter 8)
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.IO.INJ.COMMAND

Command Injection (Java)

Coverity7.5OS_CMD_INJECTIONImplemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.IDS07.EXECDo not use 'Runtime.exec()'
SonarQube
Include Page
SonarQube_V
SonarQube_V

S2076

OS commands should not be vulnerable to injection attacks

Related Vulnerabilities

Related Guidelines

Android Implementation Details

Runtime.exec() can be called from Android apps to execute operating system commands.

Bibliography


...

Image Added Image Added Image Added