Versions Compared

Key

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

The C Standard, Annex K (normative), "Bounds-checking interfacesChecking Interfaces" [ISO/IEC 9899:2011], defines alternative versions of standard string-handling functions designed to be safer replacements for existing functions. For example, it defines the strcpy_s(), strcat_s(), strncpy_s(), and strncat_s() functions as replacements for strcpy(), strcat(), strncpy(), and strncat(), respectively.

...

However, the call to copy src2 to dst2 fails because there is insufficient space is available to copy the entire string, which consists of eight characters, to the destination buffer. As a result, r2 is assigned a nonzero value and dst2[0] is set to the null character.

...

The following noncompliant code overflows its buffer if msg is too long, and it has undefined behavior if msg is a null pointer:

Code Block
bgColor#FFCCCC
langc
void complain(const char *msg) {
  static const char prefix[] = "Error: ";
  static const char suffix[] = "\n";
  char buf[BUFSIZ];

  strcpy(buf, prefix);
  strcat(buf, msg);
  strcat(buf, suffix);
  fputs(buf, stderr);
}

...

Code Block
bgColor#ccccff
langc
void complain(const char *msg) {
  errno_t err;
  static const char prefix[] = "Error: ";
  static const char suffix[] = "\n";
  char buf[BUFSIZ];

  /* Ensure that more than one character
   * is available for msg. */
  static_assert(sizeof(buf) > sizeof(prefix) + sizeof(suffix),
                "Buffer for complain() is too small");
  strcpy(buf, prefix);

  err = strcat_s(buf, sizeof(buf), msg);
  if (err != 0) {
    /* Handle error */
  }

  err = strcat_s(buf, sizeof(buf), suffix);
  if (err != 0) {
    /* Handle error */
  }
  fputs(buf, stderr);
}

...

String-handling functions defined in the C Standard, Section subclause 7.24 [ISO/IEC 9899:2011], and elsewhere are susceptible to common programming errors that can lead to serious, exploitable vulnerabilities. Proper use of the C11 Annex K functions can eliminate most of these issues.

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

 

 

PRQA QA-C
Include Page
PRQA_V
PRQA_V
Warncall -wc strcpy,
-wc strcat,
-wc strncpy,
-wc strncat
Partially implemented

...

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

Related Guidelines

...

...