Exemplo n.º 1
0
    def _addCounter(self, processName, counterType, counterName):
        pCounterPathElements = _PDH_COUNTER_PATH_ELEMENTS_A(
            LPSTR(None),
            LPSTR(counterType),
            LPSTR(processName),
            LPSTR(None),
            DWORD(-1),
            LPSTR(counterName)
        )

        pcchbufferSize = DWORD(0)

        # First run we just try to get the buffer size so we can allocate a
        # string big enough to fill it
        if pdh.PdhMakeCounterPathA(pointer(pCounterPathElements),
                                   LPCSTR(0), pointer(pcchbufferSize),
                                   DWORD(0)) != _PDH_MORE_DATA:
            raise TalosError(
                "Could not create counter path for counter %s for %s"
                % (counterName, processName)
            )

        szFullPathBuffer = LPCSTR('\0'*pcchbufferSize.value)
        # Then we run to get the actual value
        if pdh.PdhMakeCounterPathA(pointer(pCounterPathElements),
                                   szFullPathBuffer, pointer(pcchbufferSize),
                                   DWORD(0)) != 0:
            raise TalosError(
                "Could not create counter path for counter %s for %s"
                % (counterName, processName)
            )

        path = szFullPathBuffer.value

        hq = HANDLE()
        if pdh.PdhOpenQuery(None, None, byref(hq)) != 0:
            raise TalosError("Could not open win32 counter query")

        hc = HANDLE()
        if pdh.PdhAddCounterA(hq, path, 0, byref(hc)) != 0:
            raise TalosError("Could not add win32 counter %s" % path)

        self.registeredCounters[counterName] = [hq, [(hc, path)]]
Exemplo n.º 2
0
 def get_part_number(self):
     if ComPort.__dll is None:
         return 0
     handle = HANDLE(self._port_handle)
     part_num = BYTE()
     assert ComPort.__dll.CP210xRT_GetPartNumber(
         handle,
         byref(part_num)) in [0,
                              3], "Get Part number failed" + self.ERROR_MSG
     return part_num.value % 10
Exemplo n.º 3
0
def get_process_name(pid):
    hProcess = HANDLE(0)
    hProcess = Kernel32.OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
    if not hProcess:
        raise OSError('Could not open PID %s' % pid)
    try:
        return GetModuleFileNameEx(hProcess, 0)
    finally:
        Kernel32.CloseHandle(hProcess)
 def write(A, b):
     B = len(b)
     E = get_buffer(b)
     F = min(B, MAX_BYTES_WRITTEN) // 2
     C = c_ulong()
     WriteConsoleW(HANDLE(A.handle), E, F, byref(C), _A)
     D = 2 * C.value
     if D == 0 and B > 0:
         raise OSError(A._get_error_message(GetLastError()))
     return D
Exemplo n.º 5
0
def enable_vt():
    h = GetStdHandle(STD_OUTPUT_HANDLE)
    if h is None or h == HANDLE(-1):
        return False
    mode = DWORD()
    if not GetConsoleMode(h, byref(mode)):
        return False
    if SetConsoleMode(h, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING):
        return True
    return False
Exemplo n.º 6
0
def CanCreateJobObject():
    currentProc = GetCurrentProcess()
    if IsProcessInJob(currentProc):
        jobinfo = QueryInformationJobObject(
            HANDLE(0), 'JobObjectExtendedLimitInformation')
        limitflags = jobinfo['BasicLimitInformation']['LimitFlags']
        return bool(limitflags & JOB_OBJECT_LIMIT_BREAKAWAY_OK) or bool(
            limitflags & JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)
    else:
        return True
Exemplo n.º 7
0
 def quit_alternate_screen(self):
     """
     Make stdout again the active buffer.
     """
     if self._in_alternate_screen:
         stdout = HANDLE(self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE))
         self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
         self._winapi(windll.kernel32.CloseHandle, self.hconsole)
         self.hconsole = stdout
         self._in_alternate_screen = False
def isMarshalledIAccessible(IAccessibleObject):
	"""Looks at the location of the first function in the IAccessible object's vtable (IUnknown::AddRef) to see if it was implemented in oleacc.dll (its local) or ole32.dll (its marshalled)."""
	if not isinstance(IAccessibleObject,IAccessible):
		raise TypeError("object should be of type IAccessible, not %s"%IAccessibleObject)
	buf=create_unicode_buffer(1024)
	addr=POINTER(c_void_p).from_address(super(comtypes._compointer_base,IAccessibleObject).value).contents.value
	handle=HANDLE()
	windll.kernel32.GetModuleHandleExW(6,addr,byref(handle))
	windll.kernel32.GetModuleFileNameW(handle,buf,1024)
	return not buf.value.lower().endswith('oleacc.dll')
