Versions Compared

Key

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

Avoid in-band error indicators while designing interfaces. This practice is commonly used by C library functions but is not recommended. One example from the C Standard of a troublesome in-band error indicator is EOF. (See FIO34-C. Use int to capture the return value of character IO functions and FIO35-C. Use feof() and ferror() to detect end-of-file and file errors when sizeof(int) == sizeof(char).) Another problematic use of in-band error indicators from the C Standard involving the size_t and time_t types is described by MSC31-C. Ensure that return values are compared against the proper type.

...

Code Block
bgColor#FFCCCC
langc
constraint_handler_t handle_errors(void) {
  constraint_handler_t data;
  /* Define what to do when error occurs */
  return data;
}

/* ... */

set_constraint_handler(handle_errors);

/* ... */

/* Returns zero on success */
errno_t function(char *dst1){
  char src1[100] = "hello";

  strcpy_s(dst1, sizeof(dst1), src1);
  /* 
   * At this point strcpy_s may have yielded an
   *  error, and handle_errors() might have returned.
   */

  /* ... */
  return 0;
}

Compliant Solution (C11, Annex K)

...

Code Block
bgColor#CCCCFF
langc
/*
 * The abort_handler_s() function writes 
 * a message on the
 * standard error stream and
 * then calls the abort() function.
 */
set_constraint_handler(abort_handler_s);

/* ... */

/* Returns zero on success */
errno_t function(char *dst1){
  char src1[100] = "hello";

  strcpy_s(dst1, sizeof(dst1), src1);
  /*
   * Because abort_handler_s() never returns,
    * we only get here only if strcpy_s() succeeds.
   */

  /* ... */
  return 0;
}

Exceptions

ERR02-EX1: Null pointers are another example of an in-band error indicator. Use of null pointers is allowed because it is supported by the language. According to the C Standard, Section subclause 6.3.2.3 [ISO/IEC 9899:2011]:

If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

ERR02-C

lowLow

unlikelyUnlikely

highHigh

P1

L3

Related Vulnerabilities

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

...

Bibliography

[Burch 2006] 
[ISO/IEC 9899:2011]

Section 6.3.2, "Other Operands"
Annex K, "Bounds-checking Interfaces"

...