Pwning a Canary
Posted on th, by BlasStack Canaries
Eh? A Stack Canary is a mitigation designed to protect against things like stack based buffer overflows. A canary is a random value that is placed at the bottom of the stack frameand so that if a buffer overflow occurs then this value would be overwritten. There is a check before the return address is executed to determine if the canary value is unchanged. If the value has been altered then the program terminates.
Sounds unbeatable! Maybe, but there are ways we can bypass it. A stack canary can be leaked by different means such that when we do want to eventuall perform something like our stack based overflow, we should be able to overwrite the canary with its original value. Now I do Windows security so this will be based off the different approaches you can take with PE files, however, these skills can transfer over for the more Linux oriented world of ELFs.
We have little time to waste so let’s take a brief dive into a sample!
Sample
Here is a vulnerable little program that copies a string into a buffer of size 500. The issue? Well…the string is actually Message and message can have a size of up to 5000 which is significantly larger. This is a buffer overflow!
#include <iostream>
void copyMsg(char* str)
{
char buf[500] = " ";
strcpy(buf, str);
}
int main(int argc, char* argv[])
{
char Message[5000] = " ";
std::cin >> Message;
copyMsg(Message);
return 0;
}
The above code compiles on Visual Studio after performing some compilation magic and now we get to check it out on a debugger and see where the canary is present in the code.