...
This solution is not perfect. Like the previous compliant solution, it has a TOCTOU race window between when the file's attributes are read and when the file is first opened. Likewise, there is another TOCTOU between the second attributes are read and the file is reopened.
Compliant Solution (RandomAccessFile
)
A better approach is to avoid re-opening a file. The following compliant solution demonstrates use of a RandomAccessFile
, which can be opened for both reading and writing. Since the file is never closed, no race condition is possible.
Code Block | ||
---|---|---|
| ||
//Identify a file by its path
String filename = // initialized
RandomAccessFile file = new RandomAccessFile( filename, "rw");
// Write to file...
// Go back to beginning and read contents
file.seek(0);
try {
while (true) {
String s = file.readUTF();
System.out.print(s);
}
} catch (EOFException x) {
// ignore, this breaks out of while loop
}
br.close();
|
Applicability
Many file-related vulnerabilities are exploited to cause a program to access an unintended file. Proper file identification is necessary to prevent exploitation.
...