About *printf %n fortifications
Jakub Jelinek
jakub@redhat.com
Fri Feb 24 20:12:00 GMT 2006
On Fri, Feb 24, 2006 at 01:30:36PM -0500, Daniel Jacobowitz wrote:
> On Fri, Feb 24, 2006 at 07:04:08PM +0100, Gwenole Beauchesne wrote:
> > Hi,
> >
> > Why a printf() with %n in the format string would require this string to
> > be non-writable? (debug/tst-chk1.c, stdio-common/vfprintf.c)
> >
> > See the attached test case (-O2 -D_FORTIFY_SOURCE=2)
> > char fmt[] = "%s%n\n";
> > printf(fmt, "bar", &count);
> > looks valid to me, but causes an abort() with
> > *** %n in writable segment detected ***
> >
> > The check probably meant to be against the %n argument itself.
> >
> > The following patch fixes this but I have not updated tst-chk1.c yet.
> > WDYT?
>
> No, that's not the point. It doesn't matter whether the target of the
> %n is writable; if it's not, we'll just segfault. The test is supposed
> to prevent a malicious attacker inserting %n into the application
> somewhere where it will be passed to printf, causing an unexpected
> store.
>
> Of course your testcase is valid - but it's a bad idea.
Actually, the test is invalid with -D_FORTIFY_SOURCE=2.
-D_FORTIFY_SOURCE=1 are checks which will just prevent some programs
violating standards or triggering undefined behavior from doing bad things.
-D_FORTIFY_SOURCE=2 actually imposes further restrictions beyond
the standards. One of the restrictions is that %n is only permitted
in read-only strings (i.e. string literals or even gettext returned
strings). It is very rare that you need a writable format string
with %n, and on the other side it is quite common exploit technique.
Another -D_FORTIFY_SOURCE=2 limitation is that you can't use certain
str* functions accross structure field boundaries.
E.g. while
struct { char buf[10]; char buf2[10]; } a;
strcpy (a.buf, "abcdefghijklmn");
is valid program and works with -D_FORTIFY_SOURCE=1, it is invalid
under -D_FORTIFY_SOURCE=2.
memcpy (a.buf, "abcdefghijklmn", 15);
is valid in all modes.
Jakub
More information about the Libc-alpha
mailing list