Ignoring a method's return value can cause the program to overlook unexpected states and conditions.
It is not uncommon for Java programmers to misunderstand read()
and related methods that are part of many java.io
classes. Most errors and unusual events in Java result in an exception being thrown. (This is one of the advantages that Java has over languages like C: Exceptions make it easier for programmers to think about what can go wrong.) But the stream and reader classes do not consider it unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested.
This behavior makes it important for programmers to examine the return value from read()
and other IO methods to ensure that they receive the amount of data they expect.
Example: The following code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always exactly 1 kilobyte in size and therefore ignores the return value from read()
. If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and handle it as though it belongs to the attacker.
FileInputStream fis;
byte[] byteArray = new byte[1024];
for (Iterator i=users.iterator(); i.hasNext();) {
String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName;
FileInputStream fis = new FileInputStream(pFileName);
fis.read(byteArray); // the file is always 1k bytes
fis.close();
processPFile(userName, byteArray);
}
[1] Standards Mapping - OWASP Top 10 2007 - (OWASP 2007) A6 Information Leakage and Improper Error Handling
[2] Standards Mapping - OWASP Top 10 2004 - (OWASP 2004) A7 Improper Error Handling
[3] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP3120 CAT II
[4] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 252, CWE ID 754
[5] Standards Mapping - Payment Card Industry Data Security Standard Version 1.2 - (PCI 1.2) Requirement 6.3.1.2, Requirement 6.5.6
[6] Standards Mapping - Payment Card Industry Data Security Standard Version 2.0 - (PCI 2.0) Requirement 6.5.5
[7] Standards Mapping - Payment Card Industry Data Security Standard Version 1.1 - (PCI 1.1) Requirement 6.5.7
[8] Standards Mapping - SANS Top 25 2010 - (SANS 2010) Risky Resource Management - CWE ID 754