Bugtraq mailing list archives

Re: Platform independent allocating sprintf (was Re: buffer overrun


From: James Antill <james-bugtraq () and org>
Date: 24 Feb 2003 22:28:33 -0500

"Forrest J. Cavalier III" <forrest () mibsoftware com> writes:

Thamer Al-Harbash <tmh () whitefang com> wrote

On Sat, 22 Feb 2003, Richard Kettlewell wrote:

There is an internal #define (HAS_vsnprintf) that causes it to use
vsnprintf() instead of vsprintf(), but this is not enabled by default,
not tested for by the configure script, and not documented.

This is a fairly normal (and somewhat frightening) practice I've
seen in several popular packages.

 Fairly normal, for the same group of people that use fixed buffers
everywhere.

Last I checked ISC dhcp has a #define for vsnprintf to be
vsprintf if the UNIX flavor did not support snprintf.

[snip]

I know that Ted Lemon, the primary author, is aware this. I've
mentioned it to him a while ago. I am also not aware of this
causing any security holes; although I honestly have not given
his source a security audit.

 ISC doesn't write great code, I'm shocked.

There are replacement 'snprintf' packages which avoid
this. Patrick Powell's replacement is used in Mutt (a popular
MUA) and has a very liberal license.

If you can't use the allocating vasprintf() and care about security,
tmpfile() and vfprintf() are available on just about every
platform, including Windows.  

 The very simple way to do it is to use vasprintf() or vsnprintf(),
and hack vsnprintf() for those platforms that still don't have
vsnprintf() (actually it's often better to just go straight for
vsnprintf() do to the non-std. of asprintf(), for instance the glibc
error case is braindead).

 However that only solves some of the problem, all printf()
implementations aren't equal. For a comparison of some portable
printf() functions (of varying quality) see the bottom section of...

http://www.and.org/vstr/comparison.html

...although at least a couple of the string libraries there also
contain portable printf() like (again of varying quality) functions as
part of their API.

For speedup, you can "special case" some of the most common % formatting
(%%, %s, %d, and %u) and use the tmpfile() strategy only when there are
field width specifiers and unrecognized format specifiers.  When you
do that, the performance is usually acceptable, and you can still use
all of the "special" formatting you often get with localized fprintf()s.

Librock has reusable code which uses just that strategy to implement a
platform-independent "printf into an allocated string". Docs and
source at:
   http://www.mibsoftware.com/librock/text/vastrprintf.htm

 Well apart from the non-portability, the error checking is wrong on
the asprintf() calls so you'll SEGV if malloc() fails.

-- 
# James Antill -- james () and org
:0:
* ^From: .*james@and\.org
/dev/null


Current thread: