Stack Smashing Protector: Difference between revisions

m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
m (→‎See Also: add link to Undefined Behavior Sanitization)
m (Bot: Replace deprecated source tag with syntaxhighlight)
 
(4 intermediate revisions by 3 users not shown)
Line 4:
 
Compilers implement this feature by selecting appropriate functions, storing the stack canary during the function prologue, checking the value in the epilogue, and invoking a failure handler if it was changed. For instance, consider the code:
<sourcesyntaxhighlight lang="c">
void foo(const char* str)
{
Line 10:
strcpy(buffer, str);
}
</syntaxhighlight>
</source>
SSP automatically illustratively transforms that code into this:
<sourcesyntaxhighlight lang="c">
/* Note how buffer overruns are undefined behavior and the compilers tend to
optimize these checks away if you wrote them yourself, this only works
Line 26:
__stack_chk_fail();
}
</syntaxhighlight>
</source>
Note how the secret value is stored in a global variable (initialized at program
load time) and is copied into the stack frame, and how it is safely erased from
Line 88:
* Supply your own implementation in libc (so libc can take advantage of the feature) and install empty libssp and libssp_nonshared libraries (or change your toolchain to not use them).
* Use the libssp implementation that comes with GCC.
 
It should also be noted that with the optimisations enabled via <tt>-O<n></tt> in GCC, the compiler may or may not "inline" a function. If a function has been inlined, then '''stack smash protection will not work for that function.''' To prevent this, one must use the <tt>noinline</tt> attribute like so:
<syntaxhighlight lang="c">
void __attribute__ ((noinline)) foo( /* args */ )
{
// Code goes here
}
</syntaxhighlight>
 
Disabling inlining in GCC can be done with the <tt>-fno-inline</tt> compile flag, however, that will not inline functions with the <tt>inline</tt> attribute. The <tt>-fno-inline-functions</tt> will not inline functions optimised with <tt>-O<n></tt>; but that has been proven ineffective for GCC versions 3.4.5 and over ([https://gcc.gnu.org/bugzilla/show_bug.cgi?id=28120 see bug report]).
 
If any tests do not work when trying to trip the protective mechanism, this may be the reason why it does not work!
 
== Implementation ==
Line 94 ⟶ 106:
failure handler. For instance, a minimal implementation could be:
 
<sourcesyntaxhighlight lang="c">
#include <stdint.h>
#include <stdlib.h>
Line 116 ⟶ 128:
}
 
</syntaxhighlight>
</source>
 
Note how the secret guard value is hard-coded rather than being decided during