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 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 getRuntime()
method. The semantics of Runtime.exec
are poorly defined, so it's best not to rely on its behavior any more than necessary. It will invoke the command directly without a shell. If you want a shell, you can use "/bin/sh", "-c" on UNIX or "cmd.exe" on Windows. The variants of exec)(
that take the command line a single String split it with a StringTokenizer
. On Windows, these tokens will be concatenated back into a single argument string somewhere along the line.
Consequently, command injection doesn't work unless a command interpreter is explicitly invoked. However, particularly on Windows, there can be vulnerabilities where arguments have spaces, double quotes, etc., or start with a - or / to indicate a switch.
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.
Noncompliant Code Example (Windows)
A weakness in a privileged program caused by relying on untrusted sources such as system properties or 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 provides a listing of the directory that is provided by the dir
system property. It accomplishes this by using Runtime.exec()
to invoke the Windows dir
command.
import java.io.InputStream; class DirList { public static void main(String[] args) throws Exception { String dir = System.getProperty("dir"); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("cmd.exe /C dir " + 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); } } }
Since Runtime.exec()
receives unsanitized data originating from the environment (see guideline ENV06-J. Provide a trusted environment and sanitize all inputs), this code is susceptible to a command injection attack.
An attacker can exploit this program using the following command:
java -Ddir='dummy & echo bad' Java
the command executed is actually two commands:
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 proc
.
import java.io.InputStream; 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() : proc.getErrorStream(); int c; while ((c = in.read()) != -1) { System.out.print((char) c); } } }
The attacker can supply the same command, with the same effects as above. The command executed is actually:
sh -c 'ls dummy & echo bad'
Compliant Solution (Sanitization)
This compliant solution sanitizes the folder by permitting only a handful of correct characters to appear.
// ... if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) { // Handle error } // ...
Although this is a compliant solution, the sanitization method is weak because it will reject valid directories. Also since the command interpreter invoked is system dependent, it is difficult to say that this solution will not allow command injection on every possible platform in which a Java program might run.
Compliant Solution (Restricted user choice)
This compliant solution prevents command injection by only passing trusted strings to Runtime.exec()
. While the user has control over which string gets used, the user cannot send strings directly to Runtime.exec()
.
String dir = null; int number = Integer.parseInt(System.getproperty("dir")); // only allow integer choices switch(number) { case 1: dir = "data1" break; // Option 1 case 2: dir = "data2" break; // Option 2 default: // invalid break; } if (dir == null) { // handle error }
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 extensible solution is to read all the email addresses 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 directory listing, thereby preventing command injection.
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
OS command injection can cause arbitrary programs to be executed.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
IDS06-J |
high |
probable |
medium |
P12 |
L1 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
[[Chess 2007]] Chapter 5: Handling Input, "Command Injection"
[[MITRE 2009]] CWE ID 78 "Failure to Preserve OS Command Structure (aka 'OS Command Injection')"
[[OWASP 2005]] Reviewing Code for OS Injection
[[Permissions 2008]] Permissions in the Java⢠SE 6 Development Kit (JDK), Sun Microsystems, Inc. (2008)
13. Input Validation and Data Sanitization (IDS) IDS07-J. Prevent SQL Injection