Example #1
0
    def UnregisterHandlers(self, purge=False):
        '''
		Deletes breakpoints for all registered handlers.

		@purge - Removes all handlers for all instances of IDBFunctionHandler.

		Returns None.
		'''
        self.UnregisterDefaultHandler()

        if not purge:
            # Only remove this instance's handlers
            for (name, info) in self.FUNCTION_HANDLERS.iteritems():
                condition = idc.GetBptAttr(info['address'], idc.BPTATTR_COND)

                if condition == self.bpt_cnd:
                    idc.DelBpt(info['address'])
        else:
            # Try to remove ALL instance's handlers (this could remove other conditional breakpoints...)
            for i in range(0, idc.GetBptQty()):
                ea = idc.GetBptEA(i)
                condition = idc.GetBptAttr(ea, idc.BPTATTR_COND)
                if condition.endswith(self.BPT_CND % ''):
                    idc.DelBpt(ea)

        self.FUNCTION_HANDLERS = {}
Example #2
0
    def UnregisterHandler(self, name, stubs=True):
        '''
		Removes a function handler by name.

		@name  - The name of the function handler to be removed.
		@stubs - If True, corresponding function stub handlers that were automatically created by RegisterHandler will also be removed.

		Returns None.
		'''
        addr = None
        stub_name = None
        stub_addr = None

        if name is not None:
            try:
                stub_name = self.STUB_NAMING_CONVENTION % name
            except:
                pass

            if self.FUNCTION_HANDLERS.has_key(name):
                addr = self.FUNCTION_HANDLERS[name]['address']

            if self.FUNCTION_HANDLERS.has_key(stub_name):
                stub_addr = self.FUNCTION_HANDLERS[stub_name]['address']

        if addr is not None and name is not None:
            idc.DelBpt(addr)
            del self.FUNCTION_HANDLERS[name]

        if stubs and stub_addr is not None and stub_name is not None:
            idc.DelBpt(stub_addr)
            del self.FUNCTION_HANDLERS[stub_name]
Example #3
0
    def unsetBPs(self):
        """
        Remove all DIE set BreakPoints
        @return: Returns True if successful, otherwise return False
        """
        try:
            for ea in self.die_db.bp_list:
                (bp_flags, bp_desc) = self.die_db.bp_list[ea]
                if bp_flags & WAS_USER_BREAKPOINT:
                    return

                idc.DelBpt(ea)  # Remove breakpoint

            # Remove all return breakpoints
            for ea in self.ret_bps:
                idc.DelBpt(ea)

            self.die_db.bp_list.clear()  # Clear the breakpoint list.
            self.ret_bps.clear()         # Clear the return breakpoint list

            # Clear walked function list if necessary.
            if self.walked_functions is not None:
                self.walked_functions.clear()

        except Exception as ex:
            self.logger.exception("Failed to remove breakpoints: %s", ex)
Example #4
0
        def off(self):
            idc.StopDebugger()
            print('gogo exit')

            while not self.exited:
                idc.GetDebuggerEvent(idc.WFNE_ANY, 1)

            self.unhook()
            idc.DelBpt(self.start_code_ea)
            idc.DelBpt(self.ret_pad_ea)
Example #5
0
def DelAllConditionBpt():
    ea = 0x2C13000
    while ea < 0x357D000:
        mnem = idc.GetMnem(ea)
        if mnem == 'jmp' or mnem == 'retn':
            idc.DelBpt(ea)
        ea = idc.NextHead(ea)
Example #6
0
    def taintStart(self):

        Print("Taint Start pressed!")
        #Remove the starting breakpoint
        if self.taintStart is not None:
            idc.DelBpt(self.taintStart)

        #Add a new starting breakpoint
        self.taintStart = idc.here()
        instruction = idc.GetDisasm(self.taintStart)
        Print(instruction)
        idc.AddBpt(self.taintStart)
        idc.SetBptAttr(self.taintStart, idc.BPT_BRK, 0)

        callbackAddr = "interactivemodeCallback.startTrace()"
        customCallbackFuncs = ['ReadFile', 'recv']

        for callbackFunc in customCallbackFuncs:
            if callbackFunc in instruction:
                callbackAddr = "interactivemodeCallback." + callbackFunc + "()"
                Print("Found callback function %s for interactive mode" %
                      callbackAddr)
                break

        idc.SetBptCnd(self.taintStart, callbackAddr)
