示例#1
2
	def hookIE(self, dbg):
		loadpid = dbg.pid
		dbg.detach()
		dbg = pydbg()
		dbg.cf = self.cf
		print "[Info Crasher hookIE] IE first process PID = %d" %loadpid
		pattern = r'iexplore.exe\s*([0-9]*)\s*Console'
		count = 0
		while count<=1:
			p = os.popen('tasklist|find "iexplore"')
			pids = re.findall(pattern, p.read())
			count = len(pids)
		print "[Info Crasher hookIE] find IE pids:" + str(pids)
		for pid in pids:
			if loadpid == int(pid):
				print "[Crasher hookIE Debug] This loadpid is %d" %(loadpid)
				#continue
			try:
				print "[Crasher hookIE Debug] This program will attach the process and the PID is %d"  %(loadpid)
				dbg.attach(loadpid)
				dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				dbg.debug_event_loop()
				#dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				#dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				print 'hook IE(pid=%s) success!'%(loadpid)
				return dbg
			except Exception, e:
				print 'hook IE(pid=%s) failed!'%(loadpid)
				print e
				return None
def main():

    global dbg, glAddress, HwBps, MemBps

    try:
        '''
            # Acquiring information #
        '''
        #Initialize
        dbg = pydbg()
        dbg.load(arq)

        #Callback handles
        dbg.set_callback(EXIT_PROCESS_DEBUG_EVENT, NoneDbg)

        #Break on Entry Point
        dbg.bp_set(EP,description="EntryPoint",restore=True,handler=Func)

        #Run it
        dbg.debug_set_process_kill_on_exit(True)
        dbg.run()

    finally:
        for c in MemBps:
            #Check if global variable glDoCrc is still False
            if glDoCrc:
                quit()
            #Global variable of address to HWBP
            glAddress = c

            #New list of sequential read using HWBP
            HwBps = []

            #Screen print, advising about HWBP code block
            print ""
            print "-> Set HWBP in %X" % glAddress

            '''
                begin Debugger code block
            '''
            dbg = pydbg()
            dbg.load(arq)
            dbg.set_callback(EXIT_PROCESS_DEBUG_EVENT, NoneDbg)
            dbg.bp_del_hw_all()
            #First HWBP to sequential read
            dbg.bp_set_hw(glAddress, 1, HW_ACCESS, "HWBREAK", True, hw)
            dbg.run()
            '''
                end Debugger code block
            '''

        #If CRC check is found, then the script will already be dead
        print ""
        print ">> CRC CHECKING NOT FOUND <<"
        print ""
示例#3
0
def main():
    global all_func
    global most_used_funcs
    most_used_funcs = []
    all_func = parseidalog('ida-export.txt')
    dbg = pydbg()
    exe_file = sys.argv[1]
    pe = pefile.PE(exe_file)
    dbg = pydbg()
    dbg.load(exe_file)
    entry = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
    dbg.bp_set(entry, handler=setallbp)
    dbg.run()
示例#4
0
def main():
	global all_func
	global most_used_funcs
	most_used_funcs = []
	all_func = parseidalog('ida-export.txt')
	dbg = pydbg()
	exe_file = sys.argv[1]
	pe = pefile.PE(exe_file)
	dbg = pydbg()
	dbg.load(exe_file)
	entry = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
	dbg.bp_set(entry,handler=setallbp)
	dbg.run()
示例#5
0
def startfuzzer():
	printBanner()
	raw_input('[+] Press Enter to Continue...')
	c = 1
	if len(basefilelist) == 0:
		print '[+] No base files @ ',basefile_dir
		exit()
	print basefilelist
	print '[+] Starting Fuzzing..'
	while 1:
		global basefilename,ext,fuzzfilename
		basefilename = random.choice(basefilelist)
		ext = basefilename.split('.',1)[1]
		fuzzfilename = 'fuzz_' +  basefilename.split('\\',basefilename.count('\\'))[-1:][0]
		fi = open(basefilename,'rb')
		file_data = fi.read()
		fi.close()
		if c%100 == 0:
			collected = gc.collect()
			print '[+] '+str(c)+'th Testcase'
			print "[+] Garbage collector triggered: collected %d objects." % (collected)
		mutated = mutate(file_data)
		try:
			fo = open(temp_dir + fuzzfilename,'wb')
			fo.write(mutated)
			fo.close()
		except Exception, e:
			print '[+] Unable to write new file skipping..'
		dbg = pydbg()
		dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, AccessViolationHandler)
		thread.start_new_thread(StillRunning, (dbg, ))
		args = command_line_arg + " " + temp_dir + fuzzfilename
		dbg.load(programname,args , show_window=True)
		dbg.run()
		c = c + 1
