Versions Compared

Key

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

A Java OutofMemoryError occurs when the program attempts to use more heap space than is available. Among other causes, this error may result from the following:

Some of these causes are platform-dependent and difficult to anticipate. Others are fairly easy to anticipate, such as reading data from a file, are fairly easy to anticipate. As a result, programs must not accept untrusted input in a manner that can cause the program to exhaust memory.

...

This noncompliant code example reads lines of text from a file and adds each one to a vector until a line with the word "quit" is encountered.:

Code Block
bgColor#FFcccc

class ReadNames {
  private Vector<String> names = new Vector<String>();
  private final InputStreamReader input;
  private final BufferedReader reader;

  public ReadNames(String filename) throws IOException {
    this.input = new FileReader(filename);
    this.reader = new BufferedReader(input);
  }

  public void addNames() throws IOException {
    try {
      String newName;
      while (((newName = reader.readLine()) != null) &&
             !(newName.equalsIgnoreCase("quit"))) {
        names.addElement(newName);
        System.out.println("adding " + newName);
      }
    } finally {
      input.close();
    }
  }

  public static void main(String[] args) throws IOException {
    if (args.length != 1) {
      System.out.println("Arguments: [filename]");
      return;
    }
    ReadNames demo = new ReadNames(args[0]);
    demo.addNames();
  }
}

