예제 #1
0
def exportChartFileWindows(chartFile, pipeName, outputFile, key):
    handle = win32file.CreateFile(
        pipeName, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
        win32file.OPEN_EXISTING, 0, None)

    msg = fifo_msg()
    msg.cmd = OeserverdCmd.CMD_READ_ESENC
    msg.senc_name = chartFile
    msg.senc_key = key
    data = msg.pack()
    win32file.WriteFile(handle, data)

    output = os.open(outputFile, os.O_WRONLY | os.O_CREAT | os.O_BINARY)

    while True:
        try:
            data = win32file.ReadFile(handle, 1024 * 1024)
            os.write(output, data[1])
        except pywintypes.error as e:
            if e.args[0] == winerror.ERROR_PIPE_NOT_CONNECTED:
                break
            raise e
    os.close(output)
    win32file.CloseHandle(handle)
예제 #2
0
def win32_comports_bruteforce():
    import win32file
    import win32con

    ports = []
    for i in range(1, 257):
        portname = "\\\\.\\COM%i" % i
        try:
            mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
            port = \
                win32file.CreateFile(portname,
                                     mode,
                                     win32con.FILE_SHARE_READ,
                                     None,
                                     win32con.OPEN_EXISTING,
                                     0,
                                     None)
            if portname.startswith("\\"):
                portname = portname[4:]
            ports.append((portname, "Unknown", "Serial"))
            win32file.CloseHandle(port)
            port = None
        except Exception, e:
            pass
예제 #3
0
    def list_serial_ports(self):
        import win32file
        import win32con

        ports = []
        for i in range(1, 257):
            try:
                portname = "COM%i" % i
                mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
                port = \
                    win32file.CreateFile(portname,
                                         mode,
                                         win32con.FILE_SHARE_READ,
                                         None,
                                         win32con.OPEN_EXISTING,
                                         0,
                                         None)
                ports.append(portname)
                win32file.CloseHandle(port)
                port = None
            except Exception:
                pass

        return ports
예제 #4
0
def pipe_server(pipe_name):
    """Full-fledged pipe server that receives messages.

    Args:
        pipe_name (str): name of Windows named pipe
    """
    print("pipe server")
    client_done = False

    pipe = server_create_named_pipe(pipe_name)
    print("waiting for client")
    server_connect_and_wait(pipe)
    print("got client")

    while not client_done:
        try:
            resp_str = pipe_read(pipe)
            print(f"message: {resp_str}")
        except pywintypes.error as err:
            (winerror, funcname, strerror) = err.args
            if winerror == 109:
                print("Client closed access to pipe.")
                print("    {0}".format(winerror))
                print("    {0}".format(funcname))
                print("    {0}".format(strerror))
                client_done = True
            else:
                LOGGER.error("Windows error:\n    %s\n   %s\n    %s", winerror,
                             funcname, strerror)
                client_done = True
                raise
        finally:
            if client_done:
                win32file.CloseHandle(pipe)

    print("finished now")
예제 #5
0
    def create_mini_dump(self):
        file_name = self.generate_file_name()
        if os.path.isfile(file_name):
            os.remove(file_name)
        # Adjust privileges.
        self.adjust_privilege(win32security.SE_DEBUG_NAME)
        process_handle = win32api.OpenProcess(
            win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0,
            self.pid)
        print('process_handle Status: ',
              win32api.FormatMessage(win32api.GetLastError()))
        file_handle = win32file.CreateFile(
            file_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.CREATE_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None)

        print('file_handle Status: ',
              win32api.FormatMessage(win32api.GetLastError()))
        mini_dump = MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithDataSegs
        full_info_dump = (mini_dump | MiniDumpWithIndirectlyReferencedMemory
                          | MiniDumpScanMemory | MiniDumpWithFullMemory)

        success = dbghelp.MiniDumpWriteDump(
            process_handle.handle,  # Process handle
            self.pid,  # Process ID
            file_handle.handle,  # File handle
            full_info_dump,  # Dump type - MiniDumpNormal
            None,  # Exception parameter
            None,  # User stream parameter
            None,  # Callback parameter
        )

        print('MiniDump Status: ',
              win32api.FormatMessage(win32api.GetLastError()))
        win32file.CloseHandle(file_handle)
        return self.zip_and_delete_file(file_name)