示例#6
0
 def hookIE(self, dbg):
     loadpid = dbg.pid
     dbg.detach()
     dbg = pydbg()
     dbg.cf = self.cf
     print "IE first process PID = %d" % loadpid
     pattern = r"iexplore.exe\s*([0-9]*)\s*Console"
     count = 0
     while count <= 1:
         p = os.popen('tasklist|find "iexplore"')
         pids = re.findall(pattern, p.read())
         count = len(pids)
     print "find IE pids:" + str(pids)
     for pid in pids:
         if loadpid == int(pid):
             continue
         try:
             dbg.attach(int(pid))
             dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
             dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
             dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
             print "hook IE(pid=%s) success!" % (pid)
             return dbg
         except Exception, e:
             print "hook IE(pid=%s) failed!" % (pid)
             print e
             return None
示例#7
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)
示例#8
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)
def start_debugging(pid):
    ##NOCHANGESINTHEFUNCTION
    print "[3] Attaching the process to pydbg"
    dbg = pydbg()
    dbg.attach(int(pid))
    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, check_accessv)
    dbg.run()
示例#10
0
 def start_ASDsvc_debugger(self):
     self.ex_dbg = True
     self.dbg_ads = pydbg()
     # asdsvc가 있는지 확인
     while True:
         output = self.check_process("ASDsvc.exe")
         if not output:
             # asd죽어 있는거야
             print "[-] ASDsvc is dead, Starting ASDsvc"
             pydbg_ads_thread = threading.Thread(target=self.start_ASDsvc)
             pydbg_ads_thread.setDaemon(0)
             pydbg_ads_thread.start()
             while self.ex_start_ASDsvc:
                 time.sleep(1)
             self.running_exe = False
             while self.check_process("v3lite.exe") == False:
                 time.sleep(1)
             os.system("taskkill /F /IM v3lite.exe")
             continue
         else:
             # asd 잘 살아 있으면
             self.pid_ads = str(output)
             self.dbg_ads.set_callback(EXCEPTION_ACCESS_VIOLATION,
                                       self.handler_access_violation)
             self.dbg_ads.attach(int(self.pid_ads, 10))
             print "[+] Attach debugger to ASDsvc : " + str(self.pid_ads)
             self.ex_dbg = False
             self.dbg_ads.run()
             break
示例#11
0
    def verifyUrl(self):
        # Attach pydbg to renderer process
        self.dbg = pydbg()
        self.dbg.attach(self.pids[1])
        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.checkAccessv)
        print("[+] Attach pid: %d" % (self.pids[1]))

        # Start monitor thread for no crash url
        monitorThread = threading.Thread(target=self.monitorDebugger)
        monitorThread.setDaemon(0)
        monitorThread.start()

        # Continue to run url
        self.dbg.run()

        time.sleep(1)
        self.getPid("iexplore.exe")
        for pid in self.pids:
            print("[+] Kill all ie processes: pid %d" % (pid))
            try:
                os.kill(pid, signal.SIGTERM)
            except:
                print("[-] Fail to kill!")

        # Wait monitor thread exit
        while self.isMon:
            time.sleep(1)
