def print_symbols(binary): symbols = binary.symbols if len(symbols) > 0: print("== Symbols ==") f_title = "|{:<20} | {:<10} | {:<8} | {:<8} | {:<8} | {:<13} |" f_value = u"|{:<20} | 0x{:<8x} | {:<14} | {:<10} | {:<12} | {:<13} |" print(f_title.format("Name", "Value", "Section number", "Basic type", "Complex type", "Storage class")) for symbol in symbols: section_nb_str = "" if symbol.section_number <= 0: section_nb_str = str(PE.SYMBOL_SECTION_NUMBER(symbol.section_number)).split(".")[-1] else: try: section_nb_str = symbol.section.name except: section_nb_str = "section<{:d}>".format(symbol.section_number) print(f_value.format( symbol.name[:20], symbol.value, section_nb_str, str(symbol.base_type).split(".")[-1], str(symbol.complex_type).split(".")[-1], str(symbol.storage_class).split(".")[-1]))
def print_information(binary): print("== Information ==\n") format_str = "{:<30} {:<30}" format_hex = "{:<30} 0x{:<28x}" format_dec = "{:<30} {:<30d}" print(format_str.format("Name:", binary.name)) print(format_hex.format("Virtual size:", binary.virtual_size)) print(format_str.format("Imphash:", PE.get_imphash(binary)))
def create_section(binary): section = None if is_pefile(binary): # PE file section = PE.Section() section.characteristics = PE.SECTION_CHARACTERISTICS.CNT_CODE | PE.SECTION_CHARACTERISTICS.MEM_READ | PE.SECTION_CHARACTERISTICS.MEM_EXECUTE | PE.SECTION_CHARACTERISTICS.MEM_WRITE # section.virtual_size = 0x1000 section.content = [0x90] * 0x1000 else: section = ELF.Section() section += ELF.SECTION_FLAGS.ALLOC section += ELF.SECTION_FLAGS.WRITE section += ELF.SECTION_FLAGS.EXECINSTR section.alignment = 16 section.content = [0x90] * 0x1000 return section
imports = { "kernel32.dll": { "GetStdHandle": 0, "WriteFile": 0, "ReadFile": 0, "WinExec": 0, }, } data = { welcome: 0, test: 0, } binary32 = PE.Binary("pwn.exe", PE.PE_TYPE.PE32) # Start with 0x100 bytes of \cc section_text = PE.Section(".text") section_text.content = tobytes(x86.Int3().get_code() * 0x100) section_text.virtual_address = 0x1000 # Init data section data_raw = '' for obj in data.keys(): data[obj] = binary32.optional_header.imagebase + len(data_raw) + 0x2000 data_raw += obj section_data = PE.Section(".data") section_data.content = tobytes(data_raw) section_data.virtual_address = 0x2000
def main(): optparser = OptionParser( usage='Usage: %prog [options] <pe-file>', add_help_option = True, prog=sys.argv[0]) optparser.add_option('-a', '--all', action='store_true', dest='show_all', help='Show all informations') optparser.add_option('-d', '--data-directories', action='store_true', dest='show_data_directories', help='Display data directories') optparser.add_option('--debug', action='store_true', dest='show_debug', help='Display debug directory') optparser.add_option('-g', '--signature', action='store_true', dest='show_signature', help="Display the binary's signature if any") optparser.add_option('-H', '--header', action='store_true', dest='show_headers', help='Display headers') optparser.add_option('-i', '--import', action='store_true', dest='show_imports', help='Display imported functions and libraries') optparser.add_option('-r', '--relocs', action='store_true', dest='show_relocs', help='Display the relocations (if present)') optparser.add_option('-R', '--rich-header', action='store_true', dest='show_richheader', help='Display the Rich Header') optparser.add_option('-S', '--section-headers', '--sections', action='store_true', dest='show_section_header', help="Display the sections' headers") optparser.add_option('-s', '--symbols', '--syms', action='store_true', dest='show_symbols', help='Display symbols') optparser.add_option('-t', '--tls', action='store_true', dest='show_tls', help='Display TLS informations') optparser.add_option('-x', '--export', action='store_true', dest='show_export', help='Display exported functions/libraries') options, args = optparser.parse_args() if len(args) == 0: optparser.print_help() sys.exit(1) binary = None try: binary = PE.parse(args[0]) except lief.exception as e: print(e) sys.exit(1) if options.show_data_directories or options.show_all: print_data_directories(binary) if options.show_headers or options.show_all: print_header(binary) if (options.show_imports or options.show_all) and binary.has_imports: print_imports(binary) if (options.show_relocs or options.show_all) and binary.has_relocations: print_relocations(binary) if options.show_section_header or options.show_all: print_sections(binary) if options.show_symbols or options.show_all: print_symbols(binary) if (options.show_tls or options.show_all) and binary.has_tls: print_tls(binary) if (options.show_export or options.show_all) and binary.has_exports: print_export(binary) if (options.show_debug or options.show_all) and binary.has_debug: print_debug(binary) if (options.show_signature or options.show_all) and binary.has_signature: print_signature(binary) if (options.show_richheader or options.show_all) and binary.has_rich_header: print_rich_header(binary)
def main(): parser = argparse.ArgumentParser() parser.add_argument("pe_file") parser.add_argument('-a', '--all', action='store_true', dest='show_all', help='Show all informations') parser.add_argument('-d', '--data-directories', action='store_true', dest='show_data_directories', help='Display data directories') parser.add_argument('--dbg', action='store_true', dest='show_debug', help='Display debug directory') parser.add_argument('-g', '--signature', action='store_true', dest='show_signature', help="Display the binary's signature if any") parser.add_argument('-H', '--header', action='store_true', dest='show_headers', help='Display headers') parser.add_argument('-i', '--import', action='store_true', dest='show_imports', help='Display imported functions and libraries') parser.add_argument( '--resolve-ordinals', action='store_true', dest='resolve_ordinals', help= "When used with --import, it attempts to resolve names of ordinal imports" ) parser.add_argument('-r', '--relocs', action='store_true', dest='show_relocs', help='Display the relocations (if present)') parser.add_argument('-R', '--rich-header', action='store_true', dest='show_richheader', help='Display the Rich Header') parser.add_argument('--resources', '--rsrc', action='store_true', dest='show_resources', help='Display the resources (if present)') parser.add_argument('-S', '--section-headers', '--sections', action='store_true', dest='show_section_header', help="Display the sections' headers") parser.add_argument('-s', '--symbols', '--syms', action='store_true', dest='show_symbols', help='Display symbols') parser.add_argument('-t', '--tls', action='store_true', dest='show_tls', help='Display TLS informations') parser.add_argument('-x', '--export', action='store_true', dest='show_export', help='Display exported functions/libraries') parser.add_argument('--load-config', action='store_true', dest='show_loadconfig', help='Display load configuration') parser.add_argument('--ctor', action='store_true', dest='show_ctor', help='Constructor functions') parser.add_argument('-f', '--functions', action='store_true', dest='show_functions', help='Display all functions found in the binary') parser.add_argument( '--exception-functions', action='store_true', dest='show_pfunctions', help='Display functions found in the exception directory') parser.add_argument('--delay-imports', action='store_true', dest='show_delay_imports', help='Display delay imports') # Logging setup logger_group = parser.add_argument_group('Logger') verbosity = logger_group.add_mutually_exclusive_group() verbosity.add_argument('--debug', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.DEBUG) verbosity.add_argument('--trace', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.TRACE) verbosity.add_argument('--info', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.INFO) verbosity.add_argument('--warn', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.WARNING) verbosity.add_argument('--err', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.ERROR) verbosity.add_argument('--critical', dest='main_verbosity', action='store_const', const=lief.logging.LOGGING_LEVEL.CRITICAL) parser.set_defaults(main_verbosity=lief.logging.LOGGING_LEVEL.WARNING) args = parser.parse_args() lief.logging.set_level(args.main_verbosity) binary = None try: binary = PE.parse(args.pe_file) except lief.exception as e: print(e) sys.exit(1) if binary is None: sys.exit(1) print_information(binary) if args.show_data_directories or args.show_all: print_data_directories(binary) if args.show_headers or args.show_all: print_header(binary) if (args.show_imports or args.show_all) and binary.has_imports: print_imports(binary, resolve=args.resolve_ordinals) if (args.show_relocs or args.show_all) and binary.has_relocations: print_relocations(binary) if args.show_section_header or args.show_all: print_sections(binary) if args.show_symbols or args.show_all: print_symbols(binary) if (args.show_tls or args.show_all) and binary.has_tls: print_tls(binary) if (args.show_export or args.show_all) and binary.has_exports: print_export(binary) if (args.show_debug or args.show_all) and binary.has_debug: print_debug(binary) if (args.show_signature or args.show_all) and binary.has_signatures: print_signature(binary) if (args.show_richheader or args.show_all) and binary.has_rich_header: print_rich_header(binary) if (args.show_resources or args.show_all) and binary.has_resources: print_resources(binary) if (args.show_loadconfig or args.show_all) and binary.has_configuration: print_load_configuration(binary) if args.show_ctor or args.show_all: print_ctor(binary) if args.show_functions or args.show_all: print_functions(binary) if args.show_pfunctions or args.show_all: print_exception_functions(binary) if args.show_delay_imports or args.show_all: print_delay_imports(binary)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Description: # Create a PE which pop a MessageBox # with the message "Hello World" # fetch detail : https://lief.quarkslab.com/doc/tutorials/02_pe_from_scratch.html from lief import PE # First we have to create a Binary : binary32 = PE.Binary("pe_from_scratch", PE.PE_TYPE.PE32) # The first parameter is the binary’s name and the second one # is the type: PE32 or PE64 (see PE_TYPE). The Binary‘s constructor # creates automatically DosHeader, Header, OptionalHeader an empty DataDirectory. # # Now that we have a minimal binary, we have to add sections. # We will have a first section holding assembly code (.text) # and a second one containing strings (.data): # A MessageBoxA is composed of a title and a message. # These two strings will be stored in the .data as follows: title = "LIEF is awesome\0" message = "Hello World\0" data = list(map(ord, title)) data += list(map(ord, message)) code = [ 0x6a, 0x00, # push 0x00 uType
def build_pe_executable(asm_code: bytearray, memory_layout: List[MemorySection], arch: Architecture) -> str: """ Uses LIEF to build a standalone binary. Upon success, return the path to the file generated """ if not is_x86_32(arch) and not is_x86_64(arch): raise ValueError("Unsupported architecture for PE generation") is_x64 = is_x86_64(arch) if is_x64: basename = "cemu-pe-amd64-{:s}".format(generate_random_string(5)) pe = PE.Binary(basename, PE.PE_TYPE.PE32_PLUS) else: basename = "cemu-pe-i386-{:s}".format(generate_random_string(5)) pe = PE.Binary(basename, PE.PE_TYPE.PE32) # adding sections sections = {} reladdr = 0x1000 for mem in memory_layout: name, base_address, size, permission = mem.name, mem.address, mem.size, mem.permission if name in (".stack", ): continue sect = PE.Section(name) if name == ".text": # .text section: copy our code and set the entrypoint to the # beginning VA sect.content = asm_code sect.virtual_address = reladdr sect.characteristics = parse_as_lief_pe_permission( permission, "code") sections["text"] = pe.add_section(sect, PE.SECTION_TYPES.TEXT) elif name == ".data": # .data is also sure to exist sect.content = b"\x00" sect.virtual_address = reladdr sect.characteristics = parse_as_lief_pe_permission( permission, "udata") sections["data"] = pe.add_section(sect, PE.SECTION_TYPES.DATA) reladdr += size # fixing pe header pe.header.add_characteristic(PE.HEADER_CHARACTERISTICS.EXECUTABLE_IMAGE) pe.header.add_characteristic(PE.HEADER_CHARACTERISTICS.DEBUG_STRIPPED) if is_x64: pe.header.add_characteristic( PE.HEADER_CHARACTERISTICS.LARGE_ADDRESS_AWARE) else: pe.header.add_characteristic( PE.HEADER_CHARACTERISTICS.CHARA_32BIT_MACHINE) # fixing pe optional header pe.optional_header.addressof_entrypoint = sections["text"].virtual_address pe.optional_header.major_operating_system_version = 0x04 pe.optional_header.minor_operating_system_version = 0x00 pe.optional_header.major_subsystem_version = 0x05 pe.optional_header.minor_subsystem_version = 0x02 pe.optional_header.major_linker_version = 0x02 pe.optional_header.minor_linker_version = 0x1e pe.optional_header.remove(PE.DLL_CHARACTERISTICS.NX_COMPAT) pe.optional_header.add(PE.DLL_CHARACTERISTICS.NO_SEH) # pe.add_library("ntdll.dll") #building exe to disk outfile = f"{tempfile.gettempdir()}{os.path.sep:s}{basename:s}.exe" builder = PE.Builder(pe) builder.build_imports(True) builder.build() builder.write(outfile) return outfile
def main(): optparser = OptionParser(usage='Usage: %prog [options] <pe-file>', add_help_option=True, prog=sys.argv[0]) optparser.add_option('-a', '--all', action='store_true', dest='show_all', help='Show all informations') optparser.add_option('-d', '--data-directories', action='store_true', dest='show_data_directories', help='Display data directories') optparser.add_option('--debug', action='store_true', dest='show_debug', help='Display debug directory') optparser.add_option('-g', '--signature', action='store_true', dest='show_signature', help="Display the binary's signature if any") optparser.add_option('-H', '--header', action='store_true', dest='show_headers', help='Display headers') optparser.add_option('-i', '--import', action='store_true', dest='show_imports', help='Display imported functions and libraries') optparser.add_option( '--resolve-ordinals', action='store_true', dest='resolve_ordinals', help= "When used with --import, it attempts to resolve names of ordinal imports" ) optparser.add_option('-r', '--relocs', action='store_true', dest='show_relocs', help='Display the relocations (if present)') optparser.add_option('-R', '--rich-header', action='store_true', dest='show_richheader', help='Display the Rich Header') optparser.add_option('--resources', '--rsrc', action='store_true', dest='show_resources', help='Display the resources (if present)') optparser.add_option('-S', '--section-headers', '--sections', action='store_true', dest='show_section_header', help="Display the sections' headers") optparser.add_option('-s', '--symbols', '--syms', action='store_true', dest='show_symbols', help='Display symbols') optparser.add_option('-t', '--tls', action='store_true', dest='show_tls', help='Display TLS informations') optparser.add_option('-x', '--export', action='store_true', dest='show_export', help='Display exported functions/libraries') optparser.add_option('--load-config', action='store_true', dest='show_loadconfig', help='Display load configuration') optparser.add_option('--ctor', action='store_true', dest='show_ctor', help='Constructor functions') optparser.add_option('-f', '--functions', action='store_true', dest='show_functions', help='Display all functions found in the binary') optparser.add_option( '--exception-functions', action='store_true', dest='show_pfunctions', help='Display functions found in the exception directory') options, args = optparser.parse_args() if len(args) == 0: optparser.print_help() sys.exit(1) binary = None try: binary = PE.parse(args[0]) except lief.exception as e: print(e) sys.exit(1) print_information(binary) if options.show_data_directories or options.show_all: print_data_directories(binary) if options.show_headers or options.show_all: print_header(binary) if (options.show_imports or options.show_all) and binary.has_imports: print_imports(binary, resolve=options.resolve_ordinals) if (options.show_relocs or options.show_all) and binary.has_relocations: print_relocations(binary) if options.show_section_header or options.show_all: print_sections(binary) if options.show_symbols or options.show_all: print_symbols(binary) if (options.show_tls or options.show_all) and binary.has_tls: print_tls(binary) if (options.show_export or options.show_all) and binary.has_exports: print_export(binary) if (options.show_debug or options.show_all) and binary.has_debug: print_debug(binary) if (options.show_signature or options.show_all) and binary.has_signature: print_signature(binary) if (options.show_richheader or options.show_all) and binary.has_rich_header: print_rich_header(binary) if (options.show_resources or options.show_all) and binary.has_resources: print_resources(binary) if (options.show_loadconfig or options.show_all) and binary.has_configuration: print_load_configuration(binary) if options.show_ctor or options.show_all: print_ctor(binary) if options.show_functions or options.show_all: print_functions(binary) if options.show_pfunctions or options.show_all: print_exception_functions(binary)