Many file-related security vulnerabilities result from a program accessing an unintended file object. One frequent cause is that file names are only loosely bound to underlying file objects. File names are uninformative regarding the nature of the file object itself. Furthermore, the binding of a file name to a file object is reevaluated each time the file name is used in an operation. This reevaluation introduces can introduce a time-of-check, time-of-use (TOCTOU) race condition with the file system. Objects of type java.io.File
and of type java.nio.file.Path
are bound to underlying file objects by the operating system.
...
Code Block | ||
---|---|---|
| ||
public void processFile_nce(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 for an attacker to switch * out the file for another */ // Reopen the file for reading Path file2 = Paths.get(filename); try try(BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(file2)))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // Handle error } } |
...
That is, isSameFile()
may simply check that the paths to the two files are the same . If and cannot detect if the file at that path had been replaced by a different file between the two open operations, this would remain undetected.
Compliant Solution (Multiple Attributes)
...