Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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, failing to release such non-memory resources can lead to resource exhaustion attacks. 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 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 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 DoS attack. Consequently, resources other than raw memory must be explicitly freed in non-finalizer nonfinalizer methods because of the unsuitability of using finalizers. See the rule MET12-J. Do not use finalizers for additional reasons to avoid the use of finalizers.

Note that on the Windows platform, attempts to delete open files fail silently. See rule FIO03-J. Remove temporary files before termination for more information.

Noncompliant Code Example (File Handle)

This noncompliant code example opens a file and uses it but fails to explicitly close the file.

Code Block
bgColor#FFcccc
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;
}

...

Code Block
bgColor#ccccff
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 (Java

...

SE 7

...

: try-with-resources)

This compliant solution uses the try-with-resources statement, introduced in Java 1.SE 7, to release all acquired resources, regardless of any exceptions that might occur.

Code Block
bgColor#ccccff
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. 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.

...

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 could be null, causing the code in the finally block to throw a NullPointerException.

...

In this noncompliant code example, the call to rs.close() might throw a SQLException. Consequently, stmt.close() is never called. This is a violation of rule ERR05-J. Do not let checked exceptions escape from a finally block.

...

Code Block
bgColor#ccccff
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) {
    try {
      rs.close();}
    } catch (SQLException e) {
      // forward to handler
  } finally {
   } finallytry {
      if (stmt != null) {
        try {
          stmt.close();}
      } catch (SQLException e) {
        // forward to handler
      } finally {
        if (conn != null) {
          try {
        if (conn != null) {conn.close();}
          } catch (SQLException e) {
            // forward to handler
          }
        }
      }
    }
  }
}

Compliant Solution (Java

...

SE 7

...

: try-with-resources)

This compliant solution uses the try-with-resources construct, introduced in Java 1.SE 7, to ensure that resources are released as required.

Code Block
bgColor#ccccff
try (Connection conn = getConnection();
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(sqlQuery)) {

    processResults(rs);
} catch (SQLException e) {
  // forward to handler
}

...

Failure to explicitly release non-memory nonmemory system resources when they are no longer needed can result in resource exhaustion.

...

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 Some static analysis tools can detect instances cases where there is leak of a socket resource or leak of a stream representing a file or other system resources.

...

CERT C Secure Coding Standard

FIO42-C. Ensure files are properly closed when they are no longer needed

CERT C++ Secure Coding Standard

FIO42-CPP. Ensure files are properly closed when they are no longer needed

MITRE CWE

CWE-404 ". Improper Resource Shutdown or Release" resource shutdown or release

 

CWE-459 ". Incomplete Cleanup" cleanup

 

CWE-770 ". Allocation of Resources Without Limits or Throttling" resources without limits or throttling

 

CWE-405 ". Asymmetric Resource Consumption resource consumption (Amplificationamplification) "

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f21f4369fb97767f-11538d3f-442d401b-a468914c-c4c73aa0227c72a056681f68"><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="3bc06a2052405215-8a51b9bd-4e2340b0-add4ad25-d5ba1d988ae92961813a0e27"><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="ae2350d98e4f928e-9b689975-42b04b8c-ac7f88ef-8e21d199b1fd4b3ef4991b21"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]]

The try-with-resources Statement

]]></ac:plain-text-body></ac:structured-macro>

...