def decompile(func): global decompiler if decompiler is None: decompiler = DecompInterface() decompiler.openProgram(currentProgram) results = decompiler.decompileFunction(func, 10, TaskMonitor.DUMMY) return results
def get_decompile_interface(): # type: () -> DecompInterface interface = DecompInterface() options = DecompileOptions() interface.setOptions(options) interface.openProgram(currentProgram) interface.setSimplificationStyle("decompile") return interface
def renameFunctionsBasedOnstringRefrencesUsingTheDecompiler(): monitor.setMessage("Rename Functions Based on string refrences ") function = getFirstFunction() decompinterface = DecompInterface() decompinterface.openProgram(currentProgram) uniqueList = [] while function is not None and not monitor.isCancelled(): try: tokengrp = decompinterface.decompileFunction(function, 0, ConsoleTaskMonitor()) code = tokengrp.getDecompiledFunction().getC() pattern1 = r"\"[a-zA-Z0-9 .,\-\*\/\[\]\{\}\!\@\#\$\%\^\&\(\)\=\~\:\"\'\\\+\?\>\<\`\_\;]+\"" pattern2 = r'[ .,\-\*\/\[\]\{\}\!\@\#\$\%\^\&\(\)\=\~\:\"\'\\\+\?\>\<\`]+' stringList = re.findall(pattern1,code) if not stringList == []: for unique in stringList: if unique not in uniqueList: uniqueList.append(unique) name = re.sub(pattern2,"","_".join(uniqueList)) if len(name) > 15: name = name[:15] functionName = "rep_s_fun_" + str(function.getEntryPoint()) + "_" + name print functionName function.setName(functionName,USER_DEFINED) except: pass function = getFunctionAfter(function) return 0
def get_hfunction(self): decomplib = DecompInterface() decomplib.openProgram(currentProgram) timeout = self.timeout dRes = decomplib.decompileFunction(self.function, timeout, getMonitor()) hfunction = dRes.getHighFunction() return hfunction
def get_high_function(func): options = DecompileOptions() monitor = ConsoleTaskMonitor() ifc = DecompInterface() ifc.setOptions(options) ifc.openProgram(getCurrentProgram()) res = ifc.decompileFunction(func, 60, monitor) return res.getHighFunction()
def get_high_function(current_program, current_address): decomplib = DecompInterface() decomplib.openProgram(current_program) current_function = getFunctionContaining(current_address) decompile_res = decomplib.decompileFunction(current_function, 30, getMonitor()) high_function = decompile_res.getHighFunction() return high_function
def decompile_func(func): decompiler = DecompInterface() decompiler.openProgram(currentProgram) results = decompiler.decompileFunction(func, 0, monitor) if not results.decompileCompleted(): raise RuntimeError('failed to decompile function: {}'.format(func)) high_func = results.getHighFunction() return high_func
def initEmulator(self, program, address, clear_param_map=True): ''' Setup the emulator helper, symbol maps and fn related stuff ''' self.program = program self.function = self.program.getFunctionManager().getFunctionContaining(address) if self.function is None: function_name = self.plugin.askString("You are not in a function, please enter an address or a function name", "address or symbol name") for f in self.plugin.state.currentProgram.getFunctionManager().getFunctions(True): if function == f.getName(): self.plugin.state.setCurrentAddress(function.getEntryPoint()) self.doStart() return for f in self.plugin.state.currentProgram.getFunctionManager().getFunctions(True): if int(function, 16) == f.getEntryPoint().getOffset(): self.plugin.state.setCurrentAddress(function.getEntryPoint()) self.doStart() return self.entrypoint = self.program.getListing().getInstructionAt(self.function.getEntryPoint()) self.logger.info("Program: %s" % self.program) self.logger.info("Function: %s" % self.function) self.decompinterface = DecompInterface() self.decompinterface.openProgram(program) result = self.decompinterface.decompileFunction(self.function, 0, self.monitor) self.highFunction = result.getHighFunction() # self.logger.info(result) # self.logger.info(self.highFunction) self.decompiled = str(result.getCCodeMarkup()) # self.logger.info("Decompiled: %s" % self.decompiled) self.symbolMap = self.highFunction.getLocalSymbolMap() # self.logger.info(self.symbolMap) if clear_param_map: self.parameterMap = {} # fuzz = 0 self.emulatorHelper = EmulatorHelper(self.program) self.stackPointer = (((1 << (self.emulatorHelper.getStackPointerRegister().getBitLength() - 1)) - 1) ^ ((1 << (self.emulatorHelper.getStackPointerRegister().getBitLength()//2))-1)) self.returnAddressSize = program.getLanguage().getProgramCounter().getBitLength() NULL_PTR_RET = 0 self.emulatorHelper.writeRegister(self.emulatorHelper.getStackPointerRegister(), self.stackPointer) self.emulatorHelper.setBreakpoint(self.getStackAddress(NULL_PTR_RET)) self.emulatorHelper.enableMemoryWriteTracking(True) self.emulator_state = EmulatorState.WAITING_FOR_PARAM if not clear_param_map: self.emulator_state = EmulatorState.READY self.history = [] self.lastAddresses = [] # self.emulatorHelper.getEmulator().executeInstruction = executeInstruction self.hookExternalFunctions()
def colorize_blocks(self): global FINAL_MATCH_DICT global TABLE_DIALOG decompInterface = DecompInterface() decompInterface.openProgram(currentProgram) cov_block_list = [] for bb in self.basic_blocks.keys(): start_addr = toAddr(bb + self.program_base) block_size = self.basic_blocks[bb] - 1 function = getFunctionContaining(start_addr) self.set_basic_block_colors(start_addr, block_size) if function and not function in cov_block_list: cov_block_list.append(function) for function in cov_block_list: hfunction = decompInterface.decompileFunction( function, 30, TaskMonitor.DUMMY).getHighFunction() basic_blocks = hfunction.getBasicBlocks() basic_block_len = len(basic_blocks) total_block_size = 0 function_size = 0 total_cov_size = 0 for block in basic_blocks: block_size = int(block.getStop().toString(), 16) - int( block.getStart().toString(), 16) function_size += block_size bg_color = service.getBackgroundColor(block.getStart()) if bg_color and bg_color.getRGB() == -16711764: total_block_size += 1 total_cov_size += block_size block_hit = str(total_block_size) + "/" + str(basic_block_len) if total_cov_size > 0: total_cov_size = str( int(100 * float(total_cov_size) / float(function_size))) + "%" elif total_block_size == basic_block_len: total_cov_size = "100%" else: total_cov_size = "0%" FINAL_MATCH_DICT[function.getName()] = [ function.getName(), total_cov_size, block_hit, function.getEntryPoint() ] for key in FINAL_MATCH_DICT.keys(): init_obj = Initializer() init_obj.head = key init_obj.function_address = FINAL_MATCH_DICT[key][3] FINAL_MATCH_DICT[key].append(init_obj) TABLE_DIALOG.add(init_obj)
def get_decompilation(calle_addr, func_name): program = getCurrentProgram() ifc = DecompInterface() ifc.openProgram(program) # here we assume there is only one function named `main` function = getGlobalFunctions(func_name)[0] # decompile the function and print the pseudo C results = ifc.decompileFunction(function, 0, ConsoleTaskMonitor()) print(results.getDecompiledFunction().getC()) return results.getDecompiledFunction().getC()
def _decompile(): decompiler = DecompInterface() decompiler.openProgram(currentProgram) de_c = "" funcs = currentProgram.getListing().getFunctions(True) for func in funcs: decompiled_func = _decompile_func(decompiler, func) if decompiled_func: de_c += decompiled_func return de_c
def __init__(self, program=None, timeout=None): '''init Decompiler class. Args: program (ghidra.program.model.listing.Program): target program to decompile, default is `currentProgram`. timeout (ghidra.util.task.TaskMonitor): timeout for DecompInterface::decompileFunction ''' # initialize decompiler with current program self._decompiler = DecompInterface() self._decompiler.openProgram(program or ghidra_app.currentProgram) self._timeout = timeout
def _decompiler(): ifc = DecompInterface() DecOptions = DecompileOptions() service = state.getTool().getService(OptionsService) opt = service.getOptions("Decompiler") DecOptions.grabFromToolAndProgram(None, opt, currentProgram) ifc.setOptions(DecOptions) ifc.toggleCCode(True) ifc.toggleSyntaxTree(True) ifc.setSimplificationStyle("decompile") ifc.openProgram(currentProgram) return ifc
def get_decompiler(state, program): tool = state.getTool() options = DecompileOptions() decomp = DecompInterface() if tool is not None: service = tool.getService(OptionsService) if service is not None: opt = service.getOptions("Decompiler") options.grabFromToolAndProgram(None, opt, program) decomp.setOptions(options) decomp.toggleCCode(True) decomp.toggleSyntaxTree(True) decomp.setSimplificationStyle("decompile") return decomp
def generate_decomp_interface(): decompiler = DecompInterface() opts = DecompileOptions() opts.grabFromProgram(curr) decompiler.setOptions(opts) decompiler.toggleCCode(True) decompiler.toggleSyntaxTree(True) # - decompile -- The main decompiler action # - normalize -- Decompilation tuned for normalization # - jumptable -- Simplify just enough to recover a jump-table # - paramid -- Simplify enough to recover function parameters # - register -- Perform one analysis pass on registers, without stack variables # - firstpass -- Construct the initial raw syntax tree, with no simplification decompiler.setSimplificationStyle("decompile") decompiler.openProgram(curr) return decompiler
def stub(address): functionOffset = function.getEntryPoint().getOffset() while functionOffset not in function_arguments_cache and not monitor.isCancelled(): # program = currentProgram # function = currentProgram.getFunctionManager().getFunctionContaining(currentAddress) decompinterface = DecompInterface() decompinterface.openProgram(program) result = decompinterface.decompileFunction(function, 0, monitor) highFunction = result.getHighFunction() if not result.isCancelled() and not result.isTimedOut(): function_arguments_cache[functionOffset] = highFunction assert(functionOffset in function_arguments_cache) highFunction = function_arguments_cache[functionOffset] symbolMap = highFunction.getLocalSymbolMap() args = [] for parameter in [symbolMap.getParam(i) for i in range(symbolMap.getNumParams())]: emulator.logger.debug("Found parameter `%s` with size `%d` with type `%s`" % (parameter.getName(), parameter.getSize(), str(parameter.getDataType()))) param = getParam(parameter, emulator, monitor) args.append(param) emulator.logger.debug(str(args)) retval = func(*args) emulator.logger.debug('Finish execution of hook %s with return value %s' % (func.__name__, repr(retval))) pointerSize = emulator.program.getLanguage().getProgramCounter().getBitLength()//8 if type(retval) == int or type(retval) == long: retval = long_to_bytes(retval, pointerSize) if not emulator.program.getLanguage().isBigEndian(): retval = retval[::-1] offset = 0 for varnode in function.getReturn().getVariableStorage().getVarnodes(): emulator.emulatorHelper.writeMemory(varnode.getAddress(), retval[offset:offset+varnode.getSize()]) offset += varnode.getSize() emulator.logger.debug('Finish execution of hook %s we were at %s before' % (func.__name__, str(emulator.lastAddresses))) current = emulator.emulatorHelper.getExecutionAddress() for address in emulator.lastAddresses: emulator.logger.debug('Checking if %s is different from %s' % (address, current)) if str(address) != str(current): nextAddress = emulator.flatapi.getInstructionAfter(address).getAddress() emulator.logger.debug('I propose to go to %s now' % (str(nextAddress))) emulator.emulatorHelper.getEmulator().setExecuteAddress(nextAddress.getOffset()) emulator.logger.debug('Can you believe that we are at %s now?' % (str(emulator.emulatorHelper.getExecutionAddress()))) break return True
def prepare(self): Decompiler = DecompInterface() Decompiler.openProgram(currentProgram) Decompiled_Func = Decompiler.decompileFunction(self.function, 30, getMonitor()) self.highfunction = Decompiled_Func.getHighFunction()
# Verify the '.text' section is loaded assert ('.text' in [b.name for b in getMemoryBlocks()]) # Verify the entry point has been marked entry = None for f in currentProgram.getFunctionManager().getFunctions(True): if f.name == 'entry': entry = f break assert (entry is not None) # Attempt to decompile the entry point function from ghidra.app.decompiler import DecompInterface di = DecompInterface() di.openProgram(currentProgram) print(di.decompileFunction(entry, 0, None).getDecompiledFunction().getC()) # Ghidra silently swallows exceptions, so create a file at the end of the test # to mark success open('TEST_PASS', 'w').write('pass')
#@author Magnus "Nopey" Larsen #@category #@keybinding #@menupath Tools.Misc.Populate empty structs #@toolbar import re #gex from ghidra.util.task import ConsoleTaskMonitor from ghidra.app.decompiler import DecompileOptions, DecompInterface from ghidra.program.model.data import PointerDataType, Pointer from ghidra.program.database.data import StructureDB program = getCurrentProgram() dataManager = program.getDataTypeManager() # We use the decompiler to find accesses to fields. ifc = DecompInterface() ifc.openProgram(program) fm = program.getFunctionManager() # all_datatypes is just a way of skipping the paths from the DataTypeManager all_datatypes = dict() for d in dataManager.getAllDataTypes(): all_datatypes[d.getName()] = d all_datatypes["code"] = all_datatypes["void"] def getAddress(offset): return program.getAddressFactory().getDefaultAddressSpace().getAddress( offset)
def open_program(): iface = DecompInterface() iface.openProgram(currentProgram) return iface
def fixUndefinedDataTypes(): monitor.setMessage("Fixing Undefined Data Types") function = getFirstFunction() decompinterface = DecompInterface() decompinterface.openProgram(currentProgram) # get var list from decompilation while function is not None: prt = False varList = [] try: tokengrp = decompinterface.decompileFunction(function, 0, ConsoleTaskMonitor()) code = tokengrp.getDecompiledFunction().getC() for line in code.split("\n"): if line == " \r": break if prt: varList.append(filter(None,line.split(";")[0].split(" "))) if line.startswith("{"): prt = True except: pass for var in function.getAllVariables(): varMsg = str(var) dt = str(var.getDataType()) inx = 0 if "undefined" in dt: for decVar in varList: if len(decVar) > 1: arr = False if len(decVar) == 3: arr = True inx = int(decVar[2].split("[")[1].split("]")[0]) if decVar[1].replace("*","") == var.getName(): if not "undefined" in decVar[0]: if '*' in decVar[1]: dt = getDataType("/" + decVar[0] + " " + ('*' * decVar[1].count("*")),arr,inx) else: dt = getDataType("/" + decVar[0],arr,inx) else: if '*' in decVar[1]: dtlen = decVar[0].replace("undefined","") if dtlen == "": dtlen = "1" dt = getDataTypeWrap(dtlen + ('*' * decVar[1].count("*")),arr,inx) else: dt = getDataTypeWrap(decVar[0],arr,inx) if type(dt) == str: dt = str(var.getDataType()) dt = dt.replace("undefined","") dt = getDataTypeWrap(dt) if dt: try: var.setDataType(dt,USER_DEFINED) print "[+] " + str(function.getName()) + ": " + varMsg + " -> " + str(dt) except: pass function = getFunctionAfter(function) return 0
from ghidra.program.model.pcode import PcodeOp from ghidra.program.model.symbol import SourceType from ghidra.program.model.listing.Function import FunctionUpdateType from ghidra.app.util.cparser.C import CParserUtils from ghidra.program.model.listing import ReturnParameterImpl from ghidra.program.model.listing import ParameterImpl TL_APIS = {} MAX_TL_API = 0xC2 DR_APIS = {} MAX_DR_API = 0x3D blockModel = BasicBlockModel(currentProgram) functionManager = currentProgram.getFunctionManager() decompInterface = DecompInterface() decompInterface.openProgram(currentProgram) def load_api_names_types(): curdir = os.path.dirname(os.path.abspath(inspect.getsourcefile(lambda: 0))) with open(os.path.join(curdir, 'tl_apis.json'), 'r') as f: TL_APIS.update({i: (n, t) for i, n, t in json.loads(f.read())}) print("[*] Loaded %s trustlets APIs names" % len(TL_APIS)) global DR_APIS with open(os.path.join(curdir, 'dr_apis.json'), 'r') as f: DR_APIS.update({i: (n, t) for i, n, t in json.loads(f.read())}) print("[*] Loaded %s drivers APIs names" % len(DR_APIS))
while rem > 0: data = sock.recv(rem) rem = rem - len(data) return data def wr(sock, data): sz = len(data) i = 0 while i < sz: s = sock.send(data[i:]) i = i + s fm = currentProgram.getFunctionManager() decompiler = DecompInterface() decompiler.openProgram(currentProgram) serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(("localhost", 14444)) serversocket.listen(1) while True: try: (sock, address) = serversocket.accept() while True: addr_req = rd(sock, 8) fixed_addr = struct.unpack("<Q", addr_req)[0] addr_obj = getAddress(fixed_addr) func = fm.getFunctionContaining(addr_obj) status = decompiler.decompileFunction(func, 0, None)