Buffer overflow from unbound sprintf

The function sprintf is used to write formatted output to a buffer of memory. The function has a fixed size array as a destination, but sprintf doesn't impose limits on the output data, so there is potential for buffer overflow.

The SV.STRBO.UNBOUND_SPRINTF checker looks for code that calls sprintf.

Vulnerability and risk

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

Vulnerable code example

1  int main()
2  {
3       char fixed_buf[10];
4       sprintf(fixed_buf,"Very long format string\n"); 
5       return 0;
6  }

Klocwork produces an issue report at line 4 indicating that function sprintf doesn't check buffer boundaries and may overrun buffer fixed_buf of fixed size 10.

Fixed code example

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

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

Security training

Application security training materials provided by Secure Code Warrior.