A few days back, I read about stack canaries. I thought I’d blog about it. So here goes…
A Stack Canary is a mechanism that protects the stack from getting attacked by malicious code. A stack canary is an extra bit that is added to the stack after every buffer or function in the code. In short, it is inserted in the memory wherever there is a return address, right after the buffer. This bit is then followed by the return address. Thus, if a hacker tries to overwrite the return address he would have to surely overwrite the canary bit as well. When before execution goes to the overwritten address it checks if the value of the canary bit has changed or not. If it is found that the value has been changed, the execution of the program stops immediately.
The following figure shows a clear picture of where the canary bit is placed.
However, there are ways by which this mechanism could be exploited as well. The hacker could find out the value of the original value of canary bit and then copy the same value into the location of the canary bit when the return address if being overwritten or the buffer is overflowed. So, when the address in the eip is being overwritten and the value of canary is checked it remains the same.