Buffer Overflow in Bound StringCopy

The SV.STRBO.BOUND_COPY.OVERFLOW checker finds possible buffer overflows in bounded string copy operations strncpy, StrnCpy, safe_strcpy.

Vulnerability and risk

When a buffer overflow happens during string copy operations, it overwrites adjacent memory. This leads to a violation of memory safety.

To avoid such errors, destination buffer size should be properly calculated and the third parameter of bounded string copy functions should be less or equal to buffer size.

Vulnerable code example

1 #include <string.h>
2 int main(int argc, char* argv[]){
3   char foo[10];
4   char bar[] = "this text is too long";
5   strncpy(foo, bar, sizeof(bar));
6 }

Klocwork will report defect SV.STRBO.BOUND_COPY.OVERFLOW in line 5 because destination buffer size 10 is less than source buffer size 22.

Fixed code example 1

#include <string.h>
int main(int argc, char* argv[]){
  char foo[10];
  char bar[] = "this text is too long";
  strncpy(foo, bar, sizeof(foo));

In this example, defect SV.STRBO.BOUND_COPY.OVERFLOW will not be reported because during the copy operation, source string will be trimmed to destination buffer size.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.