Versions Compared

Key

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

Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object. Do not pass a character sequence or wide character sequence that is not null-terminated to a library function that expects a string or wide string argument. 

Noncompliant Code Example

This code example is noncompliant because the character sequence c_str will not be null-terminated when passed as an argument to printf(). (See STR11-C. Do not specify the bound of a character array initialized with a string literal on how to properly initialize character arrays.)

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
 
void func(void) {
  char c_str[3] = "abc";
  printf("%s\n", c_str);
}

Compliant Solution

This compliant solution does not specify the bound of the character array in the array declaration. If the array bound is omitted, the compiler allocates sufficient storage to store the entire string literal, including the terminating null character.

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
void func(void) {
  char c_str[] = "abc";
  printf("%s\n", c_str);
}

Noncompliant Code Example

This code example is noncompliant because the wide character sequence cur_msg will not be null-terminated when passed to wcslen(). This will occur if lessen_memory_usage() is invoked while cur_msg_size still has its initial value of 1024.

Code Block
bgColor#ffcccc
langc
#include <stdlib.h>
#include <wchar.h>
 
wchar_t *cur_msg = NULL;
size_t cur_msg_size = 1024;
size_t cur_msg_len = 0;

void lessen_memory_usage(void) {
  wchar_t *temp;
  size_t temp_size;

  /* ... */

  if (cur_msg != NULL) {
    temp_size = cur_msg_size / 2 + 1;
    temp = realloc(cur_msg, temp_size * sizeof(wchar_t));
    /* temp &and cur_msg may no longer be null-terminated */
    if (temp == NULL) {
      /* Handle error */
    }

    cur_msg = temp;
    cur_msg_size = temp_size;
    cur_msg_len = wcslen(cur_msg); 
  }
}

Compliant Solution

In this compliant solution, cur_msg will always be null-terminated when passed to wcslen():

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <wchar.h>
 
wchar_t *cur_msg = NULL;
size_t cur_msg_size = 1024;
size_t cur_msg_len = 0;

void lessen_memory_usage(void) {
  wchar_t *temp;
  size_t temp_size;

  

Wiki Markup
Strings must contain a null-termination character at or before the address of the last element of the array before they can be safely passed as arguments to standard string-handling functions, such as {{strcpy()}} or {{strlen()}}. This is because these functions, as well as other string-handling functions defined by C99 \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\], depend on the existence of a null-termination character to determine the length of a string. Similarly, strings must be null terminated before iterating on a character array where the termination condition of the loop depends on the existence of a null-termination character within the memory allocated for the string, as in the following example:

Code Block
langc

size_t i;
char ntbs[16];
/* ... */

for (i = 0; i < sizeof(ntbs); ++i) {
  if (ntbs[i] == '\0') break;
  /* ... */
}

Failure to properly terminate null-terminated byte strings can result in buffer overflows and other undefined behavior.

Noncompliant Code Example (strncpy())

Wiki Markup
The standard {{strncpy()}} function does not guarantee that the resulting string is null terminated \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. If there is no null character in the first {{n}} characters of the {{source}} array, the result could not be null terminated.

  if (cur_msg != NULL) {
    temp_size = cur_msg_size / 2 + 1;
    temp = realloc(cur_msg, temp_size * sizeof(wchar_t));
    /* temp and cur_msg may no longer be null-terminated */
    if (temp == NULL) {
      /* Handle error */
    }

    cur_msg = temp;
    /* Properly null-terminate cur_msg */
    cur_msg[temp_size - 1] = L'\0'; 
    cur_msg_size = temp_size;
    cur_msg_len = wcslen(cur_msg); 
  }
}

Noncompliant Code Example (strncpy())

Although the strncpy() function takes a string as input, it does not guarantee that the resulting value is still null-terminated. In the following noncompliant code example, if no null character is contained in the first n characters of the source array, the result will not be null-terminated. Passing a non-null-terminated character sequence to strlen() is undefined behaviorIn the first noncompliant code example, ntbs is null terminated before the call to strncpy(). However, the subsequent execution of strncpy() can overwrite the null-termination character.

Code Block
bgColor#FFcccc
langc
#include <string.h>
char ntbs[NTBS 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];

ntbs  size_t ret = 0;

  if (source) {
    c_str[sizeof(ntbsc_str) - 1] = '\0';
    strncpy(ntbsc_str, source, sizeof(ntbsc_str));

...

 

...

 

...

 

...

 

...

ret 

...

Code Block
bgColor#FFcccc
langc

char ntbs[NTBS_SIZE];

memset(ntbs, 0, sizeof(ntbs)-1);
strncpy(ntbs, source, sizeof(ntbs)-1);= strlen(c_str);
  } else {
    /* Handle null pointer */
  }
  return ret;
}

Compliant Solution (Truncation)

The correct solution depends on This compliant solution is correct if the programmer's intent . If the intent was is to truncate a string while ensuring that the result remains a null-terminated string, this solution can be used:

Code Block
bgColor#ccccff
langc

char ntbs[NTBS_SIZE];

strncpy(ntbs, source, sizeof(ntbs)-1);
ntbs[sizeof(ntbs)-1] = '\0';

Compliant Solution (Copy without Truncation)

If the intent is to copy without truncation, this example copies the data and guarantees that the resulting null-terminated byte string is null terminated. If the string cannot be copied, it is handled as an error condition.

Code Block
bgColor#ccccff
langc

char *source = "0123456789abcdef";
char ntbs[NTBS_SIZE];
/* ... */
#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t func(const char *source) {
  char c_str[STR_SIZE];
  size_t ret = 0;

  if (source) {
   if (strlen(source) < sizeof(ntbs)) {
    strcpy(ntbs, sourcestrncpy(c_str, source, sizeof(c_str) - 1);
    c_str[sizeof(c_str) - 1] = '\0';
    ret = strlen(c_str);
  }
  else {
    /* handleHandle stringnull too largepointer condition */
  }
}
else {
  /* handle NULL string condition */return ret;
}

Compliant Solution (Truncation, strncpy_s())

...

The C Standard, Annex K strncpy_s() function can also be used to copy with truncation. The strncpy_s()

...

function

...

copies

...

up

...

to

...

n

...

characters

...

from

...

the

...

source

...

array

...

to

...

a

...

destination

...

array

...

.

...

If

...

no

...

null

...

character

...

was

...

copied

...

from

...

the

...

source

...

array,

...

then

...

the

...

n

...

th

...

position

...

in

...

the

...

destination

...

array

...

is

...

set

...

to

...

a

...

null

...

character,

...

guaranteeing

...

that

...

the

...

resulting

...

string

...

is

...

null-terminated.

Code Block
bgColor#ccccff
langc

char *source;
char a[NTBS_SIZE];
/* ... */
if (#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>

enum { STR_SIZE = 32 };

size_t func(const char *source) {
  errno_t err = strncpy_s(a, sizeof(a), source, 5);char c_str[STR_SIZE];
  size_t ret = 0;

  if (err != 0source) {
    /* Handle error */errno_t err = strncpy_s(
  }
}
else {
  /* handle NULL string condition */
}

Noncompliant Code Example (realloc())

One method to decrease memory usage in critical situations when all available memory has been exhausted is to use the realloc() function to halve the size of message strings. The standard realloc() function has no concept of null-terminated byte strings. As a result, if realloc() is called to decrease the memory allocated for a null-terminated byte string, the null-termination character may be truncated.

The following noncompliant code example fails to ensure that cur_msg is properly null terminated:

Code Block
bgColor#ffcccc
langc

char *cur_msg = NULL;
size_t cur_msg_size = 1024;

/* ... */

void lessen_memory_usage(void c_str, sizeof(c_str), source, strnlen(source, sizeof(c_str))
    );
    if (err != 0) {
  char *temp;
  size_t temp_size;

  /* Handle ...error */

  if (cur_msg != NULL) } else {
    temp_size = cur_msg_size/2 + 1;
    temp = realloc(cur_msg, temp_size ret = strnlen(c_str, sizeof(c_str));
    if}
 (temp ==} NULL)else {
      /* Handle errornull conditionpointer */
    }
    cur_msg = temp;
    cur_msg_size = temp_size;
  }
}

/* ... */

Because realloc() does not guarantee that the string is properly null terminated, any subsequent operation on cur_msg that assumes a null-termination character may result in undefined behavior.

Compliant Solution (realloc())

return ret;
}

Compliant Solution (Copy without Truncation)

If the programmer's intent is to copy without truncation, this compliant solution copies the data and guarantees that the resulting array is null-terminated. If the string cannot be copied, it is handled as an error conditionIn this compliant solution, the lessen_memory_usage() function ensures that the resulting string is always properly null terminated.

Code Block
bgColor#ccccff
langc

char *cur_msg = NULL;#include <string.h>
 
enum { STR_SIZE = 32 };
 
size_t cur_msg_size = 1024;

/* ... */

void lessen_memory_usage(voidfunc(const char *source) {
  char *tempc_str[STR_SIZE];
  size_t temp_size ret = 0;

  /* ... */

if (source) {
    if (strnlen(source, sizeof(curc_msg != NULLstr)) < sizeof(c_str)) {
    temp_size = cur_msg_size/2 + 1strcpy(c_str, source);
    temp  ret = reallocstrlen(cur_msg, temp_sizec_str);
    if (temp == NULL)} else {
      /* Handle error conditionstring-too-large */
    }
  }  cur_msg = temp;else {
    cur_msg_size = temp_size;

    /* ensureHandle string is null-terminatednull pointer */
  }
  cur_msg[cur_msg_size - 1] = '\0';
  }
}

/* ... */
return ret;
}