示例#12
0
    def hook(self, pid):
        #loadpid = dbg.pid

        print "[fuzz] init dbg ..."
        dbg = pydbg()
        dbg.cf = self.cf

        print "[fuzz] first process PID = %d" % pid
        pattern = r'\s*([0-9]*)\s*'
        count = 0
        while count <= 1:
            pbuf = os.popen("ps auxc | grep WebContent | awk '{print $2}'")
            pids = re.findall(pattern, pbuf.read())
            count = len(pids)
            print "[fuzz] find " + str(count - 1) + " Safari pids:" + str(pids)
        for pid in pids:
            if pid != 0:
                try:
                    print "[fuzz] attach dbg to %s ..." % (pid)
                    dbg.attach(int(pid))
                    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
                    dbg.set_callback(USER_CALLBACK_DEBUG_EVENT, time_out)
                    dbg.start_time = time.time()
                    return dbg
                except Exception, e:
                    print '[fuzz] attach dbg to %s failed!' % (pid)
                    print e
                    return None
    def __init__ (self, process_monitor, proc_name, ignore_pid=None):
        '''
        Instantiate a new PyDbg instance and register user and access violation callbacks.
        '''

        threading.Thread.__init__(self)

        self.process_monitor  = process_monitor
        self.proc_name        = proc_name
        self.ignore_pid       = ignore_pid

        self.access_violation = False
        self.unscheduled_exit = False
        self.active           = True
        self.dbg              = pydbg()
        self.pid              = None
        self.stopping_process = False

        # give this thread a unique name.
        self.setName("%d" % time.time())

        self.process_monitor.log("debugger thread initialized with UID: %s" % self.getName(), 5)

        # set the user callback which is response for checking if this thread has been killed.
        self.dbg.set_callback(USER_CALLBACK_DEBUG_EVENT,  self.dbg_callback_user)
        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.dbg_callback_access_violation)
        self.dbg.set_callback(EXIT_PROCESS_DEBUG_EVENT, self.dbg_callback_unscheduled_exit)
示例#14
0
def do_pydbg_dance (proggie, the_file):
    dbg = pydbg()
    dbg.load(proggie, the_file, show_window=False)
    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, av_handler)
    dbg.set_callback(EXCEPTION_BREAKPOINT,       bp_handler)

    dbg.run()
示例#15
0
def selectProcessID():
    """
	The interface for selecting the process to monitor

	Return:
	The process ID to attach
	"""
    processes = []
    dbg = pydbg()
    #Gather an array of active processes
    for (pid, pname) in dbg.enumerate_processes():
        processes.append([pid, pname])
    print "\n=== Please pick a process to monitor ===\n"
    print "Choice    Process Name"
    counter = 0
    #Prepare a choice list for the user
    for item in processes:
        print "[%3d]     %s" % (counter, item[1])
        counter += 1
    while 1:
        try:
            index = int(raw_input("\nChoice [n]:"))
            if index < 0 or index >= counter: raise
            break
        except KeyboardInterrupt:
            sys.exit(-1)
        except:
            print "That is not a choice."
    dbg = None
    return processes[index][0]  #Return the process ID of the user's choosing
示例#16
0
	def hookIE(self, dbg):
		loadpid = dbg.pid
		dbg.detach()
		dbg = pydbg()
		dbg.cf = self.cf
		print "IE first process PID = %d"%loadpid
		pattern = r'iexplore.exe\s*([0-9]*)\s*Console'
		count = 0
		while count<=1:
			p = os.popen('tasklist|find "iexplore"')
			pids = re.findall(pattern, p.read())
			count = len(pids)
		print "find IE pids:" + str(pids)
		for pid in pids:
			if loadpid == int(pid):
				continue
			try:
				dbg.attach(int(pid))
				dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, deal_accessv)
				print 'hook IE(pid=%s) success!'%(pid)
				return dbg
			except Exception, e:
				print 'hook IE(pid=%s) failed!'%(pid)
				print e
				return None
