winappdbg.process
Process instrumentation.
This module contains the logic for handling process lifetime, memory, etc.
- class winappdbg.process.Process(dwProcessId, hProcess=None, fileName=None)
Interface to a process. Contains threads and modules snapshots.
- Variables:
dwProcessId – Global process ID. Use
get_pid()instead.hProcess – Handle to the process. Use
get_handle()instead.fileName – Filename of the main module. Use
get_filename()instead.
- clean_exit(dwExitCode=0, bWait=False, dwTimeout=None)
Injects a new thread to call ExitProcess(). Optionally waits for the injected thread to finish.
Warning
Setting
bWaittoTruewhen the process is frozen by a debug event will cause a deadlock in your debugger.- Parameters:
dwExitCode (int) – Process exit code.
bWait (bool) –
Trueto wait for the process to finish.Falseto return immediately.dwTimeout (int) – Optional timeout value in milliseconds. Ignored if
bWaitisFalse.
- Raises:
WindowsError – An exception is raised on error.
- clear()
Clears the snapshot of threads and modules.
- close_handle()
Closes the handle to the process.
Note
Normally you don’t need to call this method. All handles created by WinAppDbg are automatically closed when the garbage collector claims them. So unless you’ve been tinkering with it, setting
hProcesstoNoneshould be enough.
- debug_break()
Triggers the system breakpoint in the process.
- Raises:
WindowsError – On error an exception is raised.
- disassemble(lpAddress, dwSize)
Disassemble instructions from the address space of the process.
- Parameters:
lpAddress (int) – Memory address where to read the code from.
dwSize (int) – Size of binary code to disassemble.
- Return type:
list[tuple[int, int, str, str]]
- Returns:
List of tuples. Each tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- disassemble_around(lpAddress, dwSize=64)
Disassemble around the given address.
- Parameters:
lpAddress (int) – Memory address where to read the code from.
dwSize (int) – Delta offset. Code will be read from
lpAddress - dwSizetolpAddress + dwSize.
- Return type:
list[tuple[int, int, str, str]]
- Returns:
List of tuples. Each tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- disassemble_around_pc(dwThreadId, dwSize=64)
Disassemble around the program counter of the given thread.
- Parameters:
dwThreadId (int) – Global thread ID. The program counter for this thread will be used as the disassembly address.
dwSize (int) – Delta offset. Code will be read from
pc - dwSizetopc + dwSize.
- Return type:
list[tuple[int, int, str, str]]
- Returns:
List of tuples. Each tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- disassemble_current(dwThreadId)
Disassemble the instruction at the program counter of the given thread.
- Parameters:
dwThreadId (int) – Global thread ID. The program counter for this thread will be used as the disassembly address.
- Return type:
tuple[int, int, str, str]
- Returns:
The tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- disassemble_instruction(lpAddress)
Disassemble the instruction at the given memory address.
- Parameters:
lpAddress (int) – Memory address where to read the code from.
- Return type:
tuple[int, int, str, str]
- Returns:
The tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- disassemble_string(lpAddress, code)
Disassemble instructions from a block of binary code.
- Parameters:
lpAddress (int) – Memory address where the code was read from.
code (bytes) – Binary code to disassemble.
- Return type:
list[tuple[int, int, str, str]]
- Returns:
List of tuples. Each tuple represents an assembly instruction and contains:
Memory address of instruction.
Size of instruction in bytes.
Disassembly line of instruction.
Hexadecimal dump of instruction.
- Raises:
NotImplementedError – No compatible disassembler was found for the current platform.
- flush_instruction_cache()
Flush the instruction cache. This is required if the process memory is modified and one or more threads are executing nearby the modified memory region.
See: http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958
- Raises:
WindowsError – Raises exception on error.
- free(lpAddress)
Frees memory from the address space of the process.
- Parameters:
lpAddress (int) – Address of memory to free. Must be the base address returned by
malloc().- Raises:
WindowsError – On error an exception is raised.
- generate_memory_map(minAddr=None, maxAddr=None)
Returns a
Regeneratorthat can iterate indefinitely over the memory map to the process address space.Optionally restrict the map to the given address range.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
Regenerator[win32.MemoryBasicInformation]
- Returns:
List of memory region information objects.
- generate_memory_snapshot(minAddr=None, maxAddr=None)
Returns a
Regeneratorthat allows you to iterate through the memory contents of a process indefinitely.It’s basically the same as the
take_memory_snapshot()method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty.Example:
# print(the memory contents of a process.) process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print(HexDump.hexblock(mbi.content, mbi.BaseAddress)) finally: process.resume()
The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen.
The snapshot can be iterated more than once. Each time it’s iterated the memory contents of the process will be fetched again.
You can also iterate the memory of a dead process, just as long as the last open handle to it hasn’t been closed.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
Regenerator[win32.MemoryBasicInformation]
- Returns:
Generator that when iterated returns memory region information objects. Two extra properties are added to these objects:
filename: Mapped filename, orNone.content: Memory contents, orNone.
- generate_minidump(filename, DumpType=None, ContextRecord=None, ExceptionParam=None, UserStreamParam=None, CallbackParam=None)
Generates a minidump file for the process.
- Parameters:
filename (str) – Path to the output minidump file (.dmp).
DumpType (int) –
Type of information to include in the minidump. Defaults to
MiniDumpNormal. Can be a combination ofMINIDUMP_TYPEflags fromwin32. Common values:win32.MiniDumpNormal- Include only basic informationwin32.MiniDumpWithFullMemory- Include all accessible memorywin32.MiniDumpWithDataSegs- Include data segmentswin32.MiniDumpWithHandleData- Include handle informationwin32.MiniDumpWithThreadInfo- Include thread information
Multiple flags can be combined with bitwise OR.
ContextRecord (ctypes pointer or None) – Optional pointer to a
CONTEXTstructure for the calling thread. Used when generating a dump from an exception handler to capture the thread state. Architecture-specific (CONTEXT_i386,CONTEXT_amd64, orCONTEXT_arm64). Defaults toNone.ExceptionParam (ctypes pointer or None) – Optional pointer to a
MINIDUMP_EXCEPTION_INFORMATIONstructure. Used when generating a dump from an exception handler. Defaults toNone.UserStreamParam (ctypes pointer or None) – Optional pointer to a
MINIDUMP_USER_STREAM_INFORMATIONstructure for user-defined information to include in the minidump. Defaults toNone.CallbackParam (ctypes pointer or None) – Optional pointer to a
MINIDUMP_CALLBACK_INFORMATIONstructure for customizing minidump generation. Defaults toNone.
- Raises:
WindowsError – On error an exception is raised.
Example:
# Generate a basic minidump process.generate_minidump("crash.dmp") # Generate a full memory dump process.generate_minidump( "full_crash.dmp", win32.MiniDumpWithFullMemory | win32.MiniDumpWithHandleData ) # Advanced: Generate from exception handler with context # try: # # ... code that might crash ... # except: # exc_info = win32.MINIDUMP_EXCEPTION_INFORMATION() # context = win32.CONTEXT() # # ... fill in exception info and context ... # process.generate_minidump( # "exception.dmp", # ContextRecord=context, # ExceptionParam=exc_info # )
Note
This method requires PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights to the process. If handle information is requested (e.g., with MiniDumpWithHandleData), PROCESS_DUP_HANDLE is also required and will be automatically requested.
- get_arch()
- Return type:
str
- Returns:
The architecture in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be
ARCH_I386, but the value ofSystem.archwill beARCH_AMD64.On ARM64 systems, this can detect: - Native ARM64 processes - x64 processes running under emulation - x86 processes running under emulation
- get_bits()
- Return type:
int
- Returns:
The number of bits in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be
32, but the value ofarchwill be64.
- get_command_line()
Retrieves the command line with which the program was started.
- Return type:
str
- Returns:
Command line string.
- Raises:
WindowsError – On error an exception is raised.
- get_command_line_block()
Retrieves the command line block memory address and size.
- Return type:
tuple(int, int)
- Returns:
Tuple with the memory address of the command line block and it’s maximum size in Unicode characters.
- Raises:
WindowsError – On error an exception is raised.
- get_dep_policy()
Retrieves the DEP (Data Execution Prevention) policy for this process.
Note
This method is only available in Windows XP SP3 and above, and only for 32 bit processes. It will fail in any other circumstance.
- Return type:
tuple(int, int)
- Returns:
The first member of the tuple is the DEP flags. It can be a combination of the following values:
0: DEP is disabled for this process.
1: DEP is enabled for this process. (
PROCESS_DEP_ENABLE)2: DEP-ATL thunk emulation is disabled for this process. (
PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION)
The second member of the tuple is the permanent flag. If
Truethe DEP settings cannot be changed in runtime for this process.- Raises:
WindowsError – On error an exception is raised.
- get_entry_point()
Alias to
process.get_main_module().get_entry_point().- Return type:
int
- Returns:
Address of the entry point of the main module.
- get_environment(fUnicode=None)
Retrieves the environment with which the program is running.
Note
Duplicated keys are joined using null characters. To avoid this behavior, call
get_environment_variables()instead and convert the results to a dictionary directly, like this:dict(process.get_environment_variables())See also
GuessStringType- Parameters:
fUnicode (bool) –
Trueto return a list of Unicode strings,Falseto return a list of ANSI strings, orNoneto return whatever the default is for string types.- Return type:
dict[str, str]
- Returns:
Dictionary of environment keys and values.
- Raises:
WindowsError – On error an exception is raised.
- get_environment_block()
Retrieves the environment block memory address for the process.
Note
The size is always enough to contain the environment data, but it may not be an exact size. It’s best to read the memory and scan for two null wide chars to find the actual size.
- Return type:
tuple(int, int)
- Returns:
Tuple with the memory address of the environment block and it’s size.
- Raises:
WindowsError – On error an exception is raised.
- get_environment_variables()
Retrieves the environment variables with which the program is running.
- Return type:
list[tuple[str, str]]
- Returns:
Environment keys and values as found in the process memory.
- Raises:
WindowsError – On error an exception is raised.
- get_exit_code()
- Return type:
int
- Returns:
Process exit code, or
STILL_ACTIVEif it’s still alive.
Warning
If a process returns
STILL_ACTIVEas its exit code, you may not be able to determine if it’s active or not with this method. Useis_alive()to check if the process is still active. Alternatively, you can callget_handle()to get the handle object and then call thewaitmethod on it to wait until the process finishes running.
- get_exit_time()
Determines when has this process finished running. If the process is still alive, the current time is returned instead.
- Return type:
SYSTEMTIME- Returns:
Process exit time.
- get_filename()
- Return type:
str
- Returns:
Filename of the main module of the process.
- get_handle(dwDesiredAccess=2035711)
Returns a handle to the process with at least the access rights requested.
Note
If a handle was previously opened and has the required access rights, it’s reused. If not, a new handle is opened with the combination of the old and new access rights.
- Parameters:
dwDesiredAccess (int) – Desired access rights. Defaults to
win32.PROCESS_ALL_ACCESS. See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx- Return type:
ProcessHandle
- Returns:
Handle to the process.
- Raises:
WindowsError – It’s not possible to open a handle to the process with the requested access rights. This typically happens because the target process is a system process and the debugger is not runnning with administrative rights.
- get_image_base()
- Return type:
int
- Returns:
Image base address for the process main module.
- get_image_name()
- Return type:
str
- Returns:
Filename of the process main module.
This method does it’s best to retrieve the filename. However sometimes this is not possible, so
Nonemay be returned instead.
- get_mapped_filenames(memoryMap=None)
Retrieves the filenames for memory mapped files in the debugee.
- Parameters:
memoryMap (list[win32.MemoryBasicInformation]) – Optional. Memory map returned by
get_memory_map(). If not given, the current memory map is used.- Return type:
dict[int, str]
- Returns:
Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible.
- get_memory_map(minAddr=None, maxAddr=None)
Produces a memory map to the process address space.
Optionally restrict the map to the given address range.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
list[win32.MemoryBasicInformation]
- Returns:
List of memory region information objects.
- get_package_full_name()
Retrieves the package full name for the process.
This method is only applicable to packaged processes (Windows Store apps, UWP apps, etc.). For traditional desktop applications, this method will return
None.Requires Windows 8 or later.
- Return type:
str or None
- Returns:
Package full name if the process is packaged,
Noneotherwise.
- get_peb()
Returns a copy of the PEB. To dereference pointers in it call
read_structure().- Return type:
PEB- Returns:
PEB structure.
- Raises:
WindowsError – An exception is raised on error.
- get_peb_address()
Returns a remote pointer to the PEB.
- Return type:
int
- Returns:
Remote pointer to the
PEBstructure. ReturnsNoneon error.
- get_pid()
- Return type:
int
- Returns:
Process global ID.
- get_running_time()
Determines how long has this process been running.
- Return type:
int
- Returns:
Process running time in milliseconds.
- get_services()
Retrieves the list of system services that are currently running in this process.
- Return type:
list of
ServiceStatusProcessEntry- Returns:
List of service status descriptors.
- get_start_time()
Determines when has this process started running.
- Return type:
SYSTEMTIME- Returns:
Process start time.
- get_windows()
Get the list of top-level windows owned by this process.
- Return type:
list of
Window- Returns:
List of top-level windows for this process.
- inject_code(payload, lpParameter=0)
Injects relocatable code into the process memory and executes it.
Warning
Don’t forget to free the memory when you’re done with it! Otherwise you’ll be leaking memory in the target process.
See also
- Parameters:
payload (str) – Relocatable code to run in a new thread.
lpParameter (int) – Optional parameter to be pushed in the stack.
- Return type:
tuple[Thread, int]
- Returns:
The injected
Threadobject and the memory address where the code was written.- Raises:
WindowsError – An exception is raised on error.
- inject_dll(dllname, procname=None, lpParameter=0, bWait=True, dwTimeout=None)
Injects a DLL into the process memory.
Warning
Setting
bWaittoTruewhen the process is frozen by a debug event will cause a deadlock in your debugger.Warning
This involves allocating memory in the target process. This is how the freeing of this memory is handled:
If the
bWaitflag is set toTruethe memory will be freed automatically before returning from this method.If the
bWaitflag is set toFalse, the memory address is set as theThread.pInjectedMemoryproperty of the returned thread object.Debugobjects freeThread.pInjectedMemoryautomatically both when it detaches from a process and when the injected thread finishes its execution.The
Thread.kill()method also freesThread.pInjectedMemoryautomatically, even if you’re not attached to the process.
You could still be leaking memory if not careful. For example, if you inject a dll into a process you’re not attached to, you don’t wait for the thread’s completion and you don’t kill it either, the memory would be leaked.
See also
- Parameters:
dllname (str) – Name of the DLL module to load.
procname (str) – Optional procedure to call when the DLL is loaded.
lpParameter (int) – Optional parameter to the
procnameprocedure.bWait (bool) –
Trueto wait for the process to finish.Falseto return immediately.dwTimeout (int) – Optional timeout value in milliseconds. Ignored if
bWaitisFalse.
- Return type:
- Returns:
Newly created thread object. If
bWaitis set toTruethe thread will be dead, otherwise it will be alive.- Raises:
NotImplementedError – The target platform is not supported. Currently calling a procedure in the library is only supported in the i386 architecture.
WindowsError – An exception is raised on error.
- is_address_commited(address)
Determines if an address belongs to a commited page.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited page.- Raises:
WindowsError – An exception is raised on error.
- is_address_copy_on_write(address)
Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited, copy-on-write page.- Raises:
WindowsError – An exception is raised on error.
- is_address_executable(address)
Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited and executable page.- Raises:
WindowsError – An exception is raised on error.
- is_address_executable_and_writeable(address)
Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions.
Looking for writeable and executable pages is important when exploiting a software vulnerability.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited, writeable and executable page.- Raises:
WindowsError – An exception is raised on error.
- is_address_free(address)
Determines if an address belongs to a free page.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a free page.- Raises:
WindowsError – An exception is raised on error.
- is_address_guard(address)
Determines if an address belongs to a guard page.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a guard page.- Raises:
WindowsError – An exception is raised on error.
- is_address_readable(address)
Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited and readable page.- Raises:
WindowsError – An exception is raised on error.
- is_address_reserved(address)
Determines if an address belongs to a reserved page.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a reserved page.- Raises:
WindowsError – An exception is raised on error.
- is_address_valid(address)
Determines if an address is a valid user mode address.
- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address is a valid user mode address.- Raises:
WindowsError – An exception is raised on error.
- is_address_writeable(address)
Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions.
Note
Returns always
Falsefor kernel mode addresses.- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address belongs to a commited and writeable page.- Raises:
WindowsError – An exception is raised on error.
- is_alive()
- Return type:
bool
- Returns:
Trueif the process is currently running.
- is_buffer(address, size)
Determines if the given memory area is a valid code or data buffer.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is a valid code or data buffer,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_buffer_copy_on_write(address, size)
Determines if the given memory area is marked as copy-on-write.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is marked as copy-on-write,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_buffer_executable(address, size)
Determines if the given memory area is executable.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is executable,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_buffer_executable_and_writeable(address, size)
Determines if the given memory area is writeable and executable.
Looking for writeable and executable pages is important when exploiting a software vulnerability.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is writeable and executable,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_buffer_readable(address, size)
Determines if the given memory area is readable.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is readable,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_buffer_writeable(address, size)
Determines if the given memory area is writeable.
Note
Returns always
Falsefor kernel mode addresses.See also
- Parameters:
address (int) – Memory address.
size (int) – Number of bytes. Must be greater than zero.
- Return type:
bool
- Returns:
Trueif the memory area is writeable,Falseotherwise.- Raises:
ValueError – The size argument must be greater than zero.
WindowsError – On error an exception is raised.
- is_debugged()
Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg.
- Return type:
bool
- Returns:
Trueif the process has a debugger attached.
Warning
May return inaccurate results when some anti-debug techniques are used by the target process.
Note
To know if a process currently being debugged by a
Debugobject, callis_debugee()instead.
- is_pointer(address)
Determines if an address is a valid code or data pointer.
That is, the address must be valid and must point to code or data in the target process.
- Parameters:
address (int) – Memory address to query.
- Return type:
bool
- Returns:
Trueif the address is a valid code or data pointer.- Raises:
WindowsError – An exception is raised on error.
- is_wow64()
Determines if the process is running under WOW64.
- Return type:
bool
- Returns:
Trueif the process is running under WOW64. That is, a 32-bit application running in a 64-bit Windows.Falseif the process is either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows.- Raises:
WindowsError – On error an exception is raised.
See: http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx
- iter_memory_map(minAddr=None, maxAddr=None)
Produces an iterator over the memory map to the process address space.
Optionally restrict the map to the given address range.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
iterator[win32.MemoryBasicInformation]
- Returns:
List of memory region information objects.
- iter_memory_snapshot(minAddr=None, maxAddr=None)
Returns an iterator that allows you to go through the memory contents of a process.
It’s basically the same as the
take_memory_snapshot()method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty.Example:
# print(the memory contents of a process.) process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print(HexDump.hexblock(mbi.content, mbi.BaseAddress)) finally: process.resume()
The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen.
The snapshot can only iterated once. To be able to iterate indefinitely call the
generate_memory_snapshot()method instead.You can also iterate the memory of a dead process, just as long as the last open handle to it hasn’t been closed.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
iterator[win32.MemoryBasicInformation]
- Returns:
Iterator of memory region information objects. Two extra properties are added to these objects:
filename: Mapped filename, orNone.content: Memory contents, orNone.
- kill(dwExitCode=0)
Terminates the execution of the process.
- Raises:
WindowsError – On error an exception is raised.
- malloc(dwSize, lpAddress=None)
Allocates memory into the address space of the process.
See also
- Parameters:
dwSize (int) – Number of bytes to allocate.
lpAddress (int) – Optional. Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else.
- Return type:
int
- Returns:
Address of the newly allocated memory.
- Raises:
WindowsError – On error an exception is raised.
- mprotect(lpAddress, dwSize, flNewProtect)
Set memory protection in the address space of the process.
- Parameters:
lpAddress (int) – Address of memory to protect.
dwSize (int) – Number of bytes to protect.
flNewProtect (int) – New protect flags.
- Return type:
int
- Returns:
Old protect flags.
- Raises:
WindowsError – On error an exception is raised.
- mquery(lpAddress)
Query memory information from the address space of the process. Returns a
MemoryBasicInformationobject.- Parameters:
lpAddress (int) – Address of memory to query.
- Return type:
MemoryBasicInformation- Returns:
Memory region information.
- Raises:
WindowsError – On error an exception is raised.
- open_handle(dwDesiredAccess=2035711)
Opens a new handle to the process.
The new handle is stored in the
hProcessproperty.Warning
Normally you should call
get_handle()instead, since it’s much “smarter” and tries to reuse handles and merge access rights.- Parameters:
dwDesiredAccess (int) – Desired access rights. Defaults to
win32.PROCESS_ALL_ACCESS. See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx- Raises:
WindowsError – It’s not possible to open a handle to the process with the requested access rights. This typically happens because the target process is a system process and the debugger is not runnning with administrative rights.
- peek(lpBaseAddress, nSize)
Reads the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
nSize (int) – Number of bytes to read.
- Return type:
bytes
- Returns:
Bytes read from the process memory. Returns an empty string on error.
- peek_char(lpBaseAddress)
Reads a single character from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Character read from the process memory. Returns zero on error.
- peek_double(lpBaseAddress)
Reads a double from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
float
- Returns:
Integer value read from the process memory. Returns zero on error.
- peek_dword(lpBaseAddress)
Reads a DWORD from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory. Returns zero on error.
- peek_float(lpBaseAddress)
Reads a float from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
float
- Returns:
Integer value read from the process memory. Returns zero on error.
- peek_int(lpBaseAddress)
Reads a signed integer from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory. Returns zero on error.
- peek_pointer(lpBaseAddress)
Reads a pointer value from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Pointer value read from the process memory. Returns zero on error.
- peek_pointers_in_data(data, peekSize=16, peekStep=1)
Tries to guess which values in the given data are valid pointers, and reads some data from them.
See also
- Parameters:
data (bytes) – Binary data to find pointers in.
peekSize (int) – Number of bytes to read from each pointer found.
peekStep (int) – Expected data alignment. Typically you specify 1 when data alignment is unknown, or 4 when you expect data to be DWORD aligned. Any other value may be specified.
- Return type:
dict[int, bytes]
- Returns:
Dictionary mapping stack offsets to the data they point to.
- peek_qword(lpBaseAddress)
Reads a QWORD from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory. Returns zero on error.
- peek_string(lpBaseAddress, fUnicode=False, dwMaxSize=4096)
Tries to read an ASCII or Unicode string from the address space of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
fUnicode (bool) –
Trueis the string is expected to be Unicode,Falseif it’s expected to be ANSI.dwMaxSize (int) – Maximum allowed string length to read, in bytes.
- Return type:
str or bytes
- Returns:
String read from the process memory space. It doesn’t include the terminating null character. Returns an empty string on failure.
- peek_uint(lpBaseAddress)
Reads an unsigned integer from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory. Returns zero on error.
- poke(lpBaseAddress, lpBuffer)
Writes to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
lpBuffer (bytes) – Bytes to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_char(lpBaseAddress, char)
Writes a single character to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
char (int) – Character to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_double(lpBaseAddress, unpackedValue)
Writes a double to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (float) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_dword(lpBaseAddress, unpackedValue)
Writes a DWORD to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_float(lpBaseAddress, unpackedValue)
Writes a float to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (float) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_int(lpBaseAddress, unpackedValue)
Writes a signed integer to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_pointer(lpBaseAddress, unpackedValue)
Writes a pointer value to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_qword(lpBaseAddress, unpackedValue)
Writes a QWORD to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- poke_uint(lpBaseAddress, unpackedValue)
Writes an unsigned integer to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Return type:
int
- Returns:
Number of bytes written. May be less than the number of bytes to write.
- read(lpBaseAddress, nSize)
Reads from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
nSize (int) – Number of bytes to read.
- Return type:
bytes
- Returns:
Bytes read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_char(lpBaseAddress)
Reads a single character from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Character value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_double(lpBaseAddress)
Reads a double from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
float
- Returns:
Floating point value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_dword(lpBaseAddress)
Reads a DWORD from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_float(lpBaseAddress)
Reads a float from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
float
- Returns:
Floating point value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_int(lpBaseAddress)
Reads a signed integer from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_pointer(lpBaseAddress)
Reads a pointer value from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Pointer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_qword(lpBaseAddress)
Reads a QWORD from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_string(lpBaseAddress, nChars, fUnicode=False)
Reads an ASCII or Unicode string from the address space of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
nChars (int) – String length to read, in characters. Remember that Unicode strings have two byte characters.
fUnicode (bool) –
Trueis the string is expected to be Unicode,Falseif it’s expected to be ANSI.
- Return type:
str
- Returns:
String read from the process memory space.
- Raises:
WindowsError – On error an exception is raised.
- read_structure(lpBaseAddress, stype)
Reads a ctypes structure from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
stype (ctypes.Structure) – Structure definition.
- Return type:
ctypes.Structure
- Returns:
Structure instance filled in with data read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_uint(lpBaseAddress)
Reads an unsigned integer from the memory of the process.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- read_word(lpBaseAddress)
Reads a WORD from the memory of the process.
See also
peek_word()- Parameters:
lpBaseAddress (int) – Memory address to begin reading.
- Return type:
int
- Returns:
Integer value read from the process memory.
- Raises:
WindowsError – On error an exception is raised.
- restore_memory_snapshot(snapshot, bSkipMappedFiles=True, bSkipOnError=False)
Attempts to restore the memory state as it was when the given snapshot was taken.
Warning
Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file).
- Parameters:
snapshot (list[win32.MemoryBasicInformation]) – Memory snapshot returned by
take_memory_snapshot(). Snapshots returned bygenerate_memory_snapshot()don’t work here.bSkipMappedFiles (bool) –
Trueto avoid restoring the contents of memory mapped files,Falseotherwise. Use with care! Setting this toTruecan cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don’t change, so trying to restore their contents is usually a waste of time.bSkipOnError (bool) –
Trueto issue a warning when an error occurs during the restoration of the snapshot,Falseto stop and raise an exception instead. Use with care! Setting this toTruewill cause the debugger to falsely believe the memory snapshot has been correctly restored.
- Raises:
WindowsError – An error occured while restoring the snapshot.
RuntimeError – An error occured while restoring the snapshot.
TypeError – A snapshot of the wrong type was passed.
- resume()
Resumes execution on all threads of the process.
- Raises:
WindowsError – On error an exception is raised.
- scan()
Populates the snapshot of threads and modules.
- search(pattern, minAddr=None, maxAddr=None)
Search for the given string or pattern within the process memory.
Note
This is a more limited version of
search_process().- Parameters:
pattern (str or
Pattern) – String or hexadecimal pattern to search for.minAddr (int) – Optional. Start the search at this memory address.
maxAddr (int) – Optional. Stop the search at this memory address.
- Return type:
iterator[tuple[int, str]]
- Returns:
An iterator of tuples. Each tuple contains the following:
The memory address where the pattern was found.
The data that matches the pattern.
- Raises:
WindowsError – An error occurred when querying or reading the process memory.
- search_bytes(bytes, minAddr=None, maxAddr=None)
Search for the given byte pattern within the process memory.
Note
This is a more limited version of
search_process().- Parameters:
bytes (bytes) – Bytes to search for.
minAddr (int) – Optional. Start the search at this memory address.
maxAddr (int) – Optional. Stop the search at this memory address.
- Return type:
iterator[int]
- Returns:
An iterator of memory addresses where the pattern was found.
- Raises:
WindowsError – An error occurred when querying or reading the process memory.
- search_hexa(hexa, minAddr=None, maxAddr=None)
Search for the given hexadecimal pattern within the process memory.
Note
This is a more limited version of
search_process().Hex patterns must be in this form:
"68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world"
Spaces are optional. Capitalization of hex digits doesn’t matter. This is exactly equivalent to the previous example:
"68656C6C6F20776F726C64" # "hello world"
Wildcards are allowed, in the form of a
?sign in any hex digit:"5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value
- Parameters:
hexa (str) – Pattern to search for.
minAddr (int) – Optional. Start the search at this memory address.
maxAddr (int) – Optional. Stop the search at this memory address.
- Return type:
iterator[tuple[int, str]]
- Returns:
An iterator of tuples. Each tuple contains the following:
The memory address where the pattern was found.
The bytes that match the pattern.
- Raises:
WindowsError – An error occurred when querying or reading the process memory.
- search_text(text, encoding='utf-16le', caseSensitive=False, minAddr=None, maxAddr=None)
Search for the given text within the process memory.
Note
This is a more limited version of
search_process().- Parameters:
text (str) – Text to search for.
encoding (str) – Optional. Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don’t change unless you know what you’re doing!
caseSensitive (bool) –
Trueof the search is case sensitive,Falseotherwise.minAddr (int) – Optional. Start the search at this memory address.
maxAddr (int) – Optional. Stop the search at this memory address.
- Return type:
iterator[tuple[int, str]]
- Returns:
An iterator of tuples. Each tuple contains the following:
The memory address where the pattern was found.
The text that matches the pattern.
- Raises:
WindowsError – An error occurred when querying or reading the process memory.
- strings(minLength=4, encoding='both', minAddr=None, maxAddr=None, bufferPages=None)
Extract printable strings from the process memory.
This method extracts readable strings from the process memory, similar to the Unix
stringscommand. It can extract both ASCII and Unicode strings.- Parameters:
minLength (int) – Minimum length of strings to extract, in characters. Defaults to 4.
encoding (str) –
Type of strings to extract. Valid values are:
"ascii"- Extract only ASCII strings (8-bit)"unicode"- Extract only Unicode strings (UTF-16LE, 16-bit)"both"- Extract both ASCII and Unicode strings (default)
minAddr (int) – Optional. Start the search at this memory address.
maxAddr (int) – Optional. Stop the search at this memory address.
bufferPages (int) – Optional. Number of memory pages to buffer when performing the search. See
search_process()for details on this parameter.
- Return type:
iterator[tuple[int, str]]
- Returns:
An iterator of tuples. Each tuple contains the following:
The memory address where the string was found.
The string that was extracted (decoded as a Python str).
- Raises:
ValueError – If an invalid encoding parameter is provided.
WindowsError – An error occurred when querying or reading the process memory.
Example:
from winappdbg import Process # Open a process process = Process(1234) # Extract all strings from the process memory for address, string in process.strings(): print(f"0x{address:08x}: {string}") # Extract only ASCII strings of at least 8 characters for address, string in process.strings(minLength=8, encoding="ascii"): print(f"0x{address:08x}: {string}")
Note
This method uses
AsciiStringsPatternandUnicodeStringsPatternto extract strings. Only printable ASCII characters (0x20-0x7E) are considered.
- suspend()
Suspends execution on all threads of the process.
- Raises:
WindowsError – On error an exception is raised.
- take_memory_snapshot(minAddr=None, maxAddr=None)
Takes a snapshot of the memory contents of the process.
It’s best if the process is suspended (if alive) when taking the snapshot. Execution can be resumed afterwards.
Example:
# print(the memory contents of a process.) process.suspend() try: snapshot = process.take_memory_snapshot() for mbi in snapshot: print(HexDump.hexblock(mbi.content, mbi.BaseAddress)) finally: process.resume()
You can also iterate the memory of a dead process, just as long as the last open handle to it hasn’t been closed.
Warning
If the target process has a very big memory footprint, the resulting snapshot will be equally big. This may result in a severe performance penalty.
See also
- Parameters:
minAddr (int) – Optional. Starting address in address range to query.
maxAddr (int) – Optional. Ending address in address range to query.
- Return type:
list[win32.MemoryBasicInformation]
- Returns:
List of memory region information objects. Two extra properties are added to these objects:
filename: Mapped filename, orNone.content: Memory contents, orNone.
- wait(dwTimeout=None)
Waits for the process to finish executing.
- Raises:
WindowsError – On error an exception is raised.
- write(lpBaseAddress, lpBuffer)
Writes to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
lpBuffer (bytes) – Bytes to write.
- Raises:
WindowsError – On error an exception is raised.
- write_char(lpBaseAddress, char)
Writes a single character to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
char (int) – Character to write.
- Raises:
WindowsError – On error an exception is raised.
- write_double(lpBaseAddress, unpackedValue)
Writes a double to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (float) – Floating point value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_dword(lpBaseAddress, unpackedValue)
Writes a DWORD to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_float(lpBaseAddress, unpackedValue)
Writes a float to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (float) – Floating point value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_int(lpBaseAddress, unpackedValue)
Writes a signed integer to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_pointer(lpBaseAddress, unpackedValue)
Writes a pointer value to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_qword(lpBaseAddress, unpackedValue)
Writes a QWORD to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_uint(lpBaseAddress, unpackedValue)
Writes an unsigned integer to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.
- write_word(lpBaseAddress, unpackedValue)
Writes a WORD to the memory of the process.
Note
Page permissions may be changed temporarily while writing.
See also
poke_word()- Parameters:
lpBaseAddress (int) – Memory address to begin writing.
unpackedValue (int) – Value to write.
- Raises:
WindowsError – On error an exception is raised.