Variable length arrays (VLAs) are essentially the same as traditional C arrays, the major difference being that they are declared with a size that is not a constant integer expression. A variable length array can be declared as follows:
char vla[s];
The above statement is evaluated at runtime, allocating storage for s
characters in stack memory. If a size argument supplied to VLAs is not a positive integer value of reasonable size, then the program may behave in an unexpected way. An attacker may be able to leverage this behavior to overwrite critical program data [Griffiths 06]. The programmer must ensure that size arguments to VLAs are valid and have not been corrupted as the result of an exceptional integer condition.
Non-Compliant Code Example
In this example, a VLA of size s
is declared. In accordance with recommendation INT01-A. Use rsize_t or size_t for all integer values representing the size of an object, s
is of type size_t
, as it is used to specify the size of an object. However, it is unclear whether the value of s
is a valid size argument. Depending on how VLAs are implemented, s
may be interpreted as a negative value or a very large positive value. In either case, this may result in a security vulnerability.
void func(size_t s) { int vla[s]; /* ... */ } /* ... */ func(size); /* ... */
Compliant Code Solution
Validate size arguments used in VLA declarations. The solution below ensures the size argument, s
, used to allocate vla
is in a valid range: 1 to a user-defined constant.
enum { MAX_ARRAY = 1024 }; void func(size_t s) { if (s < MAX_ARRAY && s != 0) { int vla[s]; /* ... */ } else { /* Handle Error */ } } /* ... */ func(size); /* ... */
Implementation Details
Variable length arrays are not supported by Microsoft compilers.
Risk Assessment
Failure to properly specify the size of a variable length array may allow arbitrary code execution or result in stack exhaustion.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
ARR32-C |
3 (high) |
3 (probable) |
2 (high) |
P6 |
L1 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[Griffiths 06]]
ARR31-C. Use consistent array notation across all source files 06. Arrays (ARR) ARR33-C. Guarantee that copies are made into storage of sufficient size