Get the address of an environment variable

My ASLR is disabled. Well, I want to get the address of the environment variable "SHELL", so I use the getenv () C function.

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char* ptr = getenv("SHELL"); printf("%p\n", ptr); } 

Address obtained with getenv ()

 $ ./getenv 0xbffff752 

Address obtained with gdb:

 gdb> x/4000s $esp ... (gdb) x/s 0xbffff710 0xbffff710: "SHELL=/bin/bash" (gdb) x/s 0xbffff716 0xbffff716: "/bin/bash" 

Why are the addresses different? As already noted, I have to say the correct address in the one received with GDB.

+5
source share
3 answers

Why are the addresses different?

Since one runs under gdb and the other does not. Working in a different environment leads to a different environment. In a literal sense.

What does the printf() operator output when working under gdb ?

As a note, I have to say the correct address in the one received with gdb.

What information is this operator based on?

+5
source

The problem is that your list of environment variables may be different when working under gdb and without it. And this is enough to cause a shift in the address.

A somewhat abridged listing ... (your program)

 $ gdb ./a.out (gdb) r Starting program: /home/mfranc/a.out 0x7fffffffdd37 (gdb) r Starting program: /home/mfranc/a.out 0x7fffffffdd37 (gdb) set environment a="hello world" (gdb) r Starting program: /home/mfranc/a.out 0x7fffffffdd27 (gdb) r Starting program: /home/mfranc/a.out 0x7fffffffdd27 (gdb) unset environment a (gdb) r Starting program: /home/mfranc/a.out 0x7fffffffdd37 (gdb) 

Generally, you should debug the source environment and join the process via gdb -p $ PID. If you start the process a little differently, and the environment will be slightly different, you can see different addresses.

+1
source

[For Linux]

From man 3 getenv() (italics mine):

The implementation of getenv () is not required to be reentrant. the string pointed to by the return value of getenv () can be statically allocated and can be changed by a subsequent call to getenv ().

This means that the requested value can be copied and a link to the copy returned, so the returned address may differ from the address in which the original env-var-tuple is stored.

0
source

All Articles