简体   繁体   English

获取环境变量地址

[英]Get the environment variable address

I have ASLR disabled. 我禁用了ASLR。 Well, I want obtain the address of the environment variable "SHELL", so I use the C function getenv(). 好吧,我想获取环境变量“SHELL”的地址,所以我使用C函数getenv()。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char* ptr = getenv("SHELL");
    printf("%p\n", ptr);
}

The address obtained with getenv() 用getenv()获得的地址

$ ./getenv
0xbffff752

The address obtained with gdb: 使用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 noted, I must say the correct address in the obtained with GDB. 如上所述,我必须说明使用GDB获得的正确地址。

Why the addresses are different? 为什么地址不同?

Because one is run under gdb and one isn't. 因为一个是在gdb下运行而另一个不是。 Running under a different environment results in a different environment. 在不同的环境下运行会导致不同的环境。 Literally. 从字面上看。

What's the output of the printf() statement when running under gdb ? gdb下运行时printf()语句的输出是什么?

As note, I must say the correct address in the obtained with gdb. 请注意,我必须说明使用gdb获取的正确地址。

What information is that statement based on? 该声明基于什么信息?

The trouble is that your list of environment variables can differ when running under gdb and without it. 麻烦的是,在gdb下运行时没有环境变量列表可能会有所不同。 And that is enough to cause the shift in address. 这足以引起地址的转变。

Somewhat shortened 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 in the original environment and attach to the process via gdb -p $PID. 通常,您应该在原始环境中进行调试,并通过gdb -p $ PID附加到进程。 If you spawn process in a slightly different way and the environment will differ slightly you might see different addresses. 如果以稍微不同的方式生成进程并且环境稍有不同,您可能会看到不同的地址。

[For Linux] [对于Linux]

From man 3 getenv() ( italics by me): 来自man 3 getenv()斜体由我):

The implementation of getenv() is not required to be reentrant. getenv()的实现不需要是可重入的。 The string pointed to by the return value of getenv() may be statically allocated, and can be modified by a subsequent call to getenv(). getenv()返回值指向的字符串可以静态分配,并可以通过后续调用getenv()进行修改。

This implies that the value queried may be copied and a reference to the copy is returned, so the address returned might differ from the address where the original env-var-tuple is stored. 这意味着可以复制查询的值并返回对副本的引用,因此返回的地址可能与存储原始env-var-tuple的地址不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM