SV.STRBO.BOUND_SPRINTF

Buffer overflow from bound sprintf

The function snprintf is used to write formatted output to a buffer of memory. Among its parameters is a pointer to the output parameter and the maximum number of bytes to write to the output buffer, including the null termination byte. The size parameter must be less than or equal to the number of bytes allocated in the output buffer. If the size parameter is greater than the size of the output buffer, a buffer overflow may result.

The SV.STRBO.BOUND_SPRINTF checker looks for code that calls snprintf 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 snprintf 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.

Vulnerable code example

Copy
  void foo(const char *src)
  {
     char buf[20];
     snprintf(buf, 40, "%s", src);
  }

Klocwork produces an issue report at line 4 because the size parameter given to snprintf is 40, which is greater than the size of the output buffer 'buf', 20. The size parameter in the snprintf function must be less than or equal to the number of bytes allocated in the output buffer, so if the string in 'src' is equal to or greater than 20 in length in this case, it will result in a buffer overflow.

Fixed code example

Copy
  void foo(const char *src)
  {
     char buf[20];
     snprintf(buf, sizeof(buf), "%s", src);
  }

In the fixed code example, the sizeof(buf) parameter is used to avoid specifying a size greater than the size of the output buffer.

Security training

Application security training materials provided by Secure Code Warrior.