예제 #6
0
def set_file_time(path, creation_time, last_access_time, last_write_time):
    # First windows API call
    handle = win32file.CreateFileW(
        path,
        SYMBOLS.GENERIC_WRITE,
        SYMBOLS.FILE_SHARE_READ | SYMBOLS.FILE_SHARE_WRITE | SYMBOLS.FILE_SHARE_DELETE,
        None,
        SYMBOLS.OPEN_EXISTING,
        SYMBOLS.FILE_FLAG_OPEN_REPARSE_POINT | SYMBOLS.FILE_FLAG_BACKUP_SEMANTICS,
        0,
    )

    # Prepare arguments
    def prepare(x):
        if x == 0:
            return None
        if isinstance(x, int):
            from datetime import timezone

            x = datetime(year=x, month=1, day=1, tzinfo=timezone.utc)
        return x

    creation_time = prepare(creation_time)
    last_access_time = prepare(last_access_time)
    last_write_time = prepare(last_write_time)

    # Second windows API call
    assert handle != win32file.INVALID_HANDLE_VALUE
    win32file.SetFileTime(
        handle, creation_time, last_access_time, last_write_time,
    )

    # Close the handle
    # This is necessary since we use a single process
    # for running all the commands from a single test case
    win32file.CloseHandle(handle)
예제 #7
0
 def run(self):
     try:
         self.logger.debug( "{} creating pipe".format( self.name ) )
         p = win32pipe.CreateNamedPipe( self.pipe_name,
                 win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_WRITE_THROUGH,
                 win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_WAIT,
                 MAX_THREADS, 0, 0, 30, None )
         try:
             self.logger.debug("{} connecting to pipe".format( self.name ) )
             self.semaphore.release()
             win32pipe.ConnectNamedPipe( p, None )
             self.logger.debug("{} Writing buffer to pipe".format( self.name ) )
             win32file.WriteFile( p, self.view )
             self.all_written = True
         finally:
             win32file.CloseHandle(p)
     except:
         self.logger.debug("{} got exception".format( self.name ) )
         self.logger.debug( traceback.format_exc() )
     finally:
         self.logger.debug("{} leaving".format( self.name ) )
     if self.dumpfile is not None:
         with open( self.dumpfile, "a" ) as f:
             f.write( self.view )
