Java Reference
In-Depth Information
FileTime modified2 = attr2.lastModifiedTime();
if ( (!creation1.equals(creation2)) ||
(!modified1.equals(modified2)) ) {
// File was tampered with, handle error
}
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
}
}
Although this solution is reasonably secure, a determined attacker could create a sym-
bolic link with the same creation and last-modified times as the original file. Also, a
TOCTOUraceconditionoccursbetweenthetimethefile'sattributesarefirstreadandthe
timethefileisfirstopened.Likewise,anotherTOCTOUconditionoccursthesecondtime
the attributes are read and the file is reopened.
Compliant Solution (POSIX fileKey Attribute)
In environments that support the fileKey attribute, a more reliable approach is to check
thatthe fileKey attributesofthetwofilesarethesame.The fileKey attributeisanobject
that “uniquely identifies the file” [API 2013], as shown in this compliant solution:
Click here to view code image
public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
Object key1 = attr1.fileKey();
// Open the file for writing
try (BufferedWriter bw =
new BufferedWriter(
new Out-
putStreamWriter(Files.newOutputStream(file1)))) {
// Write to file
} catch (IOException e) {
Search WWH ::




Custom Search