Buffer overflow from unbound string copy

The function strcpy is used to copy a source string to a buffer of memory. The function has a fixed size array as a destination, but strcpy does not impose limits on copied data, so there is potential for buffer overflow.

The SV.STRBO.UNBOUND_COPY checker flags instances of code that calls strcpy.

Vulnerability and risk

The function strcpy does not check the length of the string being copied and can easily result in a buffer overrun. It is preferable, if possible, to use the strncpy function and review the usage of buffers in the application.

Vulnerable code example

1  int main()
2  {
3       char FIXEDbuf[12];
4       strcpy(FIXEDbuf, "Something rather large");
6       return 0;
7  }

Klocwork produces an issue report at line 4 indicating that function strcpy does not check buffer boundaries and may overrun buffer 'FIXEDbuf' of fixed size 12.

Fixed code example

1  int main()
2  {
3       char FIXEDbuf[23];
4       char *POINTERbuf;
5       strcpy(FIXEDbuf, "Something rather large");
6       strcpy(POINTERbuf, "Something very large as well");
8       return 0;
9  }

In the fixed code example, the size of FIXEDbuf has been increased to 23 to make sure that it has enough room for the strcpy operation. Another option for fixing the code is to use strncpy and check the buffer size.

Security training

Application security training materials provided by Secure Code Warrior.