Improper Check for Unusual or Exceptional Conditions
Weakness ID: 754 (Weakness Class)Status: Incomplete
+ Description

Description Summary

The software does not check or improperly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.

Extended Description

The programmer may assume that certain events or conditions will never occur or do not need to be worried about, such as low memory conditions, lack of access to resources due to restrictive permissions, or misbehaving clients or components. However, attackers may intentionally trigger these unusual conditions which thus violating the programmer's assumptions, possibly introducing instability, incorrect behavior, or a vulnerability.

Note that this entry is not exclusively about the use of exceptions and exception handling, which are mechanisms for both checking and handling unusual or unexpected conditions.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

Language-independent

+ Common Consequences
ScopeEffect
Integrity
Availability

The data which were produced as a result of a function call could be in a bad state upon return. If the return value is not checked, then this bad data may be used in operations, possibly leading to a crash or other unintended behaviors.

+ Likelihood of Exploit

Medium

+ Detection Methods

Automated Static Analysis

Automated static analysis may be useful for detecting unusual conditions involving system resources or common programming idioms, but not for violations of business rules.

Effectiveness: Moderate

+ Demonstrative Examples

Example 1

Consider the following code segment:

(Bad Code)
Example Language:
char buf[10], cp_buf[10];
fgets(buf, 10, stdin);
strcpy(cp_buf, buf);

The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy().

Example 2

The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc().

(Bad Code)
Example Language:
buf = (char*) malloc(req_size);
strncpy(buf, xfer, req_size);

The traditional defense of this coding error is: "If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or simply allow the program to die with a segmentation fault when it tries to dereference the null pointer." This argument ignores three important considerations: - Depending upon the type and size of the application, it may be possible to free memory that is being used elsewhere so that execution can continue. - It is impossible for the program to perform a graceful exit if required. If the program is performing an atomic operation, it can leave the system in an inconsistent state. - The programmer has lost the opportunity to record diagnostic information. Did the call to malloc() fail because req_size was too large or because there were too many requests being handled at the same time? Or was it caused by a memory leak that has built up over time? Without handling the error, there is no way to know.

Example 3

The following code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always 1 kilobyte in size and therefore ignores the return value from Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and handle it as though it belongs to the attacker.

(Bad Code)
Example Language: Java 
char[] byteArray = new char[1024];
for (IEnumerator i=users.GetEnumerator(); i.MoveNext() ;i.Current()) {
String userName = (String) i.Current();
String pFileName = PFILE_ROOT + "/" + userName;
StreamReader sr = new StreamReader(pFileName);
sr.Read(byteArray,0,1024);//the file is always 1k bytes
sr.Close();
processPFile(userName, byteArray);
}
(Bad Code)
Example Language: Java 
FileInputStream fis;
byte[] byteArray = new byte[1024];
for (Iterator i=users.iterator(); i.hasNext();) {
String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName;
FileInputStream fis = new FileInputStream(pFileName);
fis.read(byteArray); // the file is always 1k bytes
fis.close();
processPFile(userName, byteArray);

}

Example 4

The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference.

(Bad Code)
Example Language: Java 
String itemName = request.getParameter(ITEM_NAME);
if (itemName.compareTo(IMPORTANT_ITEM) == 0) {
...
}
...

The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference.

(Bad Code)
Example Language: Java 
String itemName = request.Item(ITEM_NAME);
if (itemName.Equals(IMPORTANT_ITEM)) {
...
}
...

The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved.

Example 5

The following code shows a system property that is set to null and later dereferenced by a programmer who mistakenly assumes it will always be defined.

(Bad Code)
Example Language: Java 
System.clearProperty("os.name");
...
String os = System.getProperty("os.name");
if (os.equalsIgnoreCase("Windows 95")) System.out.println("Not supported");

The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved.

Example 6

The following VB.NET code does not check to make sure that it has read 50 bytes from myfile.txt. This can cause DoDangerousOperation() to operate on an unexpected value.

(Bad Code)
Example Language: .NET 
Dim MyFile As New FileStream("myfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
Dim MyArray(50) As Byte
MyFile.Read(MyArray, 0, 50)
DoDangerousOperation(MyArray(20))

In .NET, it is not uncommon for programmers to misunderstand Read() and related methods that are part of many System.IO classes. The stream and reader classes do not consider it to be unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested.

Example 7

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.

(Bad Code)
Example Language:
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);

