The C99 {{fopen()}} function is used to open an existing file or create a new one \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. However, {{fopen()}} does not indicate if an existing file has been opened for writing or a new file has been created. This may lead to a program overwriting or accessing an unintended file. |
FileOutputStream())In this noncompliant code example, the file referenced by file is opened for writing. This example is noncompliant if the programmer's intent was to create a new file, but the referenced file already exists.
String file; OutputStream out = new FileOutputStream(file); |
StandardOpenOption.CREATE_NEW)This compliant solution uses the CREATE_NEW option from Java 1.7, which causes an exception to be thrown if the file being created already exists.
Path file = new File("file").toPath();
try (OutputStream out = Files.newOutputStream( file, StandardOpenOption.CREATE_NEW);) {
// write to out
};
|
FileWriter())In this noncompliant code example, the file referenced by file is opened for writing. Again, the example is noncompliant if the programmer's intent was to create a new file, but the referenced file already exists.
String file; Writer out = new FileWriter(file); |
StandardOpenOption.CREATE_NEW)This compliant solution uses the CREATE_NEW option from Java 1.7, which causes an exception to be thrown if the file being created already exists.
Path file = new File("file").toPath();
try (BufferedWriter out = Files.newBufferedWriter( file, Charset.forName("UTF8"),
StandardOpenOption.CREATE_NEW);) {
// write to out
};
|
The ability to determine if an existing file has been opened or a new file has been created provides greater assurance that a file other than the intended file is not acted upon.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FIO00-J |
medium |
probable |
high |
P4 |
L3 |
TODO
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
CERT C++ Secure Coding Standard: FIO03-CPP. Do not make assumptions about fopen() and file creation
CERT C Secure Coding Standard: FIO03-C. Do not make assumptions about fopen() and file creation
[[API 2006|AA. Bibliography#API 06]\] Class {{InputStream}}, {{DataInputStream}}
\[[J2SE 2011|AA. Bibliography#J2SE 11]\] The try-with-resources Statement
\[[Seacord 2005a|AA. Bibliography#Seacord 05]\] Chapter 7, "File I/O" |
FIO01-J. Do not expose buffers created using the wrap() or duplicate() methods to untrusted code 12. Input Output (FIO) FIO05-J. Do not create multiple buffered wrappers on a single InputStream