SV.UNBOUND_STRING_INPUT.FUNC

Buffer overflow from unbounded string copy

The string copy function is used to copy a string of characters to a buffer of memory. The strcpy function has no argument to limit the size of the written data, so a buffer overflow may result.

The SV.UNBOUNDED_STRING_INPUT.FUNC checker looks for code calling insecure string copy functions that don't specify a buffer size, like gets(), gettext(), or catgets().

Vulnerability and risk

If the string copy function is called without a size parameter, a buffer overrun error can result. This can lead to application instability or, with a carefully constructed attack, code injection, or other vulnerabilities.

Mitigation and prevention

To avoid this vulnerability

  • make sure you use functions that have buffer size as an input parameter, like fgets instead of gets
  • for Windows, use StrSafe functions String*Gets, such as StringCchGets, or Safe CRT functions like gets_s
  • use a function like strlen() to determine the buffer size you need

Vulnerable code example 1

Copy
   #include <stdio.h>
   
   int main()
   {
     char string [256];
     printf ("Insert your full address: ");
     gets (string);                /* SV.UNBOUND_STRING_INPUT.FUNC reported here */
     printf ("Your address is: %s\n",string); 
     return 0;
  }

Fixed code example 1

Copy
   #include <stdio.h>
   
   int main()
   {
     char string [256];
     printf ("Insert your full address: ");
     fgets (string, 256, stdin);    /* No checker reported because fgets considers the size of the string array */
     printf ("Your address is: %s\n",string);
     return 0;
  }

Vulnerable code example 2

Copy
   #include <stdio.h>
   
   int main()
   {
     char string [256];
     printf ("Please Enter Your Full Name:");
     _gettws (string);             /* SV.UNBOUND_STRING_INPUT.FUNC reported here */
     printf ("Your Full Name Is: %s\n", string);
     return 0;
  }

Fixed code example 2

Copy
   #include <stdio.h>
   
   int main()
   {
     char string [256];
     printf ("Please Enter Your Full Name:");
     gets_s (string, strlen(string));  /* no SV.UNBOUND_STRING_INPUT.FUNC reported here */
     printf ("Your Full Name Is: %s\n", string);
     return 0;
  }

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.