Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: significant rewrite

OS command injection vulnerabilities occur when an application fails to sanitize externally obtained untrusted input and allows 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.

OS Command Injection Example

Suppose a Java program wants to send email using the mail program. It might ask the user for an email address. The command might take the form:

mail <ADDRESS>

However, if an attacker supplies the following value for <ADDRESS>:

noboday@nowhere.com ; useradd attacker

the command executed is actually two commands:

mail noboday@nowhere.com ;
useradd attacker

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

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 shows a variant of the OS command injection vulnerability. The single argument version of the Runtime.exec() method uses a StringTokenizer to parse the argument into separate tokens. Consequently, command separators maliciously inserted into the argument fail to delimit the original command, so an adversary is unable to execute arbitrary system commands. Nevertheless, this noncompliant code example remains vulnerable, because a lax security policy could permit an attacker to invoke an external (and potentially privileged) programattempts to send a message to an email address supplied by an untrusted user. Since no sanitization is done on the address, the attack outlined above would work as described.

Code Block
bgColor#FFcccc
  
String programNameaddress = System.getProperty("program.nameemail");
if (programNameaddress !== null) { 
  // Runs user controlled program 
  handle error
}

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

Noncompliant Code Example

...

This noncompliant code example demonstrates a less likely, but more pernicious, form of OS command injection. The program spawns a shell (on POSIX based platforms) or a command prompt (on Windows), and permits passing arguments to external programs. The shell or prompt is often used to set an environment variable to a user-defined value from within the Java program. In this example, the programName string is expected to hold both the program's name and its arguments.

(Whitelisting)

This compliant solution sanitizes the email address by permitting only a handful of correct characters to appear, thus preventing command injectionAn adversary can execute arbitrary commands by terminating the command with a command separator, such as '&&' or '||'. The attacker can use this technique to cause a denial of service by piping the output of the program to a sensitive file; even worse, he can expose sensitive data by redirecting some sensitive output to an insecure location.

Code Block
bgColor#FFcccc
  
String address = System.getProperty("email");
if (address == null) {
  // programName can be 'ProgramName1 || ProgramName2'   handle error
}
if (!Pattern.matches("[0-9A-Za-z@.]+", address)) {
  // Handle error
}

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("/bin/shmail " + programNameaddress);  // "cmd.exe /C" on Windows
}

Compliant Solution

This compliant solution prevents command injection by requiring the user to select one of a predefined group of programs or commands. Further, both the programs and their arguments are hard-coded to prevent modification by the useraddresses. This prevents untrusted data from being added to the command.

Code Block
bgColor#ccccff
Process proc;String address = null;

int filename = Integer.parseInt(System.getproperty("program.nameaddress")); // only allow integer choices
Runtime runtime = Runtime.getRuntime();

switch(filename) {
  case 1: 
    procaddress = runtime.exec("hardcoded\program1"); "root@localhost"
    break; // Option 1
  case 2: 
    procaddress = runtime.exec("hardcoded\program2"); "postmaster@localhost"
    break; // Option 2
  default:
    System.out.println("Invalid option!");// invalid
    break; 
}

This approach also prevents exposure of the file system structure.

Compliant Solution

An alternative compliant solution is to:

  1. Store command names and arguments in a secure directory that is inaccessible to an attacker.
  2. Use a security manager to regulate both access permissions for that directory and also execute permissions for the commands to be invoked.
  3. Use the security manager's checkExec(String cmd) method to check whether the program is permitted to create the subprocess and to execute the external program.

This approach requires that the security manager must be used when running the application, and that the security policy file cannot be modified by an attacker. Use the security policy file to grant permissions to the application to execute files from a specific directory. See guideline ENV02-J. Create a secure sandbox using a Security Manager for additional information.

Wiki Markup
The security policy file must grant the {{java.io.FilePermission}} as follows \[[Permissions 2008|AA. Bibliography#Permissions 08]\]: 

  • When cmd is an absolute path, java.io.FilePermission "{cmd}", "execute"
  • otherwise, java.io.FilePermission "-", "execute";.

Note that the second alternative grants permission to execute any program. Consequently, we strongly recommend that permissions should be granted only on a per file basis, when possible. Do this by specifying absolute paths in the security policy file, as in the first alternative above.

if (address == null) {
  // handle error
}

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

Risk Assessment

OS command injection can cause arbitrary programs to be executed.

...

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

Other languages

This guideline appears in the C Secure Coding Standard as ENV03-C. Sanitize the environment when invoking external programs.

This guideline appears in the C++ Secure Coding Standard as ENV03-CPP. Sanitize the environment when invoking external programs.

Bibliography

Wiki Markup
\[[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)

...