Java Reference
In-Depth Information
The CERT ® Oracle ® Secure Coding Standard for Java [Long 2012], “FIO01-J.
Createfileswithappropriateaccesspermissions,”explainshowtospecifythepermissions
of a newly created file.
Noncompliant Code Example
This noncompliant code example tries to open a file for writing:
Click here to view code image
public void createFile(String filename)
throws FileNotFoundException{
OutputStream out = new FileOutputStream(filename);
// Work with file
}
If the file exists before being opened, its former contents will be overwritten with the
contents provided by the program.
Noncompliant Code Example (TOCTOU)
This noncompliant code example tries to avoid altering an existing file by creating an
empty file using java.io.File.createNewFile() . If a file with the given name already
exists, then createNewFile() will return false without destroying the named file's con-
tents.
Click here to view code image
public void createFile(String filename)
throws FileNotFoundException{
OutputStream out = new FileOutputStream(filename, true);
if (!new File(filename).createNewFile()) {
// File cannot be created...handle error
} else {
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 after the empty file is
Search WWH ::




Custom Search