def open_debug(self, dw_process_id): """ Open a process from its dwProcessId with the desired access This function put the process into debug mode, wich allows to read/write memory. This method first grab security information from the curent process, then we open the specified process with previous security information. __usage__ wow_process = p.open(8992, PROCESS_CLASS.ALL) """ process = OPEN_PROCESS(0x00040000, 0, dw_process_id) info = GetSecurityInfo(GetCurrentProcess(), 6, 0) SetSecurityInfo(process, 6, \ win32security.DACL_SECURITY_INFORMATION |\ win32security.UNPROTECTED_DACL_SECURITY_INFORMATION,\ None,\ None,\ info.GetSecurityDescriptorDacl(),\ info.GetSecurityDescriptorGroup()) CLOSE_HANDLE(process) self.h_process = OPEN_PROCESS(PROCESS_CLASS.ALL, 0, dw_process_id) if self.h_process: self.is_process_open = True self.process32 = process32_from_id(dw_process_id) return True return False
def logoff_and_shutdown(): shutdown_privilege = ((LookupPrivilegeValue(None, SE_SHUTDOWN_NAME), SE_PRIVILEGE_ENABLED), ) token_handle = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY) AdjustTokenPrivileges(token_handle, 0, shutdown_privilege) ExitWindowsEx(EWX_LOGOFF | EWX_SHUTDOWN | EWX_FORCE, 0)
def update(self): process_handle = GetCurrentProcess() meminfo = GetProcessMemoryInfo(process_handle) memstatus = GlobalMemoryStatusEx() self.vsz = memstatus['TotalVirtual'] - memstatus['AvailVirtual'] self.rss = meminfo['WorkingSetSize'] self.pagefaults = meminfo['PageFaultCount'] return True
def _get_current_sid(): """INTERNAL: get current SID.""" try: token = OpenThreadToken(GetCurrentThread(), MAXIMUM_ALLOWED, True) except WindowsError: token = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED) sid = GetTokenInformation(token, TokenUser)[0] return sid
def adjust_windows_shutdown_privileges(self): if not windows_check(): log.error("Only usable on Windows platform") return flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY htoken = OpenProcessToken(GetCurrentProcess(), flags) id = LookupPrivilegeValue(None, SE_SHUTDOWN_NAME) newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] AdjustTokenPrivileges(htoken, 0, newPrivileges)
def __init__(self, dParams): PlatformBase.__init__(self, dParams) # # Since the code runs on all platforms, we have to do a lot of # importing here instead of at the top of the file where it's normally located. # from win32com import universal from win32com.client import gencache, DispatchBaseClass from win32com.client import constants, getevents import win32com import pythoncom import win32api import winerror from win32con import DUPLICATE_SAME_ACCESS from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess import threading self.winerror = winerror pid = GetCurrentProcess() self.tid = GetCurrentThreadId() handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS) self.handles = [] self.handles.append(handle) # Hack the COM dispatcher base class so we can modify method and # attribute names to match those in xpcom. if _g_dCOMForward['setattr'] is None: _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__[ '__getattr__'] _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__[ '__setattr__'] setattr(DispatchBaseClass, '__getattr__', _CustomGetAttr) setattr(DispatchBaseClass, '__setattr__', _CustomSetAttr) # Hack the exception base class so the users doesn't need to check for # XPCOM or COM and do different things. ## @todo # # Make sure the gencache is correct (we don't quite follow the COM # versioning rules). # self.flushGenPyCache(win32com.client.gencache) win32com.client.gencache.EnsureDispatch('VirtualBox.Session') win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBoxClient') self.oIntCv = threading.Condition() self.fInterrupted = False _ = dParams
def parent(): print("parent started", os.getpid()) job = CreateJobObject(None, "my-first-job") AssignProcessToJobObject(job, GetCurrentProcess()) for i in range(3): subprocess.Popen("python main.py /child") raw_input("press any key to kill all child processes:") try: job_processes = QueryInformationJobObject(None, JobObjectBasicProcessIdList) for pid in job_processes: if pid == os.getpid(): # Don't kill ourselves continue child_handle = OpenProcess(PROCESS_TERMINATE, True, pid) TerminateProcess(child_handle, 1) print("Killed", pid) except pywintypes.error: # Only here to demonstrate what exception is raised. raise
def __init__(self, params): from win32com import universal from win32com.client import gencache, DispatchBaseClass from win32com.client import constants, getevents import win32com import pythoncom import win32api from win32con import DUPLICATE_SAME_ACCESS from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess import threading pid = GetCurrentProcess() self.tid = GetCurrentThreadId() handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS) self.handles = [] self.handles.append(handle) _COMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__'] DispatchBaseClass.__getattr__ = CustomGetAttr _COMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__'] DispatchBaseClass.__setattr__ = CustomSetAttr win32com.client.gencache.EnsureDispatch('VirtualBox.Session') win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') self.oIntCv = threading.Condition() self.fInterrupted = False
def __init__(self, dParams): PlatformBase.__init__(self, dParams) # # Since the code runs on all platforms, we have to do a lot of # importing here instead of at the top of the file where it's normally located. # from win32com import universal from win32com.client import gencache, DispatchBaseClass from win32com.client import constants, getevents import win32com import pythoncom import win32api import winerror from win32con import DUPLICATE_SAME_ACCESS from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess import threading self.winerror = winerror # Setup client impersonation in COM calls. try: pythoncom.CoInitializeSecurity(None, None, None, pythoncom.RPC_C_AUTHN_LEVEL_DEFAULT, pythoncom.RPC_C_IMP_LEVEL_IMPERSONATE, None, pythoncom.EOAC_NONE, None) except: _, oXcpt, _ = sys.exc_info(); if isinstance(oXcpt, pythoncom.com_error) and self.xcptGetStatus(oXcpt) == -2147417831: # RPC_E_TOO_LATE print("Warning: CoInitializeSecurity was already called"); else: print("Warning: CoInitializeSecurity failed: ", oXctp); # Remember this thread ID and get its handle so we can wait on it in waitForEvents(). self.tid = GetCurrentThreadId() pid = GetCurrentProcess() self.aoHandles = [DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS),]; # type: list[PyHANDLE] # Hack the COM dispatcher base class so we can modify method and # attribute names to match those in xpcom. if _g_dCOMForward['setattr'] is None: _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__'] _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__'] setattr(DispatchBaseClass, '__getattr__', _CustomGetAttr) setattr(DispatchBaseClass, '__setattr__', _CustomSetAttr) # Hack the exception base class so the users doesn't need to check for # XPCOM or COM and do different things. ## @todo # # Make sure the gencache is correct (we don't quite follow the COM # versioning rules). # self.flushGenPyCache(win32com.client.gencache) win32com.client.gencache.EnsureDispatch('VirtualBox.Session') win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBoxClient') self.oClient = None ##< instance of client used to support lifetime of VBoxSDS self.oIntCv = threading.Condition() self.fInterrupted = False _ = dParams
def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS)
def is_posix(): return os.name == "posix" # #This script assumes dll is already registered with system working on check #and routine to install #set some constants that we will use mymsgDLL = "C:\\Program Files (x86)\\Artillery\\src\\windows\\ArtilleryEvents.dll" AppName = "Artillery" data = "Application\0Data".encode("ascii") #category is always one for now category = 1 process = GetCurrentProcess() token = OpenProcessToken(process, TOKEN_READ) my_sid = GetTokenInformation(token, TokenUser)[0] myType = win32evtlog.EVENTLOG_INFORMATION_TYPE #Left this here for reference #ReportEvent(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None): # #below are as defined in the "dll" look @ included .mc file for message contents # #descr = 'ARTILLERY_START' def ArtilleryStartEvent(): eventID = 100 ReportEvent(AppName, eventID,
from win32security import OpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivileges, SE_DEBUG_NAME from win32process import GetWindowThreadProcessId from ctypes import c_ulong, c_long, c_ubyte, byref, windll import sys import array # Get the ReadProcessMemory function ReadProcessMemory = windll.kernel32.ReadProcessMemory # Constants CONNECTION_PTR_OFFSET = 0x01139F94 SESSIONKEY_OFFSET = 0x508 SESSIONKEY_LENGTH = 40 # Adjust current process privileges hToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY) luid = LookupPrivilegeValue(None, SE_DEBUG_NAME) AdjustTokenPrivileges(hToken, False, [(luid, SE_PRIVILEGE_ENABLED)]) CloseHandle(hToken) # Get an handle on wow windowHandle = FindWindow(None, 'World of Warcraft') if not windowHandle: print('ERROR : Unable to find WoW window') sys.exit(0) threadID, processID = GetWindowThreadProcessId(windowHandle) wowHandle = OpenProcess(PROCESS_VM_READ, False, processID) # Get a pointer to the sessionkey