• caglararli@hotmail.com
  • 05386281520

How to embed a PE file to another PE files

Çağlar Arlı      -    14 Views

How to embed a PE file to another PE files

So what I want to do basically is what BDFproxy does on the go, I want to modify a file (on the disk) to embed another PE in it and have both working, it does not matter if they work concurrently or when the main program finishes the embedded program works I just want to embed them in any way possible and if the Metasploit framework (peinjector post exploitation module) and BDFproxy can do that it is not impossible

I tried to write a python script to try and do that however when I run the outputted file it says this app cannot run on your pc here is the script:

import pefile

def embed_pe(main_exe_path, embedded_exe_path):
    # Load the main executable
    main_pe = pefile.PE(main_exe_path)

    # Load the embedded executable
    embedded_pe = pefile.PE(embedded_exe_path)

    # Create a new section in the main executable for the embedded executable
    name = ".embedded"
    virtual_size = len(embedded_pe.__data__)
    raw_size = virtual_size
    characteristics = 0xE0000020 # READ | WRITE | EXECUTE | CODE

    # Calculate the virtual offset and raw offset
    number_of_section = main_pe.FILE_HEADER.NumberOfSections
    last_section = number_of_section - 1
    virtual_offset = main_pe.sections[last_section].VirtualAddress + main_pe.sections[last_section].Misc_VirtualSize
    raw_offset = main_pe.sections[last_section].PointerToRawData + main_pe.sections[last_section].SizeOfRawData

    # Create a new section header
    new_section_header = pefile.SectionStructure(main_pe.__IMAGE_SECTION_HEADER_format__, pe=main_pe)
    new_section_header.Name = name.encode()
    new_section_header.Misc_VirtualSize = virtual_size
    new_section_header.VirtualSize = virtual_size
    new_section_header.SizeOfRawData = raw_size
    new_section_header.PointerToRawData = raw_offset
    new_section_header.VirtualAddress = virtual_offset
    new_section_header.Characteristics = characteristics

    # Add the new section header to the list of sections
    main_pe.sections.append(new_section_header)

    # Modify the main headers
    main_pe.FILE_HEADER.NumberOfSections += 1
    main_pe.OPTIONAL_HEADER.SizeOfImage += raw_size
    main_pe.OPTIONAL_HEADER.AddressOfEntryPoint = virtual_offset

    # Embed the embedded executable into the new section
    main_pe.__data__ = main_pe.__data__[:raw_offset] + embedded_pe.__data__ + main_pe.__data__[raw_offset:]

    # Save the modified main executable
    print(main_exe_path)
    main_pe.write("modified_"+main_exe_path)

# Usage
embed_pe("cygwin.exe", "message.exe")

So what is the way to achieve my goal and if there is what am I doing wrong in my Python script