Java Reference
In-Depth Information
Fortunately, files can often be identified by other attributes in addition to the file
name—for example, by comparing file creation times or modification times. Information
about a file that has been created and closed can be stored and then used to validate the
identity of the file if it must be reopened. Comparing multiple attributes of the file in-
creases the likelihood that the reopened file is the same file that was previously opened.
File identification is less crucial for applications that maintain their files in secure dir-
ectories where they can be accessed only by the owner of the file and (possibly) by a sys-
tem administrator (see The CERT ® Oracle ® Secure Coding Standard for Java [Long
2012], “FIO00-J. Do not operate on files in shared directories”).
Noncompliant Code Example
In this noncompliant code example, the file identified by the string filename is opened,
processed, closed, and then reopened for reading:
Click here to view code image
public void processFile(String filename){
// Identify a file by its path
Path file1 = Paths.get(filename);
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Close the file
/*
* A race condition here allows an attacker to switch
* out the file for another
*/
// Reopen the file for reading
Path file2 = Paths.get(filename);
try (BufferedReader br = new BufferedReader(new
InputStreamReader(Files.newInputStream(file2)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
Search WWH ::




Custom Search