3

I checked if ASLR is enabled as follows and I think it is:

[user@localhost test]$ cat /proc/sys/kernel/randomize_va_space
2

I tried testing it with the following program:

test.c:

#include <stdio.h>
int main(void)
{
    printf("%p\n", main);
    return 1;
}

I expected, if ASLR is active, to a different address for each run, right? But I got the same each time. I tested both for 64bit and 32bit executables. I am using a 64bit Arch Linux system to test this:

[user@localhost test]$ gcc test.c -o test
[user@localhost test]$ ./test
0x4004c6
[user@localhost test]$ ./test
0x4004c6
[user@localhost test]$ ./test
0x4004c6
[user@localhost test]$ ./test
0x4004c6
[user@localhost test]$ gcc -m32 test.c -o test
[user@localhost test]$ ./test
0x80483eb
[user@localhost test]$ ./test
0x80483eb
[user@localhost test]$ ./test
0x80483eb
[user@localhost test]$ ./test
0x80483eb

As you can see, the address is the same for every run. Doesn't this mean that ASLR is off?

4

1 回答 1

10

您的可执行文件必须与位置无关才能允许。

gcc -pie -fPIE -o test test.c

尝试以这种方式运行它,每次运行时地址都会明显改变。

非 PI 可执行文件旨在加载到存储在其 ELF 标头中的固定、明确的非随机地址。这种假设允许编译器和链接器将绝对地址硬编码到输出中,使其在某些目标上更小更快。

在任何其他地址加载非 PI 可执行文件会使所有这些绝对引用无效,导致最好的情况是 SIGSEGV,最坏的情况是运行一些随机代码。的地址main不能安全地随机化,因为允许编译器假设它不会,所以即使启用了 ASLR,它也永远不会完成。

为了允许随机化,必须告诉编译器生成与位置无关的代码-fPIE-pie

需要哪些选项来实现这在很大程度上取决于工具链配置,-fpie, -fPIE, -fpic, -fPIC, 有些可能会默认生成 PI 代码。安全的选择是编译-fPIE并链接到-pie -fPIE.

于 2016-08-07T20:36:24.547 回答