The fgets() function is typically used to read a newline-terminated line of input from a stream. The fgets() function takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string. Truncation errors can occur if the programmer blindly assumes that the last character in the destination string will be a newline.
Non-Compliant Code Example
This non-compliant code example is intended to be used to remove the trailing newline (\n) from an input line.
...
However, if the last character in buf is not a newline, this code overwrites an otherwise-valid character.
Compliant Solution
This compliant solution uses strchr() to replace the newline character in the string (if it exists).
| Code Block | ||
|---|---|---|
| ||
char buf[BUFSIZ + 1];
char *p;
if (fgets(buf, sizeof(buf), fp)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
}
else {
/* handle error condition */
}
|
Risk Assessment
Assuming a newline character is read can result in data truncation.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FI036-C | 2 (medium) | 1 (unlikely) | 3 (low) | P6 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
| Wiki Markup |
|---|
\[[Lai 06|AA. C References#Lai 06]\] \[[Seacord 05|AA. C References#Seacord 05]\] Chapter 2, "Strings" \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.19.7.2, "The fgets function" |