示例#17
0
def load_dbg():
	dbg = pydbg()
	
	dbg.set_callback(CREATE_PROCESS_DEBUG_EVENT, handler_create_process)
	dbg.set_callback(CREATE_THREAD_DEBUG_EVENT, handler_create_thread)
	dbg.set_callback(EXIT_PROCESS_DEBUG_EVENT, handler_exit_process)
	dbg.set_callback(EXIT_THREAD_DEBUG_EVENT, handler_exit_thread)
	dbg.set_callback(LOAD_DLL_DEBUG_EVENT, handler_load_dll)
	dbg.set_callback(UNLOAD_DLL_DEBUG_EVENT, handler_unload_dll)
	dbg.set_callback(OUTPUT_DEBUG_STRING_EVENT, handler_output_debug_string)
	dbg.set_callback(RIP_EVENT, handler_rip)

	dbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)	
	dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, handler_access_violation)
	dbg.set_callback(EXCEPTION_GUARD_PAGE, handler_guard_page)
	dbg.set_callback(EXCEPTION_SINGLE_STEP, handler_single_step)


	dbg.load(config.EXE_PATH, command_line = config.EXE_CMD, create_new_console=True)

	#dbg.load(r"E:\work\psiphon_new\psiphon3_unpacked.exe", create_new_console=True)
	#dbg.load(r"E:\work\DNS\DNS.exe", create_new_console=True)
	#dbg.load(r"E:\work\psiphon\psiphon3_old_unpacked.exe", create_new_console=True)
	#dbg.load(r"E:\work\psiphon\psiphon3_old.exe", create_new_console=True)
	#dbg.load(r"E:\work\ut\uTorrent.exe", create_new_console=True)	
	#dbg.load(r"C:\Moon\other\ftp_server.exe", create_new_console=True)
	#dbg.load(r'C:\DOCUME~1\moon\LOCALS~1\Temp\psiphon-tunnel-core.exe',r' --config "C:\Documents and Settings\moon\Application Data\Psiphon3\psiphon.config" --serverList "C:\Documents and Settings\moon\Application Data\Psiphon3\server_list.dat"',create_new_console=True)

	#dbg.load(r"C:\Program Files\Google\Chrome\Application\chrome.exe", create_new_console=True)
	#dbg.load(r"C:\Program Files\Astrill\astrill.exe", create_new_console=True)
	#dbg.load(r"C:\Moon\workspace\test_con_win32\Debug\test_con_win32.exe", create_new_console=True)	
	dbg.run()
示例#18
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"
示例#19
0
def selectProcessID():
    """
	The interface for selecting the process to attach

	Return:
	The process ID chosen by the user
	"""
    processes = []
    dbg = pydbg()
    #First we generate an array of active processes
    for (pid, pname) in dbg.enumerate_processes():
        processes.append([pid, pname])
    print "=== Please pick a process to attach ===\n"
    print "Choice    Process Name"
    pcounter = 0
    #And then we generate the choice list for the user
    for item in processes:
        print "[%3d]     %s" % (pcounter, item[1])
        pcounter += 1
    while 1:
        try:
            index = int(raw_input(
                "\nChoice [n]:"))  #If the input isn't a #, throw an exception
            if index < 0 or index >= pcounter:
                raise  #If the # is out of range, throw an exception
            break  #If input looks good, break loop and move on
        except KeyboardInterrupt:
            sys.exit(-1)
        except:
            print "That is not a choice."
    dbg = None
    return processes[index][0]
示例#20
0
    def start_debugger(self):

        self.dbg = pydbg()
        pid = self.dbg.load(self.exe_path)
        self.pid = self.dbg.pid

        self.dbg.run()
示例#21
0
def do_pydbg_dance(proggie, the_file):
    dbg = pydbg()
    dbg.load(proggie, the_file, show_window=False)
    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, av_handler)
    dbg.set_callback(EXCEPTION_BREAKPOINT, bp_handler)

    dbg.run()
示例#22
0
文件: procmon.py 项目: m0t/bongfuzz
	def __init__ (self, process_monitor, proc_name, ignore_pid=None):
		'''
		Instantiate a new PyDbg instance and register user and access violation callbacks.
		'''

		threading.Thread.__init__(self)
		#self.daemon = True

		self.process_monitor  = process_monitor
		self.proc_name		= proc_name
		self.ignore_pid	   = ignore_pid

		self.access_violation = False
		#self.active		   = True
		self.dbg			  = pydbg()
		self.pid			  = None
		#Process instance
		self.inst			= None
		#ASSUMPTION: only the first request is the one to be fuzzed, everything else is just related content,
		#after first req, flag is set to true and proxy will not fuzz (or post_send).
		#we could fuzz also related content, todo: modify handling of thread queue, test case saving 
		#(we now use test_number = thread number)
		self.FuzzReqSent = False

		# give this thread a unique name.
		self.setName("%d" % time.time())

		#self.process_monitor.log("debugger thread initialized with UID: %s" % self.getName(), 5)
		self.process_monitor.log("debugger thread initialized with UID: %s" % self.getName())

		# set the user callback which is response for checking if this thread has been killed.
		self.dbg.set_callback(USER_CALLBACK_DEBUG_EVENT,  self.dbg_callback_user)
		self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.dbg_callback_access_violation)
