Merge pull request #76 from hakril/teb_definition

TEB defintion and `Thread.teb` field
This commit is contained in:
hakril
2025-02-02 07:15:21 -08:00
committed by GitHub
30 changed files with 2292 additions and 1868 deletions
+11 -8
View File
@@ -1,14 +1,18 @@
# V0.1
name: Pytest
on: [push, pull_request, workflow_dispatch]
on:
push:
branches:
- 'master'
pull_request:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
generate_ctypes:
runs-on: windows-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
@@ -19,7 +23,6 @@ jobs:
- name: Check generated code can execute
run: py -c "import windows.generated_def"
tests:
# Not a real dependency : but starting tests when ctypes generation is broken is not useful
strategy:
fail-fast: false
matrix:
@@ -32,7 +35,7 @@ jobs:
python-architecture: x86
- python-bitness-to-test: 64
python-architecture: x64
# Not a real dependency : but starting tests when ctypes generation is broken is not useful
needs: generate_ctypes
timeout-minutes: 15
runs-on: ${{ matrix.runs-on }}
@@ -76,11 +79,11 @@ jobs:
py -${{ matrix.python-version}}-64 setup.py install
- name: Installing pytest & capstone-windows
run: py -${{ matrix.python-version}}-${{ matrix.python-bitness-to-test}} -m pip install pytest capstone-windows
run: py -${{ matrix.python-version}}-${{ matrix.python-bitness-to-test}} -m pip install pytest pytest-timeout capstone-windows
# Testing
- name: Testing
run: py -${{ matrix.python-version}}-${{ matrix.python-bitness-to-test}} -m pytest --junitxml=junit/test-results.xml -s -k "not known_to_fail" -v tests/
run: py -${{ matrix.python-version}}-${{ matrix.python-bitness-to-test}} -m pytest --junitxml=junit/test-results.xml -s -v tests/
- name: Publish PyTest Results
uses: EnricoMi/publish-unit-test-result-action/windows@v2
@@ -90,4 +93,4 @@ jobs:
check_name: PyTest Results for ${{ matrix.python-version}}-${{ matrix.python-bitness-to-test}}
secondary_rate_limit_wait_seconds: 90
seconds_between_github_writes: 10
seconds_between_github_reads: 1
seconds_between_github_reads: 1
+6 -1
View File
@@ -3,7 +3,12 @@ doctrees
*.inv
*.pickle
*.ignore
*.code-workspace
.vscode/
.cache/
dist/
dist/
build/
docs/BuildDocEnv/
playground/
*egg-info/
@@ -63,4 +63,10 @@ HMODULE LoadLibraryExW(
BOOL FreeLibrary(
HMODULE hLibModule
);
);
/* Not documented by seems present since dawn of time (WRK)
I Prefere PVOID as a return value to allow simple cast to PEB subclass in process.py*/
PVOID RtlGetCurrentPeb ();
@@ -0,0 +1,29 @@
/* Structures that do not depends on anything other that basic type
Simplify structure dependancy file graph
*/
typedef struct _LIST_ENTRY {
struct _LIST_ENTRY *Flink;
struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY;
typedef struct _LSA_UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PVOID Buffer; // PVOID to prevent ctypes to automatically read the content of the buffer till a \0
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING;
typedef struct _CLIENT_ID{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _CLIENT_ID64{
ULONG64 UniqueProcess;
ULONG64 UniqueThread;
} CLIENT_ID64, *PCLIENT_ID64;
typedef struct _CLIENT_ID32{
ULONG UniqueProcess;
ULONG UniqueThread;
} CLIENT_ID32, *PCLIENT_ID32;
@@ -0,0 +1,237 @@
/* This is the part of RTL_USER_PROCESS_PARAMETERS that works from XP to Windows 10
http://terminus.rewolf.pl/terminus/structures/ntdll/_RTL_USER_PROCESS_PARAMETERS_x86.html
*/
typedef struct _CURDIR
{
UNICODE_STRING DosPath;
PVOID Handle;
} CURDIR, *PCURDIR;
typedef struct _RTL_DRIVE_LETTER_CURDIR
{
WORD Flags;
WORD Length;
ULONG TimeStamp;
UNICODE_STRING DosPath;
} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
typedef struct _RTL_USER_PROCESS_PARAMETERS
{
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
PVOID ConsoleHandle;
ULONG ConsoleFlags;
PVOID StandardInput;
PVOID StandardOutput;
PVOID StandardError;
CURDIR CurrentDirectory;
UNICODE_STRING DllPath;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
PVOID Environment;
ULONG StartingX;
ULONG StartingY;
ULONG CountX;
ULONG CountY;
ULONG CountCharsX;
ULONG CountCharsY;
ULONG FillAttribute;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING WindowTitle;
UNICODE_STRING DesktopInfo;
UNICODE_STRING ShellInfo;
UNICODE_STRING RuntimeData;
RTL_DRIVE_LETTER_CURDIR CurrentDirectores[32];
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
// PEB: Thank to
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa813706(v=vs.85).aspx
// http://blog.rewolf.pl/blog/?p=573
// http://terminus.rewolf.pl/terminus/structures/ntdll/_PEB_combined.html
typedef struct _LDR_DATA_TABLE_ENTRY {
PVOID Reserved1[2];
LIST_ENTRY InMemoryOrderLinks;
PVOID Reserved2[2];
PVOID DllBase;
PVOID EntryPoint;
PVOID SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
PVOID Reserved5[3];
ULONG CheckSum;
ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
/* Definition of WinXP : Still same base in win11 with some extra field */
typedef struct _PEB_LDR_DATA {
ULONG Length;
BYTE Initialized;
PVOID SsHandle;
_LIST_ENTRY InLoadOrderModuleList;
_LIST_ENTRY InMemoryOrderModuleList;
_LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
// BYTE ShutdownInProgress; // New field
// PVOID ShutdownThreadId; // New field
}PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef union _ANON_PEB_SYSTEM_DEPENDENT_02 {
PVOID FastPebLockRoutine;
PVOID SparePtr1;
PVOID AtlThunkSListPtr;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_03 {
PVOID FastPebUnlockRoutine;
PVOID SparePtr2;
PVOID IFEOKey;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_06 {
PVOID FreeList;
PVOID SparePebPtr0;
PVOID ApiSetMap;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_07 {
PVOID ReadOnlySharedMemoryHeap;
PVOID HotpatchInformation;
PVOID SparePvoid0;
};
typedef union _ANON_PEB_UNION_1 {
PVOID KernelCallbackTable;
PVOID UserSharedInfoPtr;
};
typedef union _ANON_PEB_UNION_2 {
PVOID ImageProcessAffinityMask;
PVOID ActiveProcessAffinityMask;
};
typedef struct _PEB {
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[1];
PVOID Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA Ldr;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PVOID FastPebLock;
_ANON_PEB_SYSTEM_DEPENDENT_02 _SYSTEM_DEPENDENT_02;
_ANON_PEB_SYSTEM_DEPENDENT_03 _SYSTEM_DEPENDENT_03;
PVOID _SYSTEM_DEPENDENT_04;
union {
PVOID KernelCallbackTable;
PVOID UserSharedInfoPtr;
};
DWORD SystemReserved;
DWORD _SYSTEM_DEPENDENT_05;
_ANON_PEB_SYSTEM_DEPENDENT_06 _SYSTEM_DEPENDENT_06;
PVOID TlsExpansionCounter;
PVOID TlsBitmap;
DWORD TlsBitmapBits[2];
PVOID ReadOnlySharedMemoryBase;
_ANON_PEB_SYSTEM_DEPENDENT_07 _SYSTEM_DEPENDENT_07;
PVOID ReadOnlyStaticServerData;
PVOID AnsiCodePageData;
PVOID OemCodePageData;
PVOID UnicodeCaseTableData;
DWORD NumberOfProcessors;
DWORD NtGlobalFlag;
LARGE_INTEGER CriticalSectionTimeout;
PVOID HeapSegmentReserve;
PVOID HeapSegmentCommit;
PVOID HeapDeCommitTotalFreeThreshold;
PVOID HeapDeCommitFreeBlockThreshold;
DWORD NumberOfHeaps;
DWORD MaximumNumberOfHeaps;
PVOID ProcessHeaps;
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
PVOID GdiDCAttributeList;
PVOID LoaderLock;
DWORD OSMajorVersion;
DWORD OSMinorVersion;
WORD OSBuildNumber;
WORD OSCSDVersion;
DWORD OSPlatformId;
DWORD ImageSubsystem;
DWORD ImageSubsystemMajorVersion;
PVOID ImageSubsystemMinorVersion;
union {
PVOID ImageProcessAffinityMask;
PVOID ActiveProcessAffinityMask;
};
PVOID GdiHandleBuffer[26];
BYTE GdiHandleBuffer2[32];
PVOID PostProcessInitRoutine;
PVOID TlsExpansionBitmap;
DWORD TlsExpansionBitmapBits[32];
PVOID SessionId;
ULARGE_INTEGER AppCompatFlags;
ULARGE_INTEGER AppCompatFlagsUser;
PVOID pShimData;
PVOID AppCompatInfo;
UNICODE_STRING CSDVersion;
PVOID ActivationContextData;
PVOID ProcessAssemblyStorageMap;
PVOID SystemDefaultActivationContextData;
PVOID SystemAssemblyStorageMap;
PVOID MinimumStackCommit;
} PEB, *PPEB;
/* Partial TEB description
Based on:
- fields that did not move since XP
- https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-teb
*/
typedef struct _EXCEPTION_REGISTRATION_RECORD {
_EXCEPTION_REGISTRATION_RECORD *Next;
PVOID Handler;
};
typedef struct _NT_TIB {
struct _EXCEPTION_REGISTRATION_RECORD *ExceptionList;
PVOID StackBase;
PVOID StackLimit;
PVOID SubSystemTib;
union {
PVOID FiberData;
ULONG Version;
};
PVOID ArbitraryUserPointer;
struct _NT_TIB *Self;
} NT_TIB;
typedef struct _TEB {
_NT_TIB NtTib;
PVOID EnvironmentPointer;
_CLIENT_ID ClientId;
PVOID ActiveRpcHandle;
PVOID ThreadLocalStoragePointer;
_PEB *ProcessEnvironmentBlock;
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
PVOID CsrClientThread;
PVOID Win32ThreadInfo;
ULONG User32Reserved[26];
ULONG UserReserved[5];
PVOID WOW32Reserved;
ULONG CurrentLocale;
ULONG FpSoftwareStatusRegister;
} TEB;
@@ -1,195 +1,3 @@
typedef struct _LIST_ENTRY {
struct _LIST_ENTRY *Flink;
struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY;
/* Definition of WinXP : Still same base in win11 with some extra field */
typedef struct _PEB_LDR_DATA {
ULONG Length;
BYTE Initialized;
PVOID SsHandle;
_LIST_ENTRY InLoadOrderModuleList;
_LIST_ENTRY InMemoryOrderModuleList;
_LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
// BYTE ShutdownInProgress; // New field
// PVOID ShutdownThreadId; // New field
}PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _LSA_UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PVOID Buffer; // PVOID to prevent ctypes to automatically read the content of the buffer till a \0
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING;
typedef struct _CURDIR
{
UNICODE_STRING DosPath;
PVOID Handle;
} CURDIR, *PCURDIR;
typedef struct _RTL_DRIVE_LETTER_CURDIR
{
WORD Flags;
WORD Length;
ULONG TimeStamp;
UNICODE_STRING DosPath;
} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
/* This is the part of RTL_USER_PROCESS_PARAMETERS that works from XP to Windows 10
http://terminus.rewolf.pl/terminus/structures/ntdll/_RTL_USER_PROCESS_PARAMETERS_x86.html
*/
typedef struct _RTL_USER_PROCESS_PARAMETERS
{
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
PVOID ConsoleHandle;
ULONG ConsoleFlags;
PVOID StandardInput;
PVOID StandardOutput;
PVOID StandardError;
CURDIR CurrentDirectory;
UNICODE_STRING DllPath;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
PVOID Environment;
ULONG StartingX;
ULONG StartingY;
ULONG CountX;
ULONG CountY;
ULONG CountCharsX;
ULONG CountCharsY;
ULONG FillAttribute;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING WindowTitle;
UNICODE_STRING DesktopInfo;
UNICODE_STRING ShellInfo;
UNICODE_STRING RuntimeData;
RTL_DRIVE_LETTER_CURDIR CurrentDirectores[32];
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
// Thank to:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa813706(v=vs.85).aspx
// http://blog.rewolf.pl/blog/?p=573
// http://terminus.rewolf.pl/terminus/structures/ntdll/_PEB_combined.html
typedef union _ANON_PEB_SYSTEM_DEPENDENT_02 {
PVOID FastPebLockRoutine;
PVOID SparePtr1;
PVOID AtlThunkSListPtr;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_03 {
PVOID FastPebUnlockRoutine;
PVOID SparePtr2;
PVOID IFEOKey;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_06 {
PVOID FreeList;
PVOID SparePebPtr0;
PVOID ApiSetMap;
};
typedef union _ANON_PEB_SYSTEM_DEPENDENT_07 {
PVOID ReadOnlySharedMemoryHeap;
PVOID HotpatchInformation;
PVOID SparePvoid0;
};
typedef union _ANON_PEB_UNION_1 {
PVOID KernelCallbackTable;
PVOID UserSharedInfoPtr;
};
typedef union _ANON_PEB_UNION_2 {
PVOID ImageProcessAffinityMask;
PVOID ActiveProcessAffinityMask;
};
typedef struct _PEB {
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[1];
PVOID Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA Ldr;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PVOID FastPebLock;
_ANON_PEB_SYSTEM_DEPENDENT_02 _SYSTEM_DEPENDENT_02;
_ANON_PEB_SYSTEM_DEPENDENT_03 _SYSTEM_DEPENDENT_03;
PVOID _SYSTEM_DEPENDENT_04;
union {
PVOID KernelCallbackTable;
PVOID UserSharedInfoPtr;
};
DWORD SystemReserved;
DWORD _SYSTEM_DEPENDENT_05;
_ANON_PEB_SYSTEM_DEPENDENT_06 _SYSTEM_DEPENDENT_06;
PVOID TlsExpansionCounter;
PVOID TlsBitmap;
DWORD TlsBitmapBits[2];
PVOID ReadOnlySharedMemoryBase;
_ANON_PEB_SYSTEM_DEPENDENT_07 _SYSTEM_DEPENDENT_07;
PVOID ReadOnlyStaticServerData;
PVOID AnsiCodePageData;
PVOID OemCodePageData;
PVOID UnicodeCaseTableData;
DWORD NumberOfProcessors;
DWORD NtGlobalFlag;
LARGE_INTEGER CriticalSectionTimeout;
PVOID HeapSegmentReserve;
PVOID HeapSegmentCommit;
PVOID HeapDeCommitTotalFreeThreshold;
PVOID HeapDeCommitFreeBlockThreshold;
DWORD NumberOfHeaps;
DWORD MaximumNumberOfHeaps;
PVOID ProcessHeaps;
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
PVOID GdiDCAttributeList;
PVOID LoaderLock;
DWORD OSMajorVersion;
DWORD OSMinorVersion;
WORD OSBuildNumber;
WORD OSCSDVersion;
DWORD OSPlatformId;
DWORD ImageSubsystem;
DWORD ImageSubsystemMajorVersion;
PVOID ImageSubsystemMinorVersion;
union {
PVOID ImageProcessAffinityMask;
PVOID ActiveProcessAffinityMask;
};
PVOID GdiHandleBuffer[26];
BYTE GdiHandleBuffer2[32];
PVOID PostProcessInitRoutine;
PVOID TlsExpansionBitmap;
DWORD TlsExpansionBitmapBits[32];
PVOID SessionId;
ULARGE_INTEGER AppCompatFlags;
ULARGE_INTEGER AppCompatFlagsUser;
PVOID pShimData;
PVOID AppCompatInfo;
UNICODE_STRING CSDVersion;
PVOID ActivationContextData;
PVOID ProcessAssemblyStorageMap;
PVOID SystemDefaultActivationContextData;
PVOID SystemAssemblyStorageMap;
PVOID MinimumStackCommit;
} PEB, *PPEB;
typedef struct _SECURITY_ATTRIBUTES {
DWORD nLength;
LPVOID lpSecurityDescriptor;
@@ -870,34 +678,7 @@ typedef enum _SE_OBJECT_TYPE {
} SE_OBJECT_TYPE;
typedef struct _CLIENT_ID{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _CLIENT_ID64{
ULONG64 UniqueProcess;
ULONG64 UniqueThread;
} CLIENT_ID64, *PCLIENT_ID64;
typedef struct _CLIENT_ID32{
ULONG UniqueProcess;
ULONG UniqueThread;
} CLIENT_ID32, *PCLIENT_ID32;
typedef struct _LDR_DATA_TABLE_ENTRY {
PVOID Reserved1[2];
LIST_ENTRY InMemoryOrderLinks;
PVOID Reserved2[2];
PVOID DllBase;
PVOID EntryPoint;
PVOID SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
PVOID Reserved5[3];
ULONG CheckSum;
ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
typedef struct _MEMORY_BASIC_INFORMATION {
@@ -0,0 +1,18 @@
# From: ctypes_generation\extended_structs\_LIST_ENTRY.py
# _LIST_ENTRY is a self referencing structure
# Currently ctypes generation does not support extending self referencing structures
# Ass the _fields_ assignement should happen after the extended structure definition
# So we just redefine fully _LIST_ENTRY without inheriting the real one
class _LIST_ENTRY(Structure):
def get_real_struct(self, targetcls, target_field):
# >>> gdef.LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks
# <Field type=_LIST_ENTRY, ofs=16, size=16>
# This field object does not allow to retrieve the type..
# So we need to basse the target class AND the target field..
return targetcls.from_address(ctypes.addressof(self) - target_field.offset)
_LIST_ENTRY._fields_ = [
("Flink", POINTER(_LIST_ENTRY)),
("Blink", POINTER(_LIST_ENTRY)),
]
+3 -2
View File
@@ -123,8 +123,9 @@ class WinStruct(object):
def generate_selfref_ctypes_class(self):
res = ["# Self referencing struct tricks"]
res += ["""class {0}(Structure): pass""".format(self.name)]
# res += [self.generate_anonymous_union()]
res += ["""class {0}(Structure):""".format(self.name)]
# We need some code in the def of anon is empty -> insert path
res += [self.generate_anonymous_union() or " pass"]
res += [self.generate_typedef_ctypes()]
if self.pack:
+2
View File
@@ -696,6 +696,8 @@ Functions
.. function:: FreeLibrary(hLibModule)
.. function:: RtlGetCurrentPeb()
.. function:: RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
.. function:: RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -27,7 +27,7 @@ else:
yolo = generate_pop_and_exit_fixtures([pop_proc_32, pop_proc_64], ids=["proc32dbg", "proc64dbg"], dwCreationFlags=gdef.CREATE_SUSPENDED)
DEFAULT_DEBUGGER_TIMEOUT = 10
DEFAULT_DEBUGGER_TIMEOUT = 60
@pytest.mark.timeout(DEFAULT_DEBUGGER_TIMEOUT)
def test_init_breakpoint_callback(proc32_64_debug):
+37
View File
@@ -12,11 +12,25 @@ def assert_struct_offset(struct, field, offset):
if windows.current_process.bitness == 32:
PEB32 = windows.generated_def.PEB
PEB64 = rctypes.transform_type_to_remote64bits(windows.generated_def.PEB)
TEB32 = windows.generated_def.TEB
TEB64 = rctypes.transform_type_to_remote64bits(windows.generated_def.TEB)
NT_TIB32 = windows.generated_def.NT_TIB
NT_TIB64 = rctypes.transform_type_to_remote64bits(windows.generated_def.NT_TIB)
SYSTEM_PROCESS_INFORMATION32 = windows.generated_def.SYSTEM_PROCESS_INFORMATION
SYSTEM_PROCESS_INFORMATION64 = rctypes.transform_type_to_remote64bits(windows.generated_def.SYSTEM_PROCESS_INFORMATION)
else:
PEB32 = rctypes.transform_type_to_remote32bits(windows.generated_def.PEB)
PEB64 = windows.generated_def.PEB
TEB32 = rctypes.transform_type_to_remote32bits(windows.generated_def.TEB)
TEB64 = windows.generated_def.TEB
NT_TIB32 = rctypes.transform_type_to_remote32bits(windows.generated_def.NT_TIB)
NT_TIB64 = windows.generated_def.NT_TIB
SYSTEM_PROCESS_INFORMATION32 = rctypes.transform_type_to_remote32bits(windows.generated_def.SYSTEM_PROCESS_INFORMATION)
SYSTEM_PROCESS_INFORMATION64 = windows.generated_def.SYSTEM_PROCESS_INFORMATION
@@ -53,6 +67,29 @@ def test_peb64_fields():
assert_peb_offset("CSDVersion", 0x02E8)
assert_peb_offset("MinimumStackCommit", 0x0318)
# Important to the the current TEB via Self
def test_nt_tib32_fields():
assert_nt_tib_offset = lambda field, offset: assert_struct_offset(NT_TIB32, field, offset)
assert_nt_tib_offset("ExceptionList", 0)
assert_nt_tib_offset("StackBase", 4)
assert_nt_tib_offset("StackLimit", 8)
assert_nt_tib_offset("SubSystemTib", 0xc)
assert_nt_tib_offset("FiberData", 0x10)
assert_nt_tib_offset("Version", 0x10)
assert_nt_tib_offset("ArbitraryUserPointer", 0x14)
assert_nt_tib_offset("Self", 0x18) # Important !
def test_nt_tib64_fields():
assert_nt_tib_offset = lambda field, offset: assert_struct_offset(NT_TIB64, field, offset)
assert_nt_tib_offset("ExceptionList", 0)
assert_nt_tib_offset("StackBase", 8)
assert_nt_tib_offset("StackLimit", 0x10)
assert_nt_tib_offset("SubSystemTib", 0x18)
assert_nt_tib_offset("FiberData", 0x20)
assert_nt_tib_offset("Version", 0x20)
assert_nt_tib_offset("ArbitraryUserPointer", 0x28)
assert_nt_tib_offset("Self", 0x30) # Important !
def test_system_process_information32_fields():
assert_spi_offset = lambda field, offset: assert_struct_offset(SYSTEM_PROCESS_INFORMATION32, field, offset)
# Mainly based on https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/process.htm
+1 -1
View File
@@ -31,6 +31,6 @@ def test_remote_handle_type_and_name(proc32_64):
remote_handle = [x for x in proc32_64.handles if x.value == file_handle_vlue][0]
assert remote_handle.pid == proc32_64.pid
assert remote_handle.type == "File"
assert remote_handle.name.startswith("\Device\HarddiskVolume")
assert remote_handle.name.startswith(r"\Device\HarddiskVolume")
assert remote_handle.name.endswith(TEST_FILE_FOR_HANDLE[2:]) # Remove volume letter
assert remote_handle.infos
+3 -3
View File
@@ -32,7 +32,7 @@ def test_multiple_access_type(objname):
def test_complex_object_path():
obj = objmanager["\\KnownDLLs\\kernel32.dll"]
obj = objmanager[r"\KnownDLLs\kernel32.dll"]
assert obj.name == "kernel32.dll"
assert obj.fullname == "\\KnownDLLs\\kernel32.dll"
assert obj.path == "\\KnownDLLs"
@@ -41,9 +41,9 @@ def test_complex_object_path():
def test_link_object():
obj = objmanager["\\KnownDLLs\\KnownDLLPath"]
obj = objmanager[r"\KnownDLLs\KnownDLLPath"]
assert obj.type == "SymbolicLink"
assert obj.target.lower() == "c:\windows\system32"
assert obj.target.lower() == r"c:\windows\system32"
# Test unicode string in Kernel object using an ALPC port
+16 -2
View File
@@ -16,7 +16,14 @@ from .pfwtest import *
# A second check about in parameters can be done with put_Left / get_Left or put_Visible
def test_orpc_iexplore():
iid = gdef.IWebBrowser2.IID
client, ipid = windows.rpc.stubborn.stubborn_create_instance("0002DF01-0000-0000-C000-000000000046", iid)
try:
client, ipid = windows.rpc.stubborn.stubborn_create_instance("0002DF01-0000-0000-C000-000000000046", iid)
except Exception as e:
dbginfo = getattr(e, "stubborn_info", None)
if dbginfo:
for x in dbginfo.items():
print(x)
raise
# get_FullName
addrep = client.call(iid, 38, b"", ipid=ipid)
@@ -45,7 +52,14 @@ def test_orpc_iexplore():
def test_orpc_network_manager():
"""ORPC: Testing ORPCTHAT size using a method that takes no arguments and returns a single bytes"""
iid = gdef.GUID.from_string("D0074FFD-570F-4A9B-8D69-199FDBA5723B")
client, ipid = windows.rpc.stubborn.stubborn_create_instance("A47979D2-C419-11D9-A5B4-001185AD2B89", iid)
try:
client, ipid = windows.rpc.stubborn.stubborn_create_instance("A47979D2-C419-11D9-A5B4-001185AD2B89", iid)
except Exception as e:
dbginfo = getattr(e, "stubborn_info", None)
if dbginfo:
for x in dbginfo.items():
print(x)
raise
response = client.call(iid, 17, b"", ipid=ipid)
assert response[0] not in (b"\x00", 0)
+27 -2
View File
@@ -28,7 +28,7 @@ class TestCurrentProcessWithCheckGarbage(object):
return windows.current_process.peb
def test_get_current_process_modules(self):
# Use module filename because this executable can be:
# Use module filename because this executable can be:
# 1. A PyInstaller exe
# 2. A Windows App execution alias (Microsoft Store builds)
assert os.path.basename(windows.current_process.peb.ProcessParameters[0].ImagePathName.str) in windows.current_process.peb.modules[0].name
@@ -474,11 +474,28 @@ class TestProcessWithCheckGarbage(object):
with proc32_64.allocated_memory(0x1000) as addr:
assert proc32_64.get_mapped_filename(addr) is None
def test_current_thread_teb(self):
teb = windows.current_thread.teb
assert ctypes.addressof(teb) == ctypes.addressof(windows.current_thread.teb.NtTib.Self[0])
assert ctypes.addressof(windows.current_process.peb) == ctypes.addressof(teb.ProcessEnvironmentBlock[0])
# Check type of teb.peb is the correct subclass (with modules & co)
assert teb.peb.modules
def test_thread_teb_base(self, proc32_64):
t = proc32_64.threads[0]
assert t.teb_base != 0
def test_teb(self, proc32_64):
teb = proc32_64.threads[0].teb
if proc32_64.bitness == 32:
assert type(teb) == windows.winobject.process.RemoteTEB32
else:
assert type(teb) == windows.winobject.process.RemoteTEB64
assert teb.NtTib.Self.value == teb._base_addr
assert teb.ProcessEnvironmentBlock.value == teb.peb._base_addr
# Check type of teb.peb is the correct subclass (with modules & co)
assert teb.peb.modules
@windows_64bit_only
def test_thread_teb_syswow_base(self, proc32):
t = proc32.threads[0]
@@ -486,7 +503,15 @@ class TestProcessWithCheckGarbage(object):
assert t.teb_syswow_base != 0
assert t.teb_base == t.teb_syswow_base + 0x2000
@windows_64bit_only
def test_thread_teb_syswow(self, proc32):
teb_syswow = proc32.threads[0].teb_syswow
assert type(teb_syswow) == windows.winobject.process.RemoteTEB64
assert type(teb_syswow.peb) == windows.winobject.process.RemotePEB64
assert teb_syswow.NtTib.Self.value == teb_syswow._base_addr
assert teb_syswow.ProcessEnvironmentBlock.value == teb_syswow.peb._base_addr
# Check type of teb.peb is the correct subclass (with modules & co)
assert teb_syswow.peb.modules
def test_thread_owner_from_tid(self, proc32_64):
thread = proc32_64.threads[0]
+1 -1
View File
@@ -29,7 +29,7 @@ def test_remote_struct_same_bitness():
# This test fails for now. (0.6)
# Should I improve remote ctypes to handel this ?
@pytest.mark.known_to_fail
@pytest.mark.xfail
def test_remote_long_ptr():
# Bug thatwas in retrieving of NtCreateFile arguments
target = windows.current_process
+3 -3
View File
@@ -5,7 +5,7 @@ import os.path
import windows
import windows.generated_def as gdef
SCHTASKS = "c:\Windows\System32\schtasks.exe"
SCHTASKS = r"c:\Windows\System32\schtasks.exe"
task_scheduler = windows.system.task_scheduler
@@ -28,9 +28,9 @@ def schtasks_task_exists(taskname):
raise
SCHEDULED_TASK_PARAMS = [
{"DIR": "", "NAME": "PFW_TEST1", "PATH": '"c:\windows\system32\notepad.exe"', "ARGS": "PFW_TEST_PARAM.txt"},
{"DIR": "", "NAME": "PFW_TEST1", "PATH": r'"c:\windows\system32\notepad.exe"', "ARGS": "PFW_TEST_PARAM.txt"},
# Test in subdir
{"DIR": "PFW_TEST_DIR", "NAME": "PFW_TEST1", "PATH": '"c:\windows\system32\notepad.exe"', "ARGS": "PFW_TEST_PARAM.txt"}
{"DIR": "PFW_TEST_DIR", "NAME": "PFW_TEST1", "PATH": r'"c:\windows\system32\notepad.exe"', "ARGS": "PFW_TEST_PARAM.txt"}
]
+5 -5
View File
@@ -13,7 +13,7 @@ DEFAULT_DBG_OPTION = gdef.SYMOPT_DEFERRED_LOADS + gdef.SYMOPT_UNDNAME
def set_dbghelp_path(path):
"""Set the path of the ``dbghelp.dll`` file to use. It allow to configure a different version of the DLL handling PDB downloading.
r"""Set the path of the ``dbghelp.dll`` file to use. It allow to configure a different version of the DLL handling PDB downloading.
If ``path`` is a directory, the final ``dbghelp.dll`` will be computed as
``path\<current_process_bitness>\dbghelp.dll``.
@@ -124,7 +124,7 @@ class SymbolInfoA(gdef.SYMBOL_INFO, SymbolInfoBase):
CHAR_TYPE = gdef.CHAR
class SymbolInfoW(gdef.SYMBOL_INFOW, SymbolInfoBase):
"""Represent a Symbol.
r"""Represent a Symbol.
This class in based on the class `SYMBOL_INFO <https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/ns-dbghelp-symbol_info>`_
with the handling on displacement embeded into it.s
@@ -326,7 +326,7 @@ class SymbolModule(gdef.IMAGEHLP_MODULEW64):
@property
def pdb(self):
"""The local path of the loaded PDB if present
r"""The local path of the loaded PDB if present
Exemple:
>>> sh = windows.debug.symbols.VirtualSymbolHandler()
@@ -455,7 +455,7 @@ class SymbolHandler(object):
return sym
def resolve(self, name_or_addr):
"""Resolve ``name_or_addr``.
r"""Resolve ``name_or_addr``.
If its an int -> Return the :class:`SymbolInfo` at the address.
If its a string -> Return the :class:`SymbolInfo` corresponding to the symbol name
@@ -504,7 +504,7 @@ class SymbolHandler(object):
return True
def search(self, mask, mod=0, tag=0, options=gdef.SYMSEARCH_ALLITEMS, callback=None):
"""Search the symbols matching ``mask`` (``Windbg`` like).
r"""Search the symbols matching ``mask`` (``Windbg`` like).
:return: [:class:`SymbolInfo`] -- A list of :class:`SymbolInfo`
+6
View File
@@ -12730,6 +12730,7 @@ structs = {'ACCESS_ALLOWED_ACE',
'NET_DISPLAY_USER',
'NPBITMAP',
'NPRGBTRIPLE',
'NT_TIB',
'OBJECTS_AND_NAME_A',
'OBJECTS_AND_NAME_W',
'OBJECTS_AND_SID',
@@ -13471,6 +13472,7 @@ structs = {'ACCESS_ALLOWED_ACE',
'SYSTEM_RESOURCE_ATTRIBUTE_ACE',
'SYSTEM_SCOPED_POLICY_ID_ACE',
'SYSTEM_VERIFIER_INFORMATION',
'TEB',
'THREADENTRY32',
'THREAD_BASIC_INFORMATION',
'TIME_ZONE_INFORMATION',
@@ -13772,6 +13774,7 @@ structs = {'ACCESS_ALLOWED_ACE',
'_EXCEPTION_RECORD',
'_EXCEPTION_RECORD32',
'_EXCEPTION_RECORD64',
'_EXCEPTION_REGISTRATION_RECORD',
'_EXIT_PROCESS_DEBUG_INFO',
'_EXIT_THREAD_DEBUG_INFO',
'_EXPLICIT_ACCESS_W',
@@ -13917,6 +13920,7 @@ structs = {'ACCESS_ALLOWED_ACE',
'_NET_DISPLAY_GROUP',
'_NET_DISPLAY_MACHINE',
'_NET_DISPLAY_USER',
'_NT_TIB',
'_OBJECTS_AND_NAME_A',
'_OBJECTS_AND_NAME_W',
'_OBJECTS_AND_SID',
@@ -14047,6 +14051,7 @@ structs = {'ACCESS_ALLOWED_ACE',
'_SYSTEM_RESOURCE_ATTRIBUTE_ACE',
'_SYSTEM_SCOPED_POLICY_ID_ACE',
'_SYSTEM_VERIFIER_INFORMATION',
'_TEB',
'_THREAD_BASIC_INFORMATION',
'_TIME_ZONE_INFORMATION',
'_TMPUNION_CERT_ID',
@@ -15113,6 +15118,7 @@ functions = {'AccessCheck',
'RtlDosPathNameToNtPathName_U',
'RtlEqualUnicodeString',
'RtlGetCompressionWorkSpaceSize',
'RtlGetCurrentPeb',
'RtlGetUnloadEventTraceEx',
'RtlInitString',
'RtlInitUnicodeString',
+5
View File
@@ -1735,6 +1735,11 @@ LoadLibraryExWParams = ((1, 'lpLibFileName'), (1, 'hFile'), (1, 'dwFlags'))
FreeLibraryPrototype = WINFUNCTYPE(BOOL, HMODULE)
FreeLibraryParams = ((1, 'hLibModule'),)
#def RtlGetCurrentPeb():
# return RtlGetCurrentPeb.ctypes_function()
RtlGetCurrentPebPrototype = WINFUNCTYPE(PVOID)
RtlGetCurrentPebParams = ()
#def RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData):
# return RegQueryValueExA.ctypes_function(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
RegQueryValueExAPrototype = WINFUNCTYPE(LSTATUS, HKEY, LPCSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD)
+477 -388
View File
@@ -1902,7 +1902,8 @@ ATTACH_VIRTUAL_DISK_PARAMETERS = _ATTACH_VIRTUAL_DISK_PARAMETERS
PATTACH_VIRTUAL_DISK_PARAMETERS = POINTER(_ATTACH_VIRTUAL_DISK_PARAMETERS)
# Self referencing struct tricks
class _INTERNET_BUFFERSA(Structure): pass
class _INTERNET_BUFFERSA(Structure):
pass
INTERNET_BUFFERSA = _INTERNET_BUFFERSA
LPINTERNET_BUFFERSA = POINTER(_INTERNET_BUFFERSA)
_INTERNET_BUFFERSA._fields_ = [
@@ -1919,7 +1920,8 @@ _INTERNET_BUFFERSA._fields_ = [
]
# Self referencing struct tricks
class _INTERNET_BUFFERSW(Structure): pass
class _INTERNET_BUFFERSW(Structure):
pass
INTERNET_BUFFERSW = _INTERNET_BUFFERSW
LPINTERNET_BUFFERSW = POINTER(_INTERNET_BUFFERSW)
_INTERNET_BUFFERSW._fields_ = [
@@ -2453,7 +2455,8 @@ IP_INTERFACE_INFO = _IP_INTERFACE_INFO
PIP_INTERFACE_INFO = POINTER(_IP_INTERFACE_INFO)
# Self referencing struct tricks
class _DNS_CACHE_ENTRY(Structure): pass
class _DNS_CACHE_ENTRY(Structure):
pass
DNS_CACHE_ENTRY = _DNS_CACHE_ENTRY
PDNS_CACHE_ENTRY = POINTER(_DNS_CACHE_ENTRY)
_DNS_CACHE_ENTRY._fields_ = [
@@ -2982,7 +2985,9 @@ class _ANON__DNSRECORDA_SUB_UNION_2(Union):
]
# Self referencing struct tricks
class _DnsRecordA(Structure): pass
class _DnsRecordA(Structure):
_anonymous_ = ("Flags","Data")
DNS_RECORDA = _DnsRecordA
PDNS_RECORDA = POINTER(_DnsRecordA)
_DnsRecordA._fields_ = [
@@ -3092,7 +3097,9 @@ class _ANON__DNSRECORDW_SUB_UNION_2(Union):
]
# Self referencing struct tricks
class _DnsRecordW(Structure): pass
class _DnsRecordW(Structure):
_anonymous_ = ("Flags","Data")
DNS_RECORDW = _DnsRecordW
PDNS_RECORDW = POINTER(_DnsRecordW)
_DnsRecordW._fields_ = [
@@ -3171,7 +3178,8 @@ PIP_ADDRESS_STRING = POINTER(IP_ADDRESS_STRING)
PIP_MASK_STRING = POINTER(IP_ADDRESS_STRING)
# Self referencing struct tricks
class _IP_ADDR_STRING(Structure): pass
class _IP_ADDR_STRING(Structure):
pass
IP_ADDR_STRING = _IP_ADDR_STRING
PIP_ADDR_STRING = POINTER(_IP_ADDR_STRING)
_IP_ADDR_STRING._fields_ = [
@@ -3182,7 +3190,8 @@ _IP_ADDR_STRING._fields_ = [
]
# Self referencing struct tricks
class _IP_ADAPTER_INFO(Structure): pass
class _IP_ADAPTER_INFO(Structure):
pass
IP_ADAPTER_INFO = _IP_ADAPTER_INFO
PIP_ADAPTER_INFO = POINTER(_IP_ADAPTER_INFO)
_IP_ADAPTER_INFO._fields_ = [
@@ -3876,6 +3885,114 @@ class _SHFILEOPSTRUCTA(Structure):
LPSHFILEOPSTRUCTA = POINTER(_SHFILEOPSTRUCTA)
SHFILEOPSTRUCTA = _SHFILEOPSTRUCTA
# Self referencing struct tricks
class _LIST_ENTRY(Structure):
pass
LIST_ENTRY = _LIST_ENTRY
PLIST_ENTRY = POINTER(_LIST_ENTRY)
PRLIST_ENTRY = POINTER(_LIST_ENTRY)
_LIST_ENTRY._fields_ = [
("Flink", POINTER(_LIST_ENTRY)),
("Blink", POINTER(_LIST_ENTRY)),
]
# From: ctypes_generation\extended_structs\_LIST_ENTRY.py
# _LIST_ENTRY is a self referencing structure
# Currently ctypes generation does not support extending self referencing structures
# Ass the _fields_ assignement should happen after the extended structure definition
# So we just redefine fully _LIST_ENTRY without inheriting the real one
class _LIST_ENTRY(Structure):
def get_real_struct(self, targetcls, target_field):
# >>> gdef.LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks
# <Field type=_LIST_ENTRY, ofs=16, size=16>
# This field object does not allow to retrieve the type..
# So we need to basse the target class AND the target field..
return targetcls.from_address(ctypes.addressof(self) - target_field.offset)
_LIST_ENTRY._fields_ = [
("Flink", POINTER(_LIST_ENTRY)),
("Blink", POINTER(_LIST_ENTRY)),
]
LIST_ENTRY = _LIST_ENTRY
PLIST_ENTRY = POINTER(_LIST_ENTRY)
PRLIST_ENTRY = POINTER(_LIST_ENTRY)
class _LSA_UNICODE_STRING(Structure):
_fields_ = [
("Length", USHORT),
("MaximumLength", USHORT),
("Buffer", PVOID),
]
LSA_UNICODE_STRING = _LSA_UNICODE_STRING
PLSA_UNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
PUNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
UNICODE_STRING = _LSA_UNICODE_STRING
INITIAL_LSA_UNICODE_STRING = _LSA_UNICODE_STRING
class _LSA_UNICODE_STRING(INITIAL_LSA_UNICODE_STRING):
@property
def str(self):
"""The python string of the LSA_UNICODE_STRING object
:type: :class:`unicode`
"""
if not self.Length:
return ""
if getattr(self, "_target", None) is not None: #remote ctypes :D -> TRICKS OF THE YEAR
raw_data = self._target.read_memory(self.Buffer, self.Length)
return raw_data.decode("utf16")
size = int(self.Length / 2)
return (ctypes.c_wchar * size).from_address(self.Buffer)[:]
@classmethod
def from_string(cls, s):
utf16_len = len(s) * 2
return cls(utf16_len, utf16_len, ctypes.cast(PWSTR(s), PVOID))
@classmethod
def from_size(cls, size):
buffer = ctypes.create_string_buffer(size)
return cls(size, size, ctypes.cast(buffer, PVOID))
def __repr__(self):
return windows.pycompat.urepr_encode(u"""<{0} "{1}" at {2}>""".format(type(self).__name__, self.str, hex(id(self))))
def __sprint__(self):
try:
return self.__repr__()
except TypeError as e:
# Bad buffer: print raw infos
return """<{0} len={1} maxlen={2} buffer={3}>""".format(type(self).__name__, self.Length, self.MaximumLength, self.Buffer)
LSA_UNICODE_STRING = _LSA_UNICODE_STRING
PLSA_UNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
PUNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
UNICODE_STRING = _LSA_UNICODE_STRING
class _CLIENT_ID(Structure):
_fields_ = [
("UniqueProcess", HANDLE),
("UniqueThread", HANDLE),
]
CLIENT_ID = _CLIENT_ID
PCLIENT_ID = POINTER(_CLIENT_ID)
class _CLIENT_ID64(Structure):
_fields_ = [
("UniqueProcess", ULONG64),
("UniqueThread", ULONG64),
]
CLIENT_ID64 = _CLIENT_ID64
PCLIENT_ID64 = POINTER(_CLIENT_ID64)
class _CLIENT_ID32(Structure):
_fields_ = [
("UniqueProcess", ULONG),
("UniqueThread", ULONG),
]
CLIENT_ID32 = _CLIENT_ID32
PCLIENT_ID32 = POINTER(_CLIENT_ID32)
SymNone = EnumValue("SYM_TYPE", "SymNone", 0x0)
SymCoff = EnumValue("SYM_TYPE", "SymCoff", 0x1)
SymCv = EnumValue("SYM_TYPE", "SymCv", 0x2)
@@ -4437,6 +4554,82 @@ class _tagSTACKFRAME_EX(Structure):
LPSTACKFRAME_EX = POINTER(_tagSTACKFRAME_EX)
STACKFRAME_EX = _tagSTACKFRAME_EX
ComputerNameNetBIOS = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameNetBIOS", 0x0)
ComputerNameDnsHostname = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsHostname", 0x1)
ComputerNameDnsDomain = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsDomain", 0x2)
ComputerNameDnsFullyQualified = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsFullyQualified", 0x3)
ComputerNamePhysicalNetBIOS = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalNetBIOS", 0x4)
ComputerNamePhysicalDnsHostname = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsHostname", 0x5)
ComputerNamePhysicalDnsDomain = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsDomain", 0x6)
ComputerNamePhysicalDnsFullyQualified = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsFullyQualified", 0x7)
ComputerNameMax = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameMax", 0x8)
class _COMPUTER_NAME_FORMAT(EnumType):
values = [ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified, ComputerNameMax]
mapper = FlagMapper(*values)
COMPUTER_NAME_FORMAT = _COMPUTER_NAME_FORMAT
class _SYSTEM_PROCESS_INFORMATION(Structure):
_fields_ = [
("NextEntryOffset", ULONG),
("NumberOfThreads", ULONG),
("Reserved1", BYTE * (24)),
("CreateTime", LARGE_INTEGER),
("UserTime", LARGE_INTEGER),
("KernelTime", LARGE_INTEGER),
("ImageName", UNICODE_STRING),
("BasePriority", LONG),
("UniqueProcessId", HANDLE),
("InheritedFromUniqueProcessId", PVOID),
("HandleCount", ULONG),
("Reserved4", BYTE * (4)),
("Reserved5", PVOID * (1)),
("PeakVirtualSize", PVOID),
("VirtualSize", PVOID),
("PageFaultCount", PVOID),
("PeakWorkingSetSize", PVOID),
("WorkingSetSize", PVOID),
("QuotaPeakPagedPoolUsage", PVOID),
("QuotaPagedPoolUsage", PVOID),
("QuotaPeakNonPagedPoolUsage", PVOID),
("QuotaNonPagedPoolUsage", PVOID),
("PagefileUsage", PVOID),
("PeakPagefileUsage", SIZE_T),
("PrivatePageCount", SIZE_T),
("Reserved6", LARGE_INTEGER * (6)),
]
PSYSTEM_PROCESS_INFORMATION = POINTER(_SYSTEM_PROCESS_INFORMATION)
SYSTEM_PROCESS_INFORMATION = _SYSTEM_PROCESS_INFORMATION
class _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION(Structure):
_fields_ = [
("IdleTime", LARGE_INTEGER),
("KernelTime", LARGE_INTEGER),
("UserTime", LARGE_INTEGER),
("Reserved1", LARGE_INTEGER * (2)),
("Reserved2", ULONG),
]
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION = POINTER(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION = _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
class _SYSTEM_REGISTRY_QUOTA_INFORMATION(Structure):
_fields_ = [
("RegistryQuotaAllowed", ULONG),
("RegistryQuotaUsed", ULONG),
("Reserved1", PVOID),
]
PSYSTEM_REGISTRY_QUOTA_INFORMATION = POINTER(_SYSTEM_REGISTRY_QUOTA_INFORMATION)
SYSTEM_REGISTRY_QUOTA_INFORMATION = _SYSTEM_REGISTRY_QUOTA_INFORMATION
class _SYSTEM_BASIC_INFORMATION(Structure):
_fields_ = [
("Reserved1", BYTE * (24)),
("Reserved2", PVOID * (4)),
("NumberOfProcessors", CHAR),
]
PSYSTEM_BASIC_INFORMATION = POINTER(_SYSTEM_BASIC_INFORMATION)
SYSTEM_BASIC_INFORMATION = _SYSTEM_BASIC_INFORMATION
TASK_ACTION_EXEC = EnumValue("_TASK_ACTION_TYPE", "TASK_ACTION_EXEC", 0x0)
TASK_ACTION_COM_HANDLER = EnumValue("_TASK_ACTION_TYPE", "TASK_ACTION_COM_HANDLER", 0x5)
TASK_ACTION_SEND_EMAIL = EnumValue("_TASK_ACTION_TYPE", "TASK_ACTION_SEND_EMAIL", 0x6)
@@ -4545,6 +4738,269 @@ class TASK_RUN_FLAGS(EnumType):
mapper = FlagMapper(*values)
class _CURDIR(Structure):
_fields_ = [
("DosPath", UNICODE_STRING),
("Handle", PVOID),
]
CURDIR = _CURDIR
PCURDIR = POINTER(_CURDIR)
class _RTL_DRIVE_LETTER_CURDIR(Structure):
_fields_ = [
("Flags", WORD),
("Length", WORD),
("TimeStamp", ULONG),
("DosPath", UNICODE_STRING),
]
PRTL_DRIVE_LETTER_CURDIR = POINTER(_RTL_DRIVE_LETTER_CURDIR)
RTL_DRIVE_LETTER_CURDIR = _RTL_DRIVE_LETTER_CURDIR
class _RTL_USER_PROCESS_PARAMETERS(Structure):
_fields_ = [
("MaximumLength", ULONG),
("Length", ULONG),
("Flags", ULONG),
("DebugFlags", ULONG),
("ConsoleHandle", PVOID),
("ConsoleFlags", ULONG),
("StandardInput", PVOID),
("StandardOutput", PVOID),
("StandardError", PVOID),
("CurrentDirectory", CURDIR),
("DllPath", UNICODE_STRING),
("ImagePathName", UNICODE_STRING),
("CommandLine", UNICODE_STRING),
("Environment", PVOID),
("StartingX", ULONG),
("StartingY", ULONG),
("CountX", ULONG),
("CountY", ULONG),
("CountCharsX", ULONG),
("CountCharsY", ULONG),
("FillAttribute", ULONG),
("WindowFlags", ULONG),
("ShowWindowFlags", ULONG),
("WindowTitle", UNICODE_STRING),
("DesktopInfo", UNICODE_STRING),
("ShellInfo", UNICODE_STRING),
("RuntimeData", UNICODE_STRING),
("CurrentDirectores", RTL_DRIVE_LETTER_CURDIR * (32)),
]
PRTL_USER_PROCESS_PARAMETERS = POINTER(_RTL_USER_PROCESS_PARAMETERS)
RTL_USER_PROCESS_PARAMETERS = _RTL_USER_PROCESS_PARAMETERS
class _LDR_DATA_TABLE_ENTRY(Structure):
_fields_ = [
("Reserved1", PVOID * (2)),
("InMemoryOrderLinks", LIST_ENTRY),
("Reserved2", PVOID * (2)),
("DllBase", PVOID),
("EntryPoint", PVOID),
("SizeOfImage", PVOID),
("FullDllName", UNICODE_STRING),
("BaseDllName", UNICODE_STRING),
("Reserved5", PVOID * (3)),
("CheckSum", ULONG),
("TimeDateStamp", ULONG),
]
LDR_DATA_TABLE_ENTRY = _LDR_DATA_TABLE_ENTRY
PLDR_DATA_TABLE_ENTRY = POINTER(_LDR_DATA_TABLE_ENTRY)
class _PEB_LDR_DATA(Structure):
_fields_ = [
("Length", ULONG),
("Initialized", BYTE),
("SsHandle", PVOID),
("InLoadOrderModuleList", _LIST_ENTRY),
("InMemoryOrderModuleList", _LIST_ENTRY),
("InInitializationOrderModuleList", _LIST_ENTRY),
("EntryInProgress", PVOID),
]
PEB_LDR_DATA = _PEB_LDR_DATA
PPEB_LDR_DATA = POINTER(_PEB_LDR_DATA)
class _ANON_PEB_SYSTEM_DEPENDENT_02(Union):
_fields_ = [
("FastPebLockRoutine", PVOID),
("SparePtr1", PVOID),
("AtlThunkSListPtr", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_03(Union):
_fields_ = [
("FastPebUnlockRoutine", PVOID),
("SparePtr2", PVOID),
("IFEOKey", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_06(Union):
_fields_ = [
("FreeList", PVOID),
("SparePebPtr0", PVOID),
("ApiSetMap", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_07(Union):
_fields_ = [
("ReadOnlySharedMemoryHeap", PVOID),
("HotpatchInformation", PVOID),
("SparePvoid0", PVOID),
]
class _ANON_PEB_UNION_1(Union):
_fields_ = [
("KernelCallbackTable", PVOID),
("UserSharedInfoPtr", PVOID),
]
class _ANON_PEB_UNION_2(Union):
_fields_ = [
("ImageProcessAffinityMask", PVOID),
("ActiveProcessAffinityMask", PVOID),
]
class _ANON__PEB_SUB_UNION_1(Union):
_fields_ = [
("KernelCallbackTable", PVOID),
("UserSharedInfoPtr", PVOID),
]
class _ANON__PEB_SUB_UNION_2(Union):
_fields_ = [
("ImageProcessAffinityMask", PVOID),
("ActiveProcessAffinityMask", PVOID),
]
class _PEB(Structure):
_anonymous_ = ("_SYSTEM_DEPENDENT_02","_SYSTEM_DEPENDENT_03","anon_01","_SYSTEM_DEPENDENT_06","_SYSTEM_DEPENDENT_07","anon_02")
_fields_ = [
("Reserved1", BYTE * (2)),
("BeingDebugged", BYTE),
("Reserved2", BYTE * (1)),
("Mutant", PVOID),
("ImageBaseAddress", PVOID),
("Ldr", PPEB_LDR_DATA),
("ProcessParameters", PRTL_USER_PROCESS_PARAMETERS),
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID),
("_SYSTEM_DEPENDENT_02", _ANON_PEB_SYSTEM_DEPENDENT_02),
("_SYSTEM_DEPENDENT_03", _ANON_PEB_SYSTEM_DEPENDENT_03),
("_SYSTEM_DEPENDENT_04", PVOID),
("anon_01", _ANON__PEB_SUB_UNION_1),
("SystemReserved", DWORD),
("_SYSTEM_DEPENDENT_05", DWORD),
("_SYSTEM_DEPENDENT_06", _ANON_PEB_SYSTEM_DEPENDENT_06),
("TlsExpansionCounter", PVOID),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * (2)),
("ReadOnlySharedMemoryBase", PVOID),
("_SYSTEM_DEPENDENT_07", _ANON_PEB_SYSTEM_DEPENDENT_07),
("ReadOnlyStaticServerData", PVOID),
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LARGE_INTEGER),
("HeapSegmentReserve", PVOID),
("HeapSegmentCommit", PVOID),
("HeapDeCommitTotalFreeThreshold", PVOID),
("HeapDeCommitFreeBlockThreshold", PVOID),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID),
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", PVOID),
("LoaderLock", PVOID),
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", PVOID),
("anon_02", _ANON__PEB_SUB_UNION_2),
("GdiHandleBuffer", PVOID * (26)),
("GdiHandleBuffer2", BYTE * (32)),
("PostProcessInitRoutine", PVOID),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * (32)),
("SessionId", PVOID),
("AppCompatFlags", ULARGE_INTEGER),
("AppCompatFlagsUser", ULARGE_INTEGER),
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID),
("ProcessAssemblyStorageMap", PVOID),
("SystemDefaultActivationContextData", PVOID),
("SystemAssemblyStorageMap", PVOID),
("MinimumStackCommit", PVOID),
]
PEB = _PEB
PPEB = POINTER(_PEB)
# Self referencing struct tricks
class _EXCEPTION_REGISTRATION_RECORD(Structure):
pass
_EXCEPTION_REGISTRATION_RECORD._fields_ = [
("Next", POINTER(_EXCEPTION_REGISTRATION_RECORD)),
("Handler", PVOID),
]
class _ANON__NT_TIB_SUB_UNION_1(Union):
_fields_ = [
("FiberData", PVOID),
("Version", ULONG),
]
# Self referencing struct tricks
class _NT_TIB(Structure):
_anonymous_ = ("anon_01",)
NT_TIB = _NT_TIB
_NT_TIB._fields_ = [
("ExceptionList", POINTER(_EXCEPTION_REGISTRATION_RECORD)),
("StackBase", PVOID),
("StackLimit", PVOID),
("SubSystemTib", PVOID),
("anon_01", _ANON__NT_TIB_SUB_UNION_1),
("ArbitraryUserPointer", PVOID),
("Self", POINTER(_NT_TIB)),
]
class _TEB(Structure):
_fields_ = [
("NtTib", _NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", _CLIENT_ID),
("ActiveRpcHandle", PVOID),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", POINTER(_PEB)),
("LastErrorValue", ULONG),
("CountOfOwnedCriticalSections", ULONG),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", ULONG * (26)),
("UserReserved", ULONG * (5)),
("WOW32Reserved", PVOID),
("CurrentLocale", ULONG),
("FpSoftwareStatusRegister", ULONG),
]
TEB = _TEB
class _TRACE_PROVIDER_INFO(Structure):
_fields_ = [
("ProviderGuid", GUID),
@@ -5426,264 +5882,6 @@ NT_PRODUCT_TYPE = _NT_PRODUCT_TYPE
PNT_PRODUCT_TYPE = POINTER(_NT_PRODUCT_TYPE)
# Self referencing struct tricks
class _LIST_ENTRY(Structure): pass
LIST_ENTRY = _LIST_ENTRY
PLIST_ENTRY = POINTER(_LIST_ENTRY)
PRLIST_ENTRY = POINTER(_LIST_ENTRY)
_LIST_ENTRY._fields_ = [
("Flink", POINTER(_LIST_ENTRY)),
("Blink", POINTER(_LIST_ENTRY)),
]
class _PEB_LDR_DATA(Structure):
_fields_ = [
("Length", ULONG),
("Initialized", BYTE),
("SsHandle", PVOID),
("InLoadOrderModuleList", _LIST_ENTRY),
("InMemoryOrderModuleList", _LIST_ENTRY),
("InInitializationOrderModuleList", _LIST_ENTRY),
("EntryInProgress", PVOID),
]
PEB_LDR_DATA = _PEB_LDR_DATA
PPEB_LDR_DATA = POINTER(_PEB_LDR_DATA)
class _LSA_UNICODE_STRING(Structure):
_fields_ = [
("Length", USHORT),
("MaximumLength", USHORT),
("Buffer", PVOID),
]
LSA_UNICODE_STRING = _LSA_UNICODE_STRING
PLSA_UNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
PUNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
UNICODE_STRING = _LSA_UNICODE_STRING
INITIAL_LSA_UNICODE_STRING = _LSA_UNICODE_STRING
class _LSA_UNICODE_STRING(INITIAL_LSA_UNICODE_STRING):
@property
def str(self):
"""The python string of the LSA_UNICODE_STRING object
:type: :class:`unicode`
"""
if not self.Length:
return ""
if getattr(self, "_target", None) is not None: #remote ctypes :D -> TRICKS OF THE YEAR
raw_data = self._target.read_memory(self.Buffer, self.Length)
return raw_data.decode("utf16")
size = int(self.Length / 2)
return (ctypes.c_wchar * size).from_address(self.Buffer)[:]
@classmethod
def from_string(cls, s):
utf16_len = len(s) * 2
return cls(utf16_len, utf16_len, ctypes.cast(PWSTR(s), PVOID))
@classmethod
def from_size(cls, size):
buffer = ctypes.create_string_buffer(size)
return cls(size, size, ctypes.cast(buffer, PVOID))
def __repr__(self):
return windows.pycompat.urepr_encode(u"""<{0} "{1}" at {2}>""".format(type(self).__name__, self.str, hex(id(self))))
def __sprint__(self):
try:
return self.__repr__()
except TypeError as e:
# Bad buffer: print raw infos
return """<{0} len={1} maxlen={2} buffer={3}>""".format(type(self).__name__, self.Length, self.MaximumLength, self.Buffer)
LSA_UNICODE_STRING = _LSA_UNICODE_STRING
PLSA_UNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
PUNICODE_STRING = POINTER(_LSA_UNICODE_STRING)
UNICODE_STRING = _LSA_UNICODE_STRING
class _CURDIR(Structure):
_fields_ = [
("DosPath", UNICODE_STRING),
("Handle", PVOID),
]
CURDIR = _CURDIR
PCURDIR = POINTER(_CURDIR)
class _RTL_DRIVE_LETTER_CURDIR(Structure):
_fields_ = [
("Flags", WORD),
("Length", WORD),
("TimeStamp", ULONG),
("DosPath", UNICODE_STRING),
]
PRTL_DRIVE_LETTER_CURDIR = POINTER(_RTL_DRIVE_LETTER_CURDIR)
RTL_DRIVE_LETTER_CURDIR = _RTL_DRIVE_LETTER_CURDIR
class _RTL_USER_PROCESS_PARAMETERS(Structure):
_fields_ = [
("MaximumLength", ULONG),
("Length", ULONG),
("Flags", ULONG),
("DebugFlags", ULONG),
("ConsoleHandle", PVOID),
("ConsoleFlags", ULONG),
("StandardInput", PVOID),
("StandardOutput", PVOID),
("StandardError", PVOID),
("CurrentDirectory", CURDIR),
("DllPath", UNICODE_STRING),
("ImagePathName", UNICODE_STRING),
("CommandLine", UNICODE_STRING),
("Environment", PVOID),
("StartingX", ULONG),
("StartingY", ULONG),
("CountX", ULONG),
("CountY", ULONG),
("CountCharsX", ULONG),
("CountCharsY", ULONG),
("FillAttribute", ULONG),
("WindowFlags", ULONG),
("ShowWindowFlags", ULONG),
("WindowTitle", UNICODE_STRING),
("DesktopInfo", UNICODE_STRING),
("ShellInfo", UNICODE_STRING),
("RuntimeData", UNICODE_STRING),
("CurrentDirectores", RTL_DRIVE_LETTER_CURDIR * (32)),
]
PRTL_USER_PROCESS_PARAMETERS = POINTER(_RTL_USER_PROCESS_PARAMETERS)
RTL_USER_PROCESS_PARAMETERS = _RTL_USER_PROCESS_PARAMETERS
class _ANON_PEB_SYSTEM_DEPENDENT_02(Union):
_fields_ = [
("FastPebLockRoutine", PVOID),
("SparePtr1", PVOID),
("AtlThunkSListPtr", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_03(Union):
_fields_ = [
("FastPebUnlockRoutine", PVOID),
("SparePtr2", PVOID),
("IFEOKey", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_06(Union):
_fields_ = [
("FreeList", PVOID),
("SparePebPtr0", PVOID),
("ApiSetMap", PVOID),
]
class _ANON_PEB_SYSTEM_DEPENDENT_07(Union):
_fields_ = [
("ReadOnlySharedMemoryHeap", PVOID),
("HotpatchInformation", PVOID),
("SparePvoid0", PVOID),
]
class _ANON_PEB_UNION_1(Union):
_fields_ = [
("KernelCallbackTable", PVOID),
("UserSharedInfoPtr", PVOID),
]
class _ANON_PEB_UNION_2(Union):
_fields_ = [
("ImageProcessAffinityMask", PVOID),
("ActiveProcessAffinityMask", PVOID),
]
class _ANON__PEB_SUB_UNION_1(Union):
_fields_ = [
("KernelCallbackTable", PVOID),
("UserSharedInfoPtr", PVOID),
]
class _ANON__PEB_SUB_UNION_2(Union):
_fields_ = [
("ImageProcessAffinityMask", PVOID),
("ActiveProcessAffinityMask", PVOID),
]
class _PEB(Structure):
_anonymous_ = ("_SYSTEM_DEPENDENT_02","_SYSTEM_DEPENDENT_03","anon_01","_SYSTEM_DEPENDENT_06","_SYSTEM_DEPENDENT_07","anon_02")
_fields_ = [
("Reserved1", BYTE * (2)),
("BeingDebugged", BYTE),
("Reserved2", BYTE * (1)),
("Mutant", PVOID),
("ImageBaseAddress", PVOID),
("Ldr", PPEB_LDR_DATA),
("ProcessParameters", PRTL_USER_PROCESS_PARAMETERS),
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID),
("_SYSTEM_DEPENDENT_02", _ANON_PEB_SYSTEM_DEPENDENT_02),
("_SYSTEM_DEPENDENT_03", _ANON_PEB_SYSTEM_DEPENDENT_03),
("_SYSTEM_DEPENDENT_04", PVOID),
("anon_01", _ANON__PEB_SUB_UNION_1),
("SystemReserved", DWORD),
("_SYSTEM_DEPENDENT_05", DWORD),
("_SYSTEM_DEPENDENT_06", _ANON_PEB_SYSTEM_DEPENDENT_06),
("TlsExpansionCounter", PVOID),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * (2)),
("ReadOnlySharedMemoryBase", PVOID),
("_SYSTEM_DEPENDENT_07", _ANON_PEB_SYSTEM_DEPENDENT_07),
("ReadOnlyStaticServerData", PVOID),
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LARGE_INTEGER),
("HeapSegmentReserve", PVOID),
("HeapSegmentCommit", PVOID),
("HeapDeCommitTotalFreeThreshold", PVOID),
("HeapDeCommitFreeBlockThreshold", PVOID),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID),
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", PVOID),
("LoaderLock", PVOID),
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", PVOID),
("anon_02", _ANON__PEB_SUB_UNION_2),
("GdiHandleBuffer", PVOID * (26)),
("GdiHandleBuffer2", BYTE * (32)),
("PostProcessInitRoutine", PVOID),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * (32)),
("SessionId", PVOID),
("AppCompatFlags", ULARGE_INTEGER),
("AppCompatFlagsUser", ULARGE_INTEGER),
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID),
("ProcessAssemblyStorageMap", PVOID),
("SystemDefaultActivationContextData", PVOID),
("SystemAssemblyStorageMap", PVOID),
("MinimumStackCommit", PVOID),
]
PEB = _PEB
PPEB = POINTER(_PEB)
class _SECURITY_ATTRIBUTES(Structure):
_fields_ = [
("nLength", DWORD),
@@ -5733,47 +5931,6 @@ class _SYSTEM_PROCESS_ID_INFORMATION(Structure):
PSYSTEM_PROCESS_ID_INFORMATION = POINTER(_SYSTEM_PROCESS_ID_INFORMATION)
SYSTEM_PROCESS_ID_INFORMATION = _SYSTEM_PROCESS_ID_INFORMATION
class _CLIENT_ID(Structure):
_fields_ = [
("UniqueProcess", HANDLE),
("UniqueThread", HANDLE),
]
CLIENT_ID = _CLIENT_ID
PCLIENT_ID = POINTER(_CLIENT_ID)
class _CLIENT_ID64(Structure):
_fields_ = [
("UniqueProcess", ULONG64),
("UniqueThread", ULONG64),
]
CLIENT_ID64 = _CLIENT_ID64
PCLIENT_ID64 = POINTER(_CLIENT_ID64)
class _CLIENT_ID32(Structure):
_fields_ = [
("UniqueProcess", ULONG),
("UniqueThread", ULONG),
]
CLIENT_ID32 = _CLIENT_ID32
PCLIENT_ID32 = POINTER(_CLIENT_ID32)
class _LDR_DATA_TABLE_ENTRY(Structure):
_fields_ = [
("Reserved1", PVOID * (2)),
("InMemoryOrderLinks", LIST_ENTRY),
("Reserved2", PVOID * (2)),
("DllBase", PVOID),
("EntryPoint", PVOID),
("SizeOfImage", PVOID),
("FullDllName", UNICODE_STRING),
("BaseDllName", UNICODE_STRING),
("Reserved5", PVOID * (3)),
("CheckSum", ULONG),
("TimeDateStamp", ULONG),
]
LDR_DATA_TABLE_ENTRY = _LDR_DATA_TABLE_ENTRY
PLDR_DATA_TABLE_ENTRY = POINTER(_LDR_DATA_TABLE_ENTRY)
class _MEMORY_BASIC_INFORMATION(Structure):
_fields_ = [
("BaseAddress", PVOID),
@@ -6441,7 +6598,8 @@ PRTL_OSVERSIONINFOEXW = POINTER(_OSVERSIONINFOEXW)
RTL_OSVERSIONINFOEXW = _OSVERSIONINFOEXW
# Self referencing struct tricks
class _EXCEPTION_RECORD(Structure): pass
class _EXCEPTION_RECORD(Structure):
pass
EXCEPTION_RECORD = _EXCEPTION_RECORD
PEXCEPTION_RECORD = POINTER(_EXCEPTION_RECORD)
_EXCEPTION_RECORD._fields_ = [
@@ -8639,7 +8797,8 @@ PCCERT_SIMPLE_CHAIN = POINTER(_CERT_SIMPLE_CHAIN)
PCERT_SIMPLE_CHAIN = POINTER(_CERT_SIMPLE_CHAIN)
# Self referencing struct tricks
class _CERT_CHAIN_CONTEXT(Structure): pass
class _CERT_CHAIN_CONTEXT(Structure):
pass
CERT_CHAIN_CONTEXT = _CERT_CHAIN_CONTEXT
PCCERT_CHAIN_CONTEXT = POINTER(_CERT_CHAIN_CONTEXT)
PCERT_CHAIN_CONTEXT = POINTER(_CERT_CHAIN_CONTEXT)
@@ -11004,7 +11163,9 @@ class _ANON__TRUSTEE_A_SUB_UNION_1(Union):
]
# Self referencing struct tricks
class _TRUSTEE_A(Structure): pass
class _TRUSTEE_A(Structure):
_anonymous_ = ("anon_01",)
PTRUSTEEA = POINTER(_TRUSTEE_A)
PTRUSTEE_A = POINTER(_TRUSTEE_A)
TRUSTEEA = _TRUSTEE_A
@@ -11038,7 +11199,9 @@ class _ANON__TRUSTEE_W_SUB_UNION_1(Union):
]
# Self referencing struct tricks
class _TRUSTEE_W(Structure): pass
class _TRUSTEE_W(Structure):
_anonymous_ = ("anon_01",)
PTRUSTEEW = POINTER(_TRUSTEE_W)
PTRUSTEE_W = POINTER(_TRUSTEE_W)
TRUSTEEW = _TRUSTEE_W
@@ -11064,82 +11227,6 @@ EXPLICIT_ACCESS_W = _EXPLICIT_ACCESS_W
PEXPLICIT_ACCESSW = POINTER(_EXPLICIT_ACCESS_W)
PEXPLICIT_ACCESS_W = POINTER(_EXPLICIT_ACCESS_W)
ComputerNameNetBIOS = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameNetBIOS", 0x0)
ComputerNameDnsHostname = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsHostname", 0x1)
ComputerNameDnsDomain = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsDomain", 0x2)
ComputerNameDnsFullyQualified = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameDnsFullyQualified", 0x3)
ComputerNamePhysicalNetBIOS = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalNetBIOS", 0x4)
ComputerNamePhysicalDnsHostname = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsHostname", 0x5)
ComputerNamePhysicalDnsDomain = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsDomain", 0x6)
ComputerNamePhysicalDnsFullyQualified = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNamePhysicalDnsFullyQualified", 0x7)
ComputerNameMax = EnumValue("_COMPUTER_NAME_FORMAT", "ComputerNameMax", 0x8)
class _COMPUTER_NAME_FORMAT(EnumType):
values = [ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified, ComputerNameMax]
mapper = FlagMapper(*values)
COMPUTER_NAME_FORMAT = _COMPUTER_NAME_FORMAT
class _SYSTEM_PROCESS_INFORMATION(Structure):
_fields_ = [
("NextEntryOffset", ULONG),
("NumberOfThreads", ULONG),
("Reserved1", BYTE * (24)),
("CreateTime", LARGE_INTEGER),
("UserTime", LARGE_INTEGER),
("KernelTime", LARGE_INTEGER),
("ImageName", UNICODE_STRING),
("BasePriority", LONG),
("UniqueProcessId", HANDLE),
("InheritedFromUniqueProcessId", PVOID),
("HandleCount", ULONG),
("Reserved4", BYTE * (4)),
("Reserved5", PVOID * (1)),
("PeakVirtualSize", PVOID),
("VirtualSize", PVOID),
("PageFaultCount", PVOID),
("PeakWorkingSetSize", PVOID),
("WorkingSetSize", PVOID),
("QuotaPeakPagedPoolUsage", PVOID),
("QuotaPagedPoolUsage", PVOID),
("QuotaPeakNonPagedPoolUsage", PVOID),
("QuotaNonPagedPoolUsage", PVOID),
("PagefileUsage", PVOID),
("PeakPagefileUsage", SIZE_T),
("PrivatePageCount", SIZE_T),
("Reserved6", LARGE_INTEGER * (6)),
]
PSYSTEM_PROCESS_INFORMATION = POINTER(_SYSTEM_PROCESS_INFORMATION)
SYSTEM_PROCESS_INFORMATION = _SYSTEM_PROCESS_INFORMATION
class _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION(Structure):
_fields_ = [
("IdleTime", LARGE_INTEGER),
("KernelTime", LARGE_INTEGER),
("UserTime", LARGE_INTEGER),
("Reserved1", LARGE_INTEGER * (2)),
("Reserved2", ULONG),
]
PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION = POINTER(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION = _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
class _SYSTEM_REGISTRY_QUOTA_INFORMATION(Structure):
_fields_ = [
("RegistryQuotaAllowed", ULONG),
("RegistryQuotaUsed", ULONG),
("Reserved1", PVOID),
]
PSYSTEM_REGISTRY_QUOTA_INFORMATION = POINTER(_SYSTEM_REGISTRY_QUOTA_INFORMATION)
SYSTEM_REGISTRY_QUOTA_INFORMATION = _SYSTEM_REGISTRY_QUOTA_INFORMATION
class _SYSTEM_BASIC_INFORMATION(Structure):
_fields_ = [
("Reserved1", BYTE * (24)),
("Reserved2", PVOID * (4)),
("NumberOfProcessors", CHAR),
]
PSYSTEM_BASIC_INFORMATION = POINTER(_SYSTEM_BASIC_INFORMATION)
SYSTEM_BASIC_INFORMATION = _SYSTEM_BASIC_INFORMATION
class _TIME_ZONE_INFORMATION(Structure):
_fields_ = [
("Bias", LONG),
@@ -12526,7 +12613,8 @@ class sockaddr_in(Structure):
# Self referencing struct tricks
class addrinfoW(Structure): pass
class addrinfoW(Structure):
pass
ADDRINFOW = addrinfoW
PADDRINFOW = POINTER(addrinfoW)
addrinfoW._fields_ = [
@@ -12601,7 +12689,8 @@ LPWSAPROTOCOL_INFOW = POINTER(_WSAPROTOCOL_INFOW)
WSAPROTOCOL_INFOW = _WSAPROTOCOL_INFOW
# Self referencing struct tricks
class addrinfo(Structure): pass
class addrinfo(Structure):
pass
ADDRINFOA = addrinfo
PADDRINFOA = POINTER(addrinfo)
addrinfo._fields_ = [
+12 -1
View File
@@ -73,7 +73,18 @@ def stubborn_create_instance(clsid, iid):
# Bad alignement for everythin -> Legacy
resolver_info = ctypes.cast(rpiv_infoptr, gdef.PPRIV_RESOLVER_INFO_LEGACY)[0]
psa = resolver_info.OxidInfo.psa[0] # Retrieve the bidings to our COM server
try:
psa = resolver_info.OxidInfo.psa[0] # Retrieve the bidings to our COM server
except ValueError as e:
# Seen case of NULL DEREF
# Embed more value to the except for better debugging
e.stubborn_info = {
"resolver_info.OxidInfo.containerVersion.version": resolver_info.OxidInfo.containerVersion.version,
"dcomversion": (dcomversionstruct.MajorVersion, dcomversionstruct.MinorVersion),
"resolver_info": resolver_info,
}
raise
# print("psa.bidings: {0}".format(psa.bidings))
# ipidRemUnknown = resolver_info.OxidInfo.ipidRemUnknown # Useful for IRemQueryInterface
+9 -10
View File
@@ -164,19 +164,18 @@ def get_current_process_syswow_peb_addr():
def get_current_process_syswow_peb():
current_process = windows.current_process
class CurrentProcessReadSyswow(process.Process):
bitness = 64
def _get_handle(self):
return winproxy.OpenProcess(dwProcessId=current_process.pid)
def read_memory(self, addr, size):
buffer_addr = ctypes.create_string_buffer(size)
winproxy.NtWow64ReadVirtualMemory64(self.handle, addr, buffer_addr, size)
return buffer_addr[:]
peb_addr = get_current_process_syswow_peb_addr()
return windows.winobject.process.RemotePEB64(peb_addr, CurrentProcessReadSyswow())
class CurrentProcessReadSyswow(process.Process):
bitness = 64
def _get_handle(self):
return winproxy.OpenProcess(dwProcessId=windows.current_process.pid)
def read_memory(self, addr, size):
buffer_addr = ctypes.create_string_buffer(size)
winproxy.NtWow64ReadVirtualMemory64(self.handle, addr, buffer_addr, size)
return buffer_addr[:]
class ReadSyswow64Process(process.Process):
def __init__(self, target):
+1 -1
View File
@@ -626,7 +626,7 @@ class VirtualProtected(object):
class DisableWow64FsRedirection(object):
"""
r"""
A context manager that disable the SysWow64 Filesystem Redirection ::
if is_process_32_bits:
+2 -2
View File
@@ -166,13 +166,13 @@ class KernelObject(object):
raise KeyError("Could not find WinObject <{0}> under <{1}>".format(name, self.fullname))
def __getitem__(self, name):
"""Query object ``name`` from the directory, split and subquery on ``\\``::
r"""Query object ``name`` from the directory, split and subquery on ``\``::
>>> obj
<KernelObject "\Windows" (type="Directory")>
>>> obj["WindowStations"]["WinSta0"]
<KernelObject "\Windows\WindowStations" (type="Directory")>
>>> obj["WindowStations\\WinSta0"]
>>> obj[r"WindowStations\\WinSta0"]
<KernelObject "\Windows\WindowStations" (type="Directory")>
:rtype: :class:`KernelObject`
+93 -77
View File
@@ -64,7 +64,7 @@ class DeadThread(utils.AutoHandle):
class Process(utils.AutoHandle):
@utils.fixedpropety
@utils.fixedproperty
def is_wow_64(self):
"""``True`` if the process is a SysWow64 process (32bit process on 64bits system).
@@ -73,7 +73,7 @@ class Process(utils.AutoHandle):
# return utils.is_wow_64(self.handle)
return utils.is_wow_64(self.limited_handle)
@utils.fixedpropety
@utils.fixedproperty
def bitness(self):
"""The bitness of the process
@@ -85,15 +85,25 @@ class Process(utils.AutoHandle):
return 32
return 64
@utils.fixedpropety
@utils.fixedproperty
def limited_handle(self):
if windows.system.version[0] <= 5:
# Windows XP | Serveur 2003
return winproxy.OpenProcess(PROCESS_QUERY_INFORMATION, dwProcessId=self.pid)
return winproxy.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, dwProcessId=self.pid)
@utils.fixedproperty
def name(self):
"""Name of the process
@utils.fixedpropety
:type: :class:`str`
"""
buffer = ctypes.create_unicode_buffer(0x1024)
rsize = winproxy.GetProcessImageFileNameW(self.limited_handle, buffer)
# GetProcessImageFileNameW returns the fullpath
return buffer[:rsize].split("\\")[-1]
@utils.fixedproperty
def ppid(self):
"""Parent Process ID
@@ -559,7 +569,14 @@ class Thread(utils.AutoHandle):
class CurrentThread(Thread):
"""The current thread"""
@property #It's not a fixedpropety because executing thread might change
get_teb_code_by_bitness = {
32: x86.assemble("mov eax, fs:[0x18]; ret"),
64: x64.assemble("mov rax, gs:[0x30]; ret")
}
@property #It's not a fixedproperty because executing thread might change
def tid(self):
"""Thread ID
@@ -567,6 +584,15 @@ class CurrentThread(Thread):
"""
return winproxy.GetCurrentThreadId()
@property #It's not a fixedproperty because executing thread might change
def teb_base(self):
get_teb_base_code = self.get_teb_code_by_bitness[self.owner.bitness]
return self.owner.execute(get_teb_base_code)
@property
def teb(self):
return TEB.from_address(self.teb_base)
@property
def owner(self):
"""The current process
@@ -585,8 +611,6 @@ class CurrentThread(Thread):
"""Exit the thread"""
return winproxy.ExitThread(code)
def wait(self, timeout=INFINITE):
"""Raise :class:`ValueError` to prevent deadlock :D"""
raise ValueError("wait() on current thread")
@@ -594,37 +618,12 @@ class CurrentThread(Thread):
class CurrentProcess(Process):
"""The current process"""
get_peb = None
get_peb_32_code = x86.MultipleInstr()
get_peb_32_code += x86.Mov('EAX', x86.mem('fs:[0x30]'))
get_peb_32_code += x86.Ret()
get_peb_32_code = get_peb_32_code.get_code()
get_peb_64_code = x64.MultipleInstr()
get_peb_64_code += x64.Mov('RAX', x64.mem('gs:[0x60]'))
get_peb_64_code += x64.Ret()
get_peb_64_code = get_peb_64_code.get_code()
allocator = native_exec.native_function.allocator
name = "CurrentProcess" # Used by Winthread for __repr__
# Use RtlGetCurrentPeb ?
def get_peb_builtin(self):
if self.get_peb is not None:
return self.get_peb
if self.bitness == 32:
get_peb = native_exec.create_function(self.get_peb_32_code, [PVOID])
else:
get_peb = native_exec.create_function(self.get_peb_64_code, [PVOID])
self.get_peb = get_peb
return get_peb
def _get_handle(self):
return winproxy.GetCurrentProcess()
@utils.fixedpropety
@utils.fixedproperty
def limited_handle(self):
return winproxy.GetCurrentProcess()
@@ -640,23 +639,21 @@ class CurrentProcess(Process):
"""
return os.getpid()
@utils.fixedpropety # leave it has fixed property as we don't care if CurrentProcess is never collected
@utils.fixedproperty # leave it has fixed property as we don't care if CurrentProcess is never collected
def peb(self):
"""The Process Environment Block of the current process
:type: :class:`PEB`
"""
return PEB.from_address(self.get_peb_builtin()())
return PEB.from_address(windows.winproxy.RtlGetCurrentPeb())
@utils.fixedpropety
@utils.fixedproperty
def bitness(self):
"""The bitness of the process
:type: :class:`int` -- 32 or 64
"""
import platform
bits = platform.architecture()[0]
return int(bits[:2])
return ctypes.sizeof(gdef.PVOID) * 8 # byte to bits
def virtual_alloc(self, size, prot=PAGE_EXECUTE_READWRITE):
"""Allocate memory in the process
@@ -718,7 +715,7 @@ class CurrentProcess(Process):
"""Raise :class:`ValueError` to prevent deadlock :D"""
raise ValueError("wait() on current thread")
@utils.fixedpropety
@utils.fixedproperty
def peb_syswow(self):
"""The 64bits PEB of a SysWow64 process
@@ -761,21 +758,21 @@ class WinThread(Thread):
# Create a DeadThread if thread is already dead ?
return WinThread(handle=handle)
@utils.fixedpropety
@utils.fixedproperty
def tid(self):
"""Thread ID
:type: :class:`int`"""
return self._get_thread_id(self.handle)
@utils.fixedpropety
@utils.fixedproperty
def owner_pid(self):
res = THREAD_BASIC_INFORMATION()
windows.winproxy.NtQueryInformationThread(self.handle, ThreadBasicInformation, byref(res), ctypes.sizeof(res))
owner_id = res.ClientId.UniqueProcess
return owner_id
@utils.fixedpropety
@utils.fixedproperty
def owner(self):
"""The Process owning the thread
@@ -900,7 +897,11 @@ class WinThread(Thread):
# TebBase->NtTib.ExceptionList = (PVOID)Teb32Base;
return self.owner.read_dword(main_teb_addr)
@property
def teb(self):
if self.owner.bitness == 32:
return RemoteTEB32(self.teb_base, target=self.owner)
return RemoteTEB64(self.teb_base, target=self.owner)
@property
def teb_syswow_base(self):
@@ -913,6 +914,12 @@ class WinThread(Thread):
# just return the main TEB
return self._get_principal_teb_addr()
@property
def teb_syswow(self):
if windows.current_process.bitness == 64:
return RemoteTEB64(self.teb_syswow_base, self.owner)
else: #current is 32bits
return RemoteTEB64(self.teb_syswow_base, windows.syswow64.ReadSyswow64Process(self.owner))
def exit(self, code=0):
"""Exit the thread"""
@@ -1006,18 +1013,7 @@ class WinProcess(Process):
return cls(pid=pid, name=name, ppid=ppid)
@utils.fixedpropety
def name(self):
"""Name of the process
:type: :class:`str`
"""
buffer = ctypes.create_unicode_buffer(0x1024)
rsize = winproxy.GetProcessImageFileNameW(self.limited_handle, buffer)
# GetProcessImageFileNameW returns the fullpath
return buffer[:rsize].split("\\")[-1]
@utils.fixedpropety
@utils.fixedproperty
def pid(self):
"""Process ID
@@ -1150,9 +1146,7 @@ class WinProcess(Process):
return injection.execute_python_code(self, pycode)
@utils.fixedpropety
@utils.fixedproperty
def peb_addr(self):
"""The address of the PEB
@@ -1179,7 +1173,7 @@ class WinProcess(Process):
raise ValueError("Could not get peb addr of process {0}".format(self.name))
return peb_addr
# Not a fixedpropety to prevent ref-cycle and uncollectable WinProcess
# Not a fixedproperty to prevent ref-cycle and uncollectable WinProcess
# Try with a weakref ?
@property
def peb(self):
@@ -1193,7 +1187,7 @@ class WinProcess(Process):
return RemotePEB32(self.peb_addr, self)
return RemotePEB(self.peb_addr, self)
@utils.fixedpropety
@utils.fixedproperty
def peb_syswow_addr(self):
if not self.is_wow_64:
raise ValueError("Not a syswow process")
@@ -1212,7 +1206,7 @@ class WinProcess(Process):
peb_addr = struct.unpack("<Q", data[x.PebBaseAddress.offset: x.PebBaseAddress.offset+8])[0]
return peb_addr
# Not a fixedpropety to prevent ref-cycle and uncollectable WinProcess
# Not a fixedproperty to prevent ref-cycle and uncollectable WinProcess
# Try with a weakref ?
@property
def peb_syswow(self):
@@ -1232,8 +1226,6 @@ class WinProcess(Process):
return winproxy.TerminateProcess(self.handle, code)
def transform_ctypes_fields(struct, replacement):
return [(name, replacement.get(name, type)) for name, type in struct._fields_]
@@ -1276,11 +1268,6 @@ class LoadedModule(LDR_DATA_TABLE_ENTRY):
return pe_parse.GetPEFile(self.baseaddr)
class LIST_ENTRY_PTR(PVOID):
def TO_LDR_ENTRY(self):
return LDR_DATA_TABLE_ENTRY.from_address(self.value - sizeof(PVOID) * 2)
class PEB(gdef.PEB):
"""The PEB (Process Environment Block) of the current process"""
@@ -1315,13 +1302,13 @@ class PEB(gdef.PEB):
:type: [:class:`LoadedModule`] -- List of loaded modules
"""
res = []
list_entry_ptr = ctypes.cast(self.Ldr.contents.InMemoryOrderModuleList.Flink, LIST_ENTRY_PTR)
current_dll = list_entry_ptr.TO_LDR_ENTRY()
first_flink = self.Ldr.contents.InMemoryOrderModuleList.Flink[0]
current_dll = first_flink.get_real_struct(LoadedModule, LoadedModule.InMemoryOrderLinks)
while current_dll.DllBase:
res.append(current_dll)
list_entry_ptr = ctypes.cast(current_dll.InMemoryOrderLinks.Flink, LIST_ENTRY_PTR)
current_dll = list_entry_ptr.TO_LDR_ENTRY()
return [LoadedModule.from_address(addressof(LDR)) for LDR in res]
next_flink = current_dll.InMemoryOrderLinks.Flink[0]
current_dll = next_flink.get_real_struct(LoadedModule, LoadedModule.InMemoryOrderLinks)
return res
@staticmethod
def _extract_environment(env_block_addr, target):
@@ -1351,7 +1338,6 @@ class PEB(gdef.PEB):
raise NotImplementedError("ApiSetMap does not exist prior to Windows 7")
return apisetmap.get_api_set_map_for_current_process(self.ApiSetMap)
# Memory stuff
class EPSAPI_WORKING_SET_BLOCK_BASE(object):
@@ -1463,9 +1449,24 @@ class RemotePEB(rctypes.RemoteStructure.from_structure(PEB)):
raise NotImplementedError("ApiSetMap for remote process not implemented yet")
# TEB enhanced, same bitness as PEB (current process)
class TEB(gdef.TEB):
@property
def peb(self):
return ctypes.cast(self.ProcessEnvironmentBlock, ctypes.POINTER(PEB))[0]
# mote TEB enhanced, same bitness as PEB (current process)
class RemoteTEB(rctypes.RemoteStructure.from_structure(TEB)):
@property
def peb(self):
ctypes_peb = self.ProcessEnvironmentBlock.value
return RemotePEB(ctypes_peb, self._target)
if CurrentProcess().bitness == 32:
RemoteLoadedModule32 = RemoteLoadedModule
RemotePEB32 = RemotePEB
RemoteTEB32 = RemoteTEB
class RemoteLoadedModule64(rctypes.transform_type_to_remote64bits(LoadedModule)):
@property
def pe(self):
@@ -1480,7 +1481,6 @@ if CurrentProcess().bitness == 32:
def ptr_flink_to_remote_module(self, ptr_value):
return RemoteLoadedModule64(ptr_value - ctypes.sizeof(rctypes.c_void_p64) * 2, self._target)
@property
def exe(self):
"""The executable of the process, as pointed by PEB.ImageBaseAddress
@@ -1513,7 +1513,17 @@ if CurrentProcess().bitness == 32:
apisetmap = RemotePEB.apisetmap
class RemoteTEB64(rctypes.transform_type_to_remote64bits(TEB)):
@property
def peb(self):
ctypes_peb = self.ProcessEnvironmentBlock.value
return RemotePEB64(ctypes_peb, self._target)
if CurrentProcess().bitness == 64:
RemoteLoadedModule64 = RemoteLoadedModule
RemotePEB64 = RemotePEB
RemoteTEB64 = RemoteTEB
class RemoteLoadedModule32(rctypes.transform_type_to_remote32bits(LoadedModule)):
@property
@@ -1559,4 +1569,10 @@ if CurrentProcess().bitness == 64:
# TODO: Tests
return self._extract_environment(self.ProcessParameters.contents.Environment, self._target)
apisetmap = RemotePEB.apisetmap
apisetmap = RemotePEB.apisetmap
class RemoteTEB32(rctypes.transform_type_to_remote32bits(TEB)):
@property
def peb(self):
ctypes_peb = self.ProcessEnvironmentBlock.value
return RemotePEB32(ctypes_peb, self._target)
+2 -2
View File
@@ -87,7 +87,7 @@ class System(object):
@property
def logicaldrives(self):
"""List of logical drives [C:\, ...]
"""List of logical drives [C:\\, ...]
:type: [:class:`~windows.winobject.volume.LogicalDrive`] -- A list of LogicalDrive
"""
@@ -621,7 +621,7 @@ class System(object):
@staticmethod
def enumerate_threads():
return [WinThread._from_THREADENTRY32(th) for th in System.enumerate_threads_generator()]
return [process.WinThread._from_THREADENTRY32(th) for th in System.enumerate_threads_generator()]
def enumerate_threads_setup_owners(self):
+2 -2
View File
@@ -474,11 +474,11 @@ class WmiNamespace(gdef.IWbemServices, WmiComInterface):
return """<{0} "{1}"{2}>""".format(type(self).__name__, self.name, null)
class WmiManager(dict):
"""The main WMI class exposed, used to list and access differents WMI namespace, can be used as a dict to access
r"""The main WMI class exposed, used to list and access differents WMI namespace, can be used as a dict to access
:class:`WmiNamespace` by name
Example:
>>> windows.system.wmi["root\\SecurityCenter2"]
>>> windows.system.wmi[r"root\SecurityCenter2"]
<WmiNamespace "root\SecurityCenter2">
"""
DEFAULT_NAMESPACE = "root\\cimv2" #: The default namespace for :func:`select` & :func:`query`
+3
View File
@@ -10,6 +10,9 @@ class NtdllProxy(ApiProxy):
# Process
@NtdllProxy(error_check=fail_on_zero)
def RtlGetCurrentPeb():
return RtlGetCurrentPeb.ctypes_function()
@NtdllProxy()
def NtOpenProcess(ProcessHandle, DesiredAccess, ObjectAttributes, ClientId):