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 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 the program relies on finalize() to release system resources , or when there is confusion over which part of the program is responsible for releasing system resources, then there exists a possibility for 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 induce a Denial of Service attack.

If there is unreleased memory, eventually the Java garbage collector will be called to free 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 it's pool of resources. In addition, if the program uses resources like Lock or Semaphore, waiting for finalize() to release the resources may lead to resource starvation.

Noncompliant Code Example

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.

Note that on Windows systems, attempts to delete open files fail silently (see 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:The worst form of non-compliance is not calling methods to release the resource at all. If files are opened, they must be explicitly closed when their work is done.

Code Block
bgColor#FFcccc

public Stringint processFile(String fileName)
                       throws IOException, FileNotFoundException {
     FileInputStream stream = new FileInputStream(fileName);
  BufferedReader bufRead =
  props.load    new BufferedReader(new InputStreamReader(stream));
  String line;
  stream.close(while ((line = bufRead.readLine()) != null) {
    sendLine(line);
  }
   return props1;
}

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
bgColor#ccccff
try {
  final FileInputStream stream = new FileInputStream(fileName);
  try {
      System.setSecurityManager(null);
} catch (SecurityException se) { System.out.println("SecurityManager is already set\!"); }

Any Java program (bean, servlet or application) can instantiate a SecurityManager. However, for applications designed to run locally, an explicit flag must be set to enforce the SecurityManager policy. In the noncompliant example highlighted next, this flag has not been used which circumvents all SecurityManager checks.

Code Block
bgColor#FFcccc

java application

Compliant Solution

This compliant solution demonstrates how a custom SecurityManager class called CustomSecurityManager can be activated by invoking its constructor with a password. Various check methods defined within the class can then be invoked to perform access checks. Alternatively, to use the default security manager change the active instance to java.lang.SecurityManager.

Code Block
bgColor#ccccff

try {
      System.setSecurityManager(new CustomSecurityManager("password here"));
      SecurityManager sm = System.getSecurityManager();
      if(sm \!= null) {  //check if file can be read
        FilePermission perm = new FilePermission("/temp/tempFile", "read");
        sm.checkPermission(perm);
      }
} catch (SecurityException se) { System.out.println("SecurityManager is already set\!"); }

For local applications, the security manager can be installed using the flags as shown next. Note that the setSecurityManager method must be replaced by getSecurityManager in this case since the manager has already been installed using the command line flag.

Code Block
bgColor#ccccff

java \-Djava.security.manager \-Djava.security.policy=policyURL LocalJavaApp

By default, the SecurityManager checkPermission method(s) forward all calls to the java.security.Accesscontroller.checkPermission. Sometimes it is required to perform checks against a different context than the currently executing threads' context. This can be done using the checkPermission(Permission perm, Object context) method which takes an extra argument (like AccessControlContext) as the context of the desired thread.

Wiki Markup
The document \[\[Policy 02\|AA. Java References#Policy 02\]\] discusses writing policy files in depth.

Risk Assessment

Running Java code without a Security Manager being set means that there is no security at all.
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| SEC30-J | high | probable | low | P18 | L1 |

Automated Detection

TODO

Related Vulnerabilities

Wiki Markup
Search for vulnerabilities resulting from the violation of this rule on the \[CERT website\|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+SEC30-J\].

References

Wiki Markup
\[\[API 06\|AA. Java References#API 06\]\] \[Class SecurityManager\|http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html\]
\[\[Policy 02\|AA. Java References#Policy 02\]\]
\[\[Pistoia 04\|AA. Java References#Pistoia 04\]\] Section 7.4, The Security Manager
\[\[Gong 03\|AA. Java References#Gong 03\]\] Section 6.1, Security Manager


    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
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. 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 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
bgColor#FFcccc
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) { /* Forward to handler */ }
}

Noncompliant Code Example

This noncompliant code example 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 to throw a NullPointerException.

Code Block
bgColor#FFcccc
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(); conn.close();
}

Noncompliant Code Example

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

Code Block
bgColor#FFcccc
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();
  } if (conn !=null) {
       conn.close();
    }
}

Compliant Solution

This compliant solution ensures that resources are released as required:

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) {rs.close();}
  } catch (SQLException e) {
    // Forward to handler
  } finally {
    try {
      if (stmt != null) {stmt.close();}
    } catch (SQLException e) {
      // Forward to handler
    } finally {
      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:

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
}

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 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 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
Include Page
CodeSonar_V
CodeSonar_V

JAVA.ALLOC.LEAK.NOTCLOSED
JAVA.ALLOC.LEAK.NOTSTORED

Closeable Not Closed (Java)
Closeable Not Stored (Java)

Coverity7.5

ITERATOR
JDBC_CONNECTION
RESOURCE_LEAK

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
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
Include Page
SonarQube_V
SonarQube_V
S2095Implemented

Related Guidelines

SEI CERT C Coding Standard

FIO22-C. Close files before spawning processes

SEI CERT C++ Coding Standard

FIO51-CPP. Close files when they are no longer needed

MITRE CWE

CWE-404, Improper Resource Shutdown or Release
CWE-405, Asymmetric Resource Consumption (Amplification)
CWE-459, Incomplete Cleanup
CWE-770, Allocation of Resources without Limits or Throttling

Android Implementation Details

The compliant solution (try-with-resources) is not yet supported at API level 18 (Android 4.3).

Bibliography

[API 2014]

Class Object

[Goetz 2006b]


[J2SE 2011]

The try-with-resources Statement


...

Image Added Image Added Image Added Wiki Markup\---\- \[\!CERT Java Secure Coding Standard^button_arrow_left.png\|width=32,height=32\!\|SEC07-J. Minimize accessibility\]      \[\!CERT Java Secure Coding Standard^button_arrow_up.png\|width=32,height=32\!\|00. Security (SEC)\]      \[\!CERT Java Secure Coding Standard^button_arrow_right.png\|width=32,height=32\!\|SEC31-J. Never grant AllPermission to untrusted code\]