Local, automatic variables assume unexpected values if they are read before they are initialized. The C Standard, 6.7.9, paragraph 10, specifies [ISO/IEC 9899:2011] Show
See undefined behavior 11. When local, automatic variables are stored on the program stack, for example, their values default to whichever values are currently stored in stack memory. Additionally, some dynamic memory allocation functions do not initialize the contents of the memory they allocate.
Uninitialized automatic variables or dynamically allocated memory has indeterminate values, which for objects of some types, can be a trap representation. Reading such trap representations is undefined behavior; it can cause a program to behave in an unexpected manner and provide an avenue for attack. (See undefined behavior 10 and undefined behavior 12.) In many 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 (Return-by-Reference)In this noncompliant code example, the 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 for more information.) Compliant Solution (Return-by-Reference)This compliant solution trivially repairs the problem by accounting for the possibility that 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; } /* Account for number being 0 */ if (number >= 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 (Uninitialized Local)In this noncompliant code
example, the programmer mistakenly fails to set the local variable #include <stdio.h> /* Get username and password from user, return -1 on error */ extern int do_auth(void); enum { BUFFERSIZE = 24 }; void report_error(const char *msg) { 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 (Uninitialized Local)In this noncompliant code example, the #include <stdio.h> enum { BUFFERSIZE = 24 }; void report_error(const char *msg) { const char *error_log = msg; char buffer[BUFFERSIZE]; sprintf(buffer, "Error: %s", error_log); printf("%s\n", buffer); } This example remains problematic because a buffer overflow will occur if the null-terminated byte string referenced by Compliant Solution (Uninitialized Local)In this compliant solution, the buffer overflow is eliminated by calling the #include <stdio.h> enum { BUFFERSIZE = 24 }; void report_error(const char *msg) { char buffer[BUFFERSIZE]; if (0 < snprintf(buffer, BUFFERSIZE, "Error: %s", msg)) printf("%s\n", buffer); else puts("Unknown error"); } Compliant Solution (Uninitialized Local)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 #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 #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 described in
"More Randomness or Less" [Wang 2012], the process ID, time of day, and uninitialized memory #include <time.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.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. 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> #include <sys/time.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 ^ cpu_time); } Noncompliant Code Example (realloc())The It is the programmer's responsibility to ensure that any memory allocated with In this noncompliant code example, an array is allocated with #include <stdlib.h> #include <stdio.h> enum { OLD_SIZE = 10, NEW_SIZE = 20 }; int *resize_array(int *array, size_t count) { if (0 == count) { return 0; } int *ret = (int *)realloc(array, count * sizeof(int)); if (!ret) { free(array); return 0; } return ret; } void func(void) { int *array = (int *)malloc(OLD_SIZE * sizeof(int)); if (0 == array) { /* Handle error */ } for (size_t i = 0; i < OLD_SIZE; ++i) { array[i] = i; } array = resize_array(array, NEW_SIZE); if (0 == array) { /* Handle error */ } for (size_t i = 0; i < NEW_SIZE; ++i) { printf("%d ", array[i]); } } Compliant Solution (realloc())In this compliant solution, the #include <stdlib.h> #include <stdio.h> #include <string.h> enum { OLD_SIZE = 10, NEW_SIZE = 20 }; int *resize_array(int *array, size_t old_count, size_t new_count) { if (0 == new_count) { return 0; } int *ret = (int *)realloc(array, new_count * sizeof(int)); if (!ret) { free(array); return 0; } if (new_count > old_count) { memset(ret + old_count, 0, (new_count - old_count) * sizeof(int)); } return ret; } void func(void) { int *array = (int *)malloc(OLD_SIZE * sizeof(int)); if (0 == array) { /* Handle error */ } for (size_t i = 0; i < OLD_SIZE; ++i) { array[i] = i; } array = resize_array(array, OLD_SIZE, NEW_SIZE); if (0 == array) { /* Handle error */ } for (size_t i = 0; i < NEW_SIZE; ++i) { printf("%d ", array[i]); } } ExceptionsEXP33-C-EX1: Reading uninitialized memory by an
lvalue of type Risk AssessmentReading 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.
Automated Detection
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 these coding errors 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. Key here (explains table format and definitions) CERT-CWE Mapping NotesKey here for mapping notes CWE-119 and EXP33-C
CWE-676 and EXP33-C
CWE-758 and EXP33-CIndependent( INT34-C, INT36-C, MSC37-C, FLP32-C, EXP33-C, EXP30-C, ERR34-C, ARR32-C) CWE-758 = Union( EXP33-C, list) where list =
CWE-665 and EXP33-CIntersection( CWE-665, EXP33-C) = Ø CWE-665 is about correctly initializing items (usually objects), not reading them later. EXP33-C is about reading memory later (that has not been initialized). CWE-908 and EXP33-CCWE-908 = Union( EXP33-C, list) where list =
New CWE-CERT mappings: CWE-123 and EXP33-CIntersection( CWE-123, EXP33-C) = Ø EXP33-C is only about reading uninitialized memory, not writing, whereas CWE-123 is about writing. CWE-824 and EXP33-CEXP33-C = Union( CWE-824, list) where list =
BibliographyCan an if statement test expressions other than relational expressions?Can an if statement test expressions other than relational expressions? Yes - The if statement tests the expressions that returns the numeric value or Boolean value; that is True (or 1) or False (or 0).
What is the statement that causes an immediate exit from the switch structure?break is another keyword used by the switch statement. It causes immediate exit from the switch.
Is the default section required in a switch statement?The default section is required in a switch statement. An expression that has any value other than 0 is considered true by an if statement.
When a relational expression is false it has the value group of answer choices?Review Written Exam. |