15.3.3 Customizing the Stack Canary Value

The Stack Smashing Protector implementation relies on a secret value that is placed on a protected function's call stack. This value, called the canary, is determined at compile time. Your application code can (and should) define an application-specific value. The value must be kept secret from any potential attacker.

extern unsigned long __stack_chk_guard;
void __attribute__((constructor, optimize("-fno-stack-protector")))
my_stack_guard_setup(void)
{
    __stack_chk_guard = 0x12345678; // the new secret value for the canary
}
  • The custom setter function must be a constructor to ensure it is called before executing the application.
  • The attribute __optimize__ ("-fno-stack-protector"))) disable stack protector option for this function to avoid a runtime error in case –-fstack-protector-all is used.