Python print environment variable memory address
Please keep in mind that system environment variable is not an object you can access by its memory address. Each process, like Python or Ruby process running your script will receive its own copy of environment. Thats why results returned by Python and Ruby interpreters are so different.
If you would like to modify system environment variable you should use API provided by your programming language. Please see this or that post for Python solution.
I suppose you could do that using the ctypes
module to call the native getenv
directly :
import ctypes
libc = ctypes.CDLL("libc.so.6")
getenv = libc.getenv
getenv.restype = ctypes.c_voidp
print('%08x' % getenv('PATH'))
The cpython built in function id() returns a unique id for any object, which is not exactly it's memory address but is as close as you can get to such.
For example, we have variable x. id(x) does not return the memory address of the variable x, rather it returns the memory address of the object that x points to.
There's a strict separation between 'variables' and 'memory objects'. In the standard implementation, python allocates a set of locals and a stack for the virtual machine to operate on. All local slots are disjoint, so if you load an object from local slot x onto the stack and modify that object, the "location" of the x slot doesn't change.
http://docs.python.org/library/functions.html#id
This seems an impossible task at least in python. There are few things to take in consideration from this question:
- ASLR would make this completely impossible
- Every binary can have it's own overhead, different argv, so, the only reliable option is to execute the binary and trace it's memory until we found the environment variable we are looking for. Basically, even if we can find the environment address in the python process, it would be at a different position in the binary you are trying to exploit.
Best fit to answer this question is to use http://python3-pwntools.readthedocs.io/en/latest/elf.html which is taking a coredump file where it's easy to find the address.