cosmetic and typing-related changes

This commit is contained in:
Jan Petykiewicz 2020-11-01 20:16:46 -08:00
commit 6913f73db4

View file

@ -2,7 +2,7 @@
Implementation of Process class for Windows
"""
from typing import List, Tuple
from typing import List, Tuple, Optional
from math import floor
from os import strerror
import os.path
@ -20,77 +20,77 @@ logger = logging.getLogger(__name__)
# Process handle privileges
privileges = {
'PROCESS_QUERY_INFORMATION': 0x0400,
'PROCESS_VM_OPERATION': 0x0008,
'PROCESS_VM_READ': 0x0010,
'PROCESS_VM_WRITE': 0x0020,
}
'PROCESS_QUERY_INFORMATION': 0x0400,
'PROCESS_VM_OPERATION': 0x0008,
'PROCESS_VM_READ': 0x0010,
'PROCESS_VM_WRITE': 0x0020,
}
privileges['PROCESS_RW'] = (
privileges['PROCESS_QUERY_INFORMATION'] |
privileges['PROCESS_VM_OPERATION'] |
privileges['PROCESS_VM_READ'] |
privileges['PROCESS_VM_WRITE']
)
privileges['PROCESS_QUERY_INFORMATION'] |
privileges['PROCESS_VM_OPERATION'] |
privileges['PROCESS_VM_READ'] |
privileges['PROCESS_VM_WRITE']
)
# Memory region states
mem_states = {
'MEM_COMMIT': 0x1000,
'MEM_FREE': 0x10000,
'MEM_RESERVE': 0x2000,
}
'MEM_COMMIT': 0x1000,
'MEM_FREE': 0x10000,
'MEM_RESERVE': 0x2000,
}
# Memory region permissions
page_protections = {
'PAGE_EXECUTE': 0x10,
'PAGE_EXECUTE_READ': 0x20,
'PAGE_EXECUTE_READWRITE': 0x40,
'PAGE_EXECUTE_WRITECOPY': 0x80,
'PAGE_NOACCESS': 0x01,
'PAGE_READWRITE': 0x04,
'PAGE_WRITECOPY': 0x08,
}
'PAGE_EXECUTE': 0x10,
'PAGE_EXECUTE_READ': 0x20,
'PAGE_EXECUTE_READWRITE': 0x40,
'PAGE_EXECUTE_WRITECOPY': 0x80,
'PAGE_NOACCESS': 0x01,
'PAGE_READWRITE': 0x04,
'PAGE_WRITECOPY': 0x08,
}
# Custom (combined) permissions
page_protections['PAGE_READABLE'] = (
page_protections['PAGE_EXECUTE_READ'] |
page_protections['PAGE_EXECUTE_READWRITE'] |
page_protections['PAGE_READWRITE']
)
page_protections['PAGE_EXECUTE_READ'] |
page_protections['PAGE_EXECUTE_READWRITE'] |
page_protections['PAGE_READWRITE']
)
page_protections['PAGE_READWRITEABLE'] = (
page_protections['PAGE_EXECUTE_READWRITE'] |
page_protections['PAGE_READWRITE']
)
page_protections['PAGE_EXECUTE_READWRITE'] |
page_protections['PAGE_READWRITE']
)
# Memory types
mem_types = {
'MEM_IMAGE': 0x1000000,
'MEM_MAPPED': 0x40000,
'MEM_PRIVATE': 0x20000,
}
'MEM_IMAGE': 0x1000000,
'MEM_MAPPED': 0x40000,
'MEM_PRIVATE': 0x20000,
}
# C struct for VirtualQueryEx
class MEMORY_BASIC_INFORMATION32(ctypes.Structure):
_fields_ = [
('BaseAddress', ctypes.wintypes.DWORD),
('AllocationBase', ctypes.wintypes.DWORD),
('AllocationProtect', ctypes.wintypes.DWORD),
('RegionSize', ctypes.wintypes.DWORD),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD),
]
('BaseAddress', ctypes.wintypes.DWORD),
('AllocationBase', ctypes.wintypes.DWORD),
('AllocationProtect', ctypes.wintypes.DWORD),
('RegionSize', ctypes.wintypes.DWORD),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD),
]
class MEMORY_BASIC_INFORMATION64(ctypes.Structure):
_fields_ = [
('BaseAddress', ctypes.c_ulonglong),
('AllocationBase', ctypes.c_ulonglong),
('AllocationProtect', ctypes.wintypes.DWORD),
('__alignment1', ctypes.wintypes.DWORD),
('RegionSize', ctypes.c_ulonglong),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD),
('__alignment2', ctypes.wintypes.DWORD),
]
('BaseAddress', ctypes.c_ulonglong),
('AllocationBase', ctypes.c_ulonglong),
('AllocationProtect', ctypes.wintypes.DWORD),
('__alignment1', ctypes.wintypes.DWORD),
('RegionSize', ctypes.c_ulonglong),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD),
('__alignment2', ctypes.wintypes.DWORD),
]
PTR_SIZE = ctypes.sizeof(ctypes.c_void_p)
if PTR_SIZE == 8: # 64-bit python
@ -98,36 +98,39 @@ if PTR_SIZE == 8: # 64-bit python
elif PTR_SIZE == 4: # 32-bit python
MEMORY_BASIC_INFORMATION = MEMORY_BASIC_INFORMATION32
ctypes.windll.kernel32.VirtualQueryEx.argtypes = [ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t]
ctypes.windll.kernel32.ReadProcessMemory.argtypes = [ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p]
ctypes.windll.kernel32.WriteProcessMemory.argtypes = [ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p]
ctypes.windll.kernel32.VirtualQueryEx.argtypes = [
ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t]
ctypes.windll.kernel32.ReadProcessMemory.argtypes = [
ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p]
ctypes.windll.kernel32.WriteProcessMemory.argtypes = [
ctypes.wintypes.HANDLE,
ctypes.wintypes.LPCVOID,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p]
# C struct for GetSystemInfo
class SYSTEM_INFO(ctypes.Structure):
_fields_ = [
('wProcessorArchitecture', ctypes.wintypes.WORD),
('wReserved', ctypes.wintypes.WORD),
('dwPageSize', ctypes.wintypes.DWORD),
('lpMinimumApplicationAddress', ctypes.c_void_p),
('lpMaximumApplicationAddress', ctypes.c_void_p),
('dwActiveProcessorMask', ctypes.c_void_p),
('dwNumberOfProcessors', ctypes.wintypes.DWORD),
('dwProcessorType', ctypes.wintypes.DWORD),
('dwAllocationGranularity', ctypes.wintypes.DWORD),
('wProcessorLevel', ctypes.wintypes.WORD),
('wProcessorRevision', ctypes.wintypes.WORD),
]
('wProcessorArchitecture', ctypes.wintypes.WORD),
('wReserved', ctypes.wintypes.WORD),
('dwPageSize', ctypes.wintypes.DWORD),
('lpMinimumApplicationAddress', ctypes.c_void_p),
('lpMaximumApplicationAddress', ctypes.c_void_p),
('dwActiveProcessorMask', ctypes.c_void_p),
('dwNumberOfProcessors', ctypes.wintypes.DWORD),
('dwProcessorType', ctypes.wintypes.DWORD),
('dwAllocationGranularity', ctypes.wintypes.DWORD),
('wProcessorLevel', ctypes.wintypes.WORD),
('wProcessorRevision', ctypes.wintypes.WORD),
]
class Process(AbstractProcess):
@ -152,24 +155,24 @@ class Process(AbstractProcess):
def write_memory(self, base_address: int, write_buffer: ctypes_buffer_t):
try:
ctypes.windll.kernel32.WriteProcessMemory(
self.process_handle,
base_address,
ctypes.byref(write_buffer),
ctypes.sizeof(write_buffer),
None
)
self.process_handle,
base_address,
ctypes.byref(write_buffer),
ctypes.sizeof(write_buffer),
None
)
except (BufferError, ValueError, TypeError):
raise MemEditError('Error with handle {}: {}'.format(self.process_handle, self._get_last_error()))
def read_memory(self, base_address: int, read_buffer: ctypes_buffer_t) -> ctypes_buffer_t:
try:
ctypes.windll.kernel32.ReadProcessMemory(
self.process_handle,
base_address,
ctypes.byref(read_buffer),
ctypes.sizeof(read_buffer),
None
)
self.process_handle,
base_address,
ctypes.byref(read_buffer),
ctypes.sizeof(read_buffer),
None
)
except (BufferError, ValueError, TypeError):
raise MemEditError('Error with handle {}: {}'.format(self.process_handle, self._get_last_error()))
@ -184,10 +187,9 @@ class Process(AbstractProcess):
max_path_len = 260
name_buffer = (ctypes.c_char * max_path_len)()
rval = ctypes.windll.psapi.GetProcessImageFileNameA(
self.process_handle,
name_buffer,
max_path_len
)
self.process_handle,
name_buffer,
max_path_len)
if rval > 0:
return name_buffer.value.decode()
@ -199,7 +201,7 @@ class Process(AbstractProcess):
# According to EnumProcesses docs, you can't find out how many processes there are before
# fetching the list. As a result, we grab 100 on the first try, and if we get a full list
# of 100, repeatedly double the number until we get fewer than we asked for.
n = 100
returned_size = ctypes.wintypes.DWORD()
returned_size_ptr = ctypes.byref(returned_size)
@ -224,7 +226,7 @@ class Process(AbstractProcess):
return pids[:num_returned]
@staticmethod
def get_pid_by_name(target_name: str) -> int or None:
def get_pid_by_name(target_name: str) -> Optional[int]:
for pid in Process.list_available_pids():
try:
logger.info('Checking name for pid {}'.format(pid))
@ -260,11 +262,10 @@ class Process(AbstractProcess):
mbi_size = ctypes.sizeof(mbi)
success = ctypes.windll.kernel32.VirtualQueryEx(
self.process_handle,
address,
mbi_ptr,
mbi_size,
)
self.process_handle,
address,
mbi_ptr,
mbi_size)
if success != mbi_size:
if success == 0:
@ -279,10 +280,11 @@ class Process(AbstractProcess):
page_ptr = start
while page_ptr < stop:
page_info = get_mem_info(page_ptr)
if page_info.Type == mem_types['MEM_PRIVATE'] and \
page_info.State == mem_states['MEM_COMMIT'] and \
page_info.Protect & page_protections['PAGE_READABLE'] != 0 and \
(page_info.Protect & page_protections['PAGE_READWRITEABLE'] != 0 or not writeable_only):
if (page_info.Type == mem_types['MEM_PRIVATE']
and page_info.State == mem_states['MEM_COMMIT']
and page_info.Protect & page_protections['PAGE_READABLE'] != 0
and (page_info.Protect & page_protections['PAGE_READWRITEABLE'] != 0
or not writeable_only)):
regions.append((page_ptr, page_ptr + page_info.RegionSize))
page_ptr += page_info.RegionSize