def get_sid(self): if self.sid is None: ph = win32api.GetCurrentProcess() th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ) self.sid = win32security.GetTokenInformation( th, win32security.TokenUser)[0] return self.sid
def __adjust_privilege(self, name, attr=win32security.SE_PRIVILEGE_ENABLED): if isinstance(name, str): state = (win32security.LookupPrivilegeValue(None, name), attr) else: state = name hToken = win32security.OpenProcessToken(win32process.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS) return win32security.AdjustTokenPrivileges(hToken, False, [state])
def enable_debug(): flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) priv_id = win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME) old_privs = win32security.AdjustTokenPrivileges( hToken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)])
def get_pth(self): if not self.pth: try: self.pth = win32security.OpenProcessToken( self.get_ph(), win32con.TOKEN_ALL_ACCESS) except: try: self.pth = win32security.OpenProcessToken( self.get_ph(), win32con.TOKEN_READ) except: try: self.pth = win32security.OpenProcessToken( self.get_ph(), win32con.TOKEN_QUERY) #print "OpenProcessToken with TOKEN_QUERY: Failed" except: pass return self.pth
def _change_privilege_state(privilege_name, enable): ''' Change the state, either enable or disable, of the named privilege for this process. If the change fails, an exception will be raised. If successful, it returns True. ''' log.debug('{0} the privilege {1} for this process.'.format( 'Enabling' if enable else 'Disabling', privilege_name)) # this is a pseudo-handle that doesn't need to be closed hProc = win32api.GetCurrentProcess() hToken = None try: hToken = win32security.OpenProcessToken( hProc, win32security.TOKEN_QUERY | win32security.TOKEN_ADJUST_PRIVILEGES) privilege = win32security.LookupPrivilegeValue(None, privilege_name) if enable: privilege_attrs = win32security.SE_PRIVILEGE_ENABLED else: # a value of 0 disables a privilege (there's no constant for it) privilege_attrs = 0 # check that the handle has the requested privilege token_privileges = dict( win32security.GetTokenInformation(hToken, win32security.TokenPrivileges)) if privilege not in token_privileges: if enable: raise SaltInvocationError( 'The requested privilege {0} is not available for this ' 'process (check Salt user privileges).'.format( privilege_name)) else: # disable a privilege this process does not have log.debug( 'Cannot disable privilege {0} because this process ' 'does not have that privilege.'.format(privilege_name)) return True else: # check if the privilege is already in the requested state if token_privileges[privilege] == privilege_attrs: log.debug('The requested privilege {0} is already in the ' 'requested state.'.format(privilege_name)) return True changes = win32security.AdjustTokenPrivileges( hToken, False, [(privilege, privilege_attrs)]) finally: if hToken: win32api.CloseHandle(hToken) if not bool(changes): raise SaltInvocationError( 'Could not {0} the {1} privilege for this process'.format( 'enable' if enable else 'remove', privilege_name)) else: return True
def enumerate_tokens(sid=None, session_id=None, privs=None): ''' Enumerate tokens from any existing processes that can be accessed. Optionally filter by sid. ''' for p in psutil.process_iter(): if p.pid == 0: continue try: ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid) except win32api.error as exc: if exc.winerror == 5: log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name()) continue raise exc try: access = (win32security.TOKEN_DUPLICATE | win32security.TOKEN_QUERY | win32security.TOKEN_IMPERSONATE | win32security.TOKEN_ASSIGN_PRIMARY) th = win32security.OpenProcessToken(ph, access) except Exception as exc: log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username()) continue try: process_sid = win32security.GetTokenInformation( th, win32security.TokenUser)[0] except Exception as exc: log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username()) continue proc_sid = win32security.ConvertSidToStringSid(process_sid) if sid and sid != proc_sid: log.debug("Token for pid does not match user sid: %s", sid) continue if session_id and win32security.GetTokenInformation( th, win32security.TokenSessionId) != session_id: continue def has_priv(tok, priv): luid = win32security.LookupPrivilegeValue(None, priv) for priv_luid, flags in win32security.GetTokenInformation( tok, win32security.TokenPrivileges): if priv_luid == luid: return True return False if privs: has_all = True for name in privs: if not has_priv(th, name): has_all = False if not has_all: continue yield dup_token(th)
def elevate_privileges(uac): """On Windows Vista and later, try to get administrator privileges. If successful, return True (so original process can exit). If failed or not applicable, return False.""" if shell.IsUserAnAdmin(): logger.debug('already an admin (UAC not required)') htoken = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) newPrivileges = [ (win32security.LookupPrivilegeValue(None, "SeBackupPrivilege"), win32security.SE_PRIVILEGE_ENABLED), (win32security.LookupPrivilegeValue(None, "SeRestorePrivilege"), win32security.SE_PRIVILEGE_ENABLED), ] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) win32file.CloseHandle(htoken) return False elif not uac: return False if hasattr(sys, 'frozen'): # running frozen in py2exe exe = sys.executable parameters = "--gui --no-uac" else: pyfile = os.path.join(bleachbit.bleachbit_exe_path, 'bleachbit.py') # If the Python file is on a network drive, do not offer the UAC because # the administrator may not have privileges and user will not be # prompted. if len(pyfile) > 0 and path_on_network(pyfile): logger.debug( "debug: skipping UAC because '%s' is on network", pyfile) return False parameters = '"%s" --gui --no-uac' % pyfile exe = sys.executable # add any command line parameters such as --debug-log parameters = "%s %s" % (parameters, ' '.join(sys.argv[1:])) logger.debug('elevate_privileges() exe=%s, parameters=%s', exe, parameters) rc = None try: rc = shell.ShellExecuteEx(lpVerb='runas', lpFile=exe, lpParameters=parameters, nShow=win32con.SW_SHOW) except pywintypes.error as e: if 1223 == e.winerror: logger.debug('user denied the UAC dialog') return False raise logger.debug('ShellExecuteEx=%s', rc) if isinstance(rc, dict): return True return False
def main(): #defining a few variable to allow the user to change values by updating the privileges access = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access) Secure = win32security.LookupPrivilegeValue(None, "SeBackupPrivilege") win32security.AdjustTokenPrivileges( token, 0, [(Secure, win32security.SE_PRIVILEGE_ENABLED)])
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 win_power_privileges(): """ To do any power-options, the process needs higher privileges """ flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) id_ = win32security.LookupPrivilegeValue(None, ntsecuritycon.SE_SHUTDOWN_NAME) newPrivileges = [(id_, ntsecuritycon.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
def _enable_shutdown_privilege(self): process = win32process.GetCurrentProcess() token = win32security.OpenProcessToken( process, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) priv_luid = win32security.LookupPrivilegeValue( None, win32security.SE_SHUTDOWN_NAME) privilege = [(priv_luid, win32security.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(token, False, privilege)
def get_sid(self): """ get the security identifier require to write to the Windows events log """ token_handle = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_READ) self.sid = win32security.GetTokenInformation( token_handle, win32security.TokenUser)[0]
def EnablePriv(privName): new_priv = ((win32security.LookupPrivilegeValue( '', win32security.SE_DEBUG_NAME), win32con.SE_PRIVILEGE_ENABLED), ) hCurrProc = win32process.GetCurrentProcess() hToken = win32security.OpenProcessToken(hCurrProc, win32security.TOKEN_ALL_ACCESS) res = win32security.AdjustTokenPrivileges(hToken, 0, new_priv) win32api.CloseHandle(hToken) return res
def get_user_id(): """Compute the user id of the currently running process.""" process_handle = win32process.GetCurrentProcess() token_handle = win32security.OpenProcessToken( process_handle, win32security.TOKEN_ALL_ACCESS) user_sid = win32security.GetTokenInformation(token_handle, win32security.TokenUser)[0] sid_parts = str(user_sid).split("-") return int(sid_parts[-1])
def __set_debug_priveleges(self): token_handler = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) new_privs = [ (win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME), win32security.SE_PRIVILEGE_ENABLED) ] win32security.AdjustTokenPrivileges(token_handler, 0, new_privs)
def adjust_privilege(priv, enable=1): flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) id = win32security.LookupPrivilegeValue(None, priv) if enable: newPrivileges = [(id, win32con.SE_PRIVILEGE_ENABLED)] else: newPrivileges = [(id, 0)] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
def get_current_user(self): proc_token = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32security.TOKEN_QUERY) sid, tmp = win32security.GetTokenInformation(proc_token, win32security.TokenUser) username, domain, user_type = win32security.LookupAccountSid(None, sid) return domain, username
def remote_reboot_to_firmware(self): TokenHandle = win32security.OpenProcessToken( win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY) NewPrivilege = [ (win32security.LookupPrivilegeValue(None, winnt.SE_SHUTDOWN_NAME), winnt.SE_PRIVILEGE_ENABLED) ] win32security.AdjustTokenPrivileges(TokenHandle, False, NewPrivilege) os.system("shutdown -r -fw -t 0")
def write_event_log(self, message, eventID): ph = win32api.GetCurrentProcess() th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ) my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] level= win32evtlog.EVENTLOG_INFORMATION_TYPE descr = [message] win32evtlogutil.ReportEvent(self.applicationName, eventID, eventType=level, strings=descr, sid=my_sid)
def IsCurrentProcessElevated(self): if self.GetOSVersionName() < os_version_module.VISTA: # TOKEN_QUERY is not defined before Vista. All processes are elevated. return True handle = win32process.GetCurrentProcess() with contextlib.closing( win32security.OpenProcessToken(handle, win32con.TOKEN_QUERY)) as token: return bool(win32security.GetTokenInformation( token, win32security.TokenElevation))
def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT): hproc = win32api.GetCurrentProcess() htok = win32security.OpenProcessToken( hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) privs = ((win32security.LookupPrivilegeValue( None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED), ) win32security.AdjustTokenPrivileges(htok, 0, privs) win32api.ExitWindowsEx(flags, 0)
def AdjustPrivileges(privileges, enable=True): # https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants import win32api, win32security flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) id = win32security.LookupPrivilegeValue(None, privileges) if enable: new_privileges = [(id, win32security.SE_PRIVILEGE_ENABLED)] else: new_privileges = [(id, 0)] win32security.AdjustTokenPrivileges(token, 0, new_privileges) return
def run(args, cwd=None, as_admin=False, cmd_window=False): """ Run an arbitrary command. """ if isinstance(args, str): args = [args] args = list(args) if cwd is None: cwd = os.getenv("USERPROFILE") if as_admin: subprocess.call(args, shell=True, cwd=cwd) else: # We have to do all this nonsense to spawn the process # as the logged in user, rather than as the administrator # that PyleWM is running as startup_info = STARTUPINFO() process_information = PROCESS_INFORMATION() shell_window = ctypes.windll.user32.GetShellWindow() thread_id, process_id = win32process.GetWindowThreadProcessId( shell_window) shell_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, process_id) shell_token = win32security.OpenProcessToken(shell_handle, win32con.TOKEN_DUPLICATE) spawn_token = win32security.DuplicateTokenEx( shell_token, win32security.SecurityImpersonation, win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY | win32con.TOKEN_DUPLICATE | win32con.TOKEN_ADJUST_DEFAULT | 0x0100, win32security.TokenPrimary, None) escaped_commandline = "" for arg in args: escaped_commandline += '"' escaped_commandline += arg escaped_commandline += '" ' # Try to lookup where the exe is from PATH executable = args[0] if not os.path.isfile(executable): executable = shutil.which(executable) success = ctypes.windll.advapi32.CreateProcessWithTokenW( int(spawn_token), 0, executable, escaped_commandline, win32con.CREATE_NO_WINDOW if not cmd_window else win32con.CREATE_NEW_CONSOLE, None, os.getcwd(), ctypes.pointer(startup_info), ctypes.pointer(process_information)) if not success: error = ctypes.get_last_error() raise pywintypes.error(error, 'CreateProcessWithTokenW', win32api.FormatMessageW(error))
def __init__(self): super(RweHelper, self).__init__() import platform self.os_system = platform.system() self.os_release = platform.release() self.os_version = platform.version() self.os_machine = platform.machine() self.os_uname = platform.uname() if "windows" == self.os_system.lower(): win_ver = "win7_" + self.os_machine.lower() if ("5" == self.os_release): win_ver = "winxp" if logger().HAL: logger().log( "[helper] OS: %s %s %s" % (self.os_system, self.os_release, self.os_version)) if logger().HAL: logger().log("[helper] Using 'helper/win/%s' path for driver" % win_ver) self.use_existing_service = False self.driver_path = None self.win_ver = win_ver self.driver_handle = None self.device_file = pywintypes.Unicode(DEVICE_FILE) c_int_p = POINTER(c_int) # enable required SeSystemEnvironmentPrivilege privilege privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege') token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES) win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)]) win32api.CloseHandle(token) # import firmware variable API try: self.GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW self.GetFirmwareEnvironmentVariable.restype = c_int self.GetFirmwareEnvironmentVariable.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int ] self.SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW self.SetFirmwareEnvironmentVariable.restype = c_int self.SetFirmwareEnvironmentVariable.argtypes = [ c_wchar_p, c_wchar_p, c_void_p, c_int ] except AttributeError, msg: logger().warn( "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" ) pass
def _adjustProcessPrivileges(self): """提升权限 """ import win32security hCurPro = win32process.GetCurrentProcess() hToken = win32security.OpenProcessToken(hCurPro, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) luid = win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME) if luid: newState = [(luid, win32security.SE_PRIVILEGE_ENABLED),] win32security.AdjustTokenPrivileges(hToken, 0, newState) win32api.CloseHandle(hToken)
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 getusertoken(): print("Getting winlogon pid...") winlogon_pid = get_pid('winlogon.exe') print("PID:" + str(winlogon_pid)) p = win32api.OpenProcess(1024, 0, get_pid('winlogon.exe')) t = win32security.OpenProcessToken(p, win32security.TOKEN_DUPLICATE) primaryToken = win32security.DuplicateTokenEx( t, win32security.SecurityImpersonation, win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary) return primaryToken
def suspend(hibernate=False): """ Puts Windows to Suspend/Sleep/Standby or Hibernate. Parameters ---------- hibernate: bool, default False If False (default), system will enter Suspend/Sleep/Standby state. If True, system will Hibernate, but only if Hibernate is enabled in the system settings. If it's not, system will Sleep. Example -------- >>> suspend() """ # Enable the SeShutdown privilege (which must be present in your # token in the first place) priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) h_token = win32security.OpenProcessToken( win32api.GetCurrentProcess(), priv_flags ) priv_id = win32security.LookupPrivilegeValue( None, win32security.SE_SHUTDOWN_NAME ) old_privs = win32security.AdjustTokenPrivileges( h_token, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)] ) if (win32api.GetPwrCapabilities()['HiberFilePresent'] is False and hibernate is True): import warnings warnings.warn("Hibernate isn't available. Suspending.") try: ctypes.windll.powrprof.SetSuspendState(not hibernate, True, False) except: # True=> Standby; False=> Hibernate # https://msdn.microsoft.com/pt-br/library/windows/desktop/aa373206(v=vs.85).aspx # says the second parameter has no effect. # ctypes.windll.kernel32.SetSystemPowerState(not hibernate, True) win32api.SetSystemPowerState(not hibernate, True) # Restore previous privileges win32security.AdjustTokenPrivileges( h_token, 0, old_privs )
def seDebug(): try: """SEDebug""" flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY htoken = win32security.OpenProcessToken( win32api.GetCurrentProcess(), flags) id = win32security.LookupPrivilegeValue(None, "seDebugPrivilege") newPrivileges = [(id, win32security.SE_PRIVILEGE_ENABLED)] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) except Exception as e: print 'je me vautre' pass
def AdjustPrivilege(priv, enable): htoken = \ win32security.OpenProcessToken( win32api.GetCurrentProcess(), ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY ) id = win32security.LookupPrivilegeValue(None, priv) if enable: newPrivileges = [(id, ntsecuritycon.SE_PRIVILEGE_ENABLED)] else: newPrivileges = [(id, 0)] win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)