Exemplo n.º 1
0
    def __init__(self, reactor, protocol, command, args, environment, path):
        _pollingfile._PollingTimer.__init__(self, reactor)
        self.protocol = protocol

        # security attributes for pipes
        sAttrs = win32security.SECURITY_ATTRIBUTES()
        sAttrs.bInheritHandle = 1

        # create the pipes which will connect to the secondary process
        self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)

        win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT,
                                          None, None)

        # set the info structure for the new process.
        StartupInfo = win32process.STARTUPINFO()
        StartupInfo.hStdOutput = hStdoutW
        StartupInfo.hStdError = hStderrW
        StartupInfo.hStdInput = hStdinR
        StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES

        # Create new handles whose inheritance property is false
        pid = win32api.GetCurrentProcess()

        tmp = win32api.DuplicateHandle(pid, self.hStdoutR, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdoutR)
        self.hStdoutR = tmp

        tmp = win32api.DuplicateHandle(pid, self.hStderrR, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStderrR)
        self.hStderrR = tmp

        tmp = win32api.DuplicateHandle(pid, self.hStdinW, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdinW)
        self.hStdinW = tmp

        # Add the specified environment to the current environment - this is
        # necessary because certain operations are only supported on Windows
        # if certain environment variables are present.
        env = os.environ.copy()
        env.update(environment or {})

        # create the process
        cmdline = ' '.join([cmdLineQuote(a) for a in args])
        # TODO: error detection here.
        self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
            command, cmdline, None, None, 1, 0, env, path, StartupInfo)
        win32file.CloseHandle(hThread)

        # close handles which only the child will use
        win32file.CloseHandle(hStderrW)
        win32file.CloseHandle(hStdoutW)
        win32file.CloseHandle(hStdinR)

        self.closed = 0
        self.closedNotifies = 0

        # set up everything
        self.stdout = _pollingfile._PollableReadPipe(
            self.hStdoutR,
            lambda data: self.protocol.childDataReceived(1, data),
            self.outConnectionLost)

        self.stderr = _pollingfile._PollableReadPipe(
            self.hStderrR,
            lambda data: self.protocol.childDataReceived(2, data),
            self.errConnectionLost)

        self.stdin = _pollingfile._PollableWritePipe(self.hStdinW,
                                                     self.inConnectionLost)

        for pipewatcher in self.stdout, self.stderr, self.stdin:
            self._addPollableResource(pipewatcher)

        # notify protocol
        self.protocol.makeConnection(self)
Exemplo n.º 2
0
def processCreate(sName, asArgs):
    """
    Returns a (pid, handle, tid) tuple on success. (-1, None) on failure (logged).
    """

    # Construct a command line.
    sCmdLine = ''
    for sArg in asArgs:
        if sCmdLine == '':
            sCmdLine += '"'
        else:
            sCmdLine += ' "'
        sCmdLine += sArg
        sCmdLine += '"'

    # Try start the process.
    # pylint: disable=no-member
    dwCreationFlags = win32con.CREATE_NEW_PROCESS_GROUP
    oStartupInfo = win32process.STARTUPINFO()
    # pylint: disable=c-extension-no-member
    try:
        (hProcess, hThread, uPid, uTid) = win32process.CreateProcess(
            sName,  # pylint: disable=c-extension-no-member
            sCmdLine,  # CommandLine
            None,  # ProcessAttributes
            None,  # ThreadAttibutes
            1,  # fInheritHandles
            dwCreationFlags,
            None,  # Environment
            None,  # CurrentDirectory.
            oStartupInfo)
    except:
        reporter.logXcpt('sName="%s" sCmdLine="%s"' % (sName, sCmdLine))
        return (-1, None, -1)

    # Dispense with the thread handle.
    try:
        hThread.Close()
        # win32api.CloseHandle(hThread);
    except:
        reporter.logXcpt()

    # Try get full access to the process.
    try:
        hProcessFullAccess = win32api.DuplicateHandle(  # pylint: disable=c-extension-no-member
            win32api.GetCurrentProcess(),  # pylint: disable=c-extension-no-member
            hProcess,
            win32api.GetCurrentProcess(),  # pylint: disable=c-extension-no-member
            win32con.PROCESS_TERMINATE
            | win32con.PROCESS_QUERY_INFORMATION
            | win32con.SYNCHRONIZE
            | win32con.DELETE,
            False,
            0)
        hProcess.Close()
        # win32api.CloseHandle(hProcess);
        hProcess = hProcessFullAccess
    except:
        reporter.logXcpt()
    reporter.log2('processCreate -> %#x, hProcess=%s %#x' % (
        uPid,
        hProcess,
        hProcess.handle,
    ))
    return (uPid, hProcess, uTid)
