Java Reference
In-Depth Information
InputStreamReader(new FileInputStream(filename)))) {
// ... Work with file
} catch (IOException e) {
// Handle error
}
}
ThiscodeissubjecttoaTOCTOUraceconditionbetweenwhenthefilesizeischecked
and when the file is opened. If an attacker replaces a 1024-byte file with another file dur-
ing this race window, they can cause this program to open any file, defeating the check.
Compliant Solution (File Size)
Thiscompliantsolutionusesthe FileChannel.size() methodtoobtainthefilesize.Be-
cause this method is applied to the FileInputStream only after the file has been opened,
this solution eliminates the race window.
Click here to view code image
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
try (FileInputStream in = new FileInputStream(filename);
BufferedReader br = new BufferedReader(
new InputStreamReader(in))) {
long size = in.getChannel().size();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle error
}
}
Search WWH ::




Custom Search