Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: String -> NTBS (Reverted from v. 115)

Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. While not limited to null-terminated byte strings (NTBS), buffer overflows often occur when manipulating stringsNTBS data. To prevent such errors, limit copies either through truncation or, preferably, ensure that the destination is of sufficient size to hold the character data to be copied and the null-termination character. (See recommendation STR03-C. Do not inadvertently truncate a null-terminated byte string.)

Noncompliant Code Example (Off-by-One Error)

...

Wiki Markup
Command-line arguments are passed to {{main()}} as pointers to null-terminated byte strings in the array members {{argv\[0\]}} through {{argv\[argc-1\]}}. If the value of {{argc}} is greater than zero, the string pointed to by {{argv\[0\]}} is, by convention, the program name. If the value of {{argc}} is greater than one, the strings referenced by {{argv\[1\]}} through {{argv\[argc-1\]}} are the actual program arguments.

...

Remember to add a byte to accommodate null terminator in the the null-terminated byte string.

Compliant Solution (argv) (strcpy_s())

...

Environmental variables are loaded into process memory when the program is loaded. As a result, the length of these null-terminated byte strings can be determined by calling the strlen() function, and the resulting length can be used to allocate adequate dynamic memory:

...

Code Block
bgColor#ccccff
char* name; /* initialized externally */
char filename[128];
snprintf( filename, sizeof( filename), "%s.txt", name);
/* open filename * /

Risk Assessment

Copying a string NTBS data to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code with the permissions of the vulnerable process.

...

      07. Characters and Strings (STR)      STR32-C. Null-terminate byte strings as required