views:

5266

answers:

3

I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?

Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold:

  • Is there a way to get the address in memory of an environment variable?

  • Can this only be done in bash/C or can I do it purely in Python?

+1  A: 

The built in function id() returns a unique id for any object, which just happens to be it's memory address.

http://docs.python.org/library/functions.html#id

JimB
I realize this question was accepted but I don't see how it answers the root problem, namely "I need to set an environment variable in python". How will depending on the id returning a memory address solve the problem?
Bryan Oakley
I assumed he was referring to python variables, only because the "the memory address" of a shell environment variable doesn't really make sense.
JimB
I actually needed a way to get the memory address of where the shell environment variable is so I can feed it to a different program, which you can do with getenv() in C.
Chris Bunch
I'm a little confused - even in c, getenv only returns a string.char * getenv (const char *name)
JimB
Can't you just send a copy of the string to the "different program", do you really need the address?
Ali A
Yes, I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. But I need to find a way to automate this in Python, hence this question.
Chris Bunch
@Jim: getenv returns a char*, which you can cast to void* and then print to see the memory location where the env var is.
Chris Bunch
Ok, I just thought there was a strcopy going on (I don't do a lot of C though). I wouldn't have guessed that the string in python's os.environ dict points to the actual char * in the environment though.
JimB
From looking it over, it seems like it actually doesn't. It points to the Python representation, but I had accepted your answer because it looks like I can use it for a different purpose and it is technically correct.
Chris Bunch
+4  A: 

For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable.

Bryan Oakley
A: 

Pass the address itself in an environment variable, and just read it with os.getenv().

Ali A