mirror of
https://github.com/hakril/PythonForWindows
synced 2026-06-08 14:31:45 +00:00
Clean stuff in wintrust + Registry object
This commit is contained in:
@@ -3,7 +3,7 @@ from ctypes import *
|
||||
from ctypes.wintypes import *
|
||||
from .winstructs import *
|
||||
|
||||
functions = ['ExitProcess', 'TerminateProcess', 'GetLastError', 'GetCurrentProcess', 'CreateFileA', 'CreateFileW', 'NtQuerySystemInformation', 'NtQueryInformationProcess', 'NtQueryVirtualMemory', 'NtCreateThreadEx', 'NtQueryInformationThread', 'GetExitCodeThread', 'GetExitCodeProcess', 'VirtualAlloc', 'VirtualAllocEx', 'VirtualFree', 'VirtualFreeEx', 'VirtualProtect', 'VirtualQuery', 'VirtualQueryEx', 'GetModuleFileNameA', 'GetModuleFileNameW', 'CreateThread', 'CreateRemoteThread', 'VirtualProtect', 'CreateProcessA', 'CreateProcessW', 'GetThreadContext', 'NtGetContextThread', 'SetThreadContext', 'OpenThread', 'OpenProcess', 'CloseHandle', 'ReadProcessMemory', 'NtWow64ReadVirtualMemory64', 'WriteProcessMemory', 'CreateToolhelp32Snapshot', 'Thread32First', 'Thread32Next', 'Process32First', 'Process32Next', 'Process32FirstW', 'Process32NextW', 'GetProcAddress', 'LoadLibraryA', 'LoadLibraryW', 'OpenProcessToken', 'LookupPrivilegeValueA', 'LookupPrivilegeValueW', 'AdjustTokenPrivileges', 'FindResourceA', 'FindResourceW', 'SizeofResource', 'LoadResource', 'LockResource', 'GetVersionExA', 'GetVersionExW', 'GetVersion', 'GetCurrentThread', 'GetCurrentThreadId', 'GetCurrentProcessorNumber', 'AllocConsole', 'FreeConsole', 'GetStdHandle', 'SetStdHandle', 'SetThreadAffinityMask', 'WriteFile', 'GetExtendedTcpTable', 'GetExtendedUdpTable', 'SetTcpEntry', 'AddVectoredContinueHandler', 'AddVectoredExceptionHandler', 'TerminateThread', 'ExitThread', 'RemoveVectoredExceptionHandler', 'ResumeThread', 'SuspendThread', 'WaitForSingleObject', 'GetThreadId', 'LoadLibraryExA', 'LoadLibraryExW', 'SymInitialize', 'SymFromName', 'SymLoadModuleEx', 'SymSetOptions', 'SymGetTypeInfo', 'DeviceIoControl', 'GetTokenInformation', 'RegOpenKeyExA', 'RegOpenKeyExW', 'RegGetValueA', 'RegGetValueW', 'RegCloseKey', 'Wow64DisableWow64FsRedirection', 'Wow64RevertWow64FsRedirection', 'Wow64EnableWow64FsRedirection', 'Wow64GetThreadContext', 'SetConsoleCtrlHandler', 'WinVerifyTrust', 'GlobalAlloc', 'GlobalFree', 'GlobalUnlock', 'GlobalLock', 'OpenClipboard', 'EmptyClipboard', 'CloseClipboard', 'SetClipboardData', 'GetClipboardData', 'EnumClipboardFormats', 'GetClipboardFormatNameA', 'GetClipboardFormatNameW']
|
||||
functions = ['ExitProcess', 'TerminateProcess', 'GetLastError', 'GetCurrentProcess', 'CreateFileA', 'CreateFileW', 'NtQuerySystemInformation', 'NtQueryInformationProcess', 'NtQueryVirtualMemory', 'NtCreateThreadEx', 'NtQueryInformationThread', 'GetExitCodeThread', 'GetExitCodeProcess', 'VirtualAlloc', 'VirtualAllocEx', 'VirtualFree', 'VirtualFreeEx', 'VirtualProtect', 'VirtualQuery', 'VirtualQueryEx', 'GetModuleFileNameA', 'GetModuleFileNameW', 'CreateThread', 'CreateRemoteThread', 'VirtualProtect', 'CreateProcessA', 'CreateProcessW', 'GetThreadContext', 'NtGetContextThread', 'SetThreadContext', 'OpenThread', 'OpenProcess', 'CloseHandle', 'ReadProcessMemory', 'NtWow64ReadVirtualMemory64', 'WriteProcessMemory', 'CreateToolhelp32Snapshot', 'Thread32First', 'Thread32Next', 'Process32First', 'Process32Next', 'Process32FirstW', 'Process32NextW', 'GetProcAddress', 'LoadLibraryA', 'LoadLibraryW', 'OpenProcessToken', 'LookupPrivilegeValueA', 'LookupPrivilegeValueW', 'AdjustTokenPrivileges', 'FindResourceA', 'FindResourceW', 'SizeofResource', 'LoadResource', 'LockResource', 'GetVersionExA', 'GetVersionExW', 'GetVersion', 'GetCurrentThread', 'GetCurrentThreadId', 'GetCurrentProcessorNumber', 'AllocConsole', 'FreeConsole', 'GetStdHandle', 'SetStdHandle', 'SetThreadAffinityMask', 'WriteFile', 'GetExtendedTcpTable', 'GetExtendedUdpTable', 'SetTcpEntry', 'AddVectoredContinueHandler', 'AddVectoredExceptionHandler', 'TerminateThread', 'ExitThread', 'RemoveVectoredExceptionHandler', 'ResumeThread', 'SuspendThread', 'WaitForSingleObject', 'GetThreadId', 'LoadLibraryExA', 'LoadLibraryExW', 'SymInitialize', 'SymFromName', 'SymLoadModuleEx', 'SymSetOptions', 'SymGetTypeInfo', 'DeviceIoControl', 'GetTokenInformation', 'RegOpenKeyExA', 'RegOpenKeyExW', 'RegGetValueA', 'RegGetValueW', 'RegCloseKey', 'Wow64DisableWow64FsRedirection', 'Wow64RevertWow64FsRedirection', 'Wow64EnableWow64FsRedirection', 'Wow64GetThreadContext', 'SetConsoleCtrlHandler', 'WinVerifyTrust', 'GlobalAlloc', 'GlobalFree', 'GlobalUnlock', 'GlobalLock', 'OpenClipboard', 'EmptyClipboard', 'CloseClipboard', 'SetClipboardData', 'GetClipboardData', 'EnumClipboardFormats', 'GetClipboardFormatNameA', 'GetClipboardFormatNameW', 'WinVerifyTrust']
|
||||
|
||||
# ExitProcess(uExitCode):
|
||||
ExitProcessPrototype = WINFUNCTYPE(VOID, UINT)
|
||||
@@ -449,3 +449,7 @@ GetClipboardFormatNameAParams = ((1, 'format'), (1, 'lpszFormatName'), (1, 'cchM
|
||||
GetClipboardFormatNameWPrototype = WINFUNCTYPE(INT, UINT, LPCWSTR, INT)
|
||||
GetClipboardFormatNameWParams = ((1, 'format'), (1, 'lpszFormatName'), (1, 'cchMaxCount'))
|
||||
|
||||
# WinVerifyTrust(hWnd, pgActionID, pWVTData):
|
||||
WinVerifyTrustPrototype = WINFUNCTYPE(LONG, HWND, POINTER(GUID), LPVOID)
|
||||
WinVerifyTrustParams = ((1, 'hWnd'), (1, 'pgActionID'), (1, 'pWVTData'))
|
||||
|
||||
|
||||
+29
-12
@@ -14,16 +14,15 @@ class ExpectWindowsError(object):
|
||||
def __exit__(self, etype, e, tb):
|
||||
return (etype == WindowsError and e.winerror == self.errornumber)
|
||||
|
||||
|
||||
KeyValue = collections.namedtuple("KeyValue", ["name", "value", "type"])
|
||||
|
||||
class PyHKey(object):
|
||||
def __init__(self, surkey, name, sam=_winreg.KEY_READ):
|
||||
self.surkey = surkey
|
||||
self._phkey = None
|
||||
self.name = name
|
||||
self.fullname = self.surkey.fullname + "\\" + self.name if self.name else self.surkey.name
|
||||
self.sam = sam
|
||||
self._phkey = None
|
||||
|
||||
def __repr__(self):
|
||||
return '<PyHKey "{0}">'.format(self.fullname)
|
||||
@@ -32,8 +31,10 @@ class PyHKey(object):
|
||||
def phkey(self):
|
||||
if self._phkey is not None:
|
||||
return self._phkey
|
||||
print("OPEN <{0}, {1}>".format(self.surkey.phkey, self.name))
|
||||
self._phkey = _winreg.OpenKeyEx(self.surkey.phkey, self.name, 0, self.sam)
|
||||
try:
|
||||
self._phkey = _winreg.OpenKeyEx(self.surkey.phkey, self.name, 0, self.sam)
|
||||
except WindowsError as e:
|
||||
raise WindowsError("Could not open registry key <{0}>".format(self.fullname))
|
||||
return self._phkey
|
||||
|
||||
@property
|
||||
@@ -54,12 +55,13 @@ class PyHKey(object):
|
||||
|
||||
def open_subkey(self, name):
|
||||
return PyHKey(self, name, self.sam)
|
||||
|
||||
|
||||
def reopen(self, new_sam):
|
||||
return PyHKey(self.surkey, self.name, new_sam)
|
||||
|
||||
|
||||
__getitem__ = open_subkey
|
||||
|
||||
|
||||
class DummyPHKEY(object):
|
||||
def __init__(self, phkey, name):
|
||||
self.phkey = phkey
|
||||
@@ -67,16 +69,31 @@ class DummyPHKEY(object):
|
||||
|
||||
|
||||
HKEY_LOCAL_MACHINE = PyHKey(DummyPHKEY(_winreg.HKEY_LOCAL_MACHINE, "HKEY_LOCAL_MACHINE"), "", _winreg.KEY_READ)
|
||||
|
||||
HKEY_CLASSES_ROOT = PyHKey(DummyPHKEY(_winreg.HKEY_CLASSES_ROOT, "HKEY_CLASSES_ROOT"), "", _winreg.KEY_READ )
|
||||
|
||||
HKEY_CURRENT_USER = PyHKey(DummyPHKEY(_winreg.HKEY_CURRENT_USER, "HKEY_CURRENT_USER"), "", _winreg.KEY_READ)
|
||||
|
||||
HKEY_DYN_DATA = PyHKey(DummyPHKEY(_winreg.HKEY_DYN_DATA, "HKEY_DYN_DATA"), "", _winreg.KEY_READ)
|
||||
|
||||
HKEY_PERFORMANCE_DATA = PyHKey(DummyPHKEY(_winreg.HKEY_PERFORMANCE_DATA, "HKEY_PERFORMANCE_DATA"), "", _winreg.KEY_READ)
|
||||
|
||||
HKEY_USERS = PyHKey(DummyPHKEY(_winreg.HKEY_USERS, "HKEY_USERS"), "", _winreg.KEY_READ )
|
||||
|
||||
|
||||
HKEY_CURRENT_USER[r"Software\Microsoft\Windows\CurrentVersion\Run"].values
|
||||
class Registry(object):
|
||||
|
||||
registry_base_keys = {
|
||||
"HKEY_LOCAL_MACHINE" : HKEY_LOCAL_MACHINE,
|
||||
"HKEY_CLASSES_ROOT" : HKEY_CLASSES_ROOT,
|
||||
"HKEY_CURRENT_USER" : HKEY_CURRENT_USER,
|
||||
"HKEY_DYN_DATA" : HKEY_DYN_DATA,
|
||||
"HKEY_PERFORMANCE_DATA": HKEY_PERFORMANCE_DATA,
|
||||
"HKEY_USERS" : HKEY_USERS
|
||||
}
|
||||
|
||||
def __getitem__(self, name):
|
||||
if name in self.registry_base_keys:
|
||||
return self.registry_base_keys[name]
|
||||
if "\\" not in name:
|
||||
raise ValueError("Unknow registry base key <{0}>".format(name))
|
||||
base_name, subkey = name.split("\\", 1)
|
||||
if base_name not in self.registry_base_keys:
|
||||
raise ValueError("Unknow registry base key <{0}>".format(base_name))
|
||||
return self.registry_base_keys[base_name][subkey]
|
||||
|
||||
|
||||
@@ -54,6 +54,10 @@ class AutoHandle(object):
|
||||
|
||||
class System(object):
|
||||
"""Represent the current windows system python is running on"""
|
||||
|
||||
network = windows.network.Network()
|
||||
registry = windows.registry.Registry()
|
||||
|
||||
@property
|
||||
def processes(self):
|
||||
"""The list of running processes
|
||||
@@ -85,11 +89,6 @@ class System(object):
|
||||
return 64
|
||||
return 32
|
||||
|
||||
@property
|
||||
def network(self):
|
||||
return windows.network.Network()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def enumerate_processes():
|
||||
process_entry = WinProcess()
|
||||
|
||||
+11
-31
@@ -27,6 +27,7 @@ class Kernel32Error(WindowsError):
|
||||
|
||||
|
||||
class IphlpapiError(Kernel32Error):
|
||||
|
||||
def __new__(cls, func_name, code):
|
||||
win_error = ctypes.WinError(code)
|
||||
api_error = super(Kernel32Error, cls).__new__(cls)
|
||||
@@ -112,7 +113,7 @@ class ApiProxy(object):
|
||||
def generate_ctypes_function():
|
||||
try:
|
||||
c_prototyped = prototype((self.func_name, getattr(ctypes.windll, self.APIDLL)), params)
|
||||
except AttributeError:
|
||||
except (AttributeError, WindowsError):
|
||||
raise ExportNotFound(self.func_name, self.APIDLL)
|
||||
c_prototyped.errcheck = self.error_check
|
||||
self._cprototyped = c_prototyped
|
||||
@@ -145,11 +146,6 @@ class Advapi32Proxy(ApiProxy):
|
||||
default_error_check = staticmethod(kernel32_error_check)
|
||||
|
||||
|
||||
class User32Proxy(ApiProxy):
|
||||
APIDLL = "user32"
|
||||
default_error_check = staticmethod(kernel32_error_check)
|
||||
|
||||
|
||||
class IphlpapiProxy(ApiProxy):
|
||||
APIDLL = "iphlpapi"
|
||||
default_error_check = staticmethod(iphlpapi_error_check)
|
||||
@@ -159,6 +155,11 @@ class NtdllProxy(ApiProxy):
|
||||
APIDLL = "ntdll"
|
||||
default_error_check = staticmethod(kernel32_zero_check)
|
||||
|
||||
class WinTrustProxy(ApiProxy):
|
||||
APIDLL = "wintrust"
|
||||
default_error_check = staticmethod(no_error_check)
|
||||
|
||||
|
||||
|
||||
class OptionalExport(object):
|
||||
"""used 'around' a Proxy decorator
|
||||
@@ -203,7 +204,6 @@ class TransparentApiProxy(object):
|
||||
|
||||
TransparentKernel32Proxy = lambda func_name, error_check=kernel32_error_check: TransparentApiProxy("kernel32", func_name, error_check)
|
||||
TransparentAdvapi32Proxy = lambda func_name, error_check=kernel32_error_check: TransparentApiProxy("advapi32", func_name, error_check)
|
||||
TransparentUser32Proxy = lambda func_name, error_check=kernel32_error_check: TransparentApiProxy("user32", func_name, error_check)
|
||||
TransparentIphlpapiProxy = lambda func_name, error_check=iphlpapi_error_check: TransparentApiProxy("iphlpapi", func_name, error_check)
|
||||
|
||||
|
||||
@@ -243,11 +243,6 @@ VirtualQueryEx = TransparentKernel32Proxy("VirtualQueryEx")
|
||||
GetExitCodeThread = TransparentKernel32Proxy("GetExitCodeThread")
|
||||
GetExitCodeProcess = TransparentKernel32Proxy("GetExitCodeProcess")
|
||||
|
||||
GlobalAlloc = TransparentKernel32Proxy("GlobalAlloc")
|
||||
GlobalFree = TransparentKernel32Proxy("GlobalFree")
|
||||
GlobalLock = TransparentKernel32Proxy("GlobalLock")
|
||||
GlobalUnlock = TransparentKernel32Proxy("GlobalUnlock", error_check=no_error_check)
|
||||
|
||||
Wow64DisableWow64FsRedirection = OptionalExport(TransparentKernel32Proxy)("Wow64DisableWow64FsRedirection")
|
||||
Wow64RevertWow64FsRedirection = OptionalExport(TransparentKernel32Proxy)("Wow64RevertWow64FsRedirection")
|
||||
Wow64EnableWow64FsRedirection = OptionalExport(TransparentKernel32Proxy)("Wow64EnableWow64FsRedirection")
|
||||
@@ -594,23 +589,8 @@ def GetExtendedTcpTable(pTcpTable, pdwSize=None, bOrder=True, ulAf=NeededParamet
|
||||
ctypes.sizeof(pTcpTable)
|
||||
return GetExtendedTcpTable.ctypes_function(pTcpTable, pdwSize, bOrder, ulAf, TableClass, Reserved)
|
||||
|
||||
# ## WinTrustProxy PE signature##
|
||||
|
||||
# User32 #
|
||||
|
||||
EmptyClipboard = TransparentUser32Proxy("EmptyClipboard")
|
||||
CloseClipboard = TransparentUser32Proxy("CloseClipboard")
|
||||
SetClipboardData = TransparentUser32Proxy("SetClipboardData")
|
||||
GetClipboardData = TransparentUser32Proxy("GetClipboardData")
|
||||
GetClipboardFormatNameA = TransparentUser32Proxy("GetClipboardFormatNameA")
|
||||
GetClipboardFormatNameW = TransparentUser32Proxy("GetClipboardFormatNameW")
|
||||
|
||||
def check_zero_and_getlasterror(func_name, result, func, args):
|
||||
if not result and GetLastError() != 0:
|
||||
raise Kernel32Error(func_name)
|
||||
return args
|
||||
|
||||
EnumClipboardFormats = TransparentUser32Proxy("EnumClipboardFormats", error_check=check_zero_and_getlasterror)
|
||||
|
||||
@User32Proxy("OpenClipboard")
|
||||
def OpenClipboard(hWndNewOwner=None):
|
||||
return OpenClipboard.ctypes_function(hWndNewOwner)
|
||||
@WinTrustProxy('WinVerifyTrust')
|
||||
def WinVerifyTrust(hwnd, pgActionID, pWVTData):
|
||||
return WinVerifyTrust.ctypes_function(hwnd, pgActionID, pWVTData)
|
||||
+4
-7
@@ -2,6 +2,7 @@ import ctypes
|
||||
import struct
|
||||
import windows
|
||||
from windows.generated_def.winstructs import *
|
||||
from windows.winproxy import WinVerifyTrust
|
||||
|
||||
IID_PACK = "<I", "<H", "<H", "<B", "<B", "<B", "<B", "<B", "<B", "<B", "<B"
|
||||
def get_IID_from_raw(raw):
|
||||
@@ -12,7 +13,9 @@ def get_IID_from_raw(raw):
|
||||
WINTRUST_ACTION_GENERIC_VERIFY_V2_RAW = (0xaac56b, 0xcd44, 0x11d0,
|
||||
0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee)
|
||||
|
||||
WINTRUST_ACTION_GENERIC_VERIFY_V2 = get_IID_from_raw(WINTRUST_ACTION_GENERIC_VERIFY_V2_RAW)
|
||||
WINTRUST_ACTION_GENERIC_VERIFY_V2_STR = get_IID_from_raw(WINTRUST_ACTION_GENERIC_VERIFY_V2_RAW)
|
||||
# Otherwise there is a problem with `Data4` of `type c_char_Array_8` containing 0x00 (0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee)
|
||||
WINTRUST_ACTION_GENERIC_VERIFY_V2 = GUID.from_address(ctypes.addressof(WINTRUST_ACTION_GENERIC_VERIFY_V2_STR))
|
||||
|
||||
WTD_UI_ALL = 1
|
||||
WTD_UI_NONE = 2
|
||||
@@ -45,7 +48,6 @@ def check_signature(filename):
|
||||
WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2
|
||||
|
||||
win_trust_data = WINTRUST_DATA()
|
||||
|
||||
win_trust_data.cbStruct = ctypes.sizeof(WINTRUST_DATA)
|
||||
win_trust_data.pPolicyCallbackData = None
|
||||
win_trust_data.pSIPClientData = None
|
||||
@@ -58,12 +60,7 @@ def check_signature(filename):
|
||||
win_trust_data.dwUIContext = 0
|
||||
win_trust_data.tmp_union.pFile = ctypes.pointer(file_data)
|
||||
|
||||
WinVerifyTrust = ctypes.WinDLL("wintrust").WinVerifyTrust
|
||||
|
||||
x = WinVerifyTrust(None, ctypes.byref(WVTPolicyGUID), ctypes.byref(win_trust_data))
|
||||
|
||||
win_trust_data.dwStateAction = WTD_STATEACTION_CLOSE
|
||||
|
||||
WinVerifyTrust(None, ctypes.byref(WVTPolicyGUID), ctypes.byref(win_trust_data))
|
||||
|
||||
return x & 0xffffffff
|
||||
Reference in New Issue
Block a user