Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: made some more changes but now I think I'm done

Temporary files are sometimes can be used to

  • 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 include /tmp and /var/tmp on UNIX and C:\TEMP on Windows. Files in such directories may be purged regularly, for example, every night or during reboot. However, an attacker who has access to the local file system can misuse files held in world-writable directories when those files are created insecurely or remain accessible after use. For instanceexample, 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) condition to cause either a failure in creating the temporary file from within program code or operating on a file determined by the attacker. This exploit is particularly dangerous when the vulnerable program is running with elevated privileges. However, on multiuser systems a user can be tricked by an attacker into unintentionally operating on their own files.

Temporary files are files and consequently must conform to the requirements specified by rules governing operations on files including FIO00-J. Do not overwrite an existing file while attempting to create a new file, FIO03-J. Create files with appropriate access permissions, and FIO04-J. Do not operate on files in shared directories. Temporary files have an additional requirement that the they must be removed before program termination.

Removing temporary files when they are no longer required allows file names and other resources (such as secondary storage) to be recycled. 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, because the finally block may fail to execute. For this reason, many systems employ temporary file cleaner utilities to sweep temporary directories and remove old files. Such utilities can be invoked manually by a system administrator or can be periodically invoked by a system daemon. However, these utilities are themselves vulnerable to file-based exploits and often may require the use of shared secure directories.

Noncompliant Code Example

...

(createTempFile(), deleteOnExit())

This noncompliant code example provides the name of a temporary file to create. Even though the program detects whether a file still exists after its creation, this check creates a TOCTOU race condition that an attacker can exploit, by altering or deleting the file between the check and the 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());
      fop.close();
    } else { 
      System.out.println("This file does not exist"); 
    }
  }      
}

Noncompliant Code Example (createTempFile(), deleteOnExit())

This noncompliant code example improves over the previous noncompliant code example by using the method File.createTempFile() to generate a unique temporary filename based on two parameters, a prefix and an extension. This is the only method currently invokes the File.createTempFile() method to generate a unique temporary filename based on two parameters, a prefix and an extension. This is the only method currently designed and provided for producing unique file names; unfortunately, the names produced can be easily predicted. This can be easy to predict. Mitigate this vulnerability solved by using a good random number generator to produce the prefix.

Providing unique filenames is a common attempt at mitigating the risk of creating a file in an insecure or shared directory. If the filename is not sufficiently unique or random, an attacker can guess or predict the name of the file to be created, and exploit the filesystem as in the last examplecreate a symbolic link with the same name, the final target of which is a file selected by the attacker.

Wiki Markup
This 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:

...

This noncompliant code example creates a temporary file using the newest features of Java 1.7's NIO facility. 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 specifically created with POSIX file permissions denying access to the file to everyone except the file's creator, ; a similar permission set can be devised for Windows. FurthermoreAdditionally, the createTempFile() will throw an exception if the file already existed. The file is opened using the try-with-resources construct, which automatically closes the file whether or not an exception occurs. And finallyFinally, the file is opened with the Java 1.7 DELETE_ON_CLOSE option, which serves to remove the file automatically when it is closed.

...

Wiki Markup
To work around the file/stream termination issue, always attempt to terminate the resource normally before invoking {{deleteOnExit()}}. Using {{File.io.delete()}} to immediately delete the file is good practice, when possible; thisand avoids improper JVM termination related issues. Moreover, althoughAlthough unreliable, {{System.gc()}} may be invoked to free up related resources. Sometimes, the resources to be deleted cannot be closed first; see, for example, [Bug ID: 4635827|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4635827] \[[SDN 2008|AA. Bibliography#SDN 08]\]. There is no known workaround for this case.

...

This compliant solution uses the isInSecureDir() method to ensure that an attacker may not cannot tamper with the temporary file to be opened and subsequently removed. Note that once the path name of a directory has been checked using isInSecureDir(), all further file operations on that directory must be performed using the same path name.

Code Block
bgColor#ccccff
class TempFile {
  public static boolean isInSecureDir(Path file) {
    // ...
  }

  public static void main(String[] args) {
    Path tempDir = new File(args[0]).toPath();
    if (!isInSecureDir(tempDir)) {
      System.out.println("Temporary Directory not secure");
      return;
    }

    // POSIX file permissions for exclusive read/write
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
    FileAttribute att = PosixFilePermissions.asFileAttribute(perms);
    Path tempFile = null;
    try {
      tempFile = Files.createTempFile(tempDir, "file", ".myapp", att);
      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);
    }
  }
}

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="418c50f957cc18e3-5ea10e32-4c4b4db3-bcbaab1a-bed92c75b82f2b6885553c30"><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="870815e2fd82828b-c0af7f79-461a4175-9d608fd2-4d2ce87dbb9c3b05752fd813"><ac:plain-text-body><![CDATA[

[[CVE 2008

AA. Bibliography#CVE 08]]

[CVE-2008-5354

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5354]

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

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5bd9ca6d6bf346f3-cfb1ac74-4622478c-bc36a832-7f42fea710bb270055555eda"><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="a37e3b591130aeed-b242b162-4812491a-8eae8243-80ff9ee42d89f1859bfcc8c9"><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="2652cc374d1ecdf6-19341900-43df44b4-b3038ba4-97d2b5cfd8bda2657c758420"><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="357381e344ba1f1a-d454b490-477f41a7-a220b2e8-cde9f517910e70d243ece806"><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>

...