Variable length arrays (VLAs), a conditionally supported language feature, are essentially the same as traditional C arrays except that they are declared with a size that is not a constant integer expression and can be declared only at block scope or function prototype scope and no linkage. A variable When supported, a variable length array can be declared
Code Block |
---|
{ /* Block scope */ char vla[size]; } |
where the integer expression size
and the declaration of vla
are both evaluated at runtime. If the size argument supplied to a variable length array is not a positive integer value, the behavior is undefined (see undefined behavior 75).) Additionally, if the magnitude of the argument is excessive, the program may behave in an unexpected way. An attacker may be able to leverage this behavior to overwrite critical program data [Griffiths 2006]. The programmer must ensure that size arguments to variable length arrays, especially those derived from untrusted data, are in a valid range.
Because variable length arrays are a conditionally supported feature of C11, their use in portable code should be guarded by testing the value of the macro __STDC_NO_VLA__
. Implementations that do not support variable length arrays indicate so by setting __STDC_NO_VLA__
to the integer constant 1.
Noncompliant Code Example
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stddef.h> void func(size_t size) { int vla[size]; /* ... */ } |
However, it is not guaranteed that the value of size
is a valid size argument may be zero or excessive, potentially giving rise to a security vulnerability.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> enum { MAX_ARRAY = 1024 }; extern void do_work(int *array, size_t size); void func(size_t size) { if (0 < size && size < MAX_ARRAY) { int vla[size]; do_work(vla, size); } else { int *array = (int *)malloc(size * sizeof(int)); if (array == NULNULL) { /* Handle error */ } do_work(array, size); free(array); } } |
...
On an example Debian GNU/Linux Intel 32-bit test machine with GCC 4.2.2, the value of a variable length array's size is interpreted as a 32-bit signed integer. Passing in a negative number for the size will likely cause the program stack to become corrupted, and passing in a large positive number may cause a terminal stack overflow. It is important to note that this information may become outdated as GCC evolves.
...
Failure to properly specify the size of a a variable length array may allow arbitrary code execution or result in stack exhaustion.
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C Secure Coding Standard | INT01-C. Use rsize_t or size_t for all integer values representing the size of an object |
ISO/IEC TR 24772:2013 | Unchecked Array Indexing [XYZ] |
ISO/IEC TS 17961:2013 | Tainted, potentially mutilated, or out-of-domain integer values are used in a restricted sink [taintsink] |
...