Example #1
0
    def __init__(self):
        super(Win32Helper, 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
Example #2
0
def rebootComputer(message='Rebooting',
                   timeout=30,
                   forceClose=False,
                   reboot=True):
    # Enable the SeShutdown privilege (which must be present in your
    # token in the first place)
    priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES
                  | win32security.TOKEN_QUERY)
    hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                            priv_flags)
    priv_id = win32security.LookupPrivilegeValue(
        None, win32security.SE_SHUTDOWN_NAME)
    old_privs = win32security.AdjustTokenPrivileges(
        hToken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)])
    try:
        win32api.InitiateSystemShutdown(None, message, timeout, forceClose,
                                        reboot)
    finally:
        # Restore previous privileges
        win32security.AdjustTokenPrivileges(hToken, 0, old_privs)
def adjustPrivilege(priv, enable=True):
    flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                            flags)
    id = win32security.LookupPrivilegeValue(None, priv)
    if enable:
        newPrivileges = [(id, ntsecuritycon.SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(id, 0)]
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
    win32api.CloseHandle(htoken)
Example #4
0
    def adjust_privilege(privilege: str, enable: bool = False) -> bool:
        new_privileges = [(win32security.LookupPrivilegeValue(None, privilege),
                           win32con.SE_PRIVILEGE_ENABLED if enable else 0)]

        flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY
        token = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                               flags)

        if not token:
            return False

        win32security.AdjustTokenPrivileges(token, 0, new_privileges)
Example #5
0
 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)
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)])
Example #7
0
 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
Example #8
0
def change_priv (priv_name, enable=True):
  hToken = win32security.OpenProcessToken (
    win32api.GetCurrentProcess (), 
    ntsecuritycon.MAXIMUM_ALLOWED
  )
  win32security.AdjustTokenPrivileges ( 
    hToken,
    False, 
    [(
      win32security.LookupPrivilegeValue (None, priv_name), 
      win32security.SE_PRIVILEGE_ENABLED if enable else 0
    )]
  )
Example #9
0
 def put_system_to_sleep(self) -> None:
     """Put Windows into sleep mode
     """
     access = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
     htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                             access)
     if htoken:
         priv_id = win32security.LookupPrivilegeValue(
             None, win32security.SE_SHUTDOWN_NAME)
         win32security.AdjustTokenPrivileges(
             htoken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)])
         ctypes.windll.powrprof.SetSuspendState(False, True, True)
         win32api.CloseHandle(htoken)
Example #10
0
def change(s, l):
    global start
    string_date = " ".join(str(x) for x in l)
    list_date = string_date.split()
    year = int(list_date[0])
    if (list_date[0] == "00"):
        start += 1
    year = (start * 1000) + year
    month = int(list_date[1])
    dayOfWeek = int(
        list_date[2])  #CONVERT THE TIME VARIABLE INTO INTEGER VALUE
    day = int(list_date[3])
    hour = int(list_date[4])
    minute = int(list_date[5])
    second = int(list_date[6])
    microsecond = int(list_date[7])
    user_zone = 'UTC'
    local_tz = utc_to_local(
        datetime(year, month, day, hour, minute, second, microsecond),
        user_zone)
    if s == 1:
        month = monthDict[local_tz.month]
        print local_tz
        os.system('date -s "' + str(local_tz.day) + " " + month + " " +
                  str(local_tz.year) + " " + str(local_tz.hour) + ":" +
                  str(local_tz.minute) + ":" + str(local_tz.second) +
                  '"')  #SET THE TIME IN LINUX MACHINE
    elif s == 2:
        try:
            import win32api
            import win32security
        except ImportError as e:
            print str(e)
            sys.exit(1)
        print local_tz
        priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
        hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                                ntsecuritycon.MAXIMUM_ALLOWED)
        time_privilege = win32security.LookupPrivilegeValue(
            None, win32security.SE_TIME_ZONE_NAME)
        win32security.AdjustTokenPrivileges(
            hToken, 0, [(time_privilege, win32security.SE_PRIVILEGE_ENABLED)])
        win32api.SetTimeZoneInformation(
            (0, u'GMT Standard Time', (2000, 10, 5, 2, 0, 0, 0, 0), 0,
             u'GMT Daylight Time', (2000, 5, 3, 1, 0, 0, 0, 0), -60))
        win32api.SetSystemTime(
            local_tz.year, local_tz.month, dayOfWeek, local_tz.day,
            local_tz.hour, local_tz.minute, local_tz.second,
            local_tz.microsecond)  #SET THE TIME IN WINDOWS MACHINE
    else:
        print 'wrong param'
