CWE

Common Weakness Enumeration

A Community-Developed Dictionary of Software Weakness Types

CWE/SANS Top 25 Most Dangerous Software Errors Common Weakness Scoring System
Common Weakness Risk Analysis Framework
Home > CWE List > CWE- Individual Dictionary Definition (2.7)  

Presentation Filter:

CWE-404: Improper Resource Shutdown or Release

 
Improper Resource Shutdown or Release
Weakness ID: 404 (Weakness Base)Status: Draft
+ Description

Description Summary

The program does not release or incorrectly releases a resource before it is made available for re-use.

Extended Description

When a resource is created or allocated, the developer is responsible for properly releasing the resource as well as accounting for all potential paths of expiration or invalidation, such as a set period of time or revocation.

+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect

Technical Impact: DoS: resource consumption (other); Varies by context

Most unreleased resource issues result in general software reliability problems, but if an attacker can intentionally trigger a resource leak, the attacker might be able to launch a denial of service attack by depleting the resource pool.

Technical Impact: Read application data

When a resource containing sensitive information is not correctly shutdown, it may expose the sensitive data in a subsequent allocation.

+ Likelihood of Exploit

Low to Medium

+ Detection Methods

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.

Resource clean up errors might be detected with a stress-test by calling the software simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

Effectiveness: Moderate

Manual Dynamic Analysis

Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the program under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself.

+ Demonstrative Examples

Example 1

The following method never closes the file handle it opens. The Finalize() method for StreamReader eventually calls Close(), but there is no guarantee as to how long it will take before the Finalize() method is invoked. In fact, there is no guarantee that Finalize() will ever be invoked. In a busy environment, this can result in the VM using up all of its available file handles.

(Bad Code)
Example Language: Java 
private void processFile(string fName) {
StreamWriter sw = new StreamWriter(fName);
string line;
while ((line = sr.ReadLine()) != null){
processLine(line);
}
}

Example 2

This code attempts to open a connection to a database and catches any exceptions that may occur.

(Bad Code)
Example Language: Java 
try {
Connection con = DriverManager.getConnection(some_connection_string);
}
catch ( Exception e ) {
log( e );
}

If an exception occurs after establishing the database connection and before the same connection closes, the pool of database connections may become exhausted. If the number of available connections is exceeded, other users cannot access this resource, effectively denying access to the application.

Example 3

Under normal conditions the following C# code executes a database query, processes the results returned by the database, and closes the allocated SqlConnection object. But if an exception occurs while executing the SQL or processing the results, the SqlConnection object is not closed. If this happens often enough, the database will run out of available cursors and not be able to execute any more SQL queries.

(Bad Code)
Example Language: C# 
...
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
...

Example 4

The following C function does not close the file handle it opens if an error occurs. If the process is long-lived, the process can run out of file handles.

(Bad Code)
Example Language:
int decodeFile(char* fName) {
char buf[BUF_SZ];
FILE* f = fopen(fName, "r");
if (!f) {
printf("cannot open %s\n", fName);
return DECODE_FAIL;
}
else {
while (fgets(buf, BUF_SZ, f)) {
if (!checkChecksum(buf)) {
return DECODE_FAIL;
}
else {
decodeBlock(buf);
}
}
}
fclose(f);
return DECODE_SUCCESS;
}

Example 5

In this example, the program does not use matching functions such as malloc/free, new/delete, and new[]/delete[] to allocate/deallocate the resource.

(Bad Code)
Example Language: C++ 
class A {
void foo();
};
void A::foo(){
int *ptr;
ptr = (int*)malloc(sizeof(int));
delete ptr;
}

Example 6

In this example, the program calls the delete[] function on non-heap memory.

(Bad Code)
Example Language: C++ 
class A{
void foo(bool);
};
void A::foo(bool heap) {
int localArray[2] = {
11,22
};
int *p = localArray;
if (heap){
p = new int[2];
}
delete[] p;
}
+ Observed Examples
ReferenceDescription
Does not shut down named pipe connections if malformed data is sent.
Sockets not properly closed when attacker repeatedly connects and disconnects from server.
Return values of file/socket operations not checked, allowing resultant consumption of file descriptors.
+ 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.

For example, languages such as Java, Ruby, and Lisp perform automatic garbage collection that releases memory for objects that have been deallocated.

Phase: Implementation