Example #7
0
def singleStep(segfault_addr):

    # add breakpoint on segfault addr
    idc.AddBpt(segfault_addr)

    # move debugger
    idc.GetDebuggerEvent(idc.WFNE_SUSP | idc.WFNE_CONT, -1)
    rip = idc.GetRegValue("RIP")

    # now single step through segfault code
    while True:

        # print instruction
        addr = idc.GetRegValue("RIP")
        disasm = idc.GetDisasm(addr)
        msg = "{}: {}".format(hex(addr), disasm)

        # step through loaded code
        idc.StepInto()
        idc.GetDebuggerEvent(idc.WFNE_SUSP, -1)

        addr = idc.GetRegValue("RIP")
        if addr < begin or addr > (begin + size):
            break

    idc.DelBpt(segfault_addr)
Example #8
0
        def off(self):
            if self.STOP_DEBUG_AT_END:
                self.stop_debugger()

            self.unhook()
            for bpt in self.bpts:
                idc.DelBpt(bpt)
Example #9
0
    def Sync(self, offset, added, removed):
        """ Sync(offset, added, removed) => None
        Synchronize debug info with gef. This is an internal function. It is
        not recommended using it from the command line.
        """
        global _breakpoints, _current_instruction, _current_instruction_color

        if _current_instruction > 0:
            idc.SetColor(_current_instruction, CIC_ITEM, _current_instruction_color)

        base_addr = idaapi.get_imagebase()
        pc = base_addr + int(offset, 16)
        _current_instruction = long(pc)
        _current_instruction_color = GetColor(_current_instruction, CIC_ITEM)
        idc.SetColor(_current_instruction, CIC_ITEM, 0x00ff00)
        print("PC @ " + hex(_current_instruction).strip('L'))
        # post it to the ida main thread to prevent race conditions
        idaapi.execute_sync(lambda: idc.Jump(_current_instruction), idaapi.MFF_WRITE)

        cur_bps = set([ idc.GetBptEA(n)-base_addr for n in range(idc.GetBptQty()) ])
        ida_added = cur_bps - _breakpoints
        ida_removed = _breakpoints - cur_bps
        _breakpoints = cur_bps

        # update bp from gdb
        for bp in added:
            idc.AddBpt(base_addr+bp)
            _breakpoints.add(bp)
        for bp in removed:
            if bp in _breakpoints:
                _breakpoints.remove(bp)
            idc.DelBpt(base_addr+bp)

        return [list(ida_added), list(ida_removed)]
Example #10
0
def setup_buf_bpt(ptr, n, enable):
    for i in range(n):
        u = ptr + i
        if enable:
            idc.AddBptEx(u, 1, idc.BPT_RDWR)
        else:
            idc.DelBpt(u)
Example #11
0
    def MyReadFile(self):
        """
        Monitors the the beginning of ReadFile function
        ReadFile arguments are read from the stack
        This is the function that will trigger the trace
        inputLoggingList holds arguments for 
        """
        """  
        BOOL WINAPI ReadFile(
          _In_         HANDLE hFile,
          _Out_        LPVOID lpBuffer,
          _In_         DWORD nNumberOfBytesToRead,
          _Out_opt_    LPDWORD lpNumberOfBytesRead,
          _Inout_opt_  LPOVERLAPPED lpOverlapped
        ); 
        """

        hFile = Util.GetData(0x4)
        self.logger.info("hFile is 0x%x" % (hFile))

        lpBuffer = Util.GetData(0x8)
        self.logger.info("lpBuffer is 0x%x" % (lpBuffer))

        nNumberOfBytesToRead = Util.GetData(0xC)
        self.logger.info("nNumberOfBytesToRead value is 0x%x" %
                         (nNumberOfBytesToRead))

        lpNumberOfBytesRead = Util.GetData(0x10)
        self.logger.info("lpNumberOfBytesRead value is 0x%x" %
                         (lpNumberOfBytesRead))

        lpOverlapped = Util.GetData(0x14)
        self.logger.info("lpOverlapped is 0x%x" % (lpOverlapped))

        retAddr = Util.GetData(0x0)

        callerAddr = retAddr - idc.ItemSize(retAddr)

        self.tempStack = []
        self.tempStack.append(lpBuffer)
        self.tempStack.append(lpNumberOfBytesRead)
        self.tempStack.append(hFile)
        self.tempStack.append(callerAddr)
        #self.tempStack.append(idc.GetDisasm(callerAddr))
        self.tempStack.append("ReadFile")
        self.tempStack.append(idc.GetCurrentThreadId())

        if hFile in self.handleSet:
            self.logger.info("Ready to read from handle 0x%x" % hFile)
            Print("Ready to read from handle 0x%x" % hFile)
            idc.AddBpt(retAddr)
            idc.SetBptCnd(retAddr, "windowsFileIO.MyReadFileEnd()")
        else:
            if idc.CheckBpt(retAddr) >= 0:
                self.logger.info("Removing un-needed ReadFile breakpoint.")
                Print("Removing un-needed ReadFile breakpoint.")
                idc.DelBpt(retAddr)

        return 0