Example #11
0
def SaveKey( regpath , filename ) :
    assert KeyExists( regpath )
    if ( os.path.exists( filename ) ) :
        os.unlink( filename )
    assert( not os.path.exists( filename ) )

    current_process = win32api.GetCurrentProcess()
    handle_token = win32security.OpenProcessToken( current_process, win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY )
    luid = win32security.LookupPrivilegeValue(None, "SeBackupPrivilege")
    new_privs = ( (luid, win32con.SE_PRIVILEGE_ENABLED), )
    win32security.AdjustTokenPrivileges( handle_token , False, new_privs)

        
    root_key , path = parse_regpath( regpath )
    handle = _winreg.OpenKey( root_key, path )

    try:
        _winreg.SaveKey( handle, filename )
    finally:
        win32security.AdjustTokenPrivileges( handle_token, True, new_privs )
        handle.Close()

    assert( os.path.exists( filename ) )
Example #12
0
def AdjustPrivilege(priv, enable = 1):
    # Get the process token.
    flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
    # Get the ID for the system shutdown privilege.
    id = win32security.LookupPrivilegeValue(None, priv)
    # Now obtain the privilege for this process.
    # Create a list of the privileges to be added.
    if enable:
        newPrivileges = [(id, win32con.SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(id, 0)]
    # and make the adjustment.
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
Example #13
0
    def __init__(self):
        super(RweHelper, self).__init__()

        import platform, os
        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().DEBUG: logger().log( "[helper] OS: %s %s %s" % (self.os_system, self.os_release, self.os_version) )

        self.use_existing_service = False

        self.win_ver        = win_ver
        self.driver_handle  = None
        self.device_file    = pywintypes.Unicode(DEVICE_FILE)

        # check DRIVER_FILE_PATHS for the DRIVER_FILE_NAME
        self.driver_path    = None
        for path in DRIVER_FILE_PATHS:
            driver_path = os.path.join(path, DRIVER_FILE_NAME)
            if os.path.isfile(driver_path): 
                self.driver_path = driver_path
                if logger().DEBUG: logger().log("[helper] found driver in %s" % driver_path)
        if self.driver_path == None: 
            if logger().DEBUG: logger().log("[helper] RWE Driver Not Found")
            raise DriverNotFound

        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:
            if logger().DEBUG: logger().warn( "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" )
            pass
Example #14
0
 def hibernate(self, state):
     token = win32security.OpenProcessToken(
         win32api.GetCurrentProcess(),
         win32security.TOKEN_QUERY | win32security.TOKEN_ADJUST_PRIVILEGES)
     shutdown_priv = win32security.LookupPrivilegeValue(
         None, win32security.SE_SHUTDOWN_NAME)
     privs = win32security.AdjustTokenPrivileges(
         token, False,
         [(shutdown_priv, win32security.SE_PRIVILEGE_ENABLED)])
     logging.debug("Privileges before hibernation: %s", privs)
     if windll.powrprof.SetSuspendState(state == 'disk', True, False) != 0:
         logging.info("System was in hibernation state.")
     else:
         logging.error("Error setting system to hibernation state: %d",
                       win32api.GetLastError())
Example #15
0
def get_all_privs(th):
    privs = win32security.GetTokenInformation(th,
                                              ntsecuritycon.TokenPrivileges)
    for privtuple in privs:
        privs2 = win32security.GetTokenInformation(
            th, ntsecuritycon.TokenPrivileges)
        newprivs = []
        for privtuple2 in privs2:
            if privtuple2[0] == privtuple[0]:
                newprivs.append((privtuple2[0], 2))  # SE_PRIVILEGE_ENABLED
            else:
                newprivs.append((privtuple2[0], privtuple2[1]))

        # Adjust privs
        privs3 = tuple(newprivs)
        win32security.AdjustTokenPrivileges(th, False, privs3)
Example #16
0
def enable_privilege(privilege_name):
    success = False
    privilege_id = win32security.LookupPrivilegeValue(None, privilege_name)

    new_privilege = [(privilege_id, win32con.SE_PRIVILEGE_ENABLED)]

    h_token = win32security.OpenProcessToken(win32process.GetCurrentProcess(),
                                             win32security.TOKEN_ALL_ACCESS)

    if h_token:
        success = win32security.AdjustTokenPrivileges(h_token, 0,
                                                      new_privilege)

        close_handle(h_token)

    return success
Example #17
0
File: win.py Project: umutbb/hubble
def elevate_token(th):
    '''
    Set all token privileges to enabled
    '''
    # Get list of privileges this token contains
    privileges = win32security.GetTokenInformation(
        th, win32security.TokenPrivileges)

    # Create a set of all privileges to be enabled
    enable_privs = set()
    for luid, flags in privileges:
        enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))

    # Enable the privileges
    if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
        raise WindowsError(win32api.FormatMessage(win32api.GetLastError()))  # pylint: disable=undefined-variable