Exemplo n.º 9
0
 def path(self) -> Path:
     guid = _GUID(self.uuid)
     path = LPWSTR()
     if _GetFolderPath(byref(guid), 0, HANDLE(0), byref(path)) < 0:
         raise FileNotFoundError(
             f"Could not find path with GUID {self.uuid}")
     try:
         return Path(path.value)
     finally:
         _CoTaskMemFree(path)
Exemplo n.º 10
0
 def __init__(self, path):
     self._path = path
     self._file = None  # The file handle for this device
     self._winusb = HANDLE()  # The WinUSB handle for the device's default interface
     self._interface = 0
     self._endpoints = {}  # type: Dict[int, EndpointIn]
     self._event = None
     self._event_list = (HANDLE * kernel32.MAXIMUM_WAIT_OBJECTS)()
     self._event_callback_fn = None
     self._control_transfer = None
     self._update_event_list()
Exemplo n.º 11
0
 def __init__(self,
              stdout: TextIO,
              default_color_depth: Optional[ColorDepth] = None) -> None:
     self.win32_output = Win32Output(
         stdout, default_color_depth=default_color_depth)
     self.vt100_output = Vt100_Output(
         stdout,
         lambda: Size(0, 0),
         default_color_depth=default_color_depth)
     self._hconsole = HANDLE(
         windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE))
Exemplo n.º 12
0
    def __init__(self, numThreads=NULL):
        self.running = True
        self.handle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, HANDLE(0),
                                             NULL, numThreads)
        if self.handle == 0:
            raise WinError()

        self.numThreads = numThreads
        stackless.tasklet(self.poll)()
        self.overlappedByID = {}
        self._sleepers = []
Exemplo n.º 13
0
def set_regkey(rootkey, subkey, name, type_, value):
    if type_ == REG_SZ:
        value = unicode(value)
    if type_ == REG_MULTI_SZ:
        value = u"\u0000".join(value) + u"\u0000\u0000"

    res_handle = HANDLE()
    res = RegOpenKeyExW(rootkey, subkey, 0, KEY_SET_VALUE, byref(res_handle))
    if not res:
        RegSetValueExW(res_handle, name, 0, type_, value, len(value))
        RegCloseKey(res_handle)
Exemplo n.º 14
0
    def set_brightness(
        cls, value: int,
        display: Optional[Union[int, str]] = None,
        no_return: bool = False
    ) -> Union[List[int], None]:
        '''
        Sets the brightness for all connected displays using the `ctypes.windll` API

        Args:
            display (int or str): The specific display you wish to query.
                Can be index, name, model, serial or edid string.
                `int` is faster as it isn't passed to `filter_monitors` to be matched against.
                `str` is slower as it is passed to `filter_monitors` to match to a display.
            no_return (bool): if set to `True` this function will return `None`

        Returns:
            list: list of ints (0 to 100) (the result of `VCP.get_brightness`) if `no_return` is False
            None: if `no_return` is True

        Examples:
            ```python
            import screen_brightness_control as sbc

            # Set the brightness for all detected displays to 50%
            sbc.windows.VCP.set_brightness(50)

            # Set the brightness for the primary display to 75%
            sbc.windows.VCP.set_brightness(75, display = 0)

            # Set the brightness for a secondary display to 25%
            sbc.windows.VCP.set_brightness(25, display = 1)

            # Set the brightness for a display with the model 'GL2450H' to 100%
            sbc.windows.VCP.set_brightness(100, display = 'GL2450H')
            ```
        '''
        if type(display) == int:
            indexes = [display]
        else:
            # see VCP.set_brightness for the explanation for why we always gather this list
            indexes = [i['index'] for i in filter_monitors(display=display, haystack=cls.get_display_info())]

        __cache__.expire(startswith='vcp_brightness_')

        count = 0
        for m in cls.iter_physical_monitors():
            if display is None or (count in indexes):
                for _ in range(10):
                    if windll.dxva2.SetVCPFeature(HANDLE(m), BYTE(0x10), DWORD(value)):
                        break
                    else:
                        time.sleep(0.02)
            count += 1
        return cls.get_brightness(display=display) if not no_return else None