Example #12
0
    def WSOCK32Bind(self):
        """  
        int bind(
          _In_  SOCKET s,
          _In_  const struct sockaddr *name,
          _In_  int namelen
        );
        
        struct sockaddr_in {
            short   sin_family;
            u_short sin_port;
            struct  in_addr sin_addr;
            char    sin_zero[8];
        };
        """

        s = Util.GetData(0x4)
        self.logger.info("WSOCK32Bind: SOCKET is 0x%x" % (s))

        sockaddr_name = Util.GetData(0x8)
        self.logger.info("WSOCK32Bind: sockaddr_name is 0x%x" %
                         (sockaddr_name))

        port = struct.unpack(">H",
                             idaapi.dbg_read_memory(sockaddr_name + 0x2, 2))
        portName = str(port[0])
        self.logger.info("WSOCK32Bind: port value is %s" % (portName))

        namelen = Util.GetData(0xC)
        self.logger.info("WSOCK32Bind: namelen value is %d" % (namelen))

        retAddr = Util.GetData(0x0)
        Print(self.filter['network'])
        if portName in self.filter['network']:
            self.tempStack = []
            self.tempStack.append(s)
            self.tempStack.append(portName)
            idc.AddBpt(retAddr)
            idc.SetBptAttr(retAddr, idc.BPT_BRK, 0)
            idc.SetBptCnd(retAddr, "windowsNetworkIO.checkBindEnd()")
            self.logger.info(
                "WSOCK32Bind: Netork Filter matched. Adding port to the Handle's dictionary to start logging."
            )
            Print(
                "Filter matched. Add handle to the handle's dictionary to start logging."
            )

        else:
            if idc.CheckBpt(retAddr) >= 0:
                Print("Removing un-needed breakpoint.")
                self.logger.info("WSOCK32Bind: Removing un-needed breakpoint.")
                idc.DelBpt(retAddr)

            self.logger.info("WSOCK32Bind: Network Filter did not match.")

        return 0
Example #13
0
def reEnable(addr, bptEnabled, disabledSet):
    enableBpts(disabledSet)
    #print 'back from enable'
    if bptEnabled < 0:
        idc.EnableBpt(addr, False)
        success = idc.DelBpt(addr)
        #print 'reEnable delete bpt at %x success: %d' % (addr, success)
    elif bptEnabled == 0:
        #print 'reEnable reenabling bkpt at %x' % addr
        idc.EnableBpt(addr, False)
Example #14
0
    def removeRetBP(self, ea):
        """
        Remove a breakpoint for a return instruction
        @param ea: effective address of a previously placed Return Breakpoint
        @return: True if breakpoint was successfully removed, otherwise return False
        """
        if ea in self.ret_bps:
            idc.DelBpt(ea)
            del self.ret_bps[ea]
            return True

        return False
Example #15
0
    def taintStop(self):

        Print("Taint Stop pressed!")
        #Remove the stopping breakpoint
        if self.taintStop is not None:
            idc.DelBpt(self.taintStop)
        
        #Add a new stopping breakpoint
        self.taintStop = idc.here()
        Print( idc.GetDisasm(self.taintStop) )
        idc.AddBpt(self.taintStop)
        idc.SetBptAttr(self.taintStop, idc.BPT_BRK, 0)
        idc.SetBptCnd(self.taintStop, "interactivemodeCallback.stopTrace()")
