Versions Compared

Key

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

...

This rule is a specific instance of the more general rule MSC07-J. Do not assume infinite heap space.

Noncompliant Code Example

This noncompliant code fails to check the resource consumption of the file that is being unzipped. It permits the operation to run to completion or until local resources are exhausted.

Code Block
bgColor#FFcccc
static final int BUFFER = 512;
// ...

// external data source: filename
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
  System.out.println("Extracting: " +entry);
  int count;
  byte data[] = new byte[BUFFER];
  // write the files to the disk
  FileOutputStream fos = new FileOutputStream(entry.getName());
  dest = new BufferedOutputStream(fos, BUFFER);
  while ((count = zis.read(data, 0, BUFFER)) != -1) {
    dest.write(data, 0, count);
  }
  dest.flush();
  dest.close();
}
zis.close();

Compliant Solution

In this compliant solution, the code inside the while loop uses the ZipEntry.getSize() to find the uncompressed file size of each entry in a zip archive before extracting the entry. It throws an exception if the entry to be extracted is too large — 100MB in this case.

Code Block
bgColor#ccccff
static final int TOOBIG = 0x6400000; // 100MB

  // ...

  // write the files to the disk, but only if file is not insanely big
  if (entry.getSize() > TOOBIG) {
    throw new IllegalStateException("File to be unzipped is huge.");
  }
  if (entry.getSize() == -1) {
    throw new IllegalStateException("File to be unzipped might be huge.");
  }
  FileOutputStream fos = new FileOutputStream(entry.getName());
  dest = new BufferedOutputStream(fos, BUFFER);
  while ((count = zis.read(data, 0, BUFFER)) != -1) {
    dest.write(data, 0, count);
  }

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

IDS05 IDS04-J

low

probable

high

P2

L3

Related Guidelines

MITRE CWE

CWE-409, "Improper Handling of Highly Compressed Data (Data Amplification)"

Secure Coding Guidelines for the Java Programming Language, Version 3.0

Guideline 2-5 Check that inputs do not cause excessive resource consumption

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c2837da5e4d2e2e3-6b0ec3e2-4fcc4b3e-8e8e9f6f-83ee837ca39948370a309f58"><ac:plain-text-body><![CDATA[

[[Mahmoud 2002

AA. Bibliography#Mahmoud 02]]

[Compressing and Decompressing Data Using Java APIs

http://java.sun.com/developer/technicalArticles/Programming/compression/]

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

...