def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-loop (and printing output) # thread can keep up import win32process win32process.SetThreadPriority( win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL ) try: while 1: rc = win32event.WaitForMultipleObjects( (handle, stopEvent), 0, win32event.INFINITE ) if rc == win32event.WAIT_OBJECT_0: # About the only char we can't live with is \0! file.write(win32trace.read().replace("\0", "<null>")) else: # Stop event break finally: win32trace.TermRead() print("Thread dieing")
def from_thread(cls, access=constants.GENERAL.MAXIMUM_ALLOWED): hProcess = win32api.GetCurrentProcess() hThread = win32api.GetCurrentThread() try: return cls(wrapped(win32security.OpenThreadToken, hThread, access, True), hProcess, hThread) except x_no_token: return cls(wrapped(win32security.OpenProcessToken, hProcess, access), hProcess, hThread)
def __init__(self): self._my_win = None self.is_initialized = False self._attributes_dict = { 'Units': 'deg', 'Color': dict(r=1, g=1, b=1), 'Direction': 270, 'NumberOfDots': 500, 'FieldShape': 'circle', 'FieldPosition': dict(x=0.0, y=0), 'FieldSize': 1, 'DotLife': 5, # number of frames for each dot to be drawn 'SignalDots': 'same', # are the signal dots the 'same' on each frame? (see Scase et al) 'NoiseDots': 'direction', # do the noise dots follow random- 'walk', 'direction', or 'position' 'Speed': 0.01, 'Coherence': 0.9, 'RenderTime': 1, 'RenderFrequency': 60 } self.data = None # type: Dict[String, Any] self.experiment_data = None # type: ExperimentData win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_HIGHEST) pass
def setPriority(self, pid=None, priority=2): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ import win32api, win32process, win32con priorityClasses = [ win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS ] threadPriorities = [ win32process.THREAD_PRIORITY_IDLE, #win32process.THREAD_PRIORITY_ABOVE_IDLE, #win32process.THREAD_PRIORITY_LOWEST, win32process.THREAD_PRIORITY_BELOW_NORMAL, win32process.THREAD_PRIORITY_NORMAL, win32process.THREAD_PRIORITY_ABOVE_NORMAL, win32process.THREAD_PRIORITY_HIGHEST, win32process.THREAD_PRIORITY_TIME_CRITICAL ] pid = win32api.GetCurrentProcessId() tid = win32api.GetCurrentThread() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityClasses[priority]) win32process.SetThreadPriority(tid, threadPriorities[priority]) if Config.get('performance', 'restrict_to_first_processor'): win32process.SetProcessAffinityMask(handle, 1)
def impersonate_system(): with enable_privileges(win32security.SE_DEBUG_NAME): pid_csr = ntdll.CsrGetProcessId() hprocess_csr = win32api.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid_csr) htoken_csr = win32security.OpenProcessToken(hprocess_csr, win32con.TOKEN_DUPLICATE) htoken = win32security.DuplicateTokenEx( htoken_csr, win32security.SecurityImpersonation, win32con.TOKEN_QUERY | win32con.TOKEN_IMPERSONATE | win32con.TOKEN_ADJUST_PRIVILEGES, win32security.TokenImpersonation) enable_token_privileges(htoken, win32security.SE_TCB_NAME, win32security.SE_INCREASE_QUOTA_NAME, win32security.SE_ASSIGNPRIMARYTOKEN_NAME) try: htoken_prev = win32security.OpenThreadToken( win32api.GetCurrentThread(), win32con.TOKEN_IMPERSONATE, True) except pywintypes.error as e: if e.winerror != winerror.ERROR_NO_TOKEN: raise htoken_prev = None win32security.SetThreadToken(None, htoken) try: yield finally: win32security.SetThreadToken(None, htoken_prev)
def __init__(self): self._x_values = None # type: list[int] self._y_values = None # type: list[int] self._y_trials_count = None # type: list[int] self._y_trials_correct_response_count = None # type: list[int] win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_LOWEST) pass
def getDomainInfo(): try: token = win32security.OpenThreadToken(win32api.GetCurrentThread(), ntsecuritycon.TOKEN_QUERY, 1) except win32api.error, exc: if exc[0] != winerror.ERROR_NO_TOKEN: raise token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), ntsecuritycon.TOKEN_QUERY)
def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error, details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token, since no thread token # exists tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(), TOKEN_QUERY)
def after_function(self): # print('aaa') win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_LOWEST) while not self.gui_queue.empty(): name_status = self.gui_queue.get() if name_status[0] == 'enable_start_btn': self.btn_start_experiment.config(state='disabled' if name_status[1] is False else 'normal') tkinter.messagebox.showinfo('Information', 'Experiment ended succesfully !!!!') self.combobox_user_name_list.set('') self.root.after(100, self.after_function) pass
def render(self, data): win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_HIGHEST) self.data = data dot_patch = visual.WrappingDotStimOriginal( win=self._my_win, units=self.data['Units'], color=list([ eval(self.data['Color'])[0], eval(self.data['Color'])[1], eval(self.data['Color'])[2], ]), dir=self.convert_to_psycho_direction(self.data['Direction']), # density=self.data['DotsDensity'], nDots=self.density_to_number_of_dots(self.data['DotsDensity'], self.data['FieldSize'], self.data['FieldShape']), fieldShape=self.data['FieldShape'], fieldPos=[ eval(self.data['FieldPosition'])[0], eval(self.data['FieldPosition'])[1] ], fieldSize=self.data['FieldSize'], dotLife=self.data['DotLife'], # number of frames for each dot to be drawn signalDots=self.data['SignalDots'], # are the signal dots the 'same' on each frame? (see Scase et al) noiseDots=self.data['NoiseDots'], # do the noise dots follow random- 'walk', 'direction', or 'position' the # speed in the wrappingDotStim is per frame but in the user input it is in # seconds. speed=self.data['Speed'] / self.data['RenderFrequency'], coherence=self.data['Coherence']) if self.experiment_data.draw_fixation_point: fixation_point_stim = visual.Circle(win=self._my_win, radius=0.01, edges=32, pos=[0, 0], lineColor=[0, 1, 0], fillColor=[0, 1, 0]) start_time = time.time() while time.time() - start_time < self.data['RenderTime']: dot_patch.draw() if self.experiment_data.draw_fixation_point: fixation_point_stim.draw() self._my_win.flip() # redraw the buffer time.sleep((1 / self.data['RenderFrequency']))
def listening_function_thread(self, control_loop_queue): win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_LOWEST) while True: if not control_loop_queue.empty(): (command_function, command_data) = control_loop_queue.get() if command_function == 'update_graph': self.update_graph(command_data) elif command_function == 'reset_graph': self.reset_graph(command_data) elif command_function == 'init_graph': self.init_graph(command_data) pyplot.pause(0.1) time.sleep(0.5) pass
def take_ownership(path: str, owner=None, force: bool = True) -> bool: """ Set owner on NTFS & ReFS files / directories, see https://stackoverflow.com/a/61009508/2635443 :param path: (str) path :param owner: (PySID) object that represents the security identifier. If not set, current security identifier will be used :param force: (bool) Shall we force take ownership :return: """ try: hToken = win32security.OpenThreadToken( win32api.GetCurrentThread(), win32security.TOKEN_ALL_ACCESS, True ) except win32security.error: hToken = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS ) if owner is None: owner = win32security.GetTokenInformation(hToken, win32security.TokenOwner) prev_state = () if force: new_state = [ ( win32security.LookupPrivilegeValue(None, name), win32security.SE_PRIVILEGE_ENABLED, ) for name in ( win32security.SE_TAKE_OWNERSHIP_NAME, win32security.SE_RESTORE_NAME, ) ] prev_state = win32security.AdjustTokenPrivileges(hToken, False, new_state) try: sec_descriptor = win32security.SECURITY_DESCRIPTOR() sec_descriptor.SetSecurityDescriptorOwner(owner, False) win32security.SetFileSecurity( path, win32security.OWNER_SECURITY_INFORMATION, sec_descriptor ) except pywintypes.error as exc: # Let's raise OSError so we don't need to import pywintypes in parent module to catch the exception raise OSError("Cannot take ownership of file: {0}. {1}.".format(path, exc)) finally: if prev_state: win32security.AdjustTokenPrivileges(hToken, False, prev_state) return True
def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error as details: if details[0] != winerror.ERROR_NO_TOKEN: raise # attempt to open the process token, since no thread token # exists tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(), TOKEN_QUERY) sid, attr = win32security.GetTokenInformation(tok, TokenUser) win32api.CloseHandle(tok) name, dom, typ = win32security.LookupAccountSid(None, sid) return dom
def open_effective_token(access, open_as_self=True): hthread = win32api.GetCurrentThread() impersonated_self = False try: htoken = win32security.OpenThreadToken(hthread, access, open_as_self) except pywintypes.error as e: if e.winerror != winerror.ERROR_NO_TOKEN: raise win32security.ImpersonateSelf(win32security.SecurityImpersonation) impersonated_self = True htoken = win32security.OpenThreadToken(hthread, access, open_as_self) try: yield htoken finally: if impersonated_self: win32security.SetThreadToken(None, None)
def __init__(self, graph_maker_command_queue): self.tkFileDialog = None self.protocol_reader = None # type: ProtocolReader self.protocol_writer = None # type:ProtocolWriter self.control_loop = None # type: ControlLoop self.root = None # type: Tk self.protocol_file_path = 'D:\RDK-protocols\coherence.xlsx' self.label_choose_folder = None # type: Label self.btn_choose_folder = None # type: Button self.protocol_root_dir = 'D:\RDK-protocols' # type: object self.combobox_protocol_list = None # type: Combobox self.btn_start_experiment = None # type: Button self.btn_stop_experiment = None # type: Button self.dynamic_controls_dict = None # type: Dict[Any, Any] self.parameters_attributes_dictionary = None # type: Dict[Any,Any] self.label_num_of_repetitions = None # type: Label self.label_num_of_trials = None # type: Label self.label_backward_error_probability: Label self.label_forward_rightward_probability: Label self.entry_num_of_repetitions = None # type: Entry self.entry_num_of_trials = None # type: Entry self.control_loop_thread = None # type: Thread self.current_gui_tooltip_window = None # type: Toplevel self.checkbox_confidence_choice = None # type:Checkbutton self.confidence_choice_value = None # type: BooleanVar self.draw_fixation_point_value = None # type:BooleanVar self.label_save_protocol_name = None # type: Label self.entry_save_protocol_name = None # type: Entry self.combobox_user_name_list = None # type: Combobox self.label_user_name = None # type: Label self.gui_queue = queue.Queue() self.control_loop_queue = queue.Queue() self.graph_maker_command_queue = graph_maker_command_queue self.btn_save_protocol = None # type: Button self.label_screen_height_size = None # type:Label self.label_screen_width_size = None # type:Label self.entry_screen_width_size = None # type: Button self.entry_screen_height_size = None # type: Button win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_NORMAL)
def thread_target(h, progress): try: self.progress = progress self.seen_finished = False self.running = True # Drop my thread priority, so outlook can keep repainting # and doing its stuff without getting stressed. import win32process, win32api THREAD_PRIORITY_BELOW_NORMAL = -1 win32process.SetThreadPriority( win32api.GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) self.func(self.window.manager, self.window.config, progress) finally: try: win32api.PostMessage(h, MYWM_FINISHED, self.progress.stop_requested()) except win32api.error: # Bad window handle - already down. pass self.running = False self.progress = None
def manage_request(self, request, client_address): try: procHandle = win32api.GetCurrentProcess() th = win32api.DuplicateHandle(procHandle, win32api.GetCurrentThread(), procHandle, 0, 0, win32con.DUPLICATE_SAME_ACCESS) try: # Pretend Python doesn't have the interpreter lock. self.lckThreadHandles.acquire() self.thread_handles.append(th) self.lckThreadHandles.release() try: self.finish_request(request, client_address) except: s = StringIO.StringIO() traceback.print_exc(file=s) self.servicemanager.LogErrorMsg(s.getvalue()) finally: # Pretend Python doesn't have the interpreter lock... self.lckThreadHandles.acquire() self.thread_handles.remove(th) self.lckThreadHandles.release() except: s = StringIO.StringIO() traceback.print_exc(file=s) self.servicemanager.LogErrorMsg(s.getvalue())
lockfile = open(LOCKFILE, "a") try: plock.lock(lockfile, plock.LOCK_EX | plock.LOCK_NB) except IOError: eclient.log("error: another_enigma-client_process_is_already_using_this_directory") sys.exit(1) win32process.SetPriorityClass( win32process.GetCurrentProcess(), win32process.IDLE_PRIORITY_CLASS ) win32process.SetThreadPriority( win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_IDLE ) while 1: retval = os.system(cmdline) if retval == 0: eclient.log("submitting results ...") eclient.submit_chunk(server) eclient.log("success: submitted results") chunk = eclient.filereadlines('00hc.resume') if chunk is not None: eclient.log(''.join(("best result: ", chunk[1]))) eclient.log("trying to get workunit ...") eclient.get_chunk(server)
def run_as_system(command): # pylint: disable=too-many-locals currentProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, os.getpid()) currentProcessToken = win32security.OpenProcessToken(currentProcess, win32con.MAXIMUM_ALLOWED) duplicatedCurrentProcessToken = win32security.DuplicateTokenEx( ExistingToken=currentProcessToken, DesiredAccess=win32con.MAXIMUM_ALLOWED, ImpersonationLevel=win32security.SecurityImpersonation, TokenType=ntsecuritycon.TokenImpersonation, TokenAttributes=None ) _id = win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME) newprivs = [(_id, win32security.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(duplicatedCurrentProcessToken, False, newprivs) win32security.SetThreadToken(win32api.GetCurrentThread(), duplicatedCurrentProcessToken) currentProcessToken = win32security.OpenThreadToken(win32api.GetCurrentThread(), win32con.MAXIMUM_ALLOWED, False) sessionId = win32security.GetTokenInformation(currentProcessToken, ntsecuritycon.TokenSessionId) pid = None for proc in psutil.process_iter(): try: if proc.name() == "lsass.exe": pid = proc.pid break except psutil.AccessDenied: pass if not pid: raise RuntimeError("Failed to get pid of lsass.exe") lsassProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, pid) lsassProcessToken = win32security.OpenProcessToken( lsassProcess, win32con.MAXIMUM_ALLOWED ) systemToken = win32security.DuplicateTokenEx( ExistingToken=lsassProcessToken, DesiredAccess=win32con.MAXIMUM_ALLOWED, ImpersonationLevel=win32security.SecurityImpersonation, TokenType=ntsecuritycon.TokenImpersonation, TokenAttributes=None ) privs = win32security.GetTokenInformation(systemToken, ntsecuritycon.TokenPrivileges) newprivs = [] # enable all privileges for privtuple in privs: newprivs.append((privtuple[0], win32security.SE_PRIVILEGE_ENABLED)) privs = tuple(newprivs) win32security.AdjustTokenPrivileges(systemToken, False, newprivs) win32security.SetThreadToken(win32api.GetCurrentThread(), systemToken) hToken = win32security.DuplicateTokenEx( ExistingToken=lsassProcessToken, DesiredAccess=win32con.MAXIMUM_ALLOWED, ImpersonationLevel=win32security.SecurityImpersonation, TokenType=ntsecuritycon.TokenPrimary, TokenAttributes=None ) win32security.SetTokenInformation(hToken, ntsecuritycon.TokenSessionId, sessionId) privs = win32security.GetTokenInformation(hToken, ntsecuritycon.TokenPrivileges) newprivs = [] # enable all privileges for privtuple in privs: newprivs.append((privtuple[0], win32security.SE_PRIVILEGE_ENABLED)) privs = tuple(newprivs) win32security.AdjustTokenPrivileges(hToken, False, newprivs) si = win32process.STARTUPINFO() dwCreationFlags = win32con.CREATE_NEW_CONSOLE win32process.CreateProcessAsUser(hToken, None, command, None, None, 1, dwCreationFlags, None, None, si)
def run(self, profile): if profile.get('lsa_secrets'): return profile['lsa_secrets'] try: hToken = win32security.OpenThreadToken( win32api.GetCurrentThread(), win32security.TOKEN_ALL_ACCESS, True) except win32security.error: hToken = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS) prev_state = () new_state = [ (win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME), win32security.SE_PRIVILEGE_ENABLED) ] prev_state = win32security.AdjustTokenPrivileges( hToken, False, new_state) lsass_file = tempfile.mktemp('.dmp', dir=os.getenv('SystemDrive', 'C:') + '\\') try: lsass_pid = 0 for me in psutil.process_iter(): try: if me.exe().lower() == r'c:\windows\system32\lsass.exe': lsass_pid = me.pid except: pass if lsass_pid: try: with disable_fsr(): subprocess.Popen([ 'rundll32.exe', r'C:\Windows\System32\comsvcs.dll,', 'MiniDump', str(lsass_pid), lsass_file, 'full' ], stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, universal_newlines=True, shell=True).communicate() except: lsass_pid = 0 if not lsass_pid: lsass_file = 'C:\\lsassproc.dmp' assert os.path.isfile(lsass_file) finally: if prev_state: win32security.AdjustTokenPrivileges(hToken, False, prev_state) results = {} try: results = pypykatz.parse_minidump_file(lsass_file) results.reader.reader.file_handle.close() results = results.to_dict() os.remove(lsass_file) except Exception as e: pass return results
if not os.path.isfile('00bigr.cur'): eclient.log("trying to get 00bigr.cur ...") eclient.persistent_getfiles((BIDICT, ), 600) eclient.log("success: got 00bigr.cur") lockfile = open(LOCKFILE, "a") try: plock.lock(lockfile, plock.LOCK_EX | plock.LOCK_NB) except IOError: eclient.log( "error: another_enigma-client_process_is_already_using_this_directory") sys.exit(1) win32process.SetPriorityClass(win32process.GetCurrentProcess(), win32process.IDLE_PRIORITY_CLASS) win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_IDLE) while 1: retval = os.system(cmdline) if retval == 0: eclient.log("submitting results ...") eclient.submit_chunk(host, port) eclient.log("success: submitted results") chunk = eclient.filereadlines('00hc.resume') if chunk is not None: eclient.log(''.join(("best result: ", chunk[1]))) eclient.log("trying to get workunit ...") eclient.get_chunk(host, port) eclient.log("success: got workunit") elif retval == 1:
def remote_authorize(self, data): err, sec_buffer = self.mServer.authorize(data) if err == 0: # Get the handle for the authenticated user such that we can pass it # to win32security.DuplicateTokenEx() and get back a handle that # allows us to spawn interactive processes as the authenticated user. self.mServer.ctxt.ImpersonateSecurityContext() flags = win32security.TOKEN_DUPLICATE | win32security.TOKEN_QUERY handle = win32security.OpenThreadToken(win32api.GetCurrentThread(), flags, False) self.mServer.ctxt.RevertSecurityContext() # Using handle, reate a primary handle suitable for passing to # CreateProcessAsUser(). sec_attr = None # sec_attr = pywintypes.SECURITY_ATTRIBUTES() # sec_attr.Initialize() # sec_attr.bInheritHandle = True # Try different impersonation levels for DuplicateTokenEx(). These # should be in order of decreasing utility (most useful to least). # See the SECURITY_IMPERSONATION_LEVEL documentation for more # details. levels = [ win32security.SecurityDelegation, win32security.SecurityImpersonation ] primary_handle = None #access = win32security.TOKEN_ALL_ACCESS #access = win32con.MAXIMUM_ALLOWED access = win32security.TOKEN_IMPERSONATE | \ win32security.TOKEN_QUERY | \ win32security.TOKEN_ASSIGN_PRIMARY | \ win32security.TOKEN_DUPLICATE for l in levels: try: primary_handle = \ win32security.DuplicateTokenEx( ExistingToken = handle, DesiredAccess = access, ImpersonationLevel = l, TokenType = ntsecuritycon.TokenPrimary, TokenAttributes = sec_attr ) break except Exception, ex: self.mLogger.error( "Failed to create primary token with impersonation level %s:" % str(l)) self.mLogger.error(str(ex)) # If the above failed to create a primary token, then we throw an # exception. It is important that we do not return None from this # method. if primary_handle is None: msg = 'Failed to create primary token for user!' self.mLogger.error(msg) raise failure.Failure(error.UnauthorizedLogin(msg)) # acct_info[0] has the SID for the user. acct_info = win32security.GetTokenInformation( primary_handle, win32security.TokenUser) user_sid = acct_info[0] # This returns a tuple containing the user name, the domain (if # applicable), and the accouunt type. # NOTE: The returned strings may be Unicode strings. user_info = win32security.LookupAccountSid(None, user_sid) # Close the handle returned by win32security.OpenThreadToken() since # it is a duplicate. handle.Close() # NOTE: We are forcing the addition of user_sid to the window station # and desktop ACLs. This seems to be the only way for the user # authenticated through SSPI to be able to open interactive windows. return self.prepareAvatar( avatar.WindowsAvatar(primary_handle, user_sid, str(user_info[0]), str(user_info[1]), True))
def get_time(): if os.name == 'posix': return time.clock() elif os.name == 'nt': return win32process.GetThreadTimes(win32api.GetCurrentThread())