예제 #8
0
    def download(self, ftp, src, des, time):
        """
        Download file from FTP to local

        :param ftp: FTP connection var
        :param src: Source path - Cloud
        :param des: Destination path - local
        :param time: Time of modification
        """

        f = open(des, sC.WB_MODE)
        ftp.retrbinary(sC.RETR_ + src, f.write)
        f.close()
        self.logger.info(sC.STAR + sC.SPACE + pS.ADDED_ + sC.COLON + sC.SPACE +
                         des)
        win_file = win32file.CreateFile(
            des, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ
            | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None,
            win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
        # noinspection PyUnresolvedReferences
        win_time = pywintypes.Time(time)
        win32file.SetFileTime(win_file, win_time, None, None)
        win32file.CloseHandle(win_file)
        os.utime(des, (time, time))
예제 #9
0
class HIDThread(threading.Thread):
    def __init__(self, deviceName, devicePath, threadName=None):
        self.lockObject = threading.Lock()
        self.lockObject.acquire()
        self.handle = None
        self.text = Text
        self.deviceName = deviceName
        self.devicePath = devicePath
        self.abort = False
        self.initialized = False
        self._overlappedRead = win32file.OVERLAPPED()
        self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
        self._overlappedWrite = None
        self.RawCallback = None
        self.ButtonCallback = None
        self.ValueCallback = None
        self.StopCallback = None
        threading.Thread.__init__(
            self, name=threadName if threadName else self.devicePath)

    @eg.LogIt
    def AbortThread(self):
        self.abort = True
        if self._overlappedWrite:
            win32event.SetEvent(self._overlappedWrite.hEvent)
        win32event.SetEvent(self._overlappedRead.hEvent)

    def run(self):
        #open file/device
        try:
            handle = win32file.CreateFile(
                self.devicePath,
                win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
                None,  # no security
                win32con.OPEN_EXISTING,
                win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
                0)
        except pywintypes.error as (errno, function, strerror):
            self.lockObject.release()
            eg.PrintError(self.text.errorOpen + self.deviceName + " (" +
                          strerror + ")")
            return

        hidDLL = ctypes.windll.hid
        #setupapiDLL = ctypes.windll.setupapi

        #get preparsed data
        preparsedData = c_ulong()
        hidDLL.HidD_GetPreparsedData(int(handle), ctypes.byref(preparsedData))

        #getCaps
        hidpCaps = HIDP_CAPS()
        hidDLL.HidP_GetCaps(preparsedData, ctypes.byref(hidpCaps))

        n = hidpCaps.InputReportByteLength
        if n == 0:
            self.abort = True
            eg.PrintError(self.text.errorReportLength + self.deviceName)

        rt = c_int(0)  #report type input
        rl = c_ulong(n)  #report length
        maxDataL = hidDLL.HidP_MaxDataListLength(rt, preparsedData)

        #getting button caps
        bCapsArrL = c_ushort(hidpCaps.NumberInputButtonCaps)
        bCapsArrType = HIDP_BUTTON_CAPS * bCapsArrL.value
        bCapsArr = bCapsArrType()

        hidDLL.HidP_GetButtonCaps(rt, ctypes.byref(bCapsArr),
                                  ctypes.byref(bCapsArrL), preparsedData)

        #getting value caps
        vCapsArrL = c_ushort(hidpCaps.NumberInputValueCaps)
        vCapsArrType = HIDP_VALUE_CAPS * vCapsArrL.value
        vCapsArr = vCapsArrType()

        hidDLL.HidP_GetValueCaps(rt, ctypes.byref(vCapsArr),
                                 ctypes.byref(vCapsArrL), preparsedData)

        #parsing caps
        # prepare a list to find and store for each index
        # whether it is a button or value
        dataIndexType = [0] * hidpCaps.NumberInputDataIndices

        #list entries depending on caps
        for i in range(bCapsArrL.value):
            if bCapsArr[i].IsRange:
                for ii in range(bCapsArr[i].Info.Range.DataIndexMin,
                                bCapsArr[i].Info.Range.DataIndexMax + 1):
                    dataIndexType[ii] = 1
            else:
                ii = bCapsArr[i].Info.NotRange.DataIndex
                dataIndexType[ii] = 1

        for i in range(vCapsArrL.value):
            if vCapsArr[i].IsRange:
                for ii in range(vCapsArr[i].Info.Range.DataIndexMin,
                                vCapsArr[i].Info.Range.DataIndexMax + 1):
                    dataIndexType[ii] = 2
            else:
                ii = vCapsArr[i].Info.NotRange.DataIndex
                dataIndexType[ii] = 2

        #prepare data array with maximum possible length
        DataArrayType = HIDP_DATA * maxDataL
        data = DataArrayType()

        #initializing finished
        try:
            self.handle = handle
            self.initialized = True
            rc, newBuf = win32file.ReadFile(handle, n, self._overlappedRead)
            if eg.debugLevel:
                print(self.getName() + "init done. Entering loop")

            self.lockObject.release()

            while not self.abort:
                if rc == 997:  #error_io_pending
                    win32event.WaitForSingleObject(self._overlappedRead.hEvent,
                                                   win32event.INFINITE)

                buf = newBuf
                try:
                    win32event.ResetEvent(self._overlappedRead.hEvent)
                    rc, newBuf = win32file.ReadFile(handle, n,
                                                    self._overlappedRead)
                except pywintypes.error as (errno, function, strerror):
                    #device got disconnected so set status to waiting
                    self.abort = True
                    if errno == 1167:
                        eg.PrintError(self.text.errorDisconnected +
                                      self.deviceName)
                    else:
                        eg.PrintError(self.text.errorRead + self.deviceName +
                                      " (" + strerror + ")")

                #parse data
                if len(buf) == n and not self.abort:
                    #raw data events
                    if self.RawCallback:
                        try:
                            self.RawCallback(buf)
                        except Exception:
                            eg.PrintTraceback()

                    #handling button presses and values
                    if maxDataL != 0:
                        dataL = c_ulong(maxDataL)
                        hidDLL.HidP_GetData(rt, ctypes.byref(data),
                                            ctypes.byref(dataL), preparsedData,
                                            ctypes.c_char_p(str(buf)), rl)
                        #parse data to trigger events
                        btnPressed = []
                        values = {}
                        for i in range(dataL.value):
                            tmpIndex = data[i].DataIndex
                            if tmpIndex >= len(dataIndexType) or dataIndexType[
                                    tmpIndex] == 1:  #button
                                #collect buttons pressed
                                btnPressed.append(tmpIndex)
                            elif dataIndexType[tmpIndex] == 2:  #control value
                                values[tmpIndex] = int(data[i].Data.RawValue)
                            else:
                                eg.PrintError(self.text.errorInvalidDataIndex)

                        #value events
                        if self.ValueCallback:
                            try:
                                self.ValueCallback(values)
                            except Exception:
                                eg.PrintTraceback()

                        #button events
                        if self.ButtonCallback:
                            try:
                                self.ButtonCallback(btnPressed)
                            except Exception:
                                eg.PrintTraceback()
        except:
            self.abort = True
            eg.PrintError(self.text.errorRead + self.deviceName)

        finally:
            win32file.CloseHandle(handle)

            #free references
            hidDLL.HidD_FreePreparsedData(ctypes.byref(preparsedData))

            #HID thread finished
            if self.StopCallback:
                try:
                    self.StopCallback()
                except Exception:
                    eg.PrintTraceback()

            self.handle = None
예제 #10
0
 def close(self):
     """Closes the channel to the server.
     """
     if self.__pipe_handle is not None:
         win32file.CloseHandle(self.__pipe_handle)
         self.__pipe_handle = None
예제 #11
0
 def DisconnectSCTDC(self):
     try:
         win32file.CloseHandle(self.hpipe)
     except:
         print 'error Releasing pipe handle'
예제 #12
0
 def disconnect_from_child(self):
     if self.pipe:
         win32file.CloseHandle(self.pipe)
예제 #13
0
                    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)

        # 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(
