Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

h2. Non-Compliant Code Example 2

In this example, user input is copied to the character array buf. The logit() function copies the user input to another buffer, buffer, and prints it to standard output. Next, the runit() routine is called. This routine declares an array of 50 characters, buf, and a character pointer, ptr. However, because ptr is not initialized it references data used by the last function called, in this case, the contents of the user controlled data copied in the logit() function. When the data referred to by ptr is copied to buf using an unbounded strcpy(), ptr is dereferenced and the data in that location is copied to buf. If the memory referred to by ptr contains more than 50 characters without a null character, a buffer overflow will occur.

Code Block

#define BUF_SIZE 150

void runit(void) {
    char buf[50];
    char *ptr;

    memset(buf,0,50);
    strcpy(buf,ptr);
}

void logit(char *str) {
    char buffer[BUF_SIZE];

    strcpy(buffer, str);
    printf("The message: %s\nhas been logged\n",buffer);
}

int main(int argc, char *argv[]) {
    char buf[BUF_SIZE];

    strcpy(buf, argv[1]);
    logit(buf);
    runit();
}

h2. Compliant Solution 2

The local variable ptr should be initialized to a default value, in this case NULL.

Code Block

#define BUF_SIZE 150

void runit(void) {
    char buf[50];
    char *ptr = NULL; /* initialize ptr to 0 */

    memset(buf,0,50);
    strcpy(buf,ptr);
}

void logit(char *str) {
    char buffer[BUF_SIZE];
    int i;
    for (i=0; i < BUF_SIZE; ++i) buffer[i] = '\0';

    strcpy(buffer, str);
    printf("The message: %s\nhas been logged\n",buffer);
}

int main(int argc, char *argv[]) {
    char buf[BUF_SIZE];

    strcpy(buf, argv[1]);
    logit(buf);
    runit();
}

Priority: P2 Level: L2

Uninitialized variables are relatively unlikely to result in an exploitable vulnerability because most compilers provide warnings when an uninitialized variable is referenced and most programmers take these warnings seriously.

Component

Value

Severity

1 (low)

Likelihood

1 (unlikely)

Remediation cost

2 (high)

References