开发者

How does Visual Studio decide the order in which stack variables should be allocated?

开发者 https://www.devze.com 2022-12-29 08:31 出处:网络
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 p

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 byt开发者_运维百科es 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消