Although creating a file is generally accomplished with a single method call, it actually has several issues to considerthis apparently-simple action raises multiple security-related questions. What should be done if the file cannot be created? What should be done if the file already exists? What should be the file's initial attributes, such as permissions? Java provides several generations of file handling facilities. The original input/output facilities, which included basic file handling, are in the package java.io
. More comprehensive facilities were included in JDK 1.4 with the New I/O package java.nio
(see New I/O APIs [Oracle 2010b]). This package introduced a number of methods to handle finesupport finer-grained control of file creation.
...
If the file existed before being opened, its any new contents data written out will be appended to the former contents. This code is compliant only if this was behavior matches the intention intent of the programmer.
Noncompliant Code Example (TOCTOU)
...
Unfortunately, this solution is subject to a TOCTOU (time-of-check-time-of-use) race condition. It is possible for an attacker to modify the file system after the empty file is created but before the file open call such that the file that is created opened is not the file that is openedwas created.
Compliant Solution (Files
)
...
Applicability
The ability to determine if whether an existing file has been opened or a new file has been created provides greater assurance that a file other than only the intended file is not opened or overwritten and that other files remain undisturbed.
Bibliography
...