views:

79

answers:

4

I'm reading Hacking: The Art of Exploitation (2nd Edition), and I'm currently on the section about buffer overflows.

In the first example, the variables are declared/initialized in this order:

int auth_flag = 0;
char password_buffer[16];

The example goes on to explain that you can use gdb to examine auth_flag and password_buffer's addresses, and you'll notice that auth_flag's address is higher than password_buffer's. Things to keep in mind: I'm running all of this in Ubuntu within Virtualbox on a Macbook Pro (Intel processor, 64-bit).

I compiled the first example's code like this: gcc -g -fno-stack-protector -o auth_overflow auth_overflow.c

As expected, auth_flag's address is higher than password_buffer's.

To remedy the problem presented above, the author explains you should switch the ordering of the declarations:

char password_buffer[16];
int auth_flag = 0;

I compiled the code the same way: gcc -g -fno-stack-protector -o auth_overflow2 auth_overflow2.c

Unfortunately, I did not see auth_flag's address being lower than password_buffer's. In fact, it was still higher. Why is this? What am I doing wrong?

+1  A: 

Compilers are free to rearrange variables as they feel is best. I believe that the only restriction in the order of struct members. Those must be in memory in the same order as declared in the struct.

Zan Lynx
+5  A: 

The compiler is allowed to choose whatever order it wants, in order to provide more optimal code, or even just random because it's easier to implement. One thing you might try is -O0 flag which disables all optimizations.

Karl Bielefeldt
A: 

I found this thread quite interesting:

http://www.mail-archive.com/[email protected]/msg05043.html

Quote: In theory it can be done

-fdata-section
karlphillip
A: 

Apple has a security feature to prevent just the type of hacking you are talking about - There is a degree of randomization to where everything is stored in memory, so you can't for example find the memory allocated for a certain program, and go to the 1502nd byte where the function to open the high security vault locks sits, cause it isn't always in the same place in memory.

See http://en.wikipedia.org/wiki/Address_space_layout_randomization for details on how this works.

Funny coincidence that you would encounter this, and that Matt Joiner would stumble on the answer while trying to burn apple.

Alex Gosselin
On second thought... did you say Ubuntu is the active OS? I could be completely wrong if that's the case.
Alex Gosselin
Firstly, the OP did say that he's running the experiment in a Ubuntu VM. Secondly, Ubuntu has ASLR enabled too. And thirdly, ASLR randomises the stack base, but doesn't randomise the relative positions of two stack variables.
caf