Stack Smashing Protector

From OSDev.wiki
Revision as of 11:01, 16 April 2010 by Creature (talk | contribs) (Added code tags.)
Jump to navigation Jump to search

GCC Stack-Smashing Protector (ProPolice)

What is it?

The GCC SSP protects the stack from buffer overflows. If a buffer overflow occurs, you're informed instantly. The way this works is by inserting a "canary" value into the stack frame that, if changed, indicates a buffer overflow or stack corruption. This feature can not only detect buffer overflows, malicious or accidental, but also may help in detecting other stack-related bugs that are often found in kernel code.

How to implement it

When you started OS developing, you might have seen that following error:

... undefined reference to __stack_chk_fail

... undefined reference to __stack_chk_guard

That's actually the SSP! You probably just didn't care about it and disabled it.

Now, implementing this feature is dead easy and it is a really handy thing.

void * __stack_chk_guard = NULL;

void __stack_chk_guard_setup()
{
    unsigned char * p;
    p = (unsigned char *) &__stack_chk_guard;
    p[sizeof(__stack_chk_guard)-1] = 255;  /* <- this should be probably randomized */
    p[sizeof(__stack_chk_guard)-2] = '\n';
    p[0] = 0;
}

void __attribute__((noreturn)) __stack_chk_fail()
{ /* put your panic function or similar in here */
    unsigned char * vid = (unsigned char *)0xB8000;
    vid[1] = 7;
    for(;;)
    vid[0]++;
}

Call __stack_chk_guard_setup at early boot stage, from there on you're protected from most buffer overflows.

Don't forget to add -fstack-protector-all to the gcc flags.

See Also

Articles

Threads

External Links