예제 #14
0
        return

    try:
        fd = win32file.CreateFile(
            "\\\\.\\" + FLAGS.name,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

        try:
            t = time.time()
            image = Image(fd)
            print "Imaging to %s" % FLAGS.filename
            image.DumpWithRead(FLAGS.filename)
            print "\nCompleted in %s seconds" % (time.time() - t)
        finally:
            win32file.CloseHandle(fd)
    finally:
        try:
            win32service.ControlService(hSvc,
                                        win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass
        win32service.DeleteService(hSvc)
        win32service.CloseServiceHandle(hSvc)


if __name__ == "__main__":
    (FLAGS, args) = parser.parse_args()
    main()
예제 #15
0
 def __del__(self):
     win32file.CloseHandle(self.pipe_handle)
예제 #16
0
    def run(self, cmdline):
        # security attributes for pipes
        sAttrs = win32security.SECURITY_ATTRIBUTES()
        sAttrs.bInheritHandle = 1

        # create pipes
        hStdin_r, self.hStdin_w = win32pipe.CreatePipe(sAttrs, 0)
        self.hStdout_r, hStdout_w = win32pipe.CreatePipe(sAttrs, 0)
        self.hStderr_r, hStderr_w = win32pipe.CreatePipe(sAttrs, 0)

        # set the info structure for the new process.
        StartupInfo = win32process.STARTUPINFO()
        StartupInfo.hStdInput = hStdin_r
        StartupInfo.hStdOutput = hStdout_w
        StartupInfo.hStdError = hStderr_w
        StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
        # Mark doesn't support wShowWindow yet.
        # StartupInfo.dwFlags = StartupInfo.dwFlags | win32process.STARTF_USESHOWWINDOW
        # StartupInfo.wShowWindow = win32con.SW_HIDE

        # Create new output read handles and the input write handle. Set
        # the inheritance properties to FALSE. Otherwise, the child inherits
        # the these handles; resulting in non-closeable handles to the pipes
        # being created.
        pid = win32api.GetCurrentProcess()

        tmp = win32api.DuplicateHandle(
            pid,
            self.hStdin_w,
            pid,
            0,
            0,  # non-inheritable!!
            win32con.DUPLICATE_SAME_ACCESS)
        # Close the inhertible version of the handle
        win32file.CloseHandle(self.hStdin_w)
        self.hStdin_w = tmp
        tmp = win32api.DuplicateHandle(
            pid,
            self.hStdout_r,
            pid,
            0,
            0,  # non-inheritable!
            win32con.DUPLICATE_SAME_ACCESS)
        # Close the inhertible version of the handle
        win32file.CloseHandle(self.hStdout_r)
        self.hStdout_r = tmp

        # start the process.
        hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
            None,  # program
            cmdline,  # command line
            None,  # process security attributes
            None,  # thread attributes
            1,  # inherit handles, or USESTDHANDLES won't work.
            # creation flags. Don't access the console.
            0,  # Don't need anything here.
            # If you're in a GUI app, you should use
            # CREATE_NEW_CONSOLE here, or any subprocesses
            # might fall victim to the problem described in:
            # KB article: Q156755, cmd.exe requires
            # an NT console in order to perform redirection..
            None,  # no new environment
            None,  # current directory (stay where we are)
            StartupInfo)
        # normally, we would save the pid etc. here...

        # Child is launched. Close the parents copy of those pipe handles
        # that only the child should have open.
        # You need to make sure that no handles to the write end of the
        # output pipe are maintained in this process or else the pipe will
        # not close when the child process exits and the ReadFile will hang.
        win32file.CloseHandle(hStderr_w)
        win32file.CloseHandle(hStdout_w)
        win32file.CloseHandle(hStdin_r)

        self.stdin = os.fdopen(msvcrt.open_osfhandle(self.hStdin_w, 0), "wb")
        self.stdin.write('hmmmmm\r\n')
        self.stdin.flush()
        self.stdin.close()

        self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb")
        print("Read on stdout: ", repr(self.stdout.read()))

        self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb")
        print("Read on stderr: ", repr(self.stderr.read()))
예제 #17
0
    def init_client(self, control_message, additional_data):
        addr = additional_data[0]
        identifier = additional_data[1]
        sequence = additional_data[2]

        client_local = ICMP_Client()
        client_local.set_ICMP_received_identifier(identifier)
        client_local.set_ICMP_received_sequence(sequence)
        client_local.set_ICMP_sent_identifier(identifier)
        client_local.set_ICMP_sent_sequence(sequence)

        client_private_ip = control_message[0:4]
        client_public_source_ip = socket.inet_aton(addr[0])
        client_public_source_port = addr[1]

        # If this private IP is already used, the server removes that client.
        # For example: client reconnect on connection reset, duplicated configs
        # and yes, this can be used to kick somebody off the tunnel

        # close client related pipes
        for c in self.clients:
            if c.get_private_ip_addr() == client_private_ip:
                save_to_close = c
                self.clients.remove(c)
                if c.get_pipe_r() in self.rlist:
                    self.rlist.remove(c.get_pipe_r())

        found = False
        for c in self.packetselector.get_clients():
            if c.get_private_ip_addr() == client_private_ip:
                found = True
                self.packetselector.delete_client(c)

        # If client was created but not added to the PacketSelector, then the
        # pipes still need to be closed. This could happen when the authenti-
        # cation fails or gets interrupted.
        if not found:
            if self.os_type == common.OS_WINDOWS:
                import win32file

                try:
                    win32file.CloseHandle(save_to_close.get_pipe_r())
                    win32file.CloseHandle(save_to_close.get_pipe_w())
                except:
                    pass
            else:
                try:
                    save_to_close.get_pipe_r_fd().close()
                    save_to_close.get_pipe_w_fd().close()
                except:
                    pass

        # creating new pipes for the client
        pipe_r, pipe_w = os.pipe()
        client_local.set_pipes_fdnum(pipe_r, pipe_w)
        client_local.set_pipes_fd(os.fdopen(pipe_r, "r"),
                                  os.fdopen(pipe_w, "w"))

        # set connection related things and authenticated to True
        client_local.set_public_ip_addr(client_public_source_ip)
        client_local.set_public_src_port(client_public_source_port)
        client_local.set_private_ip_addr(client_private_ip)

        client_local.get_encryption().set_module(self.encryption.get_module())
        self.encryption = client_local.get_encryption()

        if self.encryption.get_module().get_step_count():
            # add encryption steps
            self.merge_cmh(self.encryption.get_module().get_cmh_struct())

        if self.authentication.get_step_count():
            # add authentication steps
            self.merge_cmh(self.authentication.get_cmh_struct())

        client_local.set_initiated(True)
        self.clients.append(client_local)

        return
    @staticmethod
    def execute(cmd, wait=False):
        try:
            (hProcess, hThread, dwProcessId,
             dwThreadId) = win32process.CreateProcess(
                 None, cmd, None, None, False, 0, None, None,
                 win32process.STARTUPINFO())
        except Exception, err:
            Logger.error("Unable to exec '%s': %s" % (cmd, str(err)))
            return 255

        if wait:
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            retValue = win32process.GetExitCodeProcess(hProcess)
        else:
            retValue = dwProcessId

        win32file.CloseHandle(hProcess)
        win32file.CloseHandle(hThread)

        return retValue

    @staticmethod
    def ArrayUnique(ar):
        r = []
        for i in ar:
            if i not in r:
                r.append(i)

        return r
예제 #19
0
    tun_recv = TunnelRecv()
    net_recv = NetworkRecv()

    timer = TimerThread(1)  # per second
    timer.start()

    while running:
        timeout = last_send + keepalive_interval - now
        rc, numberOfBytesTransferred, completionKey, overlapped = win32file.GetQueuedCompletionStatus(
            completion_port, int(1000 * timeout))
        if rc:
            if rc == win32event.WAIT_TIMEOUT:
                pass
            else:
                print "error %d" % rc
                break
        else:
            if overlapped and overlapped.object:
                overlapped.object.send(numberOfBytesTransferred)
            else:
                # timer
                now = time.time()

        if last_send + keepalive_interval <= now:
            keepalive()

    win32file.CloseHandle(completion_port)
    sock.close()
    win32file.CloseHandle(handle)
예제 #20
0
파일: win32.py 프로젝트: zf-w11/rekall
 def close(self):
     win32file.CloseHandle(self.fhandle)
예제 #21
0
    def __init__(self, reactor, protocol, command, args, environment, path):
        _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 {})

        cmdline = quoteArguments(args)
        # TODO: error detection here.
        def doCreate():
            self.hProcess, self.hThread, self.pid, 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)
