def process(start_at = MAKE_SIG_AT['fn']): fm = currentProgram.getFunctionManager() fn = fm.getFunctionContaining(currentAddress) cm = currentProgram.getCodeManager() if start_at == MAKE_SIG_AT['fn']: ins = cm.getInstructionAt(fn.getEntryPoint()) elif start_at == MAKE_SIG_AT['cursor']: ins = cm.getInstructionContaining(currentAddress) if not ins: raise Exception("Could not find entry point to function") pattern = "" # contains pattern string (supports regular expressions) byte_pattern = [] # contains BytePattern instances # keep track of our matches matches = [] match_limit = 128 while fm.getFunctionContaining(ins.getAddress()) == fn: for entry in getMaskedInstruction(ins): byte_pattern.append(entry) if entry.is_wildcard: pattern += '.' else: pattern += r'\x{:02x}'.format(entry.byte) expected_next = ins.getAddress().add(ins.length) ins = ins.getNext() if ins.getAddress() != expected_next: # we don't have a good way to deal with alignment bytes # raise an exception for now raise Exception("Instruction at %s is not adjacent" " to previous (expected %s)" % (expected_next, ins.getAddress())) if 0 < len(matches) < match_limit: # we have all the remaining matches, start only searching those addresses match_set = AddressSet() for addr in matches: match_set.add(addr, addr.add(len(byte_pattern))) matches = findBytes(match_set, pattern, match_limit, 1) else: # the matches are sorted in ascending order, so the first match will be the start matches = findBytes(matches[0] if len(matches) else None, pattern, match_limit) if len(matches) < 2: break if not len(matches) == 1: print(*(b.ida_str() for b in byte_pattern)) print('Signature matched', len(matches), 'locations:', *(matches)) raise Exception("Could not find unique signature") else: print("Signature for", fn.getName()) print(*(b.ida_str() for b in byte_pattern)) print("".join(b.sig_str() for b in byte_pattern))
def _check_and_create_memory(startAddr, endAddr): memory_range = AddressSet(toAddr(startAddr), toAddr(endAddr)) # we look for the missing part of the range # in existing memory memory_missing = memory_range.subtract(memory) if not memory_missing.isEmpty(): print "creating memory block for range %s" % memory_missing _create_memory(memory_missing.getMinAddress().getOffset(), memory_missing.getMaxAddress().getOffset())
def move_block(start, end, destination): # move block [start, end) to function of destination print("moving [0x%x, 0x%x) to function at 0x%x" % (start, end, destination)) # Ghidra needs the last byte to be inclusive end -= 1 g_start = toAddr(start) g_end = toAddr(end) g_destination = toAddr(destination) function_mgr = currentProgram.getFunctionManager() # get the original function original_function = function_mgr.getFunctionContaining(g_start) removed_original_function = False if original_function: # need to remove the range from the original function # special care when the entry point is in range original_entry = original_function.getEntryPoint() new_original_body = original_function.getBody().subtract( AddressSet(g_start, g_end)) if (g_start <= original_entry) and (original_entry < g_end): # PROBLEM: entry point of function is in block, # remove the entire function print("removing function...") removed_original_function = function_mgr.removeFunction( original_entry) assert removed_original_function new_entrypoint = new_original_body.getMinAddress() print("recreating function at 0x%x" % (new_entrypoint.getOffset())) listing.createFunction(None, new_entrypoint, new_original_body, SourceType.DEFAULT) else: # remove this block from the function original_function.setBody(new_original_body) #endif #endif # move the block to the destination function destination_function = function_mgr.getFunctionContaining(g_destination) assert destination_function # original body destination_entry = destination_function.getEntryPoint() print("adding to destination function at 0x%x" % destination_entry.getOffset()) destination_body = destination_function.getBody() destination_function.setBody( destination_body.union(AddressSet(g_start, g_end)))
def setColor(direccion, mnemonico): addresses = AddressSet() addresses.add(direccion) vcolor = Color.WHITE # Por defecto colorea a blanco para borrar colores anteriores # busca mnemonico en el array for nem in aMnemonics: if mnemonico == nem[C_MNEMONICO]: nem[C_CONTADOR] += 1 if nem[C_SETCOLOR] == True: vcolor = nem[C_COLOR] if nem[C_SHOWLOG]: label = str(getSymbolAt(direccion)) if not label == "None": print(label) + ": " msg = " " + str(direccion) + " : " + mnemonico + " " print(msg) setBackgroundColor(direccion, vcolor)
def colorize_test(address): anotherAddress = currentAddress.add(10) setBackgroundColor(anotherAddress, Color.YELLOW) # create an address set with values you want to change addresses = AddressSet() addresses.add(currentAddress.add(10)) addresses.add(currentAddress.add(11)) addresses.add(currentAddress.add(12)) setBackgroundColor(addresses, Color(100, 100, 200))
def functions(self, start=None, end=None) -> Iterable[GhidraFunction]: if start is None and end is None: iterator = self._listing.getFunctions(True) elif start is not None and end is None: iterator = self._listing.getFunctions(self._to_addr(start), True) elif start is None and end is not None: iterator = self._listing.getFunctions(self._to_addr(end), False) else: from ghidra.program.model.address import AddressSet address_set = AddressSet( self._to_addr(start), self._to_addr(end), ) iterator = self._listing.getFunctions(address_set, True) for function in iterator: yield GhidraFunction(self, function)
def process_section(memory_block): global block_uid, function_uid, edge_uid section_range = AddressSet(memory_block.getStart(), memory_block.getEnd()) # functionless instructions process_functionless(section_range) function_mgr = currentProgram.getFunctionManager() # functionless instructions nr_functionless = 0 hanging_insn_it = listing.getInstructions(section_range, True) while hanging_insn_it.hasNext(): insn = hanging_insn_it.next() func = function_mgr.getFunctionContaining(insn.getAddress()) if not func: # functionless ifile.write( "0x%x:%d:%d:%d:0x%x:%d:%d:%d\n" % (insn.getAddress().getOffset(), INVALID, INVALID, INVALID, InsGetAssembled(insn), InsIsThumb(insn), 0, 0)) nr_functionless += 1 #endif #endwhile logfile.write("Found %d functionless instructions\n" % nr_functionless) # functions function_it = function_mgr.getFunctions(section_range, True) while function_it.hasNext(): f = function_it.next() logfile.write("Doing function %s\n" % f.toString()) # basic blocks bms = state.getTool().getService(BlockModelService) cbm = bms.getActiveBlockModel() cbi = cbm.getCodeBlocksContaining(f.getBody(), monitor) while cbi.hasNext(): cb = cbi.next() bbl_first_byte = cb.getFirstStartAddress() bbl_last_byte = cb.getAddresses(False).next() logfile.write(" block %x\n" % bbl_first_byte.getOffset()) insn_it = listing.getInstructions( AddressSet(bbl_first_byte, bbl_last_byte), True) insn = None bbl_nins = 0 while insn_it.hasNext(): insn = insn_it.next() logfile.write(" instruction %s\n" % insn.toString()) ifile.write( "0x%x:%d:%d:%d:0x%x:%d:%d:%d\n" % (insn.getAddress().getOffset(), block_uid, function_uid, INVALID, InsGetAssembled(insn), InsIsThumb(insn), 0, 0)) # switch instructions is_switch, switch_destinations, default_switch_destination = InsIsSwitch( insn) if is_switch and len(switch_destinations) > 0: #TODO: instruction can be marked as switch with length 0 # this is probably an unanalysed switch # take note of the switch instruction sfile.write( "0x%x:%d:0x%x:" % (insn.getAddress().getOffset(), len(switch_destinations), default_switch_destination)) for d in switch_destinations: sfile.write("0x%x," % d.getOffset()) sfile.write("\n") #endif bbl_nins += 1 #endwhile # last instruction determines control flow block_addr = bbl_first_byte.getOffset() branch_addr = insn.getAddress().getOffset() ft = insn.getFallThrough() non_ft = insn.getFlows() flow_type = insn.getFlowType() jump_type = Tool.EDGE_JUMP ft_type = Tool.EDGE_FALLTHROUGH if flow_type.isCall(): # call logfile.write("CALL 0x%x %s\n" % (insn.getAddress().getOffset(), insn.toString())) jump_type = Tool.EDGE_CALL ft_type = Tool.EDGE_CALLFALLTHROUGH #endif if ft: # fallthrough edge logfile.write(" ft: 0x%x->0x%x\n" % (insn.getAddress().getOffset(), ft.getOffset())) efile.write("%d:0x%x:0x%x:0x%x:%d:%d:%d\n" % (edge_uid, block_addr, branch_addr, ft.getOffset(), AddressInPLT(ft), ft_type, 0)) edge_uid += 1 #endif if non_ft: # flow edges for i in non_ft: logfile.write( " jp: 0x%x->0x%x\n" % (insn.getAddress().getOffset(), i.getOffset())) efile.write("%d:0x%x:0x%x:0x%x:%d:%d:%d\n" % (edge_uid, block_addr, branch_addr, i.getOffset(), AddressInPLT(i), jump_type, 0)) edge_uid += 1 #endfor #endif bfile.write("%d:0x%x:%d:%d:%d\n" % (block_uid, bbl_first_byte.getOffset(), bbl_nins, function_uid, INVALID)) block_uid += 1 #endwhile ffile.write( "%d:%s:%d:%d\n" % (function_uid, f.getName().replace(':', '_'), INVALID, INVALID)) function_uid += 1
#@category Examples.Python from ghidra.app.plugin.core.colorizer import ColorizingService from ghidra.app.script import GhidraScript from ghidra.program.model.address import Address from ghidra.program.model.address import AddressSet from java.awt import Color service = state.getTool().getService(ColorizingService) if service is None: print "Can't find ColorizingService service" if currentSelection is not None: service.setBackgroundColor(currentSelection, Color(255, 200, 200)) elif currentAddress is not None: service.setBackgroundColor(currentAddress, currentAddress, Color(255, 200, 200)) else: print "No selection or current address to color" anotherAddress = currentAddress.add(10) setBackgroundColor(anotherAddress, Color.YELLOW) # create an address set with values you want to change addresses = AddressSet() addresses.add(currentAddress.add(10)) addresses.add(currentAddress.add(11)) addresses.add(currentAddress.add(12)) setBackgroundColor(addresses, Color(100, 100, 200))
namespaceSymbol = namespaceSymbols.pop(0) namespace = symdb.getNamespace(namespaceSymbol.name, namespaceSymbol.getParentNamespace()) if namespace is None: continue namespaceSymbols.extend(symdb.getChildren(namespaceSymbol)) for sym in symdb.getSymbols(namespace): if sym.name != u'__vt': continue addr = sym.address.next() if addr is None: continue while len(symdb.getSymbols(addr)) == 0: addr = addr.next() while addr.subtract(sym.address) % 4 != 0: addr = addr.previous() length = addr.subtract(sym.address) startAddr = sym.address endAddr = addr.previous() print namespace, sym, startAddr, length adt = ArrayDataType(PointerDataType.dataType, length / 4, 4, currentProgram.getDataTypeManager()) assert length == adt.getLength() adset = AddressSet(startAddr, endAddr) if listing.getInstructions(adset, True).hasNext(): print "Can't create data because the current selection contains instructions" continue listing.clearCodeUnits(startAddr, endAddr, False) listing.createData(startAddr, adt, length)
script_path = getSourceFile().getAbsolutePath() print("call angr:") if DEBUG: import utils utils.open_in_ipython(script_path, fn) else: call_angr = os.popen("python3 %s %s" % (script_path, fn)) print(call_angr.read()) print("===================================") with open(fn,"r") as fno: config = json.load(fno) addressSet = AddressSet() for [addr,value] in config["def_infos"]: #print(addr,value) if addr == None: continue addressSet.add(toAddr(addr)) print("@ %x :%s" % (addr, value)) setEOLComment(toAddr(addr), value) createHighlight(addressSet) else: #we are in normal python context import sys import json print("Enter angr part.")
def syncView(self, address=None): if address is None: address = self.state.getCurrentAddress() self.state.setCurrentAddress(address) self.state.setCurrentSelection(ProgramSelection(AddressSet(address)))
def get_data(block): addr_set = AddressSet(block.start, block.end) return [d for d in currentProgram.getListing().getData(addr_set, True)]
def get_bb_instructions(self, bb): ar = bb.getLastRange() return FakeIter(self.cm.getCodeUnits(AddressSet(ar), True))
#Colors all calls along the call graph to the current address #@author #@category #@keybinding #@menupath #@toolbar from ghidra.program.model.address import Address from ghidra.program.model.address import AddressSet from java.awt import Color def collect_calls(addresses, address): f = getFunctionContaining(address) if f == None: return print f.getName() e = f.getEntryPoint() for r in getReferencesTo(e): if r.getReferenceType().isCall(): a = r.getFromAddress() addresses.add(a) collect_calls(addresses, a) addresses = AddressSet() collect_calls(addresses, currentAddress) setBackgroundColor(addresses, Color.RED)
if debug: logger.setLevel(logging.DEBUG) #global variables refList = [] addresses = [] parent_functions = [] parent_function_params = [] vuln_parent = [] vuln_params = [] malloc_list = [] branches_found = [] malloc_from_list = [] service = state.getTool().getService(ColorizingService) addresses_to_color = AddressSet() def find_malloc(func_addr, fun_obj): currentInstr = getInstructionContaining(func_addr) print("In a new function!!") while (getFunctionContaining(currentInstr.getAddress()) == fun_obj): search_string = currentInstr.toString() #looking for all the bl instructions then comparing the address #of that instruction to the addresses of all the mallocs if search_string.find('bl') != -1: branches_found.append(str(currentInstr.getAddress())) if str(currentInstr.getAddress()) in malloc_from_list: print("Malloc found")