Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

This is probably a very basic question. I've read about canaries, and how they work in theory. You have a global variable that you set to a random number in the prolog of a function, do your function, and then verify its authenticity in the epilog.

void foobar(int a, int b)
{
   prolog();
   int c = a;
   int d = b;
   char *buffer[40];
   strcpy(stupidcopy);
   epilog();
}

What I don't understand is, how do I place something on the stack in prolog? Like, if I call prolog, and tell it to save a local variable, it'll be on stack, but when we get out of prolog(), won't it be popped? How can I save the canary on stack? Do I need to modify esp using assembly code to do this?

share|improve this question
1  
Step 1: Become a compiler –  CodesInChaos Jun 16 '13 at 8:30
add comment

1 Answer

up vote 3 down vote accepted

Usually it's the compiler who generates canaries. Prologue and epilogue aren't function calls, they're the instructions the compiler places at the beginning and end of a function.

Consider a naive compiler which puts variables on the stack in the same order they appear in the code and doesn't use registers. Then your function might become:

// variables on stack
int c;
int d;
char *buffer[40];
int canary;

// prologue
canary = secret;

// normal code
c=a;
d=b;
strcpy(stupidcopy);

// epilogue
if(canary != secret)
    OhNoesABufferOverflow();
return;

You can't write this code yourself since compilers can and do optimize storage on the stack. They can reorder variables, keep them in registers and it could even optimize out canary entirely since no well-behaved code will ever trigger the condition.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.