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 resources such as file descriptors and database connections. Consequently, programs that fail to release such non-memory resources can prematurely exhaust their pool of such resources. In addition, programs can experience resource starvation while waiting for finalize()
to release resources such as Lock
or Semaphore
objects. This can occur because Java lacks any temporal guarantee of when finalize()
methods will execute, other than "sometime before program termination." Finally, output streams may cache object references; such cached objects will not be garbage collected until after the output stream is closed. Consequently, output streams should be closed promptly after use.
Also note that on the Windows platform, attempts to delete open files fail silently. See rule FIO07-J. Do not create temporary files in shared directories for more information.
See also the related locking rule LCK08-J. Ensure actively held locks are released on exceptional conditions.
Resources 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 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.
public void getResults(String sqlQuery) { try { Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery); processResults(rs); stmt.close(); } catch (SQLException e) { /* forward to handler */ } }
Noncompliant Code Example
This noncompliant code example attempts to address exhaustion of database connections by adding clean-up code in a finally block. However, either or both of rs
and stmt
could be null
, causing the code in the finally block to throw a NullPointerException
.
Statement stmt = null; ResultSet rs = null Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { // forward to handler } finally { rs.close(); stmt.close(); }
Noncompliant Code Example
In this noncompliant code example, the call to rs.close()
could throw an SQLException
; consequently, stmt.close()
would never be called.
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } }
Compliant Solution
This compliant solution ensures that resources are released as required.
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { try { if (rs != null) { rs.close(); } } finally { try { if (stmt != null) { stmt.close(); } } finally { conn.close(); } } }
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resource construct, introduced in Java 1.7, to ensure that resources are released as required.
try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery)) { processResults(rs); } catch (SQLException e) { // forward to handler }
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it, but fails to explicitly close the file handle.
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).
FileInputStream stream = null; BufferedReader bufRead = null; String line; try { stream = new FileInputStream(fileName); bufRead = new BufferedReader(new InputStreamReader(stream)); while ((line = bufRead.readLine()) != null) { sendLine(line); } } catch (IOException e) { // forward to handler } finally { if (stream != null) { stream.close(); } }
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.
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 }
Risk Assessment
Failure to explicitly release non-memory system resources when they are no longer needed can result in resource exhaustion.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
FIO06-J |
low |
probable |
medium |
P4 |
L3 |
Automated Detection
Although sound automated detection of 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 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.
This rule appears in the C++ Secure Coding Standard as FIO42-CPP. Ensure files are properly closed when they are no longer needed.
Bibliography
[[API 2006]] Class Object
[[Goetz 2006b]]
[[J2SE 2011]] The try-with-resources Statement
[[MITRE 2009]] CWE-405 "Asymmetric Resource Consumption (Amplification)", CWE-404 "Improper Resource Shutdown or Release", CWE-459 "Incomplete Cleanup," CWE-770, "Allocation of Resources Without Limits or Throttling"
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