You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 13 Next »

The strlen() function computes the length of a string. It returns the number of characters that precede the terminating NULL character. Errors can occur when assumptions are made about the type of data being passed to strlen(), e.g., in cases where binary data has been read from a file instead of textual data from a user's terminal.

Non-Compliant Code Example

This non-compliant code example is intended to be used to remove the trailing newline (\n) from an input line. The fgets() function is typically used to read a newline-terminated line of input from a stream, takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string.

char buf[1024];

fgets(buf, sizeof(buf), fp);
buf[strlen(buf) - 1] = '\0';

However, if the first character in buf is a NULL, strlen(buf) will return 0 and a write-outside-array-bounds error will occur.

Compliant Solution

This compliant solution checks to make sure the first character in the buf array is not a NULL before modifying it based on the results of strlen().

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 character data has been read can result in out-of-bounds memory writes.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FI037-C

2 (medium)

1 (unlikely)

2 (medium)

P4

L3

Examples of vulnerabilities resulting from the violation of this rule can be found on the CERT website.

References

[[ISO/IEC 9899-1999]] Section 7.19.7.2, "The fgets function"
[[Lai 06]]
[[Seacord 05]] Chapter 2, "Strings"

  • No labels