Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
void *AllocBlocks(size_t cBlocks) {
  size_t alloc;

  if (cBlocks == 0) return NULL;
  alloc = multsize_t(cBlocks, 16);
  if (errno) {
    return NULL;
  }
  else {
    return malloc(alloc);
  }
} /* end AllocBlocks */

Non-Compliant Code Example

In this non-compliant code example, the string referenced by str and the string length represented by len orginate from untrusted sources. The length is used to perform a memcpy() into the fixed size static array buf. The len variable is guaranteed to be less than BUFF_SIZE. However, because len is declared as an int it could have a negative value that would bypass the check. The memcpy() function implicitly converts len to an unsigned size_t type, and the resulting operation results in a buffer overflow.

Code Block
bgColor#FFcccc

int len;
char *str;
char buf[BUFF_SIZE];

...
if (len < BUFF_SIZE){
  memcpy(buf, str, len);
}
...

Compliant Solution

In this compliant solution, len is declared as a size_t to there is no possibility of this variable having a negative value and bypassing the range check.

Code Block
bgColor#ccccff

size_t len;
char *str;
char buf[BUFF_SIZE];

...
if (len < BUFF_SIZE){
  memcpy(buf, str, len);
}
...

Risk Assessment

Providing invalid size arguments to memory allocation functions can lead to buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process.

...