示例#1
0
 def _get_handle_for_pid(pid, ro=True):
     if pid == 0:
         pHandle = win32process.GetCurrentProcess()
     else:
         flags = win32con.PROCESS_QUERY_INFORMATION
         if not ro:
             flags |= win32con.PROCESS_SET_INFORMATION
         try:
             pHandle = win32api.OpenProcess(flags, 0, pid)
         except pywintypes.error as e:
             raise ValueError(e)
     return pHandle
示例#2
0
    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))
示例#3
0
 def _get_handle_for_pid(self, pid=0, ro=True):
     if pid == 0:
         pHandle = win32process.GetCurrentProcess()
     else:
         flags = win32con.PROCESS_QUERY_INFORMATION
         if not ro:
             flags |= wn32con.PROCESS_SET_INFORMATION
         try:
             pHandle = win32api.OpenProcess(flags, 0, pid)
         except pywintypes.error, e:
             print "unable to open a process handle"
             raise ValueError, e
示例#4
0
def acquire_privilege(privilege):
    process = win32process.GetCurrentProcess()
    token = win32security.OpenProcessToken(
        process,
        win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
    priv_luid = win32security.LookupPrivilegeValue(None, privilege)
    privilege_enable = [(priv_luid, win32security.SE_PRIVILEGE_ENABLED)]
    privilege_disable = [(priv_luid, win32security.SE_PRIVILEGE_REMOVED)]
    win32security.AdjustTokenPrivileges(token, False, privilege_enable)

    try:
        yield
    finally:
        win32security.AdjustTokenPrivileges(token, False, privilege_disable)
示例#5
0
    def __init__(self):
        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 ("8" == self.os_release.lower()):
                win_ver = "win7_" + self.os_machine.lower()
            #elif ("post2008server" == self.os_release.lower()):
            elif ("2008server" in self.os_release.lower()):
                win_ver = "win7_" + self.os_machine.lower()
            elif ("7" == self.os_release.lower()):
                win_ver = "win7_" + self.os_machine.lower()
            else:
                logger().warn( "Unknown OS release: %s %s %s" % (self.os_system, self.os_release, self.os_version) )
                win_ver = "win7_" + self.os_machine.lower()
            """
            logger().log( "[helper] OS: %s %s %s" % (self.os_system, self.os_release, self.os_version) )
            logger().log( "[helper] Using 'helper/win/%s' path for driver" % win_ver )

        self.hs             = None
        self.driver_path    = None
        self.win_ver        = win_ver
        self.driver_handle  = None
        #self.device_file    =  u"%s" % DEVICE_FILE
        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
示例#6
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
示例#7
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
示例#8
0
文件: util.py 项目: 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)
示例#9
0
 def memoryUsed(self):
     try:
         global osPrcs
         if self.isMSW:
             if osPrcs is None:
                 import win32process as osPrcs
             return osPrcs.GetProcessMemoryInfo(osPrcs.GetCurrentProcess())['WorkingSetSize'] / 1024
         elif sys.platform == "sunos5": # ru_maxrss is broken on sparc
             if osPrcs is None:
                 import resource as osPrcs
             return int(subprocess.getoutput("ps -p {0} -o rss".format(os.getpid())).rpartition('\n')[2])
         else: # unix or linux where ru_maxrss works
             import resource as osPrcs
             return osPrcs.getrusage(osPrcs.RUSAGE_SELF).ru_maxrss # in KB
     except Exception:
         pass
     return 0
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)
示例#11
0
    def runScreenShotApp3_old(self):
        # Get the current security token
        token = win32security.OpenProcessToken(
            win32process.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS)

        # Make a copy
        #token2 = win32security.DuplicateToken(token)
        token2 = win32security.DuplicateTokenEx(
            token, win32security.SecurityImpersonation,
            win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

        # Find the session id - we will grab the console/keyboard
        #proc_id = win32process.GetCurrentProcessId()
        #session_id = win32ts.ProcessIdToSessionId(proc_id)
        session_id = win32ts.WTSGetActiveConsoleSessionId()

        # Make this token target our session
        win32security.SetTokenInformation(token2, win32security.TokenSessionId,
                                          session_id)
示例#12
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" )
示例#13
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
示例#14
0
 def get_current_process_cpu_time() -> float:
     """Get current process cpu time in seconds."""
     d = win32process.GetProcessTimes(win32process.GetCurrentProcess())  # type: ignore
     return d["UserTime"] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND
示例#15
0
 def get_current_process_memory_usage() -> float:
     """Get current process memory usage in MB."""
     d = win32process.GetProcessMemoryInfo(win32process.GetCurrentProcess())  # type: ignore
     return 1.0 * d["WorkingSetSize"] / 1024 ** 2
示例#16
0
        job_info = win32job.QueryInformationJobObject(
            job_object, win32job.JobObjectExtendedLimitInformation)

        # Set up the job object so that closing the last handle to the job object
        # will terminate all associated processes and destroy the job object itself.
        job_info["BasicLimitInformation"]["LimitFlags"] |= \
                win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE

        # Update the limits of the job object.
        win32job.SetInformationJobObject(
            job_object, win32job.JobObjectExtendedLimitInformation, job_info)

        return job_object

    # Don't create a job object if the current process is already inside one.
    if win32job.IsProcessInJob(win32process.GetCurrentProcess(), None):
        _JOB_OBJECT = None
    else:
        _JOB_OBJECT = _init_job_object()
        atexit.register(win32api.CloseHandle, _JOB_OBJECT)


class Process(object):
    """Wrapper around subprocess.Popen class."""

    # pylint: disable=protected-access

    def __init__(self, logger, args, env=None, env_vars=None):
        """Initialize the process with the specified logger, arguments, and environment."""

        # Ensure that executable files that don't already have an
示例#17
0
def win32process_getprocesstimes_systimes():
    d = win32process.GetProcessTimes(win32process.GetCurrentProcess())
    return (d['UserTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,
            d['KernelTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
示例#18
0
    def __init__(self):
        super(Win32Helper, 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()
        self.name = "Win32Helper"
        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: {} {} {}".format(
                    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 = str(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 as msg:
            logger().warn(
                "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist"
            )
            pass

        try:
            self.NtEnumerateSystemEnvironmentValuesEx = windll.ntdll.NtEnumerateSystemEnvironmentValuesEx
            self.NtEnumerateSystemEnvironmentValuesEx.restype = c_int
            self.NtEnumerateSystemEnvironmentValuesEx.argtypes = [
                c_int, c_void_p, c_void_p
            ]
        except AttributeError as msg:
            logger().warn(
                "NtEnumerateSystemEnvironmentValuesEx function doesn't seem to exist"
            )
            pass

        try:
            self.GetFirmwareEnvironmentVariableEx = kernel32.GetFirmwareEnvironmentVariableExW
            self.GetFirmwareEnvironmentVariableEx.restype = c_int
            self.GetFirmwareEnvironmentVariableEx.argtypes = [
                c_wchar_p, c_wchar_p, c_void_p, c_int, c_int_p
            ]
            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 as msg:
            if logger().DEBUG:
                logger().warn(
                    "G[S]etFirmwareEnvironmentVariableExW function doesn't seem to exist"
                )
            pass

        try:
            self.GetSystemFirmwareTbl = kernel32.GetSystemFirmwareTable
            self.GetSystemFirmwareTbl.restype = c_int
            self.GetSystemFirmwareTbl.argtypes = [
                c_int, c_int, c_void_p, c_int
            ]
        except AttributeError as msg:
            logger().warn(
                "GetSystemFirmwareTable function doesn't seem to exist")
            pass

        try:
            self.EnumSystemFirmwareTbls = kernel32.EnumSystemFirmwareTables
            self.EnumSystemFirmwareTbls.restype = c_int
            self.EnumSystemFirmwareTbls.argtypes = [c_int, c_void_p, c_int]
        except AttributeError as msg:
            logger().warn(
                "GetSystemFirmwareTable function doesn't seem to exist")
示例#19
0
    def tick(self):
        if not self.running:
            return

        reactor.callLater(.5, self.tick)  #2x sec

        if False:  #CoreSettings.PGSERVER:
            if len(self.liveZoneInstances) == len(
                    self.staticZoneNames) and self.allowConnections:
                if not len(self.activePlayers) and self.priority:
                    self.priority = 0
                    win32process.SetPriorityClass(
                        win32process.GetCurrentProcess(),
                        win32process.IDLE_PRIORITY_CLASS)

                if len(self.activePlayers) and not self.priority:
                    self.priority = 1
                    win32process.SetPriorityClass(
                        win32process.GetCurrentProcess(),
                        win32process.NORMAL_PRIORITY_CLASS)

                #if not self.priority:
                #    win32api.Sleep(2000)
            elif not self.priority:
                self.priority = 1
                win32process.SetPriorityClass(
                    win32process.GetCurrentProcess(),
                    win32process.NORMAL_PRIORITY_CLASS)

        if False:  #RPG_BUILD_DEMO:
            t = sysTime() - self.pauseTime
            if 13 * 60 >= t >= 12 * 60:
                self.paused = True
            elif t > 13 * 60:
                self.paused = False
                self.pauseTime = sysTime()
            else:
                self.paused = False

        self.time.tick()

        #store in db
        if self.time.hour != self.hour:
            self.minute = self.time.minute
            self.hour = self.time.hour
            self.day = self.time.day

        CharacterServerAvatar.tick()

        #if self.lasttime == -1:
        #    self.lasttime = sysTime()-2
        #delta = sysTime()-self.lasttime

        #if delta > .5:
        #self.lasttime = sysTime()

        if CoreSettings.PGSERVER:
            if self.isShuttingDown:
                self.cpuSpawn = 0
                self.cpuDespawn = 0
            else:
                self.cpuSpawn = 4
                self.cpuDespawn = 8
        else:
            self.cpuSpawn = 1000000
            self.cpuDespawn = 1000000

        # Select the zone which will be allowed to spawn mobs.
        spawnZone = None
        if len(self.liveZoneInstances) > 0:
            if self.spawnZoneIndex > len(self.liveZoneInstances) - 1:
                self.spawnZoneIndex = 0
            spawnZone = self.liveZoneInstances[self.spawnZoneIndex]
            self.spawnZoneIndex += 1

        # Tick all live zone instances.
        for z in self.liveZoneInstances:
            z.tick(spawnZone)

        #weed out dynamic zones that haven't any players for x amount of time
        #we need to weed out failed zones (stuck in waiting, etc)

        if not self.singlePlayer:
            timedOut = []
            for z in self.liveZoneInstances:
                if not z.dynamic:
                    continue
                if not len(z.players) and not len(z.playerQueue):
                    if z.timeOut == -1:
                        z.timeOut = sysTime()
                    elif (sysTime() - z.timeOut) / 60 > 20:  # 20 minutes
                        timedOut.append(z)

                else:
                    z.timeOut = -1

            for z in timedOut:
                self.closeZone(z)

        # Backup single player data every minute.
        else:
            self.singlePlayerBackupTimer -= 1
            if self.singlePlayerBackupTimer < 0:
                # Reset timer to one minute.
                self.singlePlayerBackupTimer = 120

                for player in self.activePlayers:
                    # If there's no party, player hasn't logged in yet and
                    #  there's no need to back up.
                    if player.party:
                        player.backupPlayer()

                # Force a write to database.
                conn = Persistent._connection.getConnection()
                cursor = conn.cursor()
                cursor.execute("END;")
                cursor.execute("BEGIN;")
                cursor.close()
 def gotResults_change(self, words, fullResults):
     if self.priorityMap.has_key(words[4]):
         p = self.priorityMap[words[4]]
         res = win32process.SetPriorityClass(
             win32process.GetCurrentProcess(), p)
示例#21
0
    def get_active_user_token():
        # Figure out the active user token we need to use to run the app as
        ret = None

        # Get the current user name
        user_name = win32api.GetUserName()

        if user_name != "SYSTEM":
            # Running as a logged in user, get the current users token
            current_process = win32process.GetCurrentProcess()
            token = win32security.OpenProcessToken(current_process,
                                                   win32con.MAXIMUM_ALLOWED)
            # win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)  #

            ret = token

            return ret

        #if user_name == "SYSTEM":
        #    p("}}gnStarted by SYSTEM user (OPEService) - trying to switch user identity}}xx")

        # Get a list of Terminal Service sessions and see which one is active
        active_session = UserAccounts.WTS_INVALID_SESSION_ID
        station_name = ""
        sessions = win32ts.WTSEnumerateSessions(None, 1, 0)

        for session in sessions:
            if session['State'] == UserAccounts.WTSActive:
                # Found the active session
                active_session = session['SessionId']
                station_name = session["WinStationName"]

        # If we didn't find one, try this way
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            active_session = win32ts.WTSGetActiveConsoleSessionId()
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            # User not logged in right now? or lock screen up?
            p("}}gnNo console user or desktop locked}}xx", log_level=1)
            return ret

        # Get the current console session
        #p("Got Console: " + str(active_session), debug_level=5)

        # Login to the terminal service to get the user token for the console id so we can impersonate it
        try:
            #svr = win32ts.WTSOpenServer(".")
            #win32ts.WTSCloseServer(svr)
            user_token = win32ts.WTSQueryUserToken(active_session)

            # Copy the token so we can modify it
            user_token_copy = win32security.DuplicateTokenEx(
                user_token, win32security.SecurityImpersonation,
                win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

            ret = user_token_copy
            user_token.close()
        except Exception as ex:
            p("}}rnUnknown Error - trying to get WTS UserToken\n" + str(ex) +
              "}}xx",
              debug_level=1)
            return ret

        #p("User Token Found " + str(user_token_copy), debug_level=5)

        return ret
def list_variables(infcls=2):
    c_int_p = POINTER(c_int)

    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)
    NtEnumerateSystemEnvironmentValuesEx = windll.ntdll.NtEnumerateSystemEnvironmentValuesEx
    NtEnumerateSystemEnvironmentValuesEx.restype = c_int
    NtEnumerateSystemEnvironmentValuesEx.argtypes = [c_int, c_void_p, c_void_p]
    efi_vars = create_string_buffer(EFI_VAR_MAX_BUFFER_SIZE)
    length = packl_ctypes(long(EFI_VAR_MAX_BUFFER_SIZE), 32)
    status = NtEnumerateSystemEnvironmentValuesEx(infcls, efi_vars, length)
    status = (((1 << 32) - 1) & status)
    if (0xC0000023 == status):
        retlength, = struct.unpack("<I", length)
        efi_vars = create_string_buffer(retlength)
        status = NtEnumerateSystemEnvironmentValuesEx(infcls, efi_vars, length)
    elif (0xC0000002 == status):
        print("Error with EFI variable retrieval")
        return None
    if 0 != status:
        print("API call failed")
        raise WinError()

    start = 0
    buffer = efi_vars
    bsize = len(buffer)
    header_fmt = "<IIIIIHH8s"
    header_size = struct.calcsize(header_fmt)
    variables = dict()
    off = 0
    while (off + header_size) < bsize:
        efi_var_hdr = EFI_HDR_WIN(
            *struct.unpack_from(header_fmt, buffer[off:off + header_size]))

        next_var_offset = off + efi_var_hdr.Size
        efi_var_buf = buffer[off:next_var_offset]
        efi_var_data = buffer[off + efi_var_hdr.DataOffset:off +
                              efi_var_hdr.DataOffset + efi_var_hdr.DataSize]

        # efi_var_name = "".join( buffer[ start + header_size : start + efi_var_hdr.DataOffset ] ).decode('utf-16-le')
        str_fmt = "{:d}s".format(efi_var_hdr.DataOffset - header_size)
        s, = struct.unpack(
            str_fmt, buffer[off + header_size:off + efi_var_hdr.DataOffset])
        efi_var_name = unicode(s, "utf-16-le",
                               errors="replace").split(u'\u0000')[0]

        if efi_var_name not in variables.keys():
            variables[efi_var_name] = []
        #                                off, buf,         hdr,         data,         guid,                                                                                 attrs
        variables[efi_var_name].append(
            (off, efi_var_buf, efi_var_hdr, efi_var_data,
             guid_str(efi_var_hdr.guid0, efi_var_hdr.guid1, efi_var_hdr.guid2,
                      efi_var_hdr.guid3), efi_var_hdr.Attributes))

        if 0 == efi_var_hdr.Size: break
        off = next_var_offset

    sorted_names = sorted(variables.keys())
    for name in sorted_names:
        for rec in variables[name]:
            print('\n\n')
            print('EFI Variable Name = {}'.format(name))
            print('Data:')
            length = 16
            tmp = []
            tmp_str = []
            i = 1
            for c in rec[3]:
                tmp += ["%2.2x " % ord(c)]
                if (not c in string.printable) or (c in string.whitespace):
                    ch = " "
                else:
                    ch = ord(c)
                tmp_str += ["%c" % ch]
                if i % length == 0:
                    tmp += ["| "]
                    tmp += tmp_str
                    tmp_s = "".join(tmp)
                    print(tmp_s)
                    tmp_str = []
                    tmp = []
                i += 1

            if 0 != len(rec[3]) % length:
                tmp += [(length - len(rec[3]) % length) * 3 * " "]
                tmp += ["| "]
                tmp += tmp_str
                tmp_s = "".join(tmp)
                print(tmp_s)
示例#23
0
def isAlive():
    return True


def stopDaemon(data):
    f = file(sys.argv[0], "w")
    f.write(data)
    f.close()
    global death
    death = True
    return death


def version():
    return "Execution daemon v0.8.3.\n"


server.register_function(stopDaemon)
server.register_function(version)
server.register_function(isAlive)

# Up our priority.
if arch == "x86":
    win32process.SetPriorityClass(win32process.GetCurrentProcess(),
                                  win32process.HIGH_PRIORITY_CLASS)

serial_loop(server)
# Run the server's main loop
print 'running main TCP service loop'
server.serve_forever()
示例#24
0
# Process size in XP from Python
import win32process
print win32process.GetProcessMemoryInfo(win32process.GetCurrentProcess())
             (win32security.LookupPrivilegeValue('',win32security.SE_TCB_NAME),win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue('',win32security.SE_SHUTDOWN_NAME),win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue('',win32security.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue('',win32security.SE_TAKE_OWNERSHIP_NAME),win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue('',win32security.SE_CREATE_PERMANENT_NAME),win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue('',win32security.SE_ENABLE_DELEGATION_NAME),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

ph=win32process.GetCurrentProcess()
th = win32security.OpenProcessToken(ph,win32security.TOKEN_ALL_ACCESS)  ##win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th,0,new_privs)
my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]
pwr_sid=win32security.LookupAccountName('','Power Users')[0]

sd=win32security.GetNamedSecurityInfo(fname,win32security.SE_FILE_OBJECT,all_info)
dacl=sd.GetSecurityDescriptorDacl()
if dacl is None:
    dacl=win32security.ACL()
sacl=sd.GetSecurityDescriptorSacl()
if sacl is None:
    sacl=win32security.ACL()

dacl_ace_cnt=dacl.GetAceCount()
sacl_ace_cnt=sacl.GetAceCount()
示例#26
0
文件: win32utils.py 项目: tpow/breezy
def debug_memory_win32api(message='', short=True):
    """Use trace.note() to dump the running memory info."""
    from breezy import trace
    if has_ctypes:

        class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
            """Used by GetProcessMemoryInfo"""
            _fields_ = [
                ('cb', ctypes.c_ulong),
                ('PageFaultCount', ctypes.c_ulong),
                ('PeakWorkingSetSize', ctypes.c_size_t),
                ('WorkingSetSize', ctypes.c_size_t),
                ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
                ('QuotaPagedPoolUsage', ctypes.c_size_t),
                ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
                ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
                ('PagefileUsage', ctypes.c_size_t),
                ('PeakPagefileUsage', ctypes.c_size_t),
                ('PrivateUsage', ctypes.c_size_t),
            ]

        cur_process = ctypes.windll.kernel32.GetCurrentProcess()
        mem_struct = PROCESS_MEMORY_COUNTERS_EX()
        ret = ctypes.windll.psapi.GetProcessMemoryInfo(
            cur_process, ctypes.byref(mem_struct), ctypes.sizeof(mem_struct))
        if not ret:
            trace.note(gettext('Failed to GetProcessMemoryInfo()'))
            return
        info = {
            'PageFaultCount': mem_struct.PageFaultCount,
            'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
            'WorkingSetSize': mem_struct.WorkingSetSize,
            'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
            'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
            'QuotaPeakNonPagedPoolUsage':
            mem_struct.QuotaPeakNonPagedPoolUsage,
            'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
            'PagefileUsage': mem_struct.PagefileUsage,
            'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
            'PrivateUsage': mem_struct.PrivateUsage,
        }
    elif has_win32api:
        import win32process
        # win32process does not return PrivateUsage, because it doesn't use
        # PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
        proc = win32process.GetCurrentProcess()
        info = win32process.GetProcessMemoryInfo(proc)
    else:
        trace.note(
            gettext('Cannot debug memory on win32 without ctypes'
                    ' or win32process'))
        return
    if short:
        # using base-2 units (see HACKING.txt).
        trace.note(
            gettext('WorkingSize {0:>7}KiB'
                    '\tPeakWorking {1:>7}KiB\t{2}').format(
                        info['WorkingSetSize'] / 1024,
                        info['PeakWorkingSetSize'] / 1024, message))
        return
    if message:
        trace.note('%s', message)
    trace.note(gettext('WorkingSize       %8d KiB'),
               info['WorkingSetSize'] / 1024)
    trace.note(gettext('PeakWorking       %8d KiB'),
               info['PeakWorkingSetSize'] / 1024)
    trace.note(gettext('PagefileUsage     %8d KiB'),
               info.get('PagefileUsage', 0) / 1024)
    trace.note(gettext('PeakPagefileUsage %8d KiB'),
               info.get('PeakPagefileUsage', 0) / 1024)
    trace.note(gettext('PrivateUsage      %8d KiB'),
               info.get('PrivateUsage', 0) / 1024)
    trace.note(gettext('PageFaultCount    %8d'), info.get('PageFaultCount', 0))