示例#23
0
 def Run(self):
     self.running = True
     self.dbg = pydbg()
     self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.Crash_Handler)
     args = "\"" + self.case_name + "\""
     self.dbg.load(self.target, args)
     self.dbg.run()
示例#24
0
    def start_debugger(self):

        self.dbg = pydbg()
        pid = self.dbg.load(self.exe_path)
        self.pid = self.dbg.pid

        self.dbg.run()
示例#25
0
    def __init__(self, process_monitor, proc_name, ignore_pid=None):
        '''
        Instantiate a new PyDbg instance and register user and access violation callbacks.
        '''

        threading.Thread.__init__(self)

        self.process_monitor = process_monitor
        self.proc_name = proc_name
        self.ignore_pid = ignore_pid

        self.access_violation = False
        self.active = True
        self.dbg = pydbg()
        self.pid = None

        # give this thread a unique name.
        self.setName("%d" % time.time())

        self.process_monitor.log(
            "debugger thread initialized with UID: %s" % self.getName(), 5)

        # set the user callback which is response for checking if this thread has been killed.
        self.dbg.set_callback(USER_CALLBACK_DEBUG_EVENT,
                              self.dbg_callback_user)
        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,
                              self.dbg_callback_access_violation)
示例#26
0
文件: hookAPIs.py 项目: vmkc/python
def main():
    print(
        "=======================================================================\r\n"
    )
    print(
        "HookAPIs - A tool to hook and monitor various parameter passed to APIs\r\n"
    )
    print("Author: Hardik Shah\r\n")
    print("Mail: [email protected]\r\n")
    print(
        "=======================================================================\r\n"
    )
    parser = OptionParser()
    parser.add_option("-i",
                      "--pid",
                      dest="pid",
                      help="pid of the process you want to hook",
                      metavar="PID")
    parser.add_option("-n",
                      "--pname",
                      dest="pname",
                      help="name of the process you want to hook",
                      metavar="PNAME")
    parser.add_option("-f",
                      "--fpath",
                      dest="fpath",
                      help="path of the executable you want to hook",
                      metavar="FPATH")
    (options, args) = parser.parse_args()
    if not options.pid and not options.pname and not options.fpath:
        parser.error('no argument given')
        sys.exit(2)

    dbg = pydbg()

    if options.pid:
        print "attaching to pid:", int(options.pid)
        dbg.attach(int(options.pid))
        dbg.set_callback(LOAD_DLL_DEBUG_EVENT, load_dll)
    elif options.pname:
        for pid, name in dbg.enumerate_processes():
            if name == options.pname:
                print "attaching to pid:", pid, name
                dbg.attach(pid)
                dbg.set_callback(LOAD_DLL_DEBUG_EVENT, load_dll)
                break
    elif options.fpath:
        print "loading and attaching to executable:", options.fpath
        dbg.set_callback(LOAD_DLL_DEBUG_EVENT, load_dll)
        dbg.set_callback(
            EXCEPTION_ACCESS_VIOLATION, check_accessv
        )  #Create the callback for the exception access violation
        dbg.load(options.fpath)

    #dbg.set_callback(LOAD_DLL_DEBUG_EVENT, load_dll)
    is_hook = 0
    hooks = None

    dbg.debug_event_loop()
示例#27
0
def start_debugger(self):
	print "[*]starting denbugger for iteration:%d" % self.iteration
	self.running=True
	self.dbg=pydbg()
	self.dbg.set_callback(EXECEPTION_ACCESS_VIOLATON,self.check_accessv)
	self.dbg.pid=self.dbg.load(self.exe_path,"test.%s" % self.ext)
	self.pid=self.dbg.pid
	self.dbg.run()
示例#28
0
 def start_debugger(self):
     print "[*] Starting debugger for iteration: %d" % self.iteration
     self.running = True
     self.dbg = pydbg()
     self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,self.check_accessv)
     pid = self.dbg.load(self.exe_path,"test.%s" % self.ext)
     self.pid = self.dbg.pid
     self.dbg.run()         
示例#29
0
def pydbg_bphandle(): 
    dbg = pydbg()
    pid = raw_input("Enter the printf_loop.py PID: ")
    dbg.attach(int(pid))
    printf_address = dbg.func_resolve("msvcrt", "printf")
    # Set the breakpoint with the printf_randomizer function defined as a callback
    dbg.bp_set(printf_address, description="printf_address", handler=printf_randomizer)
    dbg.run()
