...
Noncompliant Code Example
C99 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. Wiki Markup
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 | ||||
---|---|---|---|---|
| ||||
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; } |
The BSD extension function {{ Wiki Markup 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 | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
|
...
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)