Example #18
0
 def prepareForSessionActions():
     try:
         # Get some privileges to load the hive
         priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
         hToken = win32security.OpenProcessToken(
             win32api.GetCurrentProcess(), priv_flags)
         backup_privilege_id = win32security.LookupPrivilegeValue(
             None, "SeBackupPrivilege")
         restore_privilege_id = win32security.LookupPrivilegeValue(
             None, "SeRestorePrivilege")
         win32security.AdjustTokenPrivileges(
             hToken, 0,
             [(backup_privilege_id, win32security.SE_PRIVILEGE_ENABLED),
              (restore_privilege_id, win32security.SE_PRIVILEGE_ENABLED)])
     except Exception:
         Logger.exception("Failed to obtain more provilege")
Example #19
0
File: util.py Project: zjp85/QTAF
 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)
Example #20
0
def win_shutdown():
    """ Shutdown Windows system, never returns
    """
    try:
        import win32security
        import win32api
        import ntsecuritycon

        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)
        win32api.InitiateSystemShutdown("", "", 30, 1, 0)
    finally:
        os._exit(0)
Example #21
0
def AdjustPrivilege(priv, enable=1):
    # Get process token
    flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                            flags)
    # Get the ID for the system shutdown privilege
    id = win32security.LookupPrivilegeValue(
        None, priv)  # params = (systemName, privilegeName)
    # Obtain the privilege for this process
    # Create a list of privileges to be added
    if enable:
        newPrivileges = [(id, SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(id, 0)]
    # make the privilege adjustment
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
def patch_current_process_privileges():
    """
    Patch the current process to acquire the SeSystemEnvironmentPrivilege privileges,
    it is discouraged to use it in production, this function exists only for use from ipython.
    Use the privileges() function instead when possible.
    :return: Patch object that can be reverted.
    """
    process = win32process.GetCurrentProcess()
    token = win32security.OpenProcessToken(
        process,
        win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
    luid = win32security.LookupPrivilegeValue(
        None, win32con.SE_SYSTEM_ENVIRONMENT_NAME)
    privilege_enable = [(luid, win32security.SE_PRIVILEGE_ENABLED)]
    privilege_disable = [(luid, 0)]
    win32security.AdjustTokenPrivileges(token, False, privilege_enable)

    return Patch(token, privilege_disable)
Example #23
0
def get_extra_privs():
    th = win32security.OpenProcessToken(
        win32api.GetCurrentProcess(),
        win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)
    privs = win32security.GetTokenInformation(th,
                                              ntsecuritycon.TokenPrivileges)
    newprivs = []

    for privtuple in privs:
        if privtuple[0] == win32security.LookupPrivilegeValue(None, "SeBackupPrivilege")\
            or privtuple[0] == win32security.LookupPrivilegeValue(None, "SeDebugPrivilege")\
            or privtuple[0] == win32security.LookupPrivilegeValue(None, "SeSecurityPrivilege"):
            print("Added privilege " + str(privtuple[0]))
            # privtuple[1] = 2 # tuples are immutable.  WHY?!
            newprivs.append((privtuple[0], 2))  # SE_PRIVILEGE_ENABLED
        else:
            newprivs.append((privtuple[0], privtuple[1]))
    privs = tuple(newprivs)
    str(win32security.AdjustTokenPrivileges(th, False, privs))
def shutdown(off_pc=19):
    import time

    while time.localtime().tm_hour != off_pc:
        time.sleep(60)  # Ожидание 1 минута

    import sys

    if sys.platform == 'win32':
        import ctypes
        import win32security
        import win32api
        import winerror

        # Try to enable the required privileges to change the power state
        privilege_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
        token_handle = win32security.OpenProcessToken(
            win32api.GetCurrentProcess(), privilege_flags)
        privilege_id = win32security.LookupPrivilegeValue(
            None, win32security.SE_SHUTDOWN_NAME)

        # Does the user have permission to change the power state?
        win32security.AdjustTokenPrivileges(
            token_handle, 0,
            [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)])

        if ctypes.GetLastError() != winerror.ERROR_SUCCESS:
            print(ctypes.WinError(), file=sys.stderr)
            quit()

        user32 = ctypes.WinDLL('user32')

        # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-exitwindowsex
        user32.ExitWindowsEx(0x00000001, 0x00000000)

        if ctypes.GetLastError() != winerror.ERROR_SUCCESS:
            print(ctypes.WinError(), file=sys.stderr)
            quit()

    else:
        import os
        os.system('sudo shutdown now')
Example #25
0
    def __init__(self):
        # 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 )

        # get windows 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]
            self._SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW
            self._SetFirmwareEnvironmentVariableEx.restype = c_int
            self._SetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int]
        except AttributeError:
            logging.warn( "Some get/set functions don't't seem to exist" )
