A program may leak resources when it relies on finalize()
to release system resources or when there is confusion over which part of the program is responsible for releasing system resources. In a busy system, the delay before the finalize()
method is called for an object provides a window of vulnerability during which an attacker could induce a denial-of-service attack. See the rule MET18-J. Do not use finalizers for additional reasons to avoid the use of finalizers.
The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the Java garbage collector cannot free non-memory nonmemory resources such as open file descriptors and database connections. Consequently, programs that fail failing to release such non-memory resources can prematurely exhaust their pool of such resourceslead to resource exhaustion attacks. In addition, programs can experience resource starvation while waiting for finalize()
a finalizer to release resources such as Lock
or Semaphore
objects. This can occur because Java lacks any temporal guarantee of when finalize()
methods will finalizers execute , other than "sometime before program termination." Finally, output streams may cache object references; such cached objects will are not be garbage-collected until after the output stream is closed. Consequently, output streams should be closed promptly after use.
A program may leak resources when it relies on finalizers to release system resources or when there is confusion over which part of the program is responsible for releasing system resources. In a busy system, the delay before the finalizer is called for an object provides a window of vulnerability during which an attacker could induce a denial-of-service (DoS) attack. Consequently, resources other than raw memory must be explicitly freed in nonfinalizer methods because of the unsuitability of using finalizers. See MET12-J. Do not use finalizers for additional reasons to avoid the use of finalizers.
Also note Note that on the Windows platformsystems, attempts to delete open files fail silently . See rule FIO07(see FIO03-J. Do not create Remove temporary files in shared directoriesbefore termination for more information).
See also the related locking rule LCK08-J. Ensure actively held locks are released on exceptional conditions.
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it but fails to explicitly close the file:
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName)
throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
|
Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, the FileInputStream
object is closed as required.
Code Block | ||
---|---|---|
| ||
try {
final FileInputStream stream = new FileInputStream(fileName);
try {
final BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Forward to handler
}
}
}
} catch (IOException e) {
// Forward to handler
}
|
Compliant Solution (try
-with-resources)
This compliant solution uses the try
-with-resources statement, introduced in Java SE 7, to release all acquired resources regardless of any exceptions that might occur:
Code Block | ||
---|---|---|
| ||
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// Forward to handler
}
|
The try
-with-resources construct sends any IOException
to the catch
clause, where it is forwarded to an exception handler. Exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
), as well as any IOException
thrown during execution of the while
loop and any IOException
generated by closing bufRead
or stream
, are includedResources other than raw memory must be explicitly freed in non-finalizer methods, due to the unsuitability of using finalizers.
Noncompliant Code Example (SQL Connection)
The problem of resource pool exhaustion is aggravated exacerbated in the case of database connections. Many database servers allow only a fixed number of connections, depending on configuration and licensing. Consequently, failure to release database connections can result in rapid exhaustion of available connections. This noncompliant code example fails to close the connection when an error occurs during execution of the SQL statement or during processing of the results.:
Code Block | ||
---|---|---|
| ||
public void getResults(String sqlQuery) { try { Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery); processResults(rs); stmt.close(); conn.close(); } catch (SQLException e) { /* forwardForward to handler */ } } |
Noncompliant Code Example
This noncompliant code example attempts to address exhaustion of database connections by adding clean-up cleanup code in a finally
block. However, either or both of rs
and , stmt
, or conn
could be null
, causing the code in the finally
block to throw a NullPointerException
.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { // forwardForward to handler } finally { rs.close(); stmt.close(); conn.close(); } |
Noncompliant Code Example
In this noncompliant code example, the call to rs.close()
could throw an SQLException
; consequently, stmt or the call to stmt.close()
might throw a SQLException
. Consequently, conn.close()
would is never be calledcalled, which violates ERR05-J. Do not let checked exceptions escape from a finally block.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forwardForward to handler } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn !=null) { conn.close(); } } |
Compliant Solution
This compliant solution ensures that resources are released as required.:
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forwardForward to handler } finally { try { if (rs != null) { try { rs.close();} } catch (SQLException e) { // forwardForward to handler } finally { }try finally { if (stmt != null) { try { stmt.close();} } catch (SQLException e) { // forwardForward to handler } finally { if (conn != null) { try { if (conn != null) {conn.close();} } catch (SQLException e) { // forwardForward to handler } } } } } } |
Compliant Solution (
...
try
-with-resources)
This compliant solution uses the try
-with-resource resources construct, introduced in Java 1.SE 7, to ensure that resources are released as required.:
Code Block | ||
---|---|---|
| ||
try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery)) { processResults(rs); } catch (SQLException e) { // forwardForward to handler } |
The try
-with-resource resources construct will send sends any SQLException
to the catch
clause, where it gets is forwarded to an exception handler. This includes exceptions Exceptions generated during the allocation of resources (that is, the creation of the Connection
, Statement
, or ResultSet
. It also includes ), as well as any SQLException
thrown by processResults()
. Finally, it includes and any SQLException
generated by closing rs
, stmt
, or conn
.
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it, but fails to explicitly close the file handle.
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName) throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
|
Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, the FileInputStream
object is closed as required (if it was created in the first place).
Code Block | ||
---|---|---|
| ||
FileInputStream stream = null;
BufferedReader bufRead = null;
try {
stream = new FileInputStream(fileName);
bufRead = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// forward to handler
}
}
}
|
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resources statement, introduced in Java 1.7, to release all acquired resources, regardless of any exceptions that might occur.
Code Block | ||
---|---|---|
| ||
try (FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} catch (IOException e) {
// forward to handler
}
|
The try-with-resource construct will send any IOException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
. It also includes any IOException
thrown during the while loop. Finally, it includes any IOException
generated by closing bufRead
or stream
.
are included.
Risk Assessment
Failure to explicitly release non-memory nonmemory system resources when they are no longer needed can result in resource exhaustion.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
FIO04-J |
Low |
Probable |
Medium | P4 | L3 |
Automated Detection
Although sound automated detection of this this vulnerability is not feasible in the general case, many interesting cases can be soundly detected.
The Coverity Prevent Version 5.0 RESOURCE_LEAK checker can detect instances where Some static analysis tools can detect cases in which there is leak of a socket resource or leak of a stream representing a file or other system resources.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as FIO42-C. Ensure files are properly closed when they are no longer needed.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.ALLOC.LEAK.NOTCLOSED | Closeable Not Closed (Java) | ||||||
Coverity | 7.5 | ITERATOR | Implemented | ||||||
Parasoft Jtest |
| CERT.FIO04.LEAKS CERT.FIO04.CIO CERT.FIO04.CCR | Ensure resources are deallocated Close input and output resources in "finally" blocks Close all "java.io.Closeable" resources in a "finally" block | ||||||
SonarQube |
| S2095 | Implemented |
Related Guidelines
...
Related Guidelines
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f5445ad9-c54b-4b7f-891a-4644d23d69a6"><ac:plain-text-body><![CDATA[
[[MITRE 2009
AA. Bibliography#MITRE 09]]
[CWE-405
Asymmetric Resource Consumption (Amplification) |
]]></ac:plain-text-body></ac:structured-macro>
459, Incomplete Cleanup |
, Allocation of Resources |
without Limits or Throttling |
Bibliography
Android Implementation Details
The compliant solution (try
-with-resources) is not yet supported at API level 18 (Android 4.3).
Bibliography
[API 2014] | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ed45a601-36f5-4e0f-9be8-a12265d142ab"><ac:plain-text-body><![CDATA[
[[API 2006
AA. Bibliography#API 06]]
[Class Object
http://java.sun.com/javase/6/docs/api/java/lang/Object.html]
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4ee91c8a-8bc5-4f6d-aa1c-d4a1ef38ce37"><ac:plain-text-body><![CDATA[
[[Goetz 2006b
AA. Bibliography#Goetz 06b]]
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4bcd55b8-bc8d-48bc-a052-906c8f8a53db"><ac:plain-text-body><![CDATA[
[[J2SE 2011
The |
]]></ac:plain-text-body></ac:structured-macro>
...
FIO05-J. Do not create multiple buffered wrappers on a single InputStream 12. Input Output (FIO) FIO07-J. Do not create temporary files in shared directories