Note that this code is not bulletproof. It gracefully handles the case where source  is NULL, when it is a valid string, and when source is not null-terminated, but at least the first 32 bytes are valid. However, in cases where source is not NULL, but points to invalid memory, or any of the first 32 bytes are invalid memory, the first call to strnlen() will access this invalid memory, and the resulting behavior is undefined. Unfortunately, standard C provides no way to prevent or even detect this condition without some external knowledge about the memory source points to.

Risk Assessment

Failure to properly null terminate strings -terminate a character sequence that is passed to a library function that expects a string can result in buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process. Null-termination errors can also result in unintended information disclosure.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

STR32-C

high

High

probable

Probable

medium

Medium

P12

L1

Automated Detection

Tool

Version

Checker

Description

Section

Compass/ROSE

 

 

Section

can detect some violations of this rule

section

Astrée
Include Page
Astrée_V
Astrée_V

Supported

Astrée supports the implementation of library stubs to fully verify this guideline.

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-STR32Partially implemented: can detect some violation of the rule
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V
MISC.MEM.NTERM.CSTRINGUnterminated C String
Compass/ROSE



Can detect some violations of this rule

Coverity
Include Page
Coverity_V
Coverity_V
STRING_NULLFully implemented
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF2835, DF2836, DF2839


Klocwork
Include Page
c:
Klocwork_V
c:
Klocwork_V
Section

NNTS

NNTS.MIGHT
NNTS.MUST
SV.STRBO.BOUND_COPY.UNTERM


LDRA tool suite
Include Page
LDRA_V
LDRA_V

404 S, 600 S

Partially implemented

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_C-STR32-a

Avoid overflow due to reading a not zero terminated string

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule STR32-C


Checks for:

  • Invalid use of standard library string routine
  • Tainted NULL or non-null-terminated string

Rule partially covered.

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V692
TrustInSoft Analyzer

Include Page
TrustInSoft Analyzer_V
TrustInSoft Analyzer_V

match format and argumentsPartially verified.
 

Related Vulnerabilities

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

Related Guidelines

CERT C++ Secure Coding Standard: STR32-CPP. Null-terminate character arrays as required

...

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

ISO/IEC TR 24772

...

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

...

:2013String Termination [CMJ]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961:2013Passing a non-null-terminated character sequence to a library function that expects a string [strmod]Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-119, Improper Restriction of Operations within the Bounds of

...

a Memory Buffer2017-05-18: CERT: Rule subset of CWE
CWE 2.11CWE-123, Write-what-where Condition2017-06-12: CERT: Partial overlap
CWE 2.11CWE-125, Out-of-bounds Read2017-05-18: CERT: Rule subset of CWE
CWE 2.11CWE-170, Improper Null Termination2017-06-13: CERT: Exact

CERT-CWE Mapping Notes

Key here for mapping notes

CWE-119 and STR32-C

Independent( ARR30-C, ARR38-C, ARR32-C, INT30-C, INT31-C, EXP39-C, EXP33-C, FIO37-C) STR31-C = Subset( Union( ARR30-C, ARR38-C)) STR32-C = Subset( ARR38-C)

CWE-119 = Union( STR32-C, list) where list =


  • Out-of-bounds reads or writes that do not involve non-null-terminated byte strings.


CWE-125 and STR32-C

Independent( ARR30-C, ARR38-C, EXP39-C, INT30-C) STR31-C = Subset( Union( ARR30-C, ARR38-C)) STR32-C = Subset( ARR38-C)

CWE-125 = Union( STR32-C, list) where list =


  • Out-of-bounds reads that do not involve non-null-terminated byte strings.


CWE-123 and STR32-C

Independent(ARR30-C, ARR38-C) STR31-C = Subset( Union( ARR30-C, ARR38-C)) STR32-C = Subset( ARR38-C)

Intersection( CWE-123, STR32-C) =


  • Buffer overflow from passing a non-null-terminated byte string to a standard C library copying function that expects null termination, and that overwrites an (unrelated) pointer


STR32-C - CWE-123 =


  • Buffer overflow from passing a non-null-terminated byte string to a standard C library copying function that expects null termination, but it does not overwrite an (unrelated) pointer


CWE-123 – STR31-C =


  • Arbitrary writes that do not involve standard C library copying functions, such as strcpy()


Bibliography

[Seacord 2013] Chapter 2, "Strings" 
[Viega 2005]Section 5.2.14, "Miscalculated NULL Termination"


...

Image Added Image Added Image Added

MITRE CWE: CWE-170, "Improper Null Termination"

Bibliography

Wiki Markup
\[[Schwarz 2005|AA. Bibliography#Schwarz 05]\]
\[[Seacord 2005a|AA. Bibliography#Seacord 05]\] Chapter 2, "Strings"
\[[Viega 2005|AA. Bibliography#Viega 05]\] Section 5.2.14, "Miscalculated NULL termination"

Image Removed      07. Characters and Strings (STR)      STR33-C. Size wide character strings correctly