1574
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 8:
In the following C/C++ example the method outputStringToFile opens a file in the local filesystem
and outputs a string to the file. The input parameters output and filename contain the string to
output to the file and the name of the file respectively.
Example Language: C++ (Bad)
int outputStringToFile(char *output, char *filename) {
openFileToWrite(filename);
writeToFile(output);
closeFile(filename);
}
However, this code does not check the return values of the methods openFileToWrite, writeToFile,
closeFile to verify that the file was properly opened and closed and that the string was successfully
written to the file. The return values for these methods should be checked to determine if the
method was successful and allow for detection of errors or unexpected conditions as in the
following example.
Example Language: C++ (Good)
int outputStringToFile(char *output, char *filename) {
int isOutput = SUCCESS;
int isOpen = openFileToWrite(filename);
if (isOpen == FAIL) {
printf("Unable to open file %s", filename);
isOutput = FAIL;
}
else {
int isWrite = writeToFile(output);
if (isWrite == FAIL) {
printf("Unable to write to file %s", filename);
isOutput = FAIL;
}
int isClose = closeFile(filename);
if (isClose == FAIL)
isOutput = FAIL;
}
return isOutput;
}
Example 9:
CWE Version 4.14
CWE-754: Improper Check for Unusual or Exceptional Conditions
CWE-754: Improper Check for Unusual or Exceptional Conditions