Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Gave the NCCE functions different names and wrapped the third NCCE and the CS in functions

...

Code Block
bgColor#ffcccc
langjava
public void fio54_ncence1(String filename) throws FileNotFoundException{
    OutputStream out = new FileOutputStream(filename);
    // Work with FILE
}

...

Code Block
bgColor#ffcccc
langjava
public void fio54_ncence2(String filename) throws FileNotFoundException{
	OutputStream out = new FileOutputStream(filename, true);
	// Work with FILE
}

...

Code Block
bgColor#ffcccc
langjava
public void fio54_nce3(String filename) throws FileNotFoundException{
    OutputStream out = new FileOutputStream(filename, true);
    if (!new File(filename).createNewFile()) {
        // File cannot be created...handle error
    } else {
        OutputStream out = new FileOutputStream(filename);
        // Work with FILE
    }
} 

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 such that the file that is created is not the file that is opened.

...

Code Block
bgColor#ccccff
langjava
public void fio54_cs(String filename) throws FileNotFoundException{
    try (OutputStream out = new BufferedOutputStream(
         Files.newOutputStream( Paths.get(filename),
                                StandardOpenOption.CREATE_NEW))) {
            // Work with out
    } catch (IOException x) {
        // File not writable...handle error
    }
} 

Applicability

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 opened or overwritten.

...