用户工具

站点工具


cwe:cn:definition:78

CWE-78:OS命令中使用的特殊元素转义处理不恰当(OS命令注入)

Description Summary

The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

Extended Description

This could allow attackers to execute unexpected, dangerous commands directly on the operating system. This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.

There are at least two subtypes of OS command injection:

  1. The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system(“nslookup [HOSTNAME]”) to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing.
  1. The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use “exec([COMMAND])” to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line.

From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input.

Likelihood of Exploit

High

Common Consequences

Scope Technical Impace Note
Confidentiality
Integrity
Availability
Non-Repudiation
Execute unauthorized code or commands
DoS: crash / exit / restart
Read files or directories
Modify files or directories
Read application data
Modify application data
Hide activities
Attackers could execute unauthorized commands, which could then be used to disable the software, or read and modify data for which the attacker does not have permissions to access directly. Since the targeted application is directly executing the commands instead of the attacker, any malicious activities may appear to come from the application or the application's owner.

Detection Methods

Detection Method - 1

Automated Static Analysis

This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives.

Automated static analysis might not be able to recognize when proper input validation is being performed, leading to false positives - i.e., warnings that do not have any security consequences or do not require any code changes.

Automated static analysis might not be able to detect the usage of custom API functions or third-party libraries that indirectly invoke SQL commands, leading to false negatives - especially if the API/library code is not available for analysis.

This is not a perfect solution, since 100% accuracy and coverage are not feasible.
2013/05/30 09:36

Detection Method - 2

Automated Dynamic Analysis

This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

2013/05/30 09:36

Detection Method - 3

Manual Static Analysis

Since this weakness does not typically appear frequently within a single software package, manual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all potentially-vulnerable operations can be assessed within limited time constraints.

The effectiveness and speed of manual analysis will be reduced if the there is not a centralized security mechanism, and the security logic is widely distributed throughout the software.
2013/05/30 09:37

Detection Method - 4

Automated Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Detection Method - 5

=== Dynamic Analysis with automated results interpretation === According to SOAR, the following detection techniques may be useful:

Detection Method - 6

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Detection Method - 7

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Detection Method - 8

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Detection Method - 9

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Potential Mitigations

Mitigation - 1

Architecture and Design

If at all possible, use library calls rather than external processes to recreate the desired functionality.

Mitigation - 2

Architecture and Design Operation

Strategy:Sandbox or Jail

Run the code in a “jail” or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

2013/05/30 09:37

Mitigation - 3

Architecture and Design

Strategy:Identify and Reduce Attack Surface

For any data that will be used to generate a command to be executed, keep as much of that data out of external control as possible. For example, in web applications, this may require storing the data locally in the session's state instead of sending it out to the client in a hidden form field.

Mitigation - 4

Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

2013/05/30 09:37

Mitigation - 5

Architecture and Design

Strategy:Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

For example, consider using the ESAPI Encoding control [R.838.7] or a similar tool, library, or framework. These will help the programmer encode outputs in a manner less prone to error.

Note that some template mechanisms provide built-in support for the appropriate encoding.

2013/05/30 09:37

Mitigation - 6

Implementation

Strategy:Output Encoding

While it is risky to use dynamically-generated query strings, code, or commands that mix control and data together, sometimes it may be unavoidable. Properly quote arguments and escape any special characters within those arguments. The most conservative approach is to escape or filter all characters that do not pass an extremely strict whitelist (such as everything that is not alphanumeric or white space). If some special characters are still needed, such as white space, wrap each argument in quotes after the escaping/filtering step. Be careful of argument injection (CWE-88).

Instead of building a new implementation, such features may be available in the database or programming language. For example, the Oracle DBMS_ASSERT package can check or enforce that parameters have certain properties that make them less vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C and PHP.

2013/05/30 09:37

Mitigation - 7

Implementation

If the program to be executed allows arguments to be specified within an input file or from standard input, then consider using that mode to pass arguments instead of the command line.

Mitigation - 8

Architecture and Design

Strategy:Parameterization

If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.

Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using “exec” or similar functionality, since this may re-introduce the possibility of SQL injection. [R.89.3]

2013/05/30 09:37

Mitigation - 9

Implementation

Strategy:Input Validation

Assume all input is malicious. Use an “accept known good” input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, “boat” may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as “red” or “blue.”

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

2013/05/30 09:37

Mitigation - 10

Architecture and Design

Strategy:Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

2013/05/30 09:37

Mitigation - 11

Operation

Strategy:Compilation or Build Hardening

Environment Hardening

Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's ”-T” switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).

2013/05/30 09:37

Mitigation - 12

Implementation

Ensure that error messages only contain minimal details that are useful to the intended audience, and nobody else. The messages need to strike the balance between being too cryptic and not being cryptic enough. They should not necessarily reveal the methods that were used to determine the error. Such detailed information can be used to refine the original attack to increase the chances of success.

If errors must be tracked in some detail, capture them in log messages - but consider what could occur if the log messages can be viewed by attackers. Avoid recording highly sensitive information such as passwords in any form. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a username is valid or not.

In the context of SQL Injection, error messages revealing the structure of a SQL query can help attackers tailor successful attack strings.

2013/05/30 13:23

Mitigation - 13

Operation

Strategy:Sandbox or Jail

Use runtime policy enforcement to create a whitelist of allowable commands, then prevent use of any command that does not appear in the whitelist. Technologies such as AppArmor are available to do this.

Mitigation - 14

Operation

Strategy:Firewall

Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth.

2013/05/30 09:37

Mitigation - 15

Architecture and Design Operation

Strategy:Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.98.2]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

2013/05/30 09:37

