This rule highlights potentially overflowing calls to the functions sprintf, vsprintf, and gets with a warning. These functions allow unbounded writes to buffers, which may cause an overflow when used on untrusted data or without adequate checks on the size of the data. Function calls of this type constitute a security risk through buffer overflows. The gets function, in particular, is one of the vulnerabilities exploited by the Internet Worm of 1988, one of the first computer worms to spread through the Internet.

Always control the length of buffer copy and buffer write operations. Use the safer variants snprintf, vsnprintf, and fgets, which include an extra buffer length argument.

To improve the security of this example code, three changes should be made:

  1. Introduce a preprocessor define for the size of the buffer.
  2. Replace the call to gets with fgets, specifying the define as the maximum length to copy. This will prevent the buffer overflow.
  3. Replace both calls to sprintf with snprintf, specifying the define as the maximum length to copy. This will prevent the buffer overflow.
  4. Consider using the %g format specifier instead of %f.
  • Common Weakness Enumeration: CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow').
  • CERT C Coding Standard: STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator.
  • M. Howard, D. Leblanc, J. Viega, 19 Deadly Sins of Software Security: Programming Flaws and How to Fix Them, McGraw-Hill Osborne, 2005.
  • Wikipedia: Morris worm.
  • E. Spafford. The Internet Worm Program: An Analysis. Purdue Technical Report CSD-TR-823, (online), 1988.