예제 #22
0
    outfile, win32con.GENERIC_ALL,
    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, sa,
    win32con.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, None)

ctxt = 0
outctxt = 0
buf = None
readsize = 100

while 1:
    bytes_read, buf, ctxt = win32file.BackupRead(h, readsize, buf, False, True,
                                                 ctxt)
    if bytes_read == 0:
        break
    bytes_written, outctxt = win32file.BackupWrite(outh, bytes_read, buf,
                                                   False, True, outctxt)
    print('Written:', bytes_written, 'Context:', outctxt)
win32file.BackupRead(h, 0, buf, True, True, ctxt)
win32file.BackupWrite(outh, 0, str2bytes(''), True, True, outctxt)
win32file.CloseHandle(h)
win32file.CloseHandle(outh)

assert open(tempfile).read() == open(outfile).read(), "File contents differ !"
assert open(tempfile + ':streamdata').read() == open(
    outfile + ':streamdata').read(), "streamdata contents differ !"
assert open(tempfile + ':anotherstream').read() == open(
    outfile + ':anotherstream').read(), "anotherstream contents differ !"
assert ob2memory(win32security.GetFileSecurity(tempfile, all_sd_info))[:] == \
       ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:], "Security descriptors are different !"
## also should check Summary Info programatically
예제 #23
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 {})
        env = {
            os.fsdecode(key): os.fsdecode(value)
            for key, value in env.items()
        }

        # Make sure all the arguments are Unicode.
        args = [os.fsdecode(x) for x in args]

        cmdline = quoteArguments(args)

        # The command, too, needs to be Unicode, if it is a value.
        command = os.fsdecode(command) if command else command
        path = os.fsdecode(path) if path else path

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

        try:
            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))
