示例#1
0
 def __init__(self, command, arguments=None, env=None, stdout=None,
              stderr=None, redirect_output=True, working_dir=None):
     self._cmdline = _get_cmd(command, arguments)
     self._env = env
     self._stdout = os.path.abspath(stdout) if stdout else None
     self._stderr = os.path.abspath(stderr) if stderr else None
     self._redirect_output = redirect_output
     self._appName = None
     self._bInheritHandles = 1
     self._processAttributes = win32security.SECURITY_ATTRIBUTES()
     # TODO: Is this needed?
     # self._processAttributes.bInheritHandle = self._bInheritHandles
     self._threadAttributes = win32security.SECURITY_ATTRIBUTES()
     # TODO: Is this needed
     # self._threadAttributes.bInheritHandle = self._bInheritHandles
     self._dwCreationFlags = win32con.CREATE_NO_WINDOW
     # TODO: Which one of these is best?
     # self._dwCreationFlags=win32con.NORMAL_PRIORITY_CLASS
     self._currentDirectory = working_dir
     # This will be created during the start
     self._startupinfo = None
     self._hProcess = None
     self._hThread = None
     self._dwProcessId = None
     self._dwThreadId = None
     self._exit_code = None
     self._pid = None
     self._immutable = False
示例#2
0
    def _initialize_named_pipes_for_std(self):
        """Initialize the named pipes used for communication with the child
        process.
        """

        # used in generating the name for the pipe
        pid = os.getpid()

        # Security attributes for the named pipes, should not be inherited
        # by the child process. Those are used by the parent process to
        # communicate with the child process.
        _saAttr_pipe = win32security.SECURITY_ATTRIBUTES()
        _saAttr_pipe.bInheritHandle = 0
        # Security attributes for the file handles, they should be inherited
        # by the child process which will use them as stdin, stdout and stderr.
        # The parent process will close those handles after the child process
        # is created.
        _saAttr_file = win32security.SECURITY_ATTRIBUTES()
        _saAttr_file.bInheritHandle = 1

        def create_namedpipe_and_file(prefix,
                                      saAttr_pipe=_saAttr_pipe,
                                      saAttr_file=_saAttr_file):
            """Create the named pipe and the file for it.

            :param prefix: string representing the prefix which will be
                appended to the start of the name for the pipe
            :param saAttr_pipe: security attributes used to create
                the named pipe
            :param saAttr_file: security attributes used to create the file
            """
            pipename = (
                "%s_NamedPipe_%d_%d_%s" %
                (prefix, pid, time.time(), str(random.random()).split(".")[1]))
            # Create the named pipe
            pipe = NamedPipe(pipe_name=pipename, sec_attributes=saAttr_pipe)
            # Create the file for the previously created named pipe
            pipe.create_file(sec_attributes=saAttr_file)
            return pipe

        # Create the named pipes and the files used for parent - child process
        # communication.
        _pipe_stdin = create_namedpipe_and_file("Stdin")
        self._pipe_stdout = create_namedpipe_and_file("Stdout")
        self._pipe_stderr = create_namedpipe_and_file("Stderr")

        # Set the file handles from the named pipes as stdin, stdout and stderr
        # in startupinfo structure for the child process.
        self._si.hStdInput = _pipe_stdin.get_file_handle()
        self._si.hStdOutput = self._pipe_stdout.get_file_handle()
        self._si.hStdError = self._pipe_stderr.get_file_handle()
        self._si.dwFlags |= win32con.STARTF_USESTDHANDLES

        # Wrapping around stdin in order to be able to call self.stdin.close()
        # to close the stdin.
        self.stdin = ProcessWithNamedPipes.HandleClass(_pipe_stdin)
        _pipe_stdin = None
示例#3
0
文件: win_file.py 项目: SenadI/tea
    def __init__(self, filename, mode='r', encoding=None):
        if mode in ('r', 'r+'):
            creationDisposition = win32file.OPEN_EXISTING
            desiredAccess = win32con.GENERIC_READ
        elif mode == 'w':
            creationDisposition = win32con.CREATE_ALWAYS
            desiredAccess = win32con.GENERIC_WRITE
        elif mode in ('rw', 'wr', 'r+', 'w+', 'a+'):
            creationDisposition = win32con.OPEN_ALWAYS
            desiredAccess = win32con.GENERIC_READ | win32con.GENERIC_WRITE
        elif mode == 'a':
            creationDisposition = win32con.OPEN_ALWAYS
            desiredAccess = win32con.GENERIC_WRITE
        else:
            raise ValueError('Invalid access mode')
        self.filename = filename
        # shareMode = (win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE |
        #              win32con.FILE_SHARE_DELETE)
        shareMode = win32con.shareMode = (win32con.FILE_SHARE_READ
                                          | win32con.FILE_SHARE_WRITE)
        attributes = win32security.SECURITY_ATTRIBUTES()
        # dwFlagsAndAttributes = win32con.FILE_ATTRIBUTE_NORMAL
        dwFlagsAndAttributes = win32con.FILE_FLAG_WRITE_THROUGH

        self.encoding = encoding or 'utf-8'
        self.handle = win32file.CreateFile(filename, desiredAccess, shareMode,
                                           attributes, creationDisposition,
                                           dwFlagsAndAttributes, 0)
        win32api.SetHandleInformation(self.handle,
                                      win32con.HANDLE_FLAG_INHERIT, 0)
        if mode in ('a', 'a+'):
            self.seek(0, 2)
        self.file_size = win32file.GetFileSize(self.handle)
        self.is_closed = False
示例#4
0
    def start(self, cmd):
        sAttr = win32security.SECURITY_ATTRIBUTES()
        sAttr.bInheritHandle = True

        stdout_r, stdout_w = win32pipe.CreatePipe(sAttr, 0)
        stdin_r, stdin_w = win32pipe.CreatePipe(sAttr, 0)
        self.read_handle = stdout_r
        self.write_handle = stdout_w
        self.stdin_write = stdin_w

        si = win32process.STARTUPINFO()
        si.dwFlags = win32process.STARTF_USESHOWWINDOW | win32process.STARTF_USESTDHANDLES
        si.wShowWindow = win32con.SW_HIDE
        si.hStdInput = stdin_r  # file descriptor of origin stdin
        si.hStdOutput = stdout_w
        si.hStdError = stdout_w
        hProcess, hThread, dwProcessID, dwThreadID = win32process.CreateProcess(
            None, "cmd", None, None, True, win32process.CREATE_NEW_CONSOLE,
            None, None, si)
        self.dwProcessID = dwProcessID
        self.hProcess = hProcess
        sleep(0.5)
        if self.hProcess == 0:
            DebugOutput("Start Process Fail:{:d}".format(
                win32api.GetLastError()))
        DebugOutput('[*] pid: {:x}'.format(self.dwProcessID))
        self.Console_hwnd = get_hwnds_for_pid(self.dwProcessID)
        if len(self.Console_hwnd) == 0:
            raise Exception("Fail to run,No Process!")
        DebugOutput('[*] hwnd:{:x}'.format(self.Console_hwnd[0]))
示例#5
0
    def __init__(self, file):

        self.file = file

        self.type = {'LOCK_EX': 0, 'LOCK_NB': 0}

        secur_att = win32security.SECURITY_ATTRIBUTES()

        secur_att.Initialize()

        self.highbits = 0xffff0000  # high-order 32 bits of byte range to lock

        # make a handel with read/write and open or create if doesn't exist

        self.hfile = win32file.CreateFile(self.file,

                                          win32con.GENERIC_READ | win32con.GENERIC_WRITE,

                                          win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,

                                          secur_att,

                                          win32con.OPEN_ALWAYS,

                                          win32con.FILE_ATTRIBUTE_NORMAL, 0)
示例#6
0
def run_command_win32(cmd):
    sa = win32security.SECURITY_ATTRIBUTES()
    sa.bInheritHandle = True
    stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)

    si = win32process.STARTUPINFO()
    si.dwFlags = (win32process.STARTF_USESTDHANDLES
                  | win32process.STARTF_USESHOWWINDOW)
    si.wShowWindow = win32con.SW_HIDE
    si.hStdOutput = stdout_w

    process, thread, pid, tid = \
             win32process.CreateProcess(None, cmd, None, None, True,
                                        0, None, None, si)
    if process == None:
        return -1, ""

    # Must close the write handle in this process, or ReadFile will hang.
    stdout_w.Close()

    # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
    # which is okay because it happens when child process ends).
    data = ""
    error = 0
    while 1:
        try:
            hr, buffer = win32file.ReadFile(stdout_r, 4096)
            if hr != winerror.ERROR_IO_PENDING:
                data = data + buffer

        except pywintypes.error, e:
            if e.args[0] != winerror.ERROR_BROKEN_PIPE:
                error = 1
            break
示例#7
0
def _get_file_descriptor_for_new_secure_file_windows(path: str) -> int:
    try:
        file_access = win32file.GENERIC_READ | win32file.GENERIC_WRITE

        # Enables other processes to open this file with read-only access.
        # Attempts by other processes to open the file for writing while this
        # process still holds it open will fail.
        file_sharing = win32file.FILE_SHARE_READ

        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.SECURITY_DESCRIPTOR = (
            windows_permissions.get_security_descriptor_for_owner_only_perms())
        file_creation = win32file.CREATE_NEW  # fails if file exists
        file_attributes = win32file.FILE_FLAG_BACKUP_SEMANTICS

        handle = win32file.CreateFile(
            path,
            file_access,
            file_sharing,
            security_attributes,
            file_creation,
            file_attributes,
            _get_null_value_for_win32(),
        )

        detached_handle = handle.Detach()

        return win32file._open_osfhandle(detached_handle, os.O_RDWR)

    except Exception as ex:
        logger.error(f'Could not create a file at "{path}": {str(ex)}')
        raise ex
示例#8
0
    def _add_to_job_object(self):
        global _global_process_job_handle
        if _global_process_job_handle is not None:
            #This means that we are creating another process family - we'll all be in the same job
            return

        already_in_job = win32job.IsProcessInJob(win32api.GetCurrentProcess(), None)

        #Create a new job and put us in it before we create any children
        logger.debug("Creating job object and adding parent process to it")
        security_attrs = win32security.SECURITY_ATTRIBUTES()
        security_attrs.bInheritHandle = 0
        _global_process_job_handle = win32job.CreateJobObject(security_attrs, self.get_job_object_name())
        extended_info = win32job.QueryInformationJobObject(_global_process_job_handle, win32job.JobObjectExtendedLimitInformation)
        extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
        win32job.SetInformationJobObject(_global_process_job_handle, win32job.JobObjectExtendedLimitInformation, extended_info)
        try:
            win32job.AssignProcessToJobObject(_global_process_job_handle, win32api.GetCurrentProcess())
        except Exception as e:
            winv = sys.getwindowsversion()
            logger.error("Error raised during assignment of the current process to a new job object. " +\
                         "The process %s already in a job. " +\
                         "The windows version is %d.%d.\nError: %s",
                            "is" if already_in_job else "is not",
                            winv.major,
                            winv.minor,
                            _exception_str())

            if already_in_job and not (winv.major >= 6 and winv.minor >= 2):
                raise JobObjectAssignError("On Windows versions older than Windows 8 / Windows Server 2012, ProcessFamily relies on the parent process NOT being in a job already", e, already_in_job)

            raise JobObjectAssignError("Error raised during assignment of the current process to a new job object.", e, already_in_job)


        logger.debug("Added to job object")
示例#9
0
    def __init__(self, args):
        super().__init__(args)

        # Create an event which we will use to wait on. The "service stop"
        # request will set this event.
        # * We must make it inheritable so we can pass it to the child
        #   process via the cmd-line
        # * Must be manual reset so each child process and our service
        #   all get woken from a single set of the event.
        sa = win32security.SECURITY_ATTRIBUTES()
        sa.bInheritHandle = True
        self.hWaitStop = win32event.CreateEvent(sa, True, False, None)

        self.args = args
        self.dirs = None
        self.runner_prefix = None

        # Patch up the service messages file in a frozen exe.
        # (We use the py2exe option that magically bundles the .pyd files
        # into the .zip file - so servicemanager.pyd doesn't exist.)
        if is_frozen and servicemanager.RunningAsService():
            msg_file = os.path.join(os.path.dirname(sys.executable),
                                    "buildbot.msg")
            if os.path.isfile(msg_file):
                servicemanager.Initialize("BuildBot", msg_file)
            else:
                self.warning("Strange - '%s' does not exist" % (msg_file, ))
示例#10
0
def shell_as(th, enable_privs=0):
    t = thread(th)
    print t.as_text()
    new_tokenh = win32security.DuplicateTokenEx(
        th, 3, win32con.MAXIMUM_ALLOWED, win32security.TokenPrimary,
        win32security.SECURITY_ATTRIBUTES())
    print "new_tokenh: %s" % new_tokenh
    print "Impersonating..."
    if enable_privs:
        get_all_privs(new_tokenh)
    commandLine = "cmd"
    si = win32process.STARTUPINFO()
    print "pysecdump: Starting shell with required privileges..."
    (hProcess, hThread, dwProcessId,
     dwThreadId) = win32process.CreateProcessAsUser(
         new_tokenh,
         None,  # AppName
         commandLine,  # Command line
         None,  # Process Security
         None,  # ThreadSecurity
         1,  # Inherit Handles?
         win32process.NORMAL_PRIORITY_CLASS,
         None,  # New environment
         None,  # Current directory
         si)  # startup info.
    win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
    print "pysecdump: Quitting"
示例#11
0
    def test_copy_ownership_windows(self):
        system = win32security.ConvertStringSidToSid(SYSTEM_SID)
        security = win32security.SECURITY_ATTRIBUTES().SECURITY_DESCRIPTOR
        security.SetSecurityDescriptorOwner(system, False)

        with mock.patch('win32security.GetFileSecurity') as mock_get:
            with mock.patch('win32security.SetFileSecurity') as mock_set:
                mock_get.return_value = security
                filesystem.copy_ownership_and_apply_mode('dummy',
                                                         self.probe_path,
                                                         0o700,
                                                         copy_user=True,
                                                         copy_group=False)

        self.assertEqual(mock_set.call_count, 2)

        first_call = mock_set.call_args_list[0]
        security = first_call[0][2]
        self.assertEqual(system, security.GetSecurityDescriptorOwner())

        second_call = mock_set.call_args_list[1]
        security = second_call[0][2]
        dacl = security.GetSecurityDescriptorDacl()
        everybody = win32security.ConvertStringSidToSid(EVERYBODY_SID)
        self.assertTrue(dacl.GetAceCount())
        self.assertFalse([
            dacl.GetAce(index) for index in range(0, dacl.GetAceCount())
            if dacl.GetAce(index)[2] == everybody
        ])
示例#12
0
    def win32Spawn(sh, escape, cmd, args, spawnEnv):
        for var in spawnEnv:
            spawnEnv[var] = spawnEnv[var].encode("ascii", "replace")

        #sAttrs = win32security.SECURITY_ATTRIBUTES()
        #sAttrs.bInheritHandle = 1
        #hStdinR, hStdinW = win32pipe.CreatePipe(sAttrs, 0)
        #hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        #hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        #
        #pid = win32api.GetCurrentProcess()
        #
        #def replaceHandle(handle) :
        #  tmp = win32api.DuplicateHandle(pid, handle, pid, 0, 0, win32con.DUPLICATE_SAME_ACCESS)
        #  win32file.CloseHandle(handle)
        #  return tmp
        #
        #hStdinW = replaceHandle(hStdinW)
        #hStdoutR = replaceHandle(hStdoutR)
        #hStderrR = replaceHandle(hStderrR)

        sAttrs = win32security.SECURITY_ATTRIBUTES()
        startupInfo = win32process.STARTUPINFO()
        #startupInfo.hStdInput = hStdinR
        #startupInfo.hStdOutput = hStdoutW
        #startupInfo.hStdError = hStderrW
        #startupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
        newArgs = " ".join(map(escape, args[1:]))
        cmdLine = cmd + " " + newArgs

        # check for any special operating system commands
        if cmd == "del":
            for arg in args[1:]:
                win32file.DeleteFile(arg)
            exitCode = 0
        else:
            # otherwise execute the command.
            try:
                hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
                    None, cmdLine, None, None, 1, 0, spawnEnv, None,
                    startupInfo)
            except:
                errorCode = win32api.GetLastError()
                raise RuntimeError("Could not execute the following " +
                                   "command line (error code {}): {}".format(
                                       errorCode, cmdLine))
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            exitCode = win32process.GetExitCodeProcess(hProcess)

            #win32file.CloseHandle(hStdinR)
            #win32file.CloseHandle(hStdoutW)
            #win32file.CloseHandle(hStderrW)
            #with os.fdopen(msvcrt.open_osfhandle(hStdoutR, 0), "rb") as f: stdout = f.read()
            #with os.fdopen(msvcrt.open_osfhandle(hStderrR, 0), "rb") as f: stderr = f.read()
            #sys.stdout.write(stdout)
            #sys.stderr.write(stderr)

            win32file.CloseHandle(hProcess)
            win32file.CloseHandle(hThread)
        return exitCode
示例#13
0
def quiet_mkdir(path):
    # dropping to win32 for Windows
    # python modifies the permissions on Windows folders being created to be too permissive so we manually specify security info
    if sys.platform == "win32":
        import pywintypes
        import win32file
        import win32security
        try:
            """
            Owner            :
            Group            :
            DiscretionaryAcl : {NT AUTHORITY\SYSTEM: AccessAllowed (GenericAll), BUILTIN\Administrators: AccessAllowed (GenericAll)}
            SystemAcl        : {}
            RawDescriptor    : System.Security.AccessControl.CommonSecurityDescriptor
            """
            sddl = "D:PAI(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)"
            sec_descriptor = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
                sddl, win32security.SDDL_REVISION_1)
            sec_attributes = win32security.SECURITY_ATTRIBUTES()
            sec_attributes.SECURITY_DESCRIPTOR = sec_descriptor
            win32file.CreateDirectory(path, sec_attributes)
        except pywintypes.error:
            if not os.path.isdir(path):
                raise
    else:
        try:
            os.mkdir(path)
        except OSError:
            if not os.path.isdir(path):
                raise
示例#14
0
def mkdir(file_path: str, mode: int = 0o777) -> None:
    """
    Rewrite of original os.mkdir function, that will ensure on Windows that given mode
    is correctly applied.

    :param str file_path: The file path to open
    :param int mode: POSIX mode to apply on directory when created, Python defaults
                     will be applied if ``None``
    """
    if POSIX_MODE:
        return os.mkdir(file_path, mode)

    attributes = win32security.SECURITY_ATTRIBUTES()
    security = attributes.SECURITY_DESCRIPTOR
    user = _get_current_user()
    dacl = _generate_dacl(user, mode, _WINDOWS_UMASK.mask)
    security.SetSecurityDescriptorOwner(user, False)
    security.SetSecurityDescriptorDacl(1, dacl, 0)

    try:
        win32file.CreateDirectory(file_path, attributes)
    except pywintypes.error as err:
        # Handle native windows error into python error to be consistent with the API
        # of os.mkdir in the situation of a directory already existing.
        if err.winerror == winerror.ERROR_ALREADY_EXISTS:
            raise OSError(errno.EEXIST, err.strerror, file_path, err.winerror)
        raise err

    return None
示例#15
0
    def SvcDoRun(self):
        if hasattr(sys, "frozen"):
            this_dir = os.path.dirname(win32api.GetModuleFileName(None))
        else:
            this_dir = os.path.dirname(os.path.abspath(__file__))
        # TODO: maybe it is better to run this in a job object too
        with open(os.path.join(this_dir, 'npm.log'), 'w') as npm_log:
            subprocess.check_call('npm install',
                                  cwd=this_dir,
                                  shell=True,
                                  stdin=None,
                                  stdout=npm_log,
                                  stderr=subprocess.STDOUT)

        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.bInheritHandle = True
        startup = win32process.STARTUPINFO()
        startup.dwFlags |= win32process.STARTF_USESTDHANDLES
        startup.hStdInput = None
        startup.hStdOutput = win32file.CreateFile(
            os.path.join(this_dir, "service_stderr.log"),
            win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
            security_attributes, win32file.CREATE_ALWAYS, 0, None)
        startup.hStdError = win32file.CreateFile(
            os.path.join(this_dir, "service_stdout.log"),
            win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
            security_attributes, win32file.CREATE_ALWAYS, 0, None)
        (hProcess, hThread, processId, threadId) = win32process.CreateProcess(
            None, r'"C:\Program Files\nodejs\node.exe" node_worker.js', None,
            None, True, win32process.CREATE_SUSPENDED
            | win32process.CREATE_BREAKAWAY_FROM_JOB, None, this_dir, startup)

        assert not win32job.IsProcessInJob(hProcess, None)

        self.hJob = win32job.CreateJobObject(None, "")
        extended_info = win32job.QueryInformationJobObject(
            self.hJob, win32job.JobObjectExtendedLimitInformation)
        extended_info['BasicLimitInformation'][
            'LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK
        win32job.SetInformationJobObject(
            self.hJob, win32job.JobObjectExtendedLimitInformation,
            extended_info)
        win32job.AssignProcessToJobObject(self.hJob, hProcess)

        win32process.ResumeThread(hThread)
        win32api.CloseHandle(hThread)

        signalled = win32event.WaitForMultipleObjects(
            [self.hWaitStop, hProcess], False, win32event.INFINITE)
        if signalled == win32event.WAIT_OBJECT_0 + 1 and win32process.GetExitCodeProcess(
                hProcess) != 0:
            servicemanager.LogErrorMsg(
                self._svc_name_ + " process exited with non-zero status " +
                str(win32process.GetExitCodeProcess(hProcess)))
        win32api.CloseHandle(hProcess)
        win32api.CloseHandle(self.hJob)
        win32api.CloseHandle(self.hWaitStop)
        win32api.CloseHandle(startup.hStdOutput)
        win32api.CloseHandle(startup.hStdError)
示例#16
0
    def __init__(self, cmd, shell=False):
        self.queue = Queue.Queue()
        self.is_terminated = False
        self.wake_up_event = win32event.CreateEvent(None, 0, 0, None)

        exec_dir = os.getcwd()
        comspec = os.environ.get("COMSPEC", "cmd.exe")
        cmd = comspec + ' /c ' + cmd

        win32event.ResetEvent(self.wake_up_event)

        currproc = win32api.GetCurrentProcess()

        sa = win32security.SECURITY_ATTRIBUTES()
        sa.bInheritHandle = 1

        child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0)
        child_stdout_rd_dup = win32api.DuplicateHandle(
            currproc, child_stdout_rd, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stdout_rd)

        child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0)
        child_stderr_rd_dup = win32api.DuplicateHandle(
            currproc, child_stderr_rd, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stderr_rd)

        child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0)
        child_stdin_wr_dup = win32api.DuplicateHandle(
            currproc, child_stdin_wr, currproc, 0, 0,
            win32con.DUPLICATE_SAME_ACCESS)
        win32file.CloseHandle(child_stdin_wr)

        startup_info = win32process.STARTUPINFO()
        startup_info.hStdInput = child_stdin_rd
        startup_info.hStdOutput = child_stdout_wr
        startup_info.hStdError = child_stderr_wr
        startup_info.dwFlags = win32process.STARTF_USESTDHANDLES

        cr_flags = 0
        cr_flags = win32process.CREATE_NEW_PROCESS_GROUP

        env = os.environ.copy()
        self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(
            None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir),
            startup_info)

        win32api.CloseHandle(h_thread)

        win32file.CloseHandle(child_stdin_rd)
        win32file.CloseHandle(child_stdout_wr)
        win32file.CloseHandle(child_stderr_wr)

        self.__child_stdout = child_stdout_rd_dup
        self.__child_stderr = child_stderr_rd_dup
        self.__child_stdin = child_stdin_wr_dup

        self.exit_code = -1
示例#17
0
    def startBackgroundProcess(self):
        """Method to start a process running in the background.
		
		"""
        with process_lock:
            # security attributes for pipes
            sAttrs = win32security.SECURITY_ATTRIBUTES()
            sAttrs.bInheritHandle = 1

            # create pipes for the process to write to
            hStdin_r, hStdin = win32pipe.CreatePipe(sAttrs, 0)
            hStdout = win32file.CreateFile(
                _stringToUnicode(self.stdout),
                win32file.GENERIC_WRITE | win32file.GENERIC_READ,
                win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ
                | win32file.FILE_SHARE_WRITE, sAttrs, win32file.CREATE_ALWAYS,
                win32file.FILE_ATTRIBUTE_NORMAL, None)
            hStderr = win32file.CreateFile(
                _stringToUnicode(self.stderr),
                win32file.GENERIC_WRITE | win32file.GENERIC_READ,
                win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ
                | win32file.FILE_SHARE_WRITE, sAttrs, win32file.CREATE_ALWAYS,
                win32file.FILE_ATTRIBUTE_NORMAL, None)

            # set the info structure for the new process.
            StartupInfo = win32process.STARTUPINFO()
            StartupInfo.hStdInput = hStdin_r
            StartupInfo.hStdOutput = hStdout
            StartupInfo.hStdError = hStderr
            StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES

            # Create new handles for the thread ends of the pipes. The duplicated handles will
            # have their inheritence properties set to false so that any children inheriting these
            # handles will not have non-closeable handles to the pipes
            pid = win32api.GetCurrentProcess()
            tmp = win32api.DuplicateHandle(pid, hStdin, pid, 0, 0,
                                           win32con.DUPLICATE_SAME_ACCESS)
            win32file.CloseHandle(hStdin)
            hStdin = tmp

            # start the process, and close down the copies of the process handles
            # we have open after the process creation (no longer needed here)
            old_command = command = self.__quotePath(self.command)
            for arg in self.arguments:
                command = '%s %s' % (command, self.__quotePath(arg))
            try:
                self.__hProcess, self.__hThread, self.pid, self.__tid = win32process.CreateProcess(
                    None, command, None, None, 1, 0, self.environs,
                    os.path.normpath(self.workingDir), StartupInfo)
            except pywintypes.error as e:
                raise ProcessError("Error creating process %s: %s" %
                                   (old_command, e))

            win32file.CloseHandle(hStdin_r)
            win32file.CloseHandle(hStdout)
            win32file.CloseHandle(hStderr)

            # set the handle to the stdin of the process
            self.__stdin = hStdin
示例#18
0
 def _open_port(self, name):
     self._hfile = win32file.CreateFile(
         name,
         win32con.GENERIC_READ | win32con.GENERIC_WRITE,
         win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
         win32security.SECURITY_ATTRIBUTES(),
         win32con.OPEN_EXISTING,
         win32con.FILE_FLAG_OVERLAPPED,
         0)
示例#19
0
    def run(self):
        dirName = self.dirPath
        hdir = win32file.CreateFile(
            dirName, GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            win32security.SECURITY_ATTRIBUTES(), OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS, 0)

        filter = FILE_NOTIFY_CHANGE_FILE_NAME | \
                        FILE_NOTIFY_CHANGE_DIR_NAME \
                        | FILE_NOTIFY_CHANGE_ATTRIBUTES | \
                        FILE_NOTIFY_CHANGE_LAST_WRITE | \
                        FILE_NOTIFY_CHANGE_SIZE

        win32Handle = win32file.FindFirstChangeNotification(
            dirName, True, filter)

        while UtilFunc.programIsRunning():
            results =  win32file.ReadDirectoryChangesW(
                hdir,
                819600,
                True,
                FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \
                FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | \
                FILE_NOTIFY_CHANGE_CREATION,
                #                FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_LAST_ACCESS |FILE_NOTIFY_CHANGE_SECURITY
                None,
                None
                )

            for action, file in results:
                path = file
                if path == 'Thumbs.db':
                    continue

                path = os.path.join(dirName, path)
                path = path.replace('\\', '/')
                if '/.popoCloud/' in path or os.path.basename(
                        path) == '.popoCloud':
                    continue


#                print str(action) + " " + path

                if action == 1 or action == 5:
                    if os.path.isdir(path):
                        ProfileFunc.addToLibrary(path)
                    else:
                        ProfileFunc.addFileCache(path)
                elif action == 2 or action == 4:
                    ProfileFunc.delFileCache(path)
                elif action == 3:
                    if not os.path.isdir(path):
                        ProfileFunc.delFileCache(path)
                        ProfileFunc.addFileCache(path)

            win32file.FindNextChangeNotification(win32Handle)
示例#20
0
def _create_secure_directory_windows(path: str):
    try:
        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.SECURITY_DESCRIPTOR = (
            windows_permissions.get_security_descriptor_for_owner_only_perms())
        win32file.CreateDirectory(path, security_attributes)

    except Exception as ex:
        logger.error(f'Could not create a directory at "{path}": {str(ex)}')
        raise ex
示例#21
0
    def test_check_owner_windows(self):
        self.assertTrue(filesystem.check_owner(self.probe_path))

        system = win32security.ConvertStringSidToSid(SYSTEM_SID)
        security = win32security.SECURITY_ATTRIBUTES().SECURITY_DESCRIPTOR
        security.SetSecurityDescriptorOwner(system, False)

        with mock.patch('win32security.GetFileSecurity') as mock_get:
            mock_get.return_value = security
            self.assertFalse(filesystem.check_owner(self.probe_path))
示例#22
0
def create_directory(path, sddl):
    # Create security attributes
    security_attributes = win32security.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 0
    if sddl:
        security_attributes.SECURITY_DESCRIPTOR = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
            sddl, win32security.SDDL_REVISION_1,
        )

    # Windows API call
    win32file.CreateDirectory(path, security_attributes)
示例#23
0
def _GetSecurityAttributes(handle) -> win32security.SECURITY_ATTRIBUTES:
    """Returns the security attributes for a handle.

  Args:
    handle: A handle to an object.
  """
    security_descriptor = win32security.GetSecurityInfo(
        handle, win32security.SE_WINDOW_OBJECT,
        win32security.DACL_SECURITY_INFORMATION)
    result = win32security.SECURITY_ATTRIBUTES()
    result.SECURITY_DESCRIPTOR = security_descriptor
    return result
示例#24
0
 def __init__(self, filename):
     self._hfile = win32file.CreateFile(
         filename, win32con.GENERIC_READ | win32con.GENERIC_WRITE,
         win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
         win32security.SECURITY_ATTRIBUTES(), win32con.OPEN_EXISTING,
         win32con.FILE_FLAG_OVERLAPPED, 0)
     self._read_ovrlpd = pywintypes.OVERLAPPED()
     self._read_ovrlpd.hEvent = win32event.CreateEvent(
         None, True, False, None)
     self._write_ovrlpd = pywintypes.OVERLAPPED()
     self._write_ovrlpd.hEvent = win32event.CreateEvent(
         None, True, False, None)