示例#30
0
def Run2Monitor(fileName):
	global running,dbg,pid
	dbg = pydbg()
	running = True

	dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, checkav)
	dbg.set_callback(0xC000001D, checkav)
	pid = dbg.load(r"C:\Program Files (x86)\Hantools\HanSee\HanSee.exe",fileName)
	dbg.run()
示例#31
0
def start_safari():
    debug = pydbg()
    m_conmsg("Starting Safari",0)
    safari_process = subprocess.Popen(['/Applications/Safari.app/Contents/MacOS/SafariForWebKitDevelopment', ''], env=dict(os.environ, DYLD_INSERT_LIBRARIES="/usr/lib/libgmalloc.dylib"), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    debug.attach(safari_process.pid)
    print "DONE"
    time.sleep(0.6)
    m_ascript('tell application "Safari" to close every window') 
    m_ascript('tell application "Safari" to open location "about:blank"') 
示例#32
0
def main():

    target = sys.argv[1]
    dbg = pydbg()
    dbg.load(target, " ".join(sys.argv[2:]))

    pe = pefile.PE(target)
    entrypoint = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
    dbg.bp_set(entrypoint, handler=hook_install)
    dbg.run()
示例#33
0
 def __init__(self):
     self.processName = "pywindbg"
     self.dbg = pydbg()
     self.setupExeptionHandlers()
     self.verbose = False
     self.pidAttached = 0
     self.executableLoaded = False
     self.executablePath = ''
     self.pidLoaded = False
     self.debug = False
def main():

    target = sys.argv[1]
    dbg = pydbg()
    dbg.load(target, " ".join(sys.argv[2:]))

    pe = pefile.PE(target)
    entrypoint = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
    dbg.bp_set(entrypoint,handler=hook_install)
    dbg.run()
 def debug_process(self):
     
     self.running = True
     self.dbg = pydbg()
     # Install our custom handler
     self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.accessv_handler)
     self.dbg.load(self.modulePath, self.mutated_file)
     
     self.pid = self.dbg.pid
     self.dbg.run()
    def debug_process(self):

        self.running = True
        self.dbg = pydbg()
        # Install our custom handler
        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.accessv_handler)
        self.dbg.load(self.modulePath, self.mutated_file)

        self.pid = self.dbg.pid
        self.dbg.run()
示例#37
0
 def __init__(self):
     self.pids = []
     self.dbg = pydbg()
     self.isAccessv = False
     self.isVul = False
     self.isMon = False
     self.isInAv = False
     self.timeout = 1
     self.nullPtrThr = -1
     self.avBlackList = [r"cmp byte \[0x70\],0x0 from"]
示例#38
0
 def start_debugger(self):
     
     print "[*] Starting debugger for iteration: %d" % self.iteration
     self.running = True
     self.dbg = pydbg()
     
     self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.check_accessv)
     pid = self.dbg.load(self.exe_path, "%s%d.%s" % (self.test_file, self.iteration, self.ext))        
     self.pid = self.dbg.pid
     self.dbg.run()
示例#39
0
def startfuzzerPYDBG():
	print '[+] Starting Fuzzing..'
	while 1:
		genTestCase()
		dbg = pydbg()
		dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, AccessViolationHandler)
		dbg.set_callback(EXCEPTION_GUARD_PAGE, AccessViolationHandler)
		thread.start_new_thread(StillRunning, (dbg, ))
		dbg.load(r"C:\Windows\system32\wscript.exe",TESTCASENAME , show_window=True)
		dbg.run()
    def start_debugger(self):

        self.running = True
        self.dbg = pydbg()

        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,self.check_accessv)
        pid = self.dbg.load(self.exe_path, self.tmp_file)

        self.pid = self.dbg.pid
        self.dbg.run()
示例#41
0
 def pydbg_set_locale (self, host, port):
     if host not in ("localhost", "127.0.0.1") and type(port) is int:
         try:
             self.parent.pydbg = pydbg_client(host, port)
             self.parent.status_bar.SetStatusText("Successfully connected to PyDbg server on %s:%d" % (host, port))
             self.parent.status_bar.SetStatusText("PyDbg: %s" % host, 3)
         except:
             self.parent.status_bar.SetStatusText("Failed connecting to PyDbg server on %s:%d" % (host, port))
     else:
         self.parent.pydbg = pydbg()
