...
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 | ||||
---|---|---|---|---|
| ||||
#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 = ret; if (!ret) { 0; 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 | ||||
---|---|---|---|---|
| ||||
#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 | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO20-C | mediumMedium | likelyLikely | mediumMedium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
LDRA tool suite |
| 44 S | Enhanced enforcement |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard | FIO36-CPP. Do not assume a new-line character is read when using fgets() |
Bibliography
[Lai 2006] | |
[Seacord 2013] | Chapter 2, "Strings" |
...