├── AUTHORS ├── docs ├── .nojekyll ├── build │ └── html │ │ ├── _static │ │ ├── file.png │ │ ├── plus.png │ │ ├── minus.png │ │ ├── documentation_options.js │ │ └── css │ │ │ └── mbasic.css │ │ ├── _sources │ │ ├── wip.rst.txt │ │ ├── handle.rst.txt │ │ ├── volume.rst.txt │ │ ├── network.rst.txt │ │ ├── service.rst.txt │ │ ├── winobject.rst.txt │ │ ├── object_manager.rst.txt │ │ ├── alpc.rst.txt │ │ ├── pipe.rst.txt │ │ ├── system_module.rst.txt │ │ ├── registry.rst.txt │ │ ├── wintrust.rst.txt │ │ ├── etw.rst.txt │ │ ├── wmi.rst.txt │ │ └── windows.rst.txt │ │ └── .buildinfo ├── source │ ├── wip.rst │ ├── samples_output │ │ ├── debug_change_function_ret_value.txt │ │ ├── debug_debugger_on_setup.txt │ │ ├── debug_local_debugger.txt │ │ ├── alpc_simple_alpc.txt │ │ ├── debug_debug_functionbp.txt │ │ ├── com_com_inetfwpolicy2.txt │ │ ├── com_icallinterceptor.txt │ │ ├── pipe_child_send_object.txt │ │ ├── process_iat_hook.txt │ │ ├── debug_debugger_membp_singlestep.txt │ │ ├── wmi_create_process.txt │ │ ├── debug_symbol_debugger.txt │ │ ├── process_veh_segv.txt │ │ ├── debug_attach.txt │ │ ├── debug_debugger_print_LdrLoaddll.txt │ │ ├── crypto_wintrust.txt │ │ ├── service_service_demo.txt │ │ ├── debug_symbol_processsymdemo.txt │ │ ├── process_current_process.txt │ │ ├── process_apisetmap.txt │ │ ├── token_token_demo.txt │ │ ├── security_query_sacl.txt │ │ ├── registry_registry.txt │ │ ├── process_msstore_interpreter_remote_python.txt │ │ ├── security_security_descriptor.txt │ │ ├── object_manager_object_manager.txt │ │ ├── wmi_wmi_request.txt │ │ ├── device_manager_device_manager.txt │ │ ├── object_manager_findobj.txt │ │ ├── rpc_lsass.txt │ │ ├── network_network.txt │ │ ├── process_peb.txt │ │ ├── scheduled_task_scheduled_task.txt │ │ ├── debug_symbol_virtsymdemo.txt │ │ └── etw_etw_enumeration.txt │ ├── handle.rst │ ├── volume.rst │ ├── network.rst │ ├── service.rst │ ├── winobject.rst │ ├── object_manager.rst │ ├── _static │ │ └── css │ │ │ └── mbasic.css │ ├── alpc.rst │ ├── pipe.rst │ ├── system_module.rst │ ├── registry.rst │ ├── wintrust.rst │ ├── etw.rst │ ├── wmi.rst │ └── windows.rst ├── index.html └── generate_winproxy_list.py ├── tests ├── __init__.py ├── pytest.ini ├── test_cpuid.py ├── test_midl.py ├── test_system_modules.py ├── test_device_manager.py ├── test_network.py ├── test_bits.py ├── test_service.py ├── test_wintrust.py ├── test_generated_code.py ├── test_improved_buffer.py └── test_winproxy.py ├── windows ├── winobject │ └── __init__.py ├── native_exec │ └── __init__.py ├── utils │ └── __init__.py ├── crypto │ ├── catalog.py │ ├── __init__.py │ └── binary_string_conversion.py ├── rpc │ └── __init__.py ├── winproxy │ ├── __init__.py │ └── apis │ │ ├── oleacc.py │ │ ├── cryptui.py │ │ ├── tdh.py │ │ ├── __init__.py │ │ ├── ncrypt.py │ │ ├── virtdisk.py │ │ ├── shlwapi.py │ │ ├── ktmw32.py │ │ ├── shell32.py │ │ ├── dnsapi.py │ │ └── oleaut32.py ├── debug │ └── __init__.py ├── generated_def │ └── auto_doc_tst.py ├── __init__.py └── test.py ├── ctypes_generation ├── definitions │ ├── functions │ │ ├── dbghelp.txt │ │ ├── winfunc_notdoc.txt │ │ ├── heap.txt │ │ ├── netip.txt │ │ ├── trace_data_helper.txt │ │ ├── accessibility.txt │ │ ├── shlwapi.txt │ │ ├── memoryapi.txt │ │ ├── ncrypt.txt │ │ ├── time.txt │ │ ├── disk.txt │ │ ├── atoms.txt │ │ ├── shell32.txt │ │ ├── environ.txt │ │ ├── dpapi.txt │ │ ├── winfunc_crypto.txt.ignore │ │ └── synchapi.txt │ ├── defines │ │ ├── section.txt │ │ ├── disk.txt │ │ ├── midl.txt │ │ ├── version.txt │ │ ├── bits.txt │ │ ├── custom_rpc_windef.txt │ │ ├── windef_evtlog.txt │ │ ├── kuser_shared_data.txt │ │ ├── error_helper.txt │ │ ├── combase.txt │ │ └── pipe.txt │ ├── winerror_template.py │ ├── structures │ │ ├── dpapi.txt │ │ ├── guid.txt │ │ ├── time.txt │ │ ├── processor.txt │ │ ├── netip.txt │ │ ├── trace_data_helper.txt │ │ ├── io.txt │ │ ├── setupapi.txt │ │ ├── simple_structs.txt │ │ ├── bits.txt │ │ ├── internet.txt │ │ ├── shell.txt │ │ ├── section.txt │ │ ├── proc_thread_attributes.txt │ │ ├── ntregistry.txt │ │ └── MIDL.txt │ ├── com │ │ ├── IUnknown.txt │ │ ├── IStdIdentity.txt │ │ ├── IInternalUnknown.txt │ │ ├── ICallFrameEvents.txt │ │ ├── ICallFrameWalker.txt │ │ ├── IPersist.txt │ │ ├── rpc │ │ │ ├── IRpcHelper.txt │ │ │ ├── IRpcOptions.txt │ │ │ ├── IRpcChannelBuffer.txt │ │ │ └── IRpcStubBuffer.txt │ │ ├── IClassFactory.txt │ │ ├── manually_created │ │ │ └── IProxyServerIdentity.txt │ │ ├── ICallFactory.txt │ │ ├── WMI │ │ │ ├── IWbemLocatorVtbl.txt │ │ │ ├── IWbemObjectTextSrc.txt │ │ │ ├── IWbemObjectSink.txt │ │ │ └── IWbemCallResultVtbl.txt │ │ ├── combase │ │ │ ├── IActivationStageInfo.txt │ │ │ ├── IScmRequestInfo.txt │ │ │ ├── ISystemActivator.txt │ │ │ ├── IEnumSTATSTG.txt │ │ │ ├── IContext.txt │ │ │ ├── IOpaqueData.txt │ │ │ ├── IEnumContextProps.txt │ │ │ ├── IScmReplyInfo.txt │ │ │ └── IActivationPropertiesOut.txt │ │ ├── propertysystem │ │ │ └── IPackageExecutionStateChangeNotification.txt │ │ ├── BITS │ │ │ ├── IBackgroundCopyFile.txt │ │ │ └── IBackgroundCopyCallback.txt │ │ ├── ITypeComp.txt │ │ ├── IRemUnknown.txt │ │ ├── IEnumVARIANT.txt │ │ └── Explorer │ │ │ ├── IEnumString.txt │ │ │ └── IEnumMoniker.txt │ └── ntstatus_template.py ├── extended_structs │ ├── _EVENT_RECORD.py │ ├── _CRYPT_BIT_BLOB.py │ ├── _FILETIME.py │ ├── _RPC_IF_ID.py │ ├── _EVENT_DESCRIPTOR.py │ ├── tagMInterfacePointer.py │ ├── _tagADDRESS64.py │ ├── _EVENT_HEADER_EXTENDED_DATA_ITEM.py │ ├── _CRYPTOAPI_BLOB.py │ ├── _LOAD_DLL_DEBUG_INFO.py │ ├── _LUID.py │ ├── _CRYPT_ATTRIBUTES.py │ ├── _SID_AND_ATTRIBUTES.py │ ├── _FILE_RENAME_INFORMATION.py │ ├── _OBJECT_ATTRIBUTES.py │ ├── _CRYPT_ATTRIBUTE.py │ ├── _LIST_ENTRY.py │ └── _LSA_UNICODE_STRING.py ├── README ├── extended_interfaces │ └── IStream.py └── dummy_wintypes.py ├── .gitignore ├── samples ├── security │ ├── explain_security_desciptor.py │ ├── security_descriptor.py │ └── query_sacl.py ├── object_manager │ ├── winobj.py │ └── findobj.py ├── pipe │ ├── pipe_custom_acl.py │ └── child_send_object.py ├── process │ ├── dump_apisetmap.py │ └── apisetmap.py ├── debug │ ├── debugger_on_setup.py │ ├── attach.py │ ├── symbols │ │ └── symsearch.py │ ├── symbol_debugger.py │ ├── local_debugger_remote_process.py │ └── debugger_print_LdrLoaddll.py ├── registry │ └── registry.py ├── network │ ├── demo_ws2_32.py │ └── network.py ├── com │ └── com_inetfwpolicy2.py ├── service │ └── service_demo.py ├── wmi │ └── create_process.py ├── crypto │ └── wintrust.py ├── token │ └── token_demo.py └── etw │ ├── etw_enumeration.py │ └── uac_trace.py ├── setup.py └── LICENSE /AUTHORS: -------------------------------------------------------------------------------- 1 | * Hakril -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/pytest.ini: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /windows/winobject/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/dbghelp.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/winfunc_notdoc.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/section.txt: -------------------------------------------------------------------------------- 1 | #define MEM_EXTENDED_PARAMETER_TYPE_BITS 8 -------------------------------------------------------------------------------- /ctypes_generation/definitions/winerror_template.py: -------------------------------------------------------------------------------- 1 | from .flag import make_flag, FlagMapper 2 | 3 | -------------------------------------------------------------------------------- /docs/build/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hakril/PythonForWindows/HEAD/docs/build/html/_static/file.png -------------------------------------------------------------------------------- /docs/build/html/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hakril/PythonForWindows/HEAD/docs/build/html/_static/plus.png -------------------------------------------------------------------------------- /windows/native_exec/__init__.py: -------------------------------------------------------------------------------- 1 | from .native_function import create_function 2 | 3 | __all__ = ["create_function"] 4 | -------------------------------------------------------------------------------- /windows/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .pythonutils import * 2 | from .winutils import * 3 | from .improved_buffer import * 4 | -------------------------------------------------------------------------------- /docs/build/html/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hakril/PythonForWindows/HEAD/docs/build/html/_static/minus.png -------------------------------------------------------------------------------- /windows/crypto/catalog.py: -------------------------------------------------------------------------------- 1 | from windows import winproxy 2 | import windows.generated_def as gdef 3 | import windows.crypto 4 | 5 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/heap.txt: -------------------------------------------------------------------------------- 1 | LPVOID HeapAlloc( 2 | HANDLE hHeap, 3 | DWORD dwFlags, 4 | SIZE_T dwBytes 5 | ); 6 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_EVENT_RECORD.py: -------------------------------------------------------------------------------- 1 | _OLD_EVENT_RECORD = _EVENT_RECORD 2 | class _EVENT_RECORD(_OLD_EVENT_RECORD): 3 | pass -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/netip.txt: -------------------------------------------------------------------------------- 1 | ULONG GetIpNetTable( 2 | PMIB_IPNETTABLE IpNetTable, 3 | PULONG SizePointer, 4 | BOOL Order 5 | ); -------------------------------------------------------------------------------- /windows/rpc/__init__.py: -------------------------------------------------------------------------------- 1 | from . import ndr 2 | from .client import RPCClient 3 | from .epmapper import find_alpc_endpoint_and_connect, find_alpc_endpoints, construct_alpc_tower -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/trace_data_helper.txt: -------------------------------------------------------------------------------- 1 | TDHSTATUS TdhEnumerateProviders( 2 | PPROVIDER_ENUMERATION_INFO pBuffer, 3 | ULONG *pBufferSize 4 | ); -------------------------------------------------------------------------------- /windows/winproxy/__init__.py: -------------------------------------------------------------------------------- 1 | from .apiproxy import is_implemented, get_target, resolve 2 | from .error import WinproxyError, ExportNotFound 3 | from .apis import * # Import all functions -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_CRYPT_BIT_BLOB.py: -------------------------------------------------------------------------------- 1 | class _CRYPT_BIT_BLOB(_CRYPT_BIT_BLOB): 2 | @property 3 | def data(self): 4 | return bytearray(self.pbData[:self.cbData]) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | doctrees 3 | *.inv 4 | *.pickle 5 | *.ignore 6 | *.code-workspace 7 | 8 | .vscode/ 9 | .cache/ 10 | dist/ 11 | build/ 12 | docs/BuildDocEnv/ 13 | playground/ 14 | *egg-info/ -------------------------------------------------------------------------------- /docs/source/wip.rst: -------------------------------------------------------------------------------- 1 | Early Work In Progress 2 | ====================== 3 | 4 | Here are some features that are still work in progress. Code might be unstable and/or ultra-ugly. 5 | 6 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_FILETIME.py: -------------------------------------------------------------------------------- 1 | INITIAL_FILETIME = FILETIME 2 | 3 | class _FILETIME(INITIAL_FILETIME): 4 | def __int__(self): 5 | return (self.dwHighDateTime << 32) + self.dwLowDateTime -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Redirection to build/html 4 | 5 | 6 | 7 | Nothing here. 8 | 9 | -------------------------------------------------------------------------------- /windows/debug/__init__.py: -------------------------------------------------------------------------------- 1 | from .debugger import Debugger, HXBreakpoint 2 | from .symboldbg import SymbolDebugger 3 | from .localdbg import LocalDebugger 4 | from .breakpoints import * 5 | from .breakpoints import * -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/accessibility.txt: -------------------------------------------------------------------------------- 1 | HRESULT WINAPI ObjectFromLresult( 2 | _In_ LRESULT lResult, 3 | _In_ REFIID riid, 4 | _In_ WPARAM wParam, 5 | _Out_ PVOID *ppvObject 6 | ); 7 | -------------------------------------------------------------------------------- /docs/build/html/_sources/wip.rst.txt: -------------------------------------------------------------------------------- 1 | Early Work In Progress 2 | ====================== 3 | 4 | Here are some features that are still work in progress. Code might be unstable and/or ultra-ugly. 5 | 6 | -------------------------------------------------------------------------------- /docs/source/samples_output/debug_change_function_ret_value.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\change_function_ret_value.py 2 | [DEBUGGE] IsDebuggerPresent=42 3 | [DEBUGGE] IsDebuggerPresent=43 4 | [DEBUGGE] IsDebuggerPresent=44 5 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/dpapi.txt: -------------------------------------------------------------------------------- 1 | typedef struct _CRYPTPROTECT_PROMPTSTRUCT { 2 | DWORD cbSize; 3 | DWORD dwPromptFlags; 4 | HWND hwndApp; 5 | LPCWSTR szPrompt; 6 | } CRYPTPROTECT_PROMPTSTRUCT, *PCRYPTPROTECT_PROMPTSTRUCT; -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/disk.txt: -------------------------------------------------------------------------------- 1 | #define VIRTUAL_STORAGE_TYPE_DEVICE_UNKNOWN 0 2 | #define VIRTUAL_STORAGE_TYPE_DEVICE_ISO 1 3 | #define VIRTUAL_STORAGE_TYPE_DEVICE_VHD 2 4 | #define VIRTUAL_STORAGE_TYPE_DEVICE_VHDX 3 -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_RPC_IF_ID.py: -------------------------------------------------------------------------------- 1 | INITIAL_RPC_IF_ID = RPC_IF_ID 2 | 3 | class _RPC_IF_ID(INITIAL_RPC_IF_ID): 4 | def __repr__(self): 5 | return ''.format(self.Uuid.to_string(), self.VersMajor, self.VersMinor) -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/midl.txt: -------------------------------------------------------------------------------- 1 | #define FC_ALLOCATE_ALL_NODES 0x01 2 | #define FC_DONT_FREE 0x02 3 | #define FC_ALLOCED_ON_STACK 0x04 4 | #define FC_SIMPLE_POINTER 0x08 5 | #define FC_POINTER_DEREF 0x10 -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_EVENT_DESCRIPTOR.py: -------------------------------------------------------------------------------- 1 | class _EVENT_DESCRIPTOR(_EVENT_DESCRIPTOR): 2 | def __repr__(self): 3 | return "<{0} Id={self.Id} Opcode={self.Opcode} Version={self.Version} Level={self.Level}>".format(type(self).__name__, self=self) -------------------------------------------------------------------------------- /docs/build/html/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 0e250b469303f551736a785b66f0d36c 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/version.txt: -------------------------------------------------------------------------------- 1 | /* 2 | FILE_VER_GET_... flags are for use by 3 | GetFileVersionInfoSizeEx 4 | GetFileVersionInfoExW 5 | */ 6 | #define FILE_VER_GET_LOCALISED 0x01 7 | #define FILE_VER_GET_NEUTRAL 0x02 8 | #define FILE_VER_GET_PREFETCHED 0x04 -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/tagMInterfacePointer.py: -------------------------------------------------------------------------------- 1 | INITIAL_tagMInterfacePointer = tagMInterfacePointer 2 | 3 | class tagMInterfacePointer(INITIAL_tagMInterfacePointer): 4 | @property 5 | def objref(self): 6 | return OBJREF.from_address(ctypes.addressof(self.abData)) -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/shlwapi.txt: -------------------------------------------------------------------------------- 1 | PWSTR WINAPI StrStrIW( 2 | _In_ PWSTR pszFirst, 3 | _In_ PWSTR pszSrch 4 | ); 5 | 6 | PCSTR WINAPI StrStrIA( 7 | _In_ PCSTR pszFirst, 8 | _In_ PCSTR pszSrch 9 | ); 10 | 11 | 12 | BOOL IsOS( 13 | DWORD dwOS 14 | ); 15 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/bits.txt: -------------------------------------------------------------------------------- 1 | #define BG_JOB_ENUM_ALL_USERS 0x0001 2 | 3 | #define BG_NOTIFY_JOB_TRANSFERRED 0x0001 4 | #define BG_NOTIFY_JOB_ERROR 0x0002 5 | #define BG_NOTIFY_DISABLE 0x0004 6 | #define BG_NOTIFY_JOB_MODIFICATION 0x0008 7 | #define BG_NOTIFY_FILE_TRANSFERRED 0x0010 -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/guid.txt: -------------------------------------------------------------------------------- 1 | /* I 'often' add typedef for GUID: so I put it in a specific file */ 2 | 3 | typedef struct _GUID { 4 | ULONG Data1; 5 | USHORT Data2; 6 | USHORT Data3; 7 | BYTE Data4[ 8 ]; 8 | } GUID, IID, CLSID, *REFIID, *REFCLSID, *LPGUID, *REFGUID, *LPCLSID, *LPCGUID, IPID, CID, *REFIPID; -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_tagADDRESS64.py: -------------------------------------------------------------------------------- 1 | class _tagADDRESS64(_tagADDRESS64): 2 | def __repr__(self): 3 | if not self.Segment: 4 | return "<{0} {offset:#x}>".format(type(self).__name__, offset=self.Offset) 5 | return "<{0} {seg:#x}:{offset:#x}>".format(type(self).__name__, seg=self.Segment, offset=self.Offset) -------------------------------------------------------------------------------- /docs/source/handle.rst: -------------------------------------------------------------------------------- 1 | Handle -- Processes handles 2 | ============================ 3 | 4 | The list of handles is accessible via :py:attr:`windows.system.handles 5 | ` 6 | 7 | .. note:: 8 | 9 | See sample :ref:`sample_system` 10 | 11 | .. module:: windows.winobject.handle 12 | 13 | .. autoclass:: Handle -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/custom_rpc_windef.txt: -------------------------------------------------------------------------------- 1 | #define RPC_REQUEST_TYPE_CALL 0 2 | #define RPC_REQUEST_TYPE_BIND 1 3 | 4 | #define RPC_RESPONSE_TYPE_BIND_OK 1 5 | #define RPC_RESPONSE_TYPE_FAIL 2 6 | #define RPC_RESPONSE_TYPE_SUCCESS 3 7 | 8 | #define BIND_IF_SYNTAX_NDR32 1 9 | #define BIND_IF_SYNTAX_NDR64 2 10 | #define BIND_IF_SYNTAX_UNKNOWN 4 -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_EVENT_HEADER_EXTENDED_DATA_ITEM.py: -------------------------------------------------------------------------------- 1 | _OLD_EVENT_HEADER_EXTENDED_DATA_ITEM = _EVENT_HEADER_EXTENDED_DATA_ITEM 2 | class _EVENT_HEADER_EXTENDED_DATA_ITEM(_OLD_EVENT_HEADER_EXTENDED_DATA_ITEM): 3 | @property 4 | def data(self): 5 | bdata = (ctypes.c_char * self.DataSize).from_address(self.DataPtr) 6 | return bdata[:] -------------------------------------------------------------------------------- /docs/build/html/_sources/handle.rst.txt: -------------------------------------------------------------------------------- 1 | Handle -- Processes handles 2 | ============================ 3 | 4 | The list of handles is accessible via :py:attr:`windows.system.handles 5 | ` 6 | 7 | .. note:: 8 | 9 | See sample :ref:`sample_system` 10 | 11 | .. module:: windows.winobject.handle 12 | 13 | .. autoclass:: Handle -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/time.txt: -------------------------------------------------------------------------------- 1 | typedef struct _TIME_ZONE_INFORMATION { 2 | LONG Bias; 3 | WCHAR StandardName[32]; 4 | SYSTEMTIME StandardDate; 5 | LONG StandardBias; 6 | WCHAR DaylightName[32]; 7 | SYSTEMTIME DaylightDate; 8 | LONG DaylightBias; 9 | } TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION, *LPTIME_ZONE_INFORMATION; -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/memoryapi.txt: -------------------------------------------------------------------------------- 1 | 2 | HANDLE OpenFileMappingW( 3 | DWORD dwDesiredAccess, 4 | BOOL bInheritHandle, 5 | LPCWSTR lpName 6 | ); 7 | 8 | HANDLE OpenFileMappingA( 9 | DWORD dwDesiredAccess, 10 | BOOL bInheritHandle, 11 | LPCSTR lpName 12 | ); 13 | 14 | BOOL UnmapViewOfFile( 15 | LPCVOID lpBaseAddress 16 | ); 17 | 18 | 19 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_CRYPTOAPI_BLOB.py: -------------------------------------------------------------------------------- 1 | class _CRYPTOAPI_BLOB(_CRYPTOAPI_BLOB): 2 | @classmethod 3 | def from_string(cls, buf): 4 | self = cls() 5 | self.cbData = len(buf) 6 | self.pbData = (BYTE * self.cbData)(*bytearray(buf)) 7 | return self 8 | 9 | @property 10 | def data(self): 11 | return bytearray(self.pbData[:self.cbData]) -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/processor.txt: -------------------------------------------------------------------------------- 1 | typedef enum _MACHINE_ATTRIBUTES { 2 | UserEnabled = 0x00000001, 3 | KernelEnabled = 0x00000002, 4 | Wow64Container = 0x00000004 5 | } MACHINE_ATTRIBUTES; 6 | 7 | typedef struct _PROCESS_MACHINE_INFORMATION { 8 | USHORT ProcessMachine; 9 | USHORT Res0; 10 | MACHINE_ATTRIBUTES MachineAttributes; 11 | } PROCESS_MACHINE_INFORMATION; -------------------------------------------------------------------------------- /docs/build/html/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | const DOCUMENTATION_OPTIONS = { 2 | VERSION: '1.0.4', 3 | LANGUAGE: 'en', 4 | COLLAPSE_INDEX: false, 5 | BUILDER: 'html', 6 | FILE_SUFFIX: '.html', 7 | LINK_SUFFIX: '.html', 8 | HAS_SOURCE: true, 9 | SOURCELINK_SUFFIX: '.txt', 10 | NAVIGATION_WITH_KEYS: false, 11 | SHOW_SEARCH_SUMMARY: true, 12 | ENABLE_SEARCH_SHORTCUTS: true, 13 | }; -------------------------------------------------------------------------------- /tests/test_cpuid.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import windows 4 | import windows.generated_def as gdef 5 | import windows.native_exec.cpuid 6 | 7 | def test_native_exec_cpuid(): 8 | if windows.current_process.architecture == gdef.IMAGE_FILE_MACHINE_ARM64: 9 | pytest.skip("CPUID not testable on ARM64") 10 | assert windows.native_exec.cpuid.do_cpuid(0) 11 | assert windows.native_exec.cpuid.get_proc_family_model() -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/netip.txt: -------------------------------------------------------------------------------- 1 | typedef struct _MIB_IPNETROW_LH { 2 | IF_INDEX dwIndex; 3 | DWORD dwPhysAddrLen; 4 | UCHAR bPhysAddr[8]; 5 | DWORD dwAddr; 6 | union { 7 | DWORD dwType; 8 | }; 9 | } MIB_IPNETROW, *PMIB_IPNETROW; 10 | 11 | typedef struct _MIB_IPNETTABLE { 12 | DWORD dwNumEntries; 13 | MIB_IPNETROW table[ANY_SIZE]; 14 | } MIB_IPNETTABLE, *PMIB_IPNETTABLE; -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_LOAD_DLL_DEBUG_INFO.py: -------------------------------------------------------------------------------- 1 | # typedef struct _LOAD_DLL_DEBUG_INFO { 2 | # HANDLE hFile; 3 | # LPVOID lpBaseOfDll; 4 | # DWORD dwDebugInfoFileOffset; 5 | # DWORD nDebugInfoSize; 6 | # LPVOID lpImageName; 7 | # WORD fUnicode; 8 | # } LOAD_DLL_DEBUG_INFO, *LPLOAD_DLL_DEBUG_INFO; 9 | 10 | class _LOAD_DLL_DEBUG_INFO(_LOAD_DLL_DEBUG_INFO): 11 | def hello(self): 12 | return "hello" -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_LUID.py: -------------------------------------------------------------------------------- 1 | _INITIAL_LUID = _LUID 2 | class _LUID(_INITIAL_LUID): 3 | def __int__(self): 4 | return (self.HighPart << 32) | self.LowPart 5 | 6 | def __eq__(self, other): 7 | return (self.HighPart, self.LowPart) == (other.HighPart, other.LowPart) 8 | 9 | def __repr__(self): 10 | return "<{0} HighPart={1} LowPart={2}>".format(type(self).__name__, self.HighPart, self.LowPart) -------------------------------------------------------------------------------- /tests/test_midl.py: -------------------------------------------------------------------------------- 1 | import windows.generated_def as gdef 2 | 3 | def test_format_charactere_values(): 4 | assert gdef.FC_ZERO == 0 5 | assert gdef.FC_PAD == 0x5c 6 | assert gdef.FC_PAD == 0x5c 7 | assert gdef.FC_SPLIT_DEREFERENCE == 0x74 8 | assert gdef. FC_SPLIT_DIV_2 == 0x75 9 | assert gdef.FC_HARD_STRUCT == 0xb1 10 | assert gdef.FC_TRANSMIT_AS_PTR == 0xb2 11 | assert gdef.FC_END_OF_UNIVERSE == 0xba -------------------------------------------------------------------------------- /ctypes_generation/README: -------------------------------------------------------------------------------- 1 | == ctypes_generation == 2 | 3 | I don't have the need for (nor want to code) a full C parser but I need to parse some 4 | windows definitions to generate some python functions/structs/flags. 5 | So, there are 3 dumb parsers used to generate: 6 | - function prototype 7 | - ctypes struct definition 8 | - flags (int with name) 9 | 10 | Maybe one day I will do something clean and sane. 11 | But not today. 12 | sorry :( -------------------------------------------------------------------------------- /docs/source/samples_output/debug_debugger_on_setup.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\debugger_on_setup.py 2 | == With on_setup == 3 | Setup called: 4 | 5 | Process exit: 6 | 7 | == Without on_setup == 8 | Exception: EXCEPTION_BREAKPOINT(0x80000003L) 9 | 10 | Process exit: 11 | -------------------------------------------------------------------------------- /docs/source/samples_output/debug_local_debugger.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\local_debugger.py 2 | Code addr = 0x25f8532000e 3 | GOT AN HXBP at 0x25f8532000e 4 | EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x7ff8e377257d 5 | EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x7ff8e5a6aa80 6 | EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x7ff8e5aafde0 7 | EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x7ff8e5aafdf4 8 | Done! 9 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/trace_data_helper.txt: -------------------------------------------------------------------------------- 1 | typedef struct _TRACE_PROVIDER_INFO { 2 | GUID ProviderGuid; 3 | ULONG SchemaSource; 4 | ULONG ProviderNameOffset; 5 | } TRACE_PROVIDER_INFO; 6 | 7 | 8 | typedef struct _PROVIDER_ENUMERATION_INFO { 9 | ULONG NumberOfProviders; 10 | ULONG Reserved; 11 | TRACE_PROVIDER_INFO TraceProviderInfoArray[ANYSIZE_ARRAY]; 12 | } PROVIDER_ENUMERATION_INFO, *PPROVIDER_ENUMERATION_INFO; -------------------------------------------------------------------------------- /docs/source/samples_output/alpc_simple_alpc.txt: -------------------------------------------------------------------------------- 1 | (cmd) python alpc\simple_alpc.py 2 | [SERV] PORT <\RPC Control\PythonForWindowsPORT> CREATED 3 | Client pid = 15840 4 | [SERV] Message type = 0x300a 5 | [SERV] Received data: <> 6 | [SERV] Connection request 7 | [CLIENT] Connected: 8 | 9 | [SERV] Received message: 10 | [SERV] Message type = 0x3001 11 | [CLIENT] Response: 12 | BYE 13 | -------------------------------------------------------------------------------- /windows/winproxy/apis/oleacc.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter, is_implemented 5 | from ..error import succeed_on_zero 6 | 7 | class OleaccProxy(ApiProxy): 8 | APIDLL = "Oleacc" 9 | default_error_check = staticmethod(succeed_on_zero) 10 | 11 | @OleaccProxy() 12 | def ObjectFromLresult(lResult, riid, wParam, ppvObject): 13 | return ObjectFromLresult.ctypes_function(lResult, riid, wParam, ppvObject) 14 | -------------------------------------------------------------------------------- /docs/source/volume.rst: -------------------------------------------------------------------------------- 1 | Volume -- The logical drives 2 | ============================ 3 | 4 | The list of logical drives is accessible via :py:attr:`windows.system.logicaldrives 5 | ` 6 | 7 | 8 | .. note:: 9 | 10 | See sample :ref:`sample_system` 11 | 12 | .. module:: windows.winobject.volume 13 | 14 | .. autoclass:: LogicalDrive 15 | 16 | .. data:: name 17 | 18 | Name of the logical drive 19 | 20 | :type: :class:`str` -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/ncrypt.txt: -------------------------------------------------------------------------------- 1 | SECURITY_STATUS NCryptOpenKey( 2 | [in] NCRYPT_PROV_HANDLE hProvider, 3 | [out] NCRYPT_KEY_HANDLE *phKey, 4 | [in] LPCWSTR pszKeyName, 5 | [in] DWORD dwLegacyKeySpec, 6 | [in] DWORD dwFlags 7 | ); 8 | 9 | 10 | SECURITY_STATUS NCryptOpenStorageProvider( 11 | [out] NCRYPT_PROV_HANDLE *phProvider, 12 | [in, optional] LPCWSTR pszProviderName, 13 | [in] DWORD dwFlags 14 | ); -------------------------------------------------------------------------------- /docs/build/html/_sources/volume.rst.txt: -------------------------------------------------------------------------------- 1 | Volume -- The logical drives 2 | ============================ 3 | 4 | The list of logical drives is accessible via :py:attr:`windows.system.logicaldrives 5 | ` 6 | 7 | 8 | .. note:: 9 | 10 | See sample :ref:`sample_system` 11 | 12 | .. module:: windows.winobject.volume 13 | 14 | .. autoclass:: LogicalDrive 15 | 16 | .. data:: name 17 | 18 | Name of the logical drive 19 | 20 | :type: :class:`str` -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/IUnknown.txt: -------------------------------------------------------------------------------- 1 | typedef struct IUnknownVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IUnknown * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | IUnknown * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | IUnknown * This); 16 | 17 | END_INTERFACE 18 | } IUnknownVtbl; -------------------------------------------------------------------------------- /windows/winproxy/apis/cryptui.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter 5 | from ..error import fail_on_zero 6 | 7 | class CryptUIProxy(ApiProxy): 8 | APIDLL = "cryptui" 9 | default_error_check = staticmethod(fail_on_zero) 10 | 11 | 12 | @CryptUIProxy() 13 | def CryptUIDlgViewContext(dwContextType, pvContext, hwnd, pwszTitle, dwFlags, pvReserved): 14 | return CryptUIDlgViewContext.ctypes_function(dwContextType, pvContext, hwnd, pwszTitle, dwFlags, pvReserved) 15 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_CRYPT_ATTRIBUTES.py: -------------------------------------------------------------------------------- 1 | OLD_CRYPT_ATTRIBUTES = _CRYPT_ATTRIBUTES 2 | class _CRYPT_ATTRIBUTES(_CRYPT_ATTRIBUTES): 3 | @property 4 | def count(self): # __len__ ? 5 | return self.cAttr 6 | 7 | @property 8 | def attributes(self): 9 | return self.rgAttr[:self.cAttr] 10 | 11 | def __getitem__(self, oid): 12 | return [x for x in self.attributes if x.pszObjId == oid] 13 | 14 | def __repr__(self): 15 | return """<{0} Attributes={1}>""".format(type(self).__name__, self.cAttr) -------------------------------------------------------------------------------- /tests/test_system_modules.py: -------------------------------------------------------------------------------- 1 | import windows 2 | import ctypes 3 | 4 | from .pfwtest import * 5 | 6 | @cross_heaven_gates 7 | def test_system_module_gc(): 8 | # Test for issue 12 (Py3) 9 | # https://github.com/hakril/PythonForWindows/issues/12 10 | mods = windows.system.modules 11 | first_name = mods[0].ImageName 12 | import gc; gc.collect() 13 | # need to do stuff to trigger the bug 14 | # YOLO LA HEAP 15 | for i in range(0x1000): 16 | ctypes.c_buffer(i) 17 | import gc; gc.collect() 18 | assert mods[0].ImageName == first_name -------------------------------------------------------------------------------- /docs/source/network.rst: -------------------------------------------------------------------------------- 1 | Network 2 | ======= 3 | 4 | .. module:: windows.winobject.network 5 | 6 | The :class:`Network` instance is accessible via :py:attr:`windows.system.network 7 | ` 8 | 9 | .. note:: 10 | 11 | See sample :ref:`sample_network_exploration` 12 | 13 | 14 | .. autoclass:: Network 15 | 16 | Connections 17 | """"""""""" 18 | 19 | .. autoclass:: TCP4Connection 20 | 21 | 22 | .. autoclass:: TCP6Connection 23 | 24 | Firewall 25 | """""""" 26 | 27 | .. autoclass:: Firewall 28 | 29 | 30 | .. autoclass:: FirewallRule -------------------------------------------------------------------------------- /windows/crypto/__init__.py: -------------------------------------------------------------------------------- 1 | from windows.generated_def import X509_ASN_ENCODING, PKCS_7_ASN_ENCODING 2 | 3 | DEFAULT_ENCODING = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING 4 | # Keep other imports here so sub-crypto file can import windows.crypto.DEFAULT_ENCODING 5 | from windows.crypto.certificate import * 6 | from windows.crypto.encrypt_decrypt import * 7 | from windows.crypto.sign_verify import * 8 | from windows.crypto.dpapi import * 9 | from windows.crypto.cryptmsg import CryptMessage 10 | from windows.crypto.binary_string_conversion import string_to_binary, binary_to_string 11 | -------------------------------------------------------------------------------- /windows/winproxy/apis/tdh.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter 5 | from ..error import result_is_error_code 6 | 7 | # TDH: Trace Data Helper 8 | # https://docs.microsoft.com/en-us/windows/desktop/etw/retrieving-event-data-using-tdh 9 | 10 | class TdhProxy(ApiProxy): 11 | APIDLL = "tdh" 12 | default_error_check = staticmethod(result_is_error_code) 13 | 14 | @TdhProxy() 15 | def TdhEnumerateProviders(pBuffer, pBufferSize): 16 | return TdhEnumerateProviders.ctypes_function(pBuffer, pBufferSize) -------------------------------------------------------------------------------- /docs/build/html/_sources/network.rst.txt: -------------------------------------------------------------------------------- 1 | Network 2 | ======= 3 | 4 | .. module:: windows.winobject.network 5 | 6 | The :class:`Network` instance is accessible via :py:attr:`windows.system.network 7 | ` 8 | 9 | .. note:: 10 | 11 | See sample :ref:`sample_network_exploration` 12 | 13 | 14 | .. autoclass:: Network 15 | 16 | Connections 17 | """"""""""" 18 | 19 | .. autoclass:: TCP4Connection 20 | 21 | 22 | .. autoclass:: TCP6Connection 23 | 24 | Firewall 25 | """""""" 26 | 27 | .. autoclass:: Firewall 28 | 29 | 30 | .. autoclass:: FirewallRule -------------------------------------------------------------------------------- /docs/source/samples_output/debug_debug_functionbp.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\debug_functionbp.py 2 | NtCreateFile of <50173784>: handle = 0x1c4 3 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Globalization\Sorting\SortDefault.nls> 4 | 5 | NtCreateFile of <50181528>: handle = 0x1ec 6 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Fonts\StaticCache.dat> 7 | 8 | NtCreateFile of <50195912>: handle = 0x1fc 9 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Branding\Basebrd\basebrd.dll> 10 | 11 | Exiting process 12 | -------------------------------------------------------------------------------- /docs/source/service.rst: -------------------------------------------------------------------------------- 1 | Service 2 | ======= 3 | 4 | The services manager is accessible via :py:attr:`windows.system.services 5 | ` 6 | 7 | .. note:: 8 | 9 | See sample :ref:`sample_system` & :ref:`sample_services_demo` 10 | 11 | .. module:: windows.winobject.service 12 | 13 | 14 | ServiceManager 15 | """""""""""""" 16 | 17 | .. autoclass:: ServiceManager 18 | :show-inheritance: 19 | :inherited-members: 20 | :special-members: __getitem__, __iter__ 21 | 22 | 23 | Service 24 | """"""" 25 | 26 | .. autoclass:: Service 27 | :inherited-members: -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/io.txt: -------------------------------------------------------------------------------- 1 | typedef struct _OVERLAPPED { 2 | ULONG_PTR Internal; 3 | ULONG_PTR InternalHigh; 4 | union { 5 | struct { 6 | DWORD Offset; 7 | DWORD OffsetHigh; 8 | } _ANON_OVERLAPPED_DUMMYSTRUCTNAME; 9 | PVOID Pointer; 10 | } _ANON_OVERLAPPED_DUMMYUNIONNAME; 11 | HANDLE hEvent; 12 | } OVERLAPPED, *LPOVERLAPPED; 13 | 14 | typedef struct _OVERLAPPED_ENTRY { 15 | ULONG_PTR lpCompletionKey; 16 | LPOVERLAPPED lpOverlapped; 17 | ULONG_PTR Internal; 18 | DWORD dwNumberOfBytesTransferred; 19 | } OVERLAPPED_ENTRY, *LPOVERLAPPED_ENTRY; -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_SID_AND_ATTRIBUTES.py: -------------------------------------------------------------------------------- 1 | _INITIAL_SID_AND_ATTRIBUTES = _SID_AND_ATTRIBUTES 2 | class _SID_AND_ATTRIBUTES(_INITIAL_SID_AND_ATTRIBUTES): 3 | pass 4 | 5 | # Only in TOKEN_GROUPS 6 | # attributes = FlagExatractor(_INITIAL_SID_AND_ATTRIBUTES.Attributes, 7 | # (SE_GROUP_MANDATORY, 8 | # SE_GROUP_ENABLED_BY_DEFAULT, 9 | # SE_GROUP_ENABLED, 10 | # SE_GROUP_OWNER, 11 | # SE_GROUP_USE_FOR_DENY_ONLY, 12 | # SE_GROUP_INTEGRITY, 13 | # SE_GROUP_INTEGRITY_ENABLED, 14 | # SE_GROUP_LOGON_ID, 15 | # SE_GROUP_RESOURCE)) -------------------------------------------------------------------------------- /docs/build/html/_sources/service.rst.txt: -------------------------------------------------------------------------------- 1 | Service 2 | ======= 3 | 4 | The services manager is accessible via :py:attr:`windows.system.services 5 | ` 6 | 7 | .. note:: 8 | 9 | See sample :ref:`sample_system` & :ref:`sample_services_demo` 10 | 11 | .. module:: windows.winobject.service 12 | 13 | 14 | ServiceManager 15 | """""""""""""" 16 | 17 | .. autoclass:: ServiceManager 18 | :show-inheritance: 19 | :inherited-members: 20 | :special-members: __getitem__, __iter__ 21 | 22 | 23 | Service 24 | """"""" 25 | 26 | .. autoclass:: Service 27 | :inherited-members: -------------------------------------------------------------------------------- /docs/source/samples_output/com_com_inetfwpolicy2.txt: -------------------------------------------------------------------------------- 1 | (cmd) python com\com_inetfwpolicy2.py 2 | Initialisation of COM 3 | Creating INetFwPolicy2 variable 4 | at 0x2925a3e2350> (value = None) 5 | 6 | Generating CLSID 7 | 8 | 9 | Creating COM instance 10 | (value = 0x2827524184096) 11 | 12 | Checking for enabled profiles 13 | * NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN(0x1) -> True 14 | * NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE(0x2) -> True 15 | * NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC(0x4) -> True 16 | -------------------------------------------------------------------------------- /samples/security/explain_security_desciptor.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os.path 3 | 4 | import windows.security 5 | 6 | 7 | 8 | parser = argparse.ArgumentParser(prog=__file__) 9 | parser.add_argument('sddl', help='The SDDL to explain') 10 | parser.add_argument('--type', help='The type of object described by the SDDL (used for the explication of values in the access mask)') 11 | res = parser.parse_args() 12 | 13 | if os.path.exists(res.sddl): 14 | windows.security.SecurityDescriptor.from_filename(res.sddl).explain("file") 15 | else: 16 | windows.security.SecurityDescriptor.from_string(res.sddl).explain(res.type) 17 | -------------------------------------------------------------------------------- /docs/source/samples_output/com_icallinterceptor.txt: -------------------------------------------------------------------------------- 1 | (cmd) python com\icallinterceptor.py 2 | Hello from python sink ! 3 | Catching call to 4 | Info about parameters 0: 5 | * param0info.fIn -> 0x1 6 | * param0info.fOut -> 0x0 7 | * param0info.stackOffset -> 0x8 8 | * param0info.cbParam -> 0x8 9 | param0 value = 2 10 | Leaving the sink ! 11 | return value = 1234 12 | firewall enabled = VARIANT_BOOL(True) 13 | Testing a function taking a PTR to a COM interface 14 | Before call: ( at 0x1fb65de5550>, None) 15 | After call: (, 2179257488408) 16 | -------------------------------------------------------------------------------- /docs/source/winobject.rst: -------------------------------------------------------------------------------- 1 | The :mod:`windows` objects 2 | ========================== 3 | 4 | Through the :ref:`system ` object many classes representing various `Windows` 5 | parts are accessible. 6 | 7 | This sections describes them by group of relation. 8 | 9 | .. toctree:: 10 | :maxdepth: 3 11 | 12 | process.rst 13 | token.rst 14 | exception.rst 15 | registry.rst 16 | network.rst 17 | service.rst 18 | volume.rst 19 | wmi.rst 20 | handle.rst 21 | system_module.rst 22 | object_manager.rst 23 | device_manager.rst 24 | task_scheduler.rst 25 | evtlog.rst 26 | etw.rst -------------------------------------------------------------------------------- /docs/source/samples_output/pipe_child_send_object.txt: -------------------------------------------------------------------------------- 1 | (cmd) python pipe\child_send_object.py 2 | Child is 3 | Created pipe is 4 | Receiving object from injected process 5 | Remote Address = 0x97a0000 6 | Querying memory in target at <0x97a0000> 7 | * 8 | Querying mapped file in target at <0x97a0000> 9 | * \Device\HarddiskVolume2\Users\hakril\Documents\projets\PythonForWindows\samples\tst.txt 10 | -------------------------------------------------------------------------------- /docs/build/html/_sources/winobject.rst.txt: -------------------------------------------------------------------------------- 1 | The :mod:`windows` objects 2 | ========================== 3 | 4 | Through the :ref:`system ` object many classes representing various `Windows` 5 | parts are accessible. 6 | 7 | This sections describes them by group of relation. 8 | 9 | .. toctree:: 10 | :maxdepth: 3 11 | 12 | process.rst 13 | token.rst 14 | exception.rst 15 | registry.rst 16 | network.rst 17 | service.rst 18 | volume.rst 19 | wmi.rst 20 | handle.rst 21 | system_module.rst 22 | object_manager.rst 23 | device_manager.rst 24 | task_scheduler.rst 25 | evtlog.rst 26 | etw.rst -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/IStdIdentity.txt: -------------------------------------------------------------------------------- 1 | // IStdIdentity is an empty interface to check that an object is the IStdIdentity 2 | // and thus query other interface 3 | typedef struct IStdIdentityVtbl 4 | { 5 | BEGIN_INTERFACE 6 | 7 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 8 | IUnknown * This, 9 | /* [in] */ REFIID riid, 10 | /* [annotation][iid_is][out] */ 11 | __RPC__deref_out void **ppvObject); 12 | 13 | ULONG ( STDMETHODCALLTYPE *AddRef )( 14 | IUnknown * This); 15 | 16 | ULONG ( STDMETHODCALLTYPE *Release )( 17 | IUnknown * This); 18 | 19 | END_INTERFACE 20 | } IStdIdentityVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/windef_evtlog.txt: -------------------------------------------------------------------------------- 1 | #define EVENTLOG_SUCCESS 0x0000 2 | #define EVENTLOG_ERROR_TYPE 0x0001 3 | #define EVENTLOG_WARNING_TYPE 0x0002 4 | #define EVENTLOG_INFORMATION_TYPE 0x0004 5 | #define EVENTLOG_AUDIT_SUCCESS 0x0008 6 | #define EVENTLOG_AUDIT_FAILURE 0x0010 7 | 8 | 9 | #define EVENTLOG_SEQUENTIAL_READ 0x0001 10 | #define EVENTLOG_SEEK_READ 0x0002 11 | #define EVENTLOG_FORWARDS_READ 0x0004 12 | #define EVENTLOG_BACKWARDS_READ 0x0008 13 | 14 | #define EVT_VARIANT_TYPE_MASK 0x7f 15 | #define EVT_VARIANT_TYPE_ARRAY 128 -------------------------------------------------------------------------------- /docs/source/samples_output/process_iat_hook.txt: -------------------------------------------------------------------------------- 1 | (cmd) python process\iat_hook.py 2 | Asking for 3 | Hook called | hKey = 0x12d687 | lpSubKey = 4 | Secret key asked, returning magic handle 0x12345678 5 | Result = 0x12345678 6 | 7 | Asking for 8 | Hook called | hKey = 0x12d687 | lpSubKey = 9 | Asked for a failing key: returning 0x2a 10 | WindowsError(42, 'Windows Error 0x2A') 11 | 12 | Asking for 13 | Hook called | hKey = 0x80000001L | lpSubKey = 14 | Non-secret key : calling normal function 15 | Result = 0x428 16 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_FILE_RENAME_INFORMATION.py: -------------------------------------------------------------------------------- 1 | INITIAL_FILE_RENAME_INFORMATION = _FILE_RENAME_INFORMATION 2 | 3 | class _FILE_RENAME_INFORMATION(INITIAL_FILE_RENAME_INFORMATION): 4 | @property 5 | def filename(self): 6 | filename_addr = ctypes.addressof(self) + type(self).FileName.offset 7 | if getattr(self, "_target", None) is not None: #remote ctypes :D -> TRICKS OF THE YEAR 8 | raw_data = self._target.read_memory(filename_addr, self.FileNameLength) 9 | return raw_data.decode("utf16") 10 | size = int(self.FileNameLength / 2) 11 | return (ctypes.c_wchar * size).from_address(filename_addr)[:] 12 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/time.txt: -------------------------------------------------------------------------------- 1 | BOOL FileTimeToSystemTime( 2 | FILETIME *lpFileTime, 3 | LPSYSTEMTIME lpSystemTime 4 | ); 5 | 6 | BOOL SystemTimeToFileTime( 7 | SYSTEMTIME *lpSystemTime, 8 | LPFILETIME lpFileTime 9 | ); 10 | 11 | // void 12 | PVOID GetSystemTime( 13 | LPSYSTEMTIME lpSystemTime 14 | ); 15 | 16 | BOOL GetSystemTimes( 17 | PFILETIME lpIdleTime, 18 | PFILETIME lpKernelTime, 19 | PFILETIME lpUserTime 20 | ); 21 | 22 | // void 23 | PVOID GetSystemTimeAsFileTime( 24 | LPFILETIME lpSystemTimeAsFileTime 25 | ); 26 | 27 | // void 28 | PVOID GetLocalTime( 29 | LPSYSTEMTIME lpSystemTime 30 | ); 31 | 32 | DWORD GetTickCount(); 33 | 34 | ULONGLONG GetTickCount64(); -------------------------------------------------------------------------------- /samples/object_manager/winobj.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import windows 4 | import windows.generated_def as gdef 5 | 6 | def obj_with_link(obj): 7 | target = obj.target 8 | if target is None: 9 | return str(obj) 10 | return "{0} -> <{1}>".format(obj, target) 11 | 12 | def fulllistdir(dir, depth=0): 13 | for name, obj in dir.items(): 14 | print("{0} * {1}".format(" " * depth, obj_with_link(obj))) 15 | if obj.type == "Directory": 16 | try: 17 | fulllistdir(obj, depth + 4) 18 | except gdef.NtStatusException as e: 19 | print("{0} * {1}".format(" " * (depth + 4), e)) 20 | 21 | 22 | fulllistdir(windows.system.object_manager.root) -------------------------------------------------------------------------------- /docs/generate_winproxy_list.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os.path 3 | sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "\\..") 4 | print(sys.path[-1]) 5 | import pydoc 6 | import re 7 | import windows 8 | 9 | 10 | winprox = windows.winproxy 11 | all_in_module = [getattr(winprox, x) for x in dir(winprox)] 12 | functions = [f for f in all_in_module if hasattr(f, "prototype")] 13 | 14 | import pdb;pdb.set_trace() 15 | 16 | print ("Functions:") 17 | print("") 18 | for f in functions: 19 | doc = pydoc.text.document(f) 20 | doc = re.sub("\x08." , "", doc) 21 | print("* {0}::\n\n {1}".format(f.func_name, doc)) 22 | #print("* {0}::\n\n {1}".format(f.func_name, pydoc.plain(pydoc.render_doc(f)))) 23 | 24 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/disk.txt: -------------------------------------------------------------------------------- 1 | DWORD OpenVirtualDisk( 2 | PVIRTUAL_STORAGE_TYPE VirtualStorageType, 3 | PCWSTR Path, 4 | VIRTUAL_DISK_ACCESS_MASK VirtualDiskAccessMask, 5 | OPEN_VIRTUAL_DISK_FLAG Flags, 6 | POPEN_VIRTUAL_DISK_PARAMETERS Parameters, 7 | PHANDLE Handle 8 | ); 9 | 10 | 11 | DWORD AttachVirtualDisk( 12 | HANDLE VirtualDiskHandle, 13 | PSECURITY_DESCRIPTOR SecurityDescriptor, 14 | ATTACH_VIRTUAL_DISK_FLAG Flags, 15 | ULONG ProviderSpecificFlags, 16 | PATTACH_VIRTUAL_DISK_PARAMETERS Parameters, 17 | LPOVERLAPPED Overlapped 18 | ); -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/kuser_shared_data.txt: -------------------------------------------------------------------------------- 1 | #define MM_SHARED_USER_DATA_VA 0x7FFE0000 2 | 3 | #define XSTATE_LEGACY_FLOATING_POINT (0) 4 | #define XSTATE_LEGACY_SSE (1) 5 | #define XSTATE_GSSE (2) 6 | #define XSTATE_AVX (XSTATE_GSSE) 7 | #define XSTATE_MPX_BNDREGS (3) 8 | #define XSTATE_MPX_BNDCSR (4) 9 | #define XSTATE_AVX512_KMASK (5) 10 | #define XSTATE_AVX512_ZMM_H (6) 11 | #define XSTATE_AVX512_ZMM (7) 12 | #define XSTATE_IPT (8) 13 | #define XSTATE_LWP (62) 14 | #define MAXIMUM_XSTATE_FEATURES (64) -------------------------------------------------------------------------------- /docs/source/object_manager.rst: -------------------------------------------------------------------------------- 1 | Object Manager -- Kernel objects 2 | ================================ 3 | 4 | .. module:: windows.winobject.object_manager 5 | 6 | The :class:`ObjectManager` instance is accessible via :py:attr:`windows.system.object_manager 7 | ` 8 | 9 | 10 | .. note:: 11 | 12 | See sample at :ref:`sample_object_manager` 13 | 14 | 15 | ObjectManager 16 | """"""""""""" 17 | 18 | .. autoclass:: ObjectManager 19 | :members: 20 | :undoc-members: 21 | :special-members: __getitem__ 22 | 23 | 24 | 25 | KernelObject 26 | """""""""""" 27 | 28 | .. autoclass:: KernelObject 29 | :members: 30 | :undoc-members: 31 | :special-members: __getitem__,__iter__ -------------------------------------------------------------------------------- /docs/source/samples_output/debug_debugger_membp_singlestep.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\debugger_membp_singlestep.py 2 | Got exception EXCEPTION_BREAKPOINT(0x80000003) at 0x7ff8e5aebd44 3 | Got exception UNKNOW_EXCEPTION(0x4000001f) at 0x77e58727 4 | Instruction at <0xa50006> wrote at <0xa60000> 5 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa5000c 6 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa50011 7 | Instruction at <0xa50011> wrote at <0xa60004> 8 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa50017 9 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa5001c 10 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa50022 11 | Got single_step UNKNOW_EXCEPTION(0x4000001e) at 0xa50023 12 | No more single step: exiting 13 | -------------------------------------------------------------------------------- /docs/source/samples_output/wmi_create_process.txt: -------------------------------------------------------------------------------- 1 | (cmd) python wmi\create_process.py 2 | WMI namespace is <> 3 | Process class is 4 | Method Create InParams is <> 5 | Method Create InParams properties are <['CommandLine', 'CurrentDirectory', 'ProcessStartupInformation']> 6 | Creating instance of inparam 7 | InParam instance is <> 8 | Setting 9 | Executing method 10 | OutParams is 11 | Out params values are: ['ProcessId', 'ReturnValue'] 12 | Created process is 13 | Waiting 1s 14 | Killing the process 15 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/atoms.txt: -------------------------------------------------------------------------------- 1 | ATOM AddAtomA( 2 | LPCSTR lpString 3 | ); 4 | 5 | 6 | ATOM AddAtomW( 7 | LPCWSTR lpString 8 | ); 9 | 10 | 11 | ATOM GlobalAddAtomA( 12 | LPCSTR lpString 13 | ); 14 | 15 | ATOM GlobalAddAtomExA( 16 | LPCSTR lpString, 17 | DWORD Flags 18 | ); 19 | 20 | ATOM GlobalAddAtomExW( 21 | LPCWSTR lpString, 22 | DWORD Flags 23 | ); 24 | 25 | 26 | ATOM GlobalAddAtomW( 27 | LPCWSTR lpString 28 | ); 29 | 30 | 31 | ATOM GlobalDeleteAtom( 32 | ATOM nAtom 33 | ); 34 | 35 | 36 | UINT GlobalGetAtomNameA( 37 | ATOM nAtom, 38 | LPSTR lpBuffer, 39 | INT nSize 40 | ); 41 | 42 | UINT GlobalGetAtomNameW( 43 | ATOM nAtom, 44 | LPWSTR lpBuffer, 45 | INT nSize 46 | ); -------------------------------------------------------------------------------- /docs/source/samples_output/debug_symbol_debugger.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\symbol_debugger.py 2 | Namespace(dbghelp=None) 3 | Breakpoint triggered at: ntdll!LdrpInitializeProcess 4 | 5 | 6 | Breakpoint triggered at: KERNELBASE!CreateFileInternal 7 | 8 | 9 | Breakpoint triggered at: KERNELBASE!CreateFileInternal 10 | 11 | 12 | Breakpoint triggered at: KERNELBASE!CreateFileInternal 13 | 14 | Quitting 15 | 16 | -------------------------------------------------------------------------------- /docs/build/html/_sources/object_manager.rst.txt: -------------------------------------------------------------------------------- 1 | Object Manager -- Kernel objects 2 | ================================ 3 | 4 | .. module:: windows.winobject.object_manager 5 | 6 | The :class:`ObjectManager` instance is accessible via :py:attr:`windows.system.object_manager 7 | ` 8 | 9 | 10 | .. note:: 11 | 12 | See sample at :ref:`sample_object_manager` 13 | 14 | 15 | ObjectManager 16 | """"""""""""" 17 | 18 | .. autoclass:: ObjectManager 19 | :members: 20 | :undoc-members: 21 | :special-members: __getitem__ 22 | 23 | 24 | 25 | KernelObject 26 | """""""""""" 27 | 28 | .. autoclass:: KernelObject 29 | :members: 30 | :undoc-members: 31 | :special-members: __getitem__,__iter__ -------------------------------------------------------------------------------- /docs/source/_static/css/mbasic.css: -------------------------------------------------------------------------------- 1 | /* 2 | * basic.css 3 | * ~~~~~~~~~ 4 | * 5 | * Sphinx stylesheet -- basic theme. 6 | * 7 | * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. 8 | * :license: BSD, see LICENSE for details. 9 | * 10 | */ 11 | 12 | /* -- general body styles --------------------------------------------------- */ 13 | 14 | div.body { 15 | min-width: 450px; 16 | max-width: none; 17 | } 18 | 19 | div.bodywrapper { margin-right: 20px; } 20 | 21 | .sphinxsidebarwrapper { overflow-y: scroll; } 22 | 23 | div.admonition-todo { 24 | border-top: 2px solid red; 25 | border-bottom: 2px solid red; 26 | border-left: 2px solid red; 27 | border-right: 2px solid red; 28 | background-color: #ff6347 29 | } -------------------------------------------------------------------------------- /docs/build/html/_static/css/mbasic.css: -------------------------------------------------------------------------------- 1 | /* 2 | * basic.css 3 | * ~~~~~~~~~ 4 | * 5 | * Sphinx stylesheet -- basic theme. 6 | * 7 | * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. 8 | * :license: BSD, see LICENSE for details. 9 | * 10 | */ 11 | 12 | /* -- general body styles --------------------------------------------------- */ 13 | 14 | div.body { 15 | min-width: 450px; 16 | max-width: none; 17 | } 18 | 19 | div.bodywrapper { margin-right: 20px; } 20 | 21 | .sphinxsidebarwrapper { overflow-y: scroll; } 22 | 23 | div.admonition-todo { 24 | border-top: 2px solid red; 25 | border-bottom: 2px solid red; 26 | border-left: 2px solid red; 27 | border-right: 2px solid red; 28 | background-color: #ff6347 29 | } -------------------------------------------------------------------------------- /docs/source/samples_output/process_veh_segv.txt: -------------------------------------------------------------------------------- 1 | (cmd) python process\veh_segv.py 2 | Protected page is at <0x289b6bc0000> 3 | Setting page protection to 4 | 5 | ==Entry of VEH handler== 6 | Instr at 0x7ff8bda3e718 accessed to addr 0x289b6bc0000 7 | Resetting page protection to 8 | ==Entry of VEH handler== 9 | Exception of type EXCEPTION_SINGLE_STEP(0x80000004) 10 | Resetting page protection to 11 | Value 1 read 12 | 13 | ==Entry of VEH handler== 14 | Instr at 0x7ff8bda3e718 accessed to addr 0x289b6bc0010 15 | Resetting page protection to 16 | ==Entry of VEH handler== 17 | Exception of type EXCEPTION_SINGLE_STEP(0x80000004) 18 | Resetting page protection to 19 | Value 2 read 20 | -------------------------------------------------------------------------------- /windows/generated_def/auto_doc_tst.py: -------------------------------------------------------------------------------- 1 | def pretty_print_ctypes_type(t): 2 | format = "{0}" 3 | if issubclass(t, ctypes.Array): 4 | format = "[{0}" + "* {0}]".format(t._length_) 5 | t = t._type_ 6 | 7 | if issubclass(t, ctypes._Pointer): 8 | format = format.format("Pointer({0})") 9 | t = t._type_ 10 | 11 | if issubclass(t, ctypes.Structure): 12 | return format.format(":class:`{0}`".format(t.__name__)) 13 | return t 14 | 15 | 16 | def autodoc_ctypes_struct(struct): 17 | doc = ["fields:"] 18 | for name, type in struct._fields_: 19 | doc.append(" {0} -> {1}".format(name, pretty_print_ctypes_type(type))) 20 | 21 | struct.__doc__ = "\n\n".join(doc) 22 | return struct -------------------------------------------------------------------------------- /ctypes_generation/extended_interfaces/IStream.py: -------------------------------------------------------------------------------- 1 | OLD_IStream = IStream 2 | class IStream(OLD_IStream): 3 | 4 | def read(self, size): 5 | buffer = (CHAR * size)() 6 | size_read = ULONG() 7 | self.Read(buffer, size, size_read) 8 | return buffer[:size_read.value] 9 | 10 | 11 | def write(self, data): 12 | assert isinstance(data, bytes), "IStream.write() only accept bytes but {0} was passed".format(type(data)) 13 | written = ULONG() 14 | self.Write(data, len(data), written) 15 | return written.value 16 | 17 | def seek(self, position, origin=STREAM_SEEK_SET): 18 | newpos = ULARGE_INTEGER() 19 | self.Seek(position, origin, newpos) 20 | return newpos.value 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /docs/source/alpc.rst: -------------------------------------------------------------------------------- 1 | ``windows.alpc`` -- Advanced Local Procedure Call 2 | ************************************************* 3 | 4 | .. module:: windows.alpc 5 | 6 | The :mod:`windows.alpc` module regroups the classes that permits to send and receive 7 | ALPC messages over an ALPC port and the classes representing these messages. 8 | 9 | 10 | .. note:: 11 | 12 | See samples: 13 | 14 | * :ref:`sample_alpc` 15 | * :ref:`sample_advanced_alpc` 16 | 17 | ALPC Message 18 | ------------ 19 | 20 | .. autoclass:: AlpcMessage 21 | 22 | .. autoclass:: AlpcMessagePort 23 | 24 | .. autoclass:: MessageAttribute 25 | 26 | ALPC client 27 | ----------- 28 | 29 | .. autoclass:: AlpcClient 30 | 31 | ALPC Server 32 | ----------- 33 | 34 | .. autoclass:: AlpcServer -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/IInternalUnknown.txt: -------------------------------------------------------------------------------- 1 | typedef struct IInternalUnknownVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IInternalUnknown * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IInternalUnknown * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IInternalUnknown * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *QueryInternalInterface )( 17 | IInternalUnknown * This, 18 | /* [in] */ REFIID riid, 19 | /* [out] */ void **ppv); 20 | 21 | END_INTERFACE 22 | } IInternalUnknownVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/setupapi.txt: -------------------------------------------------------------------------------- 1 | // 2 | // Device interface information structure (references a device 3 | // interface that is associated with the device information 4 | // element that owns it). 5 | // 6 | typedef struct _SP_DEVICE_INTERFACE_DATA { 7 | DWORD cbSize; 8 | GUID InterfaceClassGuid; 9 | DWORD Flags; 10 | ULONG_PTR Reserved; 11 | } SP_DEVICE_INTERFACE_DATA, *PSP_DEVICE_INTERFACE_DATA; 12 | 13 | 14 | // 15 | // Device information structure (references a device instance 16 | // that is a member of a device information set) 17 | // 18 | typedef struct _SP_DEVINFO_DATA { 19 | DWORD cbSize; 20 | GUID ClassGuid; 21 | DWORD DevInst; // DEVINST handle 22 | ULONG_PTR Reserved; 23 | } SP_DEVINFO_DATA, *PSP_DEVINFO_DATA; -------------------------------------------------------------------------------- /docs/source/samples_output/debug_attach.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\attach.py 2 | Finding process with pid <27576> 3 | Target is 4 | Debugger attached: 5 | 6 | NtCreateFile of <54203712>: handle = 0x1c8 7 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Globalization\Sorting\SortDefault.nls> 8 | 9 | NtCreateFile of <54268840>: handle = 0x1f0 10 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Fonts\StaticCache.dat> 11 | 12 | NtCreateFile of <54280288>: handle = 0x200 13 | Handle manually found! typename=, name=<\Device\HarddiskVolume3\Windows\Branding\Basebrd\basebrd.dll> 14 | 15 | Exiting process 16 | -------------------------------------------------------------------------------- /docs/source/samples_output/debug_debugger_print_LdrLoaddll.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\debugger_print_LdrLoaddll.py 2 | Got exception EXCEPTION_BREAKPOINT(0x80000003) at 0x7ff8e5aebd44 3 | Loading 4 | Got exception UNKNOW_EXCEPTION(0x4000001f) at 0x77e58727 5 | Loading 6 | Loading 7 | Loading 8 | Loading 9 | Loading 10 | Loading 11 | Loading 12 | Loading 13 | Loading 14 | Loading 15 | Loading 16 | Ask to load : exiting process 17 | -------------------------------------------------------------------------------- /windows/winproxy/apis/__init__.py: -------------------------------------------------------------------------------- 1 | from .advapi32 import * 2 | from .cfgmgr32 import * 3 | from .crypt32 import * 4 | from .cryptui import * 5 | from .dbghelp import * 6 | from .dnsapi import * 7 | from .iphlpapi import * 8 | from .kernel32 import * 9 | from .ktmw32 import * 10 | from .ncrypt import * 11 | from .ntdll import * 12 | from .netapi32 import * 13 | from .ole32 import * 14 | from .oleaut32 import * 15 | from .oleacc import * 16 | from .psapi import * 17 | from .setupapi import * 18 | from .shell32 import * 19 | from .shlwapi import * 20 | from .tdh import * 21 | from .user32 import * 22 | from .version import * 23 | from .virtdisk import * 24 | from .wevtapi import * 25 | from .winhttp import * 26 | from .wininet import * 27 | from .wintrust import * 28 | from .ws2_32 import * -------------------------------------------------------------------------------- /docs/build/html/_sources/alpc.rst.txt: -------------------------------------------------------------------------------- 1 | ``windows.alpc`` -- Advanced Local Procedure Call 2 | ************************************************* 3 | 4 | .. module:: windows.alpc 5 | 6 | The :mod:`windows.alpc` module regroups the classes that permits to send and receive 7 | ALPC messages over an ALPC port and the classes representing these messages. 8 | 9 | 10 | .. note:: 11 | 12 | See samples: 13 | 14 | * :ref:`sample_alpc` 15 | * :ref:`sample_advanced_alpc` 16 | 17 | ALPC Message 18 | ------------ 19 | 20 | .. autoclass:: AlpcMessage 21 | 22 | .. autoclass:: AlpcMessagePort 23 | 24 | .. autoclass:: MessageAttribute 25 | 26 | ALPC client 27 | ----------- 28 | 29 | .. autoclass:: AlpcClient 30 | 31 | ALPC Server 32 | ----------- 33 | 34 | .. autoclass:: AlpcServer -------------------------------------------------------------------------------- /docs/source/pipe.rst: -------------------------------------------------------------------------------- 1 | ``windows.pipe`` -- Inter-Process Communication 2 | *********************************************** 3 | 4 | .. module:: windows.pipe 5 | 6 | 7 | :mod:`windows.pipe` is wrapper around :class:`_multiprocessing.PipeConnection` simplifiying its use. 8 | 9 | The main improvement are: 10 | 11 | - send/recv object from a pipe name in one line 12 | - Context manager around pipe connection 13 | 14 | .. note:: 15 | 16 | see sample :ref:`sample_pipe` 17 | 18 | Helper functions 19 | """""""""""""""" 20 | 21 | .. autofunction:: create 22 | .. autofunction:: connect 23 | .. autofunction:: recv_object 24 | .. autofunction:: send_object 25 | .. autofunction:: full_pipe_address 26 | 27 | 28 | PipeConnection 29 | """""""""""""" 30 | 31 | .. autoclass:: PipeConnection -------------------------------------------------------------------------------- /docs/source/samples_output/crypto_wintrust.txt: -------------------------------------------------------------------------------- 1 | (cmd) python crypto\wintrust.py 2 | Checking signature of 3 | is_signed: 4 | check_signature: <0> 5 | full_signature_information: 6 | * signed 7 | * catalog 8 | * catalogsigned 9 | * additionalinfo <0> 10 | Checking signature of some loaded DLL 11 | : True 12 | : True 13 | : True 14 | : True 15 | : True 16 | -------------------------------------------------------------------------------- /docs/build/html/_sources/pipe.rst.txt: -------------------------------------------------------------------------------- 1 | ``windows.pipe`` -- Inter-Process Communication 2 | *********************************************** 3 | 4 | .. module:: windows.pipe 5 | 6 | 7 | :mod:`windows.pipe` is wrapper around :class:`_multiprocessing.PipeConnection` simplifiying its use. 8 | 9 | The main improvement are: 10 | 11 | - send/recv object from a pipe name in one line 12 | - Context manager around pipe connection 13 | 14 | .. note:: 15 | 16 | see sample :ref:`sample_pipe` 17 | 18 | Helper functions 19 | """""""""""""""" 20 | 21 | .. autofunction:: create 22 | .. autofunction:: connect 23 | .. autofunction:: recv_object 24 | .. autofunction:: send_object 25 | .. autofunction:: full_pipe_address 26 | 27 | 28 | PipeConnection 29 | """""""""""""" 30 | 31 | .. autoclass:: PipeConnection -------------------------------------------------------------------------------- /tests/test_device_manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import windows 4 | import windows.generated_def as gdef 5 | 6 | from windows.pycompat import unicode_type 7 | 8 | 9 | # Good test candidate for DeviceClass : System {4d36e97d-e325-11ce-bfc1-08002be10318} 10 | # https://learn.microsoft.com/en-us/windows-hardware/drivers/install/system-defined-device-setup-classes-available-to-vendors 11 | # This class includes HALs, system buses, system bridges, the system ACPI driver, and the system volume manager driver. 12 | 13 | 14 | def test_device_manager_class_name(): 15 | assert u"System" in [c.name for c in windows.system.device_manager.classes] 16 | system_class = [c for c in windows.system.device_manager.classes if c.name == u"System"][0] 17 | assert isinstance(system_class.name, unicode_type) -------------------------------------------------------------------------------- /windows/winproxy/apis/ncrypt.py: -------------------------------------------------------------------------------- 1 | 2 | import ctypes 3 | import windows.generated_def as gdef 4 | 5 | from ..apiproxy import ApiProxy, NeededParameter 6 | from ..error import no_error_check, succeed_on_zero 7 | 8 | import windows.pycompat 9 | from windows.pycompat import int_types 10 | 11 | class NCryptProxy(ApiProxy): 12 | APIDLL = "ncrypt" 13 | default_error_check = staticmethod(succeed_on_zero) 14 | 15 | 16 | @NCryptProxy() 17 | def NCryptOpenKey(hProvider, phKey, pszKeyName, dwLegacyKeySpec, dwFlags): 18 | return NCryptOpenKey.ctypes_function(hProvider, phKey, pszKeyName, dwLegacyKeySpec, dwFlags) 19 | 20 | 21 | @NCryptProxy() 22 | def NCryptOpenStorageProvider(phProvider, pszProviderName, dwFlags): 23 | return NCryptOpenStorageProvider.ctypes_function(phProvider, pszProviderName, dwFlags) -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/ICallFrameEvents.txt: -------------------------------------------------------------------------------- 1 | typedef struct ICallFrameEventsVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | ICallFrameEvents * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | ICallFrameEvents * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | ICallFrameEvents * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *OnCall )( 18 | ICallFrameEvents * This, 19 | /* [in] */ ICallFrame *pFrame); 20 | 21 | END_INTERFACE 22 | } ICallFrameEventsVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/ICallFrameWalker.txt: -------------------------------------------------------------------------------- 1 | typedef struct ICallFrameWalkerVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | ICallFrameWalker * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | ICallFrameWalker * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | ICallFrameWalker * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *OnWalkInterface )( 18 | ICallFrameWalker * This, 19 | /* [in] */ REFIID iid, 20 | /* [in] */ PVOID *ppvInterface, 21 | /* [in] */ BOOL fIn, 22 | /* [in] */ BOOL fOut); 23 | 24 | END_INTERFACE 25 | } ICallFrameWalkerVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/IPersist.txt: -------------------------------------------------------------------------------- 1 | typedef struct IPersistVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | __RPC__in IPersist * This, 7 | /* [in] */ __RPC__in REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | __RPC__in IPersist * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | __RPC__in IPersist * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *GetClassID )( 18 | __RPC__in IPersist * This, 19 | /* [out] */ __RPC__out CLSID *pClassID); 20 | 21 | END_INTERFACE 22 | } IPersistVtbl; -------------------------------------------------------------------------------- /tests/test_network.py: -------------------------------------------------------------------------------- 1 | import windows 2 | import windows.generated_def as gdef 3 | 4 | def test_ipv4_connection(): 5 | windows.system.network.ipv4 # Better idea ? 6 | 7 | def test_ipv6_connection(): 8 | windows.system.network.ipv6 # Better idea ? 9 | 10 | def test_firewall(): 11 | firewall = windows.system.network.firewall 12 | assert firewall.enabled # Its a dict that should not be empty 13 | assert firewall.rules # Its a list that should not be empty 14 | # Just check that fields exists and do not crash for now 15 | rule = firewall.rules[0] 16 | rule.name 17 | rule.description 18 | rule.protocol 19 | rule.remote_port 20 | rule.local_port 21 | rule.local_address 22 | rule.remote_address 23 | rule.application_name 24 | rule.direction 25 | rule.enabled 26 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/shell32.txt: -------------------------------------------------------------------------------- 1 | HINSTANCE WINAPI ShellExecuteA( 2 | _In_opt_ HWND hwnd, 3 | _In_opt_ LPCSTR lpOperation, 4 | _In_ LPCSTR lpFile, 5 | _In_opt_ LPCSTR lpParameters, 6 | _In_opt_ LPCSTR lpDirectory, 7 | _In_ INT nShowCmd 8 | ); 9 | 10 | 11 | HINSTANCE WINAPI ShellExecuteW( 12 | _In_opt_ HWND hwnd, 13 | _In_opt_ LPWSTR lpOperation, 14 | _In_ LPWSTR lpFile, 15 | _In_opt_ LPWSTR lpParameters, 16 | _In_opt_ LPWSTR lpDirectory, 17 | _In_ INT nShowCmd 18 | ); 19 | 20 | 21 | BOOL SHGetPathFromIDListA( 22 | PCIDLIST_ABSOLUTE pidl, 23 | LPCSTR pszPath 24 | ); 25 | 26 | BOOL SHGetPathFromIDListW( 27 | PCIDLIST_ABSOLUTE pidl, 28 | LPWSTR pszPath 29 | ); 30 | 31 | INT SHFileOperationA( 32 | LPSHFILEOPSTRUCTA lpFileOp 33 | ); -------------------------------------------------------------------------------- /docs/source/samples_output/service_service_demo.txt: -------------------------------------------------------------------------------- 1 | (cmd) python service\service_demo.py 2 | Listing the first 3 services: 3 | * 4 | * 5 | * 6 | 7 | Retriving service 8 | 9 | - name: 'TapiSrv' 10 | - description: 'Telephony' 11 | - state: SERVICE_STOPPED(0x1) 12 | - type: 48L 13 | - process: None 14 | - security-description: O:SYG:SYD:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWRPLOCRRC;;;IU)(A;;CCLCSWRPLOCRRC;;;SU) 15 | Trying to start the service 16 | Service started ! 17 | 18 | - state: SERVICE_RUNNING(0x4) 19 | - process: 20 | -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_OBJECT_ATTRIBUTES.py: -------------------------------------------------------------------------------- 1 | class _OBJECT_ATTRIBUTES(_OBJECT_ATTRIBUTES): 2 | @classmethod 3 | def from_string(cls, path, attributes=OBJ_CASE_INSENSITIVE): # Directly on constructor ? 4 | self = cls() 5 | self.Length = ctypes.sizeof(self) 6 | self.RootDirectory = 0 7 | self.ObjectName = ctypes.pointer(LSA_UNICODE_STRING.from_string(path)) 8 | self.Attributes = attributes 9 | self.SecurityDescriptor = 0 10 | self.SecurityQualityOfService = 0 11 | return self 12 | 13 | def __repr__(self): 14 | if not self.ObjectName: 15 | return super(_OBJECT_ATTRIBUTES, self).__repr__() 16 | # .contents allow compatibility with remotectypes 17 | return """<{0} ObjectName="{1}">""".format(type(self).__name__, self.ObjectName.contents.str) -------------------------------------------------------------------------------- /samples/pipe/pipe_custom_acl.py: -------------------------------------------------------------------------------- 1 | import windows.test 2 | import windows.pipe 3 | 4 | p = windows.test.pop_proc_32() 5 | print("Child is {0}".format(p)) 6 | 7 | PIPE_NAME = "PFW_Pipe" 8 | 9 | lower_integrity = """ 10 | import windows 11 | import windows.pipe 12 | windows.current_process.token.integrity = 0x1000 13 | """ 14 | 15 | p.execute_python(lower_integrity) 16 | assert p.token.integrity == 0x1000 17 | 18 | send_object = """ 19 | windows.pipe.send_object("{pipe}", {{"KIKOU": "LOL"}}) 20 | """.format(pipe=PIPE_NAME) 21 | 22 | # S:(ML;;;;;LW) -> Allow connection from LOW integrity 23 | with windows.pipe.create(PIPE_NAME, security_descriptor="S:(ML;;;;;LW)") as np: 24 | print("Created pipe is {0}".format(np)) 25 | p.execute_python(send_object) 26 | print("Receiving object from injected process") 27 | obj = np.recv() 28 | print("obj = {0}".format(obj)) -------------------------------------------------------------------------------- /docs/source/system_module.rst: -------------------------------------------------------------------------------- 1 | System Module -- Loaded kernel modules 2 | ====================================== 3 | 4 | .. module:: windows.winobject.system_module 5 | 6 | 7 | The list of system modules is accessible via :py:attr:`windows.system.modules ` 8 | 9 | 10 | .. note:: 11 | 12 | See sample :ref:`sample_system` 13 | 14 | 15 | 16 | 17 | SystemModule 18 | """""""""""" 19 | 20 | .. autoclass:: SystemModule 21 | :inherited-members: 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | 27 | SystemModuleWow64 28 | """"""""""""""""" 29 | 30 | .. autoclass:: SystemModuleWow64 31 | :inherited-members: 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | 37 | BaseSystemModule 38 | """""""""""""""" 39 | 40 | .. autoclass:: BaseSystemModule 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/source/samples_output/debug_symbol_processsymdemo.txt: -------------------------------------------------------------------------------- 1 | (cmd) python debug\symbols\processsymdemo.py 2 | Namespace(dbghelp=None) 3 | Target is 4 | Some loaded modules are: 5 | * 6 | * 7 | * 8 | 9 | Resolving function 10 | Symbol found ! 11 | * __repr__: 12 | * __str__: advapi32!CreateServiceEx 13 | * addr: 0x7ff8e4b2d2e0 14 | * name: CreateServiceEx 15 | * fullname: advapi32!CreateServiceEx 16 | * module: 17 | -------------------------------------------------------------------------------- /windows/winproxy/apis/virtdisk.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter 5 | from ..error import no_error_check, result_is_error_code 6 | 7 | class VirtDiskProxy(ApiProxy): 8 | APIDLL = "virtdisk" 9 | default_error_check = staticmethod(result_is_error_code) 10 | 11 | 12 | @VirtDiskProxy() 13 | def OpenVirtualDisk(VirtualStorageType, Path, VirtualDiskAccessMask, Flags, Parameters, Handle): 14 | return OpenVirtualDisk.ctypes_function(VirtualStorageType, Path, VirtualDiskAccessMask, Flags, Parameters, Handle) 15 | 16 | @VirtDiskProxy() 17 | def AttachVirtualDisk(VirtualDiskHandle, SecurityDescriptor, Flags, ProviderSpecificFlags, Parameters, Overlapped): 18 | return AttachVirtualDisk.ctypes_function(VirtualDiskHandle, SecurityDescriptor, Flags, ProviderSpecificFlags, Parameters, Overlapped) 19 | -------------------------------------------------------------------------------- /docs/build/html/_sources/system_module.rst.txt: -------------------------------------------------------------------------------- 1 | System Module -- Loaded kernel modules 2 | ====================================== 3 | 4 | .. module:: windows.winobject.system_module 5 | 6 | 7 | The list of system modules is accessible via :py:attr:`windows.system.modules ` 8 | 9 | 10 | .. note:: 11 | 12 | See sample :ref:`sample_system` 13 | 14 | 15 | 16 | 17 | SystemModule 18 | """""""""""" 19 | 20 | .. autoclass:: SystemModule 21 | :inherited-members: 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | 27 | SystemModuleWow64 28 | """"""""""""""""" 29 | 30 | .. autoclass:: SystemModuleWow64 31 | :inherited-members: 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | 36 | 37 | BaseSystemModule 38 | """""""""""""""" 39 | 40 | .. autoclass:: BaseSystemModule 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /samples/process/dump_apisetmap.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import windows 3 | 4 | def read_apisetmap(): 5 | cp = windows.current_process 6 | apisetmap_addr = cp.peb.ApiSetMap 7 | print("ApiSetMap address <{0:#x}>".format(apisetmap_addr)) 8 | apisetmap_version = cp.read_dword(apisetmap_addr) 9 | print("ApiSetMap version <{0}>".format(apisetmap_version)) 10 | meminfo = cp.query_memory(apisetmap_addr) 11 | print(meminfo) 12 | data = cp.read_memory(meminfo.BaseAddress, meminfo.RegionSize) 13 | return data 14 | 15 | 16 | 17 | parser = argparse.ArgumentParser(prog=__file__) 18 | parser.add_argument('--filename', default="apisetmap.dmp", help='The filename in which the ApiSetMap is dumped') 19 | res = parser.parse_args() 20 | 21 | with open(res.filename, "wb") as f: 22 | f.write(read_apisetmap().encode("base64")) 23 | print("<{0}> generated".format(res.filename)) -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/rpc/IRpcHelper.txt: -------------------------------------------------------------------------------- 1 | typedef struct IRpcHelperVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IRpcHelper * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IRpcHelper * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IRpcHelper * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *GetDCOMProtocolVersion )( 17 | IRpcHelper * This, 18 | /* [out] */ DWORD *pComVersion); 19 | 20 | HRESULT ( STDMETHODCALLTYPE *GetIIDFromOBJREF )( 21 | IRpcHelper * This, 22 | /* [in] */ void *pObjRef, 23 | /* [out] */ IID **piid); 24 | 25 | END_INTERFACE 26 | } IRpcHelperVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/environ.txt: -------------------------------------------------------------------------------- 1 | DWORD GetEnvironmentVariableA( 2 | [in, optional] LPCSTR lpName, 3 | [out, optional] LPSTR lpBuffer, 4 | [in] DWORD nSize 5 | ); 6 | 7 | DWORD GetEnvironmentVariableW( 8 | [in, optional] LPCWSTR lpName, 9 | [out, optional] LPWSTR lpBuffer, 10 | [in] DWORD nSize 11 | ); 12 | 13 | 14 | BOOL SetEnvironmentVariableA( 15 | [in] LPCSTR lpName, 16 | [in, optional] LPCSTR lpValue 17 | ); 18 | 19 | BOOL SetEnvironmentVariableW( 20 | [in] LPCWSTR lpName, 21 | [in, optional] LPCWSTR lpValue 22 | ); 23 | 24 | PVOID GetEnvironmentStringsA(); 25 | 26 | PVOID GetEnvironmentStringsW(); 27 | 28 | BOOL SetEnvironmentStringsW( 29 | LPWCH NewEnvironment 30 | ); 31 | 32 | BOOL FreeEnvironmentStringsA( 33 | PVOID penv 34 | ); 35 | 36 | BOOL FreeEnvironmentStringsW( 37 | PVOID penv 38 | ); -------------------------------------------------------------------------------- /docs/source/samples_output/process_current_process.txt: -------------------------------------------------------------------------------- 1 | (cmd) python process\current_process.py 2 | current process is 3 | current process is a <64> bits process 4 | current process is a SysWow64 process ? 5 | current process pid <26976> and ppid <28256> 6 | Here are the current process threads: <[, , , ]> 7 | Let's execute some native code ! (0x41 + 1) 8 | Native code returned <0x42> 9 | Allocating memory in current process 10 | Allocated memory is at <0x1dd8d2f0000> 11 | Writing 'SOME STUFF' in allocation memory 12 | Reading memory : 13 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/IClassFactory.txt: -------------------------------------------------------------------------------- 1 | typedef struct IClassFactoryVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IClassFactory * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IClassFactory * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IClassFactory * This); 15 | 16 | /* [local] */ HRESULT ( STDMETHODCALLTYPE *CreateInstance )( 17 | IClassFactory * This, 18 | /* [unique][in] */ IUnknown *pUnkOuter, 19 | /* [in] */ REFIID riid, 20 | /* [iid_is][out] */ void **ppvObject); 21 | 22 | /* [local] */ HRESULT ( STDMETHODCALLTYPE *LockServer )( 23 | IClassFactory * This, 24 | /* [in] */ BOOL fLock); 25 | 26 | END_INTERFACE 27 | } IClassFactoryVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/error_helper.txt: -------------------------------------------------------------------------------- 1 | #define APPLICATION_ERROR_MASK 0x20000000 2 | #define ERROR_SEVERITY_SUCCESS 0x00000000 3 | #define ERROR_SEVERITY_INFORMATIONAL 0x40000000 4 | #define ERROR_SEVERITY_WARNING 0x80000000 5 | #define ERROR_SEVERITY_ERROR 0xC0000000 6 | 7 | // https://learn.microsoft.com/en-us/windows/win32/com/structure-of-com-error-codes 8 | // Define the facility codes 9 | // 10 | #define FACILITY_WINDOWS 0x8 11 | #define FACILITY_WIN32 0x7 12 | #define FACILITY_STORAGE 0x3 13 | #define FACILITY_RPC 0x1 14 | #define FACILITY_NULL 0x0 15 | #define FACILITY_ITF 0x4 16 | #define FACILITY_DISPATCH 0x2 17 | 18 | 19 | // 20 | // Define the severity codes 21 | // 22 | #define STATUS_SEVERITY_SUCCESS 0x0 23 | #define STATUS_SEVERITY_COERROR 0x2 -------------------------------------------------------------------------------- /docs/source/samples_output/process_apisetmap.txt: -------------------------------------------------------------------------------- 1 | (cmd) python process\apisetmap.py 2 | Computer is a 3 | ApiSetMap: (version = 6) 4 | Entries in 'apisetmap_dict' are the full api-dll path extracted 5 | * apisetmap.apisetmap_dict['api-ms-win-core-processthreads-l1-1-3'] -> kernelbase.dll 6 | Entries in 'resolution_dict' are the contains the util-part check by windows 7 | * apisetmap.resolution_dict['api-ms-win-core-processthreads-l1-1-'] -> kernelbase.dll 8 | ApiSetMap.resolve resolve a api-dll based on the util part 9 | * apisetmap.resolve('api-ms-win-core-processthreads-l1-1-1') -> kernelbase.dll 10 | * apisetmap.resolve('api-ms-win-core-processthreads-l1-1-2') -> kernelbase.dll 11 | * apisetmap.resolve('api-ms-win-core-processthreads-l1-1-PART_IS_IGNORED') -> kernelbase.dll 12 | * apisetmap.resolve('BAD_DLL-3.dll') -> raised: KeyError('BAD_DLL-',) 13 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/manually_created/IProxyServerIdentity.txt: -------------------------------------------------------------------------------- 1 | typedef struct IProxyServerIdentityVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IProxyServerIdentity * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | IProxyServerIdentity * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | IProxyServerIdentity * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *GetServerProcessId )( 18 | IProxyServerIdentity * This, 19 | UINT *processId); 20 | 21 | HRESULT ( STDMETHODCALLTYPE *GetServerProcessHandle )( 22 | IProxyServerIdentity * This, 23 | DWORD dwDesiredAccess, 24 | INT bInheritHandle, 25 | PVOID *phProcess) ; 26 | 27 | END_INTERFACE 28 | } IProxyServerIdentityVtbl; -------------------------------------------------------------------------------- /windows/winproxy/apis/shlwapi.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows 3 | import windows.generated_def as gdef 4 | 5 | from ..apiproxy import ApiProxy, NeededParameter, is_implemented 6 | from ..error import fail_on_zero 7 | 8 | class ShlwapiProxy(ApiProxy): 9 | APIDLL = "Shlwapi" 10 | default_error_check = staticmethod(fail_on_zero) 11 | 12 | @ShlwapiProxy() 13 | def StrStrIW(pszFirst, pszSrch): 14 | return StrStrIW.ctypes_function(pszFirst, pszSrch) 15 | 16 | @ShlwapiProxy() 17 | def StrStrIA(pszFirst, pszSrch): 18 | return StrStrIA.ctypes_function(pszFirst, pszSrch) 19 | 20 | @ShlwapiProxy() 21 | def IsOS(dwOS): 22 | if not is_implemented(IsOS) and windows.system.version[0] < 6: 23 | # Before Vista: 24 | # If so use ordinal 437 from DOCUMENTATION 25 | # https://docs.microsoft.com/en-us/windows/desktop/api/shlwapi/nf-shlwapi-isos#remarks 26 | IsOS.proxy.func_name = 437 27 | return IsOS.ctypes_function(dwOS) 28 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/dpapi.txt: -------------------------------------------------------------------------------- 1 | BOOL CryptProtectData( 2 | DATA_BLOB *pDataIn, 3 | LPCWSTR szDataDescr, 4 | DATA_BLOB *pOptionalEntropy, 5 | PVOID pvReserved, 6 | CRYPTPROTECT_PROMPTSTRUCT *pPromptStruct, 7 | DWORD dwFlags, 8 | DATA_BLOB *pDataOut 9 | ); 10 | 11 | BOOL CryptUnprotectData( 12 | DATA_BLOB *pDataIn, 13 | LPWSTR *ppszDataDescr, 14 | DATA_BLOB *pOptionalEntropy, 15 | PVOID pvReserved, 16 | CRYPTPROTECT_PROMPTSTRUCT *pPromptStruct, 17 | DWORD dwFlags, 18 | DATA_BLOB *pDataOut 19 | ); 20 | 21 | BOOL CryptProtectMemory( 22 | LPVOID pDataIn, 23 | DWORD cbDataIn, 24 | DWORD dwFlags 25 | ); 26 | 27 | BOOL CryptUnprotectMemory( 28 | LPVOID pDataIn, 29 | DWORD cbDataIn, 30 | DWORD dwFlags 31 | ); -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_CRYPT_ATTRIBUTE.py: -------------------------------------------------------------------------------- 1 | OLD_CRYPT_ATTRIBUTE = _CRYPT_ATTRIBUTE 2 | 3 | class _CRYPT_ATTRIBUTE(_CRYPT_ATTRIBUTE): 4 | @property 5 | def count(self): # __len__ ? 6 | return self.cValue 7 | 8 | @property 9 | def values(self): 10 | return self.rgValue[:self.cValue] 11 | 12 | @property 13 | def objid(self): 14 | # SZOID_MAPPER defined in the generated structures template.py 15 | return SZOID_MAPPER[self.pszObjId] 16 | 17 | def __repr__(self): 18 | # return """<{0} pszObjId={1!r} Values={2}>""".format(type(self).__name__, self.objid, self.cValue) 19 | if not self.pszObjId in SZOID_MAPPER: 20 | return """<{0} pszObjId="{1}" Values={2}>""".format(type(self).__name__, self.pszObjId, self.cValue) 21 | flag = SZOID_MAPPER[self.pszObjId] 22 | return """<{0} pszObjId="{1}" ({2}) Values={3}>""".format(type(self).__name__, flag, flag.name, self.cValue) -------------------------------------------------------------------------------- /ctypes_generation/extended_structs/_LIST_ENTRY.py: -------------------------------------------------------------------------------- 1 | # From: ctypes_generation\extended_structs\_LIST_ENTRY.py 2 | # _LIST_ENTRY is a self referencing structure 3 | # Currently ctypes generation does not support extending self referencing structures 4 | # Ass the _fields_ assignement should happen after the extended structure definition 5 | # So we just redefine fully _LIST_ENTRY without inheriting the real one 6 | 7 | class _LIST_ENTRY(Structure): 8 | def get_real_struct(self, targetcls, target_field): 9 | # >>> gdef.LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks 10 | # 11 | # This field object does not allow to retrieve the type.. 12 | # So we need to basse the target class AND the target field.. 13 | return targetcls.from_address(ctypes.addressof(self) - target_field.offset) 14 | 15 | _LIST_ENTRY._fields_ = [ 16 | ("Flink", POINTER(_LIST_ENTRY)), 17 | ("Blink", POINTER(_LIST_ENTRY)), 18 | ] -------------------------------------------------------------------------------- /docs/source/registry.rst: -------------------------------------------------------------------------------- 1 | Registry 2 | ======== 3 | 4 | .. module:: windows.winobject.registry 5 | 6 | The :class:`Registry` instance is accessible via :py:attr:`windows.system.registry 7 | ` 8 | 9 | .. note:: 10 | 11 | See sample :ref:`sample_registry` 12 | 13 | Registry 14 | """""""" 15 | 16 | .. autoclass:: Registry 17 | :special-members: __call__ 18 | 19 | 20 | PyHKey 21 | """""" 22 | 23 | .. autoclass:: PyHKey 24 | 25 | .. function:: __call__(name) 26 | 27 | Alias for :func:`open_subkey` 28 | 29 | .. function:: __getitem__(name) 30 | 31 | Alias for :func:`get` 32 | 33 | .. function:: __setitem__(name) 34 | 35 | Wrapper for :func:`set`, accept ``value`` or ``(value, type)`` 36 | 37 | .. function:: __delitem__(name) 38 | 39 | Alias for :func:`delete_value` 40 | 41 | KeyValue 42 | """""""" 43 | 44 | .. autoclass:: KeyValue 45 | :exclude-members: count, index -------------------------------------------------------------------------------- /docs/build/html/_sources/registry.rst.txt: -------------------------------------------------------------------------------- 1 | Registry 2 | ======== 3 | 4 | .. module:: windows.winobject.registry 5 | 6 | The :class:`Registry` instance is accessible via :py:attr:`windows.system.registry 7 | ` 8 | 9 | .. note:: 10 | 11 | See sample :ref:`sample_registry` 12 | 13 | Registry 14 | """""""" 15 | 16 | .. autoclass:: Registry 17 | :special-members: __call__ 18 | 19 | 20 | PyHKey 21 | """""" 22 | 23 | .. autoclass:: PyHKey 24 | 25 | .. function:: __call__(name) 26 | 27 | Alias for :func:`open_subkey` 28 | 29 | .. function:: __getitem__(name) 30 | 31 | Alias for :func:`get` 32 | 33 | .. function:: __setitem__(name) 34 | 35 | Wrapper for :func:`set`, accept ``value`` or ``(value, type)`` 36 | 37 | .. function:: __delitem__(name) 38 | 39 | Alias for :func:`delete_value` 40 | 41 | KeyValue 42 | """""""" 43 | 44 | .. autoclass:: KeyValue 45 | :exclude-members: count, index -------------------------------------------------------------------------------- /docs/source/wintrust.rst: -------------------------------------------------------------------------------- 1 | ``windows.wintrust`` -- Checking signature 2 | ****************************************** 3 | 4 | .. module:: windows.wintrust 5 | 6 | .. note:: 7 | 8 | See sample :ref:`sample_wintrust` 9 | 10 | The :mod:`wintrust` module offers wrapper around ``wintrust.dll``. 11 | It allows to check the signature of a file. 12 | 13 | The signature of a file can be at two differents place: 14 | 15 | * In the file itself (:func:`check_signature`) 16 | * In a catalog file (:func:`full_signature_information`) 17 | 18 | .. note:: 19 | 20 | `Explanation about catalog files `_ 21 | 22 | 23 | API 24 | """ 25 | 26 | .. autofunction:: is_signed 27 | 28 | .. autofunction:: full_signature_information 29 | 30 | .. autofunction:: check_signature 31 | 32 | 33 | SignatureData 34 | ''''''''''''' 35 | 36 | .. autoclass:: SignatureData 37 | :exclude-members: count, index 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /tests/test_bits.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os.path 3 | 4 | import windows 5 | import windows.generated_def as gdef 6 | 7 | pytestmark = pytest.mark.usefixtures("init_com_security") 8 | 9 | SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) 10 | 11 | @pytest.fixture 12 | def bitsjob(): 13 | newjob = windows.system.bits.create("PFW_TEST_BITSJOB", gdef.BG_JOB_TYPE_DOWNLOAD) 14 | yield newjob 15 | newjob.Cancel() 16 | 17 | def test_job_state(bitsjob): 18 | # Check state returns the value and not enum struct 19 | assert bitsjob.state == gdef.BG_JOB_STATE_SUSPENDED 20 | # Enum value should be castable to int 21 | assert int(bitsjob.state) == gdef.BG_JOB_STATE_SUSPENDED 22 | 23 | def test_job_multi_files(bitsjob): 24 | bitsjob.AddFile("https://example.com/REMOTE_FILE_1", os.path.join(SCRIPT_PATH, "local1")) 25 | bitsjob.AddFile("https://example.com/REMOTE_FILE_2", os.path.join(SCRIPT_PATH, "local2")) 26 | files = bitsjob.files 27 | assert len(files) == 2 28 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/rpc/IRpcOptions.txt: -------------------------------------------------------------------------------- 1 | typedef struct IRpcOptionsVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IRpcOptions * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IRpcOptions * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IRpcOptions * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *Set )( 17 | IRpcOptions * This, 18 | /* [in] */ IUnknown *pPrx, 19 | /* [in] */ DWORD dwProperty, 20 | /* [in] */ ULONG_PTR dwValue); 21 | 22 | HRESULT ( STDMETHODCALLTYPE *Query )( 23 | IRpcOptions * This, 24 | /* [in] */ IUnknown *pPrx, 25 | /* [in] */ DWORD dwProperty, 26 | /* [out] */ ULONG_PTR *pdwValue); 27 | 28 | END_INTERFACE 29 | } IRpcOptionsVtbl; -------------------------------------------------------------------------------- /docs/build/html/_sources/wintrust.rst.txt: -------------------------------------------------------------------------------- 1 | ``windows.wintrust`` -- Checking signature 2 | ****************************************** 3 | 4 | .. module:: windows.wintrust 5 | 6 | .. note:: 7 | 8 | See sample :ref:`sample_wintrust` 9 | 10 | The :mod:`wintrust` module offers wrapper around ``wintrust.dll``. 11 | It allows to check the signature of a file. 12 | 13 | The signature of a file can be at two differents place: 14 | 15 | * In the file itself (:func:`check_signature`) 16 | * In a catalog file (:func:`full_signature_information`) 17 | 18 | .. note:: 19 | 20 | `Explanation about catalog files `_ 21 | 22 | 23 | API 24 | """ 25 | 26 | .. autofunction:: is_signed 27 | 28 | .. autofunction:: full_signature_information 29 | 30 | .. autofunction:: check_signature 31 | 32 | 33 | SignatureData 34 | ''''''''''''' 35 | 36 | .. autoclass:: SignatureData 37 | :exclude-members: count, index 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/simple_structs.txt: -------------------------------------------------------------------------------- 1 | /* Structures that do not depends on anything other that basic type 2 | Simplify structure dependancy file graph 3 | */ 4 | 5 | typedef struct _LIST_ENTRY { 6 | struct _LIST_ENTRY *Flink; 7 | struct _LIST_ENTRY *Blink; 8 | } LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY; 9 | 10 | typedef struct _LSA_UNICODE_STRING { 11 | USHORT Length; 12 | USHORT MaximumLength; 13 | PVOID Buffer; // PVOID to prevent ctypes to automatically read the content of the buffer till a \0 14 | } LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING; 15 | 16 | typedef struct _CLIENT_ID{ 17 | HANDLE UniqueProcess; 18 | HANDLE UniqueThread; 19 | } CLIENT_ID, *PCLIENT_ID; 20 | 21 | typedef struct _CLIENT_ID64{ 22 | ULONG64 UniqueProcess; 23 | ULONG64 UniqueThread; 24 | } CLIENT_ID64, *PCLIENT_ID64; 25 | 26 | typedef struct _CLIENT_ID32{ 27 | ULONG UniqueProcess; 28 | ULONG UniqueThread; 29 | } CLIENT_ID32, *PCLIENT_ID32; -------------------------------------------------------------------------------- /docs/source/etw.rst: -------------------------------------------------------------------------------- 1 | ETW -- Event Tracing for Windows 2 | ================================ 3 | 4 | .. module:: windows.winobject.event_trace 5 | 6 | The :class:`EtwManager` instance is accessible via :py:attr:`windows.system.etw 7 | ` 8 | 9 | .. note:: 10 | 11 | This code is the result of my research on ``ETW`` that lead to this presentation `ETW for the lazy reverser (FR) `_ 12 | 13 | 14 | .. note:: 15 | 16 | See sample :ref:`sample_etw` 17 | 18 | 19 | EtwManager 20 | """""""""" 21 | 22 | 23 | .. autoclass:: EtwManager 24 | :members: 25 | 26 | 27 | Tracing Events 28 | """""""""""""" 29 | 30 | EtwTrace 31 | '''''''' 32 | 33 | .. autoclass:: EtwTrace 34 | :members: 35 | 36 | 37 | EventTraceProperties 38 | '''''''''''''''''''' 39 | 40 | .. autoclass:: EventTraceProperties 41 | :members: 42 | 43 | EventRecord 44 | ''''''''''' 45 | 46 | .. autoclass:: EventRecord 47 | :members: 48 | 49 | -------------------------------------------------------------------------------- /samples/debug/debugger_on_setup.py: -------------------------------------------------------------------------------- 1 | import windows.debug 2 | 3 | class MySetupDebugger(windows.debug.Debugger): 4 | def on_setup(self): 5 | super(MySetupDebugger, self).on_setup() 6 | print("Setup called: {0}".format(self.current_process)) 7 | 8 | def on_exception(self, exc): 9 | print("Exception: {0}".format(exc.ExceptionRecord.ExceptionCode)) 10 | 11 | def on_exit_process(self, evt): 12 | print("Process exit: {0}".format(self.current_process)) 13 | 14 | class SimpleDebugger(windows.debug.Debugger): 15 | def on_exception(self, exc): 16 | print("Exception: {0}".format(exc.ExceptionRecord.ExceptionCode)) 17 | 18 | def on_exit_process(self, evt): 19 | print("Process exit: {0}".format(self.current_process)) 20 | 21 | 22 | 23 | print("== With on_setup ==") 24 | dbg = MySetupDebugger.debug(r"c:\windows\system32\whoami.exe") 25 | dbg.loop() 26 | 27 | print("\n== Without on_setup ==") 28 | dbg = SimpleDebugger.debug(r"c:\windows\system32\whoami.exe") 29 | dbg.loop() -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/ICallFactory.txt: -------------------------------------------------------------------------------- 1 | typedef struct ICallFactoryVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | ICallFactory * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | ICallFactory * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | ICallFactory * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *CreateCall )( 18 | ICallFactory * This, 19 | /* [annotation][in] */ 20 | __in REFIID riid, 21 | /* [annotation][in] */ 22 | __in_opt IUnknown *pCtrlUnk, 23 | /* [annotation][in] */ 24 | __in REFIID riid2, 25 | /* [annotation][iid_is][out] */ 26 | __deref_out IUnknown **ppv); 27 | 28 | END_INTERFACE 29 | } ICallFactoryVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/WMI/IWbemLocatorVtbl.txt: -------------------------------------------------------------------------------- 1 | typedef struct IWbemLocatorVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IWbemLocator * This, 7 | /* [in] */ REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | __RPC__deref_out void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | IWbemLocator * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | IWbemLocator * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *ConnectServer )( 18 | IWbemLocator * This, 19 | /* [in] */ const BSTR strNetworkResource, 20 | /* [in] */ const BSTR strUser, 21 | /* [in] */ const BSTR strPassword, 22 | /* [in] */ const BSTR strLocale, 23 | /* [in] */ long lSecurityFlags, 24 | /* [in] */ const BSTR strAuthority, 25 | /* [in] */ IWbemContext *pCtx, 26 | /* [out] */ IWbemServices **ppNamespace); 27 | 28 | END_INTERFACE 29 | } IWbemLocatorVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/combase/IActivationStageInfo.txt: -------------------------------------------------------------------------------- 1 | typedef struct IActivationStageInfoVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IActivationStageInfo * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IActivationStageInfo * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IActivationStageInfo * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *SetStageAndIndex )( 17 | IActivationStageInfo * This, 18 | /* [in] */ ACTIVATION_STAGE stage, 19 | /* [in] */ int index); 20 | 21 | HRESULT ( STDMETHODCALLTYPE *GetStage )( 22 | IActivationStageInfo * This, 23 | /* [out] */ ACTIVATION_STAGE *pstage); 24 | 25 | HRESULT ( STDMETHODCALLTYPE *GetIndex )( 26 | IActivationStageInfo * This, 27 | /* [out] */ int *pindex); 28 | 29 | END_INTERFACE 30 | } IActivationStageInfoVtbl; -------------------------------------------------------------------------------- /docs/source/samples_output/token_token_demo.txt: -------------------------------------------------------------------------------- 1 | (cmd) python token\token_demo.py 2 | Our process token is 3 | Retrieving some infos 4 | Username: 5 | User: 6 | - lookup : ('WILLIE', 'hakril') 7 | Primary group: 8 | - lookup : ('WILLIE', 'Aucun') 9 | 10 | Token Groups is 11 | First group SID is 12 | Some sid and attributes: 13 | - S-1-5-21-184905214-2723199098-2761450773-513: 7 14 | - S-1-1-0: 7 15 | - S-1-5-114: 16 16 | 17 | Duplicate token is 18 | Enabling 19 | Current thread token is 20 | Setting impersonation token ! 21 | Current thread token is 22 | -------------------------------------------------------------------------------- /docs/build/html/_sources/etw.rst.txt: -------------------------------------------------------------------------------- 1 | ETW -- Event Tracing for Windows 2 | ================================ 3 | 4 | .. module:: windows.winobject.event_trace 5 | 6 | The :class:`EtwManager` instance is accessible via :py:attr:`windows.system.etw 7 | ` 8 | 9 | .. note:: 10 | 11 | This code is the result of my research on ``ETW`` that lead to this presentation `ETW for the lazy reverser (FR) `_ 12 | 13 | 14 | .. note:: 15 | 16 | See sample :ref:`sample_etw` 17 | 18 | 19 | EtwManager 20 | """""""""" 21 | 22 | 23 | .. autoclass:: EtwManager 24 | :members: 25 | 26 | 27 | Tracing Events 28 | """""""""""""" 29 | 30 | EtwTrace 31 | '''''''' 32 | 33 | .. autoclass:: EtwTrace 34 | :members: 35 | 36 | 37 | EventTraceProperties 38 | '''''''''''''''''''' 39 | 40 | .. autoclass:: EventTraceProperties 41 | :members: 42 | 43 | EventRecord 44 | ''''''''''' 45 | 46 | .. autoclass:: EventRecord 47 | :members: 48 | 49 | -------------------------------------------------------------------------------- /samples/debug/attach.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os.path 3 | import pprint 4 | sys.path.append(os.path.abspath(__file__ + "\..\..")) 5 | 6 | import windows 7 | import windows.test 8 | import windows.debug 9 | 10 | from windows.generated_def.winstructs import * 11 | 12 | # Just a debugger that follow NtCreateFile and print filename & handler 13 | from debug_functionbp import FollowNtCreateFile 14 | 15 | 16 | def follow_create_file(pid): 17 | print("Finding process with pid <{0}>".format(pid)) 18 | target = [p for p in windows.system.processes if p.pid == pid][0] 19 | print("Target is {0}".format(target)) 20 | dbg = windows.debug.Debugger.attach(target) 21 | print("Debugger attached: {0}".format(dbg)) 22 | print("") 23 | dbg.add_bp(FollowNtCreateFile()) 24 | dbg.loop() 25 | 26 | if __name__ == "__main__": 27 | # Create a non-debugged process safe to debug 28 | calc = windows.test.pop_proc_32(dwCreationFlags=0) 29 | # Give ovnly the PID to follow_create_file 30 | follow_create_file(calc.pid) 31 | -------------------------------------------------------------------------------- /samples/security/security_descriptor.py: -------------------------------------------------------------------------------- 1 | import windows.security 2 | 3 | SDDL = "O:BAG:AND:(A;OI;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)(D;CIIO;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)" 4 | 5 | sd = windows.security.SecurityDescriptor.from_string(SDDL) 6 | print("Security descriptor is: {0}".format(sd)) 7 | 8 | print("Owner: {0}".format(sd.owner)) 9 | print(" - lookup: {0}".format(windows.utils.lookup_sid(sd.owner))) 10 | print("Group: {0}".format(sd.group)) 11 | print(" - lookup: {0}".format(windows.utils.lookup_sid(sd.group))) 12 | 13 | dacl = sd.dacl 14 | print("Dacl: {0}".format(dacl)) 15 | 16 | for i, ace in enumerate(dacl): 17 | print("") 18 | print(" ACE [{0}]: {1}".format(i, ace)) 19 | print(" - Header-AceType: {0}".format(ace.Header.AceType)) 20 | print(" - Header-AceFlags: {0}".format(ace.Header.AceFlags)) 21 | print(" - Header-flags: {0}".format(ace.Header.flags)) 22 | print(" - Mask: {0}".format(ace.Mask)) 23 | print(" - mask: {0}".format(ace.mask)) 24 | print(" - Sid: {0}".format(ace.sid)) -------------------------------------------------------------------------------- /ctypes_generation/dummy_wintypes.py: -------------------------------------------------------------------------------- 1 | names = ['HINSTANCE', 'HRESULT', 'ATOM', 'BOOL', 'BOOLEAN', 'BYTE', 'COLORREF', 'DOUBLE', 'DWORD', 'FILETIME', 'FLOAT', 'HACCEL', 'HANDLE', 'HBITMAP', ' HBRUSH', 'HCOLORSPACE', 'HDC', 'HDESK', 'HDWP', 'HENHMETAFILE', 'HFONT', 'HGDIOBJ', 'HGLOBAL', 'HHOOK', 'HICON', 'HINSTA NCE', 'HKEY', 'HKL', 'HLOCAL', 'HMENU', 'HMETAFILE', 'HMODULE', 'HMONITOR', 'HPALETTE', 'HPEN', 'HRGN', 'HRSRC', 'HSTR', 'HTASK', 'HWINSTA', 'HWND', 'INT', 'LANGID', 'LARGE_INTEGER', 'LCID', 'LCTYPE', 'LGRPID', 'LONG', 'LPARAM', 'LPCOLESTR' , 'LPCSTR', 'LPCVOID', 'LPCWSTR', 'LPOLESTR', 'LPSTR', 'LPVOID', 'LPWSTR', 'MAX_PATH', 'MSG', 'OLESTR', 'POINT', 'POINTL ', 'RECT', 'RECTL', 'RGB', 'SC_HANDLE', 'SERVICE_STATUS_HANDLE', 'SHORT', 'SIZE', 'SIZEL', 'SMALL_RECT', 'UINT', 'ULARGE _INTEGER', 'ULONG', 'USHORT', 'VARIANT_BOOL', 'WCHAR', 'WIN32_FIND_DATAA', 'WIN32_FIND_DATAW', 'WORD', 'WPARAM', '_COORD ', '_FILETIME', '_LARGE_INTEGER', '_POINTL', '_RECTL', '_SMALL_RECT', '_ULARGE_INTEGER', "ULARGE_INTEGER", 'tagMSG', 'tagPOINT', 'tagRECT' , 'tagSIZE'] 2 | -------------------------------------------------------------------------------- /docs/source/samples_output/security_query_sacl.txt: -------------------------------------------------------------------------------- 1 | (cmd) python security\query_sacl.py 2 | This sample should be run as admin to demonstration SACL access 3 | 4 | [NO-PRIV] Querying SecurityDescriptor without SACL 5 | sacl = 6 | 7 | [NO-PRIV] Querying SecurityDescriptor with SACL 8 | None: [Error 1314] A required privilege is not held by the client. 9 | 10 | Enabling 11 | [ERROR] has no privilege 12 | 13 | 14 | (cmd-admin) python security\query_sacl.py 15 | 16 | [NO-PRIV] Querying SecurityDescriptor without SACL 17 | sacl = 18 | 19 | [NO-PRIV] Querying SecurityDescriptor with SACL 20 | None: [Error 1314] A required privilege is not held by the client. 21 | 22 | Enabling 23 | 24 | [PRIV] Querying SecurityDescriptor with SACL 25 | sacl = 26 | [] -------------------------------------------------------------------------------- /windows/winproxy/apis/ktmw32.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter 5 | from ..error import fail_on_zero 6 | 7 | class Ktmw32Proxy(ApiProxy): 8 | APIDLL = "Ktmw32" 9 | default_error_check = staticmethod(fail_on_zero) 10 | 11 | 12 | @Ktmw32Proxy() 13 | def CommitTransaction(TransactionHandle): 14 | return CommitTransaction.ctypes_function(TransactionHandle) 15 | 16 | 17 | @Ktmw32Proxy() 18 | def CreateTransaction(lpTransactionAttributes, UOW, CreateOptions, IsolationLevel, IsolationFlags, Timeout, Description): 19 | return CreateTransaction.ctypes_function(lpTransactionAttributes, UOW, CreateOptions, IsolationLevel, IsolationFlags, Timeout, Description) 20 | 21 | 22 | @Ktmw32Proxy() 23 | def RollbackTransaction(TransactionHandle): 24 | return RollbackTransaction.ctypes_function(TransactionHandle) 25 | 26 | 27 | @Ktmw32Proxy() 28 | def OpenTransaction(dwDesiredAccess, TransactionId): 29 | return OpenTransaction.ctypes_function(dwDesiredAccess, TransactionId) 30 | -------------------------------------------------------------------------------- /samples/registry/registry.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os.path 3 | import pprint 4 | sys.path.append(os.path.abspath(__file__ + "\..\..")) 5 | 6 | import windows 7 | 8 | registry = windows.system.registry 9 | print("Registry is <{0}>".format(registry)) 10 | 11 | current_user = registry("HKEY_CURRENT_USER") 12 | print("HKEY_CURRENT_USER is <{0}>".format(current_user)) 13 | subkeys_name = [s.name for s in current_user.subkeys] 14 | print("HKEY_CURRENT_USER subkeys names are:") 15 | pprint.pprint(subkeys_name) 16 | 17 | print("Opening 'Software' in HKEY_CURRENT_USER: {0}".format(current_user("Software"))) 18 | print("We can also open it in one access: {0}".format(registry(r"HKEY_CURRENT_USER\Sofware"))) 19 | print("Looking at CurrentVersion") 20 | 21 | windows_info = registry("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion") 22 | print("Key is {0}".format(windows_info)) 23 | 24 | print("values are:") 25 | pprint.pprint(windows_info.values) 26 | 27 | registered_owner = windows_info["RegisteredOwner"] 28 | print("registered owner = <{0}>".format(registered_owner)) -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/winfunc_crypto.txt.ignore: -------------------------------------------------------------------------------- 1 | BOOL WINAPI CryptCATAdminCalcHashFromFileHandle( 2 | __in HANDLE hFile, 3 | __inout DWORD *pcbHash, 4 | _Out_opt_ BYTE *pbHash, 5 | __in DWORD dwFlags); 6 | 7 | HCATINFO WINAPI CryptCATAdminEnumCatalogFromHash( 8 | __in HCATADMIN hCatAdmin, 9 | __in BYTE *pbHash, 10 | __in DWORD cbHash, 11 | __in DWORD dwFlags, 12 | __inout HCATINFO *phPrevCatInfo); 13 | 14 | BOOL WINAPI CryptCATAdminAcquireContext( 15 | _Out_ HCATADMIN *phCatAdmin, 16 | _In_ GUID *pgSubsystem, 17 | _In_ DWORD dwFlags 18 | ); 19 | 20 | BOOL WINAPI CryptCATCatalogInfoFromContext( 21 | _In_ HCATINFO hCatInfo, 22 | _Inout_ CATALOG_INFO *psCatInfo, 23 | _In_ DWORD dwFlags 24 | ); 25 | 26 | 27 | BOOL WINAPI CryptCATAdminReleaseCatalogContext( 28 | _In_ HCATADMIN hCatAdmin, 29 | _In_ HCATINFO hCatInfo, 30 | _In_ DWORD dwFlags 31 | ); 32 | 33 | BOOL WINAPI CryptCATAdminReleaseContext( 34 | _In_ HCATADMIN hCatAdmin, 35 | _In_ DWORD dwFlags 36 | ); -------------------------------------------------------------------------------- /docs/source/samples_output/registry_registry.txt: -------------------------------------------------------------------------------- 1 | (cmd) python registry\registry.py 2 | Registry is <> 3 | HKEY_CURRENT_USER is <> 4 | HKEY_CURRENT_USER subkeys names are: 5 | ['AppEvents', 6 | 'AppXBackupContentType', 7 | 'Console', 8 | 'Control Panel', 9 | 'Environment', 10 | 'EUDC', 11 | 'Keyboard Layout', 12 | 'Network', 13 | 'Printers', 14 | 'Software', 15 | 'System', 16 | 'Uninstall', 17 | 'Volatile Environment'] 18 | Opening 'Software' in HKEY_CURRENT_USER: 19 | We can also open it in one access: 20 | Looking at CurrentVersion 21 | Key is 22 | values are: 23 | [KeyValue(name='SoftwareType', value=u'System', type=1), 24 | KeyValue(name='RegisteredOwner', value=u'hakril', type=1), 25 | ... 26 | KeyValue(name='PathName', value=u'C:\\WINDOWS', type=1)] 27 | registered owner = 28 | -------------------------------------------------------------------------------- /docs/source/samples_output/process_msstore_interpreter_remote_python.txt: -------------------------------------------------------------------------------- 1 | PS C:\Users\hakril\PythonForWindows> py .\samples\process\msstore_interpreter_remote_python.py 2 | Executable is: C:\Users\hakril\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\python.exe 3 | Trying normal execute_python() 4 | Exception during proc1.execute_python(): 5 | InjectionFailedError('Injection of failed') 6 | Trying mspython workaround: 7 | Executing python code! 8 | Injecting: C:\Users\hakril\AppData\Local\Temp\pfw_dllcache\vcruntime140.dll 9 | Injecting: C:\Users\hakril\AppData\Local\Temp\pfw_dllcache\python313.dll 10 | Executing more python code! 11 | Executing an error python code! 12 | Expected error during safe_execute_python 13 | b'Traceback (most recent call last):\n File "", line 1, in \nNameError: name \'BAD_VARIABLE\' is not defined\n' 14 | Sleeping a little 15 | Killing target process ! -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/bits.txt: -------------------------------------------------------------------------------- 1 | typedef enum __MIDL_IBackgroundCopyJob2_0002 { 2 | BG_AUTH_SCHEME_BASIC, 3 | BG_AUTH_SCHEME_DIGEST, 4 | BG_AUTH_SCHEME_NTLM, 5 | BG_AUTH_SCHEME_NEGOTIATE, 6 | BG_AUTH_SCHEME_PASSPORT 7 | } BG_AUTH_SCHEME; 8 | 9 | 10 | typedef enum __MIDL_IBackgroundCopyJob2_0001 { 11 | BG_AUTH_TARGET_SERVER, 12 | BG_AUTH_TARGET_PROXY 13 | } BG_AUTH_TARGET; 14 | 15 | 16 | typedef struct __MIDL_IBackgroundCopyJob2_0003 { 17 | LPWSTR UserName; 18 | LPWSTR Password; 19 | } BG_BASIC_CREDENTIALS; 20 | 21 | typedef union __MIDL_IBackgroundCopyJob2_0004 { 22 | BG_BASIC_CREDENTIALS Basic; 23 | } BG_AUTH_CREDENTIALS_UNION; 24 | 25 | typedef struct { 26 | BG_AUTH_TARGET Target; 27 | BG_AUTH_SCHEME Scheme; 28 | BG_AUTH_CREDENTIALS_UNION Credentials; 29 | } BG_AUTH_CREDENTIALS; 30 | 31 | typedef struct _BG_JOB_REPLY_PROGRESS { 32 | UINT64 BytesTotal; 33 | UINT64 BytesTransferred; 34 | } BG_JOB_REPLY_PROGRESS; 35 | 36 | typedef struct _BG_FILE_RANGE { 37 | UINT64 InitialOffset; 38 | UINT64 Length; 39 | } BG_FILE_RANGE; -------------------------------------------------------------------------------- /docs/source/wmi.rst: -------------------------------------------------------------------------------- 1 | WMI -- Make request to WMI 2 | ========================== 3 | 4 | .. module:: windows.winobject.wmi 5 | 6 | 7 | The :class:`WmiManager` is accessible via :py:attr:`windows.system.wmi 8 | ` 9 | 10 | .. note:: 11 | 12 | See sample :ref:`wmi_samples` 13 | 14 | 15 | WmiManager 16 | """""""""" 17 | 18 | .. autoclass:: WmiManager 19 | :no-inherited-members: 20 | :members: DEFAULT_NAMESPACE, select, query, namespaces 21 | 22 | 23 | WmiNamespace 24 | """""""""""" 25 | 26 | .. autoclass:: WmiNamespace 27 | :members: 28 | :show-inheritance: 29 | 30 | WmiObject 31 | """"""""" 32 | 33 | .. autoclass:: WmiObject 34 | :members: 35 | :special-members: __call__, __getitem__, __setitem__ 36 | :show-inheritance: 37 | 38 | 39 | WmiCallResult 40 | """"""""""""" 41 | 42 | .. autoclass:: WmiCallResult 43 | :members: 44 | :show-inheritance: 45 | 46 | WmiEnumeration 47 | """""""""""""" 48 | 49 | .. autoclass:: WmiEnumeration 50 | :members: 51 | :special-members: __call__, __iter__ 52 | :show-inheritance: 53 | -------------------------------------------------------------------------------- /tests/test_service.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import windows 4 | import windows.generated_def as gdef 5 | 6 | 7 | def test_services_process(): 8 | services_with_process = [s for s in windows.system.services if s.status.dwProcessId] 9 | service = services_with_process[0] 10 | proc = service.process 11 | assert proc.pid == service.status.dwProcessId 12 | 13 | 14 | def test_service_appinfo(): 15 | appinfo = windows.system.services["Appinfo"] 16 | assert appinfo.status.type & gdef.SERVICE_WIN32_OWN_PROCESS 17 | # Check other fields 18 | assert appinfo.name == "Appinfo" 19 | assert appinfo.description == "Application Information" 20 | assert appinfo.security_descriptor 21 | 22 | 23 | def test_service_start(): 24 | appinfo = windows.system.services["Appinfo"] 25 | # Just start a random serivce with a string (even if already started) 26 | # Used to check string compat in py2/py3 27 | try: 28 | appinfo.start("TEST STRING") 29 | except WindowsError as e: 30 | if e.winerror != gdef.ERROR_SERVICE_ALREADY_RUNNING: 31 | raise 32 | 33 | -------------------------------------------------------------------------------- /docs/build/html/_sources/wmi.rst.txt: -------------------------------------------------------------------------------- 1 | WMI -- Make request to WMI 2 | ========================== 3 | 4 | .. module:: windows.winobject.wmi 5 | 6 | 7 | The :class:`WmiManager` is accessible via :py:attr:`windows.system.wmi 8 | ` 9 | 10 | .. note:: 11 | 12 | See sample :ref:`wmi_samples` 13 | 14 | 15 | WmiManager 16 | """""""""" 17 | 18 | .. autoclass:: WmiManager 19 | :no-inherited-members: 20 | :members: DEFAULT_NAMESPACE, select, query, namespaces 21 | 22 | 23 | WmiNamespace 24 | """""""""""" 25 | 26 | .. autoclass:: WmiNamespace 27 | :members: 28 | :show-inheritance: 29 | 30 | WmiObject 31 | """"""""" 32 | 33 | .. autoclass:: WmiObject 34 | :members: 35 | :special-members: __call__, __getitem__, __setitem__ 36 | :show-inheritance: 37 | 38 | 39 | WmiCallResult 40 | """"""""""""" 41 | 42 | .. autoclass:: WmiCallResult 43 | :members: 44 | :show-inheritance: 45 | 46 | WmiEnumeration 47 | """""""""""""" 48 | 49 | .. autoclass:: WmiEnumeration 50 | :members: 51 | :special-members: __call__, __iter__ 52 | :show-inheritance: 53 | -------------------------------------------------------------------------------- /samples/pipe/child_send_object.py: -------------------------------------------------------------------------------- 1 | import windows 2 | import windows.test 3 | import windows.pipe 4 | 5 | p = windows.test.pop_proc_32() 6 | print("Child is {0}".format(p)) 7 | 8 | PIPE_NAME = "PFW_Pipe" 9 | 10 | rcode = """ 11 | import windows 12 | import windows.pipe 13 | 14 | f = open('tst.txt', "w+") 15 | fh = windows.utils.get_handle_from_file(f) 16 | hm = windows.winproxy.CreateFileMappingA(fh, dwMaximumSizeLow=0x1000, lpName=None) 17 | addr = windows.winproxy.MapViewOfFile(hm, dwNumberOfBytesToMap=0x1000) 18 | 19 | windows.pipe.send_object("{pipe}", addr) 20 | """ 21 | 22 | with windows.pipe.create(PIPE_NAME) as np: 23 | print("Created pipe is {0}".format(np)) 24 | p.execute_python(rcode.format(pipe=PIPE_NAME)) 25 | print("Receiving object from injected process") 26 | addr = np.recv() 27 | 28 | print("Remote Address = {0:#x}".format(addr)) 29 | print("Querying memory in target at <{0:#x}>".format(addr)) 30 | print(" * {0}".format(p.query_memory(addr))) 31 | print("Querying mapped file in target at <{0:#x}>".format(addr)) 32 | print(" * {0}".format(p.get_mapped_filename(addr))) 33 | p.exit() -------------------------------------------------------------------------------- /docs/source/samples_output/security_security_descriptor.txt: -------------------------------------------------------------------------------- 1 | (cmd) python security\security_descriptor.py 2 | Security descriptor is: O:BAG:AND:(A;OI;CCDCLCSWRPWPRCWDWOGA;;;S-1-0-0)(D;CIIO;CCDCLCSWRPWPRCWDWOGA;;;S-1-0-0) 3 | Owner: S-1-5-32-544 4 | - lookup: ('BUILTIN', 'Administrators') 5 | Group: S-1-5-7 6 | - lookup: ('NT AUTHORITY', 'ANONYMOUS LOGON') 7 | Dacl: 8 | 9 | ACE [0]: 10 | - Header-AceType: ACCESS_ALLOWED_ACE_TYPE(0x0) 11 | - Header-AceFlags: 1 12 | - Header-flags: [OBJECT_INHERIT_ACE(0x1)] 13 | - Mask: 269353023 14 | - mask: [1, 2, 4, 8, 16, 32, READ_CONTROL(0x20000), WRITE_DAC(0x40000), WRITE_OWNER(0x80000), GENERIC_ALL(0x10000000)] 15 | - Sid: S-1-0-0 16 | 17 | ACE [1]: 18 | - Header-AceType: ACCESS_DENIED_ACE_TYPE(0x1) 19 | - Header-AceFlags: 10 20 | - Header-flags: [CONTAINER_INHERIT_ACE(0x2), INHERIT_ONLY_ACE(0x8)] 21 | - Mask: 269353023 22 | - mask: [1, 2, 4, 8, 16, 32, READ_CONTROL(0x20000), WRITE_DAC(0x40000), WRITE_OWNER(0x80000), GENERIC_ALL(0x10000000)] 23 | - Sid: S-1-0-0 24 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/propertysystem/IPackageExecutionStateChangeNotification.txt: -------------------------------------------------------------------------------- 1 | typedef struct IPackageExecutionStateChangeNotificationVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | __RPC__in IPackageExecutionStateChangeNotification * This, 7 | /* [in] */ __RPC__in REFIID riid, 8 | /* [annotation][iid_is][out] */ 9 | _COM_Outptr_ void **ppvObject); 10 | 11 | ULONG ( STDMETHODCALLTYPE *AddRef )( 12 | __RPC__in IPackageExecutionStateChangeNotification * This); 13 | 14 | ULONG ( STDMETHODCALLTYPE *Release )( 15 | __RPC__in IPackageExecutionStateChangeNotification * This); 16 | 17 | HRESULT ( STDMETHODCALLTYPE *OnStateChanged )( 18 | __RPC__in IPackageExecutionStateChangeNotification * This, 19 | /* [string][in] */ __RPC__in_string LPCWSTR pszPackageFullName, 20 | /* [in] */ PACKAGE_EXECUTION_STATE pesNewState); 21 | 22 | END_INTERFACE 23 | } IPackageExecutionStateChangeNotificationVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/combase.txt: -------------------------------------------------------------------------------- 1 | #define ORPCF_NULL ( 0 ) 2 | #define ORPCF_LOCAL ( 1 ) 3 | #define ORPCF_RESERVED1 ( 2 ) 4 | #define ORPCF_RESERVED2 ( 4 ) 5 | #define ORPCF_RESERVED3 ( 8 ) 6 | #define ORPCF_RESERVED4 ( 16 ) 7 | 8 | #define ORPCF_INPUT_SYNC ORPCF_RESERVED1 9 | #define ORPCF_ASYNC ORPCF_RESERVED2 10 | #define ORPCF_DYNAMIC_CLOAKING ORPCF_RESERVED3 11 | 12 | #define ORPCF_REJECTED ORPCF_RESERVED1 13 | #define ORPCF_RETRY_LATER ORPCF_RESERVED2 14 | 15 | #define OBJREF_SIGNATURE ( 0x574f454d ) 16 | #define OBJREF_STANDARD ( 0x1 ) 17 | #define OBJREF_HANDLER ( 0x2 ) 18 | #define OBJREF_CUSTOM ( 0x4 ) 19 | #define OBJREF_EXTENDED ( 0x8 ) 20 | #define SORF_OXRES1 ( 0x1 ) 21 | #define SORF_OXRES2 ( 0x20 ) 22 | #define SORF_OXRES3 ( 0x40 ) 23 | #define SORF_OXRES4 ( 0x80 ) 24 | #define SORF_OXRES5 ( 0x100 ) 25 | #define SORF_OXRES6 ( 0x200 ) 26 | #define SORF_OXRES7 ( 0x400 ) 27 | #define SORF_OXRES8 ( 0x800 ) 28 | #define SORF_NULL ( 0 ) 29 | #define SORF_NOPING ( 0x1000 ) 30 | 31 | #define UNIQUE_FLAG_PADDING 2 32 | #define MAINHDRSIG 0x414E554B 33 | #define ENTRYHDRSIG 0x494E414E -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/internet.txt: -------------------------------------------------------------------------------- 1 | typedef struct _INTERNET_BUFFERSA { 2 | DWORD dwStructSize; 3 | struct _INTERNET_BUFFERSA *Next; 4 | LPCSTR lpcszHeader; 5 | DWORD dwHeadersLength; 6 | DWORD dwHeadersTotal; 7 | LPVOID lpvBuffer; 8 | DWORD dwBufferLength; 9 | DWORD dwBufferTotal; 10 | DWORD dwOffsetLow; 11 | DWORD dwOffsetHigh; 12 | } INTERNET_BUFFERSA, *LPINTERNET_BUFFERSA; 13 | 14 | typedef struct _INTERNET_BUFFERSW { 15 | DWORD dwStructSize; 16 | struct _INTERNET_BUFFERSW *Next; 17 | LPCWSTR lpcszHeader; 18 | DWORD dwHeadersLength; 19 | DWORD dwHeadersTotal; 20 | LPVOID lpvBuffer; 21 | DWORD dwBufferLength; 22 | DWORD dwBufferTotal; 23 | DWORD dwOffsetLow; 24 | DWORD dwOffsetHigh; 25 | } INTERNET_BUFFERSW, *LPINTERNET_BUFFERSW; 26 | 27 | -------------------------------------------------------------------------------- /samples/object_manager/findobj.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import windows 4 | import windows.generated_def as gdef 5 | 6 | def obj_with_link(obj): 7 | target = obj.target 8 | if target is None: 9 | return str(obj) 10 | return "{0} -> <{1}>".format(obj, target) 11 | 12 | 13 | def find_name(root, findname): 14 | TODO = [root] 15 | while TODO: 16 | try: 17 | for name, obj in TODO.pop().items(): 18 | if findname in name or findname in obj.type: 19 | print("* {0}".format(obj_with_link(obj))) 20 | if obj.type == "Directory": 21 | TODO.append(obj) 22 | except gdef.NtStatusException as e: 23 | print("<{0}> -> {1}".format(obj.fullname, e.name)) 24 | 25 | 26 | 27 | parser = argparse.ArgumentParser(prog=__file__) 28 | parser.add_argument('name', nargs='?', default="ls", help='The name of the object to find') 29 | res = parser.parse_args() 30 | 31 | objmanag = windows.system.object_manager 32 | print("Looking for object name containing <{0}>".format(res.name)) 33 | find_name(objmanag.root, res.name) 34 | 35 | 36 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/combase/IScmRequestInfo.txt: -------------------------------------------------------------------------------- 1 | typedef struct IScmRequestInfoVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IScmRequestInfo * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IScmRequestInfo * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IScmRequestInfo * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *SetScmInfo )( 17 | IScmRequestInfo * This, 18 | /* [in] */ PRIV_SCM_INFO *pScmInfo); 19 | 20 | HRESULT ( STDMETHODCALLTYPE *GetScmInfo )( 21 | IScmRequestInfo * This, 22 | /* [out] */ PRIV_SCM_INFO **ppScmInfo); 23 | 24 | HRESULT ( STDMETHODCALLTYPE *SetRemoteRequestInfo )( 25 | IScmRequestInfo * This, 26 | /* [in] */ REMOTE_REQUEST_SCM_INFO *pRemoteReq); 27 | 28 | HRESULT ( STDMETHODCALLTYPE *GetRemoteRequestInfo )( 29 | IScmRequestInfo * This, 30 | /* [out] */ REMOTE_REQUEST_SCM_INFO **ppRemoteReq); 31 | 32 | END_INTERFACE 33 | } IScmRequestInfoVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/combase/ISystemActivator.txt: -------------------------------------------------------------------------------- 1 | typedef struct ISystemActivatorVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | ISystemActivator * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | ISystemActivator * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | ISystemActivator * This); 15 | 16 | HRESULT ( STDMETHODCALLTYPE *GetClassObject )( 17 | ISystemActivator * This, 18 | /* [unique][in] */ IActivationPropertiesIn *pActProperties, 19 | /* [out] */ IActivationPropertiesOut **ppActProperties); 20 | 21 | HRESULT ( STDMETHODCALLTYPE *CreateInstance )( 22 | ISystemActivator * This, 23 | /* [unique][in] */ IUnknown *pUnkOuter, 24 | /* [unique][in] */ IActivationPropertiesIn *pActProperties, 25 | /* [out] */ IActivationPropertiesOut **ppActProperties); 26 | 27 | END_INTERFACE 28 | } ISystemActivatorVtbl; -------------------------------------------------------------------------------- /ctypes_generation/definitions/functions/synchapi.txt: -------------------------------------------------------------------------------- 1 | HANDLE CreateEventA( 2 | LPSECURITY_ATTRIBUTES lpEventAttributes, 3 | BOOL bManualReset, 4 | BOOL bInitialState, 5 | LPCSTR lpName 6 | ); 7 | 8 | HANDLE CreateEventW( 9 | LPSECURITY_ATTRIBUTES lpEventAttributes, 10 | BOOL bManualReset, 11 | BOOL bInitialState, 12 | LPCWSTR lpName 13 | ); 14 | 15 | HANDLE CreateEventExA( 16 | LPSECURITY_ATTRIBUTES lpEventAttributes, 17 | LPCSTR lpName, 18 | DWORD dwFlags, 19 | DWORD dwDesiredAccess 20 | ); 21 | 22 | HANDLE CreateEventExW( 23 | LPSECURITY_ATTRIBUTES lpEventAttributes, 24 | LPCWSTR lpName, 25 | DWORD dwFlags, 26 | DWORD dwDesiredAccess 27 | ); 28 | 29 | HANDLE WINAPI OpenEventA( 30 | __in DWORD dwDesiredAccess, 31 | __in BOOL bInheritHandle, 32 | __in LPCSTR lpName 33 | ); 34 | 35 | HANDLE WINAPI OpenEventW( 36 | __in DWORD dwDesiredAccess, 37 | __in BOOL bInheritHandle, 38 | __in LPCWSTR lpName 39 | ); 40 | 41 | -------------------------------------------------------------------------------- /ctypes_generation/definitions/structures/shell.txt: -------------------------------------------------------------------------------- 1 | typedef struct _SHITEMID { 2 | USHORT cb; 3 | BYTE abID[1]; 4 | } SHITEMID; 5 | 6 | 7 | /* MANUAL TYPEDEF see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773321(v=vs.85).aspx*/ 8 | 9 | typedef struct _ITEMIDLIST { 10 | SHITEMID mkid; 11 | } ITEMIDLIST, *PCIDLIST_ABSOLUTE, *PIDLIST_ABSOLUTE; 12 | 13 | 14 | typedef enum ACTIVATEOPTIONS 15 | { 16 | AO_NONE = 0, 17 | AO_DESIGNMODE = 0x1, 18 | AO_NOERRORUI = 0x2, 19 | AO_NOSPLASHSCREEN = 0x4, 20 | AO_PRELAUNCH = 0x2000000 21 | } ACTIVATEOPTIONS; 22 | 23 | 24 | typedef /* [v1_enum] */ 25 | enum PACKAGE_EXECUTION_STATE 26 | { 27 | PES_UNKNOWN = 0, 28 | PES_RUNNING = 1, 29 | PES_SUSPENDING = 2, 30 | PES_SUSPENDED = 3, 31 | PES_TERMINATED = 4 32 | } PACKAGE_EXECUTION_STATE; 33 | 34 | typedef struct _SHFILEOPSTRUCTA { 35 | HWND hwnd; 36 | UINT wFunc; 37 | PCSTR pFrom; 38 | PCSTR pTo; 39 | FILEOP_FLAGS fFlags; 40 | BOOL fAnyOperationsAborted; 41 | LPVOID hNameMappings; 42 | PCSTR lpszProgressTitle; 43 | } SHFILEOPSTRUCTA, *LPSHFILEOPSTRUCTA; -------------------------------------------------------------------------------- /samples/debug/symbols/symsearch.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | import windows 5 | import windows.debug.symbols as symbols 6 | 7 | 8 | parser = argparse.ArgumentParser(prog=__file__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) 9 | parser.add_argument('pattern') 10 | parser.add_argument('file', help="The PE file to load") 11 | parser.add_argument('--addr', type=lambda x: int(x, 0), default=0, help="The load address of the PE") 12 | parser.add_argument('--tag', type=lambda x: int(x, 0), default=0) 13 | parser.add_argument('--dbghelp', help='The path of DBG help to use (default use env:PFW_DBGHELP_PATH)') 14 | 15 | args = parser.parse_args() 16 | if args.dbghelp: 17 | symbols.set_dbghelp_path(args.dbghelp) 18 | else: 19 | if "PFW_DBGHELP_PATH" not in os.environ: 20 | print("Not dbghelp path given and no environ var 'PFW_DBGHELP_PATH' sample may fail") 21 | 22 | 23 | sh = symbols.VirtualSymbolHandler() 24 | mod = sh.load_file(path=args.file, addr=args.addr) 25 | res = sh.search(args.pattern, mod=mod, tag=args.tag) 26 | print("{0} symbols found:".format(len(res))) 27 | for sym in res: 28 | print(" * {0!r}".format(sym)) 29 | -------------------------------------------------------------------------------- /docs/source/samples_output/object_manager_object_manager.txt: -------------------------------------------------------------------------------- 1 | (cmd) python object_manager\object_manager.py 2 | Object manager is 3 | Root object is 4 | 5 | Listing some of root-subobject: 6 | * PendingRenameMutex: 7 | * ObjectTypes: 8 | * storqosfltport: 9 | * MicrosoftMalwareProtectionRemoteIoPortWD: 10 | 11 | Retrieving <\Rpc Control\lsasspirpc>: 12 | Object is: 13 | * name: 14 | * path: <\Rpc Control> 15 | * fullname: <\Rpc Control\lsasspirpc> 16 | * type: 17 | * target: 18 | 19 | Looking for a SymbolicLink in 20 | Object is: 21 | * name: 22 | * target: <\Device\Harddisk0\Partition0> 23 | -------------------------------------------------------------------------------- /samples/network/demo_ws2_32.py: -------------------------------------------------------------------------------- 1 | import windows.generated_def as gdef 2 | import windows.winproxy 3 | import ctypes 4 | 5 | 6 | WEBSITE = b"perdu.com" 7 | MESSAGE = b"""GET / HTTP/1.1\r\nHost: perdu.com\r\n\r\n""" 8 | 9 | x = gdef.WSADATA() 10 | windows.winproxy.WSAStartup(0x0202, x) 11 | 12 | print("=== WSADATA ===") 13 | windows.utils.sprint(x) 14 | 15 | hints = gdef.ADDRINFOA() 16 | hints.ai_family = gdef.AF_UNSPEC 17 | hints.ai_socktype = gdef.SOCK_STREAM 18 | hints.ai_protocol = gdef.IPPROTO_TCP 19 | 20 | result = gdef.PADDRINFOA() 21 | windows.winproxy.getaddrinfo(WEBSITE, b"80", hints, result); 22 | 23 | print("=== PADDRINFOA ===") 24 | windows.utils.sprint(result) 25 | 26 | 27 | connect_socket = windows.winproxy.socket(result[0].ai_family, result[0].ai_socktype, result[0].ai_protocol) 28 | res = windows.winproxy.connect(connect_socket, result[0].ai_addr, result[0].ai_addrlen) 29 | windows.winproxy.send(connect_socket, MESSAGE) 30 | 31 | buf = ctypes.create_string_buffer(10000) 32 | windows.winproxy.recv(connect_socket, buf) 33 | print("Received:\n{0}".format(buf.value)) 34 | 35 | windows.winproxy.closesocket(connect_socket) 36 | windows.winproxy.WSACleanup() -------------------------------------------------------------------------------- /windows/winproxy/apis/shell32.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import windows.generated_def as gdef 3 | 4 | from ..apiproxy import ApiProxy, NeededParameter 5 | from ..error import fail_on_zero, succeed_on_zero 6 | 7 | class Shell32Proxy(ApiProxy): 8 | APIDLL = "shell32" 9 | default_error_check = staticmethod(fail_on_zero) 10 | 11 | @Shell32Proxy() 12 | def ShellExecuteA(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd): 13 | return ShellExecuteA.ctypes_function(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd) 14 | 15 | @Shell32Proxy() 16 | def ShellExecuteW(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd): 17 | return ShellExecuteW.ctypes_function(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd) 18 | 19 | @Shell32Proxy() 20 | def SHGetPathFromIDListA(pidl, pszPath): 21 | return SHGetPathFromIDListA.ctypes_function(pidl, pszPath) 22 | 23 | @Shell32Proxy() 24 | def SHGetPathFromIDListW(pidl, pszPath): 25 | return SHGetPathFromIDListW.ctypes_function(pidl, pszPath) 26 | 27 | @Shell32Proxy(error_check=succeed_on_zero) 28 | def SHFileOperationA(lpFileOp): 29 | return SHFileOperationA.ctypes_function(lpFileOp) -------------------------------------------------------------------------------- /ctypes_generation/definitions/defines/pipe.txt: -------------------------------------------------------------------------------- 1 | #define PIPE_ACCESS_INBOUND 0x00000001 2 | #define PIPE_ACCESS_OUTBOUND 0x00000002 3 | #define PIPE_ACCESS_DUPLEX 0x00000003 4 | 5 | // 6 | // Define the Named Pipe End flags for GetNamedPipeInfo 7 | // 8 | 9 | #define PIPE_CLIENT_END 0x00000000 10 | #define PIPE_SERVER_END 0x00000001 11 | 12 | // 13 | // Define the dwPipeMode values for CreateNamedPipe 14 | // 15 | 16 | #define PIPE_WAIT 0x00000000 17 | #define PIPE_NOWAIT 0x00000001 18 | #define PIPE_READMODE_BYTE 0x00000000 19 | #define PIPE_READMODE_MESSAGE 0x00000002 20 | #define PIPE_TYPE_BYTE 0x00000000 21 | #define PIPE_TYPE_MESSAGE 0x00000004 22 | #define PIPE_ACCEPT_REMOTE_CLIENTS 0x00000000 23 | #define PIPE_REJECT_REMOTE_CLIENTS 0x00000008 24 | 25 | // 26 | // Define the well known values for CreateNamedPipe nMaxInstances 27 | // 28 | 29 | #define PIPE_UNLIMITED_INSTANCES 255 30 | 31 | 32 | #define NMPWAIT_WAIT_FOREVER 0xffffffff 33 | #define NMPWAIT_NOWAIT 0x00000001 34 | #define NMPWAIT_USE_DEFAULT_WAIT 0x00000000 -------------------------------------------------------------------------------- /ctypes_generation/definitions/com/combase/IEnumSTATSTG.txt: -------------------------------------------------------------------------------- 1 | typedef struct IEnumSTATSTGVtbl 2 | { 3 | BEGIN_INTERFACE 4 | 5 | HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 6 | IEnumSTATSTG * This, 7 | /* [in] */ REFIID riid, 8 | /* [iid_is][out] */ void **ppvObject); 9 | 10 | ULONG ( STDMETHODCALLTYPE *AddRef )( 11 | IEnumSTATSTG * This); 12 | 13 | ULONG ( STDMETHODCALLTYPE *Release )( 14 | IEnumSTATSTG * This); 15 | 16 | /* [local] */ HRESULT ( STDMETHODCALLTYPE *Next )( 17 | IEnumSTATSTG * This, 18 | /* [in] */ ULONG celt, 19 | /* [length_is][size_is][out] */ STATSTG *rgelt, 20 | /* [out] */ ULONG *pceltFetched); 21 | 22 | HRESULT ( STDMETHODCALLTYPE *Skip )( 23 | IEnumSTATSTG * This, 24 | /* [in] */ ULONG celt); 25 | 26 | HRESULT ( STDMETHODCALLTYPE *Reset )( 27 | IEnumSTATSTG * This); 28 | 29 | HRESULT ( STDMETHODCALLTYPE *Clone )( 30 | IEnumSTATSTG * This, 31 | /* [out] */ IEnumSTATSTG **ppenum); 32 | 33 | END_INTERFACE 34 | } IEnumSTATSTGVtbl; -------------------------------------------------------------------------------- /docs/source/samples_output/wmi_wmi_request.txt: -------------------------------------------------------------------------------- 1 | (cmd) python wmi\wmi_request.py 2 | WMI requester is 3 | Selecting * from 'Win32_Process' 4 | They are <329> processes 5 | Looking for ourself via pid 6 | Some info about our process: 7 | * Name -> python.exe 8 | * ProcessId -> 28460 9 | * OSName -> Microsoft Windows 11 Pro|C:\Windows|\Device\Harddisk0\Partition3 10 | * UserModeTime -> 0 11 | * WindowsVersion -> 10.0.22631 12 | * CommandLine -> C:\Users\cleme\AppData\Local\Programs\Python\Python311\python.exe wmi\wmi_request.py 13 |