Versions Compared

Key

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

...

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

Noncompliant Code Example (strncpy())

The strncpy() function does not guarantee that the resulting string value is null terminated. 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 string character sequence to strlen() results in undefined behavior, as shown by this noncompliant code example:

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

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

Compliant Solution (Truncation)

The correct solution depends on the programmer's intent. If the intent 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
#include <string.h>
 
enum { NTBS_SIZE = 32 };
 
size_t func(const char *source) {
  char ntbs[NTBS_SIZE];

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

Compliant Solution (Copy without Truncation)

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

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

  if (source) {
    if (strlen(source) < sizeof(ntbs)) {
      strcpy(ntbs, source);
    } else {
      /* Handle string-too-large condition */
    }
  } else {
    /* Handle NULLnull stringpointer condition */
  }
  return strlen( ntbs);
}

Compliant Solution (strncpy_s(), C11 Annex K)

The C11 Annex K 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 nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.

Code Block
bgColor#ccccff
langc
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
  
enum { NTBS_SIZE = 32 };
  
size_t func(const 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 NULLnull string conditionpointer */
  }
  return strlen_s( s, sizeof(a));
}

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.

...

Because realloc() does not guarantee that the string is properly null-terminated, and the function subsequently passes cur_msg to a library function (fputs()) that expects null-termination, the result is undefined behavior.

Compliant Solution (realloc())

In this compliant solution, the lessen_memory_usage() function ensures that the resulting string is always properly null-terminated:

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

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

  if (cur_msg != NULL) {
    temp_size = cur_msg_size / 2 + 1;
    temp = realloc(cur_msg, temp_size);
    if (temp == NULL) {
      /* Handle error */
    }
    cur_msg = temp;
    cur_msg_size = temp_size;

    /* Ensure string is null-terminated */
    cur_msg[cur_msg_size - 1] = '\0';
  }
  fputs(stderr, cur_msg);
}

Risk Assessment

Failure to properly null-terminate strings 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

Probable

Medium

P12

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect some violations of this rule

Coverity6.5STRING_NULLFully Implemented

Klocwork

Include Page
Klocwork_V
Klocwork_V

NNTS

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

600 S

Fully implemented

Related Vulnerabilities

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

Related Guidelines

CERT C++ Secure Coding StandardSTR32-CPP. Null-terminate character arrays as required
ISO/IEC TR 24772:2013String Termination [CMJ]
ISO/IEC TS 17961Passing a non-null-terminated character sequence to a library function that expects a string [strmod]
MITRE CWECWE-119, Failure to constrain operations within the bounds of an allocated memory buffer
CWE-170, Improper null termination

Bibliography

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

...