一、开发内容介绍
为了对一个进程进行调试,你首先必须用一些方法把调试器和进程连接起来。所以, 我
们的调试器要不然就是装载一个可执行程序然后运行它, 要不然就是动态的附加到一个运行
的进程。Windows 的调试接口(Windows debugging API)提供了一个非常简单的方法完成
这两点。
运行一个程序和附加到一个程序有细微的差别。 打开一个程序的优点在于他能在程序运
行任何代码之前完全的控制程序。 这在分析病毒或者恶意代码的时候非常有用。 附加到一个
进程,仅仅是强行的进入一个已经运行了的进程内部,它允许你跳过启动部分的代码,分析
你感兴趣的代码。你正在分析的地方也就是程序目前正在执行的地方。
第一种方法,其实就是从调试器本身调用这个程序(调试器就是父进程,对被调试进程
的控制权限更大) 。在 Windows 上创建一个进程用 CreateProcessA()函数。将特定的标志传
进这个函数,使得目标进程能够被调试。
目标:使用CreateProcess打开一个进程
二、需要用到的winAPI函数
函数原型:
创建两个 Python 文件 my_debugger.py 和 my_debugger_defines.py。 我们将创建一个父类
debugger() 接着逐渐的增加各种调试函数。另外,把所有的结构,联合,常量放 到
my_debugger_defines.py 方便以后维护。
# my_debugger_defines.py
from ctypes import *
# Let's map the Microsoft types to ctypes for clarity
WORD = c_ushort
DWORD = c_ulong
LPBYTE = POINTER(c_ubyte)
LPTSTR = POINTER(c_char)
HANDLE = c_void_p
# Constants
DEBUG_PROCESS = 0x00000001
CREATE_NEW_CONSOLE = 0x00000010
# Structures for CreateProcessA() function
class STARTUPINFO(Structure):
_fields_ = [
("cb", DWORD),
("lpReserved", LPTSTR),
("lpDesktop", LPTSTR),
("lpTitle", LPTSTR),
("dwX", DWORD),
("dwY", DWORD),
("dwXSize", DWORD),
("dwYSize", DWORD),
("dwXCountChars", DWORD),
("dwYCountChars", DWORD),
("dwFillAttribute",DWORD),
("dwFlags", DWORD),
("wShowWindow", WORD),
("cbReserved2", WORD),
("lpReserved2", LPBYTE),
("hStdInput", HANDLE),
("hStdOutput", HANDLE),
("hStdError", HANDLE),
]
class PROCESS_INFORMATION(Structure):
_fields_ = [
("hProcess", HANDLE),
("hThread", HANDLE),
("dwProcessId", DWORD),
("dwThreadId", DWORD),
]
# my_debugger.py
from ctypes import *
from my_debugger_defines import *
kernel32 = windll.kernel32
class debugger():
def __init__(self):
pass
def load(self,path_to_exe):
# dwCreation flag determines how to create the process
# set creation_flags = CREATE_NEW_CONSOLE if you want
# to see the calculator GUI
creation_flags = DEBUG_PROCESS
# instantiate the structs
startupinfo = STARTUPINFO()
process_information = PROCESS_INFORMATION()
# The following two options allow the started process
# to be shown as a separate window. This also illustrates
# how different settings in the STARTUPINFO struct can affect
# the debuggee.
startupinfo.dwFlags = 0x1
startupinfo.wShowWindow = 0x0
# We then initialize the cb variable in the STARTUPINFO struct
# which is just the size of the struct itself
startupinfo.cb = sizeof(startupinfo)
if kernel32.CreateProcessA(path_to_exe,
None,
None,
None,
None,
creation_flags,
None,
None,
byref(startupinfo),
byref(process_information)):
print "[*] We have successfully launched the process!"
print "[*] PID: %d" % process_information.dwProcessId
else:
print "[*] Error: 0x%08x." % kernel32.GetLastError()
#my_test.py
import my_debugger
debugger = my_debugger.debugger()
debugger.load("C:\WINDOWS\system32\calc.exe")
运行结果:
Connected to pydev debugger (build 145.844)
[*] We have successfully launched the process!
[*] PID: 4720