Example #26
0
def RunAsStandardUser(command_line, env, cwd, timeout):
    """Runs a command as non-elevated logged-on user.

    Args:
        command_line: The command line string, including arguments, to run.
        env: Environment variables for child process, None to inherit.
        cwd: Working directory for child process, None to inherit from parent.
        timeout: How long in seconds should wait for child process.

    Returns:
        (pid, exit_code, sdtout, stderr) tuple.

    Raises:
        ImpersonationError: when impersonation failed.
    """
    logging.info('Running "%s" as the logon user.', command_line)

    # Adjust current process to be part of the trusted computer base.
    current_process_token = win32security.OpenProcessToken(
        win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS)
    tcb_privilege_flag = win32security.LookupPrivilegeValue(
        None, win32security.SE_TCB_NAME)
    se_enable = win32security.SE_PRIVILEGE_ENABLED
    win32security.AdjustTokenPrivileges(current_process_token, 0,
                                        [(tcb_privilege_flag, se_enable)])

    active_session_id = proc_util.GetActiveSessionID()
    if not active_session_id:
        raise ImpersonationError('Cannot find active logon session.')

    try:
        logon_user_token = win32ts.WTSQueryUserToken(active_session_id)
    except pywintypes.error as err:
        if err.winerror == winerror.ERROR_NO_TOKEN:
            raise ImpersonationError('No user is logged on.')
        else:
            raise ImpersonationError('Failed to get user token: %s' % err)

    return _RunAsOnWindowStationDesktop(command_line, logon_user_token,
                                        'WinSta0', 'default', env, cwd,
                                        timeout)
