Versions Compared

Key

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

Temporary files are typically used to:

  • Share data between processes
  • Store auxiliary program data (to save memory)
  • Construct and/or load classes, JAR files and native libraries dynamically

Programmers frequently create temporary files in directories that are writable by everyone (examples are /tmp and /var/tmp on UNIX and C:\TEMP on Windows) and . Temporary files may be purged regularly (, for example, every night or during reboot). Temporary files are typically used to:

  • Share data between processes
  • Store auxiliary program data (to save memory)
  • Construct and/or load classes, JAR files and native libraries dynamically

. However, this allows an adversary who has access to the local file system to misuse them. An adversary can cause a program to incorrectly interpret the temporary data if temporary files are not created safely or beget a denial of service if the file is not deleted after use. For instance, if the name of the file can be predetermined, an attacker can use the time-of-check -to- time-of-use (TOCTOU) condition to create a file with the same name leading to either a failure in creating the temporary file from within program code or the program reading a crafted file whose contents are determined by the attacker.

...

1. Use other IPC mechanisms such as sockets and remote procedure calls
2. Use the low-level Java Native Interface (JNI).
3. Use memory mapped files
4. Use threads to share heap data within the same JVM (applies to data sharing between Java processes only)
5. Use a secure directory that can only be accessed by application instances (making make sure that multiple instances of the application running on the same platform do not compete).

When two or more users, or a group of users, have write permission to a directory, the potential for deception is far greater than it is for shared access to a few limited number of files.

Consequently, temporary files in shared directories must be:

1. Created with unique and unpredictable file names,
2. Opened with exclusive access,
3. Removed before the program exits, and
4. Opened with appropriate permissions.

Securely creating Secure creation of temporary files is error prone and relies on platform dependent on the operating system, behavior, the Operating System and the file system being the determining factors. Code that works for a locally mounted file system, for example, may be vulnerable when used with a remotely mounted file system. Moreover, none of the most relevant APIs are without problemsproblematic. The only secure solution is not to create refrain from creating temporary files in shared directories.

...

This noncompliant code example hardcodes the name of the temporary file which implies that it the name is predictable. Even though there is a built-in check to detect whether a file still exists after its creation, a TOCTOU condition exists such that can prevent a program from making use of the temporary filean attacker can alter or delete the file before it is read.

Code Block
bgColor#FFcccc
class TempFile{
  public static void main(String[] args) throws IOException{
    File f = new File("tempnam.tmp");
    FileOutputStream fop = new FileOutputStream(f);
    String str = "Data";
    
    if(f.exists()){
      fop.write(str.getBytes());
    } else { 
      System.out.println("This file does not exist"); 
    }
  }      
}

Additionally, the output stream has not been closed after use which violates FIO32-J. Ensure all resources are properly closed when they are no longer needed. Finally, no measure to delete the file is not deleted after use has been considered.

Exclusive Access

Wiki Markup
Exclusive access grants unrestricted file access to the locking process while denying access to all other processes and eliminates the potential for a race condition on the locked region.
Wiki Markup
 Files, or regions of files, can be locked to prevent two processes from concurrent access. The {{java.nio.channels.FileLock}} class facilitates file locking. According to the Java API \[[API 06|AA. Java References#API 06]\] documentation:

...

A shared lock is useful when a file is to be read concurrently from multiple processes whereas an exclusive lock is more useful for writing. File locks cannot be used with threads within a single process. Both shared locks and exclusive locks eliminate the potential for a race condition on the locked region. The exclusive lock is similar to a mutual exclusion solution, and the shared lock eliminates race conditions by removing the potential for altering the state of the locked file region (one of the required properties for a data race).

Wiki Markup
"Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified" \[[API 06|AA. Java References#API 06]\]. Microsoft Windows uses a file-locking mechanism called mandatory locking because every process attempting access to a locked file region is subject to the restriction. Linux implements mandatory locks and advisory locks. An advisory lock is not enforced by the operating system, which severely diminishes its value from a security perspective. Unfortunately, the mandatory file lock in Linux is also largely impractical for the following reasons:

...

Noncompliant Code Example

This noncompliant code example improves over the previous noncompliant code example by demonstrating how the method File.createTempFile() can be used to generate a unique temporary filename based on two parameters, a prefix and an extension. Currently, this is the only method that is designed for producing unique file names but even then, the names produced are not hard to predict. It is recommended that the prefix be generated using a good random number generator.

Wiki Markup
According to the Java API \[[API 06|AA. Java References#API 06]\] Class {{File}}, method {{deleteOnExit()}} documentation:

Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification. Once deletion has been requested, it is not possible to cancel the request. This method should consequently be used with care.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably.

...

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

...

Wiki Markup
As a workaround to the file/stream termination issue described above, always try to terminate the resource first. This should have been done using {{fop.close();}} in the abovenoncompliant noncompliantcode example. It is also recommended that {{File.io.delete()}} be used to immediately delete the file to avoid improper JVM termination related issues. Moreover, although unreliable, {{System.gc()}} may be invoked to free up related resources. Sometimes, it is not possible to close the resources on which the delete operation has to be invoked \[[Bug ID: 4635827|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4635827]\]. Currently, there is no way to handle this case. It is highly recommended that temporary files be created only in secure directories.

...