...
Code Block | ||
---|---|---|
| ||
public void fio52_cs3(String filename) throws IOException{ // Identify a file by its path 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(); } |
Noncompliant Code Example (file size)
This noncompliant code example tries to ensure that the file it opens has exactly 1024 bytes.
Code Block | ||||
---|---|---|---|---|
| ||||
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
long size = new File( filename).length();
if (size != goodSize) {
System.out.println("File is wrong size!");
return;
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( filename)))) {
// ... work with file
} catch (Exception e) {
System.out.println("Exception during file access" + e);
}
}
|
This code is subject to a (TOCTOU) race condition between when the file size is learned and when the file is opened. If an attacker replaces a 1024-byte file with another file during this race window, they can cause this program to open any file, defeating the check.
Compliant Solution (file size)
This compliant solution uses the FileChannel.size()
method to obtain the file size. Since this method is applied only to the file after it has been opened, this solution eliminates the race window.
Code Block | ||||
---|---|---|---|---|
| ||||
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 is wrong size!");
return;
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("Exception during file access" + e);
}
}
|
Applicability
Many file-related vulnerabilities are exploited to cause a program to access an unintended file. Proper file identification is necessary to prevent exploitation.
...