Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

...

Code Block
bgColor#FFcccc
class TempFile {
  public static void main(String[] args) throws IOException{
    File f = File.createTempFile("tempnam",".tmp");
    FileOutputStream fop = null;
    try {
      fop = new FileOutputStream(f);
      String str = "Data";
      fop.write(str.getBytes());
      fop.flush();
    } finally {
      // Stream/file still open; file will
      // not be deleted on Windows systems
      f.deleteOnExit(); // Delete the file when the JVM terminates

      if (fop != null) {
        try {
          fop.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

Compliant Solution (

...

DELETE_ON_CLOSE)

This compliant solution creates a temporary file using several methods from Java's NIO.2 package (introduced in Java SE 7). It uses the createTempFile() method, which creates an unpredictable name. (The actual method by which the name is created is implementation-defined and undocumented.) The file is opened using the try-with-resources construct, which automatically closes the file regardless of whether an exception occurs. Finally, the file is opened with the Java SE 7 DELETE_ON_CLOSE option, which removes the file automatically when it is closed.

...

Failure to remove temporary files before termination can result in information leakage and resource exhaustion.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO03-J

Medium

Probable

Medium

P8

L2

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.FIO03.ATF
CERT.FIO03.REMTMP
Avoid temporary files
Remove temporary files before termination

Related Guidelines

Bibliography

[API 2014]

Class File
   Method createTempFile
   Method delete
   Method deleteOnExit

[Darwin 2004]

Section 11.5, "Creating a Transient File"

[J2SE 2011]

 


[JDK Bug 2015]

Bug JDK-

4171239

4405521
Bug JDK-

4405521

4631820

[SDN 2008]Bug
JDK-4631820
ID: 4171239 

[Secunia 2008]

Secunia Advisory 20132

...


...