Versions Compared

Key

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

ISO/IEC TR 24731 The C Standard, Annex K (normative), defines alternative versions of C standard string-handling functions that are designed to be safer replacements for existing functions. For example, ISO/IEC TR 24731 Part I (24731-1)  it defines the strcpy_s(), strcat_s(), strncpy_s(), and strncat_s() functions as replacements for strcpy(), strcat(), strncpy(), and strncat(), respectively.

The ISO/IEC TR 24731-1 The Annex K functions were created by Microsoft to help retrofit its existing , legacy code base in response to numerous, well-publicized security incidents over the past decade. These functions were subsequently proposed to the international standardization working group for the programming language C (ISO/IEC JTC1/SC22/WG14) for standardization.

The strcpy_s() function, for example, has this signature:

Code Block

errno_t strcpy_s(
   char * restrict s1,
   rsize_t s1max,
   const char * restrict s2
);

The signature is similar to strcpy() but takes an extra argument of type rsize_t that specifies the maximum length of the destination buffer. ( Functions that accept parameters of type rsize_t diagnose a constraint violation if the values of those parameters are greater than RSIZE_MAX. Extremely large object sizes are frequently a sign that an object's size was calculated incorrectly. For example, negative numbers appear as very large positive numbers when converted to an unsigned type like size_t. For those reasons, it is sometimes beneficial to restrict the range of object sizes to detect errors. For machines with large address spaces, ISO/IEC TR 24731-1 , the C Standard, Annex K, recommends that RSIZE_MAX be defined as the smaller of the size of the largest object supported or (SIZE_MAX >> 1), even if this limit is smaller than the size of some legitimate, but very large, objects . See (see also INT01-AC. Use rsize_t or size_t for all integer values representing the size of an object).)

The semantics of strcpy_s() are also similar to the semantics of strcpy(). When there are no input validation errors, the strcpy_s() function copies characters from a source string to a destination character array up to and including the terminating null character. The function returns zero returns 0 on success.

The strcpy_s() function succeeds only succeeds when the source string can be fully copied to the destination without overflowing the destination buffer. Specifically, the following checks are made:

  • The source and destination pointers are checked to see if they are null NULL.
  • The maximum length of the destination buffer is checked to see if it is equal to zero0, greater than RSIZE_MAX, or less than or equal to the length of the source string.
  • Copying is not allowed between objects that overlap.

When a runtime-constraint violation is detected, the destination string is set to the null string (as long as it is not a null pointer, and the maximum length of the destination buffer is greater than zero than 0 and not greater than RSIZE_MAX), and the function returns a nonzero value. In the following example, the strcpy_s() function is used to copy src1 to dst1.:

Code Block

char src1[100] = "hello";
char src2[8] =  {'g','o','o','d','b','y','e','\0'};
char dst1[6],;
char dst2[5];
int r1,;
int r2;

r1 = strcpy_s(dst1, sizeof(dst1), src1);
r2 = strcpy_s(dst2, sizeof(dst2), src2);

Wiki MarkupHowever, 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.

Users of the ISO/IEC TR 24731-1 C Standard Annex K functions are less likely to introduce a security flaw because the size of the destination buffer and the maximum number of characters to append must be specified.   ISO/IEC TR 24731 Part II ([ISO/IEC TR 24731-2, in progress) will offer :2010] offers another approach, supplying functions that allocate enough memory for their results.   ISO/IEC TR 24731 Part II functions also ensure null termination of the destination string.

ISO/IEC TR 24731-1 The C Standard Annex K functions are still capable of overflowing a buffer if the maximum length of the destination buffer and number of characters to copy are incorrectly specified.    ISO/IEC TR 24731 -2 Part II functions may can make it more difficult to keep track of memory that must be freed, leading to memory leaks.   As a result, the C Standard Annex K and the ISO/IEC TR 24731 Part II functions are not especially particularly secure but may be useful in preventive maintenance to reduce the likelihood of vulnerabilities in an existing legacy code base.

...

Noncompliant Code Example

The following non-compliant This 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);
}

Compliant Solution (

...

Runtime)

The following This compliant solution will not overflow its buffer.:

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];

  if ((err = strcpy_s(buf, sizeof(buf), prefix));
  if (err != 0) {
    /* handleHandle error */
  }

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

  fputs(buf, stderr);
}

Compliant Solution (

...

Partial Compile Time)

The following This compliant solution performs some of the checking at compile time using a static assertion (see DCL03-AC. Use a static assertion to test the value of a constant expression).

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);

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

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

Risk Assessment

String-handling functions defined in C99 Section the C Standard, subclause 7.21 24, and elsewhere are susceptible to common programming errors that can lead to serious, exploitable vulnerabilities. Proper use of TR 24731 the C11 Annex K functions can eliminate the majority eliminate most of these issues.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

STR00

STR07-

A

C

high

High

probable

Probable

medium

Medium

P12

L1

Automated Detection

...

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V

Supported
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-STR07
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

BADFUNC.BO.OEMTOCHAR
BADFUNC.BO.STRCAT
BADFUNC.BO.STRCATCHAINW
BADFUNC.BO.STRCHR
BADFUNC.BO.STRCMP
BADFUNC.BO.STRCOLL
BADFUNC.BO.STRCPY
BADFUNC.BO.STRCSPN
BADFUNC.BO.STRLEN
BADFUNC.BO.STRPBRK
BADFUNC.BO.STRRCHR
BADFUNC.BO.STRSPN
BADFUNC.BO.STRSTR
BADFUNC.BO.STRTOK
BADFUNC.BO.STRTRNS


Use of OemToAnsi, use of OemToChar (both include checks for uses of similar functions)
Use of strcat (includes checks for uses of similar library functions such as StrCatA(), wcscat(), etc.)
Use of StrCatChainW
Use of strchr
Use of strcmp (includes checks for uses of similar library functions such as lstrcmp())
Use of strcoll
Use of strcpy (includes checks for uses of similar library functions such as StrCCpy(), wcscpy(), etc.)
Use of strcspn
Use of strlen (includes checks for uses of similar library functions such as lstrlen())
Use of strpbrk
Use of strrchr
Use of strspn
Use of strstr
Use of strtok
Use of strtrns

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C5008
LDRA tool suite
Include Page
LDRA_V
LDRA_V

44 S

Enhanced enforcement

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V

CERT_C-STR07-a

Avoid using unsafe string functions that do not check bounds

Parasoft Insure++

Runtime analysis
PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

586

Fully supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rec. STR07-C

Checks for:

  • Use of dangerous standard function
  • Destination buffer overflow in string manipulation
  • Insufficient destination buffer size

Rec. partially covered.

SonarQube C/C++ Plugin
Include Page
SonarQube C/C++ Plugin_V
SonarQube C/C++ Plugin_V
S1081

Related Vulnerabilities

Search for 

The LDRA tool suite V 7.6.0 is able to detect violations of this recommendation.

Related Vulnerabilities

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

References

...

Related Guidelines

...

...

...

...

2:2010
ISO/IEC TR 24772:2013Use of Libraries [TRJ]

Bibliography

[Seacord 2005b]"Managed String Library for C, C/C++"
[Seacord 2013]Chapter 2, "Strings"


...

Image Added Image Added TR 24731-1-2007]\] \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.21, "String handling <string.h>" \[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 2, "Strings" \[[Seacord 05b|AA. C References#Seacord 05b]\]STR06-A. Do not assume that strtok() leaves the parse string unchanged      07. Characters and Strings (STR)       Image Modified