/*routine that ensures user_supplied_addr is in the right format for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(&hostname, hp->h_name);
}

If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL . When this occurs, a NULL pointer dereference (CWE-476) will occur in the call to strcpy().

Note that this example is also vulnerable to a buffer overflow (see CWE-119).

Example 8

In the following C/C++ example the method outputStringToFile opens a file in the local filesystem and outputs a string to the file. The input parameters output and filename contain the string to output to the file and the name of the file respectively.

(Bad Code)
Example Language: C++ 
int outputStringToFile(char *output, char *filename) {

openFileToWrite(filename);
writeToFile(output);
closeFile();
}

However, this code does not check the return values of the methods openFileToWrite, writeToFile, closeFile to verify that the file was properly opened and closed and that the string was successfully written to the file. The return values for these methods should be checked to determine if the method was successful and allow for detection of errors or unexpected conditions as in the following example.

(Good Code)
Example Language: C++ 
int outputStringToFile(char *output, char *filename) {
int isOutput = SUCCESS;

int isOpen = openFileToWrite(filename);
if (isOpen == FAIL) {
printf("Unable to open file %s", filename);
isOutput = FAIL;
}
else {
int isWrite = writeToFile(output);
if (isWrite == FAIL) {
printf("Unable to write to file %s", filename);
isOutput = FAIL;
}

int isClose = closeFile();
if (isClose == FAIL)
isOutput = FAIL;
}
return isOutput;
}

Example 9

In the following Java example the method readFromFile uses a FileReader object to read the contents of a file. The FileReader object is created using the File object readFile, the readFile object is initialized using the setInputFile method. The setInputFile method should be called before calling the readFromFile method.

(Bad Code)
Example Language: Java 
private File readFile = null;

public void setInputFile(String inputFile) {
// create readFile File object from string containing name of file
}

public void readFromFile() {
try {
reader = new FileReader(readFile);

// read input file

} catch (FileNotFoundException ex) {...}
}

However, the readFromFile method does not check to see if the readFile object is null, i.e. has not been initialized, before creating the FileReader object and reading from the input file. The readFromFile method should verify whether the readFile object is null and output an error message and raise an exception if the readFile object is null, as in the following code.

(Good Code)
Example Language: Java 
private File readFile = null;

public void setInputFile(String inputFile) {
// create readFile File object from string containing name of file
}

public void readFromFile() {
try {
if (readFile == null) {
System.err.println("Input file has not been set, call setInputFile method before calling openInputFile");
throw NullPointerException;
}

reader = new FileReader(readFile);

// read input file

} catch (FileNotFoundException ex) {...}
catch (NullPointerException ex) {...}
}
+ Observed Examples
ReferenceDescription
CVE-2007-3798Unchecked return value leads to resultant integer overflow and code execution.
CVE-2006-4447Program does not check return value when invoking functions to drop privileges, which could leave users with higher privileges than expected by forcing those functions to fail.
CVE-2006-2916Program does not check return value when invoking functions to drop privileges, which could leave users with higher privileges than expected by forcing those functions to fail.
+ Potential Mitigations

Phase: Requirements

Strategy: Language Selection

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

Choose languages with features such as exception handling that force the programmer to anticipate unusual conditions that may generate exceptions. Custom exceptions may need to be developed to handle unusual business-logic conditions. Be careful not to pass sensitive exceptions back to the user (CWE-209, CWE-248).

Phase: Implementation

Check the results of all functions that return a value and verify that the value is expected.

Effectiveness: High

Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment.

Phase: Implementation

If using exception handling, catch and throw specific exceptions instead of overly-general exceptions (CWE-396, CWE-397). Catch and handle exceptions as locally as possible so that exceptions do not propagate too far up the call stack (CWE-705). Avoid unchecked or uncaught exceptions where feasible (CWE-248).

Effectiveness: High

Using specific exceptions, and ensuring that exceptions are checked, helps programmers to anticipate and appropriately handle many unusual events that could occur.

Phase: 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. Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

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 you are expecting colors such as "red" or "blue."

Performing extensive input validation does not help with handling unusual conditions, but it will minimize their occurrences and will make it more difficult for attackers to trigger them.

Phase: Architecture and Design

If the program must fail, ensure that the it fails gracefully (fails closed). There may be a temptation to simply let the program fail poorly in cases such as low memory conditions, but an attacker may be able to assert control before the software has fully exited. Alternately, an uncontrolled failure could cause cascading problems with other downstream components; for example, the program could send a signal to a downstream process so the process immediately knows that a problem has occurred and has a better chance of recovery.

Phase: Architecture and Design

Use system limits, which should help to prevent resource exhaustion. However, the software should still handle low resource conditions since they may still occur.

+ Background Details

Many functions will return some value about the success of their actions. This will alert the program whether or not to handle any errors caused by that function.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory388Error Handling
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class703Failure to Handle Exceptional Conditions
Research Concepts (primary)1000
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ParentOfWeakness BaseWeakness Base252Unchecked Return Value
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base253Incorrect Check of Function Return Value
Research Concepts1000
ParentOfWeakness BaseWeakness Base273Improper Check for Dropped Privileges
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base296Improper Following of Chain of Trust for Certificate Validation
Research Concepts1000
ParentOfWeakness BaseWeakness Base297Improper Validation of Host-specific Certificate Data
Research Concepts1000
ParentOfWeakness BaseWeakness Base298Improper Validation of Certificate Expiration
Research Concepts1000
ParentOfWeakness BaseWeakness Base299Improper Check for Certificate Revocation
Research Concepts1000
ParentOfWeakness BaseWeakness Base354Improper Validation of Integrity Check Value
Research Concepts1000
ParentOfWeakness BaseWeakness Base394Unexpected Status Code or Return Value
Research Concepts (primary)1000
+ Relationship Notes

Sometimes, when a return value can be used to indicate an error, an unchecked return value is a code-layer instance of an application-layer failure to check for exceptional conditions. However, exceptional conditions may occur that are not communicated via return values, such as expiration of resources, values passed by reference, asynchronously modified data, sockets, etc.

+ Related Attack Patterns
CAPEC-IDAttack Pattern Name
(CAPEC Version: 1.4)
232Exploitation of Privilege/Trust
30Hijacking a Privileged Thread of Execution
234Hijacking a privileged process
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 7, "Program Building Blocks" Page 341. 1st Edition. Addison Wesley. 2006.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 1, "Exceptional Conditions," Page 22. 1st Edition. Addison Wesley. 2006.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 11: Failure to Handle Errors Correctly." Page 183. McGraw-Hill. 2010.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-03-03Internal CWE Team
New entry for reorganization of CWE-703.
Modifications
Modification DateModifierOrganizationSource
2009-07-27CWE Content TeamMITREInternal
updated Relationships
2009-12-28CWE Content TeamMITREInternal
updated Applicable Platforms, Likelihood of Exploit, Time of Introduction