Versions Compared

Key

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

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 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 Runtime.getRuntime() method. The semantics of Runtime.exec() are poorly defined, so it 's is best not to rely on its behavior any more than necessary. It will invoke , 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 somewhere 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.

This is a specific instance of the rule IDS00-J. Sanitize untrusted 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)

This noncompliant code example provides a directory listing using the dir command. This It is implemented using the Runtime.exec() to invoke the Windows dir command.

Code Block
bgColor#FFcccc
  
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);
    }
  }
}

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 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 that the argument is passed to proc Runtime.exec().

Code Block
bgColor#FFcccc
  
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 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 solution sanitizes the untrusted user input by permitting only allowing a small number group of whitelisted characters to in the argument that will be passed as part of the argument to the Runtime.exec() method; all other characters are excluded.

Code Block
bgColor#ccccff

// ...
if (!Pattern.matches("[0-9A-Za-z@.]+", dir)) {
  // Handle error
}
// ...

Although this it is a compliant solution, the this sanitization method approach rejects valid directories. Also, because the command interpreter invoked is system dependent, it is difficult to establish that this solution will not allow prevents command injection injections on every possible platform in on which a Java program might run.

Compliant Solution (Restricted User Choice)

This compliant solution prevents command injection by passing only passing trusted strings to Runtime.exec(). While the The user has control over which string is used , the user but cannot provide string data directly to Runtime.exec().

Code Block
bgColor#ccccff

// ...
String dir = null;

int number = Integer.parseInt(System.getpropertygetProperty("dir")); // onlyOnly allow integer choices
switch (number) {
  case 1: 
    dir = "data1";
    break; // Option 1
  case 2: 
    dir = "data2";
    break; // Option 2
  default: // invalidInvalid
    break; 
}
if (dir == null) {
  // handleHandle 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 scalable solution is to read all the email addresses permitted directories from a properties file into a java.util.Properties object. Alternately, the switch statement can operate on an enumerated type.

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 attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

IDS07-J

high

High

probable

Probable

medium

Medium

P12

L1

Automated Detection

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

Related Vulnerabilities

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5323a439-f34a-40cb-8b3c-5d390e513531"><ac:plain-text-body><![CDATA[

[

CVE-2010-0886

]

[

Sun Java Web Start Plugin Command Line Argument Injection

http://www.securitytube.net/video/1465]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f7bfbb4d-0142-4482-9ab1-162193e93f8e"><ac:plain-text-body><![CDATA[

[

CVE-2010-1826

]

[

Command injection in updateSharingD's handling of Mach RPC messages

http://securitytracker.com/id/1024617]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="01546829-7fb8-4df5-b35e-7f63ef11b3d6"><ac:plain-text-body><![CDATA[

[

T-472

]

[

Mac OS X Java Command Injection Flaw in updateSharingD

Lets Local Users Gain Elevated Privileges

http://www.doecirc.energy.gov/bulletins/t-472.shtml]

]]></ac:plain-text-body></ac:structured-macro>

Related Guidelines

Related Guidelines

SEI CERT C

The CERT C Secure ENV04

Coding Standard

ENV03-C. Sanitize the environment when invoking external programs

 

ENV33-C. Do not call system()

if you do not need a command processorThe

SEI CERT C++

Secure ENV04

Coding Standard

ENV03-CPP. Sanitize the environment when invoking external programs

 

[

VOID ENV02-CPP. Do not call system() if you do not need a command processor

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c554f127-591a-45ff-ab12-c8eed233c675"><ac:plain-text-body><![CDATA[

SEI CERT Perl Coding StandardIDS34-PL. Do not pass untrusted, unsanitized data to a command interpreter

http://www.aitcnet.org/isai/]

"

ISO/IEC TR 24772:

2010

2013

Injection [RST]

"

]]></ac:plain-text-body></ac:structured-macro>

MITRE CWE

CWE-78,

"

Improper Neutralization of Special Elements

used

Used in an OS Command (

'

"OS Command Injection

')"

Bibliography

")

Android Implementation Details

Runtime.exec() can be called from Android apps to execute operating system commands.

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3ad17253-d1c9-4cc2-9b29-526a7e811fca"><ac:plain-text-body><![CDATA[

[[Chess 2007

AA. Bibliography#Chess 07]]

Chapter 5: Handling Input, "Command Injection"]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2c1c2fdb-243d-4e77-b4fb-358d8512f134"><ac:plain-text-body><![CDATA[

[[OWASP 2005

AA. Bibliography#OWASP 05]]

[Reviewing Code for OS Injection

http://www.owasp.org/index.php/Reviewing_Code_for_OS_Injection]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8337440e-ac79-441a-b069-be03a298cc67"><ac:plain-text-body><![CDATA[

[[Permissions 2008

AA. Bibliography#Permissions 08]]

[

[Chess 2007]

Chapter 5, "Handling Input," section "Command Injection"

[OWASP 2005]A Guide to Building Secure Web Applications and Web Services
[Permissions 2008]
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)

]]></ac:plain-text-body></ac:structured-macro>

[Seacord 2015]


...

Image Added Image Added Image AddedIDS06-J. Exclude user input from format strings      Image Removed      IDS08-J. Sanitize untrusted data passed to a regex