检查 PIE 是否在 python 中启用

check if PIE is enable in python

从昨天开始我就在这里查看如何检测保护 "PIE" 是否被激活。为此,我分析了重定位条目的输出,以查看 _ITM_deregisterTMClone 是否存在。有没有更好的方法来检测 PIE 而无需通过 readelf 输出?

这是我目前拥有的:

def display_pie(counter):
    if (counter == 1):
            print("Pie : Enable")
    else:
            print("Pie: No PIE")

def check_file_pie(data_file):
    data = []
    data2 = []
    result = []
    ctn = 0
    check = subprocess.Popen(["readelf", "-r", data_file],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    result = check.stdout.readlines()
    for x in result:
        data.append(list(x))
    for lines in data:
            data2.append("".join(map(chr, lines)))
    for new_lines in data2:
            if "_ITM_deregisterTMClone" in new_lines:
                    ctn += 1
    display_pie(ctn)

谢谢,它非常技术性,所以如果有人能向我解释一种检查可执行独立位置的更好方法,我很感兴趣!

您可以使用 pwntools, which has functionality for manipulating ELF files。用法示例:

>>> from pwn import *
>>> e = ELF('your-elf-file')
>>> e.pie
True

如果你想知道它是如何实现的,可以find the source code here

您可以使用pyelftools检查ELF是否为共享对象以及图像基地址是否为零:

def is_pie(filename):
    from elftools.elf.elffile import ELFFile
    with open(filename, 'rb') as file:
        elffile = ELFFile(file)
        base_address = next(seg for seg in elffile.iter_segments() if seg['p_type'] == "PT_LOAD")['p_vaddr']
        return elffile.elftype == 'DYN' and base_address == 0