views:

42

answers:

2

I'm trying to turn some of the programs in gera's Insecure Programming by example into client/server applications that could be used in capture the flag scenarios to teach exploit development. The problem I'm having is that I'm not sure how Visual Studio (I'm using 2005 Professional Edition) decides where to allocate variables on the stack.

When I compile and run example 1:

int main() {
    int cookie;
    char buf[80];

    printf("buf: %08x cookie: %08x\n", &buf, &cookie);
    gets(buf);

    if (cookie == 0x41424344)
        printf("you win!\n");
}

I get the following result:

buf: 0012ff14 cookie: 0012ff64

buf starts at an address eighty bytes lower than cookie, and any four bytes that are copied in buf after the first eighty will appear in cookie.

The problem I'm having is when I place this code in some other function. When I compile and run the following code, I get a different result: buf appears at an address greater than cookie's.

void ClientSocketHandler(SOCKET cs){
 int cookie;
 char buf[80];
 char stringToSend[160];
 int numBytesRecved;
 int totalNumBytes;

 sprintf(stringToSend,"buf: %08x cookie: %08x\n",&buf,&cookie);
 send(cs,stringToSend,strlen(stringToSend),NULL);

The result is:

buf: 0012fd00 cookie: 0012fcfc

Now there is no way to set cookie to arbitrary data via overwriting buf. Is there any way to tell Visual Studio to allocate cookie before buf? Is there any way to tell beforehand how the variables will be allocated?

Thanks,

Jason

Ah, okay. Yes, I guess structs will have to do. Thanks for the help.

+1  A: 

Try turning off compiler optimizations.

If optimizations are already off, your best bet to force the compiler to put locals in a specific order is to place the local vars into a structure, and allocate that structure on the local stack. The fields in that structure are less likely to be moved around (relative to each other) by the compiler than independent local vars.

dthorpe
A: 

Thanks for answering so quickly. Yes, the result that is shown above was compiled without optimizations enabled.

Jason