Versions Compared

Key

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

Temporary files can be used to

  • Share share data between processes.
  • Store store auxiliary program data (for example, to preserve memory).
  • Construct construct and/or load classes, JAR files, and native libraries dynamically.

Programmers frequently create temporary files in directories that are writable by everyone; examples include /tmp and /var/tmp on UNIX POSIX and C:\TEMP on Windows. Files in such directories may be purged regularly, such as every night or during reboot. However, an attacker who has access to the local file system can exploit operations on files in shared directories when those files are created insecurely or remain accessible after use. For example, an attacker who can both predict the name of a temporary file and can change or replace that file can exploit a time-of-check time-of-use (TOCTOU) race condition to cause either a failure in creating the temporary file from within program code or operating to cause the program to operate on a file determined by the attacker. This exploit is particularly dangerous when the vulnerable program is running with elevated privileges. On multiuser systems, a user can be tricked by an attacker into unintentionally operating on their his or her own files. Consequently, temporary file management must comply with rule FIO00-J. Do not operate on files in shared directories.

Many programs that create temporary files attempt to give them unique and unpredictable file names. This is a common attempt at mitigating the risk of creating a file in an insecure or shared directory. If the file name is not sufficiently insufficiently unique or random, an attacker can could guess or predict the name of the file to be created and could create a file link with the same name, the final target of which is a file selected by the attacker. However, if a temporary file is when temporary files are created in a secure directory, an attacker cannot tamper with the file, and so them, consequently, the need for unpredictable names is eliminated.

Temporary files are files and consequently must conform to the requirements specified by other rules governing operations on files, including rules FIO00-J. Do not operate on files in shared directories and FIO01-J. Create files with appropriate access permissions. Furthermore, temporary files have an the additional requirement in that they must be removed before program termination.

...

For this and subsequent code examples, we will assume that the files are automatically being created in a secure directory , to comply in compliance with rule FIO00-J. Do not operate on files in shared directories. We will also assume the files are created with proper access permissions, to compy with rule FIO01-J. Create files with appropriate access permissions. Both requirements may be managed outside the JVM.

This noncompliant code example makes no attempt fails to remove the file upon completion.

...

Wiki Markup
This example also attempts to useuses the {{deleteOnExit()}} method to ensure that the temporary file is deleted when the Java Virtual Machine (JVM) terminates. However, according to the Java API \[[API 2006|AA. Bibliography#API 06]\] Class {{File}}, method {{deleteOnExit()}} documentation,

...

Wiki Markup
Consequently, the file is not deleted if the JVM terminates unexpectedly. A longstanding bug on Windows -based systems reported as [Bug ID: 4171239|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4171239] \[[SDN 2008|AA. Bibliography#SDN 08]\] causes JVMs to fail to delete a file when {{deleteOnExit()}} is invoked before the associated stream or {{RandomAccessFile}} is closed.

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 (Java

...

SE 7

...

: DELETE_ON_CLOSE)

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

Code Block
bgColor#ccccff
class TempFile {
  public static void main(String[] args) {
    Path tempFile = null;
    try {
      tempFile = Files.createTempFile("tempnam", ".tmp");
      try (BufferedWriter writer =
          Files.newBufferedWriter(tempFile, Charset.forName("UTF8"),
                                  StandardOpenOption.DELETE_ON_CLOSE)) {
          // write to file
      }
      System.out.println("Temporary file write done, file erased");
    } catch (FileAlreadyExistsException x) {
      System.err.println("File exists: " + tempFile);
    } catch (IOException x) {
      // Some other sort of failure, such as permissions.
      System.err.println("Error creating temporary file: " + x);
    }
  }
}

Compliant Solution

If When a secure directory for storing temporary files is not available, then the vulnerabilities that result from using temporary files in insecure directories can be avoided by using alternate alternative mechanisms, including

  • other IPC mechanisms such as sockets and remote procedure calls.
  • the low-level Java Native Interface (JNI).
  • memory-mapped files.
  • threads to share heap data within the same JVM (applies to data sharing between Java processes only).
  • a secure directory that can be accessed only by application instances, provided that multiple instances of the application running on the same platform avoid competing for the same files.

Risk Assessment

Failure to follow best practices while creating, using, and deleting temporary files can lead to information leakage, misinterpretations, and alterations in control flow.

...

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="7ce46a1a7c506a37-4ee91808-446e432c-babdb730-f86c8482b339602f2be34a36"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

Class File, methods createTempFile, delete, deleteOnExit

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c2c79cbe7cc1ffef-ce889486-44b94f56-9b039cdf-8d439eec75db868c42905265"><ac:plain-text-body><![CDATA[

[[Darwin 2004

AA. Bibliography#Darwin 04]]

11.5, Creating a Transient File

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="79739f9c787b7269-0457538a-4c614886-8d058a50-d2d1f23b72cce4e734291515"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]]

 

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a7979c998b9c3f4d-3418ba8a-46b74675-b380adf8-f3043969bb75ab58ee759283"><ac:plain-text-body><![CDATA[

[[SDN 2008

AA. Bibliography#SDN 08]]

Bug IDs : 4171239, 4405521, 4635827, 4631820

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6b8dd6c96ad5e5e3-638b8409-48504a56-bc57babd-575016d79ddbbbf61b69f027"><ac:plain-text-body><![CDATA[

[[Secunia 2008

AA. Bibliography#Secunia 08]]

[Secunia Advisory 20132

http://secunia.com/advisories/20132/]

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

...