Stack Smashing Protector

From OSDev.wiki
Revision as of 13:39, 2 July 2010 by Solar (talk | contribs) (→‎How to implement it: p[1] wasn't initialized, and the sizeof() wasn't strictly necessary.)
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;
    /* 32bit code, obviously */
    p[0] = 0;
    p[1] = 0;
    p[2] = '\n';
    p[3] = 255; /* <- this should probably be randomized */
}

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