Errors can occur when assumptions are made about the type of data being read. These assumptions may be violated, for example, when binary data has been read from a file instead of text from a user's terminal. (See recommendation FIO14-C. Understand the difference between text mode and binary mode with file streams.) On some systems, it may also be possible to input a null byte (as well as other binary codes) from the keyboard.
C99, Section 7.1921.7.2 , "The fgets function", paragraph 3 saysof 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.
Therefore, if fgets() returns a non-null pointer, we can assume it actually filled the array with data. However, assuming that it filled the array with a non-empty nonempty null-terminated byte string (NTBS) is erroneous because the data it placed in the array may contain null characters.
...
This noncompliant code example attempts to remove the trailing new-line newline (\n) from an input line. The fgets() function is typically used to read a newnewline-line terminated - line of input from a stream. It takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a character array.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char buf[BUFSIZ + 1];
if (fgets(buf, sizeof(buf), stdin) == NULL) {
/* Handle error */
}
buf[strlen(buf) - 1] = '\0';
|
...
This compliant solution uses strchr() to replace the new-line newline character in the string , if it exists. (See rue FIO36-C. Do not assume a new-line newline character is read when using fgets().)
| Code Block | ||||
|---|---|---|---|---|
| ||||
char buf[BUFSIZ + 1];
char *p;
if (fgets(buf, sizeof(buf), stdin)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
}
else {
/* Handle error condition */
}
|
...
Tool | Version | Checker | Description | ||
|---|---|---|---|---|---|
| Section | Fortify SCA section | V. 5.0 |
|
| |
| Section | |
|
| | Section | Could detect some violations of this rule. In particular, it could detect the NCCE bythe noncompliant code example by searching for −1. The crux of this rule is that a string returned by they would need to enumerate thembe enumerated before ROSE could detect them. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: FIO37-CPP. Do not assume character data has been read
ISO/IEC 9899:1999 Section 2011 Section 7.1921.7.2, "The fgets function"
MITRE CWE: CWE-119, "Failure to Constrain Operations constrain operations within the Bounds bounds of an Allocated Memory Bufferallocated memory buffer"
MITRE CWE: CWE-241, "Failure to Handle Wrong Data Typehandle wrong data type"
Bibliography
[Lai 2006]
[Seacord 2005a] Chapter 2, "Strings"
...