Exemplo n.º 15
0
    def disable_mouse_support(self) -> None:
        ENABLE_MOUSE_INPUT = 0x10
        handle = HANDLE(windll.kernel32.GetStdHandle(STD_INPUT_HANDLE))

        original_mode = DWORD()
        self._winapi(windll.kernel32.GetConsoleMode, handle, pointer(original_mode))
        self._winapi(
            windll.kernel32.SetConsoleMode,
            handle,
            original_mode.value & ~ENABLE_MOUSE_INPUT,
        )
Exemplo n.º 16
0
def create_win32_event() -> HANDLE:
    """
    Creates a Win32 unnamed Event .
    http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
    """
    return HANDLE(
        windll.kernel32.CreateEventA(
            pointer(SECURITY_ATTRIBUTES()),
            BOOL(True),  # Manual reset event.
            BOOL(False),  # Initial state.
            None,  # Unnamed event object.
        ))
Exemplo n.º 17
0
def spray():
    """Spray the Kernel Pool with IO_COMPLETION_OBJECT. Each object
    is 0x60 bytes in length and is allocated from the Nonpaged kernel pool"""
    global handles
    handles = {}
    IO_COMPLETION_OBJECT = 1
    for i in range(0, 50000):
        hHandle = HANDLE(0)
        ntdll.NtAllocateReserveObject(byref(hHandle), 0x0,
                                      IO_COMPLETION_OBJECT)
        handles[i] = hHandle.value
    print "[+] Spray done!"
Exemplo n.º 18
0
def set_regkey(rootkey, subkey, name, type_, value):
    if type_ == _winreg.REG_SZ:
        value = unicode(value)
    if type_ == _winreg.REG_MULTI_SZ:
        value = u"\u0000".join(value) + u"\u0000\u0000"

    res_handle = HANDLE()
    res = RegCreateKeyExW(rootkey, subkey, 0, None, 0, _winreg.KEY_ALL_ACCESS,
                          0, byref(res_handle), None)
    if not res:
        RegSetValueExW(res_handle, name, 0, type_, value, len(value))
        RegCloseKey(res_handle)
Exemplo n.º 19
0
    def win32_refresh_window(cls):
        """
        Call win32 API to refresh the whole Window.

        This is sometimes necessary when the application paints background
        for completion menus. When the menu disappears, it leaves traces due
        to a bug in the Windows Console. Sending a repaint request solves it.
        """
        # Get console handle
        handle = HANDLE(windll.kernel32.GetConsoleWindow())

        RDW_INVALIDATE = 0x0001
        windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE))
Exemplo n.º 20
0
 def allocateMemory(self, no_of_buffers=1):
     self.no_of_buffers = no_of_buffers
     for i in range(min(no_of_buffers, 1)):
         self.picEvent.append(HANDLE())
         self.addr.append(c_void_p())
         err = AllocateBufferEx(self.hdriver, byref(self.allocate),
                                self.bufsize, byref(self.picEvent[i]),
                                byref(self.addr[i]))
         self.allocate = c_int(-1)
         if (err != 0):
             print "Allocation failed!"
             self.no_of_buffers = 0
             break
Exemplo n.º 21
0
 def check(self, password):
     token = HANDLE()
     domain = ''  #os.environ.get('COMPUTERNAME')
     status = LogonUser(self.username, domain, password,
                        LOGON32_LOGON_NETWORK_CLEARTEXT,
                        LOGON32_PROVIDER_DEFAULT, byref(token))
     error = GetLastError()
     if status:
         CloseHandle(token)
         return True
     log.error("Error: win32 authentication failed:")
     log.error(" %s", FormatError(error))
     return False
Exemplo n.º 22
0
def windows_set_vt100(enable):
    """En/disable Windows 10 cmd.exe ANSI VT Virtual Terminal Processing."""
    from ctypes import byref, POINTER, windll, WINFUNCTYPE
    from ctypes.wintypes import BOOL, DWORD, HANDLE

    GetStdHandle = WINFUNCTYPE(HANDLE,
                               DWORD)(('GetStdHandle', windll.kernel32))

    GetFileType = WINFUNCTYPE(DWORD, HANDLE)(('GetFileType', windll.kernel32))

    GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
        ('GetConsoleMode', windll.kernel32))

    SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE,
                                 DWORD)(('SetConsoleMode', windll.kernel32))

    FILE_TYPE_CHAR = 0x0002

    stdin = 0
    stdout = 1
    stderr = 2
    stdio = (stdin, stdout, stderr)

    h = [GetStdHandle(-1 - n) for n in stdio]
    if any([
            h[n] is None or h[n] == HANDLE(-1)
            or (GetFileType(h[n]) & 3) != FILE_TYPE_CHAR for n in stdio
    ]):
        print("Error opening handles")
        return False

    mode = [DWORD() for _ in stdio]
    if not all([GetConsoleMode(h[n], byref(mode[n])) for n in stdio]):
        print("Error getting handle modes")
        return False
    print(*["Mode[{}] before: 0x{:x}".format(n, mode[n].value) for n in stdio])

    if enable:
        print("Enabling ANSI")
        SetConsoleMode(h[stdout],
                       mode[stdout].value | ENABLE_VIRTUAL_TERMINAL_PROCESSING
                       )  # | ENABLE_VIRTUAL_TERMINAL_INPUT)
    else:
        print("Disabling ANSI")
        SetConsoleMode(h[stdout],
                       mode[stdout].value & ~ENABLE_VIRTUAL_TERMINAL_PROCESSING
                       )  # | ENABLE_VIRTUAL_TERMINAL_INPUT))

    print(*["Mode[{}] after: 0x{:x}".format(n, mode[n].value) for n in stdio])

    return True
