Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

Noncompliant Code Example

Wiki MarkupC99 includes support for variable-length arrays (VLAs) \ [[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. If the array length is derived from an untrusted data source, an attacker can cause the process to perform an excessive allocation on the stack.

This noncompliant 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 can be exploited to cause a denial-of-service attack.

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

  while (fgets(buf, bufsize, src)) {
    if (fputs(buf, dst) == EOF) {
      /* Handle error */
    }
  }

  return 0;
}

Wiki MarkupThe BSD extension function {{alloca()}} behaves in a similar fashion to variable-length arrays; its use is not recommended \[ [Loosemore 2007|AA. Bibliography#Loosemore 07]\].

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.

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MEM05-C

low

likely

medium

P6

L2

Automated Detection

Tool

Version

Checker

Description

Section

Coverity Prevent

Include Page
c:Coverity_Vc:
Coverity_V
Section

STACK_USE

Section

can help detect single stack allocations that are dangerously large, although it will not detect excessive stack use resulting from recursion

...

MISRA 2004 Rule 16.2

Bibliography

...

\[[Loosemore 2007|AA. Bibliography#Loosemore 07]\] [Section 3.2.5, "Automatic Storage with Variable Size"|http://www.gnu.org/software/libc/manual/html_mono/libc.html#Variable-Size-Automatic] \[[Seacord 2005a|AA. Bibliography#Seacord 05]\] Chapter 4, "Dynamic Memory Management" \[[van Sprundel 2006|http://ilja.netric.org/files/Unusual%20bugs.pdf]\] "Stack Size"
[Seacord 2005a] Chapter 4, "Dynamic Memory Management"
[van Sprundel 2006] "Stack Overflow"

...

MEM04-C. Do not perform zero length allocations      08. Memory Management (MEM)