Versions Compared

Key

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

A Java OutofMemoryError occurs if infinite when the program attempts to use more heap space than is assumed, making the program crash. This error can be generated due to the following possible reasonsavailable. Among other causes, this error may result from the following:

  • A memory leak (see MSC04-J. Do not leak memory)
  • An infinite loop
  • The program requires more memory than is present by default in the heapLimited amounts of default heap memory available
  • Incorrect implementation of common data structures (such as hash tables, vectors etc, and so on)

Non Compliant Code Example 1

This example uses unlimited amount of memory due to which the program can easily exhaust the heap.

Some of these causes are platform-dependent and difficult to anticipate. Others, 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.

Noncompliant Code Example (readLine())

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:A heap error will be generated if the heap is continued to be accessed even if there is no memory left in the heap.

Code Block
bgColor#FFcccc

public class ShowHeapErrorReadNames {

   private Vector<String> names = new Vector<String>();
  private final InputStreamReader input;
  private final StringBufferedReader newName=nullreader;

  public ReadNames(String filename) throws IOException InputStreamReader {
    this.input = new InputStreamReaderFileReader(System.infilename);
    BufferedReader this.reader = new BufferedReader(input);

  }

  public void addNames() throws IOException {
    	dotry {
      		//adding unknown number of records to a list
    		//the user can enter as much data as he wants and exhaust the heap
    		System.out.print(" To quit, enter \"quit\"\nEnter record: "String newName;
      while (((newName = reader.readLine()) != null) &&
             !(newName.equalsIgnoreCase("quit"))) {
        names.addElement(newName);
        System.out.println("adding " + newName);
      }
    } finally {
      input.close();
    }
  }

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

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. The limit is set with the Files.size() method, which 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  			//names are continued to be added without bothering about the size on the heap== 0L) {
      throw new IOException("File size cannot be determined, possibly too large");
    }
    this.input = new FileReader(filename);
   			names.addElement(newName this.reader = new BufferedReader(input);
  }
}

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 {
  // ... Other methods and 		}variables

  public 			} catch (IOException e) {
   			}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) {
   System.out.println(newName);

     return ((sb.length() > 0) ? sb.toString() : null);
      	}
      if (((char)  while (!newName.equalsIgnoreCase("quit")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 main(String[] args)addNames() throws IOException {
    try {
      String newName;
      for ShowHeapError(int demoi = new ShowHeapError(0; i < lineCountLimit; i++) {
        newName = readLimitedLine(reader, lineLengthLimit);
         demo.addNames();
if (newName == null || newName.equalsIgnoreCase("quit")) {
          break;
        }
}

Compliant solution 1

To handle this problem, where the data structure size is so big that the heap gets exhausted, the user should consider using databases, where the record will get written on to the disk. Hence, this structure will never outgrow the heap.

In the above example, the user can re-use a single Long variable where the input gets stored and write that value into a simple database, containing a table User with a field userID and any other required fields. This will prevent the heap to get exhausted.

Non Compliant Code Example 2

Wiki Markup
In this example, the program needs more memory on the heap than the default. In a server-class machine running either VM (client or server) with parallel garbage collector, the default initial and maximum heap sizes are for J2SE 5.0 \[1\]:

...

        names.addElement(newName);
        System.out.println("adding " + newName);
      }
    } finally {
      input.close();
    }
  }

}

The readLimitedLine() method takes a numeric limit, indicating the total number of characters that may exist on one line. If a line contains more characters, the line is truncated, and the characters are returned on the next invocation. This prevents an attacker from exhausting memory by supplying input with no line breaks.

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]:

  • Initial heap size: larger of 1/64 of the machine's physical memory

...

  • or some reasonable minimum.

...

  • 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

public class ShowHeapError {

    /*assuming Assuming the heap size as 512mB 512 MB 
 * (calculated as 1/4th4 of 2 GB2GB RAM = 512mB512MB)
	 * Considering long values being entered (64 bits each, 
 * the max number of elements
	* would be 5122mB512MB/64bits64 bits = 
 * 67108864)
	 */
	public class ReadNames {
  // Accepts unknown number of records
  Vector<Long> names = new Vector<Long>(67108865); 
    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    // Adding unknown number of records to a list
        		* the// The user can enter more number of IDs than what the heap can support and exhaust the heap
    		* assume,
        // 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\nEnter recordID): ");
          	newID = reader.nextLong();

          	//names are continued to be added without bothering about the size on the heap
          	names.addElement(newIDnames.addElement(newID);
        i++;
      } while (i < count || newID != -1);
    } finally {
    	System.out.println(newID  input.close();
          	i++;

    	}while (i<count || newID!=-1);
    }

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

Compliant Solution

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 Wiki MarkupThis exception can be avoided by either making sure that there are no infinite loops or memory leaks. If the programmer knows that the application would require a lot of memory then, he can increase the heap size in Java using the following run time parameters \[2\]:

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

for For example:,

java -Xms128m -Xmx512m ShowHeapErrorReadNames

Here we have set the initial heap size as 128Mb is set to 128MB and the maximum heap size as 512Mbto 512MB.

This setting These settings can be done changed either in using the Java Control Panel or on from the command line. This setting They cannot be controlled in adjusted through the application itself.

Risk Assessment

It is difficult identifying a heap exhaustion, since static analysis tools would not be able to pin point anything and the heap size could be different for different machines.

In case the heap size is increased through the command line, then the assessment would be as follows:

Assuming infinite heap space can result in denial of service.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO37

MSC05-J

low

Low

probable

Probable

medium

Medium

P4

L3

In case the database solution is used, the cost would increase to high due to the coding of a disk-based solution.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO37-J

low

probable

high

P2

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website

References

[1] Garbage Collection Ergonomics Default values for the Initial and Maximum heap size

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 Coding Standard

MEM11-C. Do not assume infinite heap space

SEI CERT C++ Coding Standard

VOID MEM12-CPP. Do not assume infinite heap space

ISO/IEC TR 24772:2010

Resource Exhaustion [XZP]

MITRE CWE

CWE-400, Uncontrolled Resource Consumption ("Resource Exhaustion")
CWE-770, Allocation of Resources without Limits or Throttling

Bibliography


...

Image Added Image Added Image Added[2] Non Standard Options for java: The Java application launcher Syntax for increasing the heap size