Versions Compared

Key

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

...

This compliant solution solves the problem by expanding the buffer to read the entire contents from stdin instead of failing if the caller did not allocate enough space.  If the allocation fails, it will return NULL, but otherwise, it returns a buffer of the received data, which the caller must free.

 

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_filled_buffer(void) {
  char temp[32];
  char *ret = malloc(sizeof(temp))NULL;
  char *endsize_t full_length = ret0;
  if (!ret) {
    return NULL;
  }

  while (fgets(temp, sizeof(temp), stdin)) {
    size_t len = strlen(temp);
    constif size_t(SIZE_MAX - len - 1 < full_sizelength) {
 = end - ret + lenbreak;
    }
    char *r_temp = realloc(ret, full_sizelength + len + 1); /* NTBS */
    if (r_temp == NULL) {
      retbreak;
 = r_temp;
  }
    strcat(ret, = r_temp);
      end = strcpy(ret + full_sizelength, temp);
 /*   } else {concatenate */
    full_length += breaklen;
    }

    if (feof(stdin) || temp[len-1] == '\n') {
      return ret;
    }
  }

  free(ret);
  return NULL;
}

Compliant Solution (POSIX getline())

The getline() function was originally a GNU extension, but is now standard in POSIX.1-2008. It also fills a string with characters from an input stream. In this case, the program passes it a NULL pointer for a string, indicating that getline() should allocate sufficient space for the string and the caller frees it later.

Code Block
bgColor#ccccff
langc
#include <stdio.h>

void func(void) {
  char* buf = NULL;
  size_t dummy = 0;
  if (getline(&buf, &dummy, stdin) == -1) {
	/* handle error */
  }
  printf("The user input %s\n", buf);
  free(buf);
}

Risk Assessment

Incorrectly assuming a newline character is read by fgets() or fgetws() can result in data truncation.

Recommendation

Severity

Likelihood

Detectable

Remediation Cost

Repairable

Priority

Level

FIO20-C

Medium

medium

Likely

likely

No

medium

Yes

P12

L1

Automated Detection

Tool

Version

Checker

Description

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C3591
C3592


LDRA tool suite
Include Page
LDRA_V
LDRA_V
44 SEnhanced enforcement

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...

Bibliography

[Lai 2006]
 

[Seacord 2013]Chapter 2, "Strings"

...


...

Image Modified Image Modified Image Modified