Exemplo n.º 23
0
    def _create_pty(self, pty_size):
        hPipePTYOut = HANDLE(INVALID_HANDLE_VALUE)
        hPipePTYIn = HANDLE(INVALID_HANDLE_VALUE)

        hPipeOut = HANDLE(INVALID_HANDLE_VALUE)
        hPipeIn = HANDLE(INVALID_HANDLE_VALUE)

        hPTY = HPCON(INVALID_HANDLE_VALUE)

        try:
            if not CreatePipe(byref(hPipePTYIn), byref(hPipeIn), None, 0):
                raise WinError(get_last_error())

            if not CreatePipe(byref(hPipeOut), byref(hPipePTYOut), None, 0):
                raise WinError(get_last_error())

            if CreatePseudoConsole(COORD(*pty_size), hPipePTYIn, hPipePTYOut,
                                   0, byref(hPTY)) != S_OK:
                raise WinError(get_last_error())

            logger.info('hPTY: %x', hPTY.value)

            if hPTY.value == INVALID_HANDLE_VALUE:
                raise WinError(get_last_error())

        except WinError:
            for handle in (hPipePTYOut, hPipePTYIn, hPipeOut, hPipeIn):
                if handle.value != INVALID_HANDLE_VALUE:
                    CloseHandle(handle)

            raise

        CloseHandle(hPipePTYIn)
        CloseHandle(hPipePTYOut)

        self._pty = hPTY
        self._conout_pipe = hPipeOut
        self._conin_pipe = hPipeIn
Exemplo n.º 24
0
    def write(self, b):
        bytes_to_be_written = len(b)
        buf = get_buffer(b)
        code_units_to_be_written = min(bytes_to_be_written,
                                       MAX_BYTES_WRITTEN) // 2
        code_units_written = c_ulong()

        WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,
                      byref(code_units_written), None)
        bytes_written = 2 * code_units_written.value

        if bytes_written == 0 and bytes_to_be_written > 0:
            raise OSError(self._get_error_message(GetLastError()))
        return bytes_written
Exemplo n.º 25
0
 def CreatePipeSecurityObject(self):
     TOKEN_QUERY = 0x8
     cur_proc = GetCurrentProcess()
     log("CreatePipeSecurityObject() GetCurrentProcess()=%#x", cur_proc)
     process = HANDLE()
     if OpenProcessToken(HANDLE(cur_proc), TOKEN_QUERY, ctypes.byref(process))==0:
         raise WindowsError()
     log("CreatePipeSecurityObject() process=%s", process.value)
     data_size = DWORD()
     GetTokenInformation(process, TOKEN_QUERY, 0, 0, ctypes.byref(data_size))
     log("CreatePipeSecurityObject() GetTokenInformation data size%s", data_size.value)
     data = ctypes.create_string_buffer(data_size.value)
     if GetTokenInformation(process, TOKEN_QUERY, ctypes.byref(data), ctypes.sizeof(data), ctypes.byref(data_size))==0:
         raise WindowsError()
     user = ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents
     log("CreatePipeSecurityObject() user: SID=%s, attributes=%#x", user.SID, user.ATTRIBUTES)
     SD = SECURITY_DESCRIPTOR()
     InitializeSecurityDescriptor(ctypes.byref(SD), SECURITY_DESCRIPTOR.REVISION)
     SetSecurityDescriptorOwner(ctypes.byref(SD), user.SID, 0)
     SA = SECURITY_ATTRIBUTES()
     SA.descriptor = SD
     SA.bInheritHandle = False
     return SA