示例#42
0
 def __init__(self):
     self.pids = []
     self.dbg = pydbg()
     self.isAccessv = False
     self.isVul = False
     self.isMon = False
     self.isInAv = False
     self.timeout = 1
     self.nullPtrThr = 0x1000
     self.avBlackList = [r"cmp byte \[0x70\],0x0 from"]
示例#43
0
 def __init__(self):
     self.dbg = pydbg()
     self.dbg.start_time = time.time()
     self.cf = conf.conf()
     #self.crasher = fuzzutil.crasher(self.cf)
     self.InitPage = 'http://' + self.cf.host + ':' + self.cf.port + '/'
     print '[maim] Server: ' + self.cf.host + ':' + self.cf.port
     print '[main] Taregt: ' + self.cf.target
     print '[main] Image: ' + self.cf.image
     os.system('mkdir logs 2> null')
     print '[main] LogPath: ./logs/'
示例#44
0
	def checkierunning(self):
		'''
		Parse process list and return a list with all iexplore.exe PIDs.
		'''
		ie_pids = []
		dbg1 = pydbg()
		for (pid,name) in dbg1.enumerate_processes():
			if name == 'iexplore.exe':
				ie_pids.append(pid)
		del dbg1
		return ie_pids
示例#45
0
文件: vult3.py 项目: n0rmen/vult3
    def __init__(self, hooks_db):
        """Initialize

        Keyword Arguments:
        hooks_db -- Reference to the HOOKS DB.

        """
        self.dbg = pydbg()
        self.dbg.get_debug_privileges()
        self.FUNCTION_HOOKS = hooks_db
        self.verbose = False
示例#46
0
def main():
	dbg = pydbg()
	pid = raw_input ('Enter PID : ')
	dbg.attach(int(pid))
	print '[+] Attached'
	#HeapWalk(dbg)
	try:
		mb = dbg.func_resolve_debuggee('user32.dll','MessageBoxA')
		dbg.bp_set(mb,handler=HeapWalk)
	except Exception,e:
		print '[+] Failed'
示例#47
0
    def execute(self, command, args):
        self.output = None
        dbg = pydbg()
        dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.handle_av)
        dbg.set_callback(0xC000001D, self.handle_av) # illegal instruction
        dbg.set_callback(USER_CALLBACK_DEBUG_EVENT, self.timeout_callback)
        dbg.load(command, command_line=args)
        dbg.start_time = time()
        dbg.run()

        return self.output
示例#48
0
 def __init__(self):
     self.dbg = pydbg()
     self.dbg.start_time = time.time()
     self.cf = conf.conf()
     #self.crasher = fuzzutil.crasher(self.cf)
     self.InitPage = 'http://'+self.cf.host+':'+self.cf.port+'/'
     print '[maim] Server: ' + self.cf.host+':'+self.cf.port
     print '[main] Taregt: ' + self.cf.target
     print '[main] Image: ' + self.cf.image
     os.system('mkdir logs 2> null')
     print '[main] LogPath: ./logs/'
示例#49
0
文件: iofuzz.py 项目: XinliNiu/iofuzz
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()
示例#50
0
def pydbg_valunfind():
    dbg = pydbg()
    pid = int(raw_input("Enter the PID you wish to monitor: "))
    dbg.attach(pid)
    # Track down all of the dangerous functions and set breakpoints 
    for func in dangerous_functions.keys():
        func_address = dbg.func_resolve( dangerous_functions[func],func )
        print "[*] Resolved breakpoint: %s -> 0x%08x" % ( func, func_address ) 
        dbg.bp_set( func_address, handler = danger_handler ) 
        dangerous_functions_resolved[func_address] = func
    dbg.set_callback( EXCEPTION_ACCESS_VIOLATION, access_violation_handler ) 
    dbg.set_callback( EXCEPTION_SINGLE_STEP, single_step_handler )
    dbg.run()
