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

Compare with Current View Page History

« Previous Version 12 Next »

Upon return, functions should guarantee that any object returned by the function, or any modified value referenced by a pointer argument, is a valid object of function return type or argument type. Otherwise, type errors can occur in the program.

A good example is the null-terminated byte string type in C. If a string lacks the terminating null character, the program may be tricked into accessing storage after the string as legitimate data. A program may, as a result, process a string it should not process, which might be a security flaw in itself. It may also cause the program to abort, which might be a denial-of-service attack.

The emphasis of this rule is to avoid producing unterminated string; it does not address processing of already existing unterminated strings. However, by preventing the creation of unterminated strings, the need to process them is greatly lessened.

Noncompliant Code Example

The standard strncpy() function does not guarantee that the resulting string is null-terminated [ISO/IEC 9899:2011]. If there is no null character in the first n characters of the source array, the result may not be null-terminated.

char *source;
char a[NTBS_SIZE];
/* ... */
if (source) {
  errno_t err = strncpy(a, source, 5);
  if (err != 0) {
    /* Handle error */
  }
}
else {
  /* handle NULL string condition */
}

Compliant Solution (strncpy_s())

The strncpy_s() function copies up to n characters from the source array to a destination array [TR 24731]. If no null character was copied from the source array, the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.

char *source;
char a[NTBS_SIZE];
/* ... */
if (source) {
  errno_t err = strncpy_s(a, sizeof(a), source, 5);
  if (err != 0) {
    /* Handle error */
  }
}
else {
  /* handle NULL string condition */
}

Risk Assessment

Failure to enforce type safety can result in type errors in the program.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

API07-C

medium

unlikely

medium

P4

L3

Related Vulnerabilities

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

Related Guidelines

ISO/IEC 9899:2011 Section 7.24, "String handling <string.h>"

ISO/IEC TR 24772 "CJM String termination"

ISO/IEC TR 24731-1:2007 Section 6.7.1.4, "The strncpy_s function"

Sources


  • No labels