From 9c80593a9756f8a59983b4101c16bc0cccaa3ff6 Mon Sep 17 00:00:00 2001 From: Clement Rouault Date: Wed, 11 Mar 2015 15:51:00 +0100 Subject: [PATCH] Committing all the stuff --- __init__.py | 6 + generated_def/__init__.py | 0 generated_def/windef.py | 240 +++++++++++++++ generated_def/winfuncs.py | 175 +++++++++++ generated_def/winstructs.py | 521 +++++++++++++++++++++++++++++++++ hooks.py | 92 ++++++ injection.py | 92 ++++++ k32testing.py | 262 +++++++++++++++++ native_exec/__init__.py | 2 + native_exec/native_function.py | 200 +++++++++++++ native_exec/simple_x86.py | 227 ++++++++++++++ pe_parse.py | 347 ++++++++++++++++++++++ remote_callback.py | 34 +++ utils.py | 85 ++++++ winobject.py | 148 ++++++++++ 15 files changed, 2431 insertions(+) create mode 100644 __init__.py create mode 100644 generated_def/__init__.py create mode 100644 generated_def/windef.py create mode 100644 generated_def/winfuncs.py create mode 100644 generated_def/winstructs.py create mode 100644 hooks.py create mode 100644 injection.py create mode 100644 k32testing.py create mode 100644 native_exec/__init__.py create mode 100644 native_exec/native_function.py create mode 100644 native_exec/simple_x86.py create mode 100644 pe_parse.py create mode 100644 remote_callback.py create mode 100644 utils.py create mode 100644 winobject.py diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..d7aed84 --- /dev/null +++ b/__init__.py @@ -0,0 +1,6 @@ +from utils import * + +system = System() +current_process = CurrentProcess() + +__all__ = ["system", "VirtualProtected", 'current_process'] \ No newline at end of file diff --git a/generated_def/__init__.py b/generated_def/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/generated_def/windef.py b/generated_def/windef.py new file mode 100644 index 0000000..a47c78a --- /dev/null +++ b/generated_def/windef.py @@ -0,0 +1,240 @@ +#Generated file + +class Flag(long): + def __new__(cls, name, value): + return super(Flag, cls).__new__(cls, value) + + def __init__(self, name, value): + self.name = name + + def __repr__(self): + return "{0}({1})".format(self.name, hex(self)) + +NULL = Flag("NULL", 0) +MAX_PATH = Flag("MAX_PATH", 260) +ANYSIZE_ARRAY = Flag("ANYSIZE_ARRAY", 1) +WARMING_NOT_SAME_FLAG_FOR_WINXP = Flag("WARMING_NOT_SAME_FLAG_FOR_WINXP", 0) +PROCESS_ALL_ACCESS = Flag("PROCESS_ALL_ACCESS", 0x001F0FFF) +THREAD_ALL_ACCESS = Flag("THREAD_ALL_ACCESS", 0x001F03FF) +STARTF_USESHOWWINDOW = Flag("STARTF_USESHOWWINDOW", 0x00000001) +STARTF_USESIZE = Flag("STARTF_USESIZE", 0x00000002) +STARTF_USEPOSITION = Flag("STARTF_USEPOSITION", 0x00000004) +STARTF_USECOUNTCHARS = Flag("STARTF_USECOUNTCHARS", 0x00000008) +STARTF_USEFILLATTRIBUTE = Flag("STARTF_USEFILLATTRIBUTE", 0x00000010) +STARTF_RUNFULLSCREEN = Flag("STARTF_RUNFULLSCREEN", 0x00000020) +STARTF_FORCEONFEEDBACK = Flag("STARTF_FORCEONFEEDBACK", 0x00000040) +STARTF_FORCEOFFFEEDBACK = Flag("STARTF_FORCEOFFFEEDBACK", 0x00000080) +STARTF_USESTDHANDLES = Flag("STARTF_USESTDHANDLES", 0x00000100) +SW_HIDE = Flag("SW_HIDE", 0) +SW_SHOWNORMAL = Flag("SW_SHOWNORMAL", 1) +SW_NORMAL = Flag("SW_NORMAL", 1) +SW_SHOWMINIMIZED = Flag("SW_SHOWMINIMIZED", 2) +SW_SHOWMAXIMIZED = Flag("SW_SHOWMAXIMIZED", 3) +SW_MAXIMIZE = Flag("SW_MAXIMIZE", 3) +SW_SHOWNOACTIVATE = Flag("SW_SHOWNOACTIVATE", 4) +SW_SHOW = Flag("SW_SHOW", 5) +SW_MINIMIZE = Flag("SW_MINIMIZE", 6) +SW_SHOWMINNOACTIVE = Flag("SW_SHOWMINNOACTIVE", 7) +SW_SHOWNA = Flag("SW_SHOWNA", 8) +SW_RESTORE = Flag("SW_RESTORE", 9) +SW_SHOWDEFAULT = Flag("SW_SHOWDEFAULT", 10) +SW_FORCEMINIMIZE = Flag("SW_FORCEMINIMIZE", 11) +SW_MAX = Flag("SW_MAX", 11) +DEBUG_PROCESS = Flag("DEBUG_PROCESS", 0x00000001) +DEBUG_ONLY_THIS_PROCESS = Flag("DEBUG_ONLY_THIS_PROCESS", 0x00000002) +CREATE_SUSPENDED = Flag("CREATE_SUSPENDED", 0x00000004) +DETACHED_PROCESS = Flag("DETACHED_PROCESS", 0x00000008) +CREATE_NEW_CONSOLE = Flag("CREATE_NEW_CONSOLE", 0x00000010) +NORMAL_PRIORITY_CLASS = Flag("NORMAL_PRIORITY_CLASS", 0x00000020) +IDLE_PRIORITY_CLASS = Flag("IDLE_PRIORITY_CLASS", 0x00000040) +HIGH_PRIORITY_CLASS = Flag("HIGH_PRIORITY_CLASS", 0x00000080) +REALTIME_PRIORITY_CLASS = Flag("REALTIME_PRIORITY_CLASS", 0x00000100) +CREATE_NEW_PROCESS_GROUP = Flag("CREATE_NEW_PROCESS_GROUP", 0x00000200) +CREATE_UNICODE_ENVIRONMENT = Flag("CREATE_UNICODE_ENVIRONMENT", 0x00000400) +CREATE_SEPARATE_WOW_VDM = Flag("CREATE_SEPARATE_WOW_VDM", 0x00000800) +CREATE_SHARED_WOW_VDM = Flag("CREATE_SHARED_WOW_VDM", 0x00001000) +CREATE_FORCEDOS = Flag("CREATE_FORCEDOS", 0x00002000) +BELOW_NORMAL_PRIORITY_CLASS = Flag("BELOW_NORMAL_PRIORITY_CLASS", 0x00004000) +ABOVE_NORMAL_PRIORITY_CLASS = Flag("ABOVE_NORMAL_PRIORITY_CLASS", 0x00008000) +INHERIT_PARENT_AFFINITY = Flag("INHERIT_PARENT_AFFINITY", 0x00010000) +INHERIT_CALLER_PRIORITY = Flag("INHERIT_CALLER_PRIORITY", 0x00020000) +CREATE_PROTECTED_PROCESS = Flag("CREATE_PROTECTED_PROCESS", 0x00040000) +EXTENDED_STARTUPINFO_PRESENT = Flag("EXTENDED_STARTUPINFO_PRESENT", 0x00080000) +PROCESS_MODE_BACKGROUND_BEGIN = Flag("PROCESS_MODE_BACKGROUND_BEGIN", 0x00100000) +PROCESS_MODE_BACKGROUND_END = Flag("PROCESS_MODE_BACKGROUND_END", 0x00200000) +CREATE_BREAKAWAY_FROM_JOB = Flag("CREATE_BREAKAWAY_FROM_JOB", 0x01000000) +CREATE_PRESERVE_CODE_AUTHZ_LEVEL = Flag("CREATE_PRESERVE_CODE_AUTHZ_LEVEL", 0x02000000) +CREATE_DEFAULT_ERROR_MODE = Flag("CREATE_DEFAULT_ERROR_MODE", 0x04000000) +CREATE_NO_WINDOW = Flag("CREATE_NO_WINDOW", 0x08000000) +PROFILE_USER = Flag("PROFILE_USER", 0x10000000) +PROFILE_KERNEL = Flag("PROFILE_KERNEL", 0x20000000) +PROFILE_SERVER = Flag("PROFILE_SERVER", 0x40000000) +CREATE_IGNORE_SYSTEM_DEFAULT = Flag("CREATE_IGNORE_SYSTEM_DEFAULT", 0x80000000) +STATUS_WAIT_0 = Flag("STATUS_WAIT_0", ( 0x00000000L )) +STATUS_ABANDONED_WAIT_0 = Flag("STATUS_ABANDONED_WAIT_0", ( 0x00000080L )) +STATUS_USER_APC = Flag("STATUS_USER_APC", ( 0x000000C0L )) +STATUS_TIMEOUT = Flag("STATUS_TIMEOUT", ( 0x00000102L )) +STATUS_PENDING = Flag("STATUS_PENDING", ( 0x00000103L )) +DBG_EXCEPTION_HANDLED = Flag("DBG_EXCEPTION_HANDLED", ( 0x00010001L )) +DBG_CONTINUE = Flag("DBG_CONTINUE", ( 0x00010002L )) +STATUS_SEGMENT_NOTIFICATION = Flag("STATUS_SEGMENT_NOTIFICATION", ( 0x40000005L )) +DBG_TERMINATE_THREAD = Flag("DBG_TERMINATE_THREAD", ( 0x40010003L )) +DBG_TERMINATE_PROCESS = Flag("DBG_TERMINATE_PROCESS", ( 0x40010004L )) +DBG_CONTROL_C = Flag("DBG_CONTROL_C", ( 0x40010005L )) +DBG_PRINTEXCEPTION_C = Flag("DBG_PRINTEXCEPTION_C", ( 0x40010006L )) +DBG_RIPEXCEPTION = Flag("DBG_RIPEXCEPTION", ( 0x40010007L )) +DBG_CONTROL_BREAK = Flag("DBG_CONTROL_BREAK", ( 0x40010008L )) +DBG_COMMAND_EXCEPTION = Flag("DBG_COMMAND_EXCEPTION", ( 0x40010009L )) +STATUS_GUARD_PAGE_VIOLATION = Flag("STATUS_GUARD_PAGE_VIOLATION", ( 0x80000001L )) +STATUS_DATATYPE_MISALIGNMENT = Flag("STATUS_DATATYPE_MISALIGNMENT", ( 0x80000002L )) +STATUS_BREAKPOINT = Flag("STATUS_BREAKPOINT", ( 0x80000003L )) +STATUS_SINGLE_STEP = Flag("STATUS_SINGLE_STEP", ( 0x80000004L )) +STATUS_LONGJUMP = Flag("STATUS_LONGJUMP", ( 0x80000026L )) +STATUS_UNWIND_CONSOLIDATE = Flag("STATUS_UNWIND_CONSOLIDATE", ( 0x80000029L )) +DBG_EXCEPTION_NOT_HANDLED = Flag("DBG_EXCEPTION_NOT_HANDLED", ( 0x80010001L )) +STATUS_ACCESS_VIOLATION = Flag("STATUS_ACCESS_VIOLATION", ( 0xC0000005L )) +STATUS_IN_PAGE_ERROR = Flag("STATUS_IN_PAGE_ERROR", ( 0xC0000006L )) +STATUS_INVALID_HANDLE = Flag("STATUS_INVALID_HANDLE", ( 0xC0000008L )) +STATUS_INVALID_PARAMETER = Flag("STATUS_INVALID_PARAMETER", ( 0xC000000DL )) +STATUS_NO_MEMORY = Flag("STATUS_NO_MEMORY", ( 0xC0000017L )) +STATUS_ILLEGAL_INSTRUCTION = Flag("STATUS_ILLEGAL_INSTRUCTION", ( 0xC000001DL )) +STATUS_NONCONTINUABLE_EXCEPTION = Flag("STATUS_NONCONTINUABLE_EXCEPTION", ( 0xC0000025L )) +STATUS_INVALID_DISPOSITION = Flag("STATUS_INVALID_DISPOSITION", ( 0xC0000026L )) +STATUS_ARRAY_BOUNDS_EXCEEDED = Flag("STATUS_ARRAY_BOUNDS_EXCEEDED", ( 0xC000008CL )) +STATUS_FLOAT_DENORMAL_OPERAND = Flag("STATUS_FLOAT_DENORMAL_OPERAND", ( 0xC000008DL )) +STATUS_FLOAT_DIVIDE_BY_ZERO = Flag("STATUS_FLOAT_DIVIDE_BY_ZERO", ( 0xC000008EL )) +STATUS_FLOAT_INEXACT_RESULT = Flag("STATUS_FLOAT_INEXACT_RESULT", ( 0xC000008FL )) +STATUS_FLOAT_INVALID_OPERATION = Flag("STATUS_FLOAT_INVALID_OPERATION", ( 0xC0000090L )) +STATUS_FLOAT_OVERFLOW = Flag("STATUS_FLOAT_OVERFLOW", ( 0xC0000091L )) +STATUS_FLOAT_STACK_CHECK = Flag("STATUS_FLOAT_STACK_CHECK", ( 0xC0000092L )) +STATUS_FLOAT_UNDERFLOW = Flag("STATUS_FLOAT_UNDERFLOW", ( 0xC0000093L )) +STATUS_INTEGER_DIVIDE_BY_ZERO = Flag("STATUS_INTEGER_DIVIDE_BY_ZERO", ( 0xC0000094L )) +STATUS_INTEGER_OVERFLOW = Flag("STATUS_INTEGER_OVERFLOW", ( 0xC0000095L )) +STATUS_PRIVILEGED_INSTRUCTION = Flag("STATUS_PRIVILEGED_INSTRUCTION", ( 0xC0000096L )) +STATUS_STACK_OVERFLOW = Flag("STATUS_STACK_OVERFLOW", ( 0xC00000FDL )) +STATUS_DLL_NOT_FOUND = Flag("STATUS_DLL_NOT_FOUND", ( 0xC0000135L )) +STATUS_ORDINAL_NOT_FOUND = Flag("STATUS_ORDINAL_NOT_FOUND", ( 0xC0000138L )) +STATUS_ENTRYPOINT_NOT_FOUND = Flag("STATUS_ENTRYPOINT_NOT_FOUND", ( 0xC0000139L )) +STATUS_CONTROL_C_EXIT = Flag("STATUS_CONTROL_C_EXIT", ( 0xC000013AL )) +STATUS_DLL_INIT_FAILED = Flag("STATUS_DLL_INIT_FAILED", ( 0xC0000142L )) +STATUS_FLOAT_MULTIPLE_FAULTS = Flag("STATUS_FLOAT_MULTIPLE_FAULTS", ( 0xC00002B4L )) +STATUS_FLOAT_MULTIPLE_TRAPS = Flag("STATUS_FLOAT_MULTIPLE_TRAPS", ( 0xC00002B5L )) +STATUS_REG_NAT_CONSUMPTION = Flag("STATUS_REG_NAT_CONSUMPTION", ( 0xC00002C9L )) +STATUS_STACK_BUFFER_OVERRUN = Flag("STATUS_STACK_BUFFER_OVERRUN", ( 0xC0000409L )) +STATUS_INVALID_CRUNTIME_PARAMETER = Flag("STATUS_INVALID_CRUNTIME_PARAMETER", ( 0xC0000417L )) +STATUS_ASSERTION_FAILURE = Flag("STATUS_ASSERTION_FAILURE", ( 0xC0000420L )) +STATUS_POSSIBLE_DEADLOCK = Flag("STATUS_POSSIBLE_DEADLOCK", ( 0xC0000194 )) +WAIT_IO_COMPLETION = Flag("WAIT_IO_COMPLETION", STATUS_USER_APC) +STILL_ACTIVE = Flag("STILL_ACTIVE", STATUS_PENDING) +EXCEPTION_ACCESS_VIOLATION = Flag("EXCEPTION_ACCESS_VIOLATION", STATUS_ACCESS_VIOLATION) +EXCEPTION_DATATYPE_MISALIGNMENT = Flag("EXCEPTION_DATATYPE_MISALIGNMENT", STATUS_DATATYPE_MISALIGNMENT) +EXCEPTION_BREAKPOINT = Flag("EXCEPTION_BREAKPOINT", STATUS_BREAKPOINT) +EXCEPTION_SINGLE_STEP = Flag("EXCEPTION_SINGLE_STEP", STATUS_SINGLE_STEP) +EXCEPTION_ARRAY_BOUNDS_EXCEEDED = Flag("EXCEPTION_ARRAY_BOUNDS_EXCEEDED", STATUS_ARRAY_BOUNDS_EXCEEDED) +EXCEPTION_FLT_DENORMAL_OPERAND = Flag("EXCEPTION_FLT_DENORMAL_OPERAND", STATUS_FLOAT_DENORMAL_OPERAND) +EXCEPTION_FLT_DIVIDE_BY_ZERO = Flag("EXCEPTION_FLT_DIVIDE_BY_ZERO", STATUS_FLOAT_DIVIDE_BY_ZERO) +EXCEPTION_FLT_INEXACT_RESULT = Flag("EXCEPTION_FLT_INEXACT_RESULT", STATUS_FLOAT_INEXACT_RESULT) +EXCEPTION_FLT_INVALID_OPERATION = Flag("EXCEPTION_FLT_INVALID_OPERATION", STATUS_FLOAT_INVALID_OPERATION) +EXCEPTION_FLT_OVERFLOW = Flag("EXCEPTION_FLT_OVERFLOW", STATUS_FLOAT_OVERFLOW) +EXCEPTION_FLT_STACK_CHECK = Flag("EXCEPTION_FLT_STACK_CHECK", STATUS_FLOAT_STACK_CHECK) +EXCEPTION_FLT_UNDERFLOW = Flag("EXCEPTION_FLT_UNDERFLOW", STATUS_FLOAT_UNDERFLOW) +EXCEPTION_INT_DIVIDE_BY_ZERO = Flag("EXCEPTION_INT_DIVIDE_BY_ZERO", STATUS_INTEGER_DIVIDE_BY_ZERO) +EXCEPTION_INT_OVERFLOW = Flag("EXCEPTION_INT_OVERFLOW", STATUS_INTEGER_OVERFLOW) +EXCEPTION_PRIV_INSTRUCTION = Flag("EXCEPTION_PRIV_INSTRUCTION", STATUS_PRIVILEGED_INSTRUCTION) +EXCEPTION_IN_PAGE_ERROR = Flag("EXCEPTION_IN_PAGE_ERROR", STATUS_IN_PAGE_ERROR) +EXCEPTION_ILLEGAL_INSTRUCTION = Flag("EXCEPTION_ILLEGAL_INSTRUCTION", STATUS_ILLEGAL_INSTRUCTION) +EXCEPTION_NONCONTINUABLE_EXCEPTION = Flag("EXCEPTION_NONCONTINUABLE_EXCEPTION", STATUS_NONCONTINUABLE_EXCEPTION) +EXCEPTION_STACK_OVERFLOW = Flag("EXCEPTION_STACK_OVERFLOW", STATUS_STACK_OVERFLOW) +EXCEPTION_INVALID_DISPOSITION = Flag("EXCEPTION_INVALID_DISPOSITION", STATUS_INVALID_DISPOSITION) +EXCEPTION_GUARD_PAGE = Flag("EXCEPTION_GUARD_PAGE", STATUS_GUARD_PAGE_VIOLATION) +EXCEPTION_INVALID_HANDLE = Flag("EXCEPTION_INVALID_HANDLE", STATUS_INVALID_HANDLE) +EXCEPTION_POSSIBLE_DEADLOCK = Flag("EXCEPTION_POSSIBLE_DEADLOCK", STATUS_POSSIBLE_DEADLOCK) +CONTROL_C_EXIT = Flag("CONTROL_C_EXIT", STATUS_CONTROL_C_EXIT) +EXCEPTION_DEBUG_EVENT = Flag("EXCEPTION_DEBUG_EVENT", 1) +CREATE_THREAD_DEBUG_EVENT = Flag("CREATE_THREAD_DEBUG_EVENT", 2) +CREATE_PROCESS_DEBUG_EVENT = Flag("CREATE_PROCESS_DEBUG_EVENT", 3) +EXIT_THREAD_DEBUG_EVENT = Flag("EXIT_THREAD_DEBUG_EVENT", 4) +EXIT_PROCESS_DEBUG_EVENT = Flag("EXIT_PROCESS_DEBUG_EVENT", 5) +LOAD_DLL_DEBUG_EVENT = Flag("LOAD_DLL_DEBUG_EVENT", 6) +UNLOAD_DLL_DEBUG_EVENT = Flag("UNLOAD_DLL_DEBUG_EVENT", 7) +OUTPUT_DEBUG_STRING_EVENT = Flag("OUTPUT_DEBUG_STRING_EVENT", 8) +RIP_EVENT = Flag("RIP_EVENT", 9) +TH32CS_SNAPHEAPLIST = Flag("TH32CS_SNAPHEAPLIST", 0x00000001) +TH32CS_SNAPPROCESS = Flag("TH32CS_SNAPPROCESS", 0x00000002) +TH32CS_SNAPTHREAD = Flag("TH32CS_SNAPTHREAD", 0x00000004) +TH32CS_SNAPMODULE = Flag("TH32CS_SNAPMODULE", 0x00000008) +TH32CS_SNAPMODULE32 = Flag("TH32CS_SNAPMODULE32", 0x00000010) +TH32CS_SNAPALL = Flag("TH32CS_SNAPALL", ( TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE )) +TH32CS_INHERIT = Flag("TH32CS_INHERIT", 0x80000000) +CONTEXT_I386 = Flag("CONTEXT_I386", 0x00010000) +CONTEXT_CONTROL = Flag("CONTEXT_CONTROL", 0x00000001L) +CONTEXT_INTEGER = Flag("CONTEXT_INTEGER", 0x00000002L) +CONTEXT_SEGMENTS = Flag("CONTEXT_SEGMENTS", 0x00000004L) +CONTEXT_FLOATING_POINT = Flag("CONTEXT_FLOATING_POINT", 0x00000008L) +CONTEXT_DEBUG_REGISTERS = Flag("CONTEXT_DEBUG_REGISTERS", 0x00000010L) +CONTEXT_EXTENDED_REGISTERS = Flag("CONTEXT_EXTENDED_REGISTERS", 0x00000020L) +CONTEXT_FULL = Flag("CONTEXT_FULL", ( CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS )) +CONTEXT_ALL = Flag("CONTEXT_ALL", ( CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS )) +CONTEXT_FULL = Flag("CONTEXT_FULL", CONTEXT_I386 | CONTEXT_FULL) +CONTEXT_ALL = Flag("CONTEXT_ALL", CONTEXT_I386 | CONTEXT_ALL) +PAGE_NOACCESS = Flag("PAGE_NOACCESS", 0x01) +PAGE_READONLY = Flag("PAGE_READONLY", 0x02) +PAGE_READWRITE = Flag("PAGE_READWRITE", 0x04) +PAGE_WRITECOPY = Flag("PAGE_WRITECOPY", 0x08) +PAGE_EXECUTE = Flag("PAGE_EXECUTE", 0x10) +PAGE_EXECUTE_READ = Flag("PAGE_EXECUTE_READ", 0x20) +PAGE_EXECUTE_READWRITE = Flag("PAGE_EXECUTE_READWRITE", 0x40) +PAGE_EXECUTE_WRITECOPY = Flag("PAGE_EXECUTE_WRITECOPY", 0x80) +PAGE_GUARD = Flag("PAGE_GUARD", 0x100) +PAGE_NOCACHE = Flag("PAGE_NOCACHE", 0x200) +PAGE_WRITECOMBINE = Flag("PAGE_WRITECOMBINE", 0x400) +MEM_COMMIT = Flag("MEM_COMMIT", 0x1000) +MEM_RESERVE = Flag("MEM_RESERVE", 0x2000) +MEM_DECOMMIT = Flag("MEM_DECOMMIT", 0x4000) +MEM_RELEASE = Flag("MEM_RELEASE", 0x8000) +MEM_FREE = Flag("MEM_FREE", 0x10000) +MEM_PRIVATE = Flag("MEM_PRIVATE", 0x20000) +MEM_MAPPED = Flag("MEM_MAPPED", 0x40000) +MEM_RESET = Flag("MEM_RESET", 0x80000) +MEM_TOP_DOWN = Flag("MEM_TOP_DOWN", 0x100000) +MEM_WRITE_WATCH = Flag("MEM_WRITE_WATCH", 0x200000) +MEM_PHYSICAL = Flag("MEM_PHYSICAL", 0x400000) +MEM_ROTATE = Flag("MEM_ROTATE", 0x800000) +MEM_LARGE_PAGES = Flag("MEM_LARGE_PAGES", 0x20000000) +MEM_4MB_PAGES = Flag("MEM_4MB_PAGES", 0x80000000) +SEC_FILE = Flag("SEC_FILE", 0x800000) +SEC_IMAGE = Flag("SEC_IMAGE", 0x1000000) +SEC_PROTECTED_IMAGE = Flag("SEC_PROTECTED_IMAGE", 0x2000000) +SEC_RESERVE = Flag("SEC_RESERVE", 0x4000000) +SEC_COMMIT = Flag("SEC_COMMIT", 0x8000000) +SEC_NOCACHE = Flag("SEC_NOCACHE", 0x10000000) +SEC_WRITECOMBINE = Flag("SEC_WRITECOMBINE", 0x40000000) +SEC_LARGE_PAGES = Flag("SEC_LARGE_PAGES", 0x80000000) +MEM_IMAGE = Flag("MEM_IMAGE", SEC_IMAGE) +WRITE_WATCH_FLAG_RESET = Flag("WRITE_WATCH_FLAG_RESET", 0x01) +DELETE = Flag("DELETE", ( 0x00010000L )) +READ_CONTROL = Flag("READ_CONTROL", ( 0x00020000L )) +WRITE_DAC = Flag("WRITE_DAC", ( 0x00040000L )) +WRITE_OWNER = Flag("WRITE_OWNER", ( 0x00080000L )) +SYNCHRONIZE = Flag("SYNCHRONIZE", ( 0x00100000L )) +STANDARD_RIGHTS_REQUIRED = Flag("STANDARD_RIGHTS_REQUIRED", ( 0x000F0000L )) +STANDARD_RIGHTS_READ = Flag("STANDARD_RIGHTS_READ", ( READ_CONTROL )) +STANDARD_RIGHTS_WRITE = Flag("STANDARD_RIGHTS_WRITE", ( READ_CONTROL )) +STANDARD_RIGHTS_EXECUTE = Flag("STANDARD_RIGHTS_EXECUTE", ( READ_CONTROL )) +STANDARD_RIGHTS_ALL = Flag("STANDARD_RIGHTS_ALL", ( 0x001F0000L )) +SPECIFIC_RIGHTS_ALL = Flag("SPECIFIC_RIGHTS_ALL", ( 0x0000FFFFL )) +TOKEN_ASSIGN_PRIMARY = Flag("TOKEN_ASSIGN_PRIMARY", ( 0x0001 )) +TOKEN_DUPLICATE = Flag("TOKEN_DUPLICATE", ( 0x0002 )) +TOKEN_IMPERSONATE = Flag("TOKEN_IMPERSONATE", ( 0x0004 )) +TOKEN_QUERY = Flag("TOKEN_QUERY", ( 0x0008 )) +TOKEN_QUERY_SOURCE = Flag("TOKEN_QUERY_SOURCE", ( 0x0010 )) +TOKEN_ADJUST_PRIVILEGES = Flag("TOKEN_ADJUST_PRIVILEGES", ( 0x0020 )) +TOKEN_ADJUST_GROUPS = Flag("TOKEN_ADJUST_GROUPS", ( 0x0040 )) +TOKEN_ADJUST_DEFAULT = Flag("TOKEN_ADJUST_DEFAULT", ( 0x0080 )) +TOKEN_ADJUST_SESSIONID = Flag("TOKEN_ADJUST_SESSIONID", ( 0x0100 )) +TOKEN_ALL_ACCESS_P = Flag("TOKEN_ALL_ACCESS_P", ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT )) +TOKEN_ALL_ACCESS = Flag("TOKEN_ALL_ACCESS", ( TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID )) +SE_PRIVILEGE_ENABLED_BY_DEFAULT = Flag("SE_PRIVILEGE_ENABLED_BY_DEFAULT", ( 0x00000001L )) +SE_PRIVILEGE_ENABLED = Flag("SE_PRIVILEGE_ENABLED", ( 0x00000002L )) +SE_PRIVILEGE_REMOVED = Flag("SE_PRIVILEGE_REMOVED", ( 0X00000004L )) +SE_PRIVILEGE_USED_FOR_ACCESS = Flag("SE_PRIVILEGE_USED_FOR_ACCESS", ( 0x80000000L )) \ No newline at end of file diff --git a/generated_def/winfuncs.py b/generated_def/winfuncs.py new file mode 100644 index 0000000..7292c5d --- /dev/null +++ b/generated_def/winfuncs.py @@ -0,0 +1,175 @@ +#Generated file +from ctypes import * +from ctypes.wintypes import * +from winstructs import * + +functions = ['ExitProcess', 'GetLastError', 'GetCurrentProcess', 'CreateFileA', 'CreateFileW', 'NtQuerySystemInformation', 'VirtualAlloc', 'VirtualAllocEx', 'VirtualProtect', 'VirtualQuery', 'GetModuleFileNameA', 'GetModuleFileNameW', 'CreateRemoteThread', 'VirtualProtect', 'CreateProcessA', 'CreateProcessW', 'GetThreadContext', 'SetThreadContext', 'OpenThread', 'OpenProcess', 'CloseHandle', 'ReadProcessMemory', 'WriteProcessMemory', 'CreateToolhelp32Snapshot', 'Thread32First', 'Thread32Next', 'Process32First', 'Process32Next', 'Process32FirstW', 'Process32NextW', 'GetProcAddress', 'LoadLibraryA', 'LoadLibraryW', 'OpenProcessToken', 'LookupPrivilegeValueA', 'LookupPrivilegeValueW', 'AdjustTokenPrivileges', 'FindResourceA', 'FindResourceW', 'SizeofResource', 'LoadResource', 'LockResource'] + +# ExitProcess(uExitCode): +ExitProcessPrototype = WINFUNCTYPE(VOID, UINT) +ExitProcessParams = ((1, 'uExitCode'),) + +# GetLastError(): +GetLastErrorPrototype = WINFUNCTYPE(DWORD) +GetLastErrorParams = () + +# GetCurrentProcess(): +GetCurrentProcessPrototype = WINFUNCTYPE(HANDLE) +GetCurrentProcessParams = () + +# CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile): +CreateFileAPrototype = WINFUNCTYPE(HANDLE, LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE) +CreateFileAParams = ((1, 'lpFileName'), (1, 'dwDesiredAccess'), (1, 'dwShareMode'), (1, 'lpSecurityAttributes'), (1, 'dwCreationDisposition'), (1, 'dwFlagsAndAttributes'), (1, 'hTemplateFile')) + +# CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile): +CreateFileWPrototype = WINFUNCTYPE(HANDLE, LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE) +CreateFileWParams = ((1, 'lpFileName'), (1, 'dwDesiredAccess'), (1, 'dwShareMode'), (1, 'lpSecurityAttributes'), (1, 'dwCreationDisposition'), (1, 'dwFlagsAndAttributes'), (1, 'hTemplateFile')) + +# NtQuerySystemInformation(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength): +NtQuerySystemInformationPrototype = WINFUNCTYPE(NTSTATUS, SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG) +NtQuerySystemInformationParams = ((1, 'SystemInformationClass'), (1, 'SystemInformation'), (1, 'SystemInformationLength'), (1, 'ReturnLength')) + +# VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect): +VirtualAllocPrototype = WINFUNCTYPE(LPVOID, LPVOID, SIZE_T, DWORD, DWORD) +VirtualAllocParams = ((1, 'lpAddress'), (1, 'dwSize'), (1, 'flAllocationType'), (1, 'flProtect')) + +# VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect): +VirtualAllocExPrototype = WINFUNCTYPE(LPVOID, HANDLE, LPVOID, SIZE_T, DWORD, DWORD) +VirtualAllocExParams = ((1, 'hProcess'), (1, 'lpAddress'), (1, 'dwSize'), (1, 'flAllocationType'), (1, 'flProtect')) + +# VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect): +VirtualProtectPrototype = WINFUNCTYPE(BOOL, LPVOID, SIZE_T, DWORD, PDWORD) +VirtualProtectParams = ((1, 'lpAddress'), (1, 'dwSize'), (1, 'flNewProtect'), (1, 'lpflOldProtect')) + +# VirtualQuery(lpAddress, lpBuffer, dwLength): +VirtualQueryPrototype = WINFUNCTYPE(DWORD, LPCVOID, PMEMORY_BASIC_INFORMATION, DWORD) +VirtualQueryParams = ((1, 'lpAddress'), (1, 'lpBuffer'), (1, 'dwLength')) + +# GetModuleFileNameA(hModule, lpFilename, nSize): +GetModuleFileNameAPrototype = WINFUNCTYPE(DWORD, HMODULE, LPSTR, DWORD) +GetModuleFileNameAParams = ((1, 'hModule'), (1, 'lpFilename'), (1, 'nSize')) + +# GetModuleFileNameW(hModule, lpFilename, nSize): +GetModuleFileNameWPrototype = WINFUNCTYPE(DWORD, HMODULE, LPWSTR, DWORD) +GetModuleFileNameWParams = ((1, 'hModule'), (1, 'lpFilename'), (1, 'nSize')) + +# CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId): +CreateRemoteThreadPrototype = WINFUNCTYPE(HANDLE, HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPTHREAD_START_ROUTINE, LPVOID, DWORD, LPDWORD) +CreateRemoteThreadParams = ((1, 'hProcess'), (1, 'lpThreadAttributes'), (1, 'dwStackSize'), (1, 'lpStartAddress'), (1, 'lpParameter'), (1, 'dwCreationFlags'), (1, 'lpThreadId')) + +# VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect): +VirtualProtectPrototype = WINFUNCTYPE(BOOL, LPVOID, SIZE_T, DWORD, PDWORD) +VirtualProtectParams = ((1, 'lpAddress'), (1, 'dwSize'), (1, 'flNewProtect'), (1, 'lpflOldProtect')) + +# CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation): +CreateProcessAPrototype = WINFUNCTYPE(BOOL, LPCSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCSTR, LPSTARTUPINFOA, LPPROCESS_INFORMATION) +CreateProcessAParams = ((1, 'lpApplicationName'), (1, 'lpCommandLine'), (1, 'lpProcessAttributes'), (1, 'lpThreadAttributes'), (1, 'bInheritHandles'), (1, 'dwCreationFlags'), (1, 'lpEnvironment'), (1, 'lpCurrentDirectory'), (1, 'lpStartupInfo'), (1, 'lpProcessInformation')) + +# CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation): +CreateProcessWPrototype = WINFUNCTYPE(BOOL, LPCWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION) +CreateProcessWParams = ((1, 'lpApplicationName'), (1, 'lpCommandLine'), (1, 'lpProcessAttributes'), (1, 'lpThreadAttributes'), (1, 'bInheritHandles'), (1, 'dwCreationFlags'), (1, 'lpEnvironment'), (1, 'lpCurrentDirectory'), (1, 'lpStartupInfo'), (1, 'lpProcessInformation')) + +# GetThreadContext(hThread, lpContext): +GetThreadContextPrototype = WINFUNCTYPE(BOOL, HANDLE, LPCONTEXT) +GetThreadContextParams = ((1, 'hThread'), (1, 'lpContext')) + +# SetThreadContext(hThread, lpContext): +SetThreadContextPrototype = WINFUNCTYPE(BOOL, HANDLE, POINTER(CONTEXT)) +SetThreadContextParams = ((1, 'hThread'), (1, 'lpContext')) + +# OpenThread(dwDesiredAccess, bInheritHandle, dwThreadId): +OpenThreadPrototype = WINFUNCTYPE(HANDLE, DWORD, BOOL, DWORD) +OpenThreadParams = ((1, 'dwDesiredAccess'), (1, 'bInheritHandle'), (1, 'dwThreadId')) + +# OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId): +OpenProcessPrototype = WINFUNCTYPE(HANDLE, DWORD, BOOL, DWORD) +OpenProcessParams = ((1, 'dwDesiredAccess'), (1, 'bInheritHandle'), (1, 'dwProcessId')) + +# CloseHandle(hObject): +CloseHandlePrototype = WINFUNCTYPE(BOOL, HANDLE) +CloseHandleParams = ((1, 'hObject'),) + +# ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead): +ReadProcessMemoryPrototype = WINFUNCTYPE(BOOL, HANDLE, LPCVOID, LPVOID, SIZE_T, POINTER(SIZE_T)) +ReadProcessMemoryParams = ((1, 'hProcess'), (1, 'lpBaseAddress'), (1, 'lpBuffer'), (1, 'nSize'), (1, 'lpNumberOfBytesRead')) + +# WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten): +WriteProcessMemoryPrototype = WINFUNCTYPE(BOOL, HANDLE, LPVOID, LPCVOID, SIZE_T, POINTER(SIZE_T)) +WriteProcessMemoryParams = ((1, 'hProcess'), (1, 'lpBaseAddress'), (1, 'lpBuffer'), (1, 'nSize'), (1, 'lpNumberOfBytesWritten')) + +# CreateToolhelp32Snapshot(dwFlags, th32ProcessID): +CreateToolhelp32SnapshotPrototype = WINFUNCTYPE(HANDLE, DWORD, DWORD) +CreateToolhelp32SnapshotParams = ((1, 'dwFlags'), (1, 'th32ProcessID')) + +# Thread32First(hSnapshot, lpte): +Thread32FirstPrototype = WINFUNCTYPE(BOOL, HANDLE, LPTHREADENTRY32) +Thread32FirstParams = ((1, 'hSnapshot'), (1, 'lpte')) + +# Thread32Next(hSnapshot, lpte): +Thread32NextPrototype = WINFUNCTYPE(BOOL, HANDLE, LPTHREADENTRY32) +Thread32NextParams = ((1, 'hSnapshot'), (1, 'lpte')) + +# Process32First(hSnapshot, lppe): +Process32FirstPrototype = WINFUNCTYPE(BOOL, HANDLE, LPPROCESSENTRY32) +Process32FirstParams = ((1, 'hSnapshot'), (1, 'lppe')) + +# Process32Next(hSnapshot, lppe): +Process32NextPrototype = WINFUNCTYPE(BOOL, HANDLE, LPPROCESSENTRY32) +Process32NextParams = ((1, 'hSnapshot'), (1, 'lppe')) + +# Process32FirstW(hSnapshot, lppe): +Process32FirstWPrototype = WINFUNCTYPE(BOOL, HANDLE, LPPROCESSENTRY32W) +Process32FirstWParams = ((1, 'hSnapshot'), (1, 'lppe')) + +# Process32NextW(hSnapshot, lppe): +Process32NextWPrototype = WINFUNCTYPE(BOOL, HANDLE, LPPROCESSENTRY32W) +Process32NextWParams = ((1, 'hSnapshot'), (1, 'lppe')) + +# GetProcAddress(hModule, lpProcName): +GetProcAddressPrototype = WINFUNCTYPE(FARPROC, HMODULE, LPCSTR) +GetProcAddressParams = ((1, 'hModule'), (1, 'lpProcName')) + +# LoadLibraryA(lpFileName): +LoadLibraryAPrototype = WINFUNCTYPE(HMODULE, LPCSTR) +LoadLibraryAParams = ((1, 'lpFileName'),) + +# LoadLibraryW(lpFileName): +LoadLibraryWPrototype = WINFUNCTYPE(HMODULE, LPCWSTR) +LoadLibraryWParams = ((1, 'lpFileName'),) + +# OpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle): +OpenProcessTokenPrototype = WINFUNCTYPE(BOOL, HANDLE, DWORD, PHANDLE) +OpenProcessTokenParams = ((1, 'ProcessHandle'), (1, 'DesiredAccess'), (1, 'TokenHandle')) + +# LookupPrivilegeValueA(lpSystemName, lpName, lpLuid): +LookupPrivilegeValueAPrototype = WINFUNCTYPE(BOOL, LPCSTR, LPCSTR, PLUID) +LookupPrivilegeValueAParams = ((1, 'lpSystemName'), (1, 'lpName'), (1, 'lpLuid')) + +# LookupPrivilegeValueW(lpSystemName, lpName, lpLuid): +LookupPrivilegeValueWPrototype = WINFUNCTYPE(BOOL, LPCWSTR, LPCWSTR, PLUID) +LookupPrivilegeValueWParams = ((1, 'lpSystemName'), (1, 'lpName'), (1, 'lpLuid')) + +# AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength): +AdjustTokenPrivilegesPrototype = WINFUNCTYPE(BOOL, HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD) +AdjustTokenPrivilegesParams = ((1, 'TokenHandle'), (1, 'DisableAllPrivileges'), (1, 'NewState'), (1, 'BufferLength'), (1, 'PreviousState'), (1, 'ReturnLength')) + +# FindResourceA(hModule, lpName, lpType): +FindResourceAPrototype = WINFUNCTYPE(HRSRC, HMODULE, LPCSTR, LPCSTR) +FindResourceAParams = ((1, 'hModule'), (1, 'lpName'), (1, 'lpType')) + +# FindResourceW(hModule, lpName, lpType): +FindResourceWPrototype = WINFUNCTYPE(HRSRC, HMODULE, LPCWSTR, LPCWSTR) +FindResourceWParams = ((1, 'hModule'), (1, 'lpName'), (1, 'lpType')) + +# SizeofResource(hModule, hResInfo): +SizeofResourcePrototype = WINFUNCTYPE(DWORD, HMODULE, HRSRC) +SizeofResourceParams = ((1, 'hModule'), (1, 'hResInfo')) + +# LoadResource(hModule, hResInfo): +LoadResourcePrototype = WINFUNCTYPE(HGLOBAL, HMODULE, HRSRC) +LoadResourceParams = ((1, 'hModule'), (1, 'hResInfo')) + +# LockResource(hResData): +LockResourcePrototype = WINFUNCTYPE(LPVOID, HGLOBAL) +LockResourceParams = ((1, 'hResData'),) + diff --git a/generated_def/winstructs.py b/generated_def/winstructs.py new file mode 100644 index 0000000..84ecc8e --- /dev/null +++ b/generated_def/winstructs.py @@ -0,0 +1,521 @@ +#Generated file +from ctypes import * +from ctypes.wintypes import * +from windef import * + +PWSTR = LPWSTR +SIZE_T = c_ulong +PVOID = c_void_p +PPS_POST_PROCESS_INIT_ROUTINE = PVOID +NTSTATUS = DWORD +PULONG = POINTER(ULONG) +PDWORD = POINTER(DWORD) +LPDWORD = POINTER(DWORD) +LPTHREAD_START_ROUTINE = PVOID +LPBYTE = POINTER(BYTE) +ULONG_PTR = PULONG +CHAR = c_char +FARPROC = PVOID +HGLOBAL = PVOID +HRESULT = c_long +PHANDLE = POINTER(HANDLE) +VOID = DWORD + +structs = ['_LIST_ENTRY', '_PEB_LDR_DATA', '_LSA_UNICODE_STRING', '_RTL_USER_PROCESS_PARAMETERS', '_PEB', '_SECURITY_ATTRIBUTES', '_SYSTEM_VERIFIER_INFORMATION', '_LDR_DATA_TABLE_ENTRY', '_PEB_LDR_DATA', '_IMAGE_FILE_HEADER', '_IMAGE_DATA_DIRECTORY', '_IMAGE_OPTIONAL_HEADER', '_IMAGE_NT_HEADERS', '_MEMORY_BASIC_INFORMATION', '_STARTUPINFOA', '_STARTUPINFOW', '_PROCESS_INFORMATION', '_FLOATING_SAVE_AREA', '_CONTEXT', 'tagPROCESSENTRY32W', 'tagPROCESSENTRY32', 'tagTHREADENTRY32', '_LUID', '_LUID_AND_ATTRIBUTES', '_TOKEN_PRIVILEGES'] + +enums = ['_SYSTEM_INFORMATION_CLASS'] + +# Enum _SYSTEM_INFORMATION_CLASS definitions +_SYSTEM_INFORMATION_CLASS = DWORD +SYSTEM_INFORMATION_CLASS = _SYSTEM_INFORMATION_CLASS + +SystemBasicInformation = 0x0 +SystemProcessorInformation = 0x1 +SystemPerformanceInformation = 0x2 +SystemTimeOfDayInformation = 0x3 +SystemPathInformation = 0x4 +SystemProcessInformation = 0x5 +SystemCallCountInformation = 0x6 +SystemDeviceInformation = 0x7 +SystemProcessorPerformanceInformation = 0x8 +SystemFlagsInformation = 0x9 +SystemCallTimeInformation = 0xa +SystemModuleInformation = 0xb +SystemLocksInformation = 0xc +SystemStackTraceInformation = 0xd +SystemPagedPoolInformation = 0xe +SystemNonPagedPoolInformation = 0xf +SystemHandleInformation = 0x10 +SystemObjectInformation = 0x11 +SystemPageFileInformation = 0x12 +SystemVdmInstemulInformation = 0x13 +SystemVdmBopInformation = 0x14 +SystemFileCacheInformation = 0x15 +SystemPoolTagInformation = 0x16 +SystemInterruptInformation = 0x17 +SystemDpcBehaviorInformation = 0x18 +SystemFullMemoryInformation = 0x19 +SystemLoadGdiDriverInformation = 0x1a +SystemUnloadGdiDriverInformation = 0x1b +SystemTimeAdjustmentInformation = 0x1c +SystemSummaryMemoryInformation = 0x1d +SystemMirrorMemoryInformation = 0x1e +SystemPerformanceTraceInformation = 0x1f +SystemObsolete0 = 0x20 +SystemExceptionInformation = 0x21 +SystemCrashDumpStateInformation = 0x22 +SystemKernelDebuggerInformation = 0x23 +SystemContextSwitchInformation = 0x24 +SystemRegistryQuotaInformation = 0x25 +SystemExtendServiceTableInformation = 0x26 +SystemPrioritySeperation = 0x27 +SystemVerifierAddDriverInformation = 0x28 +SystemVerifierRemoveDriverInformation = 0x29 +SystemProcessorIdleInformation = 0x2a +SystemLegacyDriverInformation = 0x2b +SystemCurrentTimeZoneInformation = 0x2c +SystemLookasideInformation = 0x2d +SystemTimeSlipNotification = 0x2e +SystemSessionCreate = 0x2f +SystemSessionDetach = 0x30 +SystemSessionInformation = 0x31 +SystemRangeStartInformation = 0x32 +SystemVerifierInformation = 0x33 +SystemVerifierThunkExtend = 0x34 +SystemSessionProcessInformation = 0x35 +SystemLoadGdiDriverInSystemSpace = 0x36 +SystemNumaProcessorMap = 0x37 +SystemPrefetcherInformation = 0x38 +SystemExtendedProcessInformation = 0x39 +SystemRecommendedSharedDataAlignment = 0x3a +SystemComPlusPackage = 0x3b +SystemNumaAvailableMemory = 0x3c +SystemProcessorPowerInformation = 0x3d +SystemEmulationBasicInformation = 0x3e +SystemEmulationProcessorInformation = 0x3f +SystemExtendedHandleInformation = 0x40 +SystemLostDelayedWriteInformation = 0x41 +SystemBigPoolInformation = 0x42 +SystemSessionPoolTagInformation = 0x43 +SystemSessionMappedViewInformation = 0x44 +SystemHotpatchInformation = 0x45 +SystemObjectSecurityMode = 0x46 +SystemWatchdogTimerHandler = 0x47 +SystemWatchdogTimerInformation = 0x48 +SystemLogicalProcessorInformation = 0x49 +SystemWow64SharedInformation = 0x4a +SystemRegisterFirmwareTableInformationHandler = 0x4b +SystemFirmwareTableInformation = 0x4c +SystemModuleInformationEx = 0x4d +SystemVerifierTriageInformation = 0x4e +SystemSuperfetchInformation = 0x4f +SystemMemoryListInformation = 0x50 +SystemFileCacheInformationEx = 0x51 +MaxSystemInfoClass = 0x52 +# Struct _LIST_ENTRY definitions +# Self referencing struct tricks +class _LIST_ENTRY(Structure): pass +_LIST_ENTRY._fields_ = [ + ("Flink", POINTER(_LIST_ENTRY)), + ("Blink", POINTER(_LIST_ENTRY)), +] +PLIST_ENTRY = POINTER(_LIST_ENTRY) +LIST_ENTRY = _LIST_ENTRY +PRLIST_ENTRY = POINTER(_LIST_ENTRY) + +# Struct _PEB_LDR_DATA definitions +class _PEB_LDR_DATA(Structure): + _fields_ = [ + ("Reserved1", BYTE * 8), + ("Reserved2", PVOID * 3), + ("InMemoryOrderModuleList", LIST_ENTRY), + ] +PPEB_LDR_DATA = POINTER(_PEB_LDR_DATA) +PEB_LDR_DATA = _PEB_LDR_DATA + +# Struct _LSA_UNICODE_STRING definitions +class _LSA_UNICODE_STRING(Structure): + _fields_ = [ + ("Length", USHORT), + ("MaximumLength", USHORT), + ("Buffer", PWSTR), + ] +PUNICODE_STRING = POINTER(_LSA_UNICODE_STRING) +UNICODE_STRING = _LSA_UNICODE_STRING +LSA_UNICODE_STRING = _LSA_UNICODE_STRING +PLSA_UNICODE_STRING = POINTER(_LSA_UNICODE_STRING) + +# Struct _RTL_USER_PROCESS_PARAMETERS definitions +class _RTL_USER_PROCESS_PARAMETERS(Structure): + _fields_ = [ + ("Reserved1", BYTE * 16), + ("Reserved2", PVOID * 10), + ("ImagePathName", UNICODE_STRING), + ("CommandLine", UNICODE_STRING), + ] +PRTL_USER_PROCESS_PARAMETERS = POINTER(_RTL_USER_PROCESS_PARAMETERS) +RTL_USER_PROCESS_PARAMETERS = _RTL_USER_PROCESS_PARAMETERS + +# Struct _PEB definitions +class _PEB(Structure): + _fields_ = [ + ("Reserved1", BYTE * 2), + ("BeingDebugged", BYTE), + ("Reserved2", BYTE * 1), + ("Reserved3", PVOID * 2), + ("Ldr", PPEB_LDR_DATA), + ("ProcessParameters", PRTL_USER_PROCESS_PARAMETERS), + ("Reserved4", BYTE * 104), + ("Reserved5", PVOID * 52), + ("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE), + ("Reserved6", BYTE * 128), + ("Reserved7", PVOID * 1), + ("SessionId", ULONG), + ] +PPEB = POINTER(_PEB) +PEB = _PEB + +# Struct _SECURITY_ATTRIBUTES definitions +class _SECURITY_ATTRIBUTES(Structure): + _fields_ = [ + ("nLength", DWORD), + ("lpSecurityDescriptor", LPVOID), + ("bInheritHandle", BOOL), + ] +SECURITY_ATTRIBUTES = _SECURITY_ATTRIBUTES +LPSECURITY_ATTRIBUTES = POINTER(_SECURITY_ATTRIBUTES) +PSECURITY_ATTRIBUTES = POINTER(_SECURITY_ATTRIBUTES) + +# Struct _SYSTEM_VERIFIER_INFORMATION definitions +class _SYSTEM_VERIFIER_INFORMATION(Structure): + _fields_ = [ + ("NextEntryOffset", ULONG), + ("Level", ULONG), + ("DriverName", UNICODE_STRING), + ("RaiseIrqls", ULONG), + ("AcquireSpinLocks", ULONG), + ("SynchronizeExecutions", ULONG), + ("AllocationsAttempted", ULONG), + ("AllocationsSucceeded", ULONG), + ("AllocationsSucceededSpecialPool", ULONG), + ("AllocationsWithNoTag", ULONG), + ("TrimRequests", ULONG), + ("Trims", ULONG), + ("AllocationsFailed", ULONG), + ("AllocationsFailedDeliberately", ULONG), + ("Loads", ULONG), + ("Unloads", ULONG), + ("UnTrackedPool", ULONG), + ("CurrentPagedPoolAllocations", ULONG), + ("CurrentNonPagedPoolAllocations", ULONG), + ("PeakPagedPoolAllocations", ULONG), + ("PeakNonPagedPoolAllocations", ULONG), + ("PagedPoolUsageInBytes", SIZE_T), + ("NonPagedPoolUsageInBytes", SIZE_T), + ("PeakPagedPoolUsageInBytes", SIZE_T), + ("PeakNonPagedPoolUsageInBytes", SIZE_T), + ] +PSYSTEM_VERIFIER_INFORMATION = POINTER(_SYSTEM_VERIFIER_INFORMATION) +SYSTEM_VERIFIER_INFORMATION = _SYSTEM_VERIFIER_INFORMATION + +# Struct _LDR_DATA_TABLE_ENTRY definitions +class _LDR_DATA_TABLE_ENTRY(Structure): + _fields_ = [ + ("Reserved1", PVOID * 2), + ("InMemoryOrderLinks", LIST_ENTRY), + ("Reserved2", PVOID * 2), + ("DllBase", PVOID), + ("EntryPoint", PVOID), + ("Reserved3", PVOID), + ("FullDllName", UNICODE_STRING), + ("BaseDllName", UNICODE_STRING), + ("Reserved5", PVOID * 3), + ("CheckSum", ULONG), + ("TimeDateStamp", ULONG), + ] +PLDR_DATA_TABLE_ENTRY = POINTER(_LDR_DATA_TABLE_ENTRY) +LDR_DATA_TABLE_ENTRY = _LDR_DATA_TABLE_ENTRY + +# Struct _PEB_LDR_DATA definitions +class _PEB_LDR_DATA(Structure): + _fields_ = [ + ("Reserved1", BYTE * 8), + ("Reserved2", PVOID * 3), + ("InMemoryOrderModuleList", LIST_ENTRY), + ] +PPEB_LDR_DATA = POINTER(_PEB_LDR_DATA) +PEB_LDR_DATA = _PEB_LDR_DATA + +# Struct _IMAGE_FILE_HEADER definitions +class _IMAGE_FILE_HEADER(Structure): + _fields_ = [ + ("Machine", WORD), + ("NumberOfSections", WORD), + ("TimeDateStamp", DWORD), + ("PointerToSymbolTable", DWORD), + ("NumberOfSymbols", DWORD), + ("SizeOfOptionalHeader", WORD), + ("Characteristics", WORD), + ] +IMAGE_FILE_HEADER = _IMAGE_FILE_HEADER +PIMAGE_FILE_HEADER = POINTER(_IMAGE_FILE_HEADER) + +# Struct _IMAGE_DATA_DIRECTORY definitions +class _IMAGE_DATA_DIRECTORY(Structure): + _fields_ = [ + ("VirtualAddress", DWORD), + ("Size", DWORD), + ] +IMAGE_DATA_DIRECTORY = _IMAGE_DATA_DIRECTORY +PIMAGE_DATA_DIRECTORY = POINTER(_IMAGE_DATA_DIRECTORY) + +# Struct _IMAGE_OPTIONAL_HEADER definitions +class _IMAGE_OPTIONAL_HEADER(Structure): + _fields_ = [ + ("Magic", WORD), + ("MajorLinkerVersion", BYTE), + ("MinorLinkerVersion", BYTE), + ("SizeOfCode", DWORD), + ("SizeOfInitializedData", DWORD), + ("SizeOfUninitializedData", DWORD), + ("AddressOfEntryPoint", DWORD), + ("BaseOfCode", DWORD), + ("BaseOfData", DWORD), + ("ImageBase", DWORD), + ("SectionAlignment", DWORD), + ("FileAlignment", DWORD), + ("MajorOperatingSystemVersion", WORD), + ("MinorOperatingSystemVersion", WORD), + ("MajorImageVersion", WORD), + ("MinorImageVersion", WORD), + ("MajorSubsystemVersion", WORD), + ("MinorSubsystemVersion", WORD), + ("Win32VersionValue", DWORD), + ("SizeOfImage", DWORD), + ("SizeOfHeaders", DWORD), + ("CheckSum", DWORD), + ("Subsystem", WORD), + ("DllCharacteristics", WORD), + ("SizeOfStackReserve", DWORD), + ("SizeOfStackCommit", DWORD), + ("SizeOfHeapReserve", DWORD), + ("SizeOfHeapCommit", DWORD), + ("LoaderFlags", DWORD), + ("NumberOfRvaAndSizes", DWORD), + ("DataDirectory", PIMAGE_DATA_DIRECTORY), + ] +PIMAGE_OPTIONAL_HEADER = POINTER(_IMAGE_OPTIONAL_HEADER) +IMAGE_OPTIONAL_HEADER = _IMAGE_OPTIONAL_HEADER + +# Struct _IMAGE_NT_HEADERS definitions +class _IMAGE_NT_HEADERS(Structure): + _fields_ = [ + ("Signature", DWORD), + ("FileHeader", IMAGE_FILE_HEADER), + ("OptionalHeader", IMAGE_OPTIONAL_HEADER), + ] +PIMAGE_NT_HEADERS = POINTER(_IMAGE_NT_HEADERS) +IMAGE_NT_HEADERS = _IMAGE_NT_HEADERS + +# Struct _MEMORY_BASIC_INFORMATION definitions +class _MEMORY_BASIC_INFORMATION(Structure): + _fields_ = [ + ("BaseAddress", PVOID), + ("AllocationBase", PVOID), + ("AllocationProtect", DWORD), + ("RegionSize", SIZE_T), + ("State", DWORD), + ("Protect", DWORD), + ("Type", DWORD), + ] +PMEMORY_BASIC_INFORMATION = POINTER(_MEMORY_BASIC_INFORMATION) +MEMORY_BASIC_INFORMATION = _MEMORY_BASIC_INFORMATION + +# Struct _STARTUPINFOA definitions +class _STARTUPINFOA(Structure): + _fields_ = [ + ("cb", DWORD), + ("lpReserved", LPSTR), + ("lpDesktop", LPSTR), + ("lpTitle", LPSTR), + ("dwX", DWORD), + ("dwY", DWORD), + ("dwXSize", DWORD), + ("dwYSize", DWORD), + ("dwXCountChars", DWORD), + ("dwYCountChars", DWORD), + ("dwFillAttribute", DWORD), + ("dwFlags", DWORD), + ("wShowWindow", WORD), + ("cbReserved2", WORD), + ("lpReserved2", LPBYTE), + ("hStdInput", HANDLE), + ("hStdOutput", HANDLE), + ("hStdError", HANDLE), + ] +LPSTARTUPINFOA = POINTER(_STARTUPINFOA) +STARTUPINFOA = _STARTUPINFOA + +# Struct _STARTUPINFOW definitions +class _STARTUPINFOW(Structure): + _fields_ = [ + ("cb", DWORD), + ("lpReserved", LPWSTR), + ("lpDesktop", LPWSTR), + ("lpTitle", LPWSTR), + ("dwX", DWORD), + ("dwY", DWORD), + ("dwXSize", DWORD), + ("dwYSize", DWORD), + ("dwXCountChars", DWORD), + ("dwYCountChars", DWORD), + ("dwFillAttribute", DWORD), + ("dwFlags", DWORD), + ("wShowWindow", WORD), + ("cbReserved2", WORD), + ("lpReserved2", LPBYTE), + ("hStdInput", HANDLE), + ("hStdOutput", HANDLE), + ("hStdError", HANDLE), + ] +STARTUPINFOW = _STARTUPINFOW +LPSTARTUPINFOW = POINTER(_STARTUPINFOW) + +# Struct _PROCESS_INFORMATION definitions +class _PROCESS_INFORMATION(Structure): + _fields_ = [ + ("hProcess", HANDLE), + ("hThread", HANDLE), + ("dwProcessId", DWORD), + ("dwThreadId", DWORD), + ] +LPPROCESS_INFORMATION = POINTER(_PROCESS_INFORMATION) +PROCESS_INFORMATION = _PROCESS_INFORMATION +PPROCESS_INFORMATION = POINTER(_PROCESS_INFORMATION) + +# Struct _FLOATING_SAVE_AREA definitions +class _FLOATING_SAVE_AREA(Structure): + _fields_ = [ + ("ControlWord", DWORD), + ("StatusWord", DWORD), + ("TagWord", DWORD), + ("ErrorOffset", DWORD), + ("ErrorSelector", DWORD), + ("DataOffset", DWORD), + ("DataSelector", DWORD), + ("RegisterArea", BYTE * 80), + ("Cr0NpxState", DWORD), + ] +FLOATING_SAVE_AREA = _FLOATING_SAVE_AREA + +# Struct _CONTEXT definitions +class _CONTEXT(Structure): + _fields_ = [ + ("ContextFlags", DWORD), + ("Dr0", DWORD), + ("Dr1", DWORD), + ("Dr2", DWORD), + ("Dr3", DWORD), + ("Dr6", DWORD), + ("Dr7", DWORD), + ("FloatSave", FLOATING_SAVE_AREA), + ("SegGs", DWORD), + ("SegFs", DWORD), + ("SegEs", DWORD), + ("SegDs", DWORD), + ("Edi", DWORD), + ("Esi", DWORD), + ("Ebx", DWORD), + ("Edx", DWORD), + ("Ecx", DWORD), + ("Eax", DWORD), + ("Ebp", DWORD), + ("Eip", DWORD), + ("SegCs", DWORD), + ("EFlags", DWORD), + ("Esp", DWORD), + ("SegSs", DWORD), + ("ExtendedRegisters", BYTE * 512), + ] +PCONTEXT = POINTER(_CONTEXT) +LPCONTEXT = POINTER(_CONTEXT) +CONTEXT = _CONTEXT + +# Struct tagPROCESSENTRY32W definitions +class tagPROCESSENTRY32W(Structure): + _fields_ = [ + ("dwSize", DWORD), + ("cntUsage", DWORD), + ("th32ProcessID", DWORD), + ("th32DefaultHeapID", ULONG_PTR), + ("th32ModuleID", DWORD), + ("cntThreads", DWORD), + ("th32ParentProcessID", DWORD), + ("pcPriClassBase", LONG), + ("dwFlags", DWORD), + ("szExeFile", WCHAR * MAX_PATH), + ] +PPROCESSENTRY32W = POINTER(tagPROCESSENTRY32W) +LPPROCESSENTRY32W = POINTER(tagPROCESSENTRY32W) +PROCESSENTRY32W = tagPROCESSENTRY32W + +# Struct tagPROCESSENTRY32 definitions +class tagPROCESSENTRY32(Structure): + _fields_ = [ + ("dwSize", DWORD), + ("cntUsage", DWORD), + ("th32ProcessID", DWORD), + ("th32DefaultHeapID", ULONG_PTR), + ("th32ModuleID", DWORD), + ("cntThreads", DWORD), + ("th32ParentProcessID", DWORD), + ("pcPriClassBase", LONG), + ("dwFlags", DWORD), + ("szExeFile", CHAR * MAX_PATH), + ] +PROCESSENTRY32 = tagPROCESSENTRY32 +PPROCESSENTRY32 = POINTER(tagPROCESSENTRY32) +LPPROCESSENTRY32 = POINTER(tagPROCESSENTRY32) + +# Struct tagTHREADENTRY32 definitions +class tagTHREADENTRY32(Structure): + _fields_ = [ + ("dwSize", DWORD), + ("cntUsage", DWORD), + ("th32ThreadID", DWORD), + ("th32OwnerProcessID", DWORD), + ("tpBasePri", LONG), + ("tpDeltaPri", LONG), + ("dwFlags", DWORD), + ] +PTHREADENTRY32 = POINTER(tagTHREADENTRY32) +THREADENTRY32 = tagTHREADENTRY32 +LPTHREADENTRY32 = POINTER(tagTHREADENTRY32) + +# Struct _LUID definitions +class _LUID(Structure): + _fields_ = [ + ("LowPart", DWORD), + ("HighPart", LONG), + ] +LUID = _LUID +PLUID = POINTER(_LUID) + +# Struct _LUID_AND_ATTRIBUTES definitions +class _LUID_AND_ATTRIBUTES(Structure): + _fields_ = [ + ("Luid", LUID), + ("Attributes", DWORD), + ] +LUID_AND_ATTRIBUTES = _LUID_AND_ATTRIBUTES +PLUID_AND_ATTRIBUTES = POINTER(_LUID_AND_ATTRIBUTES) + +# Struct _TOKEN_PRIVILEGES definitions +class _TOKEN_PRIVILEGES(Structure): + _fields_ = [ + ("PrivilegeCount", DWORD), + ("Privileges", LUID_AND_ATTRIBUTES * ANYSIZE_ARRAY), + ] +TOKEN_PRIVILEGES = _TOKEN_PRIVILEGES +PTOKEN_PRIVILEGES = POINTER(_TOKEN_PRIVILEGES) + diff --git a/hooks.py b/hooks.py new file mode 100644 index 0000000..8dc23f4 --- /dev/null +++ b/hooks.py @@ -0,0 +1,92 @@ +import sys +import utils +import native_exec +import ctypes +import windows.generated_def.winfuncs as winfuncs +import windows.generated_def.windef as windef + +DWORD = ctypes.wintypes.DWORD +HANDLE = ctypes.wintypes.HANDLE + +class Callback(object): + def __init__(self, *types): + self.types = types + + def __call__(self, func): + func._types_info = self.types + return func + +class KnownCallback(object): + types = () + + def __call__(self, func): + func._types_info = self.types + return func + +def add_callback_to_module(callback): + setattr(sys.modules[__name__], type(callback).__name__, callback) + +# Generate IATCallback decorator for all known functions +for func in winfuncs.functions: + prototype = getattr(winfuncs, func + "Prototype") + callback_name = func + "Callback" + + class CallBackDeclaration(KnownCallback): + types = (prototype._restype_,) + prototype._argtypes_ + + CallBackDeclaration.__name__ = callback_name + add_callback_to_module(CallBackDeclaration()) + + +class IATHook(object): + + #callback_inject = python_native_execution.CallbackInjector() + + def __init__(self, IAT_entry, callback, types=None): + if types is None: + if not hasattr(callback, "_types_info"): + raise ValueError("Callback for IATHook has no type infomations") + types = callback._types_info + self.original_types = types + self.callback_types = self.transform_arguments(self.original_types) + self.entry = IAT_entry + self.callback = callback + self.stub = native_exec.generate_callback_stub(self.hook_callback, self.callback_types) + self.realfunction = ctypes.WINFUNCTYPE(*types)(IAT_entry.nonhookvalue) + self.is_enable = False + + + def transform_arguments(self, types): + res = [] + for type in types: + if type in (ctypes.c_wchar_p, ctypes.c_char_p): + res.append(ctypes.c_void_p) + else: + res.append(type) + return res + + def enable(self): + with utils.VirtualProtected(self.entry.addr, 0x4, windef.PAGE_EXECUTE_READWRITE): + self.entry.value = self.stub + self.is_enable = True + + def disable(self): + with utils.VirtualProtected(self.entry.addr, 0x4, windef.PAGE_EXECUTE_READWRITE): + self.entry.value = self.entry.nonhookvalue + self.is_enable = False + + def hook_callback(self, *args): + original_args = args + adapted_args = [] + for value, type in zip(args, self.original_types[1:]): + if type == ctypes.c_wchar_p: + adapted_args.append(ctypes.c_wchar_p(value)) + elif type == ctypes.c_char_p: + adapted_args.append(ctypes.c_char_p((value))) + else: + adapted_args.append(value) + def real_function(*args): + if args == (): + args = adapted_args + return self.realfunction(*args) + return self.callback(*adapted_args, real_function=real_function) \ No newline at end of file diff --git a/injection.py b/injection.py new file mode 100644 index 0000000..bf51f12 --- /dev/null +++ b/injection.py @@ -0,0 +1,92 @@ +import sys +import os + +import utils +from native_exec.simple_x86 import * + + +RPython = os.getcwd() + r'\..\RPython' +sys.path.append(RPython) +#import master + +def generate_python_exec_shellcode(PYDLL_addr, PyInit, PyRun, PYCODE_ADDR): + LoadLibraryA = utils.get_func_addr('kernel32', 'LoadLibraryA') + GetProcAddress = utils.get_func_addr('kernel32', 'GetProcAddress') + code = MultipleInstr() + code += Push_X(PYDLL_addr) + code += Mov_EAX_X(LoadLibraryA) + code += Call_EAX() + code += Push_EAX() + code += Pop_EDI() + code += Push_X(PyInit) + code += Push_EDI() + code += Mov_EBX_X(GetProcAddress) + code += Call_EBX() + code += Call_EAX() + code += Push_X(PyRun) + code += Push_EDI() + code += Call_EBX() + code += Push_X(PYCODE_ADDR) + code += Call_EAX() + code += Int3() + return code.get_code() + +def inject_python_command(process, code_injected, PYDLL="python27.dll\x00"): + PyInitT = "Py_Initialize\x00" + Pyrun = "PyRun_SimpleString\x00" + PYCODE = code_injected + "\x00" + remote_addr_base = process.virtual_alloc(len(code_injected) + 0x100) + remote_addr = remote_addr_base + + PYDLL_addr = remote_addr + process.write_memory(remote_addr, PYDLL) + remote_addr += len(PYDLL) + + + PyInitT_ADDR = remote_addr + process.write_memory(remote_addr, PyInitT) + remote_addr += len(PyInitT) + + Pyrun_ADDR = remote_addr + process.write_memory(remote_addr, Pyrun) + remote_addr += len(Pyrun) + + PYCODE_ADDR = remote_addr + process.write_memory(remote_addr, PYCODE) + remote_addr += len(PYCODE) + + + SHELLCODE_ADDR = remote_addr + shellcode = generate_python_exec_shellcode(PYDLL_addr, PyInitT_ADDR, Pyrun_ADDR, PYCODE_ADDR) + process.write_memory(SHELLCODE_ADDR, shellcode) + return SHELLCODE_ADDR + + +def execute_python_code(process, code): + shellcode_remote_addr = inject_python_command(process, code) + return process.create_thread(shellcode_remote_addr, 0) + +remote_slave_launcher = """ +import sys +import ctypes + +sys.path.append(r'{0}') +import slave + +sys.path.append(r'{1}') +import windows + +name_pool = {{'ctypes' : ctypes, '__import__' : __import__, 'windows' : windows}} +s = slave.RemotePythonSlave.create(name_pool) +slave.debug_run(s) +""".format(RPython, os.getcwd()) + + +def launch_remote_slave(process): + import master + execute_python_code(process, remote_slave_launcher) + m = master.RemotePython.create() + return m + + + \ No newline at end of file diff --git a/k32testing.py b/k32testing.py new file mode 100644 index 0000000..0bc39c4 --- /dev/null +++ b/k32testing.py @@ -0,0 +1,262 @@ +import ctypes +import functools + +from ctypes.wintypes import * +from windows.generated_def.winstructs import * +from windows.generated_def.windef import * +import windows.generated_def.winfuncs as winfuncs + + +kernel32 = ctypes.windll.kernel32 +advapi32 = ctypes.windll.Advapi32 + + + +class Kernel32Error(WindowsError): + + def __new__(cls, func_name): + win_error = ctypes.WinError() + api_error = super(Kernel32Error, cls).__new__(cls) + api_error.api_name = func_name + api_error.winerror = win_error.winerror + api_error.strerror = win_error.strerror + api_error.args = (func_name, win_error.winerror, win_error.strerror) + return api_error + + def __init__(self, func_name): + pass + + def __repr__(self): + return "{0}: {1}".format(self.api_name, super(Kernel32Error, self).__repr__()) + + def __str__(self): + return "{0}: {1}".format(self.api_name, super(Kernel32Error, self).__str__()) + +def no_error_check(result, func, args): + """Nothing special""" + return args + +# Design 1 +class ApiProxy(object): + APIDLL = None + """Create a python wrapper around a kernel32 function""" + def __init__(self, func_name, error_check=None): + self.func_name = func_name + if error_check is None: + error_check = self.default_error_check + self.error_check = error_check + + def default_error_check(self, result, func, args): + """raise Kernel32Error if result is 0""" + if not result: + raise Kernel32Error(self.func_name) + return args + + def __call__(self, python_proxy, ): + prototype = getattr(winfuncs, self.func_name + "Prototype") + params = getattr(winfuncs, self.func_name + "Params") + c_prototyped = prototype((self.func_name, self.APIDLL), params) + c_prototyped.errcheck = self.error_check + if (self.error_check.__doc__): + doc = python_proxy.__doc__ + doc = doc if doc else "" + python_proxy.__doc__ = doc + "\nErrcheck:\n " + self.error_check.__doc__ + params_name = [param[1] for param in params] + def check_arguments(*args): + if len(params_name) != len(args): + raise ValueError("I do not have all parameters: how is that possible ?") + for param_name, param_value in zip(params_name, args): + if param_value is NeededParameter: + raise TypeError("{0}: Missing Mandatory parameter <{1}>".format(self.func_name, param_name)) + return c_prototyped(*args) + setattr(python_proxy, "ctypes_function", check_arguments) + return python_proxy + +class Kernel32Proxy(ApiProxy): + APIDLL = kernel32 + +class Advapi32Proxy(ApiProxy): + APIDLL = advapi32 + +def TransparentApiProxy(APIDLL, func_name, error_check=None): + """Create a ctypes function for 'func_name' with no python arg pre-check""" + def default_error_check(result, func, args): + if not result: + raise Kernel32Error(func_name) + return args + if error_check is None: + error_check = default_error_check + prototype = getattr(winfuncs, func_name + "Prototype") + args = getattr(winfuncs, func_name + "Params") + c_prototyped = prototype((func_name, APIDLL), args) + c_prototyped.errcheck = error_check + return c_prototyped + + +TransparentKernel32Proxy = lambda *args: TransparentApiProxy(kernel32, *args) +TransparentAdvapi32Proxy = lambda *args: TransparentApiProxy(advapi32, *args) + +class NeededParameterType(object): + _inst = None + def __new__(cls): + if cls._inst is None: + cls._inst = super(NeededParameterType, cls).__new__(cls) + return cls._inst + + def __repr__(self): + return "NeededParameter" + +NeededParameter = NeededParameterType() + + + +ExitProcess = TransparentKernel32Proxy("ExitProcess") +CloseHandle = TransparentKernel32Proxy("CloseHandle") +GetProcAddress = TransparentKernel32Proxy("GetProcAddress") +LoadLibraryA = TransparentKernel32Proxy("LoadLibraryA") +LoadLibraryW = TransparentKernel32Proxy("LoadLibraryW") +GetLastError = TransparentKernel32Proxy("GetLastError", no_error_check) +GetCurrentProcess = TransparentKernel32Proxy("GetCurrentProcess") + +# This kind of function could be fully done by using paramflags +@Kernel32Proxy("VirtualAlloc") +def VirtualAlloc(lpAddress=0, dwSize=NeededParameter, flAllocationType=MEM_COMMIT, flProtect=PAGE_EXECUTE_READWRITE): + return VirtualAlloc.ctypes_function(lpAddress, dwSize, flAllocationType, flProtect) + +@Kernel32Proxy("CreateRemoteThread") +def CreateRemoteThread(hProcess=NeededParameter, lpThreadAttributes=None, dwStackSize=0, + lpStartAddress=NeededParameter, lpParameter=NeededParameter, dwCreationFlags=0, lpThreadId=None): + return CreateRemoteThread.ctypes_function(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId) + +@Kernel32Proxy("VirtualProtect") +def VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect=0): + return VirtualProtect.ctypes_function(lpAddress, dwSize, flNewProtect, lpflOldProtect) + +@Kernel32Proxy("CreateProcessA") +def CreateProcessA(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, + dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None, lpProcessInformation=None): + if lpStartupInfo is None: + StartupInfo = STARTUPINFOA() + StartupInfo.cb = ctypes.sizeof(StartupInfo) + StartupInfo.dwFlags = STARTF_USESHOWWINDOW + StartupInfo.wShowWindow = SW_HIDE + lpStartupInfo = ctypes.byref(StartupInfo) + if lpProcessInformation is None: + lpProcessInformation = ctypes.byref(PROCESS_INFORMATION()) + return CreateProcessA.ctypes_function(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation) + +@Kernel32Proxy("CreateProcessW") +def CreateProcessW(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, + dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None, lpProcessInformation=None): + if lpStartupInfo is None: + StartupInfo = STARTUPINFOW() + StartupInfo.cb = ctypes.sizeof(StartupInfo) + StartupInfo.dwFlags = STARTF_USESHOWWINDOW + StartupInfo.wShowWindow = SW_HIDE + lpStartupInfo = ctypes.byref(StartupInfo) + if lpProcessInformation is None: + lpProcessInformation = ctypes.byref(PROCESS_INFORMATION()) + return CreateProcessW.ctypes_function(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation) + +@Kernel32Proxy("GetThreadContext") +def GetThreadContext(hThread, lpContext=None): + if lpContext is None: + Context = CONTEXT() + context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS + lpContext = ctypes.byref(Context) + return GetThreadContext.ctypes_function(hThread, lpContext) + +@Kernel32Proxy("SetThreadContext") +def SetThreadContext(hThread, lpContext): + """ Allows to directly pass a CONTEXT and will call with byref(CONTEXT) by itself""" + if type(lpContext) == CONTEXT: + lpContext = ctypes.byref(lpContext) + return SetThreadContext.ctypes_function(hThread, lpContext) + +@Kernel32Proxy("OpenThread") +def OpenThread(dwDesiredAccess=THREAD_ALL_ACCESS, bInheritHandle=0, dwThreadId=NeededParameter): + return OpenThread.ctypes_function(dwDesiredAccess, bInheritHandle, dwThreadId) + +@Kernel32Proxy("OpenProcess") +def OpenProcess(dwDesiredAccess=PROCESS_ALL_ACCESS, bInheritHandle=0, dwProcessId=NeededParameter): + return OpenProcess.ctypes_function(dwDesiredAccess, bInheritHandle, dwProcessId) + +@Kernel32Proxy("ReadProcessMemory") +def ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer=None, nSize=NeededParameter, lpNumberOfBytesRead=None): + """Create a string buffer if lpBuffer is not given""" + if lpBuffer is None and nSize is not NeededParameter: + lpBuffer = ctypes.create_string_buffer(nSize) + return ReadProcessMemory.ctypes_function(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead) + +@Kernel32Proxy("WriteProcessMemory") +def WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize=None, lpNumberOfBytesWritten=None): + """Computer nSize with len(lpBuffer) if not given""" + if nSize is None: + nSize = len(lpBuffer) + return WriteProcessMemory.ctypes_function(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead) + +@Kernel32Proxy("CreateToolhelp32Snapshot") +def CreateToolhelp32Snapshot(dwFlags, th32ProcessID=0): + return CreateToolhelp32Snapshot.ctypes_function(dwFlags, th32ProcessID) + +@Kernel32Proxy("Thread32First", no_error_check) +def Thread32First(hSnapshot, lpte): + """Set byref(lpte) if needed""" + if type(lpte) == THREADENTRY32: + lpte = ctypes.byref(lpte) + return Thread32First.ctypes_function(hSnapshot, lpte) + +@Kernel32Proxy("Thread32Next", no_error_check) +def Thread32Next(hSnapshot, lpte): + """Set byref(lpte) if needed""" + if type(lpte) == THREADENTRY32: + lpte = ctypes.byref(lpte) + return Thread32Next.ctypes_function(hSnapshot, lpte) + +@Kernel32Proxy("Process32First", no_error_check) +def Process32First(hSnapshot, lpte): + """Set byref(lpte) if needed""" + if type(lpte) == THREADENTRY32: + lpte = ctypes.byref(lpte) + return Process32First.ctypes_function(hSnapshot, lpte) + +@Kernel32Proxy("Process32Next", no_error_check) +def Process32Next(hSnapshot, lpte): + """Set byref(lpte) if needed""" + if type(lpte) == THREADENTRY32: + lpte = ctypes.byref(lpte) + return Process32Next.ctypes_function(hSnapshot, lpte) + + +###### ADVAPI32 ######## + +@Advapi32Proxy('OpenProcessToken') +def OpenProcessToken(ProcessHandle=None, DesiredAccess=NeededParameter, TokenHandle=NeededParameter): + """If ProcessHandle is None: take the current process""" + if ProcessHandle is None: + ProcessHandle = GetCurrentProcess() + return OpenProcessToken.ctypes_function(ProcessHandle, DesiredAccess, TokenHandle) + +@Advapi32Proxy('LookupPrivilegeValueA') +def LookupPrivilegeValueA(lpSystemName=None, lpName=NeededParameter, lpLuid=NeededParameter): + return LookupPrivilegeValueA.ctypes_function(lpSystemName, lpName, lpLuid) + +@Advapi32Proxy('LookupPrivilegeValueW') +def LookupPrivilegeValueW(lpSystemName=None, lpName=NeededParameter, lpLuid=NeededParameter): + return LookupPrivilegeValueW.ctypes_function(lpSystemName, lpName, lpLuid) + +@Advapi32Proxy('AdjustTokenPrivileges') +def AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges=False, NewState=NeededParameter, BufferLength=None, PreviousState=None, ReturnLength=None): + if BufferLength is None: + BufferLength = ctypes.sizeof(NewState) + return AdjustTokenPrivileges.ctypes_function(TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength) +# if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { +# fprintf(stderr, "[-] The token does not have the specified privilege\n"); +# return FALSE; + + + +# Design 2 +# Design 2 should use the automatics args + + \ No newline at end of file diff --git a/native_exec/__init__.py b/native_exec/__init__.py new file mode 100644 index 0000000..bd8d3c2 --- /dev/null +++ b/native_exec/__init__.py @@ -0,0 +1,2 @@ +from native_function import generate_callback_stub, create_function + \ No newline at end of file diff --git a/native_exec/native_function.py b/native_exec/native_function.py new file mode 100644 index 0000000..718cf80 --- /dev/null +++ b/native_exec/native_function.py @@ -0,0 +1,200 @@ +import ctypes +import mmap +import platform + +class PyObj(ctypes.Structure): + _fields_ = [("ob_refcnt", ctypes.c_size_t), + ("ob_type", ctypes.c_void_p)] #must be cast + +class PyMmap(PyObj): + _fields_ = [("ob_addr", ctypes.c_size_t), ("ob_size", ctypes.c_size_t)] + +# Specific mmap class for code injection + +class MyMap(mmap.mmap): + """ A mmap that is never unmapped and that contains the page address """ + def __init__(self, *args, **kwarg): + #Get the page address by 'introspection' of the C struct + m = PyMmap.from_address(id(self)) + self.addr = m.ob_addr + #Prevent garbage collection (so unmaping) of the page + m.ob_refcnt += 1 + + @classmethod + def get_map(cls, size): + """ Dispatch to the good mmap implem depending on the current system """ + systems = {'windows' : Win32MyMap, + 'linux' : UnixMyMap } + x = platform.system().lower() + if x not in systems: + raise ValueError("Unknow system {0}".format(x)) + return systems[x].get_map(size) + +class Win32MyMap(MyMap): + @classmethod + def get_map(cls, size): + #access = mmap.ACCESS_READ | mmap.ACCESS_WRITE + #return cls(-1, size, access=access) + access = mmap.ACCESS_READ | mmap.ACCESS_WRITE + addr = ctypes.windll.kernel32.VirtualAlloc(0, size, 0x1000, 0x40) + + new_map = (ctypes.c_char * size).from_address(addr) + new_map.addr = addr + if new_map.addr == 0: + raise ctypes.WinError() + return new_map + +class UnixMyMap(MyMap): + @classmethod + def get_map(cls, size): + prot = mmap.PROT_EXEC | mmap.PROT_WRITE | mmap.PROT_READ + return cls(-1, size, prot=prot) + + +class CustomAllocator(object): + int_size = {'32bit' : 4, '64bit' : 8} + + def __init__(self): + self.maps = [] + self.get_new_page(0x1000) + self.names = [] + + @classmethod + def get_int_size(cls): + bits = platform.architecture()[0] + if bits not in cls.int_size: + raise ValueError("Unknow platform bits <{0}>".format(bits)) + return cls.int_size[bits] + + def get_new_page(self, size): + self.maps.append(MyMap.get_map(size)) + self.cur_offset = 0 + self.cur_page_size = size + + def reserve_size(self, size): + if size + self.cur_offset > self.cur_page_size: + self.get_new_page((payload_size + 0x1000) & ~0xfff) + addr = self.maps[-1].addr + self.cur_offset + self.cur_offset += size + return addr + + def reserve_int(self): + int_size = self.get_int_size() + return self.reserve_size(int_size) + + def write_code(self, code): + size = len(code) + if size + self.cur_offset > self.cur_page_size: + self.get_new_page((payload_size + 0x1000) & ~0xfff) + self.maps[-1][self.cur_offset: self.cur_offset + size] = code + addr = self.maps[-1].addr + self.cur_offset + self.cur_offset += size + return addr + +allocator = CustomAllocator() + + +def get_functions(): + # Windows only with python27.dll | improve this + import sys + + sys.path.append(r"C:\Users\hakril\Documents\Work\Python_Injection") + + import windows + PyGILState_Ensure = windows.get_func_addr('python27', 'PyGILState_Ensure') + PyObject_CallObject = windows.get_func_addr('python27', 'PyObject_CallObject') + PyGILState_Release = windows.get_func_addr('python27', 'PyGILState_Release') + return [PyGILState_Ensure, PyObject_CallObject, PyGILState_Release] + +def analyse_callback(callback): + if not callable(callback): + raise ValueError("Need a callable object :)") + obj_id = id(callback) + if not hasattr(callback, '_objects'): + raise ValueError("Need a ctypes PyCFuncPtr") + return obj_id + +from simple_x86 import * + +# For windows 32 bits with stdcall +def generate_stub(callback): + obj_id = analyse_callback(callback) + + c_callback = ctypes.c_ulong.from_address(id(callback._objects['0']) + 0xc).value + gstate_save_addr = allocator.reserve_int() + return_addr_save_addr = allocator.reserve_int() + + save_ebx = allocator.reserve_int() + save_ecx = allocator.reserve_int() + save_edx = allocator.reserve_int() + save_esi = allocator.reserve_int() + save_edi = allocator.reserve_int() + + ensure, objcall, release = get_functions() + + ### Shellcode ### + code = MultipleInstr() + + code += Mov_DX_EBX(save_ebx) + code += Mov_DX_ECX(save_ecx) + code += Mov_DX_EDX(save_edx) + code += Mov_DX_ESI(save_esi) + code += Mov_DX_EDI(save_edi) + + code += Mov_EAX_X(ensure) + code += Call_EAX() + code += Mov_DX_EAX(gstate_save_addr) + + #Save real return addr (for good argument parsing by the callback) + + code += Pop_EAX() + code += Mov_DX_EAX(return_addr_save_addr) + + # Set call_real_function to 0 (no call by default) + + code += Mov_EAX_X(c_callback) + code += Call_EAX() + + for i in range(len(callback.argtypes)): + code += Pop_EBX() + + # Restore real return value + code += Mov_EBX_DX(return_addr_save_addr) + code += Push_EBX() + + # Save return value + code += Push_EAX() + code += Mov_EBX_DX(gstate_save_addr) + code += Push_EBX() + + code += Mov_EAX_X(release) + code += Call_EAX() + + # Discard `release` argument + code += Pop_EAX() + # Restore return value + code += Pop_EAX() + code += Mov_EBX_DX(save_ebx) + code += Mov_ECX_DX(save_ecx) + code += Mov_EDX_DX(save_edx) + code += Mov_ESI_DX(save_esi) + code += Mov_EDI_DX(save_edi) + code += Ret() + return code + + +def generate_callback_stub(callback, types): + func_type = ctypes.CFUNCTYPE(*types) + c_callable = func_type(callback) + stub = generate_stub(c_callable) + stub_addr = allocator.write_code(stub.get_code()) + generate_callback_stub.l.append((stub, c_callable)) + return stub_addr + +generate_callback_stub.l = [] + +def create_function(code, types): + func_type = ctypes.CFUNCTYPE(*types) + addr = allocator.write_code(code) + return func_type(addr) + \ No newline at end of file diff --git a/native_exec/simple_x86.py b/native_exec/simple_x86.py new file mode 100644 index 0000000..7460ad1 --- /dev/null +++ b/native_exec/simple_x86.py @@ -0,0 +1,227 @@ +import struct +import sys + +this_module = sys.modules[__name__] + +def add_instruction(name, instruction): + setattr(this_module, name, instruction) + +reg_order = ['EAX', 'ECX', 'EDX', 'EBX', 'ESP', 'EBP', 'ESI', 'EDI'] +reg_opcode = {v : format(i, "03b") for i, v in enumerate(reg_order)} + + +class X86Instruction(object): + mnemo = "" + code = "" + biding = 0 + + def __init__(self, *bind_values): + if len(bind_values) != self.biding: + raise ValueError("{0} expect {1} values got {2}".format(self.__class__.__name__, self.biding, len(bind_values))) + self.bind_values = bind_values + for i, v in enumerate(bind_values): + if not isinstance(v, (int, long)): + raise ValueError("{0} bindings must be 'int' got '{1}' instead".format(self.__class__.__name__, type(v).__name__)) + if not 0 <= v <= 0xffffffff: + raise ValueError("{0} bindings must be between 0 and 0xffffffff".format(self.__class__.__name__)) + + def get_unbinded_code(self): + return self.code.replace(" ", "").decode('hex') + + def get_code(self): + code = self.get_unbinded_code() + for i in range(self.biding): + code = code.replace((str(i + 1) * 8).decode('hex'), struct.pack("".format(self.value, hex(self.addr)) + + # Good idea ? + class StringRVa(RVA): + @property + def str(self): + return ctypes.c_char_p(self.addr).value + + def __repr__(self): + return "".format(self.value, self.str) + + def __int__(self): + return self.value + + + class IATEntry(ctypes.Structure): + _fields_ = [ + ("value", DWORD)] + + @classmethod + def create(cls, addr, ord, name): + self = cls.from_address(addr) + self.addr = addr + self.ord = ord + self.name = name + self.hook = None + self.nonhookvalue = self.value + return self + + def __repr__(self): + return '<{0} "{1}" ordinal {2}>'.format(self.__class__.__name__, self.name, self.ord) + + def set_hook(self, callback, types=None): + import hooks # TODO: set import at the beginning + hook = hooks.IATHook(self, callback, types) + self.hook = hook + hook.enable() + return hook + + def remove_hook(self): + if self.hook is None: + return None + self.hook.disable() + self.hook = None + return True + + + + class IMPORT_DESCRIPTOR(ctypes.Structure): + _fields_ = [ + ("OriginalFirstThunk", RVA), + ("TimeDateStamp", DWORD), + ("ForwarderChain", DWORD), + ("Name", StringRVa), + ("FirstThunk", RVA)] + + + def get_INT(self): + if not self.OriginalFirstThunk.value: + return None + int_addr = self.OriginalFirstThunk.addr + int_entry = THUNK_DATA.from_address(int_addr) + res = [] + while int_entry.Ordinal: + if int_entry.Ordinal & IMAGE_ORDINAL_FLAG32: + res += [(int_entry.Ordinal & 0x7fffffff, None)] + else: + import_by_name = IMPORT_BY_NAME.from_address(baseaddr + int_entry.AddressOfData) + name = ctypes.c_char_p(ctypes.addressof(import_by_name) + IMPORT_BY_NAME.Name.offset).value + res.append((import_by_name.Hint, name)) + int_addr += ctypes.sizeof(THUNK_DATA) + int_entry = THUNK_DATA.from_address(int_addr) + return res + + + #def get_IAT(self): + # iat_addr = self.FirstThunk.addr + # iat_entry = THUNK_DATA.from_address(iat_addr) + # res = [] + # INT_iter = iter(self.get_INT()) + # while iat_entry.Ordinal: + # try: + # ordinal, name = next(INT_iter) #Should never StopIteration as IAT and INT are the same size + # except StopIteration: + # raise ValueError("Int shorter than IAT") + # res.append(IATEntry.create(iat_addr, ordinal, name)) + # iat_addr += ctypes.sizeof(THUNK_DATA) + # iat_entry = THUNK_DATA.from_address(iat_addr) + # return res + + def get_IAT(self): + iat_addr = self.FirstThunk.addr + iat_entry = THUNK_DATA.from_address(iat_addr) + res = [] + while iat_entry.Ordinal: + res.append(IATEntry.create(iat_addr, -1, "??")) + iat_addr += ctypes.sizeof(THUNK_DATA) + iat_entry = THUNK_DATA.from_address(iat_addr) + return res + + + + class IMPORT_BY_NAME(ctypes.Structure): + _fields_ = [ + ("Hint", WORD), + ("Name", BYTE) + ] + + class THUNK_DATA(ctypes.Union): + _fields_ = [ + ("Ordinal", DWORD), + ("AddressOfData", DWORD) + ] + + class IMAGE_EXPORT_DIRECTORY(ctypes.Structure): + _fields_ = [ + ("Characteristics", DWORD), + ("TimeDateStamp", DWORD), + ("MajorVersion", WORD), + ("MinorVersion", WORD), + ("Name", StringRVa), + ("Base", DWORD), + ("NumberOfFunctions", DWORD), + ("NumberOfNames", DWORD), + ("AddressOfFunctions", RVA), + ("AddressOfNames", RVA), + ("AddressOfNameOrdinals", RVA), + ] + + def get_exports(self): + NameOrdinals = (WORD * self.NumberOfNames).from_address(self.AddressOfNameOrdinals.addr) + NameOrdinals = list(NameOrdinals) + Functions = (RVA * self.NumberOfFunctions).from_address(self.AddressOfFunctions.addr) + Names = (StringRVa * self.NumberOfNames).from_address(self.AddressOfNames.addr) + res = [] + for nb,func in enumerate(Functions): + if nb in NameOrdinals: + name = Names[NameOrdinals.index(nb)] + else: + name = None + res.append((nb, func, name)) + return res + + return current_pe \ No newline at end of file diff --git a/remote_callback.py b/remote_callback.py new file mode 100644 index 0000000..979708f --- /dev/null +++ b/remote_callback.py @@ -0,0 +1,34 @@ +import ctypes +import ctypes.wintypes +from windows.hooks import * + + +@Callback(ctypes.c_ulong, ctypes.c_ulong) +def exit_callback(x, real_function): + print("Try to quit with {0} | {1}".format(x, type(x))) + if x == 3: + print("TRYING TO REAL EXIT") + return real_function(1234) + return 0 + +tt = False + +DWORD = ctypes.wintypes.DWORD + +@Callback(DWORD, DWORD , DWORD, DWORD, DWORD) +def valloc_callback(*args, **kwargs): + global tt + real_function = kwargs['real_function'] + print("Try to virtual alloc with {0}".format([hex(x) for x in args])) + tt = not tt + if tt: + return real_function() + return 0 + +@CreateFileACallback +def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function): + print("Trying to open {0}".format(lpFileName)) + if "dick" in lpFileName: + return 0x4242 + return real_function() + \ No newline at end of file diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..e818992 --- /dev/null +++ b/utils.py @@ -0,0 +1,85 @@ +import ctypes +import k32testing as kernel32proxy +import generated_def.windef as windef +import winobject +import copy +import native_exec +import generated_def.winstructs as winstructs + +# Function resolution ! + +def swallow_ctypes_copy(ctypes_object): + new_copy = type(ctypes_object)() + ctypes.memmove(ctypes.byref(new_copy), ctypes.byref(ctypes_object), ctypes.sizeof(new_copy)) + return new_copy + +def get_func_addr(dll_name, func_name): + dll = ctypes.WinDLL(dll_name) + return kernel32proxy.GetProcAddress(dll._handle, func_name) + +def enumerate_processes(): + process_entry = winobject.WinProcess() + #process_entry = winstructs.PROCESSENTRY32() + process_entry.dwSize = ctypes.sizeof(process_entry) + snap = kernel32proxy.CreateToolhelp32Snapshot(windef.TH32CS_SNAPPROCESS, 0) + kernel32proxy.Process32First(snap, process_entry) + res = [] + res.append(swallow_ctypes_copy(process_entry)) + while kernel32proxy.Process32Next(snap, process_entry): + res.append(swallow_ctypes_copy(process_entry)) + return res + +def enumerate_threads(): + thread_entry = winobject.WinThread() + thread_entry.dwSize = ctypes.sizeof(thread_entry) + snap = kernel32proxy.CreateToolhelp32Snapshot(windef.TH32CS_SNAPTHREAD, 0) + threads = [] + kernel32proxy.Thread32First(snap, thread_entry) + threads.append(copy.copy(thread_entry)) + while kernel32proxy.Thread32Next(snap, thread_entry): + threads.append(copy.copy(thread_entry)) + return threads + +class System(object): + + @property + def processes(self): + return enumerate_processes() + + @property + def threads(self): + return enumerate_threads() + +class CurrentProcess(object): + get_peb = None + + get_peb_32_code = '64a130000000c3'.decode('hex') + + def get_peb_builtin(self): + if self.get_peb is not None: + return self.get_peb + get_peb = native_exec.create_function(self.get_peb_32_code, [winstructs.PVOID]) + self.get_peb = get_peb + return get_peb + + @property + def peb(self): + return winobject.PEB.from_address(self.get_peb_builtin()()) + + +class VirtualProtected(object): + def __init__(self, addr, size, new_protect): + if (addr % 0x1000): + addr = addr - addr % 0x1000 + self.addr = addr + self.size = size + self.new_protect = new_protect + + def __enter__(self): + self.old_protect = winstructs.DWORD() + kernel32proxy.VirtualProtect(self.addr, self.size, self.new_protect, ctypes.byref(self.old_protect)) + return self + + def __exit__(self, exc_type, exc_value, traceback): + kernel32proxy.VirtualProtect(self.addr, self.size, self.old_protect.value, ctypes.byref(self.old_protect)) + return False \ No newline at end of file diff --git a/winobject.py b/winobject.py new file mode 100644 index 0000000..960e5ca --- /dev/null +++ b/winobject.py @@ -0,0 +1,148 @@ +import ctypes +import utils +import k32testing as kernel32proxy +import injection + +from generated_def.winstructs import * +import pe_parse + + +class AutoHandle(object): + def _get_handle(self): + raise NotImplementedError('_get_handle') + + @property + def handle(self): + if hasattr(self, "_handle"): + return self._handle + self._handle = self._get_handle() + return self._handle + + def __del__(self): + if hasattr(self, "_handle"): + kernel32proxy.CloseHandle(self._handle) + + +class WinThread(THREADENTRY32, AutoHandle): + @property + def tid(self): + return self.th32ThreadID + + @property + def owner(self): + if hasattr(self, "_owner"): + return self._owner + self._owner = [process for process in utils.enumerate_processes() if process.pid == self.th32OwnerProcessID][0] + return self._owner + + def _get_handle(self): + return kernel32proxy.OpenThread(dwThreadId=self.tid) + + def __repr__(self): + return '<{0} {1} owner "{2}" at {3}>'.format(self.__class__.__name__, self.tid, self.owner.name, hex(id(self))) + + +class WinProcess(PROCESSENTRY32, AutoHandle): + is_pythondll_injected = 0 + is_remote_slave_running = False + + @property + def name(self): + return self.szExeFile[:] + + @property + def pid(self): + return self.th32ProcessID + + @property + def threads(self): + return [thread for thread in utils.enumerate_threads() if thread.th32OwnerProcessID == self.pid] + + def _get_handle(self): + return kernel32proxy.OpenProcess(dwProcessId=self.pid) + + def __repr__(self): + return '<{0} "{1}" pid {2} at {3}>'.format(self.__class__.__name__, self.name, self.pid, hex(id(self))) + + def virtual_alloc(self, size): + return kernel32proxy.VirtualAllocEx(self.handle, dwSize=size) + + def write_memory(self, addr, data): + return kernel32proxy.WriteProcessMemory(self.handle, addr, lpBuffer=data) + + def read_memory(self, addr, size): + return kernel32proxy.ReadProcessMemory(self.handle, addr, nSize=size) + + def create_thread(self, addr, param): + return kernel32proxy.CreateRemoteThread(hProcess=self.handle, lpStartAddress=addr, lpParameter=param) + + def load_library(self, dll_path): + x = self.virtual_alloc(0x1000) + self.write_memory(x, dll_path) + LoadLibrary = utils.get_func_addr('kernel32', 'LoadLibraryA') + return self.create_thread(LoadLibrary, x) + + def execute(self, code): + x = self.virtual_alloc(len(code)) + self.write_memory(x, code) + return self.create_thread(x, 0) + + def get_remote_python(self): + return injection.launch_remote_slave(self) + + +class LoadedModule(LDR_DATA_TABLE_ENTRY): + + @property + def baseaddr(self): + return self.DllBase + + @property + def name(self): + return self.BaseDllName.Buffer + + @property + def fullname(self): + return self.FullDllName.Buffer + + def __repr__(self): + return '<{0} "{1}" at {2}>'.format(self.__class__.__name__, self.name, hex(id(self))) + + @property + def pe(self): + return pe_parse.PEFile(self.baseaddr) + +class WinUnicodeString(LSA_UNICODE_STRING): + def __repr__(self): + return """<{0} "{1}" at {2}>""".format(type(self).__name__, self.Buffer, hex(id(self))) + + +class LIST_ENTRY_PTR(PVOID): + def TO_LDR_ENTRY(self): + return LDR_DATA_TABLE_ENTRY.from_address(self.value - sizeof(PVOID) * 2) + + +# May want to have all known fields.. +class PEB(PEB): + + @property + def imagepath(self): + raw_imagepath = self.ProcessParameters.contents.ImagePathName + return WinUnicodeString.from_address(ctypes.addressof(raw_imagepath)) + + @property + def commandline(self): + # This or changing the __repr__ of LSA_UNICODE_STRING + raw_cmd = self.ProcessParameters.contents.CommandLine + return WinUnicodeString.from_address(ctypes.addressof(raw_cmd)) + @property + + def modules(self): + res = [] + list_entry_ptr = ctypes.cast(self.Ldr.contents.InMemoryOrderModuleList.Flink, LIST_ENTRY_PTR) + current_dll = list_entry_ptr.TO_LDR_ENTRY() + while current_dll.DllBase: + res.append(current_dll) + list_entry_ptr = ctypes.cast(current_dll.InMemoryOrderLinks.Flink, LIST_ENTRY_PTR) + current_dll = list_entry_ptr.TO_LDR_ENTRY() + return [LoadedModule.from_address(addressof(LDR)) for LDR in res] \ No newline at end of file