1665
}
If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is
not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument
to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be
interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely
available to the destination buffer (CWE-787, CWE-788).
Example 3:
This code takes an IP address from the user and verifies that it is well formed. It 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);
}
This function allocates a buffer of 64 bytes to store the hostname. However, there is no guarantee
that the hostname will not be larger than 64 bytes. If an attacker specifies an address which
resolves to a very large hostname, then the function may overwrite sensitive data or even
relinquish control flow to the attacker.
Note that this example also contains an unchecked return value (CWE-252) that can lead to a
NULL pointer dereference (CWE-476).
Example 4:
This code applies an encoding procedure to an input string and stores it into a buffer.
Example Language: C (Bad)
char * copy_input(char *user_supplied_string){
int i, dst_index;
char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);
if ( MAX_SIZE <= strlen(user_supplied_string) ){
die("user string too long, die evil hacker!");
}
dst_index = 0;
for ( i = 0; i < strlen(user_supplied_string); i++ ){
if( '&' == user_supplied_string[i] ){
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'a';
dst_buf[dst_index++] = 'm';
dst_buf[dst_index++] = 'p';
dst_buf[dst_index++] = ';';
}
else if ('<' == user_supplied_string[i] ){
/* encode to &lt; */
}
else dst_buf[dst_index++] = user_supplied_string[i];
}
return dst_buf;
}
CWE Version 4.14
CWE-787: Out-of-bounds Write
CWE-787: Out-of-bounds Write