Python print environment variable memory address Python print environment variable memory address ruby ruby

Python print environment variable memory address


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.

enter image description herehttp://docs.python.org/library/functions.html#id


I suppose you could do that using the ctypes module to call the native getenv directly :

import ctypeslibc = ctypes.CDLL("libc.so.6")getenv = libc.getenvgetenv.restype = ctypes.c_voidpprint('%08x' % getenv('PATH'))


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.