Local, automatic variables assume unexpected values if they are read before they are initialized. The C Standard, subclause 6.7.9 paragraph 10 specifies [ISO/IEC 9899:2011]:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
(See also undefined behavior 11 in Annex J.)
In the common case of local, automatic variables being stored on the program stack, their values default to whichever values are currently stored in stack memory. Uninitialized memory has indeterminate value, which for objects of some types can be a trap representation. Reading uninitialized memory is undefined behavior (see undefined behavior 10 and undefined behavior 12 in Annex J of the C Standard); it can cause a program to behave in an unexpected manner and provide an avenue for attack.
Additionally, memory allocated by functions, such as malloc()
, should not be read before being initialized because its contents are also indeterminate.
In most cases, compilers issue a warning diagnostic message when reading uninitialized variables. See MSC00-C. Compile cleanly at high warning levels for more information.
Noncompliant Code Example
In this noncompliant code example, the set_flag()
function is intended to set the parameter, sign_flag
, to the sign of number
. However, the programmer neglected to account for number
being 0
. Because the local variable sign
is uninitialized when calling set_flag()
, and is never written to by set_flag()
, the comparison operation exhibits undefined behavior when reading sign
.
void set_flag(int number, int *sign_flag) { if (NULL == sign_flag) { return; } if (number > 0) { *sign_flag = 1; } else if (number < 0) { *sign_flag = -1; } } int is_negative(int number) { int sign; set_flag(number, &sign); return sign < 0; }
Some compilers assume that when the address of an uninitialized variable is passed to a function, the variable is initialized within that function. Because compilers frequently fail to diagnose any resulting failure to initialize the variable, the programmer must apply additional scrutiny to ensure the correctness of the code.
This defect results from a failure to consider all possible data states. (See MSC01-C. Strive for logical completeness.) Once the problem is identified,
Compliant Solution
This compliant solution trivially repairs the problem by accounting for the possibility that number
can be equal to 0.
Although compilers and static analysis tools often detect uses of uninitialized variables when they have access to the source code, diagnosing the problem is difficult or impossible when either the initialization or the use takes place in object code for which the source code is inaccessible. Unless doing so is prohibitive for performance reasons, an additional defense-in-depth practice worth considering is to initialize local variables immediately after declaration.
void set_flag(int number, int *sign_flag) { if (NULL == sign_flag) { return; } if (number >= 0) { /* Account for number being 0 */ *sign_flag = 1; } else { *sign_flag = -1; } } int is_negative(int number) { int sign = 0; /* Initialize for defense-in-depth */ set_flag(number, &sign); return sign < 0; }
Noncompliant Code Example
In this noncompliant code example, the programmer mistakenly fails to set the local variable error_log
to the msg
argument in the report_error()
function [Mercy 2006]. Because error_log
has not been initialized, reading it results in undefined behavior, and an indeterminate value is read. The sprintf()
call copies data from the arbitrary location pointed to by the indeterminate error_log
variable until a null byte is reached, which can result in a buffer overflow.
#include <stdio.h> /* Get username and password from user, return -1 on error */ extern int do_auth(void); void report_error(const char *msg) { enum { BUFFERSIZE = 24 }; const char *error_log; char buffer[BUFFERSIZE]; sprintf(buffer, "Error: %s", error_log); printf("%s\n", buffer); } int main(void) { if (do_auth() == -1) { report_error("Unable to login"); } return 0; }
Noncompliant Code Example
In this noncompliant code example, the report_error()
function has been modified so that error_log
is properly initialized:
#include <stdio.h> void report_error(const char *msg) { enum { BUFFERSIZE = 24 }; const char *error_log = msg; char buffer[BUFFERSIZE]; sprintf(buffer, "Error: %s", error_log); printf("%s\n", buffer); }
This example is still problematic because a buffer overflow will occur if the null-terminated byte string referenced by msg
is greater than 17 characters, including the null terminator. For more information, see STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator.
Compliant Solution
In this compliant solution, the buffer overflow is eliminated by using the snprintf()
function:
#include <stdio.h> void report_error(const char *msg) { enum { BUFFERSIZE = 24 }; const char *error_log = msg; char buffer[BUFFERSIZE]; snprintf(buffer, BUFFERSIZE, "Error: %s", error_log); printf("%s\n", buffer); }
Compliant Solution
A less error-prone compliant solution is to simply print the error message directly instead of using an intermediate buffer:
#include <stdio.h> void report_error(const char *msg) { printf("Error: %s\n", msg); }
Noncompliant Code Example (mbstate_t
)
In this noncompliant code example, the function mbrlen()
is passed the address of an automatic mbstate_t
object that has not been properly initialized. This leads to undefined behavior, because mbrlen()
dereferences and reads its third argument. See undefined behavior 200 in Annex J of the C Standard.
#include <string.h> #include <wchar.h> void func(const char *mbs) { size_t len; mbstate_t state; len = mbrlen(mbs, strlen(mbs), &state); }
Compliant Solution (mbstate_t
)
Before being passed to a multibyte conversion function, an mbstate_t
object must be either initialized to the initial conversion state or set to a value that corresponds to the most recent shift state by a prior call to a multibyte conversion function. The compliant solution sets the mbstate_t
object to the initial conversion state by setting it to all zeros.
#include <string.h> #include <wchar.h> void func(const char *mbs) { size_t len; mbstate_t state; memset(&state, 0, sizeof(state)); len = mbrlen(mbs, strlen(mbs), &state); }
Noncompliant Code Example (POSIX, Entropy)
In this noncompliant code example, the process ID, time of day, and uninitialized memory junk
is used to seed a random number generator. This behavior is characteristic of some distributions derived from Debian that use uninitialized memory as a source of entropy because the value stored in junk
is indeterminate. However, because accessing indeterminate values is undefined behavior, compilers may optimize out the uninitialized variable access completely, leaving only the time and process ID and resulting in a loss of desired entropy.
#include <time.h> #include <unistd.h> #include <stdlib.h> void func(void) { struct timeval tv; unsigned long junk; gettimeofday(&tv, NULL); srandom((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ junk); }
In security protocols that rely on unpredictability, such as RSA encryption, a loss in entropy results in a less secure system [Wang 2012].
Compliant Solution (POSIX, Entropy)
This compliant solution seeds the random number generator by using the CPU clock and the real-time clock instead of reading uninitialized memory:
#include <time.h> #include <unistd.h> #include <stdlib.h> void func(void) { double cpu_time; struct timeval tv; cpu_time = ((double) clock()) / CLOCKS_PER_SEC; gettimeofday(&tv, NULL); srandom((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec); }
Exceptions
EXP33-EX0: Reading uninitialized memory of type unsigned char
does not trigger undefined behavior. The unsigned char
type is defined to not have a trap representation (see the C Standard, subclause 6.2.6.1, paragraph 3), which allows for moving bytes without knowing if they are initialized. However, on some architectures, such as the Intel Itanium, registers have a bit to indicate whether or not they have been initialized. The C Standard, subclause 6.3.2.1, paragraph 2, allows such implementations to cause a trap for an object that never had its address taken and is stored in a register if such an object is referred to in any way.
Risk Assessment
Reading uninitialized variables is undefined behavior and can result in unexpected program behavior. In some cases, these security flaws may allow the execution of arbitrary code.
Reading uninitialized variables for creating entropy is problematic, because these memory accesses can be removed by compiler optimization. VU#925211 is an example of a vulnerability caused by this coding error.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP33-C | High | Probable | Medium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
Compass/ROSE | Automatically detects simple violations of this rule, although it may return some false positives. It may not catch more complex violations, such as initialization within functions taking uninitialized variables as arguments. It does catch the second noncompliant code example, and can be extended to catch the first as well | ||
Coverity | 6.5 | UNINIT NO_EFFECT | Fully implemented Can find cases of an uninitialized variable being used before it is initialized, although it cannot detect cases of uninitialized members of a |
Fortify SCA | Can detect violations of this rule but will return false positives if the initialization was done in another function | ||
GCC | 4.3.5 | Can detect some violations of this rule when the | |
9.1 | UNINIT.HEAP.MIGHT | ||
9.7.1 | 57 D | Fully implemented | |
PRQA QA-C | Unable to render {include} The included page could not be found. | 2961 (D) 2962 (A) 2963 (S) 2971 (D) 2972 (A) | Fully implemented |
Splint | 3.1.1 |
Related Vulnerabilities
CVE-2009-1888 results from a violation of this rule. Some versions of SAMBA (up to 3.3.5) call a function that takes in two potentially uninitialized variables involving access rights. An attacker can exploit this to bypass the access control list and gain access to protected files [xorl 2009].
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C Secure Coding Standard | MSC00-C. Compile cleanly at high warning levels MSC01-C. Strive for logical completeness |
CERT C++ Secure Coding Standard | EXP33-CPP. Do not reference uninitialized memory |
ISO/IEC TR 24772:2013 | Initialization of Variables [LAV] |
ISO/IEC TS 17961 | Referencing uninitialized memory [uninitref] |
Bibliography
[Flake 2006] | |
[ISO/IEC 9899:2011] | Subclause 6.7.9, "Initialization" Subclause 6.2.6.1, "General" Subclause 6.3.2.1, "Lvalues, arrays, and function designators" |
[Mercy 2006] | |
[Wang 2012] | "More Randomness or Less" |
[xorl 2009] | "CVE-2009-1888: SAMBA ACLs Uninitialized Memory Read" |