0

How to turn off gcc compiler optimization to enable buffer overflow

I see that a command like gcc vuln.c -o vuln_disable_canary -fno-stack-protector is said to disable canary.

I tried the following example, the vanilla gcc command generates a file without canary.

Does anybody know how to disable/enable canary?

$ cat helloworld.c
#include <stdio.h>
int main() {
    puts("Hello World!");
}
$ gcc helloworld.c
$ gcc helloworld.c -o no_canary.out -fno-stack-protector
$ rabin2 -I a.out | grep canary
canary   false
$ rabin2 -I no_canary.out | grep canary
canary   false

BTW, what does the name canary mean?

1 Answers1

3

So, apparently it's disabled by default on your platform; this behavior is configurable when gcc is built from source, and this is what your OS or packager chose to do. Use -fstack-protector to enable it (if your platform supports it at all).

For more about how gcc's stack canary system works, see Stack smashing detected.

In ordinary English, a canary is a type of bird that was used to detect toxic gases in mines. The birds were more sensitive to these gases than humans are, and so if the bird died, this could alert the miners to the danger while they still had time to evacuate. The analogy is that the value on the stack is like a canary: if it "dies" (is overwritten) then the program can "evacuate" (abort) before an exploit can occur.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • So, the canary value should be overwritten by a value that literally does not change the original value. In this case the stack corruption will not be detected? –  Apr 07 '21 at 14:49
  • 1
    @user15502206: Right, if you want to mount a successful attack, that's what you have to do. The problem is that the canary value is chosen randomly on each run of the program, so you as the attacker normally won't know what it is. You have to either get very lucky, or find some other vulnerability that leaks the canary value. – Nate Eldredge Apr 07 '21 at 14:52