示例#51
0
	def attach_debugger(self,pid,PageHeap):
		# Attach debugger to Parent IE Process Broker
		try:
			print ('[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Attaching IE process to Debugeer :'+str(pid))
			dbg_p = pydbg()
			dbg_p.attach(pid)
			dbg_p.set_callback(EXCEPTION_ACCESS_VIOLATION, self.av_handler)	# Normal Read/Write AV
			if PageHeap:
				print ('[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S")+' GUARD_PAGE Access will be monitored')
				dbg_p.set_callback(EXCEPTION_GUARD_PAGE, self.av_handler)		# Required while page heap is enabled
			dbg_p.run()
		except Exception, e:
			print ('[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Could not attach to process..'+str(pid)+str(e))	
			self.killie()
示例#52
0
def main():
    target = r"F:\MYPROJECTS\Ex15\Debug\Ex15.exe"

    pe = pefile.PE(target)
    dbg = pydbg()

    #if it's a console program, so set create_new_console = True
    dbg.load(target, create_new_console=True)

    #set a break point at the entry point
    entry_point = pe.OPTIONAL_HEADER.AddressOfEntryPoint + pe.OPTIONAL_HEADER.ImageBase
    dbg.bp_set(entry_point, handler=entry_point_handler)

    dbg.run()
示例#53
0
	def __init__(self, test_id):
		threading.Thread.__init__(self)
		
		self.keep_file = False
		self.test_id = test_id
		self.current_testcase = 'sample_%d.flv' % test_id
		self.sample_deleted = False
		self.lock = threading.Lock()
		self.event = threading.Event()
		
		self.dbg = pydbg()
		self.dbg.pydbg_log = self.log
		self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.handle_av)
		self.dbg.set_callback(USER_CALLBACK_DEBUG_EVENT, self.handle_timeout)
示例#54
0
文件: main.py 项目: BwRy/visdasm
def main():
	print '[+] Reading configuration file'
	parseconfig()
	global hit_seq
	hit_seq = []
	global entry
	pe = pefile.PE(exe_file)
	entry = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
	startjs()	
	print '[+] Starting Application for the first time'
	dbg = pydbg()
	dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, crash_handler)
	#thread.start_new_thread(stillrunning, (dbg, ))#still running huhh??
	dbg.load(exe_file,input_file)
	dbg.bp_set(entry,handler=set_all_jmp_bp)
	dbg.run()
	print '[+] Running the target application second time to recored dereference information'
	dbg = pydbg()
	dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, crash_handler1)
	#thread.start_new_thread(stillrunning, (dbg, ))#still running huhh??
	dbg.load(exe_file,input_file)
	dbg.bp_set(entry,handler=set_all_addr_bp)
	dbg.run()
示例#55
0
def startDBG(pid):
    global forcedExit
    print "[+] Starting a new pydbg instance for pid %d" % (pid)
    dbg = pydbg()
    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, avHandler)
    while True:
        try:
            if dbg.attach(pid):
                return dbg
            else:
                return False
        except:
            print "[D] Error in attaching pydbg"
            forcedExit=True
            sys.exit()
示例#56
0
 def __init__(self):
     atexit.register(self.atExit)
     self.logFile = open('log.txt', 'a', 0)
     print >>self.logFile, 40 * '='
     print >>self.logFile, str.format('Started ItemAlertPoE version {0} at {1!s}.', ALERT_VERSION, datetime.datetime.now())
     print >>self.logFile, str.format('Python version: {0!s}', sys.version_info)
     self.dbg = pydbg()
     self.dbg.attach(self.getProcessId())
     self.baseAddress = self.getBaseAddress()
     adjustment = self.baseAddress - 0x00400000
     ItemAlert.BP0 += adjustment
     ItemAlert.BP1 += adjustment
     ItemAlert.BP2 += adjustment
     self.lastPacketBufferAddress = 0
     self.lastPacketSize = 0
示例#57
0
def debug_process(pid):
    """Create a debugger instance and attach to ovas PID"""
    
    dbg = pydbg()
    dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, _access_violation_handler)

    while True:
        try:
            print("[*] Attaching debugger to pid: {}.".format(pid))
            if dbg.attach(pid):
                return dbg
            else:
                return False
        except Exception as e:
            print("[*] Error while attaching: {}.".format(e.message))
            return False
示例#58
-1
    def start_debugger(self):

        self.running = True
        self.dbg = pydbg()

        self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION,self.check_accessv)
        pid = self.dbg.load(self.exe_path, self.tmp_file)

        self.pid = self.dbg.pid
        self.dbg.run()
示例#59
-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)