mirror of
https://github.com/dobin/SuperMega
synced 2026-06-03 01:27:11 +00:00
feature: data reuse (tmp, to fix)
This commit is contained in:
+14
-1
@@ -8,6 +8,7 @@ from config import config
|
||||
from observer import observer
|
||||
from model import *
|
||||
from phases.masmshc import process_file, Params
|
||||
from phases.datareuse import *
|
||||
|
||||
logger = logging.getLogger("Compiler")
|
||||
use_templates = True
|
||||
@@ -35,6 +36,15 @@ def compile(
|
||||
file_to_lf(asm_out)
|
||||
observer.add_text("carrier_asm_orig", file_readall_text(asm_out))
|
||||
|
||||
# DataReuse first
|
||||
asmFileParser = AsmFileParser(asm_out)
|
||||
asmFileParser.init()
|
||||
data_fixups = asmFileParser.fixup_data_reuse()
|
||||
data_fixup_entries = asmFileParser.get_data_reuse_entries()
|
||||
config.data_fixups = data_fixups
|
||||
config.data_fixup_entries = data_fixup_entries
|
||||
asmFileParser.write_lines_to(asm_out)
|
||||
|
||||
# Assembly text fixup (SuperMega)
|
||||
logger.info("---[ ASM Fixup : {} ".format(asm_out))
|
||||
if not fixup_asm_file(asm_out, payload_len, short_call_patching=short_call_patching):
|
||||
@@ -47,7 +57,10 @@ def compile(
|
||||
asm_clean_file = asm_out + ".clean"
|
||||
logger.info("---[ ASM masm_shc: {} ".format(asm_out))
|
||||
if True:
|
||||
params = Params(asm_out, asm_clean_file, True, True, True)
|
||||
params = Params(asm_out, asm_clean_file,
|
||||
inline_strings=False, # not for DATA_REUSE
|
||||
remove_crt=True,
|
||||
append_rsp_stub=True) # required atm
|
||||
process_file(params)
|
||||
else:
|
||||
run_process_checkret([
|
||||
|
||||
+99
-1
@@ -2,6 +2,7 @@ import sys
|
||||
import pefile
|
||||
from intervaltree import Interval, IntervalTree
|
||||
from typing import List
|
||||
import os
|
||||
|
||||
|
||||
class PeSection():
|
||||
@@ -22,6 +23,93 @@ class PeRelocation():
|
||||
self.type: str = pefile.RELOCATION_TYPE[reloc.type][0]
|
||||
|
||||
|
||||
def bytes_to_asm_db(byte_data: bytes) -> bytes:
|
||||
# Convert each byte to a string in hexadecimal format
|
||||
# prefixed with '0' and suffixed with 'h'
|
||||
hex_values = [f"0{byte:02x}H" for byte in byte_data]
|
||||
formatted_string = ', '.join(hex_values)
|
||||
return "\tDB " + formatted_string
|
||||
|
||||
|
||||
class AsmFileParser():
|
||||
def __init__(self, filepath):
|
||||
self.filepath = filepath
|
||||
self.lines = []
|
||||
|
||||
|
||||
def init(self):
|
||||
with open(self.filepath, "r") as f:
|
||||
self.lines = f.readlines()
|
||||
self.lines = [line.rstrip() for line in self.lines]
|
||||
|
||||
|
||||
def fixup_data_reuse(self):
|
||||
fixups = []
|
||||
# lea rcx, OFFSET FLAT:$SG72513
|
||||
for idx, line in enumerate(self.lines):
|
||||
if "OFFSET FLAT:$SG" in line:
|
||||
string_ref = line.split("OFFSET FLAT:")[1]
|
||||
register = line.split("lea\t")[1].split(",")[0]
|
||||
randbytes: bytes = os.urandom(7) # lea is 7 bytes
|
||||
fixups.append({
|
||||
"string_ref": string_ref,
|
||||
"register": register,
|
||||
"randbytes": randbytes,
|
||||
})
|
||||
self.lines[idx] = bytes_to_asm_db(randbytes) + " ; .rdata Reuse for {} ({})".format(
|
||||
string_ref, register)
|
||||
return fixups
|
||||
|
||||
|
||||
def get_data_reuse_entries(self) -> List[str]:
|
||||
entries = {}
|
||||
current_entry_name = ""
|
||||
|
||||
for line in self.lines:
|
||||
# $SG72513 DB 'U', 00H, 'S', 00H, 'E', 00H, 'R', 00H, 'P', 00H, 'R', 00H
|
||||
# DB 'O', 00H, 'F', 00H, 'I', 00H, 'L', 00H, 'E', 00H, 00H, 00H
|
||||
if line.startswith("$SG"):
|
||||
parts = line.split()
|
||||
name = parts[0]
|
||||
current_entry_name = name
|
||||
value = b''
|
||||
for part in parts:
|
||||
if part.startswith('\''):
|
||||
value += str.encode(part.split('\'')[1])
|
||||
elif part.endswith('H') or part.endswith('H,'):
|
||||
hex = part.split('H')[0]
|
||||
value += bytes.fromhex(hex)
|
||||
entries[name] = value
|
||||
|
||||
elif line.startswith("\tDB"):
|
||||
if current_entry_name == "":
|
||||
continue
|
||||
value = b''
|
||||
parts = line.split()
|
||||
for part in parts:
|
||||
if part.startswith('\''):
|
||||
value += str.encode(part.split('\'')[1])
|
||||
elif part.endswith('H') or part.endswith('H,'):
|
||||
hex = part.split('H')[0]
|
||||
if len(hex) == 3:
|
||||
hex = hex.lstrip('0')
|
||||
#print("--> {}".format(line))
|
||||
#print("---> {}".format(hex))
|
||||
value += bytes.fromhex(hex)
|
||||
|
||||
entries[current_entry_name] += value
|
||||
else:
|
||||
current_entry_name = ""
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def write_lines_to(self, filename):
|
||||
with open(filename, 'w',) as asmfile:
|
||||
for line in self.lines:
|
||||
asmfile.write(line + "\n")
|
||||
|
||||
|
||||
class DataReuser():
|
||||
def __init__(self, filepath):
|
||||
self.pe = pefile.PE(filepath)
|
||||
@@ -40,6 +128,8 @@ class DataReuser():
|
||||
for entry in base_reloc.entries:
|
||||
self.base_relocs.append(PeRelocation(entry))
|
||||
|
||||
#self.pe.close()
|
||||
|
||||
|
||||
def get_section_by_name(self, name: str) -> PeSection:
|
||||
for section in self.pe_sections:
|
||||
@@ -59,13 +149,21 @@ class DataReuser():
|
||||
return []
|
||||
return [reloc for reloc in self.base_relocs if reloc.base_rva == section.virt_addr]
|
||||
|
||||
|
||||
|
||||
def get_reloc_largest_gap(self, section_name=".rdata"):
|
||||
tree = IntervalTree()
|
||||
section = self.get_section_by_name(section_name)
|
||||
|
||||
#print("MOTHERFUCKER: {}".format(section))
|
||||
#print("MOTHERFUCKER: {}".format(self.base_relocs))
|
||||
print("-- Relocations: {}".format(len(self.base_relocs)))
|
||||
print("-- section: 0x{:x}".format(section.virt_addr))
|
||||
|
||||
for reloc in self.base_relocs:
|
||||
#print("FUCK: 0x{:x} 0x{:x}".format(reloc.base_rva, section.virt_addr))
|
||||
|
||||
if reloc.base_rva == section.virt_addr:
|
||||
print("Adding reloc: {} {}".format(reloc.offset, reloc.offset + 8))
|
||||
tree.add(Interval(reloc.offset, reloc.offset + 8))
|
||||
tree.add(Interval(section.virt_size, section.virt_size + 1))
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ from model import *
|
||||
from observer import observer
|
||||
from helper import rbrunmode_str
|
||||
from derbackdoorer.derbackdoorer import PeBackdoor
|
||||
from phases.datareuse import DataReuser
|
||||
|
||||
|
||||
logger = logging.getLogger("Injector")
|
||||
|
||||
@@ -65,6 +67,7 @@ def injected_fix_iat(exe_out: FilePath, exe_info: ExeInfo):
|
||||
|
||||
off = code.index(cap.id)
|
||||
current_address = off + exe_info.image_base + exe_info.code_virtaddr
|
||||
#current_address += 2
|
||||
destination_address = cap.addr
|
||||
logger.info(" Replace at 0x{:x} with call to 0x{:x}".format(
|
||||
current_address, destination_address
|
||||
@@ -78,6 +81,65 @@ def injected_fix_iat(exe_out: FilePath, exe_info: ExeInfo):
|
||||
write_code_section(exe_file=exe_out, new_data=code)
|
||||
|
||||
|
||||
def injected_fix_data(exe_path, data_fixups, data_fixup_entries, exe_info):
|
||||
data_reuser = DataReuser(exe_path)
|
||||
data_reuser.init()
|
||||
#ret = data_reuser.get_reloc_largest_gap(".rdata")
|
||||
#size = ret[0]
|
||||
#start = ret[1]
|
||||
#stop = ret[2]
|
||||
#print("GAP: {} {} {}".format(size, start, stop))
|
||||
#addr = start
|
||||
|
||||
# Insert my data into the .rdata section
|
||||
sect = data_reuser.get_section_by_name(".rdata")
|
||||
addr = sect.raw_addr + 0x1AB0 #+ 0x1000
|
||||
#addr += 0x100
|
||||
#addr = 0
|
||||
print("Write into .data:".format())
|
||||
data_reuser.pe.close()
|
||||
|
||||
with open(exe_path, "r+b") as f:
|
||||
for fixup in data_fixups:
|
||||
var_data = data_fixup_entries[fixup["string_ref"]]
|
||||
|
||||
print(" Addr: {} / 0x{:X} Data: {}".format(
|
||||
addr, addr, len(var_data)))
|
||||
|
||||
# Overwrite data in the .rdata section with ours
|
||||
#data_reuser.pe.set_bytes_at_offset(addr, var_data)
|
||||
f.seek(addr)
|
||||
f.write(var_data)
|
||||
#f.write(b"AAAAAAAAAAAAAAAAAAAAAAAAAAA")
|
||||
print("ADD: 0x{:X} 0x{:X} 0x{:X}".format(addr, sect.virt_addr, exe_info.image_base))
|
||||
fixup["addr"] = addr + sect.virt_addr + exe_info.image_base - sect.raw_addr
|
||||
addr += len(var_data) + 8
|
||||
#data_reuser.pe.write(exe_path + ".tmp")
|
||||
#data_reuser.pe.close()
|
||||
#shutil.move(exe_path + ".tmp", exe_path)
|
||||
|
||||
# patch code section
|
||||
code = extract_code_from_exe(exe_path)
|
||||
for fixup in data_fixups:
|
||||
if not fixup["randbytes"] in code:
|
||||
raise Exception("DataResuse: ID {} not found, abort".format(fixup["randbytes"]))
|
||||
|
||||
off = code.index(fixup["randbytes"])
|
||||
current_address = off + exe_info.image_base + exe_info.code_virtaddr
|
||||
destination_address = fixup["addr"]
|
||||
logger.info(" Replace at 0x{:x} with call to 0x{:x}".format(
|
||||
current_address, destination_address
|
||||
))
|
||||
lea = assemble_lea(
|
||||
current_address, destination_address, fixup["register"]
|
||||
)
|
||||
code = code.replace(fixup["randbytes"], lea)
|
||||
|
||||
# write back our patched code into the exe
|
||||
write_code_section(exe_file=exe_path, new_data=code)
|
||||
|
||||
|
||||
|
||||
def verify_injected_exe(exefile: FilePath) -> int:
|
||||
logger.info("---[ Verify infected exe: {} ".format(exefile))
|
||||
# remove indicator file
|
||||
|
||||
Reference in New Issue
Block a user