[Python] 纯文本查看 复制代码import lief
import argparse
def add_empty_section(input_path, output_path, section_name=".injected", size=4096):
binary = lief.parse(input_path)
new_section = lief.ELF.Section(section_name)
new_section.type = lief.ELF.Section.TYPE.PROGBITS
print(binary.get_section(".text").alignment)
new_section.flags = 6
new_section.content = [0x90]*size
new_section.alignment = 16
new_section.size = size
binary.add(new_section,True)
for sec in binary.sections:
print(f"sec name :{sec.name} offset:0x{sec.offset:x} size:0x{sec.size:x} align:0x{sec.alignment:x} type:{sec.type} flags:{sec.flags}")
binary.write(output_path)
return binary
def fix_section_header_alignment(file_path):
binary = lief.ELF.parse(file_path)
if not binary:
raise RuntimeError(f"Failed to parse {file_path} as ELF binary")
shoff_original = binary.header.section_header_offset
print(f"Original section header offset: {shoff_original}")
pad_len = (8 - (shoff_original % 8)) % 8
print("Padding needed:", pad_len)
if pad_len == 0:
print("Section header already aligned, no need to modify")
return
shoff_aligned = shoff_original + pad_len
print(f"Aligned section header offset: {shoff_aligned}, padding {pad_len} bytes")
padding_section = lief.ELF.Section()
padding_section.name = ""
padding_section.type = lief.ELF.Section.TYPE.NOBITS
padding_section.flags = 0
padding_section.content = []
padding_section.size = pad_len
padding_section.offset = shoff_original
padding_section.virtual_address = 0
binary.add(padding_section, loaded=False)
binary.header.section_header_offset = shoff_aligned
for section in binary.sections:
if section.offset >= shoff_original:
section.offset += pad_len
for segment in binary.segments:
if segment.file_offset >= shoff_original:
segment.file_offset += pad_len
binary.write(file_path)
print(f"Successfully aligned section headers in {file_path} section header offset is now {binary.header.section_header_offset} size {binary.header.section_header_size}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="为 ELF 文件添加空 Section")
parser.add_argument("input", help="输入 .so 文件路径")
parser.add_argument("output", help="输出 .so 文件路径")
parser.add_argument("--name", default=".injected", help="Section 名称(默认:.injected)")
parser.add_argument("--size", type=int, default=4096, help="Section 大小(默认:4096)")
args = parser.parse_args()
binary = add_empty_section(args.input, args.output, args.name, args.size)
fix_section_header_alignment(args.output)
[color=]