将二进制文件转为C风格shellcode的Python代码

代码

#!/usr/bin/env python
# encoding: utf-8

import os
import binascii
from datetime import datetime, timezone

colnum_per_row = 16
file_path = 'demo.sys'
output_path = 'demo_shellcode.h'
array_name = 'demo_shellcode'
xor_key = 0xd8

def exe_to_c_array(file_path, array_name):
    with open(file_path, 'rb') as file:
        binary_data = file.read()
    
    # Encrypt binary data
    binary_data = bytes( byte ^ xor_key for i, byte in enumerate(binary_data) )

    hex_data = binascii.hexlify(binary_data).decode()
    c_array = "const unsigned char {}[] = \n".format(array_name)

    row = "\""
    for i in range(2, len(hex_data) + 2, 2):
        # print(i, len(hex_data), hex_data[i-2], hex_data[i-1])
        row += "\\x" + hex_data[i-2] + hex_data[i-1]

        if i % (colnum_per_row * 2) == 0 or i >= len(hex_data):
            row += "\""
            if i + 2 < len(hex_data):
                row += "\n"

            c_array += row
            row = "\""

    c_array += ";";
    
    return c_array

if __name__ == '__main__':
    # print(exe_to_c_array(file_path, array_name))
    with open(output_path, 'w', encoding='utf-8') as f:
        utc_time = datetime.now(timezone.utc)
        format_time = utc_time.strftime("%Y-%m-%d %H:%M:%S")

        f.write('// Generate UTC Time: {}\n'.format(format_time))
        f.write('// Source File: {}\n\n'.format(os.path.basename(file_path)))
        f.write('// clang-format off\n\n')
        f.write('const unsigned char xor_key = 0x{:x};\n\n'.format(xor_key))
        f.write(exe_to_c_array(file_path, array_name))
        f.write('\n\n// clang-format on\n')
posted @ 2025-03-20 00:54  倚剑问天  阅读(22)  评论(0)    收藏  举报