Buffer overflow from non null-terminated string
In C and C++, a C string, or a null-terminated string, is a character sequence terminated with a null character (\0). The length of a C string is found by searching for the null character.
The NNTS family of checkers looks for code that uses string manipulation functions with character arrays that are not or may not be null terminated. The NNTS.MUST checker looks for code using string manipulation functions in which a character array is not null terminated.
Vulnerability and risk
The null termination has historically created security problems. For example:
- a null character inserted into a string can truncate it unexpectedly
- it's a common bug not to allocate enough space for the null character or to forget the null
- many programs don't check the length before copying a string to a fixed-size buffer, causing a buffer overflow when it's too long
- the inability to store a null character means that string and binary data needs to be handled by different functions, which can cause problems if the wrong function is used
Mitigation and prevention
To avoid the problem:
- add special code to validate null termination of string buffers if performance constraints permit
- switch to bounded-string manipulation functions like strncpy
- inspect buffer lengths involved in the buffer overrun traceback
Vulnerable code example
const char * src = "abcdef";
strncpy(buf, src, 3);
Klocwork produces a buffer overflow report for array 'tgt' at line 10: buffer overflow of 'tgt', due to non-null terminated string 'buf'. A similar error is reported for array 'buf' also at line 10. In the example, the array bounds violation is reported twice because there is a reading of 'buf' and writing of 'tgt'. Both read and write occur beyond the buffers' boundaries (equal to or greater than 3), due to the fact that 'buf' was not null terminated (which in turn occurred because of the improper use of strcpy). This code will result in a buffer overflow, which can cause various significant security problems.
- CERT ARR00-C: Understand how arrays work
- CERT ARR30-C: Do not form or use out-of-bounds pointers or array subscripts
- CERT STR03-C: Do not inadvertently truncate a string
- CERT STR32-C: Do not pass a non-null-terminated character sequence to a library function that expects a string
- CERT STR50-CPP: Guarantee that storage for strings has sufficient space for character data and the null terminator
- CWE-20: Improper Input Validation
- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE-125: Out-of-bounds Read
- CWE-170: Improper Null Termination
- CWE-787: Out-of-bounds Write
- OWASP A3:2021 Injection
- STIG-ID: APP3590.1 Application is vulnerable to buffer overflows
Application security training materials provided by Secure Code Warrior.
This checker can be extended. See Tuning C/C++ analysis for more information.