Stack protection via GCC's `-fstack-protector'
[Please keep both <[email protected]> and <[email protected]> in the recipients list.]
Hello!
For some time, GCC now offers the following feature:
info Gcc
#v+
`-fstack-protector'
Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call alloca, and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits.
#v-
I now happen to be running a GCC 4.1 installation which has that one enabled by default. Unfortunately, building GNU Mach and GRUB2 (didn't check GRUB legacy) is affected by that:
GRUB2
#v+
[...]
gcc -o kernel.exec kernel_img-kern_i386_pc_startup.o kernel_img-kern_main.o kernel_img-kern_device.o kernel_img-kern_disk.o kernel_img-kern_dl.o kernel_img-kern_file.o kernel_img-kern_fs.o kernel_img-kern_err.o kernel_img-kern_misc.o kernel_img-kern_mm.o kernel_img-kern_loader.o kernel_img-kern_rescue.o kernel_img-kern_term.o kernel_img-kern_i386_dl.o kernel_img-kern_i386_pc_init.o kernel_img-kern_parser.o kernel_img-kern_partition.o kernel_img-kern_env.o kernel_img-disk_i386_pc_biosdisk.o kernel_img-term_i386_pc_console.o kernel_img-symlist.o -nostdlib -Wl,-N,-Ttext,8200 -fno-builtin -mrtd -mregparm=3 -m32 kernel_img-kern_device.o: In function `grub_device_iterate':../kern/device.c:142: undefined reference to `__stack_chk_fail'
kernel_img-kern_disk.o: In function `grub_disk_write':../kern/disk.c:553: undefined reference to `__stack_chk_fail'
kernel_img-kern_misc.o: In function `grub_vsprintf':../kern/misc.c:897: undefined reference to `__stack_chk_fail'
kernel_img-kern_rescue.o: In function `grub_rescue_cmd_cat':../kern/rescue.c:169: undefined reference to `__stack_chk_fail'
kernel_img-kern_i386_pc_init.o: In function `grub_machine_set_prefix':../kern/i386/pc/init.c:239: undefined reference to `__stack_chk_fail'
kernel_img-kern_parser.o:../kern/parser.c:230: more undefined references to `__stack_chk_fail' follow
collect2: ld returned 1 exit status
make: *** [kernel.exec] Error 1
#v-
GNU Mach
#v+
[...]
ld -u _start -r -o gnumach.o --start-group libkernel.a liblinux.a liblinux_pcmcia_cs_modules.a liblinux_pcmcia_cs_clients.a liblinux_pcmcia_cs_wireless.a
nm -u gnumach.o | sed 's/ *U *//;s/^_*//' | sort -u > gnumach-undef
sed '/^memcpy$/d; /^memmove$/d; /^memset$/d; /^bcopy$/d; /^bzero$/d; /^strchr$/d; /^strstr$/d; /^strsep$/d; /^strpbrk$/d; /^strtok$/d; /^htonl$/d; /^htons$/d; /^ntohl$/d; /^ntohs$/d; /^etext$/d; /^edata$/d; /^end$/d;' gnumach-undef > gnumach-undef-bad if test -s gnumach-undef-bad; \
then cat gnumach-undef-bad; exit 2; else true; fistack_chk_fail
make[2]: *** [clib-routines.o] Error 2
make[2]: Leaving directory `/fs/data/mount/home/thomas/tmp/source/gnumach/gnumach-1-branch/build'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/fs/data/mount/home/thomas/tmp/source/gnumach/gnumach-1-branch/build'
make: *** [all] Error 2
#v-
Is it feasible to have the -fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass -fno-stack-protector' if available?
Regards,
Thomas
Hi,
Quoted 6 lines · Thomas Schwinge, le Wed 08 Nov 2006 22:40:54 +0100, a écrit :
then cat gnumach-undef-bad; exit 2; else true; fi
stack_chk_failIs it feasible to have the
-fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass-fno-stack-protector' if available?
I'd say it shouldn't be very hard to provide a stack_chk_fail function, even if all it does is just panic().
Samuel
Hello!
Quoted 7 lines · Samuel Thibault
Thomas Schwinge, le Wed 08 Nov 2006 22:40:54 +0100, a ?crit :
Quoted 3 lines
Is it feasible to have the
-fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass-fno-stack-protector' if available?I'd say it shouldn't be very hard to provide a
stack_chk_failfunction, even if all it does is justpanic().
Having had a look at glibc's implementation and its complexity ;-) that might indeed be a reachable goal (assuming that no other surprises show up):
debug/stack_chk_fail.c
#v+
[Copyright header.]
#include <stdio.h>
#include <stdlib.h>
extern char **__libc_argv attribute_hidden;
void__attribute__ ((noreturn)) __stack_chk_fail (void)
{
/* The loop is added only to keep gcc happy. */ while (1)
__libc_message (1, "*** stack smashing detected ***: %s terminated\n",
__libc_argv[0] ?: "<unknown>");
}#v-
I'll give it a try.
Regards,
Thomas
Hi,
Quoted 10 lines · Samuel Thibault
Quoted 6 lines · Thomas Schwinge, le Wed 08 Nov 2006 22:40:54 +0100, a écrit :
then cat gnumach-undef-bad; exit 2; else true; fi
stack_chk_failIs it feasible to have the
-fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass-fno-stack-protector' if available?I'd say it shouldn't be very hard to provide a
stack_chk_failfunction, even if all it does is justpanic().
wont this add unnecessary bloat to the binary? No, not the function calling panic. Or are we seriously concerned about buffer overflows in the bootloader?
S.
Signature · 3 lines
coresystems GmbH • Brahmsstr. 16 • D-79104 Freiburg i. Br.
Tel.: +49 761 7668825 • Fax: +49 761 7664613
Email: [email protected] • http://www.coresystems.de/Hi,
Quoted 5 lines · Stefan Reinauer, le Wed 08 Nov 2006 23:36:44 +0100, a écrit :
Quoted 4 lines · Samuel Thibault
Quoted 3 lines · Thomas Schwinge, le Wed 08 Nov 2006 22:40:54 +0100, a écrit :
then cat gnumach-undef-bad; exit 2; else true; fi
stack_chk_fail
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
Is it feasible to have the
-fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass-fno-stack-protector' if available?I'd say it shouldn't be very hard to provide a
stack_chk_failfunction, even if all it does is justpanic().wont this add unnecessary bloat to the binary?
Just like to any binary of a distribution that would enable -fstack-protector by default. That's not our concern, that's the distribution's.
Samuel
Hello!
Quoted 6 lines · On Wed, Nov 08, 2006 at 11:36:20PM +0100, I wrote:
Quoted 5 lines · Samuel Thibault
Thomas Schwinge, le Wed 08 Nov 2006 22:40:54 +0100, a ?crit :
Quoted 3 lines
Is it feasible to have the
-fstack-protector' functionality in GNU Mach and GRUB2 (and how to do that, then) or shall we unconditionally pass-fno-stack-protector' if available?
Quoted 6 lines
Quoted 2 lines
I'd say it shouldn't be very hard to provide a
stack_chk_failfunction, even if all it does is justpanic().Having had a look at glibc's implementation and its complexity ;-) that might indeed be a reachable goal (assuming that no other surprises show up):
There were other surprises (namely a GCC bug), but see below: what follows there is a proposal for GNU Mach, the one for GNU GRUB2 would look somewhat similar.
To be discussed is the initialization of `__stack_chk_guard'. As I understand it, this is --- in user space programs and the OpenBSD kernel --- done by using some (pseudo)random values or --- if that's not possible in user space or in the DragonflyBSD kernel --- by using some special characters (nul', \n', `0x255'), like e.g.:
dragonflybsd/src/sys/libkern/stack_protector.c
#v+
[...]
#if BYTE_ORDER == LITTLE_ENDIAN
int __guard = 0x00000aff;
#else
int __guard = 0xff0a0000;
#endif
[...]
#v-
Other examples:
openbsd/src/sys/kern/init_main.c
#v+
[...]
long __guard[8];
[...]
{
volatile long newguard[8];
int i;
arc4random_bytes((long *)newguard, sizeof(newguard));
for (i = sizeof(__guard)/sizeof(__guard[0]) - 1; i; i--)
__guard[i] = newguard[i];
}[...]
#v-
user space gcc/libssp/ssp.c (the same is basically done in glibc's sysdeps/unix/sysv/linux/dl-osinfo.h, sysdeps/generic/dl-osinfo.h) #v+
[...]
void *__stack_chk_guard = 0;
[...]
static void __attribute__ ((constructor))__guard_setup (void)
{
unsigned char *p;
int fd;
if (__stack_chk_guard != 0)
return;
fd = open ("/dev/urandom", O_RDONLY);
if (fd != -1)
{
ssize_t size = read (fd, &__stack_chk_guard,
sizeof (__stack_chk_guard));
close (fd);
if (size == sizeof(__stack_chk_guard) && __stack_chk_guard != 0)
return;
} /* If a random generator can't be used, the protector switches the guard
to the "terminator canary". */
p = (unsigned char *) &__stack_chk_guard; p[sizeof(__stack_chk_guard)-1] = 255; p[sizeof(__stack_chk_guard)-2] = '\n';
p[0] = 0;
}
[...]
#v-
What do we want in GNU Mach?
The patch follows:
Index: configure.ac
===================================================================
RCS file: /cvsroot/hurd/gnumach/Attic/configure.ac,v retrieving revision 1.1.2.6
configure.ac +61 -0
@@ -83,6 +83,67 @@ dnl See below why we need to patch stuff AC_CHECK_PROG([PATCH], [patch], [patch], [patch-not-found]) # +# Compiler features. +# + +# Smashing stack protector. + +AC_ARG_ENABLE([smashing-stack-protector], + AS_HELP_STRING([--disable-smashing-stack-protector], + [disable the smashing stack protector])) +[# Default to using it, if possible. +enable_smashing_stack_protector=${enable_smashing_stack_protector-auto} +ssp_possible=no +# There was a bug in certain versions of GCC that made it emit incorrect code +# when used in a non-glibc environment. +ssp_usable=no +if [ x"$enable_smashing_stack_protector" != xno ]; then] + AC_MSG_CHECKING([whether the compiler accepts `-fstack-protector' and the \ +resulting code is suitable in a kernel environment]) + AC_LANG_CONFTEST([[void foo (void) { volatile char a[8]; a[3]; }]]) + [# `$CC -c -o ...' might not be portable. But, oh, well... + # Is calling `ac_compile' like this correct, after all? + if eval "$ac_compile -S -fstack-protector -o conftest.s"; then + ssp_possible=yes + if grep -q '%gs' conftest.s; then] + AC_MSG_RESULT([accepted, but not usable]) + [else] + AC_MSG_RESULT([yes]) + [ssp_usable=yes + fi + # Should we clear up other files as well, having called `AC_LANG_CONFTEST'? + rm -f conftest.s + else] + AC_MSG_RESULT([not accepted]) + [fi +fi +enable_smashing_stack_protector=\ +$enable_smashing_stack_protector-$ssp_possible-$ssp_usable +case $enable_smashing_stack_protector in + no-*) :;; + yes-no-*)] AC_MSG_ERROR([cannot use the smashing stack protector as it's \ +not supported by the compiler.])[;; + yes-*-no)] AC_MSG_ERROR([cannot use the smashing stack protector as it's \ +not properly supported by the compiler.])[;; + *-no-*)] AC_MSG_WARN([won't use the smashing stack protector as it's not \ +supported by the compiler.])[;; + *-*-no)] AC_MSG_WARN([won't use the smashing stack protector as it's not \ +properly supported by the compiler.])[;; + *-yes-yes) CFLAGS=$CFLAGS\ -fstack-protector + enable_smashing_stack_protector=yes + # This definition isn't used anywhere, but it's useful for having + # all files recompiled if an already-built tree is reconfigured + # to switch from using the smashing stack protector to not using + # it and vice versa.] + AC_DEFINE([USING_SMASHING_STACK_PROTECTOR], [], + [Are we using the smashing stack protector?])[;; + *)] AC_MSG_ERROR([please report to <$PACKAGE_BUGREPORT> that `configure.ac' \ +is buggy w.r.t. smashing stack protector detection.])[;; +esac] +AM_CONDITIONAL([enable_smashing_stack_protector], + [[[ x"$enable_smashing_stack_protector" = xyes ]]]) + +# # configure fragments. #
Index: Makefrag.am
===================================================================
RCS file: /cvsroot/hurd/gnumach/Attic/Makefrag.am,v retrieving revision 1.1.2.6
Makefrag.am +5 -0
@@ -111,6 +111,11 @@ libkernel_a_SOURCES += \ util/putchar.c \ util/puts.c +if enable_smashing_stack_protector +libkernel_a_SOURCES += \ + util/stack_chk_fail.c +endif + # Virtual memory implementation. libkernel_a_SOURCES += \ vm/vm_debug.c \
Index: util/stack_chk_fail.c
===================================================================
RCS file: util/stack_chk_fail.c
stack_chk_fail.c new file +33 -0
@@ -0,0 +1,33 @@ +/* +* Support for the smashing stack protector. +* +* Copyright (C) 2006 Free Software Foundation, Inc. +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License as +* published by the Free Software Foundation; either version 2, or (at +* your option) any later version. +* +* This program is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include <kern/debug.h> + +unsigned int __stack_chk_guard =12345 ; + +void +__attribute__ ((noreturn)) +__stack_chk_fail (void ) +{ +panic ("*** stack smashing detected ***\n" +"TODO: Explain.\n" +"TODO: Please do whatever and report to <" PACKAGE_BUGREPORT +"> or don't." ); +}
Index: doc/mach.texi
===================================================================
RCS file: /cvsroot/hurd/gnumach/doc/mach.texi,v
retrieving revision 1.4.2.5
mach.texi +5 -0
@@ -547,6 +547,11 @@ Sets the prefix to PREFIX. The default is the correct value for the GNU system. The prefix is prepended to all file names at installation time. +@item --disable-smashing-stack-protector +Specifying this, the smashing stack protector is disabled. By +default it is enabled if the compiler has proper support for it. +TODO: Explain what this does. + @item --enable-kdb Enables the in-kernel debugger. This is only useful if you actually anticipate debugging the kernel. It is not enabled by default because
What follows now is the snippet I used for testing this...
Index: i386/i386at/i386at_ds_routines.c
===================================================================
RCS file: /cvsroot/hurd/gnumach/i386/i386at/Attic/i386at_ds_routines.c,v retrieving revision 1.4.2.5
i386at/i386at_ds_routines.c +10 -0
@@ -74,6 +74,16 @@ ds_device_open (ipc_port_t open_port, ipint i;io_return_t err; +void crash_kernel_now (void ) + { +volatile char a[8 ]; +printf ("Preparing to crash the kernel...\n" ); + a[8 ] =42 ; + } + +if (name && name[0 ] =='c' && name[1 ] ==0 ) +crash_kernel_now (); +/* Open must be called on the master device port. */ if (open_port != master_device_port)return D_INVALID_OPERATION ;
... that one and then a doughty ``sudo devprobe c'' and I found myself in the kernel debugger and a ``*** stack smashing detected ***[...]'' message on the screen, as expected.
Regards,
Thomas
Hi,
Quoted 1 line · Thomas Schwinge, le Mon 13 Nov 2006 19:29:53 +0100, a écrit :
+unsigned int
__stack_chk_guard= 12345;
I'd say this should be something like a value with higher bits set, so that it wouldn't be a valid pointer, even for reading.
Samuel
Hello!
Quoted 14 lines · On Wed, Nov 08, 2006 at 10:40:54PM +0100, I wrote:
For some time, GCC now offers the following feature:
info Gcc
#v+
`-fstack-protector'
Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call alloca, and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits.
#v-
Quoted 3 lines
I now happen to be running a GCC 4.1 installation which has that one enabled by default. Unfortunately, building GNU Mach and GRUB2 (didn't check GRUB legacy) is affected by that:
To completely support this feature in kernel-like environments, work on GCC itself is needed, see
<http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29838>, so for the mean time I created the following patch to be able to continue building GRUB2 on systems that have `-fstack-protector' enabled by default. (This patch is equal to what we've been using in GNU Mach for some time now.)
2006-12-15 Thomas Schwinge <[email protected]>
* aclocal.m4 (grub_CHECK_STACK_PROTECTOR): New definition.
* configure.ac: Use it for testing the HOST and TARGET compilers.
Index: aclocal.m4
===================================================================
RCS file: /cvsroot/grub/grub2/aclocal.m4,v
retrieving revision 1.5
aclocal.m4 +20 -0
@@ -343,3 +343,23 @@ dnl So use regparm 2 until a better test [Catch gcc bug]) fi ]) + +dnl Check if the C compiler supports `-fstack-protector'. +dnl Written by Thomas Schwinge. +AC_DEFUN(grub_CHECK_STACK_PROTECTOR,[ +[# Smashing stack protector. +ssp_possible=yes] +AC_MSG_CHECKING([whether `$CC' accepts `-fstack-protector']) +# Is this a reliable test case? +AC_LANG_CONFTEST([[void foo (void) { volatile char a[8]; a[3]; }]]) +[# `$CC -c -o ...' might not be portable. But, oh, well... Is calling +# `ac_compile' like this correct, after all? +if eval "$ac_compile -S -fstack-protector -o conftest.s" 2> /dev/null; then] + AC_MSG_RESULT([yes]) + [# Should we clear up other files as well, having called `AC_LANG_CONFTEST'? + rm -f conftest.s +else + ssp_possible=no] + AC_MSG_RESULT([no]) +[fi] +])
Index: configure.ac
===================================================================
RCS file: /cvsroot/grub/grub2/configure.ac,v
retrieving revision 1.35
configure.ac +25 -0
@@ -149,6 +149,19 @@ fi AC_CHECK_FUNCS(posix_memalign memalign) # +# Compiler features. +# + +# Smashing stack protector. +grub_CHECK_STACK_PROTECTOR +[# Need that, because some distributions ship compilers that include +# `-fstack-protector' in the default specs. +if [ x"$ssp_possible" = xyes ]; then + CFLAGS=$CFLAGS\ -fno-stack-protector +fi] + + +# # Check for target programs. #
@@ -225,6 +238,18 @@ if test "x$target_m32" = x1; then TARGET_LDFLAGS="$TARGET_LDFLAGS -m32" fi +# +# Compiler features. +# + +# Smashing stack protector. +grub_CHECK_STACK_PROTECTOR +[# Need that, because some distributions ship compilers that include +# `-fstack-protector' in the default specs. +if [ x"$ssp_possible" = xyes ]; then + TARGET_CFLAGS=$TARGET_CFLAGS\ -fno-stack-protector +fi] + AC_SUBST(TARGET_CFLAGS) AC_SUBST(TARGET_CPPFLAGS) AC_SUBST(TARGET_LDFLAGS)
Regards,
Thomas
Hello!
Quoted 9 lines · On Fri, Dec 15, 2006 at 08:36:09PM +0100, I wrote:
I created the following patch to be able to continue building GRUB2 on systems that have `-fstack-protector' enabled by default. (This patch is equal to what we've been using in GNU Mach for some time now.)
2006-12-15 Thomas Schwinge <[email protected]>
* aclocal.m4 (
grub_CHECK_STACK_PROTECTOR): New definition.
* configure.ac: Use it for testing the HOST and TARGET compilers.
At Marco's disposition I just checked this in.
Regards,
Thomas