Exemplo n.º 3
0
 def memory():
     process_handle = win32api.GetCurrentProcess()
     memory_info = win32process.GetProcessMemoryInfo(process_handle)
     return memory_info['PeakWorkingSetSize']
Exemplo n.º 4
0
from rpython.tool.udir import udir

import os, sys, py

if sys.platform != 'win32':
    py.test.skip("_winreg is a win32 module")

try:
    # To call SaveKey, the process must have Backup Privileges
    import win32api
    import win32security
    priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
    hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), priv_flags)
    privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege")
    win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)])
except:
    canSaveKey = False
else:
    canSaveKey = True

class AppTestHKey:
    spaceconfig = dict(usemodules=('_winreg',))

    def test_repr(self):
        import _winreg
        k = _winreg.HKEYType(0x123)
        assert str(k) == "<PyHKEY:0x123>"

class AppTestFfi:
    spaceconfig = dict(usemodules=('_winreg',))
Exemplo n.º 5
0
def test():
    # check if running on Windows NT, if not, display notice and terminate
    if win32api.GetVersion() & 0x80000000:
        print("This sample only runs on NT")
        return

    import sys, getopt

    opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
    computer = None
    do_read = do_write = 1

    logType = "Application"
    verbose = 0

    if len(args) > 0:
        print("Invalid args")
        usage()
        return 1
    for opt, val in opts:
        if opt == "-t":
            logType = val
        if opt == "-c":
            computer = val
        if opt in ["-h", "-?"]:
            usage()
            return
        if opt == "-r":
            do_read = 0
        if opt == "-w":
            do_write = 0
        if opt == "-v":
            verbose = verbose + 1
    if do_write:
        ph = win32api.GetCurrentProcess()
        th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
        my_sid = win32security.GetTokenInformation(th,
                                                   win32security.TokenUser)[0]

        win32evtlogutil.ReportEvent(
            logType,
            2,
            strings=["The message text for event 2", "Another insert"],
            data="Raw\0Data".encode("ascii"),
            sid=my_sid,
        )
        win32evtlogutil.ReportEvent(
            logType,
            1,
            eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
            strings=["A warning", "An even more dire warning"],
            data="Raw\0Data".encode("ascii"),
            sid=my_sid,
        )
        win32evtlogutil.ReportEvent(
            logType,
            1,
            eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
            strings=["An info", "Too much info"],
            data="Raw\0Data".encode("ascii"),
            sid=my_sid,
        )
        print("Successfully wrote 3 records to the log")

    if do_read:
        ReadLog(computer, logType, verbose > 0)
Exemplo n.º 6
0
    def __init__(self, reactor, protocol, command, args, environment, path):
        _pollingfile._PollingTimer.__init__(self, reactor)
        self.protocol = protocol

        # security attributes for pipes
        sAttrs = win32security.SECURITY_ATTRIBUTES()
        sAttrs.bInheritHandle = 1

        # create the pipes which will connect to the secondary process
        self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)

        win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT,
                                          None, None)

        # set the info structure for the new process.
        StartupInfo = win32process.STARTUPINFO()
        StartupInfo.hStdOutput = hStdoutW
        StartupInfo.hStdError = hStderrW
        StartupInfo.hStdInput = hStdinR
        StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES

        # Create new handles whose inheritance property is false
        pid = win32api.GetCurrentProcess()

        tmp = win32api.DuplicateHandle(pid, self.hStdoutR, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdoutR)
        self.hStdoutR = tmp

        tmp = win32api.DuplicateHandle(pid, self.hStderrR, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStderrR)
        self.hStderrR = tmp

        tmp = win32api.DuplicateHandle(pid, self.hStdinW, pid, 0, 0,
                                       win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdinW)
        self.hStdinW = tmp

        # Add the specified environment to the current environment - this is
        # necessary because certain operations are only supported on Windows
        # if certain environment variables are present.

        env = os.environ.copy()
        env.update(environment or {})

        cmdline = quoteArguments(args)

        # TODO: error detection here.
        def doCreate():
            self.hProcess, self.hThread, dwPid, dwTid = win32process.CreateProcess(
                command, cmdline, None, None, 1, 0, env, path, StartupInfo)

        try:
            doCreate()
        except pywintypes.error, pwte:
            if not _invalidWin32App(pwte):
                # This behavior isn't _really_ documented, but let's make it
                # consistent with the behavior that is documented.
                raise OSError(pwte)
            else:
                # look for a shebang line.  Insert the original 'command'
                # (actually a script) into the new arguments list.
                sheb = _findShebang(command)
                if sheb is None:
                    raise OSError("%r is neither a Windows executable, "
                                  "nor a script with a shebang line" % command)
                else:
                    args = list(args)
                    args.insert(0, command)
                    cmdline = quoteArguments(args)
                    origcmd = command
                    command = sheb
                    try:
                        # Let's try again.
                        doCreate()
                    except pywintypes.error, pwte2:
                        # d'oh, failed again!
                        if _invalidWin32App(pwte2):
                            raise OSError("%r has an invalid shebang line: "
                                          "%r is not a valid executable" %
                                          (origcmd, sheb))
                        raise OSError(pwte2)
Exemplo n.º 7
0
     win32con.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_SHUTDOWN_NAME),
     win32con.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue('', ntsecuritycon.SE_RESTORE_NAME),
     win32con.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue('',
                                        ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),
     win32con.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue(
        '', ntsecuritycon.SE_CREATE_PERMANENT_NAME),
     win32con.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue('', 'SeEnableDelegationPrivilege'),
     win32con.SE_PRIVILEGE_ENABLED)  # doesn't seem to be in ntsecuritycon.py ?
)

ph = win32api.GetCurrentProcess()
# win32con.TOKEN_ADJUST_PRIVILEGES)
th = win32security.OpenProcessToken(ph, win32security.TOKEN_ALL_ACCESS)
win32security.AdjustTokenPrivileges(th, 0, new_privs)

all_security_info = \
    win32security.OWNER_SECURITY_INFORMATION | win32security.GROUP_SECURITY_INFORMATION | \
    win32security.DACL_SECURITY_INFORMATION | win32security.SACL_SECURITY_INFORMATION

sd = win32security.GetFileSecurity(fname, all_security_info)

old_sacl = sd.GetSecurityDescriptorSacl()
if old_sacl is None:
    old_sacl = win32security.ACL()
old_dacl = sd.GetSecurityDescriptorDacl()
if old_dacl is None:
Exemplo n.º 8
0
def make_inheritable(token):
    return win32api.DuplicateHandle(win32api.GetCurrentProcess(), token,
                                    win32api.GetCurrentProcess(), 0, 1,
                                    win32con.DUPLICATE_SAME_ACCESS)
Exemplo n.º 9
0
    def __init__(self, reactor, protocol, command, args, environment, path):
        """
        Create a new child process.
        """
        _pollingfile._PollingTimer.__init__(self, reactor)
        BaseProcess.__init__(self, protocol)

        # security attributes for pipes
        sAttrs = win32security.SECURITY_ATTRIBUTES()
        sAttrs.bInheritHandle = 1

        # create the pipes which will connect to the secondary process
        self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)

        win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT,
                                          None, None)

        # set the info structure for the new process.
        StartupInfo = win32process.STARTUPINFO()
        StartupInfo.hStdOutput = hStdoutW
        StartupInfo.hStdError = hStderrW
        StartupInfo.hStdInput = hStdinR
        StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES

        # Create new handles whose inheritance property is false
        currentPid = win32api.GetCurrentProcess()

        tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid,
                                       0, 0, win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdoutR)
        self.hStdoutR = tmp

        tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid,
                                       0, 0, win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStderrR)
        self.hStderrR = tmp

        tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0,
                                       0, win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(self.hStdinW)
        self.hStdinW = tmp

        # Add the specified environment to the current environment - this is
        # necessary because certain operations are only supported on Windows
        # if certain environment variables are present.

        env = os.environ.copy()
        env.update(environment or {})

        if _PY3:
            # Make sure all the arguments are Unicode.
            args = [_maybeMBCS(x) for x in args]

        cmdline = quoteArguments(args)

        if _PY3:
            # The command, too, needs to be Unicode, if it is a value.
            command = _maybeMBCS(command) if command else command

        # TODO: error detection here.  See #2787 and #4184.
        def doCreate():
            self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess(
                command, cmdline, None, None, 1, 0, env, path, StartupInfo)

        try:
            try:
                doCreate()
            except TypeError as e:
                # win32process.CreateProcess cannot deal with mixed
                # str/unicode environment, so we make it all Unicode
                if e.args != ('All dictionary items must be strings, or '
                              'all must be unicode', ):
                    raise
                newenv = {}
                for key, value in items(env):

                    key = _maybeMBCS(key)
                    value = _maybeMBCS(value)

                    newenv[key] = value

                env = newenv
                doCreate()
        except pywintypes.error as pwte:
            if not _invalidWin32App(pwte):
                # This behavior isn't _really_ documented, but let's make it
                # consistent with the behavior that is documented.
                raise OSError(pwte)
            else:
                # look for a shebang line.  Insert the original 'command'
                # (actually a script) into the new arguments list.
                sheb = _findShebang(command)
                if sheb is None:
                    raise OSError("%r is neither a Windows executable, "
                                  "nor a script with a shebang line" % command)
                else:
                    args = list(args)
                    args.insert(0, command)
                    cmdline = quoteArguments(args)
                    origcmd = command
                    command = sheb
                    try:
                        # Let's try again.
                        doCreate()
                    except pywintypes.error as pwte2:
                        # d'oh, failed again!
                        if _invalidWin32App(pwte2):
                            raise OSError("%r has an invalid shebang line: "
                                          "%r is not a valid executable" %
                                          (origcmd, sheb))
                        raise OSError(pwte2)

        # close handles which only the child will use
        win32file.CloseHandle(hStderrW)
        win32file.CloseHandle(hStdoutW)
        win32file.CloseHandle(hStdinR)

        # set up everything
        self.stdout = _pollingfile._PollableReadPipe(
            self.hStdoutR, lambda data: self.proto.childDataReceived(1, data),
            self.outConnectionLost)

        self.stderr = _pollingfile._PollableReadPipe(
            self.hStderrR, lambda data: self.proto.childDataReceived(2, data),
            self.errConnectionLost)

        self.stdin = _pollingfile._PollableWritePipe(self.hStdinW,
                                                     self.inConnectionLost)

        for pipewatcher in self.stdout, self.stderr, self.stdin:
            self._addPollableResource(pipewatcher)

        # notify protocol
        self.proto.makeConnection(self)

        self._addPollableResource(_Reaper(self))
Exemplo n.º 10
0
def runas(cmdLine, username, password=None, cwd=None):
    """
    Run a command as another user. If the process is running as an admin or
    system account this method does not require a password. Other non
    privileged accounts need to provide a password for the user to runas.
    Commands are run in with the highest level privileges possible for the
    account provided.
    """
    # Validate the domain and sid exist for the username
    username, domain = split_username(username)
    try:
        _, domain, _ = win32security.LookupAccountName(domain, username)
    except pywintypes.error as exc:
        message = win32api.FormatMessage(exc.winerror).rstrip("\n")
        raise CommandExecutionError(message)

    # Elevate the token from the current process
    access = win32security.TOKEN_QUERY | win32security.TOKEN_ADJUST_PRIVILEGES
    th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access)
    salt.platform.win.elevate_token(th)

    # Try to impersonate the SYSTEM user. This process needs to be running as a
    # user who as been granted the SeImpersonatePrivilege, Administrator
    # accounts have this permission by default.
    try:
        impersonation_token = salt.platform.win.impersonate_sid(
            salt.platform.win.SYSTEM_SID, session_id=0, privs=["SeTcbPrivilege"],
        )
    except WindowsError:  # pylint: disable=undefined-variable
        log.debug("Unable to impersonate SYSTEM user")
        impersonation_token = None
        win32api.CloseHandle(th)

    # Impersonation of the SYSTEM user failed. Fallback to an un-privileged
    # runas.
    if not impersonation_token:
        log.debug("No impersonation token, using unprivileged runas")
        return runas_unpriv(cmdLine, username, password, cwd)

    if domain == "NT AUTHORITY":
        # Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK
        # SERVICE.
        user_token = win32security.LogonUser(
            username,
            domain,
            "",
            win32con.LOGON32_LOGON_SERVICE,
            win32con.LOGON32_PROVIDER_DEFAULT,
        )
    elif password:
        # Login with a password.
        user_token = win32security.LogonUser(
            username,
            domain,
            password,
            win32con.LOGON32_LOGON_INTERACTIVE,
            win32con.LOGON32_PROVIDER_DEFAULT,
        )
    else:
        # Login without a password. This always returns an elevated token.
        user_token = salt.platform.win.logon_msv1_s4u(username).Token

    # Get a linked user token to elevate if needed
    elevation_type = win32security.GetTokenInformation(
        user_token, win32security.TokenElevationType
    )
    if elevation_type > 1:
        user_token = win32security.GetTokenInformation(
            user_token, win32security.TokenLinkedToken
        )

    # Elevate the user token
    salt.platform.win.elevate_token(user_token)

    # Make sure the user's token has access to a windows station and desktop
    salt.platform.win.grant_winsta_and_desktop(user_token)

    # Create pipes for standard in, out and error streams
    security_attributes = win32security.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 1

    stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0)
    stdin_read = salt.platform.win.make_inheritable(stdin_read)

    stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0)
    stdout_write = salt.platform.win.make_inheritable(stdout_write)

    stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0)
    stderr_write = salt.platform.win.make_inheritable(stderr_write)

    # Run the process without showing a window.
    creationflags = (
        win32process.CREATE_NO_WINDOW
        | win32process.CREATE_NEW_CONSOLE
        | win32process.CREATE_SUSPENDED
    )

    startup_info = salt.platform.win.STARTUPINFO(
        dwFlags=win32con.STARTF_USESTDHANDLES,
        hStdInput=stdin_read.handle,
        hStdOutput=stdout_write.handle,
        hStdError=stderr_write.handle,
    )

    # Create the environment for the user
    env = win32profile.CreateEnvironmentBlock(user_token, False)

    hProcess = None
    try:
        # Start the process in a suspended state.
        process_info = salt.platform.win.CreateProcessWithTokenW(
            int(user_token),
            logonflags=1,
            applicationname=None,
            commandline=cmdLine,
            currentdirectory=cwd,
            creationflags=creationflags,
            startupinfo=startup_info,
            environment=env,
        )

        hProcess = process_info.hProcess
        hThread = process_info.hThread
        dwProcessId = process_info.dwProcessId
        dwThreadId = process_info.dwThreadId

        # We don't use these so let's close the handle
        salt.platform.win.kernel32.CloseHandle(stdin_write.handle)
        salt.platform.win.kernel32.CloseHandle(stdout_write.handle)
        salt.platform.win.kernel32.CloseHandle(stderr_write.handle)

        ret = {"pid": dwProcessId}
        # Resume the process
        psutil.Process(dwProcessId).resume()

        # Wait for the process to exit and get its return code.
        if (
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            == win32con.WAIT_OBJECT_0
        ):
            exitcode = win32process.GetExitCodeProcess(hProcess)
            ret["retcode"] = exitcode

        # Read standard out
        fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT)
        with os.fdopen(fd_out, "r") as f_out:
            stdout = f_out.read()
            ret["stdout"] = stdout

        # Read standard error
        fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT)
        with os.fdopen(fd_err, "r") as f_err:
            stderr = f_err.read()
            ret["stderr"] = stderr
    finally:
        if hProcess is not None:
            salt.platform.win.kernel32.CloseHandle(hProcess)
        win32api.CloseHandle(th)
        win32api.CloseHandle(user_token)
        if impersonation_token:
            win32security.RevertToSelf()
        win32api.CloseHandle(impersonation_token)

    return ret
Exemplo n.º 11
0
        'MaximumSpeed': {
            'value': pp.global_abs_max('SpeedSensor.v'),
            'unit': 'm/s'
        }
    })

    cwd = os.getcwd()
    os.chdir('..')
    update_metrics_in_report_json(metrics)
    check_limits_and_add_to_report_json(pp, limits_dict)
    os.chdir(cwd)


if __name__ == '__main__':
    root_dir = os.getcwd()
    try:
        main()
    except:
        os.chdir(root_dir)
        import traceback
        trace = traceback.format_exc()
        # Generate this file on failed executions, https://github.com/scipy/scipy/issues/1840
        with open(os.path.join('..', '_POST_PROCESSING_FAILED.txt'),
                  'wb') as f_out:
            f_out.write(trace)
        if os.name == 'nt':
            import win32api
            win32api.TerminateProcess(win32api.GetCurrentProcess(), 1)
        else:
            sys.exit(1)
Exemplo n.º 12
0
import winerror
from nxdrive.logging_config import get_logger
from time import sleep

UCHAR = c_ubyte
PVOID = c_void_p
ntdll = windll.ntdll

SystemHandleInformation = 16
STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
STATUS_BUFFER_OVERFLOW = 0x80000005L
STATUS_INVALID_HANDLE = 0xC0000008L
STATUS_BUFFER_TOO_SMALL = 0xC0000023L
STATUS_SUCCESS = 0

CURRENT_PROCESS = win32api.GetCurrentProcess()

threads = 0
log = get_logger(__name__)


class x_file_handles(Exception):
    pass


def signed_to_unsigned(signed):
    unsigned, = struct.unpack("L", struct.pack("l", signed))
    return unsigned


class SYSTEM_HANDLE_TABLE_ENTRY_INFO(Structure):
Exemplo n.º 13
0
    def __init__(self, reactor, protocol, command, args, environment, path):
        self.reactor = reactor
        self.protocol = protocol
        self.outBuffer = reactor.AllocateReadBuffer(self.bufferSize)
        self.errBuffer = reactor.AllocateReadBuffer(self.bufferSize)
        # This is the buffer for *reading* stdin, which is only done to
        # determine if the other end of the pipe was closed.
        self.inBuffer = reactor.AllocateReadBuffer(self.bufferSize)
        # IO operation classes
        self.readOutOp = ops.ReadOutOp(self)
        self.readErrOp = ops.ReadErrOp(self)
        self.readInOp = ops.ReadInOp(self)
        self.writeInOp = ops.WriteInOp(self)

        self.writeBuffer = ""
        self.writing = False
        self.finished = False
        self.offset = 0
        self.writeBufferedSize = 0
        self.closingStdin = False
        self.closedStdin = False
        self.closedStdout = False
        self.closedStderr = False
        # Stdio handles
        self.hChildStdinRd = None
        self.hChildStdinWr = None
        self.hChildStdinWrDup = None
        self.hChildStdoutRd = None
        self.hChildStdoutWr = None
        self.hChildStdoutRdDup = None
        self.hChildStderrRd = None
        self.hChildStderrWr = None
        self.hChildStderrRdDup = None

        self.closedNotifies = 0  # increments to 3 (for stdin, stdout, stderr)
        self.closed = False  # set to true when all 3 handles close
        self.exited = False  # set to true when WFMO thread gets signalled proc handle.  See doWaitForProcessExit.

        # Set the bInheritHandle flag so pipe handles are inherited.
        saAttr = win32security.SECURITY_ATTRIBUTES()
        saAttr.bInheritHandle = 1

        currentPid = win32api.GetCurrentProcess(
        )  # -1 which stands for current process
        self.pid = os.getpid()  # unique pid for pipe naming

        # Create a pipe for the child process's STDOUT.
        self.stdoutPipeName = r"\\.\pipe\twisted-iocp-stdout-%d-%d-%d" % (
            self.pid, counter.next(), time.time())
        self.hChildStdoutRd = win32pipe.CreateNamedPipe(
            self.stdoutPipeName,
            win32con.PIPE_ACCESS_INBOUND
            | win32con.FILE_FLAG_OVERLAPPED,  # open mode
            win32con.PIPE_TYPE_BYTE,  # pipe mode
            1,  # max instances
            self.pipeBufferSize,  # out buffer size
            self.pipeBufferSize,  # in buffer size
            0,  # timeout 
            saAttr)

        self.hChildStdoutWr = win32file.CreateFile(
            self.stdoutPipeName, win32con.GENERIC_WRITE,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr,
            win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0)

        # Create noninheritable read handle and close the inheritable read
        # handle.
        self.hChildStdoutRdDup = win32api.DuplicateHandle(
            currentPid, self.hChildStdoutRd, currentPid, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32api.CloseHandle(self.hChildStdoutRd)
        self.hChildStdoutRd = self.hChildStdoutRdDup

        # Create a pipe for the child process's STDERR.
        self.stderrPipeName = r"\\.\pipe\twisted-iocp-stderr-%d-%d-%d" % (
            self.pid, counter.next(), time.time())
        self.hChildStderrRd = win32pipe.CreateNamedPipe(
            self.stderrPipeName,
            win32con.PIPE_ACCESS_INBOUND
            | win32con.FILE_FLAG_OVERLAPPED,  # open mode
            win32con.PIPE_TYPE_BYTE,  # pipe mode
            1,  # max instances
            self.pipeBufferSize,  # out buffer size
            self.pipeBufferSize,  # in buffer size
            0,  # timeout 
            saAttr)
        self.hChildStderrWr = win32file.CreateFile(
            self.stderrPipeName, win32con.GENERIC_WRITE,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr,
            win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0)

        # Create noninheritable read handle and close the inheritable read
        # handle.
        self.hChildStderrRdDup = win32api.DuplicateHandle(
            currentPid, self.hChildStderrRd, currentPid, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32api.CloseHandle(self.hChildStderrRd)
        self.hChildStderrRd = self.hChildStderrRdDup

        # Create a pipe for the child process's STDIN. This one is opened
        # in duplex mode so we can read from it too in order to detect when
        # the child closes their end of the pipe.
        self.stdinPipeName = r"\\.\pipe\twisted-iocp-stdin-%d-%d-%d" % (
            self.pid, counter.next(), time.time())
        self.hChildStdinWr = win32pipe.CreateNamedPipe(
            self.stdinPipeName,
            win32con.PIPE_ACCESS_DUPLEX
            | win32con.FILE_FLAG_OVERLAPPED,  # open mode
            win32con.PIPE_TYPE_BYTE,  # pipe mode
            1,  # max instances
            self.pipeBufferSize,  # out buffer size
            self.pipeBufferSize,  # in buffer size
            0,  # timeout 
            saAttr)

        self.hChildStdinRd = win32file.CreateFile(
            self.stdinPipeName, win32con.GENERIC_READ,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, saAttr,
            win32con.OPEN_EXISTING, win32con.FILE_FLAG_OVERLAPPED, 0)

        # Duplicate the write handle to the pipe so it is not inherited.
        self.hChildStdinWrDup = win32api.DuplicateHandle(
            currentPid, self.hChildStdinWr, currentPid, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32api.CloseHandle(self.hChildStdinWr)
        self.hChildStdinWr = self.hChildStdinWrDup

        # set the info structure for the new process.  This is where
        # we tell the process to use the pipes for stdout/err/in.
        StartupInfo = win32process.STARTUPINFO()
        StartupInfo.hStdOutput = self.hChildStdoutWr
        StartupInfo.hStdError = self.hChildStderrWr
        StartupInfo.hStdInput = self.hChildStdinRd
        StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES

        # create the process
        cmdline = quoteArguments(args)
        self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
            command,  # name
            cmdline,  # command line
            None,  # process security attributes
            None,  # primary thread security attributes
            1,  # handles are inherited
            0,  # creation flags
            environment,  # if NULL, use parent environment
            path,  # current directory
            StartupInfo)  # STARTUPINFO pointer

        # close handles which only the child will use
        win32file.CloseHandle(self.hChildStderrWr)
        win32file.CloseHandle(self.hChildStdoutWr)
        win32file.CloseHandle(self.hChildStdinRd)

        # Begin reading on stdout and stderr, before we have output on them.
        self.readOutOp.initiateOp(self.hChildStdoutRd, self.outBuffer)
        self.readErrOp.initiateOp(self.hChildStderrRd, self.errBuffer)
        # Read stdin which was opened in duplex mode so we can detect when
        # the child closed their end of the pipe.
        self.readInOp.initiateOp(self.hChildStdinWr, self.inBuffer)

        # When the process is done, call connectionLost().
        # This function returns right away.  Note I call this after
        # protocol.makeConnection to ensure that the protocol doesn't
        # have processEnded called before protocol.makeConnection.
        self.reactor.processWaiter.beginWait(self.reactor, self.hProcess, self)

        # notify protocol by calling protocol.makeConnection and specifying
        # ourself as the transport.
        self.protocol.makeConnection(self)
Exemplo n.º 14
0
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
Exemplo n.º 15
0
def DuplicateHandle(handle):
  """Duplicates a win32 handle."""
  proc = win32api.GetCurrentProcess()
  return win32api.DuplicateHandle(proc,handle,proc,0,0,win32con.DUPLICATE_SAME_ACCESS)
Exemplo n.º 16
0
def reboot(flags: int = EWX_FORCEIFHUNG | EWX_REBOOT) -> None:
    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)