Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: substantial re-write of explanatory text.

...

  • Share data between processes
  • Store auxiliary program data (for example, 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 include /tmp and /var/tmp on UNIX and C:\TEMP on Windows). Temporary files . Files in such directories may be purged regularly, for example, every night or during reboot. 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 can misuse files held in world-writable directories when those files are created insecurely or remain accessible after use. For instance, if an attacker who can both predict the name of the a temporary file can be predetermined, an attacker can use the and can change or replace that file, can exploit a time-of-check time-of-use (TOCTOU) condition to create a file with the same name leading to cause either a failure in creating the temporary file from within program code or the program reading a crafted of file whose contents are determined by the attacker.

Mitigation strategies include the following:

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

Shared access to a directory entails greater vulnerability than does 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 limited number of files. Consequently, temporary files in shared directories must be

...

Secure creation of temporary files is error prone and relies on platform dependent behavior, ; the Operating System, and the file system being are 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, most relevant APIs are problematic. The only secure comprehensive solution is to refrain from creating temporary files in shared directories.

...

Wiki Markup
A recently identified bug manifests in JRE and JDK version 6.0 and prior,earlier whereinpermits an attacker who can predict the names of the temporary files and as a resultto write malicious JAR files via unknown vectors \[[CVE 2008|AA. Bibliography#CVE 08]\]. DenialFailure ofto Service attacks are also possible if unclaimed reclaim temporary resources can cause rapid disk space exhaustion due to unreclaimed files \[[Secunia Advisory 20132|http://secunia.com/advisories/20132/]\].

...

This noncompliant code example hardcodes the name of the a temporary file which implies that the ; consequently, the file's 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 an attacker can alter or delete exploit the TOCTOU condition by altering or deleting the file before it is read.

...

Additionally, the output stream has not been closed remains open after use, which violates guideline FIO06-J. Ensure all resources are properly closed when they are no longer needed. Finally, The program also fails to delete the file is not deleted after use.

Exclusive Access

Wiki Markup
Exclusive access grants unrestricted file access to the locking process while denying access to all other processes, andthus eliminateseliminating the potential for a race condition on the locked region. 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 2006|AA. Bibliography#API 06]\] documentation

A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs.

A shared lock is useful when a file is to be read concurrently Shared locks support concurrent read access from multiple processes whereas an exclusive lock is more useful for writing. File locks cannot be used with ; exclusive locks support exclusive write access. File locks provide protection across processes; they are ineffective for multiple threads within a single process. Both shared locks and exclusive locks eliminate the potential for a cross-process 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 Exclusive locks provide mutual exclusion; shared locks prevent alteration of 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 consequently unspecified" \[[API 2006|AA. Bibliography#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 both mandatory locks and advisory locks. AnAdvisory advisorylocks lockare is not enforced by the operating system, which severely diminishes itstheir value from a security perspective. Unfortunately, the mandatory file lock in Linux is also largelygenerally impractical for the following reasonsbecause:

1. Mandatory locking works is supported only on local file systems and does not extend to ; it lacks support for network file systems (such as NFS or AFS).
2. File systems must be explicitly mounted with support for mandatory locking, and ; this support is disabled by default.
3. Locking relies on the group ID bit, however that bit can be turned off disabled by another process (thereby defeating the lock).

Removal Before Termination

Removing temporary files when they are no longer required allows file names and other resources (such as secondary storage) to be recycled. In Each program is responsible for ensuring that temporary files are removed during normal operation. There is no surefire method that can guarantee the removal of orphaned files in the case of abnormal termination (, even in the presence of a finally block that does not get a chance to execute), there is no surefire method that can guarantee the removal of orphaned files, because the finally block may fail to execute. For this reason, many systems employ temporary file cleaner utilities , which are to sweep temporary directories and remove old files. Such utilities can be invoked manually by a system administrator or can be periodically run invoked by a daemon to sweep temporary directories and remove old files, are widely usedsystem daemon. However, these utilities are themselves vulnerable to file-based exploits and often require the use of shared directories. During normal operation, it is the responsibility of the program to ensure that temporary files are removed appropriately.

Noncompliant Code Example

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

Wiki Markup
AccordingThis example also attempts to use the {{deleteOnExit()}} method to ensure that the temporary file is deleted when the JVM terminates. However, according to the Java API \[[API 2006|AA. Bibliography#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.

Wiki Markup
This implies thatThus the file wouldis not be deleted if the JVM terminates unexpectedly. AnotherA longstanding bug that remains unresolved violates the temporary file deletion contract provided by the {{deleteOnExit()}} method. If a stream or a {{RandomAccessFile}} is left unclosed before calling {{deleteOnExit()}}, the file is not deleted on Windows based systems --- \[[Bug ID: 4171239|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4171239]\] --- 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 = new FileOutputStream(f);
    String str = "Data";
    try {
      fop.write(str.getBytes());
      fop.flush();        
    }finally {
      // Stream/file still open; file will
 is not closed first, file will// not be deleted on Windows systems
      f.deleteOnExit(); // Delete the file when the JVM terminates
    }
  }       
}

Compliant Solution

Wiki Markup
AsTo awork workaroundaround to the file/stream termination issue described above, always tryattempt to terminate the resource first before invoking {{deleteOnExit()}}. This should have been done using {{fop.close()}} in the noncompliant code example. It is also recommended thatUsing {{File.io.delete()}} be used to immediately delete the file to avoid is good practice, when possible; this avoids improper JVM termination related issues. Moreover, although unreliable, {{System.gc()}} may be invoked to free up related resources. Sometimes, it is not possiblethe resources to closebe thedeleted resourcescannot onbe whichclosed thefirst; deletesee, operation has to be invokedfor example, \[[Bug ID: 4635827|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4635827]\]. Currently,There there is no wayknown toworkaround handlefor this case. It is highly recommended that Consequently, temporary files must be created only in secure directories.

Risk Assessment

Not following the Failure to follow best practices while creating, using and deleting temporary files can lead to denial of service vulnerabilities, misinterpretations and alterations in control flow.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

FIO07-J

high

probable

medium

P12

L1

Automated Detection

...

Related Vulnerabilities

GERONIMO-3489

...