610
The following VB.NET code does not check to make sure that it has read 50 bytes from myfile.txt.
This can cause DoDangerousOperation() to operate on an unexpected value.
Example Language: C# (Bad)
Dim MyFile As New FileStream("myfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
Dim MyArray(50) As Byte
MyFile.Read(MyArray, 0, 50)
DoDangerousOperation(MyArray(20))
In .NET, it is not uncommon for programmers to misunderstand Read() and related methods
that are part of many System.IO classes. The stream and reader classes do not consider it to be
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.
Example 8:
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. 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 9:
This example takes an IP address from a user, verifies that it is well formed and then looks up the
hostname and copies it into a buffer.
Example Language: C (Bad)
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);
/*routine that ensures user_supplied_addr is in the right format for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(hostname, hp->h_name);
}
If an attacker provides an address that appears to be well-formed, but the address does not resolve
to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the
return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then
occur in the call to strcpy().
Note that this code is also vulnerable to a buffer overflow (CWE-119).
Example 10:
The following function attempts to acquire a lock in order to perform operations on a shared
resource.
Example Language: C (Bad)
void f(pthread_mutex_t *mutex) {
pthread_mutex_lock(mutex);
/* access shared resource */
CWE Version 4.14
CWE-252: Unchecked Return Value
CWE-252: Unchecked Return Value