The Java garbage collector is called to free unreferenced but as-yet unreleased memory. However, the garbage collector cannot free nonmemory resources such as open file descriptors and database connections. Consequently, failing to release such resources can lead to resource exhaustion attacks. In addition, programs can experience resource starvation while waiting for a finalizer to release resources such as Lock
or Semaphore
objects. This can occur because Java lacks any temporal guarantee of when finalizers execute other than "sometime before program termination." Finally, output streams may cache object references; such cached objects are not 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 If a program relies on finalize()
to release system resources , or if when there is confusion over which part of the program is responsible for releasing system resources, then there exists a possibility of a potential resource leak. In a busy system, there might be a time gap the delay before the finalize()
method finalizer is called for an object . An attacker might exploit this vulnerability to provides a window of vulnerability during which an attacker could induce a denial-of-service attack. The guideline OBJ08-J. Avoid using finalizers has more information on the demerits of using finalizers.
The Java garbage collector is called to free up unreleased memory. However, if the program relies on non-memory resources like file descriptors and database connections, unreleased resources might lead the program to prematurely exhaust its pool of resources. In addition, if the program uses resources like Lock
or Semaphore
, waiting for finalize()
to release the resources may result in resource starvation. Caching of object references in the output stream also implies that the objects will not be garbage collected unless the streams are closed promptly after use.
(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.
Note that on Windows systemsAlso note that on the Windows platform, attempts to delete open files fail silently . See FIO07(see FIO03-J. Do not create Remove temporary files in shared directoriesbefore termination for more information).
There is a similar rule for releasing concurrency locks: CON15-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 included.
Noncompliant Code Example (SQL Connection)
...
The problem of resource pool exhaustion is aggravated exacerbated in the case of database connections. Traditionally, Many database servers have allowed allow only a fixed number of connections, depending on configuration and licensing. Failing Consequently, failure to release database connections can result in rapid exhaustion of available connections. This noncompliant code example does not fails to close the connection if when an error occurs while executing during execution of the SQL statement or while 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
While being slightly better than the previous This noncompliant code example , this code is also noncompliant. Both rs
and stmt
might be null
and the clean-up attempts to address exhaustion of database connections by adding cleanup code in a finally
block. However, rs
, stmt
, or conn
could be null
, causing the code in the finally
block may result in 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()
might itself result in or the call to stmt.close()
might throw a SQLException
. Consequently, and so stmtconn.close()
will 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 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) {rs.close();} } catch (SQLException rs.close();e) { // Forward to }handler } finally { try { if (stmt != null) { stmt.close();} } }catch (SQLException e) { } // Forward finallyto {handler } conn.close();finally { } } } |
Noncompliant Code Example
This noncompliant code example opens a file, uses it, but does not explicitly close the 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
try {
if (conn != null) {conn.close();}
} catch (SQLException e) {
// Forward to handler
}
}
}
}
|
Compliant Solution (try
-with-resources)
This compliant solution uses the try
-with-resources construct, introduced in Java SE 7, to ensure that resources are released as required:This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, if a FileInputStream
object is instantiated, it will be closed as required.
Code Block | ||
---|---|---|
| ||
FileInputStream streamtry (Connection conn = nullgetConnection(); BufferedReader bufRead = null; String line; try { Statement streamstmt = new FileInputStream(fileNameconn.createStatement(); bufRead = new BufferedReader(new InputStreamReader(stream)); while((line = bufRead.readLine()) != null) ResultSet rs = stmt.executeQuery(sqlQuery)) { sendLineprocessResults(liners); } } catch (IOExceptionSQLException e) { // forwardForward to handler } finally { if(stream != null) { stream.close(); } } |
Risk Assessment
|
The try
-with-resources construct sends any SQLException
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 Connection
, Statement
, or ResultSet
), as well as any SQLException
thrown by processResults()
and any SQLException
generated by closing rs
, stmt
, or conn
are included.
Risk Assessment
Failure to explicitly release nonmemory system resources when they are no longer needed can Acquiring non-memory system resources and not releasing them explicitly may result in resource exhaustion.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
FIO04-J |
Low |
Probable |
Medium | P4 | L3 |
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.
...
Automated Detection
Although sound automated detection of this vulnerability is not feasible in the general case, many interesting cases can be soundly detected.
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.
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
...
...
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] [Class Object| http://java.sun.com/javase/6/docs/api/java/lang/Object.html]
\[[Goetz 06b|AA. Java References#Goetz 06b]\]
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE-405|http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)", [CWE-404|http://cwe.mitre.org/data/definitions/404.html] "Improper Resource Shutdown or Release", [CWE-459 |http://cwe.mitre.org/data/definitions/459.html] "Incomplete Cleanup," [CWE-770|http://cwe.mitre.org/data/definitions/770.html], "Allocation of Resources Without Limits or Throttling" |
CWE-404, Improper Resource Shutdown or Release |
Android Implementation Details
The compliant solution (try
-with-resources) is not yet supported at API level 18 (Android 4.3).
Bibliography
[API 2014] | |
The |
...
FIO05-J. Do not create multiple buffered wrappers on an InputStream 09. Input Output (FIO) FIO07-J. Do not create temporary files in shared directories