Wiki MarkupThe code places no upper bounds on the memory space required to execute the program. Consequently, the program can easily exhaust the available heap space in two ways. First, an attacker can supply arbitrarily many lines in the file, causing the vector to grow until memory is exhausted. Second, an attacker can simply supply an arbitrarily long line, causing the {{readLine()}} method to exhaust memory. According to the Java API documentation \[[API 2006|AA. References#API 06]\], the {{BufferedReader.readLine()}} The code places no upper bounds on the memory space required to execute the program. Consequently, the program can easily exhaust the available heap space in two ways. First, an attacker can supply arbitrarily many lines in the file, causing the vector to grow until memory is exhausted. Second, an attacker can simply supply an arbitrarily long line, causing the readLine() method to exhaust memory. According to the Java API documentation [API 2014], the BufferedReader.readLine() method

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Any code that uses this method is susceptible to a resource exhaustion attack because the user can enter a string of any length.

Compliant Solution (

...

Limited File Size)

This compliant solution imposes a limit on the size of the file being read. This The limit is accomplished set with the Files.size() method, which is new to was introduced in Java SE 7. If the file is within the limit, we can assume the standard readLine() method will not exhaust memory, nor will memory be exhausted by the while loop.

Code Block
bgColor#ccccff

class ReadNames {
  // ... Other methods and variables

  public static final int fileSizeLimit = 1000000;

  public ReadNames(String filename) throws IOException {
    long size = Files.size( Paths.get( filename));
    if (size > fileSizeLimit) {
      throw new IOException("File too large");
    } else if (size == 0L) {
      throw new IOException("File size cannot be determined, possibly too large");
    }
    this.input = new FileReader(filename);
    this.reader = new BufferedReader(input);
  }

  // ...other methods
}

Compliant Solution (Limited Length Input)

This compliant solution imposes limits both on the length of each line and on the total number of items to add to the vector. (It does not depend on any Java SE 7 or later features.)

Code Block
bgColor#ccccff

class ReadNames {
  // ... otherOther methods and variables

  public static String readLimitedLine(Reader reader, int limit) 
                                       throws IOException {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < limit; i++) {
      int c = reader.read();
      if (c == -1) {
        return null;
      ((sb.length() > 0) ? sb.toString() : null);
      }
      if (((char) c == '\n') || ((char) c == '\r')) {
        break;
      }
      sb.append((char) c);
    }
    return sb.toString();
  }

  public static final int lineLengthLimit = 1024;
  public static final int lineCountLimit = 1000000;

  public void addNames() throws IOException {
    try {
      String newName;
      for (int i = 0; i < lineCountLimit; i++) {
        newName = readLimitedLine(reader, lineLengthLimit);
        if (newName == null || newName.equalsIgnoreCase("quit")) {
          break;
        }
        names.addElement(newName);
        System.out.println("adding " + newName);
      }
    } finally {
      input.close();
    }
  }

}

...

Noncompliant Code Example

...

In a server-class machine using a parallel garbage collector, the default initial and maximum heap sizes are as follows for Java SE 6 \ [[Sun 2006|AA. References#Sun 06]\]:

  • initial Initial heap size: larger of 1/64 of the machine's physical memory or some reasonable minimum.
  • maximum Maximum heap size: smaller of 1/4 of the physical memory or 1GB.

This noncompliant code example requires more memory on the heap than is available by default.:

Code Block
bgColor#FFcccc

/** Assuming the heap size as 512 MB 
 *   (calculated as 1/4th4 of 2 GB2GB RAM = 512 MB512MB)
 *  Considering long values being entered (64 bits each, 
 *  the max number of elements would be 512 MB/64bits512MB/64 bits = 
 *  67108864)
 */
public class ReadNames {
  // Accepts unknown number of records
  Vector<Long> names = new Vector<Long>(); 
  long newID = 0L;
  int count = 67108865;
  int i = 0;
  InputStreamReader input = new InputStreamReader(System.in);
  Scanner reader = new Scanner(input);

  public void addNames() {
    try {
      do {
        // Adding unknown number of records to a list
        // The user can enter more IDs than the heap can support and,
        // as a result, exhaust the heap. Assume that the record ID
        // is a 64 -bit long value
        System.out.print("Enter recordID (To quit, enter -1): ");
        newID = reader.nextLong();

        names.addElement(newID);
        i++;
      } while (i < count || newID != -1);
    } finally {
      input.close();
    }
  }

  public static void main(String[] args) {
    ReadNames demo = new ReadNames();
    demo.addNames();
  }
}

...

A simple compliant solution is to reduce the number of names to read.:

Code Block
bgColor#ccccff

  // ...
  int count = 10000000;
  // ...

Compliant Solution

...

The {{OutOfMemoryError}} can be avoided by ensuring the absence of infinite loops, memory leaks, and unnecessary object retention. When memory requirements are known ahead of time, the heap size can be tailored to fit the requirements using the following runtime parameters \ [[Java 2006|AA. References#Java 06]\]:

java -Xms<initial heap size> -Xmx<maximum heap size>

For example,

java -Xms128m -Xmx512m ShowHeapErrorReadNames

Here the initial heap size is set to 128 MB 128MB and the maximum heap size to 512MB.

...

Assuming infinite heap space can result in DoS denial of service.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC05-J

low

Low

probable

Probable

medium

Medium

P4

L3

Related Vulnerabilities

The Apache Geronimo bug described by GERONIMO-4224 results in an OutOfMemoryError exception thrown by the WebAccessLogViewer when the access log file size is too large.

Automated Detection

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.ALLOC.LEAK.NOTSTORED
JAVA.CLASS.UI

Closeable Not Stored (Java)
Inefficient Instantiation (Java)


Related Guidelines

SEI CERT C

Secure

Coding Standard

MEM11-C. Do not assume infinite heap space

SEI CERT C++

Secure [

Coding Standard

VOID MEM12-CPP. Do not assume infinite heap space

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="98ff85e3-3035-444e-9331-9dc2f8cacc57"><ac:plain-text-body><![CDATA[

ISO/IEC TR 24772:2010

http://www.aitcnet.org/isai/]

Resource

Resource Exhaustion [XZP]

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

MITRE CWE

CWE-400

.

, Uncontrolled

resource consumption

Resource Consumption ("

resource exhaustion

Resource Exhaustion")

 


CWE-770

.

, Allocation of

resources

Resources without

limits

Limits or

throttling

Throttling

Bibliography

[API 2014]

Class ObjectInputStream
Class ObjectOutputStream

[Java 2006]

Java—The Java Application Launcher, Syntax for Increasing the Heap Size

[Oracle 2015]Tuning the Java Runtime System

[SDN 2008]

Serialization FAQ

[Sun 2006]

Garbage Collection Ergonomics, Default Values

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b52c736a-3670-4d8c-8150-463ddf3d1bc0"><ac:plain-text-body><![CDATA[

[[API 2006

AA. References#API 06]]

Class ObjectInputStream and ObjectOutputStream

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3419b39c-a5ae-4746-abb5-04a024f11b26"><ac:plain-text-body><![CDATA[

[[Java 2006

AA. References#Java 06]]

[java – The Java application launcher

http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html], Syntax for increasing the heap size

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c6cc2c2f-3e9c-4d89-9430-b60baf9eb75e"><ac:plain-text-body><![CDATA[

[[SDN 2008

AA. References#SDN 08]]

[Serialization FAQ

http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp]

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9b170920-e642-4e0f-b40f-2f698638c3ce"><ac:plain-text-body><![CDATA[

[[Sun 2003

AA. References#Sun 03]]

Chapter 5, Tuning the Java Runtime System, [Tuning the Java Heap

http://docs.sun.com/source/817-2180-10/pt_chap5.html#wp57027]

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="50f00ea0-50f4-460c-aa4c-1675b8a47c35"><ac:plain-text-body><![CDATA[

[[Sun 2006

AA. References#Sun 06]]

[Garbage Collection Ergonomics

http://java.sun.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html ], Default values

for the Initial and Maximum Heap Size

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


...

Image Removed      49. Miscellaneous (MSC)      Image Added Image Added