Pwn题中修改程序连接库的方法

做Pwn的时候有时候会遇到题目的环境和本地环境不一致的情况。如果要装和远程环境相同的虚拟机就会比较麻烦,下面可以通过修改binary动态连接库的方法,强行让程序链接到与远程环境相同的库上。

1.首先下载好和远程环境相同的动态库,如libc-2.23.so;然后下载与之相符的链接器ld-2.23.so。有两个项目可以实现自动下载 libc:https://github.com/niklasb/libc-database和https://github.com/matrix1001/glibc-all-in-one。
2.运行下面脚本。这个脚本修改了二进制文件的头部信息,将其连接器位置修改成你想替换的连接器,然后修改环境变量LD_PRELOAD,去加载动态库。

import os
from pwn import *

def change_ld(binary, ld):
    """
    Force to use assigned new ld.so by changing the binary
    """
    if not os.access(ld, os.R_OK): 
        log.failure("Invalid path {} to ld".format(ld))
        return None
 
         
    if not isinstance(binary, ELF):
        if not os.access(binary, os.R_OK): 
            log.failure("Invalid path {} to binary".format(binary))
            return None
        binary = ELF(binary)
 
    for segment in binary.segments:
        if segment.header['p_type'] == 'PT_INTERP':
            size = segment.header['p_memsz']
            addr = segment.header['p_paddr']
            data = segment.data()
            if size <= len(ld):
                log.failure("Failed to change PT_INTERP from {} to {}".format(data, ld))
                return None
            binary.write(addr, ld.ljust(size, '\0'))
            if not os.access('./Pwn', os.F_OK): os.mkdir('./Pwn')
            path = './Pwn/{}_debug'.format(os.path.basename(binary.path))
            if os.access(path, os.F_OK): 
                os.remove(path)
                info("Removing exist file {}".format(path))
            binary.save(path)    
            os.chmod(path, 0b111000000) #rwx------
    success("PT_INTERP has changed from {} to {}. Using temp file {}".format(data, ld, path)) 
    return ELF(path)

elf=change_ld('./pwn','./ld-2.23.so')
p = elf.process(env={'LD_PRELOAD':'./libc-2.23.so'})
p.interactive()

3.如果要动态调试,在运行二进制之后,attach这个进程即可。

参考连接:关于不同版本glibc强行加载的方法

你可能感兴趣的:(pwn)