Versions Compared

Key

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

...

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

  if (source) {
    c_str[sizeof(c_str) - 1] = '\0';
    strncpy(c_str, source, sizeof(c_str));
  return  ret = strlen(c_str);
  } else {
    /* Handle null pointer */
  }
  return ret;
}

Compliant Solution (Truncation)

...

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

  if (source) {
    strncpy(c_str, source, sizeof(c_str) - 1);
    c_str[sizeof(c_str) - 1] = '\0';
  return  ret = strlen(c_str);
  } else {
    /* Handle null pointer */
  }
  return ret;
}

Compliant Solution (Truncation, strncpy_s())

...

Code Block
bgColor#ccccff
langc
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>

enum { STR_SIZE = 32 };

size_t func(const char *source) {
  char a[STR_SIZE];
  size_t ret = 0;

  if (source) {
    errno_t err = strncpy_s(
      a, sizeof(a), source, strlen(source)
    );
    if (err != 0) {
      /* Handle error */
    } else {
      ret = strnlen_s(a, sizeof(a));
    }
  } else {
     /* Handle null pointer */
  }
  return strlen_s(s, sizeof(a))ret;
}

Compliant Solution (Copy without Truncation)

...

Code Block
bgColor#ccccff
langc
#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(c_str)) {
      strcpy(c_str, source);
      ret = strlen(c_str);
    } else {
      /* Handle string-too-large */
    }
  } else {
    /* Handle null pointer */
  }
  return strlen(c_str)ret;
}

Risk Assessment

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

...