Example #16
0
    def My_fread(self):
        """  
        old - size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
        
        size_t _IO_fread (void * ptr, size_t size, size_t count, FILE * stream )
        
        """

        ptr = Util.GetData(0x4)
        self.logger.info("fp is 0x%x" % (ptr))

        _size = Util.GetData(0x8)
        self.logger.info("size is %d" % (_size))

        _count = Util.GetData(0xc)
        self.logger.info("count is %d" % (_count))

        stream = Util.GetData(0x10)
        self.logger.info("stream is 0x%x" % (stream))

        self.pSize = _size * _count
        self.pBuffer = ptr

        retAddr = Util.GetData(0x0)

        callerAddr = retAddr - idc.ItemSize(retAddr)

        self.tempStack = []
        self.tempStack.append(self.pBuffer)
        self.tempStack.append(self.pSize)
        self.tempStack.append(stream)
        self.tempStack.append(callerAddr)

        self.tempStack.append("fread")
        self.tempStack.append(idc.GetCurrentThreadId())

        if stream in self.handleSet:
            self.logger.info("Found stream 0x%x" % stream)

            idc.AddBpt(retAddr)
            idc.SetBptAttr(retAddr, idc.BPT_BRK, 0)
            idc.SetBptCnd(retAddr, "linuxFileIO.My_freadEnd()")
        else:
            self.logger.info("Cannot find handle 0x%x" % stream)
            Print("Removing un-needed fread breakpoint.")
            idc.DelBpt(retAddr)

        return 0
Example #17
0
    def removeBP(self, ea):
        """
        Remove a breakpoint
        @param ea:
        @return: True if breakpoint was removed, otherwise False. Returns -1 if an error occurred.
        """
        try:
            if not ea in self.die_db.bp_list:
                return False

            (bp_flags, bp_desc) = self.die_db.bp_list[ea]
            if bp_flags & WAS_USER_BREAKPOINT:
                return True

            idc.DelBpt(ea)           # Remove breakpoint
            self.die_db.bp_list.pop(ea)     # Remove from breakpoint list

            return True

        except Exception as ex:
            self.logger.exception("Could not remove breakpoint: %s", ex)
            return -1
Example #18
0
def delAllBpts():
    while (True):
        bp = idc.GetBptEA(0)
        if bp == 0xffffffffffffffff:
            break
        idc.DelBpt(bp)
Example #19
0
def remove_all_breakpoint():
    for i in range(idc.GetBptQty()):
        idc.DelBpt(idc.GetBptEA(i))
    all_breakpoint.clear()
Example #20
0
 def delete(self):
     if all_breakpoint[self.addr] is self:
         del all_breakpoint[self.addr]
         idc.DelBpt(self.addr)
Example #21
0
    def MyCreateFileW(self):
        """
        Monitors the the beginning of CreateFileW function
        CreateFileW arguments are read from the stack
        """
        """
        HANDLE WINAPI CreateFileW(
        _In_      LPCTSTR lpFileName,
        _In_      DWORD dwDesiredAccess,
        _In_      DWORD dwShareMode,
        _In_opt_  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
        _In_      DWORD dwCreationDisposition,
        _In_      DWORD dwFlagsAndAttributes,
        _In_opt_  HANDLE hTemplateFile
        );
        """

        lpFileName = Util.GetData(0x4)
        self.logger.info("MyCreateFileW lpFileName is 0x%x" % lpFileName)

        filePath = "".join(Util.Read(lpFileName, 2))

        self.logger.info("filePath is %s" % filePath)

        dwDesiredAccess = Util.GetData(0x8)
        self.logger.info("dwDesiredAccess is 0x%x" % (dwDesiredAccess))

        dwShareMode = Util.GetData(0xC)
        self.logger.info("dwShareMode value is 0x%x" % (dwShareMode))

        lpSecurityAttributes = Util.GetData(0x10)
        self.logger.info("lpSecurityAttributes value is 0x%x" %
                         (lpSecurityAttributes))

        dwCreationDisposition = Util.GetData(0x14)
        self.logger.info("dwCreationDisposition value is 0x%x" %
                         (dwCreationDisposition))

        dwFlagsAndAttributes = Util.GetData(0x18)
        hTemplateFile = Util.GetData(0x1C)

        fileName = os.path.basename(filePath)

        self.logger.info("The filename is %s" % fileName)

        retAddr = Util.GetData(0x0)

        if fileName in self.filter['file']:
            idc.AddBpt(retAddr)
            idc.SetBptAttr(retAddr, idc.BPT_BRK, 0)
            idc.SetBptCnd(retAddr, "windowsFileIO.MyCreateFileWEnd()")
            self.logger.info(
                "Filter matched. Add handle to the handle's dictionary to start logging."
            )
            Print(
                "Filter matched. Add handle to the handle's dictionary to start logging."
            )

        else:
            if idc.CheckBpt(retAddr) >= 0:
                Print("Removing un-needed breakpoint.")
                self.logger.info("Removing un-needed breakpoint.")
                idc.DelBpt(retAddr)

            self.logger.info("Filter did not match.")

        return 0