CERT.FIO.FGETS

A call to '{0}' can return an empty string that is later incorrectly assumed non-empty when accessing an array element.

This checker looks for potential buffer underflow defects happening due to incorrect assumptions after using the fgets() or fgetws() functions. These functions can return successfully and give an empty string. If the designer considers that these functions cannot return an empty string, then they are opening themselves to potential buffer underflows.

Vulnerability and risk

Buffer underflows may result in erratic program behavior, including memory access errors, incorrect results, a crash, or a breach of system security.

Consequences of buffer underflow include valid data being overwritten and execution of arbitrary and potentially malicious code. For example, buffer underflows can manipulate a program in several ways:

  • By overwriting a local variable that is near the buffer in memory to change the behavior of the program to benefit the attacker
  • By overwriting the return address in a stack frame so that execution resumes at the return address specified by the attacker (usually a user input-filled buffer)
  • By overwriting a function pointer or exception handler, which is subsequently executed

Vulnerable code example

Copy
#include <stdio.h>
#include <string.h>
 
enum { BUFFER_SIZE = 1024 };
 
void func(void) {
    char buf[BUFFER_SIZE];
 
    if (fgets(buf, sizeof(buf), stdin) == NULL) {
        return;
    }
    buf[strlen(buf) - 1] = '\0';
}

Klocwork reports defect CERT.FIO.FGETS on line 9 stating "A call to 'fgets' can return an empty string that is later incorrectly assumed non-empty when accessing an array element." This code is supposed to remove the trailing newline character from the input string, but if at line 9 the return value of the function fgets is a valid (non-null) pointer stored in the array 'buf', that can be empty. In this case, the call to strlen(buf) at line 12 will result in the value 0, will then be decremented by 1, and will be used to access the array 'buf'. Thus, there will be a buffer underflow with the index -1 at line 12.

Fixed code example

Copy
#include <stdio.h>
#include <string.h>
 
enum { BUFFER_SIZE = 1024 };
 
void func(void) {
    char buf[BUFFER_SIZE];
 
    if (fgets(buf, sizeof(buf), stdin) == NULL) {
        return;
    }
    size_t length = strlen(buf);
    if (length > 0) {
        buf[length - 1] = '\0';
    }
}

The defect here is now avoided since the code considers the case that the returned string is empty and will not try to remove the newline character in this case.