Rule Definition
The 'scanf()' functions can lead to buffer overflow if used improperly. They do not have bound checking capability and if the input string is longer than the buffer size, then the characters will overflow into the adjoining memory.
Remediation
It is possible to avoid buffer overflow by specifying a field width. In this case, you must provide a 'char *' buffer with dynamic allocation and you need to check the field width you specify does not exceed the size of the buffer.
Violation Code Sample
int main()
{
char buffer[15]={0};
printf("Enter name:");
scanf(buffer,"%s");
}
Fixed Code Sample
#include <stdio.h>
int main()
{
int buf_size = 25;
char *my_buf;
my_buf = (char *) malloc (buf_size);
printf ("Enter name");
scanf ("%20s", my_buf);
}
Reference
Build Security In (https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding)
Related Technologies
C++
Technical Criterion
CWE-676 - Use of Potentially Dangerous Function
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.