...
Subclause 7.21.7.2 of the C Standard [ISO/IEC 9899:2011] says,
The
fgetsfunction returnssif successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
#include <string.h>
void func(void) {
char buf[BUFSIZ];
char *p;
if (fgets(buf, sizeof(buf), stdin)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
} else {
/* Handle error */
}
} |
Risk Assessment
Assuming that character data has been read can result in an out-of-bounds memory write.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FIO37-C | highHigh | probableProbable | mediumMedium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description |
|---|---|---|---|
| Compass/ROSE |
|
| Could detect some violations of this rule. In particular, it could detect the noncompliant code example by searching for |
5.0 |
|
|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
| CERT C Secure Coding Standard | FIO14-C. Understand the difference between text mode and binary mode with file streams FIO20-C. Avoid unintentional truncation when using fgets() or fgetws() |
| CERT C++ Secure Coding Standard | FIO37-CPP. Do not assume character data has been read |
| MITRE CWE | CWE-119, Failure to constrain operations within the bounds of an allocated memory buffer CWE-241, Failure to handle wrong data type |
Bibliography
| [ISO/IEC 9899:2011] | Subclause 7.21.7.2, "The fgets Function" |
| [Lai 2006] | |
| [Seacord 2013] | Chapter 2, "Strings" |
...