Mitigation - 16

Operation Implementation

Strategy:Environment Hardening

When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

Often, programmers do not protect direct access to files intended only to be included by core programs. These include files may assume that critical variables have already been initialized by the calling program. As a result, the use of register_globals combined with the ability to directly access the include file may allow attackers to conduct file inclusion attacks. This remains an extremely common pattern as of 2009.

2013/05/30 09:37

Demonstrative Examples

Example - 1

This example code intends to take the name of a user and list the contents of that user's home directory. It is subject to the first variant of OS command injection.

$userName = $_POST["user"]; 
$command = 'ls -l /home/' . $userName; 
system($command); 

The $userName variable is not checked for malicious input. An attacker could set the $userName variable to an arbitrary OS command such as:

;rm -rf / 

Which would result in $command being:

ls -l /home/;rm -rf / 

Since the semi-colon is a command separator in Unix, the OS would first execute the ls command, then the rm command, deleting the entire file system.

Also note that this example code is vulnerable to Path Traversal (CWE-22) and Untrusted Search Path (CWE-426) attacks.

Example - 2

This example is a web application that intends to perform a DNS lookup of a user-supplied domain name. It is subject to the first variant of OS command injection.

use CGI qw(:standard); 
$name = param('name'); 
$nslookup = "/path/to/nslookup"; 
print header; 
if (open($fh, "$nslookup $name|")) { 
while (<$fh>) { 
print escapeHTML($_); 
print "<br>\n"; 
 
} 
close($fh); 
 
} 

Suppose an attacker provides a domain name like this:

cwe.mitre.org%20%3B%20/bin/ls%20-l 

The ”%3B” sequence decodes to the ”;” character, and the %20 decodes to a space. The open() statement would then process a string like this:

/path/to/nslookup cwe.mitre.org ; /bin/ls -l 

As a result, the attacker executes the ”/bin/ls -l” command and gets a list of all the files in the program's working directory. The input could be replaced with much more dangerous commands, such as installing a malicious program on the server.

Example - 3

The example below reads the name of a shell script to execute from the system properties. It is subject to the second variant of OS command injection.

String script = System.getProperty("SCRIPTNAME"); 
if (script != null) 
System.exec(script); 
 

If an attacker has control over this property, then they could modify the property to point to a dangerous program.

Example - 4

In the example below, a method is used to transform geographic coordinates from latitude and longitude format to UTM format. The method gets the input coordinates from a user through a HTTP request and executes a program local to the application server that performs the transformation. The method passes the latitude and longitude coordinates as a command-line option to the external program and will perform some processing to retrieve the results of the transformation and return the resulting UTM coordinates.

public String coordinateTransformLatLonToUTM(String coordinates) 
{ 
String utmCoords = null; 
try { 
String latlonCoords = coordinates; 
Runtime rt = Runtime.getRuntime(); 
Process exec = rt.exec("cmd.exe /C latlon2utm.exe -" + latlonCoords); 
// process results of coordinate transform 
// ... 
 
} 
catch(Exception e) {...} 
return utmCoords; 
 
} 

However, the method does not verify that the contents of the coordinates input parameter includes only correctly-formatted latitude and longitude coordinates. If the input coordinates were not validated prior to the call to this method, a malicious user could execute another program local to the application server by appending '&' followed by the command for another program to the end of the coordinate string. The '&' instructs the Windows operating system to execute another program.

Example - 5

The following code is from an administrative web application designed to allow users to kick off a backup of an Oracle database using a batch-file wrapper around the rman utility and then run a cleanup.bat script to delete some temporary files. The script rmanDB.bat accepts a single command line parameter, which specifies what type of backup to perform. Because access to the database is restricted, the application runs the backup as a privileged user.

... 
String btype = request.getParameter("backuptype"); 
String cmd = new String("cmd.exe /K \" 
c:\\util\\rmanDB.bat " 
+btype+ 
"&&c:\\utl\\cleanup.bat\"") 
 
System.Runtime.getRuntime().exec(cmd); 
... 

The problem here is that the program does not do any validation on the backuptype parameter read from the user. Typically the Runtime.exec() function will not execute multiple commands, but in this case the program first runs the cmd.exe shell in order to run multiple commands with a single call to Runtime.exec(). Once the shell is invoked, it will happily execute multiple commands separated by two ampersands. If an attacker passes a string of the form ”& del c:\\dbms\\*.*”, then the application will execute this command along with the others specified by the program. Because of the nature of the application, it runs with the privileges necessary to interact with the database, which means whatever command the attacker injects will run with those privileges as well.

2013/05/30 13:23

Observed Examples

Reference Description
CVE-1999-0067Canonical example. CGI program does not neutralize “” metacharacter when invoking a phonebook program.
CVE-2001-1246Language interpreter's mail function accepts another argument that is concatenated to a string used in a dangerous popen() call. Since there is no neutralization of this argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are possible.
CVE-2002-0061Web server allows command execution using “” (pipe) character.
CVE-2003-0041FTP client does not filter “” from filenames returned by the server, allowing for OS command injection.
CVE-2008-2575Shell metacharacters in a filename in a ZIP archive
CVE-2002-1898Shell metacharacters in a telnet:// link are not properly handled when the launching application processes the link.
CVE-2008-4304OS command injection through environment variable.
CVE-2008-4796OS command injection through https:// URLs
CVE-2007-3572Chain: incomplete blacklist for OS command injection
CVE-2012-1988Product allows remote users to execute arbitrary commands by creating a file whose pathname contains shell metacharacters.
cwe/cn/definition/78.txt · 最后更改: 2014/09/04 14:53 (外部编辑)