It is good practice to be responsible for freeing all resources you allocate and to be consistent with how and where you free memory in a function. If you allocate memory that you intend to free upon completion of the function, you must be sure to free the memory at all exit points for that function including error conditions.

Phase: Implementation

Memory should be allocated/freed using matching functions such as malloc/free, new/delete, and new[]/delete[].

Phase: Implementation

When releasing a complex object or structure, ensure that you properly dispose of all of its member components, not just the object itself.

+ Weakness Ordinalities
OrdinalityDescription

Improper release or shutdown of resources can be primary to resource exhaustion, performance, and information confidentiality problems to name a few.

Improper release or shutdown of resources can be resultant from improper error handling or insufficient resource tracking.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Development Concepts699
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory399Resource Management Errors
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class664Improper Control of a Resource Through its Lifetime
Research Concepts (primary)1000
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory7522009 Top 25 - Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory857CERT Java Secure Coding Section 12 - Input Output (FIO)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory876CERT C++ Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory877CERT C++ Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory882CERT C++ Secure Coding Section 14 - Concurrency (CON)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory892SFP Cluster: Resource Management
Software Fault Pattern (SFP) Clusters (primary)888
PeerOfWeakness ClassWeakness Class405Asymmetric Resource Consumption (Amplification)
Research Concepts1000
ParentOfWeakness VariantWeakness Variant262Not Using Password Aging
Research Concepts1000
ParentOfWeakness BaseWeakness Base263Password Aging with Long Expiration
Research Concepts1000
ParentOfWeakness VariantWeakness Variant299Improper Check for Certificate Revocation
Research Concepts1000
ParentOfWeakness BaseWeakness Base459Incomplete Cleanup
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base619Dangling Database Cursor ('Cursor Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base763Release of Invalid Pointer or Reference
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base772Missing Release of Resource after Effective Lifetime
Research Concepts (primary)1000
PeerOfWeakness VariantWeakness Variant239Failure to Handle Incomplete Element
Research Concepts1000
+ Relationship Notes

Overlaps memory leaks, asymmetric resource consumption, malformed input errors.

+ Functional Areas
  • Non-specific
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERImproper resource shutdown or release
7 Pernicious KingdomsUnreleased Resource
OWASP Top Ten 2004A9Denial of Service
CERT C Secure CodingFIO42-CEnsure files are properly closed when they are no longer needed
CERT Java Secure CodingFIO04-JRelease resources when they are no longer needed
CERT C++ Secure CodingMEM39-CPPResources allocated by memory allocation functions must be released using the corresponding memory deallocation function
CERT C++ Secure CodingFIO42-CPPEnsure files are properly closed when they are no longer needed
CERT C++ Secure CodingCON02-CPPUse lock classes for mutex management
+ References
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 8: C++ Catastrophes." Page 143. McGraw-Hill. 2010.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
Externally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01CigitalExternal
updated Time_of_Introduction
2008-08-15VeracodeExternal
Suggested OWASP Top Ten 2004 mapping
2008-09-08MITREInternal
updated Description, Relationships, Other_Notes, Taxonomy_Mappings
2008-10-14MITREInternal
updated Relationships
2008-11-24MITREInternal
updated Relationships, Taxonomy_Mappings
2009-01-12MITREInternal
updated Common_Consequences, Likelihood_of_Exploit, Other_Notes, Potential_Mitigations, Relationship_Notes, Relationships, Weakness_Ordinalities
2009-03-10MITREInternal
updated Potential_Mitigations
2009-05-27MITREInternal
updated Description, Relationships
2009-07-27MITREInternal
updated Demonstrative_Examples, Related_Attack_Patterns
2009-10-29MITREInternal
updated Other_Notes
2010-02-16MITREInternal
updated Potential_Mitigations, Relationships
2010-06-21MITREInternal
updated Detection_Factors, Potential_Mitigations
2010-12-13MITREInternal
updated Demonstrative_Examples
2011-03-29MITREInternal
updated Weakness_Ordinalities
2011-06-01MITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-06-27MITREInternal
updated Common_Consequences
2011-09-13MITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11MITREInternal
updated Demonstrative_Examples, References, Relationships, Taxonomy_Mappings
2014-02-18MITREInternal
updated Demonstrative_Examples
2014-06-23MITREInternal
updated Related_Attack_Patterns
Page Last Updated: June 23, 2014