Checkers:SV.STRBO.BOUND_COPY

From current

Reference > C/C++ checkers > SV.STRBO.BOUND COPY

Buffer overflow from bound string copy

The function strncpy is used to copy a string of characters to a buffer of memory. Among its parameters is an argument that limits the size of written data. If strncpy copies data to an array of fixed size (buf), normally the limit should be sizeof(buf) -1. The -1 is important because a trailing zero is counted as a byte. If the size parameter is greater than the size of the output buffer, a buffer overflow may result.

The SV.STRBO.BOUND_COPY checker looks for code that calls strncpy using an array of fixed size as the output buffer and in which the size parameter is greater than the known size of the buffer.

Vulnerability and risk

If the strncpy function is called with a size parameter that is greater than the size of the output buffer, a buffer overrun error can result. This can lead to application instability or, with a carefully constructed attack, code injection, or other vulnerabilities.

For information on vulnerability and risk in buffer overflows, see Understanding buffer overflows.

Code examples

Vulnerable code example

1  int main()
2  {
3      char buf [20];
4      char long_src[30];
5      char *external_pointer;
6      strncpy(buf, long_src, 30);
7      strncpy(buf, external_pointer, sizeof(buf));
8      strncpy(buf, external_pointer, 30); 
9      strncpy(buf, external_pointer, sizeof(buf)-1); 
10 }

Klocwork produces issue reports at lines 6, 7, and 8, indicating that function strncpy may incorrectly check buffer boundaries and overflow buffer 'buf' of size 20. With a size parameter greater than the size of the output buffer, a buffer overflow may result.

At line 9, the trailing zero is taken into account, so no issue report is produced. The -1 allows for the fact that a trailing zero is counted as a byte.

Related checkers

External guidance