Example #27
0
    def get_app_info():
        try:
            import win32gui
            # TODO: or maybe win32gui.GetFocus() ?
            hwnd = win32gui.GetForegroundWindow()

            # Request privileges to enable "debug process", so we can
            # later use PROCESS_VM_READ, retardedly required to
            # GetModuleFileNameEx()
            import win32security, win32con, win32process, win32api
            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)])

            # Open the process, and query it's filename
            processid = win32process.GetWindowThreadProcessId(hwnd)
            pshandle = win32api.OpenProcess(
                win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ,
                False, processid[1])
            exename = win32process.GetModuleFileNameEx(pshandle, 0)

            # clean up
            win32api.CloseHandle(pshandle)
            win32api.CloseHandle(hToken)

            return {
                "appName": exename,
                "windowTitle": win32gui.GetWindowText(hwnd),
                "url": None,
                "idleTime": None
            }

        except Exception, e:
            print e
            return None
Example #28
0
def elevate():
    import os
    import win32security

    pid = os.getpid()
    phandle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
    token_handle=win32security.OpenProcessToken(phandle,win32con.TOKEN_ALL_ACCESS)
    if token_handle==0:
        print('提取令牌失败')
    else:
        Luid=win32security.LookupPrivilegeValue(None,win32security.SE_DEBUG_NAME)
        if Luid==0:
            print('Luid获取失败')
        else:
            new_token_pricileges=[(Luid,win32security.SE_PRIVILEGE_ENABLED)]
            i=win32security.AdjustTokenPrivileges(token_handle,0,new_token_pricileges)
            if i==0:
                print('提权失败')
            else:
                print('succ')
    win32api.CloseHandle(token_handle)
Example #29
0
    def __init__(self):
        # 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)

        kernel32 = windll.kernel32
        ntdll = windll.ntdll

        # import firmware variable APIs
        try:
            self._GetSystemFirmwareTable = kernel32.GetSystemFirmwareTable
            self._GetSystemFirmwareTable.restype = c_int
            self._GetSystemFirmwareTable.argtypes = [
                c_int, c_int, c_void_p, c_int
            ]

            self._NtQuerySystemInformation = ntdll.NtQuerySystemInformation

            # NTSTATUS WINAPI NtQuerySystemInformation(
            #     _In_      SYSTEM_INFORMATION_CLASS SystemInformationClass,
            #     _Inout_   PVOID                    SystemInformation,
            #     _In_      ULONG                    SystemInformationLength,
            #     _Out_opt_ PULONG                   ReturnLength
            # );
            self._NtQuerySystemInformation.restype = c_ulong
            self._NtQuerySystemInformation.argtypes = [
                c_int, c_void_p, c_ulong,
                POINTER(c_ulong)
            ]

        except AttributeError:
            logging.error(
                "GetSystemFirmwareTable function doesn't seem to exist")
            pass
Example #30
0
def _windows_sleep():
    '''Put a Windows computer to sleep.'''
    # This function was taken from:  http://permalink.gmane.org/gmane.comp.python.windows/7382

    #
    # Enable the SeShutdown privilege (which must be present in your
    # token in the first place)
    #
    priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                            priv_flags)
    priv_id = win32security.LookupPrivilegeValue(
        None, win32security.SE_SHUTDOWN_NAME)
    win32security.AdjustTokenPrivileges(
        htoken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)])

    #
    # Params:
    # True=> Standby; False=> Hibernate
    # True=> Force closedown; False=> Don't force
    #
    ctypes.windll.kernel32.SetSystemPowerState(True, True)