Versions Compared

Key

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

...

C99 includes support for variable length arrays (VLAs). If the array length is derived from an untrusted data source, an attacker could cause the process to perform an excessive allocation on the stack.

This non-compliant code example temporarily stores data read from a source file into a buffer. The buffer is allocated on the stack as a variable length array of size bufsize. If bufsize can be controlled by a malicious user, this code could be exploited to cause a denial-of-service attack.

Code Block
bgColor#FFcccc
int copy_file(FILE *src, FILE *dst, size_t bufsize) {
  char buf[bufsize];

  while (fgets(buf, bufsize, src)) {
    fputs(buf, dst);
  }

  return 0;
}

Wiki Markup
The BSD extension function {{alloca()}} behaves in a similar fashion to VLAs; its use is not recommended \[Loosemore 07|AA. C References#Loosemore 07]\] 
If bufsize can be controlled by a malicious user, this code could be exploited to cause a denial-of-service attack
.

Compliant Solution

This compliant solution replaces the variable length array with a call to malloc(). If malloc() fails, the return value can be checked to prevent the program from terminating abnormally.

...

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.5.2, "Array declarators", Section 7.20.3, "Memory management functions"
\[Loosemore 07|AA. C References#Loosemore 07]\] Section 3.2.5, "Automatic Storage with Variable Size"
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management"
\[[van Sprundel 06|http://ilja.netric.org/files/Unusual%20bugs.pdf]\] "Stack Overflow"

...