[Python-Dev] sprintf() usage (Re: mysnprintf broken)

M.-A. Lemburg mal@lemburg.com
Tue, 27 Nov 2001 21:39:03 +0100


"Martin v. Loewis" wrote:
> 
> > Grepping through the Python source code there are 191
> > usages of sprintf() -- shouldn't these be modified to
> > use PyOS_snprintf() instead ?
> 
> Not necessarily. sprintf is perfectly ok if used correctly (i.e. if
> you can guarantee an upper bound on the resulting string length, and
> compute this bound either statically or dynamically).

This is done in most cases, indeed. Still I think we need some
auditing here and having all audited sprintf() uses renamed
to say PyOS_snprintf() would make auditing future Python releases
a lot easier.
 
> > Python/getargs.c would be a particularly important case
> > to fix, since the sprintf()s in there are not protected
> > against buffer overflows -- it seems that long function
> > names could be used to exploit this, e.g. in multi-user
> > environments like Zope to obtain admin priviledges.
> 
> That indeed appears to be the case. However, given
> 
>         char buf[256];
>                         sprintf(p, "%s() ", fname);
> 
> I think the correct reformulation should be
> 
>         char buf[256];
>                         sprintf(p, "%.100s() ", fname);

Right.
 
> In seterror, you add then a number of strings containing each a %d
> (adding 20 bytes worst-case each), where the loop should terminate if
> there are only, say, 140 bytes left; the final printf could then use
> %.100s.
> 
> Alternatively, you could use "%.*s" through-out, operating with the
> lengths of the strings themselves.

I think that would make the code much more complicated.

-- 
Marc-Andre Lemburg
CEO eGenix.com Software GmbH
______________________________________________________________________
Consulting & Company:                           http://www.egenix.com/
Python Software:                        http://www.lemburg.com/python/