示例#25
0
    def __init__(self, inherit_handle=True):
        """Create a pipe for Windows

        Create a new pipe

        Args:
            inherit_handle (bool): Whether the child can inherit this handle

        Returns:
            WinPipe: ``WinPipe`` instance.
        """
        attr = win32security.SECURITY_ATTRIBUTES()
        attr.bInheritHandle = inherit_handle
        self.rp, self.wp = win32pipe.CreatePipe(attr, 0)
示例#26
0
    def _createParentJob(self):
        # Create a new job that this process will be assigned to.
        job_name = ''  # must be anonymous otherwise we'd get conflicts
        security_attrs = win32security.SECURITY_ATTRIBUTES()
        security_attrs.bInheritHandle = 1
        job = win32job.CreateJobObject(security_attrs, job_name)
        extended_limits = win32job.QueryInformationJobObject(
            job, win32job.JobObjectExtendedLimitInformation)
        extended_limits['BasicLimitInformation'][
            'LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE

        win32job.SetInformationJobObject(
            job, win32job.JobObjectExtendedLimitInformation, extended_limits)
        return job
示例#27
0
文件: win.py 项目: umutbb/hubble
def dup_token(th):
    '''
    duplicate the access token
    '''
    # TODO: is `duplicate_token` the same?
    sec_attr = win32security.SECURITY_ATTRIBUTES()
    sec_attr.bInheritHandle = True
    return win32security.DuplicateTokenEx(
        th,
        win32security.SecurityImpersonation,
        win32con.MAXIMUM_ALLOWED,
        win32security.TokenPrimary,
        sec_attr,
    )
示例#28
0
def windows_create_pipe(sAttrs=-1, nSize=None):
    # Default values if parameters are not passed
    if sAttrs == -1:
        sAttrs = win32security.SECURITY_ATTRIBUTES()
        sAttrs.bInheritHandle = 1
    if nSize is None:
        # If this parameter is zero, the system uses the default buffer size.
        nSize = 0

    try:
        (read_pipe, write_pipe) = win32pipe.CreatePipe(sAttrs, nSize)
    except pywintypes.error:
        raise

    return (read_pipe, write_pipe)
示例#29
0
def run_command_win32(cmd):
    sa = win32security.SECURITY_ATTRIBUTES()
    sa.bInheritHandle = True
    stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)

    si = win32process.STARTUPINFO()
    si.dwFlags = (win32process.STARTF_USESTDHANDLES
                  | win32process.STARTF_USESHOWWINDOW)
    si.wShowWindow = win32con.SW_HIDE
    si.hStdOutput = stdout_w

    process, thread, pid, tid = \
             win32process.CreateProcess(None, cmd, None, None, True,
                                        0, None, None, si)
    if process == None:
        return -1, ""

    # Must close the write handle in this process, or ReadFile will hang.
    stdout_w.Close()

    # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
    # which is okay because it happens when child process ends).
    data = ""
    error = 0
    while 1:
        try:
            hr, buffer = win32file.ReadFile(stdout_r, 4096)
            if hr != winerror.ERROR_IO_PENDING:
                data = data + buffer

        except pywintypes.error as e:
            if e.args[0] != winerror.ERROR_BROKEN_PIPE:
                error = 1
            break

    if error:
        return -2, ""

    # Everything is okay --- the called process has closed the pipe.
    # For safety, check that the process ended, then pick up its exit code.
    win32event.WaitForSingleObject(process, win32event.INFINITE)
    if win32process.GetExitCodeProcess(process):
        return -3, ""

    global debug
    if debug:
        sys.stdout.write(data)
    return 0, data
示例#30
0
    def __init__(self):
        # Pipes to stream outputs.
        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.bInheritHandle = 1
        stdout_r, stdout_w = win32pipe.CreatePipe(security_attributes, 0)
        stderr_r, stderr_w = win32pipe.CreatePipe(security_attributes, 0)
        self.stdout_r = stdout_r.Detach()
        self.stdout_w = self._MakeInheritable(stdout_w)
        self.stderr_r = stderr_r.Detach()
        self.stderr_w = self._MakeInheritable(stderr_w)

        # Threads to read pipes and the actual contents returned.
        self.stdout_read_thread = None
        self.stdout = None
        self.stderr_read_thread = None
        self.stderr = None