Exemplo n.º 26
0
    def __init__(self, board=0):
        super(self.__class__, self).__init__()
        self.hdriver = HANDLE()
        err = InitBoard(board, byref(self.hdriver))
        if (err == PCO_NOERROR):
            print "Initializing successful"
        else:
            print "Initialization unsuccessful."
        self.path = os.path.dirname(os.path.realpath("__file__"))
        self.isrunning = 0
        self.prepared = False
        self.live = False
        self.hbin = 0
        self.vbin = 0
        self.gain = 0
        self.exp_time = 0
        self.mode = 0x11
        self.no_of_buffers = 0
        self.buf_index = 0
        SetMode(self.hdriver, self.mode, 0, self.exp_time, self.hbin,
                self.vbin, self.gain, 0, 12, 0)
        self.ccdxsize, self.ccdysize, self.width, self.height, self.bitpix = GetSizes(
            self.hdriver)
        self.bufsize = self.width * self.height * ((self.bitpix + 7) / 8)
        self.allocate = c_int(-1)

        # Queues that hold the data collected in the camera.
        self.pic = np.zeros((self.ccdysize, self.ccdxsize))
        self.q = Queue.Queue(maxsize=2)

        self.skipfirstimage = False
        self.addr = []
        self.picEvent = []
        self.ROIState = self.loadROI()

        self.ROIBackground = np.zeros(
            self.roi.getArrayRegion(self.pic, self.img).shape)
        self.ROIBackgroundStdDev = np.zeros(
            self.roi.getArrayRegion(self.pic, self.img).shape)
        self.spatialROIBackground = np.zeros(self.ROIBackground.shape[1])

        self.movingROISumAvg = 0
        self.avgSampleSize = 100
        self.roiSumArray = np.zeros(self.avgSampleSize)
        self.roiSumArrayIndex = 0
        self.updateROI = False
        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL("timeout()"), self.getData)
        self.timer.start()
Exemplo n.º 27
0
    def enter_alternate_screen(self):
        """
        Go to alternate screen buffer.
        """
        if not self._in_alternate_screen:
            GENERIC_READ = 0x80000000
            GENERIC_WRITE = 0x40000000

            # Create a new console buffer and activate that one.
            handle = HANDLE(self._winapi(windll.kernel32.CreateConsoleScreenBuffer, GENERIC_READ|GENERIC_WRITE,
                                         DWORD(0), None, DWORD(1), None))

            self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, handle)
            self.hconsole = handle
            self._in_alternate_screen = True
Exemplo n.º 28
0
    def openfilewin(path):

        createfile = ctypes.windll.kernel32.CreateFileW

        cpath = ctypes.create_unicode_buffer(path)
        access = 0
        mode = 7  # FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE
        disposition = 3  # OPEN_EXISTING
        flags = 33554432  # FILE_FLAG_BACKUP_SEMANTICS

        createfile.restype = HANDLE
        h = createfile(
            cpath,
            DWORD(access),
            DWORD(mode),
            None,
            DWORD(disposition),
            DWORD(flags),
            HANDLE(0),
        )
        if h == HANDLE(-1).value:
            raise WindowsError("Failed to open file: " + path)

        return HANDLE(h)
 def readinto(D, b):
     A = len(b)
     if not A: return 0
     elif A % 2:
         raise ValueError(
             'cannot read odd number of bytes from UTF-16-LE encoded console'
         )
     B = get_buffer(b, writable=_B)
     E = A // 2
     C = c_ulong()
     F = ReadConsoleW(HANDLE(D.handle), B, E, byref(C), _A)
     if GetLastError() == ERROR_OPERATION_ABORTED: time.sleep(0.1)
     if not F: raise OSError(f"Windows error: {GetLastError()}")
     if B[0] == EOF: return 0
     return 2 * C.value
Exemplo n.º 30
0
 def _query_interface_settings(self, interface, alternate_setting=0):
     if interface != 0:
         handle = HANDLE()
         result = WinUsb_GetAssociatedInterface(self._winusb, interface, byref(handle))
         if result == 0:
             raise IOError('WinUsb_GetAssociatedInterface failed: ' + kernel32.get_last_error())
     else:
         handle = self._winusb
     interface_descriptor = usb_core.InterfaceDescriptor()
     result = WinUsb_QueryInterfaceSettings(handle, alternate_setting, byref(interface_descriptor))
     if interface != 0:
         WinUsb_Free(handle)
     if result == 0:
         raise IOError('WinUsb_QueryInterfaceSettings failed: ' + kernel32.get_last_error())
     return interface_descriptor