Versions Compared

Key

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

OS command 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 does not sanitize externally obtained fails to sanitize untrusted input and allows uses it in the execution of arbitrary system commands (with carefully chosen arguments) or an external program.

Noncompliant Code Example

A weakness in a privileged program caused by relying on untrusted sources such as the environment (See ENV06-J. Provide a trusted environment and sanitize all inputs), can result in the execution of a command or a program that has more privileges than those possessed by a typical user. This noncompliant code example shows such a variant of the OS command injection vulnerability.

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 commandWhen the single argument version of the Runtime.exec() method is invoked, the arguments are parsed by a StringTokenizer into separate tokens. Consequently, any command separators maliciously inserted into the argument do not delimit the original command and an adversary is unable to proceed in executing arbitrary system commands. However, this code is still vulnerable as an attacker can easily invoke an external (privileged) program, even in the presence of a security manager.

Code Block
bgColor#FFcccc
class DirList {
  public static void main(String[] args) throws Exception {
    String programNamedir = System.getProperty("program.name");
if (programName("dir");
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("cmd.exe /C dir " + dir);
    int result = proc.waitFor();
    if (result != null0) {
     
  // Runs user controlled program 
  Runtime runtime = Runtime.getRuntime();
  Process proc = runtime.exec(programName); 
}

Noncompliant Code Example

This noncompliant code example portrays a less likely, though more pernicious form of OS command injection. The program spawns a shell (*nix) or a command prompt (Windows) and allows passing arguments to external programs. Sometimes the shell or prompt is used to set an environment variable to a user defined value from within the program. The programName string is expected to hold the program's name, as well as the arguments.

 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()An adversary can terminate the command with a command separator (such as '&&' and '||') or cause the output of the program to be piped to a sensitive file for the purpose of causing a denial of service, or even worse, redirect some sensitive output to a non sensitive location.

Code Block
bgColor#FFcccc
class DirList 
// programName can be 'ProgramName1 || ProgramName2'  
{
  public static void main(String[] args) throws Exception {
    String dir = System.getProperty("dir");
    Runtime rt = Runtime.getRuntime();
    Process proc = runtimert.exec("/bin/new String[] {"sh", "-c", "ls " + programName);  // "cmd.exe /C" on Windows

Compliant Solution

 dir});
    int result = 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);
    }
  }
}

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@.]+", dir)) {
  // 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()This compliant solution restricts the programs that a privileged application can invoke when using user controlled inputs.

Code Block
bgColor#ccccff

Process proc// ...
String dir = null;

int filenamenumber = Integer.parseInt(System.getpropertygetProperty("program.namedir")); // onlyOnly allow integer choices
Runtime runtime = Runtime.getRuntime();

switch(filenameswitch (number) {
  case 1: 
    procdir = runtime.exec("hardcoded\program1"); "data1";
    break; // Option 1
  case 2: 
    procdir = runtime.exec("hardcoded\program2"); "data2";
    break; // Option 2
  default: // Invalid
    break;  System.out.println("Invalid option!");
}
if (dir == null) {
  // Handle break; error
}

Compliant Solution

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 An alternative is to read all the file names from a source existing in a secure directory, inaccessible to an attacker. The security policy file may grant permissions to the application to read files from a specific directory. The security manager must be used when running the application (ENV02-J. Create a secure sandbox using a Security Manager). It is also possibe to define a custom permission to control access to specific programs and using a security manager to enforce this permission (SEC10-J. Define custom security permissions for fine grained security).

Risk Assessment

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 attacksOS command injection can cause arbitrary programs to be executed.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC32

IDS07-J

high

High

probable

Probable

medium

Medium

P12

L1

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other languages

...

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

References

Wiki Markup
\[[OWASP 05|AA. Java References#OWASP 05]\] [Reviewing Code for OS Injection|http://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection]
\[[Chess 07|AA. Java References#Chess 07]\] Chapter 5: Handling Input, "Command Injection"
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 78|http://cwe.mitre.org/data/definitions/78.html] "Failure to Preserve OS Command Structure (aka 'OS Command Injection')"

IDS14-J. Perform loss less conversion of String to given encoding and back      10. Input Validation and Data Sanitization (IDS)      IDS07-J. Prevent against SQL Injection