예제 #24
0
 def mClose(self):
     if self._oFd:
         win32file.CloseHandle(self._oFd)
         self._oFd = 0
예제 #25
0
import win32file as w  #use windows API

print("Starting")

# Open Driver as a File Device
hdevice = w.CreateFile("\\\\.\\ReadWrite", 0x80000000 | 0x40000000, 0, None, 3,
                       0x00000080, None)

w.WriteFile(hdevice, "Hello", None)
tam, string = w.ReadFile(hdevice, 200, None)
print(string)
w.CloseHandle(hdevice)
예제 #26
0
# Tested on Python 3.4

import win32file
import pywintypes

GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 3
FILE_WRITE_ACCESS = 0x0002
FILE_SHARE_WRITE = 0x00000002
FILE_ATTRIBUTE_NORMAL = 0x00000080
METHOD_BUFFERED = 0
FILE_DEVICE_PROCMON_LOG = 0x00009535
PROCMON_DEBUGGER_HANDLER = r"\\.\Global\ProcmonDebugLogger"
IOCTL_EXTERNAL_LOG_DEBUGOUT = 2503311876  # Why: https://github.com/zippy1981/ProcMon.LINQpad/blob/master/ProcMonDebugOutput.linq

msg = bytes("Hello ProcMon from python with pywin32!", 'UTF-16')
msgLen = len(msg)
handle = win32file.CreateFile(PROCMON_DEBUGGER_HANDLER, GENERIC_WRITE,
                              FILE_SHARE_WRITE, None, OPEN_EXISTING,
                              FILE_ATTRIBUTE_NORMAL, 0)
