def normalpriority(): """ Set the priority of the process to below-normal.""" if sys.platform == 'win32': # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ try: import win32api import win32process import win32con except ImportError as e: warnings.warn("Could not set process priority: %s" % e) return pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.NORMAL_PRIORITY_CLASS) else: import os # Reset nice to 0 os.nice(-os.nice(0))
def LowerPriority(): """ Platform dependent method to lower the priority of the running process. """ try: sys.getwindowsversion() # @UndefinedVariable except: isWindows = False else: isWindows = True if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ import win32api # @UnresolvedImport import win32process # @UnresolvedImport import win32con # @UnresolvedImport pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) else: import os os.nice(20)
def kill_process_by_name(name): """Find and kill all processes containing a certain name""" pids = get_pids(name) if sys.platform == 'win32': for p in pids: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) #get process handle win32api.TerminateProcess(handle, 0) #kill by handle win32api.CloseHandle(handle) #close api else: for pid in pids: os.kill(pid, signal.SIGTERM) sleep(.5) if len(get_pids(name)) is not 0: try: os.kill(pid, signal.SIGKILL) except OSError: pass sleep(.5) if len(get_pids(name)) is not 0: logger.error('Could not kill process')
def get_process_privileges(pid): try: # 対象のプロセスへのハンドルを取得 hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) # メインのプロセストークンを開く htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) # 有効化されている権限のリストを取得 privs = win32security.GetTokenInformation(htok, win32security, TokenPrivileges) # 権限をチェックして、有効化されているものだけを出力するループ priv_lsit = "" for i in privs: # 権限が有効化されているかチェック if i[1] == 3: priv_lsit += "%s|" % win32security.LookupPrivilegeName( None, i[0]) except: priv_lsit = "N/A" return priv_lsit
def ReadProcessMemory(ProcessID, rules): base = 0 memory_basic_information = MEMORY_BASIC_INFORMATION() AdjustPrivilege("seDebugPrivilege") pHandle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ | win32con.PROCESS_VM_OPERATION , 0, ProcessID) while VIRTUALQUERYEX(pHandle.handle, base, byref(memory_basic_information), sizeof(memory_basic_information)) > 0: count = c_ulong(0) #MEM_COMMIT && MEM_PRIVATE #if memory_basic_information.State == 0x1000 and memory_basic_information.Type == 0x20000: try: buff = create_string_buffer(memory_basic_information.RegionSize) if READ_PROCESS_MEMORY(pHandle.handle, base, buff, memory_basic_information.RegionSize, byref(count)): #print buff.raw matches = rules.match(data=buff.raw) for m in matches: print m, "0x%x" % memory_basic_information.BaseAddress except: pass base += memory_basic_information.RegionSize win32api.CloseHandle(pHandle)
def get_process_privileges(pid): try: # obtain a handle to the target process hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) # open the main process token htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) # retrieve the list of privileges enabled privs = win32security.GetTokenInformation( htok, win32security.TokenPrivileges) # iterate over privileges and output the ones that are enabled priv_list = "" for i in privs: # check if the privilege is enabled if i[1] == 3: priv_list += "%s|" % win32security.LookupPrivilegeName( None, i[0]) except: priv_list = get_process_privileges(pid) return priv_list
def processExists(uPid): """ Checks if the specified process exits. This will only work if we can signal/open the process. Returns True if it positively exists, False otherwise. """ if sys.platform == 'win32': fRc = False try: hProcess = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, uPid) except: pass else: win32api.CloseHandle(hProcess) fRc = True else: try: os.kill(uPid, 0) fRc = True except: fRc = False return fRc
def kill_old_process(): """ Kills or brings to the foreground (if possible) any other instance of this program. It avoids multiple icons in the Tray on Windows. On OSX, we don't have to do anything: icons don't get duplicated. """ # Is there another Agent Manager process running ? pidfile = PidFile('agent-manager-gui').get_path() old_pid = None try: pf = file(pidfile, 'r') old_pid = int(pf.read().strip()) pf.close() except (IOError, ValueError): pass if old_pid is not None and pid_exists(old_pid): handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, old_pid) exe_path = win32process.GetModuleFileNameEx(handle, 0) # If (and only if) this process is indeed an instance of the GUI, let's kill it if 'agent-manager.exe' in exe_path: win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) # If we reached that point it means the current process should be the only running # agent-manager.exe, let's save its pid pid = str(os.getpid()) try: with open(pidfile, 'w+') as fp: fp.write(str(pid)) except Exception, e: msg = "Unable to write pidfile: %s %s" % (pidfile, str(e)) log.exception(msg) sys.stderr.write(msg + "\n") sys.exit(1)
def SvcDoRun(self): import servicemanager servicemanager.LogInfoMsg(self._svc_name_ + " Start Requested") try: hJob = win32job.CreateJobObject(None, "") extended_info = win32job.QueryInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation) extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE win32job.SetInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation, extended_info) command = "resilient-circuits.exe run " + self._resilient_args_ command_args = shlex.split(command) self.process_handle = subprocess.Popen(command_args) # Convert process id to process handle: perms = win32con.PROCESS_TERMINATE | win32con.PROCESS_SET_QUOTA hProcess = win32api.OpenProcess(perms, False, self.process_handle.pid) win32job.AssignProcessToJobObject(hJob, hProcess) except: servicemanager.LogErrorMsg(self._svc_name_ + " failed to launch resilient-circuits.exe") raise servicemanager.LogInfoMsg(self._svc_name_ + " Started") while self.isAlive: if self.process_handle.poll() != None: self.SvcStop() win32api.SleepEx(10000, True)
def get_process_privileges(pid): try: # Obtain a handle to the target process hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) # Open the main process token htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) # Retrieve the list of privileges enabled privs = win32security.GetTokenInformation( htok, win32security.TokenPrivileges) # Iterate over privileges and output the ones that are enabled priv_list = [] for priv_id, priv_flags in privs: # Check if the privilege is enabled if priv_flags == 3: priv_list.append( win32security.LookupPrivilegeName(None, priv_id)) except: priv_list.append("N/A") return "|".join(priv_list)
def get_process_privs(pid): try: # Obtain a handle to target process hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) # Open the main process token htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) # Retrieve list of privs privs = win32security.GetTokenInformation( htok, win32security.TokenPrivileges) # Iterate over list of privs, output enabled priv_list = "" for i in privs: if i[1] == 3: priv_list += "%s|" % win32security.LookupPrivilegeName( None, i[0]) except: priv_list = "N/A" return priv_list
def get_process_privileges(pid): try: # 获取目标句柄 hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) # 打开主进程令牌 htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) # 解析已启用权限的列表 privs = win32security.GetTokenInformation( htok, win32security.TokenPrivileges) # 迭代每个权限并输出其中已经启用的 priv_list = "" for i in privs: # 检测权限是否已经启用 if i[1] == 3: priv_list += "%s|" % win32security.LookupPrivilegeName( None, i[0]) except: priv_list = "N/A" return priv_list
def get_by_name(cls, process_name: str) -> "Process": """Finds a process by name and returns a Process object.""" for process_id in win32process.EnumProcesses(): # If process_id is the same as this program, skip it if process_id == -1: continue handle = None # Try to read the process memory try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, True, process_id) except: continue else: # iterate over an array of base addresses of each module for base_address in win32process.EnumProcessModules(handle): # Get the name of the module current_name = str( win32process.GetModuleFileNameEx(handle, base_address)) # compare it if process_name.casefold() in current_name.casefold(): logging.debug( f"Base address of {process_name} ({process_id}): {hex(base_address)}" ) return cls(process_id, process_name, base_address) finally: if handle: # close the handle as we don't need it anymore win32api.CloseHandle(handle) raise Exception(f"{process_name} could not be found.")
def grab_reward_from_memory(self, window_handle=None, memory_address=0x0053B644): """ 根据窗口的句柄,和进程的内存地址,读出地址的值 :param window_handle: 窗口的句柄 :param memory_address: 内存地址 :return: 地址的值 """ # 获取窗口进程(线程[0]和进程[1]) process_id = win32process.GetWindowThreadProcessId(window_handle)[1] #print(f"窗口句柄是{window_handle}, 窗口的进程pid是{process_id}") # 获取进程的句柄,在0x1F0FFF处循环遍历,False句柄不被子进程继承 process_handle = win32api.OpenProcess(0x1F0FFF, False, process_id) # 读出内核 kernel32 = ctypes.windll.LoadLibrary( r"C:\Windows\System32\kernel32.dll") # 转换数据类型为C long,ctypes.byref作为缓存区处理不兼容问题,4个字节长度,(None数据尺寸?) memory_data = ctypes.c_long() kernel32.ReadProcessMemory(int(process_handle), memory_address, ctypes.byref(memory_data), 4, None) print(f"当前的得分是{memory_data.value}") return memory_data.value
def create_mini_dump(self): file_name = self.generate_file_name() if os.path.isfile(file_name): os.remove(file_name) # Adjust privileges. self.adjust_privilege(win32security.SE_DEBUG_NAME) process_handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, self.pid) print('process_handle Status: ', win32api.FormatMessage(win32api.GetLastError())) file_handle = win32file.CreateFile( file_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) print('file_handle Status: ', win32api.FormatMessage(win32api.GetLastError())) mini_dump = MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithDataSegs full_info_dump = (mini_dump | MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory | MiniDumpWithFullMemory) success = dbghelp.MiniDumpWriteDump( process_handle.handle, # Process handle self.pid, # Process ID file_handle.handle, # File handle full_info_dump, # Dump type - MiniDumpNormal None, # Exception parameter None, # User stream parameter None, # Callback parameter ) print('MiniDump Status: ', win32api.FormatMessage(win32api.GetLastError())) win32file.CloseHandle(file_handle) return self.zip_and_delete_file(file_name)
def get_process_privileges(pid): try: #OBTAIN A HANDLE TO THE TARGET hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) #OPRN THE MAIN PROCESS TOKEN htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) #RETRIEVE THE LIST OF PRIVLEGES ENABLED privs = win32security.GetTokenInformation( htok, win32security.TokenPrivileges) #ITERATE OVER PRIVELEGES AND OUTPUT THE ENABLED priv_list = "" for i in privs: #CHECK IF PRIVILEGE IS ENABLED if i[1] == 3: priv_list += "%s|" % win32security.LookupPrivilegeName( None, i[0]) except: priv_list = "N/A" return priv_list
def highpriority(): """ Set the priority of the process to below-normal.""" import sys try: sys.getwindowsversion() except AttributeError: isWindows = False else: isWindows = True if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ import win32api, win32process, win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.HIGH_PRIORITY_CLASS) else: import os os.nice(1)
def KillPID(self): """ Kill VNC instance, called by the Stop Button or Application ends. @author: Derek Buranen @author: Aaron Gerber """ if self.returnPID != 0: print "Processes.KillPID(" + str(self.returnPID) + ")" if sys.platform == 'win32': import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, self.returnPID.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) elif re.match('(?:open|free|net)bsd|linux',sys.platform): # New processes are created when you made connections. So if you kill self.returnPID, # you're just killing the dispatch process, not the one actually doing business... os.spawnlp(os.P_NOWAIT, 'pkill', 'pkill', '-f', 'vncviewer') os.spawnlp(os.P_NOWAIT, 'pkill', 'pkill', '-f', 'x11vnc') else: os.kill(self.returnPID, signal.SIGKILL) self.returnPID = 0 return
def pid_running(pid): """Return True if we know if process with pid is currently running, False if it isn't running, and None if we don't know for sure.""" if os.name == 'nt': import win32api import win32con import pywintypes process = None try: process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) except pywintypes.error as error: if error[0] == 87: return False else: msg = "Warning: unable to check if PID %d still running" log.Log(msg % pid, 2) return None # we don't know if the process is running else: if process: win32api.CloseHandle(process) return True else: return False else: try: os.kill(pid, 0) except ProcessLookupError: # errno.ESRCH - pid doesn't exist return False except OSError: # any other OS error log.Log( "Warning: unable to check if PID %d still running" % (pid, ), 2) return None # we don't know if the process is still running else: # the process still exists return True
def executable_for_unelevated_window(window_handle): # Get window's process ID: tid, pid = win32process.GetWindowThreadProcessId(window_handle) # Get the process handle of this window's process ID. # (auto closed on garbage collection) try: process_handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid) except: return "" if not process_handle: return "" try: # This doesn't work for 64 bit applications: executable_path = win32process.GetModuleFileNameEx(process_handle, 0) except: Psapi = ctypes.WinDLL('Psapi.dll') GetProcessImageFileName = Psapi.GetProcessImageFileNameA GetProcessImageFileName.restype = ctypes.wintypes.DWORD MAX_PATH = 260 # Windows pathname limit for non-Unicode calls ImageFileName = (ctypes.c_char*MAX_PATH)() size = GetProcessImageFileName(process_handle.handle, ImageFileName, MAX_PATH) if size == 0: raise ctypes.WinError() return "" executable_path = ImageFileName.value[0: size] filename = os.path.basename(executable_path) # at this point we have Unicode so... return filename.encode("windows-1252", 'xmlcharrefreplace')
def DumpProcess(ProcessID, rules): AdjustPrivilege("seDebugPrivilege") # PROCESS_ALL_ACCESS try: pHandle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, ProcessID) except pywintypes.error as err: print(f"...{err}") return fHandle = win32file.CreateFile( "%d.tmp" % ProcessID, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None, ) ret = MINI_DUMP_WRITER(pHandle.handle, ProcessID, fHandle.handle, MINIDUMP_TYPES_CLASS.MiniDumpWithFullMemory, None, None, None) win32api.CloseHandle(pHandle) win32api.CloseHandle(fHandle) matches = None try: matches = rules.match("%d.tmp" % ProcessID) except: pass if matches: for m in matches: print(f"[+] {ProcessID} Matched:", m) os.remove("%d.tmp" % ProcessID)
# Create a process that won't end on its own import subprocess process = subprocess.Popen(['python.exe', '-c', 'while 1: pass']) # Kill the process using pywin32 import win32api win32api.TerminateProcess(int(process._handle), -1) # Kill the process using ctypes import ctypes ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1) # Kill the proces using pywin32 and pid import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) # Kill the proces using ctypes and pid import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle)
# handle error messages except Exception, e: if verbose == True: print e pass # if the attacker specifies a command shell lets get it ready if data == "ps": try: # if we're running windows then use win32process to enumerate if operating_system == "windows": processes = win32process.EnumProcesses() data = "" for pid in processes: try: handle = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS, False, pid) exe = win32process.GetModuleFileNameEx( handle, 0) data += exe + " PID:" + str(pid) + "\r\n" except: pass # if we're running linux then run subprocess ps -aux to enumerate if operating_system == "posix": # send our command that would be 'data' proc = subprocess.Popen("ps -ax", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
def kill(self): import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, self.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle)
def oncommandfromserver(self,command,args,socket): try: if command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!enable" and args[0] in self.app.admins: self.disabled = False socket.send("MYSTATUS %i\n" % int(int(self.listfull)+int(self.disabled)*2)) socket.send("SAYPRIVATE %s %s\n" % (args[0],"Hosting new games enabled")) self.app.config.set('autohost', "enabled", "1") self.app.SaveConfig() elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!disable" and args[0] in self.app.admins: self.disabled = True socket.send("MYSTATUS %i\n" % int(int(self.listfull)+int(self.disabled)*2)) socket.send("SAYPRIVATE %s %s\n" % (args[0],"Hosting new games disabled")) self.app.config.set('autohost', "enabled", "0") self.app.SaveConfig() elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!listbans" and args[0] in self.app.admins: x = 0 l0 = [] for b in self.bans: l0.append(b) x += 1 if x >= 5: socket.send("SAYPRIVATE %s %s\n" % (args[0],' | '.join(l0))) x = 0 l0 = [] socket.send("SAYPRIVATE %s %s\n" % (args[0],' | '.join(l0))) elif command == "SAIDPRIVATE" and len(args) >= 3 and args[1] == "!ban" and args[0] in self.app.admins: toban = args[2:] for b in toban: if not b in self.bans: self.bans.append(b) socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" Banned")) else: socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" is already banned")) self.app.config.set('autohost', "bans", ','.join(self.bans)) self.app.SaveConfig() socket.send("SAYPRIVATE %s %s\n" % (args[0],"Done.")) elif command == "SAIDPRIVATE" and len(args) >= 3 and args[1] == "!unban" and args[0] in self.app.admins: toban = args[2:] for b in toban: if not b in self.bans: socket.send("SAYPRIVATE %s %s\n" % (args[0],b+"is not currently banned")) else: self.bans.remove(b) socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" has been unbanned")) self.app.config.set('autohost', "bans", ','.join(self.bans)) self.app.SaveConfig() socket.send("SAYPRIVATE %s %s\n" % (args[0],"Done.")) elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!registerall" and args[0] in self.app.admins: for b in self.botstatus: if not self.botstatus[b]: slot = b self.threads.append(thread.start_new_thread(self.botthread,(slot,self.an[slot],socket,args[0],self.ap,self))) self.botstatus[slot] = True time.sleep(1) if b + 1 == len(self.botstatus): # The bot spawned was the last one self.listfull = True socket.send("MYSTATUS 1\n") elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!spawn" and args[0] not in self.ul and not self.disabled: if args[0] in self.bans: socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: You are banned!")) return freeslot = False slot = 0 for b in self.botstatus: if not self.botstatus[b]: freeslot = True slot = b break if freeslot: self.threads.append(thread.start_new_thread(self.botthread,(slot,self.an[slot],socket,args[0],self.ap,self))) socket.send("SAYPRIVATE %s %s\n" %(args[0],self.an[slot])) self.ul.append(args[0]) self.botstatus[slot] = True if b + 1 == len(self.botstatus): # The bot spawned was the last one self.listfull = True socket.send("MYSTATUS 1\n") else: socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: All bots are spawned")) #elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!spawn" and len(self.ul) >= len(self.an): # socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: All bots are spawned")) #elif command == "SAIDPRIVATE" and len(args) >= 1 and : # socket.send("SAYPRIVATE %s %s\n" %(args[0],"\002")) elif command == "LEFT" and args[0] == "autohost" and len(args) > 4 and args[3] == "inconsistent" and args[1] in self.bots: self.say_ah("Bot(%s) kicked by inconsistent data error , killing" % args[1]) try: if platform.system() == "Windows": handle = win32api.OpenProcess(1, 0, self.bots[args[1]]) win32api.TerminateProcess(handle, 0) else: os.kill(self.bots[args[1]],signal.SIGKILL) except Exception, e: Log.exception(e) except Exception, e: exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) self.sayex_ah("*** EXCEPTION: BEGIN") for line in exc: self.sayex_ah(line) self.sayex_ah("*** EXCEPTION: END") Log.exception(e)
def start(self): self._hPid = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 0, self.pid) self._lastValues = None return BaseProcessMonitor.start(self)
('y', c_int), ] class StructPointerTest(Structure): _fields_ = [('x', c_int), ('y', c_int), ('z', Pointer), ('a', POINTER(Pointer1)), ] if __name__ == '__main__': Advapi32 = windll.LoadLibrary("Advapi32") hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, win32api.GetCurrentProcessId()); hToken = win32security.OpenProcessToken(hProcess, win32con.TOKEN_ADJUST_PRIVILEGES) value = apiprocess.LookupPrivilegeValue("", win32con.SE_DEBUG_NAME) la = apiprocess.LUID_AND_ATTRIBUTES(value, win32con.SE_PRIVILEGE_ENABLED) tpIn = apiprocess.TOKEN_PRIVILEGES(1, la) tpOut = apiprocess.TOKEN_PRIVILEGES() print dir(hToken), pointer(tpIn) Advapi32.LookupPrivilegeNameA.argtypes = [c_ulong, c_bool, POINTER(apiprocess.TOKEN_PRIVILEGES), c_ulong, POINTER(apiprocess.TOKEN_PRIVILEGES), c_ulong] Advapi32.LookupPrivilegeNameA(240, 0, pointer(tpIn), sizeof(tpIn), pointer(tpOut), sizeof(tpOut)) # lib.test.restype = PO1INTER(StructPointer) # p = lib.test() # print p.contents.x # p = Pointer(1, 2) # p1 = Pointer1(1, 2)
import psutil import pywintypes import win32api def getpid(): for proc in psutil.process_iter(): if proc.name() == "UnityPlayer.dll": return proc.pid my_pid = getpid() PROCESS_ALL_ACCESS = 0x1F0FFF processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, my_pid) modules = win32process.EnumProcessModules(processHandle) processHandle.close() base_addr = modules[0] # for me it worked to select the first item in list...
seen = set() seen_add = seen.add proc_ids.sort() return [ x for x in proc_ids if x not in seen and not seen_add(x)] if __name__ == "__main__": priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), priv_flags) # enable "debug process" privilege_id = win32security.LookupPrivilegeValue (None,win32security.SE_DEBUG_NAME) old_privs = win32security.AdjustTokenPrivileges (hToken, 0,[(privilege_id, win32security.SE_PRIVILEGE_ENABLED)]) _result = [] for proc in procids(): #print proc[1] # 0 -> SYSTEM IDLE # 4 -> SYSTEM PROCESS try: pshandle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, int(proc[1])) exename = win32process.GetModuleFileNameEx(pshandle, 0) _result.append(exename) # clean up win32api.CloseHandle(pshandle) except: pass win32api.CloseHandle(hToken) result = set()
win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_CHANGE_NOTIFY_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_DEBUG_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_PROF_SINGLE_PROCESS_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_SYSTEM_PROFILE_NAME), win32con.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue('', win32security.SE_LOCK_MEMORY_NAME), win32con.SE_PRIVILEGE_ENABLED) ) all_info = win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | \ win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION pid = win32api.GetCurrentProcessId() ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) ## PROCESS_ALL_ACCESS does not contain ACCESS_SYSTEM_SECURITY (neccessy to do SACLs) th = win32security.OpenProcessToken(ph, win32security.TOKEN_ALL_ACCESS) ##win32con.TOKEN_ADJUST_PRIVILEGES) old_privs = win32security.AdjustTokenPrivileges(th, 0, new_privs) my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] pwr_sid = win32security.LookupAccountName('', 'Power Users')[0] ## reopen process with ACCESS_SYSTEM_SECURITY now that sufficent privs are enabled ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS | win32con.ACCESS_SYSTEM_SECURITY, 0, pid) sd = win32security.GetKernelObjectSecurity(ph, all_info) dacl = sd.GetSecurityDescriptorDacl() if dacl is None: dacl = win32security.ACL() sacl = sd.GetSecurityDescriptorSacl() if sacl is None: sacl = win32security.ACL()