Versions Compared

Key

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

According to C99, if the fgets() function fails, the contents of its parameterized array the array it was writing to are undefined. Therefore, As a result it is necessary to reset the string to a known value to avoid possible errors on subsequent string manipulation functions.

...

Code Block
bgColor#ffcccc
enum { BUFFERSIZE = 1024 };

char buf[BUFFERSIZE];
FILE *file;
/* Initialize file */

if (fgets(buf, sizeof(buf), file) == NULL) {
  /* set error flag and continue */
}
printf("Read in: %s\n", buf);

Compliant Solution

After fgets fails, In this compliant solution buf is set to an error message after fgets fails.

Code Block
bgColor#ccccff
enum { BUFFERSIZE = 1024 };

char buf[BUFFERSIZE];
FILE *file;
/* Initialize file */

if (fgets(buf, sizeof(buf), file) == NULL) {
  /* set error flag and continue */
  strcpy(buf, "fgets failed");
}
printf("Read in: %s\n", buf);

...

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

Mitigation Strategies

Static Analysis

Since the nature of this issue and the solution recommended by this rule is local, simple static analysis should be effective at assuring compliance with this rule.  A simple search should be able to find calls to fgets() and local analysis should be effective at finding the code that applies when a NULL is returned as well as determining if the returned string is reset. 

This rule also lends itself to inclusion in a global rules set that can be shipped with a static analysis tool.

Dynamic Analysis

It may be possible to assure compliance with this rule with some run-time mechanism.  However, it seems unlikely that dynamic analysis would be chosen over the straight forward static analysis considering the well known disadvantages of dynamic analysis (performance, hard to confirm that all cases are covered, etc.).

Manual inspection

Manual inspection (especially if assisted by tooling to locate all calls to fgets()) could be effective and relatively efficient. 

Testing

Due to the low level of this rule (all calls to fgets()), it seems unlikely that testing would be used to provide assurance of a codebase's compliance.

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.19.7.2, "The {{fgets}} function"

...