def find_all_ioctls():
"""
From the currently selected address attempts to traverse all blocks inside the current function to find all immediate values which
are used for a comparison/sub immediately before a jz. Returns a list of address, second operand pairs.
"""
ioctls = []
# Find the currently selected function and get a list of all of it's basic blocks
addr = idc.ScreenEA()
f = idaapi.get_func(addr)
fc = idaapi.FlowChart(f, flags=idaapi.FC_PREDS)
for block in fc:
# grab the last two instructions in the block
last_inst = idc.PrevHead(block.endEA)
penultimate_inst = idc.PrevHead(last_inst)
# If the penultimate instruction is cmp or sub against an immediate value immediatly preceding a 'jz'
# then it's a decent guess that it's an IOCTL code (if this is a disptach function)
if idc.GetMnem(penultimate_inst) in ['cmp', 'sub'] and idc.GetOpType(penultimate_inst, 1) == 5:
if idc.GetMnem(last_inst) == 'jz':
ioctl_tracker.add_ioctl(penultimate_inst)
for inst in ioctl_tracker.ioctl_locs:
value = get_operand_value(inst)
ioctls.append((inst, value))
return ioctls
python类ScreenEA()的实例源码
def get_position_and_translate():
"""
Gets the current selected address and decodes the second parameter to the instruction if it exists/is an immediate
then adds the C define for the code as a comment and prints a summary table of all decoded IOCTL codes.
"""
pos = idc.ScreenEA()
if idc.GetOpType(pos, 1) != 5: # Check the second operand to the instruction is an immediate
return
ioctl_tracker.add_ioctl(pos)
value = get_operand_value(pos)
define = ioctl_decoder.get_define(value)
make_comment(pos, define)
# Print summary table each time a new IOCTL code is decoded
ioctls = []
for inst in ioctl_tracker.ioctl_locs:
value = get_operand_value(inst)
ioctls.append((inst, value))
ioctl_tracker.print_table(ioctls)
def finish_populating_tform_popup(self, form, popup):
tft = idaapi.get_tform_type(form)
if tft != idaapi.BWN_DISASM:
return
if not device_type.is_driver():
return
pos = idc.ScreenEA()
# If the second argument to the current selected instruction is an immediately
# then give the option to decode it.
if idc.GetOpType(pos, 1) == 5:
register_dynamic_action(form, popup, 'Decode IOCTL', DecodeHandler())
if pos in ioctl_tracker.ioctl_locs:
register_dynamic_action(form, popup, 'Invalid IOCTL', InvalidHandler())
register_dynamic_action(form, popup, 'Decode All IOCTLs in Function', DecodeAllHandler())
if len(ioctl_tracker.ioctl_locs) > 0:
register_dynamic_action(form, popup, 'Show All IOCTLs', ShowAllHandler())
def handleUnhookInst(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
if self.hookedInstruction(address) == False:
return
entry = self.idbHookMap[address]
outJSON = json.dumps({
"req_id": kFridaLink_DelHookRequest,
"data": entry.genDelRequest()
})
del self.idbHookMap[address]
self.clientSocket.sendto(outJSON, self.clientAddress)
SetColor(address, CIC_ITEM, kIDAViewColor_Reset)
refresh_idaview_anyway()
self.idbHooksView.setContent(self.idbHookMap)
def handleUnhookFunc(self, screenEA = None):
if screenEA is not None:
func = get_func(screenEA)
else:
func = get_func(ScreenEA())
if func is None:
return
address = func.startEA;
if self.hookedFunction(address) == False:
return
entry = self.idbHookMap[address]
outJSON = json.dumps({
"req_id": kFridaLink_DelHookRequest,
"data": entry.genDelRequest()
})
del self.idbHookMap[address]
self.clientSocket.sendto(outJSON, self.clientAddress)
SetColor(address, CIC_FUNC, kIDAViewColor_Reset)
refresh_idaview_anyway()
self.idbHooksView.setContent(self.idbHookMap)
def hookedFunction(self, screenEA = None):
if screenEA is not None:
func = get_func(screenEA)
else:
func = get_func(ScreenEA())
if func is None:
return False;
address = func.startEA;
if address in self.idbHookMap:
# can be start of the function, check hook type
if self.idbHookMap[func.startEA].hook.type == "func":
return True
else:
return False
else:
return False
def ClearorShow(self):
ea = idc.ScreenEA()
(startEA,endEA) = self._GetFuncRange(ea)
self.ColorCompare()
self._delComms(startEA,endEA)
cid = [i for i,item in enumerate(self._tablelist) if item[0]==hex(startEA)]
DEBUG_PRINT( 'clear or show')
DEBUG_PRINT( cid)
if cid != []:
DEBUG_PRINT( 'in')
cindex = cid[0]
DEBUG_PRINT( cindex)
DEBUG_PRINT( self._tablelist[cindex])
if self._tablelist[cindex][2] == '0':
self._showComms(startEA,endEA,0)
self._tablelist[cindex][2] = '1'
else:
self._tablelist[cindex][2] = '0'
return
def PreIdx(self): # ,
DEBUG_PRINT('IN PreIdx')
ea = idc.ScreenEA()
# print 'Cursor is at 0x%x'%(ea)
if ea not in self._dbDict.keys():
print '\n0x%x has no comments'%(ea)
return
if ea != self._choose_ea:
self._choose_ea = ea
self._choose_idx = self.GetIDX(ea)
if self._choose_idx == -1:
print 'no comment'
return
self._choose_id = self.GetID(ea,self._choose_idx)
if self._choose_id == 0:
print 'Already FIRST Index'
return
self._choose_id -= 1
id = self._choose_id;
if id >= 0:
self.ForwardView(ea, id,innermode = 1)
def _do_callbacks(cls, ptr_or_reg):
data = {
'ea': idc.ScreenEA(),
'ptr_or_reg': ptr_or_reg
}
for callback in cls._callbacks[ptr_or_reg]:
callback(data)
def start(self):
tainter = PropagateTaint(idc.ScreenEA(), self.kind)
tainter.on_finish(lambda bap: self.finish(bap))
tainter.run()
def run(self, arg):
"""
Ask user for BAP args to pass, BIR attributes to print; and run BAP.
Allows users to also use {screen_ea} in the BAP args to get the
address at the location pointed to by the cursor.
"""
args_msg = "Arguments that will be passed to `bap'"
args = idaapi.askstr(ARGS_HISTORY, '--passes=', args_msg)
if args is None:
return
attr_msg = "A comma separated list of attributes,\n"
attr_msg += "that should be propagated to comments"
attr_def = self.recipes.get(args, '')
attr = idaapi.askstr(ATTR_HISTORY, attr_def, attr_msg)
if attr is None:
return
# store a choice of attributes for the given set of arguments
# TODO: store recipes in IDA's database
self.recipes[args] = attr
ea = idc.ScreenEA()
attrs = []
if attr != '':
attrs = attr.split(',')
analysis = BapScripter(args, attrs)
analysis.on_finish(lambda bap: self.load_script(bap, ea))
analysis.run()
def get_current_function_xrefs_from( self ):
addr_in_func = idc.ScreenEA()
curr_func = idc.GetFunctionName( addr_in_func )
refs = self.find_xrefs_from( addr_in_func )
return [ ref.get_row( XrefsFromFinder.XREF_TYPE2STR ) for ref in refs ]
# ------------------------------------------------------------------------------
def main():
va = idc.ScreenEA()
fva = get_function(va)
print('-' * 80)
rule = create_yara_rule_for_function(fva)
print(rule)
if test_yara_rule(rule):
print('success: validated the generated rule')
else:
print('error: failed to validate generated rule')
def setupUI(self):
ea = idc.ScreenEA()
seg = idaapi.getseg(ea)
SigmName = idc.SegName(ea)
startA = idc.SegStart(ea)
endA = idc.SegEnd(ea)
className = idaapi.get_segm_class(seg)
self.setWindowTitle("Jumper--%s %s %s" % (hex(ea - startA).upper(), SigmName, className))
self.groupBox.setLayout(self.enum_segm())
search_hbox = QHBoxLayout()
search_hbox.addWidget(QLabel("search"))
search_hbox.addWidget(self.search_edit)
offset_hbox = QHBoxLayout()
offset_hbox.addWidget(QLabel("offset"))
offset_hbox.addWidget(self.off_edit)
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True) # Set to make the inner widget resize with scroll area
self.scroll.setWidget(self.groupBox)
globle_vbox = QVBoxLayout(self)
globle_vbox.addWidget(self.scroll)
globle_vbox.addLayout(search_hbox)
globle_vbox.addLayout(offset_hbox)
btn_layout = QHBoxLayout()
jump = QPushButton("jump")
jump.clicked.connect(self.jump_click)
get_offset = QPushButton("offset")
get_offset.clicked.connect(self.get_cur_offset)
btn_layout.addWidget(jump)
btn_layout.addWidget(get_offset)
globle_vbox.addLayout(btn_layout)
self.search_edit.textChanged.connect(self.search_changed)
def get_cur_offset(self):
ea = idc.ScreenEA()
seg = idaapi.getseg(ea)
SigmName = idc.SegName(ea)
startA = idc.SegStart(ea)
self.off_edit.setText(hex(ea - startA).upper())
self.search_edit.setText(SigmName)
def activate(self, ctx):
pos = idc.ScreenEA()
# Get current comment for this instruction and remove the C define from it, if present
comment = idc.Comment(pos)
code = get_operand_value(pos)
define = ioctl_decoder.get_define(code)
comment = comment.replace(define, "")
idc.MakeComm(pos, comment)
# Remove the ioctl from the valid list and add it to the invalid list to avoid 'find_all_ioctls' accidently re-indexing it.
ioctl_tracker.remove_ioctl(pos)
def handleHookInstOnce(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
self.handleQuickInstHook(address, True)
def handleHookInstPerm(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
self.handleQuickInstHook(address, False)
def handleHookInstBreakOnce(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
self.handleQuickInstHook(address, True, True)
def handleHookInstBreakPerm(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
self.handleQuickInstHook(address, False, True)
def handleHookFuncPerm(self, screenEA = None):
if screenEA is not None:
func = get_func(screenEA)
else:
func = get_func(ScreenEA())
if func is None:
return
address = func.startEA;
self.handleQuickFuncHook(address, False)
def handleHookInstEdit(self, screenEA = None):
if self.hookedInstruction() == False:
return
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
entry = self.idbHookMap[address]
entry.hook.mnemonic = GetDisasm(address)
hookDlg = InstructionHookDialog(entry.hook.module, "%X" % entry.hook.id, entry.hook.mnemonic, entry.hook.recentSrcFile)
hookDlg.Compile()
hookDlg.script.value = entry.hook.script
hookDlg.trigger.value = 0 if entry.hook.once == True else 1
ok = hookDlg.Execute()
if ok != 1:
return
flags = HookEntry.UDP_NONE
once = True if hookDlg.trigger.value == 0 else False
if entry.hook.once != once:
entry.hook.once = once
flags |= HookEntry.UPD_TRIGGER
entry.hook.recentSrcFile = hookDlg.recentScriptFile
if entry.hook.script != hookDlg.script.value:
entry.hook.script = hookDlg.script.value
flags |= HookEntry.UPD_SCRIPT
outJSON = json.dumps({
"req_id": kFridaLink_UpdHookRequest,
"data": entry.genUpdRequest(flags)
})
self.clientSocket.sendto(outJSON, self.clientAddress)
def handleHookInstShowCPU(self):
if self.hookedInstruction() == False:
return
address = ScreenEA()
if self.cpuContextViews.hasView(address) == False:
entry = self.idbHookMap[address]
newView = CPUContextView(self, entry.hook.id, entry.hook.mnemonic)
self.cpuContextViews.addView("CPU Context", newView)
self.cpuContextViews.setContent(entry.hook.id, {"arch":entry.arch, "context":entry.cpu_ctx})
self.cpuContextViews.showView(address)
def handleHookInstShowBacktrace(self):
if self.hookedInstruction() == False:
return
address = ScreenEA()
if self.backtraceViews.hasView(address) == False:
entry = self.idbHookMap[address]
newView = BacktraceView(self, entry.hook.id)
self.backtraceViews.addView("Backtrace", newView)
self.backtraceViews.setContent(entry.hook.id, entry.backtrace)
self.backtraceViews.showView(address)
def handleHookFuncShowCPU(self):
if self.hookedFunction() == False:
return
func = get_func(ScreenEA())
if func is None:
return
address = func.startEA;
if self.cpuContextViews.hasView(address) == False:
entry = self.idbHookMap[address]
newView = CPUContextView(self, entry.hook.id, entry.hook.symbol)
self.cpuContextViews.addView("CPU Context", newView)
self.cpuContextViews.setContent(entry.hook.id, {"arch":entry.arch, "context":entry.cpu_ctx})
self.cpuContextViews.showView(address)
def handleHookFuncShowStack(self):
if self.hookedFunction() == False:
return
func = get_func(ScreenEA())
if func is None:
return
address = func.startEA;
if self.stackViews.hasView(address) == False:
entry = self.idbHookMap[address]
newView = StackView(self, entry.hook.id, entry.hook.symbol)
self.stackViews.addView("Stack", newView)
self.stackViews.setContent(entry.hook.id, entry.stack)
self.stackViews.showView(address)
def handleHookFuncShowBacktrace(self):
if self.hookedFunction() == False:
return
func = get_func(ScreenEA())
if func is None:
return
address = func.startEA;
if self.backtraceViews.hasView(address) == False:
entry = self.idbHookMap[address]
newView = BacktraceView(self, entry.hook.id)
self.backtraceViews.addView("Backtrace", newView)
self.backtraceViews.setContent(entry.hook.id, entry.backtrace)
self.backtraceViews.showView(address)
def handleHookInstLinkMemory(self):
if self.hookedInstruction() == False:
return
address = ScreenEA()
self.idbHookMap[address].mem_list = self.linkMemoryRanges();
entry = self.idbHookMap[address]
outJSON = json.dumps({
"req_id": kFridaLink_UpdHookRequest,
"data": entry.genUpdRequest(HookEntry.UPD_MEMLIST)
})
self.clientSocket.sendto(outJSON, self.clientAddress)
def hookedInstruction(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
if address in self.idbHookMap:
# can be start of the function, check hook type
if self.idbHookMap[address].hook.type == "inst":
return True
else:
return False
else:
return False
def handleGetRealAddress(self, screenEA = None):
if screenEA is not None:
address = screenEA
else:
address = ScreenEA()
offset, moduleName = self.getAddressDetails(address)
for module in self.targetModules:
if module['name'] == moduleName:
moduleBase = module['base']
realAddr = int(moduleBase,16) + offset
self.handleFraplLog("info", "[ %s ] 0x%X => 0x%X %s" % (moduleName, address, realAddr, GetDisasm(address)))
break