if handle == -1: raise RuntimeWarning("ProcMon doesn't appear to be running")
else:
    try:
        win32file.DeviceIoControl(handle, IOCTL_EXTERNAL_LOG_DEBUGOUT, msg,
                                  None)
    except pywintypes.error as e:
        if (e.winerror != 87):
            raise  # Error 87 means ProcMon simply isn't running

    win32file.CloseHandle(handle)
예제 #27
0
def GetDeviceDescriptions():
    """
    gets inforamtions about the available HID as a list of DeviceDescription objects
    """
    deviceList = []

    #dll references
    setupapiDLL = ctypes.windll.setupapi
    hidDLL = ctypes.windll.hid

    #prepare Interfacedata
    interfaceInfo = SP_DEVICE_INTERFACE_DATA()
    interfaceInfo.cbSize = sizeof(interfaceInfo)

    #prepare InterfaceDetailData Structure
    interfaceDetailData = SP_DEVICE_INTERFACE_DETAIL_DATA_A()
    interfaceDetailData.cbSize = 5

    #prepare HIDD_ATTRIBUTES
    hiddAttributes = HIDD_ATTRIBUTES()
    hiddAttributes.cbSize = sizeof(hiddAttributes)

    #get guid for HID device class
    g = GUID()
    hidDLL.HidD_GetHidGuid(byref(g))

    #get handle to the device information set
    hinfo = setupapiDLL.SetupDiGetClassDevsA(
        byref(g), None, None, DIGCF_PRESENT + DIGCF_DEVICEINTERFACE)

    #enumerate devices
    i = 0
    while setupapiDLL.SetupDiEnumDeviceInterfaces(hinfo, None, byref(g), i,
                                                  byref(interfaceInfo)):
        i += 1

        #get the required size
        requiredSize = c_ulong()
        setupapiDLL.SetupDiGetDeviceInterfaceDetailA(hinfo,
                                                     byref(interfaceInfo),
                                                     None, 0,
                                                     byref(requiredSize), None)
        if requiredSize.value > 250:
            eg.PrintError(Text.errorRetrieval)
            continue  #prevent a buffer overflow

        #get the actual info
        setupapiDLL.SetupDiGetDeviceInterfaceDetailA(
            hinfo, byref(interfaceInfo), byref(interfaceDetailData),
            requiredSize, pointer(requiredSize), None)
        devicePath = interfaceDetailData.DevicePath

        #get handle to HID device
        try:
            hidHandle = win32file.CreateFile(
                devicePath, win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None,
                win32con.OPEN_EXISTING, 0, 0)
            #skipping devices which cannot be opened
            #(e.g. mice & keyboards, which are opened exclusively by OS)
            if int(hidHandle) <= 0:
                continue
        except:
            continue

        #getting additional info
        hidDLL.HidD_GetAttributes(int(hidHandle), byref(hiddAttributes))

        #prepare string buffer for device info strings
        hidpStringType = c_wchar * 128
        infoStr = hidpStringType()

        #getting manufacturer
        result = hidDLL.HidD_GetManufacturerString(int(hidHandle),
                                                   byref(infoStr),
                                                   ctypes.sizeof(infoStr))
        if not result or len(infoStr.value) == 0:
            #build a generic ManufacturerString with the vendor ID
            vendorString = Text.vendorID + str(hiddAttributes.VendorID)
        else:
            vendorString = infoStr.value

        #getting device name
        result = hidDLL.HidD_GetProductString(int(hidHandle), byref(infoStr),
                                              ctypes.sizeof(infoStr))
        if not result or len(infoStr.value) == 0:
            #getting product name via registry
            devicePathSplit = devicePath[4:].split("#")
            regHandle = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                "SYSTEM\\CurrentControlSet\\Enum\\" + devicePathSplit[0] +
                "\\" + devicePathSplit[1] + "\\" + devicePathSplit[2])
            productString, regType = _winreg.QueryValueEx(
                regHandle, "DeviceDesc")
            _winreg.CloseKey(regHandle)
        else:
            productString = infoStr.value

        #close handle
        win32file.CloseHandle(hidHandle)

        #create object with all the infos
        device = DeviceDescription(devicePath, hiddAttributes.VendorID,
                                   vendorString, hiddAttributes.ProductID,
                                   productString, hiddAttributes.VersionNumber)

        #add device to internal list
        deviceList.append(device)

    #end loop
    #destroy deviceinfolist
    setupapiDLL.SetupDiDestroyDeviceInfoList(hinfo)
    return deviceList
예제 #28
0
 def closePipe(self):
     win32file.CloseHandle(self.pipe_handle)
예제 #29
0
 def close_handles(self):
     import win32file
     for h in itervalues(self.handle_map):
         win32file.CloseHandle(h)
     self.handle_map = {}
예제 #30
0
 def close(self):
     if self.handle is not None:
         win32file.CancelIo(self.handle)
         win32file.CloseHandle(self.handle)
     if self.event is not None:
         win32file.CloseHandle(self.event)