Versions Compared

Key

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

...

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
bgColor#ccccff

// ...
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
bgColor#ccccff

// ...
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
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);
      }
    }
  }
}

...

...

[Chess 2007]

Chapter 5, Handling Input, "Command Injection"

[OWASP 2005]

[Permissions 2008]

 

IDS06-J. Exclude user input from format strings            IDS08-J. Sanitize untrusted data passed to a regex