Buffer overflows with s(n)printf ()



John K Luebs wrote:

How, exactly, does use of snprintf() lead to buffer overflow
vulnerabilities?

Mainly for two reasons:

1. you (accidentally) use sprintf () instead of snprintf (). Never do
   that! However, since snprintf () isn't really part of plain old
   ANSI-C you might want to use g_snprintf () instead to maximize
   your portability (concerning GTK applications). I haven't seen any
   C environment / platform without any kind of snprintf () support
   for quite some years, though. GNU always has it.

2. you screw up the buffersize argument. For auto (local) buffers this  
   should always simply be "sizeof (your_buffer)". A little more care  
   about the size parameter is necessary when the target is a pointer
   to an allocated buffer (instead of the buffer itself). In this case
   the "sizeof" operator doesn't help. Instead you have to provide a
   proper buffer size value by yourself.

Rare causes for buffer overflows even when properly using snprintf ()
include:

1. buggy / broken / compromised implementations of snprintf ()

2. being spoofed by an snprintf () function that's actually mapped
   over an sprintf () function, thus omitting the size check and
   opening the Gates for overflows.

These shouldn't happen if you link properly against standard libraries
which are available for your platform / development environment. It's
only an issue if you link against libraries which still contain their
own implementation of snprintf (). Very few seem to do.

There are other not-to-be-used C functions besides sprintf (), btw. See
http://www-106.ibm.com/developerworks/security/library/s-buffer-defend.html
for a rather detailed list and explanation of what and why not to use
and possibly what to use instead.

In short: if you encounter ANY of those functions listed in your
program then it's inherently unsafe and buffer-overflow-prone.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]