...
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
|
...
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'
|
...
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 | ||
---|---|---|
| ||
// ...
if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) {
// Handle error
}
// ...
|
...
This compliant solution prevents command injection by passing only trusted strings to Runtime.exec()
. While the user has control over which string is used, the user cannot provide string data directly to Runtime.exec()
.
Code Block | ||
---|---|---|
| ||
// ...
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
}
|
...
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 | ||
---|---|---|
| ||
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);
}
}
}
}
|
...
ENV03-C. Sanitize the environment when invoking external programs | |
| ENV04-C. Do not call system() if you do not need a command processor |
ENV03-CPP. Sanitize the environment when invoking external programs | |
| ENV04-CPP. Do not call system() if you do not need a command processor |
The CERT Perl Secure Coding Standard | IDS34-PL. Do not pass untrusted, unsanitized data to a command interpreter |
Injection [RST] | |
CWE-78. Improper neutralization of special elements used in an OS command ("OS command injection") |
...
Chapter 5, Handling Input, "Command Injection" | |
IDS06-J. Exclude user input from format strings IDS08-J. Sanitize untrusted data passed to a regex