Exemplo n.º 1
0
def get_device_info_detail(dev=0):
    """Get an entry from the internal device info list. """
    dwIndex = c.c_ulong(dev)
    lpdwFlags = c.c_ulong()
    lpdwType = c.c_ulong()
    lpdwID = c.c_ulong()
    lpdwLocId = c.c_ulong()
    pcSerialNumber = c.c_buffer(MAX_DESCRIPTION_SIZE)
    pcDescription = c.c_buffer(MAX_DESCRIPTION_SIZE)
    ftHandle = c.c_ulong()
    _PY_GetDeviceInfoDetail(dwIndex,
                                c.byref(lpdwFlags),
                                c.byref(lpdwType),
                                c.byref(lpdwID),
                                c.byref(lpdwLocId),
                                pcSerialNumber,
                                pcDescription,
                                c.byref(ftHandle))
    return {'Dev': dwIndex.value,
            'Flags': lpdwFlags.value,
            'Type': lpdwType.value,
            'ID': lpdwID.value,
            'LocId': lpdwLocId.value,
            'SerialNumber': pcSerialNumber.value,
            'Description': pcDescription.value,
            'ftHandle': ftHandle}
Exemplo n.º 2
0
def crypt_unprotect_data(ctext, entropy=None):
    '''
    This function uses the Windows function, CryptUnprotectData, to decrypt
    ctext IAW with http://msdn.microsoft.com/en-us/library/ms995355.aspx.
    
    It was heavily influenced by:
    Crusher Joe - http://article.gmane.org/gmane.comp.python.ctypes/420
    '''    
    ptext = ''
    CryptUnprotectData = windll.crypt32.CryptUnprotectData
    CRYPTPROTECT_UI_FORBIDDEN = 0x01
    blob_in = BLOB(len(ctext), c_buffer(ctext, len(ctext)))
    if entropy:
        buffer_entropy = c_buffer(entropy, len(entropy)) 
        blob_entropy = byref(BLOB(len(entropy), buffer_entropy))
    else:
        blob_entropy = entropy
    blob_out = BLOB()
    if CryptUnprotectData(byref(blob_in), 
                          None, #pointer to readable description
                          blob_entropy, 
                          None, 
                          None,
                          CRYPTPROTECT_UI_FORBIDDEN, 
                          byref(blob_out)):
        ptext = blob_out.data()
    return ptext
Exemplo n.º 3
0
	def __call__(self, func, *args):
		if not func in self.funcs:
			raise Exception("This function doesn't belongs to this plug")

		if func.anonymous:
			op = Plug.KPLUGS_EXECUTE_ANONYMOUS
			length = 0
			ptr = func.addr
		else:
			op = Plug.KPLUGS_EXECUTE
			length = len(func.name)
			name_buf = ctypes.c_buffer(func.name)
			ptr = ctypes.addressof(name_buf)

		new_args = []
		bufs = []
		for arg in args:
			add = arg
			if isinstance(arg, str):
				bufs.append(ctypes.c_buffer(arg))
				add = ctypes.addressof(bufs[-1])
			new_args.append(add)
		args_buf = ctypes.c_buffer(struct.pack("P" * len(new_args), *new_args))

		# send the command (will throw an exception if it fails)
		return self._exec_cmd(op, length, len(args) * WORD_SIZE, ptr, ctypes.addressof(args_buf))
Exemplo n.º 4
0
def get_device_info_detail(dev=0):
    """Get an entry from the internal device info list. """
    dwIndex = c.c_ulong(dev)
    lpdwFlags = c.c_ulong()
    lpdwType = c.c_ulong()
    lpdwID = c.c_ulong()
    lpdwLocId = c.c_ulong()
    pcSerialNumber = c.c_buffer(MAX_DESCRIPTION_SIZE)
    pcDescription = c.c_buffer(MAX_DESCRIPTION_SIZE)
    ftHandle = c.c_ulong()
    _PY_GetDeviceInfoDetail(
        dwIndex,
        c.byref(lpdwFlags),
        c.byref(lpdwType),
        c.byref(lpdwID),
        c.byref(lpdwLocId),
        pcSerialNumber,
        pcDescription,
        c.byref(ftHandle),
    )
    return {
        "Dev": dwIndex.value,
        "Flags": lpdwFlags.value,
        "Type": lpdwType.value,
        "ID": lpdwID.value,
        "LocId": lpdwLocId.value,
        "SerialNumber": pcSerialNumber.value,
        "Description": pcDescription.value,
        "ftHandle": ftHandle,
    }
Exemplo n.º 5
0
    def get_mapped_filename(self, addr):
        """The filename mapped at address ``addr`` or ``None``

        :rtype: :class:`str` or ``None``
		"""
        buffer_size = 0x1000
        buffer = ctypes.c_buffer(buffer_size)

        if  windows.current_process.bitness == 32 and self.bitness == 64:
             target_size = ctypes.c_buffer(buffer_size)
             try:
                windows.syswow64.NtQueryVirtualMemory_32_to_64(self.handle, addr, MemorySectionName, buffer, buffer_size, target_size)
             except NtStatusException as e:
                if e.code not in  [STATUS_FILE_INVALID, STATUS_INVALID_ADDRESS, STATUS_TRANSACTION_NOT_ACTIVE]:
                    raise
                return None
             remote_winstring = rctypes.transform_type_to_remote64bits(WinUnicodeString)
             mapped_filename = remote_winstring(ctypes.addressof(buffer), windows.current_process)
             return mapped_filename.str

        try:
                size = winproxy.GetMappedFileNameA(self.handle, addr, buffer, buffer_size)
        except winproxy.Kernel32Error as e:
            return None
        return buffer[:size]
Exemplo n.º 6
0
 def getHardwareInformation(self):
     model = c_buffer(255)
     softwareVersion = c_buffer(255)
     hardwareNotes = c_buffer(255)
     self.aptdll.GetHWInfo(self.SerialNum, model, 255, softwareVersion, 255, hardwareNotes, 255)
     hwinfo = [model.value, softwareVersion.value, hardwareNotes.value]
     return hwinfo
Exemplo n.º 7
0
def SetupDiGetDeviceProperty(device_info_set, devinfo_data, property_key):
    from . import SetupDiGetDevicePropertyW as interface

    value_type = DWORD()
    required_size = DWORD()
    device_info_buffer = c_buffer(SP_DEVINFO_DATA.write_to_string(devinfo_data), SP_DEVINFO_DATA.min_max_sizeof().max)
    property_key_buffer = c_buffer(DEVPROPKEY.write_to_string(property_key), DEVPROPKEY.min_max_sizeof().max)
    try:
        interface(
            device_info_set, device_info_buffer, property_key_buffer, byref(value_type), 0, 0, byref(required_size), 0
        )
    except WindowsException as exception:
        if exception.winerror != ERROR_INSUFFICIENT_BUFFER:
            raise

    value_buffer = c_buffer(required_size.value)
    interface(
        device_info_set,
        device_info_buffer,
        property_key_buffer,
        byref(value_type),
        value_buffer,
        required_size,
        byref(required_size),
        0,
    )
    return Property(value_buffer.raw, value_type.value, property_key)
Exemplo n.º 8
0
def get_info(drivename):
    size = 0x1000
    volume_name = ctypes.c_buffer(size)
    fs_name = ctypes.c_buffer(size)
    flags = DWORD()
    winproxy.GetVolumeInformationA(drivename, volume_name, size, None, None, ctypes.byref(flags), fs_name, size)
    raise NotImplementedError("get_info")
Exemplo n.º 9
0
def grab_screen(bbox=None):
    """
    Grabs a screenshot. This is a replacement for PIL's ImageGrag.grab() method
    that supports multiple monitors. (SEE: https://github.com/python-pillow/Pillow/issues/1547)
    
    Returns a PIL Image, so PIL library must be installed.
    
    Usage:
        im = grab_screen() # grabs a screenshot of the primary monitor
        im = grab_screen([-1600, 0, -1, 1199]) # grabs a 1600 x 1200 screenshot to the left of the primary monitor
        im.save('screencap.jpg')
    """
    
    def cleanup():
        if bitmap:
            DeleteObject(bitmap)
        DeleteDC(screen_copy)
        DeleteDC(screen)
    
    try:
        screen = CreateDC(c_char_p('DISPLAY'), NULL, NULL, NULL)
        screen_copy = CreateCompatibleDC(screen)
        
        if bbox:
            left,top,x2,y2 = bbox
            width = x2 - left + 1
            height = y2 - top + 1
        else:
            left = 0
            top = 0
            width = GetDeviceCaps(screen, HORZRES)
            height = GetDeviceCaps(screen, VERTRES)
        
        bitmap = CreateCompatibleBitmap(screen, width, height)
        if bitmap == NULL:
            print('grab_screen: Error calling CreateCompatibleBitmap. Returned NULL')
            return
            
        hobj = SelectObject(screen_copy, bitmap)
        if hobj == NULL or hobj == HGDI_ERROR:
            print('grab_screen: Error calling SelectObject. Returned {0}.'.format(hobj))
            return
        
        if BitBlt(screen_copy, 0, 0, width, height, screen, left, top, SRCCOPY) == NULL:
            print('grab_screen: Error calling BitBlt. Returned NULL.')
            return
        
        bitmap_header = pack('LHHHH', calcsize('LHHHH'), width, height, 1, 24)
        bitmap_buffer = c_buffer(bitmap_header)
        bitmap_bits = c_buffer(' ' * (height * ((width * 3 + 3) & -4)))
        got_bits = GetDIBits(screen_copy, bitmap, 0, height, bitmap_bits, bitmap_buffer, 0)
        if got_bits == NULL or got_bits == ERROR_INVALID_PARAMETER:
            print('grab_screen: Error calling GetDIBits. Returned {0}.'.format(got_bits))
            return
            
        image = Image.frombuffer('RGB', (width, height), bitmap_bits, 'raw', 'BGR', (width * 3 + 3) & -4, -1)
        return image
    finally:
        cleanup()
Exemplo n.º 10
0
    def tidy_document(self, text, options=None):
        """ Run a string with markup through HTML Tidy; return the corrected one
        and any error output.

        text: The markup, which may be anything from an empty string to a complete
        (X)HTML document. If you pass in a unicode type (py3 str, py2 unicode) you
        get one back out, and tidy will have some options set that may affect
        behavior (e.g. named entities converted to plain unicode characters). If
        you pass in a bytes type (py3 bytes, py2 str) you will get one of those
        back.

        options (dict): Options passed directly to HTML Tidy; see the HTML Tidy docs
        (http://www.html-tidy.org/documentation/) or run tidy -help-config from the
        command line.

        returns (str, str): The tidied markup and unparsed warning/error messages.
        Warnings and errors are returned just as tidylib returns them.
        """

        # Unicode approach is to encode as string, then decode libtidy output
        use_unicode = False
        if is_unicode(text):
            use_unicode = True
            text = text.encode('utf-8')

        with self._doc_and_sink() as (doc, sink):
            tidy_options = dict(BASE_OPTIONS)
            if options:
                tidy_options.update(options)
            if use_unicode:
                tidy_options['input-encoding'] = 'utf8'
                tidy_options['output-encoding'] = 'utf8'
            for key in tidy_options:
                value = tidy_options[key]
                key = key.replace('_', '-')
                if value is None:
                    value = ''
                key, value = encode_key_value(key, value)
                self._tidy.tidyOptParseValue(doc, key, value)
                error = str(sink)
                if error:
                    raise ValueError("(tidylib) " + error)

            self._tidy.tidyParseString(doc, text)
            self._tidy.tidyCleanAndRepair(doc)

            # Guess at buffer size; tidy returns ENOMEM if the buffer is too
            # small and puts the required size into out_length
            out_length = ctypes.c_int(8192)
            out = ctypes.c_buffer(out_length.value)
            while ENOMEM == self._tidy.tidySaveString(doc, out, ctypes.byref(out_length)):
                out = ctypes.c_buffer(out_length.value)

            document = out.value
            if use_unicode:
                document = document.decode('utf-8')
            errors = str(sink)

        return (document, errors)
Exemplo n.º 11
0
 def __str__(self):
     stlen = ctypes.c_int(8192)
     st = ctypes.c_buffer(stlen.value)
     rc = _tidy.SaveString(self.cdoc, st, ctypes.byref(stlen))
     if rc == -12:  # buffer too small
         st = ctypes.c_buffer(stlen.value)
         _tidy.SaveString(self.cdoc, st, ctypes.byref(stlen))
     return st.value
Exemplo n.º 12
0
 def takerRealloc(width, height, srcdc, memdc, bmp, c_bmp_header, c_bits):
     takerFree(srcdc, memdc, bmp)
     bmp_header = struct.pack('LHHHH', struct.calcsize('LHHHH'), width, height, 1, 24)
     srcdc = ctypes.windll.user32.GetDC(0)
     memdc = ctypes.windll.gdi32.CreateCompatibleDC(srcdc)
     bmp = ctypes.windll.gdi32.CreateCompatibleBitmap(srcdc, width, height)
     c_bmp_header = ctypes.c_buffer(bmp_header)
     c_bits = ctypes.c_buffer(' ' * (height * ((width * 3 + 3) & -4)))
     return srcdc, memdc, bmp, c_bmp_header, c_bits
Exemplo n.º 13
0
 def _send(self, command):
     buf = ctypes.c_buffer(255)
     ret = self._mci(str(command), buf, 254, 0)
     if ret:
         err = int(ret)
         err_buf = ctypes.c_buffer(255)
         self._mci(err, err_buf, 254)
         raise RuntimeError("Error %d: %s" % (err, err_buf.vale))
     else:
         return buf.value
Exemplo n.º 14
0
 def _user_and_computer_name(self):
     tok_usr = self.token_user
     sid = tok_usr.User.Sid
     usernamesize = DWORD(0x1000)
     computernamesize = DWORD(0x1000)
     username = ctypes.c_buffer(usernamesize.value)
     computername = ctypes.c_buffer(computernamesize.value)
     peUse = SID_NAME_USE()
     winproxy.LookupAccountSidA(None, sid, username, usernamesize, computername, computernamesize, peUse)
     return username[:usernamesize.value], computername[:computernamesize.value]
Exemplo n.º 15
0
Arquivo: sgio.py Projeto: MoonDav/sgio
def smartReadThresholds(dev):
    sense = ctypes.c_buffer(64)
    buf = ctypes.c_buffer(512)
    sgio = prepareSgio(0xb0, 0xd1, 1, 0xc24f00, SG_DXFER_FROM_DEV, sense, buf)  # SMART READ THRESHOLDS
    with open(dev, 'r') as fd:
        if fcntl.ioctl(fd, SG_IO, ctypes.addressof(sgio)) != 0:
            return None  # fcntl failed!
    if checkSense(sense, debug) is None:
        return None
    return sense, buf
Exemplo n.º 16
0
Arquivo: sgio.py Projeto: MoonDav/sgio
def sectorRead(dev, start, count):
    sense = ctypes.c_buffer(64)
    buf = ctypes.c_buffer(count * 512)
    sgio = prepareSgio(0x24, 0, count, start, SG_DXFER_FROM_DEV, sense, buf)  # READ SECTORS EXT
    with open(dev, 'r') as fd:
        if fcntl.ioctl(fd, SG_IO, ctypes.addressof(sgio)) != 0:
            return None  # fcntl failed!
    if checkSense(sense, debug) is None:
        return None
    return sense, buf
Exemplo n.º 17
0
    def getDeviceInfo(self):
        """Returns a dictionary describing the device. """
        deviceType = _ft.DWORD()
        deviceId = _ft.DWORD()
        desc = c.c_buffer(MAX_DESCRIPTION_SIZE)
        serial = c.c_buffer(MAX_DESCRIPTION_SIZE)

        call_ft(_ft.FT_GetDeviceInfo, self.handle, c.byref(deviceType),
                c.byref(deviceId), serial, desc, None)
        return {'type': deviceType.value, 'id': deviceId.value,
                'description': desc.value, 'serial': serial.value}
Exemplo n.º 18
0
 def winCommand(*command):
     buf = c_buffer(255)
     command = ' '.join(command).encode(getfilesystemencoding())
     errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0))
     if errorCode:
         errorBuffer = c_buffer(255)
         windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254)
         exceptionMessage = ('\n    Error ' + str(errorCode) + ' for command:'
                             '\n        ' + command.decode() +
                             '\n    ' + errorBuffer.value.decode())
         raise PlaysoundException(exceptionMessage)
     return buf.value
Exemplo n.º 19
0
def dpapi_decrypt_blob(blob, entropy=None):
    """Decrypts a blob of data using DPAPI.

    :param blob: encrypted blob to decrypt
    :type blob: string

    :param entropy: additional entropy to use to decrypt
    :type entropy: string

    :return: decrypted blob
    :rtype: string

    :raise Exception: if the platform is not Windows or the decryption failed
    """

    if os.name != "nt":
        raise Exception("DP API functions are only available in Windows")

    blob = bytes(blob)
    entropy = bytes(entropy or "")

    from ctypes import windll, byref, cdll, Structure, POINTER, c_char, c_buffer
    from ctypes.wintypes import DWORD

    LocalFree = windll.kernel32.LocalFree
    memcpy = cdll.msvcrt.memcpy
    CryptUnprotectData = windll.crypt32.CryptUnprotectData
    CRYPTPROTECT_UI_FORBIDDEN = 0x01

    class DATA_BLOB(Structure):
        _fields_ = [('cbData', DWORD),
                    ('pbData', POINTER(c_char))
                    ]

    def parse_data(data):
        cbData = int(data.cbData)
        pbData = data.pbData
        buffer = c_buffer(cbData)
        memcpy(buffer, pbData, cbData)
        LocalFree(pbData)
        return buffer.raw

    buffer_in = c_buffer(blob, len(blob))
    buffer_entropy = c_buffer(entropy, len(entropy))
    blob_in = DATA_BLOB(len(blob), buffer_in)
    blob_entropy = DATA_BLOB(len(entropy), buffer_entropy)
    blob_out = DATA_BLOB()

    if CryptUnprotectData(byref(blob_in), None, byref(blob_entropy), None, None,
                          CRYPTPROTECT_UI_FORBIDDEN, byref(blob_out)):
        return parse_data(blob_out)

    raise Exception("Unable to decrypt blob")
def ReadBuffer(proc_mem, offset, size):
   mem_address = proc_mem.Address + offset
   if (mem_address == 0) or (size == 0):
      return
   try:
      raw_mem = ctypes.c_buffer(size)
      local_ptr = ctypes.addressof(raw_mem)
      read_size = proc_mem.Read(offset, size, local_ptr)
      #print "read from memory: 0x%x (0x%X)" %(mem_address, read_size)
      return raw_mem if (read_size > 0) else ctypes.c_buffer(0)
   except:
      print "ups, cannot read buffer: 0x%x" % (mem_address), " size: ", size
      return
Exemplo n.º 21
0
def ioctl_volume_get_volume_disk_extents(handle):
    size = structures.VOLUME_DISK_EXTENTS.min_max_sizeof().min + _sizeof(structures.DISK_EXTENT)
    string = ctypes.c_buffer('\x00' * size, size)
    try:
        infi.wioctl.ioctl(handle, infi.wioctl.constants.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, string, size)
    except infi.wioctl.api.WindowsException as e:
        if e.winerror != infi.wioctl.constants.ERROR_MORE_DATA:
            raise
    count = structures.DWORD.create_from_string(string)
    size = size + ((count - 1) * _sizeof(structures.DISK_EXTENT))
    string = ctypes.c_buffer('\x00' * size, size)
    infi.wioctl.ioctl(handle, infi.wioctl.constants.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, string, size)
    instance = structures.VOLUME_DISK_EXTENTS.create_from_string(string)
    return instance.Extents
Exemplo n.º 22
0
Arquivo: sgio.py Projeto: MoonDav/sgio
def driveIdentify(dev):
    sense = ctypes.c_buffer(64)
    identify = ctypes.c_buffer(512)
    sgio = prepareSgio(0xec, 0, 0, 0, SG_DXFER_FROM_DEV, sense, identify)  # IDENTIFY
    with open(dev, 'r') as fd:
        if fcntl.ioctl(fd, SG_IO, ctypes.addressof(sgio)) != 0:
            return None  # fcntl failed!
    if checkSense(sense, debug) is None:
        return None
    serial = swapString(identify[20:40])
    firmware = swapString(identify[46:53])
    model = swapString(identify[54:93])
    sectors = int.from_bytes(identify[200] + identify[201] + identify[202] + identify[203] +
                             identify[204] + identify[205] + identify[206] + identify[207], byteorder='little')
    return (serial, firmware, model, sectors)
Exemplo n.º 23
0
Arquivo: i2c.py Projeto: ks156/IoTPy
    def read(self, address, count):
        read_buf = ctypes.c_buffer("\0"*count, count)

        read_msg = struct.pack("@HHHP", address, 0x0001, count, ctypes.addressof(read_buf))
        msgs = ctypes.c_buffer(read_msg, len(read_msg))

        txfer = struct.pack("@PI", ctypes.addressof(msgs), 1)
        txfer = array.array('b', txfer)

        try:
            fcntl.ioctl(self._file, LinuxI2C.I2C_RDWR, txfer, True)
        except IOError as e:
            return "", e.errno

        return ctypes.string_at(read_buf, count), 0
Exemplo n.º 24
0
def getDeviceInfoDetail(devnum=0):
    """Get an entry from the internal device info list. """
    f = _ft.DWORD()
    t = _ft.DWORD()
    i = _ft.DWORD()
    l = _ft.DWORD()
    h = _ft.FT_HANDLE()
    n = c.c_buffer(MAX_DESCRIPTION_SIZE)
    d = c.c_buffer(MAX_DESCRIPTION_SIZE)
    createDeviceInfoList()
    call_ft(_ft.FT_GetDeviceInfoDetail, _ft.DWORD(devnum),
            c.byref(f), c.byref(t), c.byref(i), c.byref(l), n, d, c.byref(h))
    return {'index': devnum, 'flags': f.value, 'type': t.value,
            'id': i.value, 'location': l.value, 'serial': n.value,
            'description': d.value, 'handle': h}
Exemplo n.º 25
0
Arquivo: i2c.py Projeto: ks156/IoTPy
    def write(self, address, data):
        write_buf = ctypes.c_buffer(data, len(data))

        write_msg = struct.pack("@HHHP", address, 0x0000, len(data), ctypes.addressof(write_buf))
        msgs = ctypes.c_buffer(write_msg, len(write_msg))

        txfer = struct.pack("@PI", ctypes.addressof(msgs), 1)
        txfer = array.array('b', txfer)

        try:
            fcntl.ioctl(self._file, LinuxI2C.I2C_RDWR, txfer, True)
        except IOError as e:
            return "", e.errno

        return "", 0
Exemplo n.º 26
0
 def read(self, dwBytesToRead, raw=True):
     '''Read in int-type of bytes. Returns either the data
     or raises an exception'''
     lpdwBytesReturned = c.c_ulong()
     lpBuffer = c.c_buffer(dwBytesToRead)
     _PY_Read(self.ftHandle, lpBuffer, dwBytesToRead, c.byref(lpdwBytesReturned))
     return lpBuffer.raw[:lpdwBytesReturned.value] if raw else lpBuffer.value[:lpdwBytesReturned.value]
Exemplo n.º 27
0
def _task_list():
    psapi = ctypes.windll.psapi
    kernel = ctypes.windll.kernel32

    hModule = ctypes.c_ulong()
    count = ctypes.c_ulong()
    modname = ctypes.c_buffer(30)
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_READ = 0x0010

    pid_list = win32process.EnumProcesses()
    info_list = []
    
    for pid in pid_list:
        
        hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
        if hProcess:
            psapi.EnumProcessModules(hProcess, ctypes.byref(hModule), ctypes.sizeof(hModule), ctypes.byref(count))
            psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, ctypes.sizeof(modname))
            pname = ctypes.string_at(modname)

            procmeminfo = win32process.GetProcessMemoryInfo(hProcess)
            procmemusage = (procmeminfo["WorkingSetSize"]/1024)
            info_list.append((pid, pname, procmemusage))
                        
            kernel.CloseHandle(hProcess)

    return info_list
Exemplo n.º 28
0
def readlink(path):
    reparse_point_handle = CreateFileW(path,
                                       0,
                                       0,
                                       None,
                                       OPEN_EXISTING,
                                       FILE_FLAG_OPEN_REPARSE_POINT |
                                       FILE_FLAG_BACKUP_SEMANTICS,
                                       None)
    if reparse_point_handle == INVALID_HANDLE_VALUE:
        raise WinError()
    target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
    n_bytes_returned = DWORD()
    io_result = DeviceIoControl(reparse_point_handle,
                                FSCTL_GET_REPARSE_POINT,
                                None, 0,
                                target_buffer, len(target_buffer),
                                byref(n_bytes_returned),
                                None)
    CloseHandle(reparse_point_handle)
    if not io_result:
        raise WinError()
    rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
    if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
        return rdb.SymbolicLinkReparseBuffer.PrintName
    elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
        return rdb.MountPointReparseBuffer.PrintName
    raise ValueError("not a link")
Exemplo n.º 29
0
 def send(self, command):
     buffer = c_buffer(255)
     errorcode = self.w32mci(str(command), buffer, 254, 0)
     if errorcode:
         return errorcode, self.get_error(errorcode)
     else:
         return errorcode, buffer.value
Exemplo n.º 30
0
def get_short_path(path):
    """Return the short path form for ``path``

        :raise: :class:`~windows.winproxy.Kernel32Error` if ``path`` does not exists
        :param path: a valid Windows path
        :type path: :class:`str` | :obj:`unicode`
        :returns: :class:`str` | :obj:`unicode` -- same type as ``path`` parameter
    """
    size = 0x1000
    if isinstance(path, unicode):
        buffer = ctypes.create_unicode_buffer(size)
        rsize = winproxy.GetShortPathNameW(path, buffer, size)
    else:
        buffer = ctypes.c_buffer(size)
        rsize = winproxy.GetShortPathNameA(path, buffer, size)
    return buffer[:rsize]
Exemplo n.º 31
0
 def resolve(self) -> bool:
     """
     Updates the local pointer to the address of the remote memory
     """
     address = self.base_address
     for offset in self.offsets:
         data = bytes(
             kernel32.ReadProcessMemory(self.handle, address,
                                        self.pointer_size))
         if data is None:
             return False
         data = ctypes.c_buffer(data)
         address = ctypes.cast(data, self.c_pointer)[0]
         address += offset
     self.address = address
     return True
Exemplo n.º 32
0
def sane_read(handle, nb_bytes):
    global sane_available
    assert(sane_available)

    buf = ctypes.c_buffer(nb_bytes)
    length = ctypes.c_int()

    status = SANE_LIB.sane_read(handle, ctypes.pointer(buf), len(buf),
                                ctypes.pointer(length))
    if status == SaneStatus.NO_DOCS:
        raise StopIteration()
    elif status == SaneStatus.EOF:
        raise EOFError()
    elif status != SaneStatus.GOOD:
        raise SaneException(SaneStatus(status))
    return buf[:length.value]
Exemplo n.º 33
0
    def transaction(self, data_out):
        size = len(data_out)
        buf = ctypes.c_buffer(data_out, size)

        txfer = struct.pack("@QQIIHBBxxxx", ctypes.addressof(buf),
                            ctypes.addressof(buf), size, 0, 0, 8, 0)
        txfer = array.array('b', txfer)

        SPI_IOC_MAGIC = ord('k')
        SPI_IOC_MESSAGE = IOW(SPI_IOC_MAGIC, 0, 32)
        try:
            ioctl(self._file, SPI_IOC_MESSAGE, txfer, True)
        except:
            raise RuntimeError("Error while performing SPI transaction.")

        return ctypes.string_at(buf, size)
Exemplo n.º 34
0
def AutoSizeDialog(dialog, center=True):
    classNameBuffer = ctypes.c_buffer(1024)
    children = []
    editBoxes = []
    for child in EnumChildWindows(dialog):
        children.append(child)
        user32.GetClassNameA(child, classNameBuffer, 1024)
        if classNameBuffer.value.lower() == 'edit':
            editBoxes.append(child)

    editBoxes.sort(lambda x, y: cmp(GetWindowRect(x).top, GetWindowRect(y).top))

    for editBox in editBoxes:
        text = GetText(editBox)
        user32.SetWindowTextA(editBox, 'X\r\nX')
        if user32.SendMessageA(editBox, EM_GETLINECOUNT, 0, 0) < 2:
            user32.SetWindowTextA(editBox, text)
        else:
            lineHeight = HIWORD(user32.SendMessageA(editBox, EM_POSFROMCHAR, 3, 0)) - HIWORD(user32.SendMessageA(editBox, EM_POSFROMCHAR, 0, 0))
            user32.SetWindowTextA(editBox, text)
            newHeight = user32.SendMessageA(editBox, EM_GETLINECOUNT, 0, 0)*lineHeight + 2*LOWORD(user32.SendMessageA(editBox, EM_GETMARGINS, 0, 0))
            editBoxRect = GetWindowRect(editBox)
            oldHeight = height(editBoxRect)
            if newHeight != oldHeight:
                topLeft = wintypes.POINT(editBoxRect.left, editBoxRect.top)
                user32.ScreenToClient(dialog, ctypes.byref(topLeft))
                user32.MoveWindow(editBox, topLeft.x, topLeft.y, width(editBoxRect), newHeight, False)

                for child in children:
                    childRect = GetWindowRect(child)
                    if childRect.top >= editBoxRect.bottom:
                        topLeft = wintypes.POINT(childRect.left, childRect.top)
                        user32.ScreenToClient(dialog, ctypes.byref(topLeft))
                        user32.MoveWindow(child,
                                          topLeft.x, topLeft.y + newHeight - oldHeight,
                                          width(childRect), height(childRect),
                                          False
                                         )

                dRect = GetWindowRect(dialog)
                dRect.bottom += newHeight - oldHeight
                topLeft = wintypes.POINT(dRect.left, dRect.top)
                user32.MoveWindow(dialog, topLeft.x, topLeft.y, width(dRect), height(dRect), False)
                user32.InvalidateRect(dialog, None, True)

    if center:
        CenterWindow(dialog)
Exemplo n.º 35
0
    def get_file_version(self, name):
        size = winproxy.GetFileVersionInfoSizeA(name)
        buf = ctypes.c_buffer(size)
        winproxy.GetFileVersionInfoA(name, 0, size, buf)

        bufptr = PVOID()
        bufsize = UINT()
        winproxy.VerQueryValueA(buf, "\\VarFileInfo\\Translation",
                                ctypes.byref(bufptr), ctypes.byref(bufsize))
        bufstr = ctypes.cast(bufptr, LPCSTR)
        tup = struct.unpack("<HH", bufstr.value[:4])
        req = "{0:04x}{1:04x}".format(*tup)
        winproxy.VerQueryValueA(
            buf, "\\StringFileInfo\\{0}\\ProductVersion".format(req),
            ctypes.byref(bufptr), ctypes.byref(bufsize))
        bufstr = ctypes.cast(bufptr, LPCSTR)
        return bufstr.value
Exemplo n.º 36
0
    def ictclas_paragraphProcess(self, paragraph, code_type, POStagged=True):
        '''
        ICTCLAS Paragraph Process
        @param paragraph: The source paragraph
        @param code_type: The character coding type of the string
        @param POStagged: Judge whether need POS tagging, 0 for no tag; 1 for tagging; default:1.
        @return: Return the result
        '''
        self._ictclas_lib = cdll.LoadLibrary(self._lib_path)

        paragraph, length = self.__pargragph_process(paragraph, code_type)
        result = c_buffer(length * 6)
        self._ictclas_lib._Z24ICTCLAS_ParagraphProcessPKciPc9eCodeTypeb(
            c_char_p(paragraph), c_int(length), result, code_type,
            c_int(POStagged))

        return result
Exemplo n.º 37
0
    def testCreation(self):
        """Test creating a subclass of EventClass."""
        class TestEventClass(event.EventClass):
            _fields_ = [('TestString', field.String),
                        ('TestInt32', field.Int32), ('TestInt64', field.Int64)]

        time_s = int(time.time())
        date_time = datetime.datetime.utcfromtimestamp(time_s)
        sys_time = evntrace.SYSTEMTIME(date_time.year, date_time.month, 0,
                                       date_time.day, date_time.hour,
                                       date_time.minute, date_time.second,
                                       date_time.microsecond / 1000)
        file_time = ctypes.wintypes.FILETIME()
        ctypes.windll.kernel32.SystemTimeToFileTime(ctypes.byref(sys_time),
                                                    ctypes.byref(file_time))
        time_stamp = file_time.dwHighDateTime
        time_stamp <<= 32
        time_stamp |= file_time.dwLowDateTime

        header_dict = {
            'ProcessId': 5678,
            'ThreadId': 8765,
            'TimeStamp': time_stamp
        }

        data = ctypes.c_buffer(18)
        data.value = 'Hello'

        ptr = ctypes.cast(data, ctypes.c_void_p)

        int32 = ctypes.cast(ptr.value + 6, ctypes.POINTER(ctypes.c_int))
        int32.contents.value = 1234

        int64 = ctypes.cast(ptr.value + 10, ctypes.POINTER(ctypes.c_longlong))
        int64.contents.value = 4321

        mock_event_trace = MockEventTrace(header_dict, ptr.value,
                                          ctypes.sizeof(data))
        mock_session = MockSession()
        obj = TestEventClass(mock_session, mock_event_trace)
        self.assertEqual(obj.process_id, 5678)
        self.assertEqual(obj.thread_id, 8765)
        self.assertEqual(obj.time_stamp, time_s)
        self.assertEqual(obj.TestString, 'Hello')
        self.assertEqual(obj.TestInt32, 1234)
        self.assertEqual(obj.TestInt64, 4321)
Exemplo n.º 38
0
 def _get_object_type(self):
     lh = self.local_handle
     xxx = gdef.PUBLIC_OBJECT_TYPE_INFORMATION()
     size_needed = gdef.DWORD()
     try:
         winproxy.NtQueryObject(lh, gdef.ObjectTypeInformation,
                                ctypes.byref(xxx), ctypes.sizeof(xxx),
                                ctypes.byref(size_needed))
     except WindowsError as e:
         if e.code != gdef.STATUS_INFO_LENGTH_MISMATCH:
             raise
         size = size_needed.value
         buffer = ctypes.c_buffer(size)
         winproxy.NtQueryObject(lh, gdef.ObjectTypeInformation, buffer,
                                size, ctypes.byref(size_needed))
         xxx = gdef.PUBLIC_OBJECT_TYPE_INFORMATION.from_buffer_copy(buffer)
     return xxx.TypeName.str
Exemplo n.º 39
0
def PILImageToPix(pil_img):
    if pil_img.mode != "RGBA":
        pil_img = pil_img.convert("RGBA")
    w, h = pil_img.size
    depth = 32
    lep_img = lep.PIX(w, h, depth)
    size = w * h
    img_data = pil_img.tostring()
    # ctypes miss a way to get the string buffer as  a memory read source
    interm_buffer = ctypes.c_buffer(img_data)
    ctypes.memmove(lep_img.data, interm_buffer, len(img_data))
    lep.functions.pixEndianByteSwap(lep_img)
    # Normally in Leptonica the alpha byte is set to "zero"
    # I am betting there is no problem leaving the same value
    # that comes from PIL (255 for opaque) for non transaprency use in
    # leptonica
    return lep_img
Exemplo n.º 40
0
 def securityEraseUnit(self, master, enhanced, password):
     buf = ctypes.c_buffer(512)
     if master:
         buf[0] = 1
     else:
         buf[0] = 0
     if enhanced:
         buf[0] = buf[0] + 2
     pwd = str.encode(password)
     i = 2
     for b in pwd:
         buf[i] = b
         i = i + 1
     sgio = self.prepareSgio(SECURITY_ERASE_PREPARE, 0, 0, 0, SG_DXFER_NONE,
                             None)
     with open(self.dev, 'r') as fd:
         try:
             fcntl.ioctl(fd, SG_IO, ctypes.addressof(sgio))
         except IOError:
             raise sgioFalied("fcntl.ioctl falied")
     tempTimeout = self.timeout
     if enhanced:
         self.timeout = self.enhancedEraseTimeout
     else:
         self.timeout = self.normalEraseTimeout
     if self.timeout == 0 or self.timeout == 510:
         self.timeout = 12 * 60 * 60 * 1000  # default timeout twelve hours
     else:
         self.timeout = (
             self.timeout +
             30) * 60 * 1000  # +30min then convert to milliseconds
     sgio = self.prepareSgio(SECURITY_ERASE_UNIT, 0, 0, 0, SG_DXFER_TO_DEV,
                             buf)
     self.clearSense()
     with open(self.dev, 'r') as fd:
         try:
             startTime = time.time()
             fcntl.ioctl(fd, SG_IO, ctypes.addressof(sgio))
         except IOError:
             raise sgioFalied("fcntl.ioctl falied")
     self.timeout = tempTimeout
     self.duration = (time.time() - startTime) * 1000
     try:
         self.checkSense()
     except senseError:
         raise securityError()
Exemplo n.º 41
0
def is_process_running_win32(name):
    """Return boolean whether process (like firefox.exe) is running

    Does not work on 64-bit Windows

    Originally by Eric Koome
    license GPL
    http://code.activestate.com/recipes/305279/
    """

    hModule = c_ulong()
    count = c_ulong()
    modname = c_buffer(30)
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_READ = 0x0010

    for pid in win32process.EnumProcesses():

        # Get handle to the process based on PID
        hProcess = kernel.OpenProcess(
            PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
            False, pid)
        if hProcess:
            psapi.EnumProcessModules(
                hProcess, byref(hModule), sizeof(hModule), byref(count))
            psapi.GetModuleBaseNameA(
                hProcess, hModule.value, modname, sizeof(modname))
            clean_modname = "".join(
                [i for i in modname if i != '\x00']).lower()

            # Clean up
            for i in range(modname._length_):
                modname[i] = '\x00'

            kernel.CloseHandle(hProcess)

            if len(clean_modname) > 0 and '?' != clean_modname:
                # Filter out non-ASCII characters which we don't need
                # and which may cause display warnings
                clean_modname2 = re.sub(
                    r'[^a-z.]', '_', clean_modname.lower())
                if clean_modname2 == name.lower():
                    return True

    return False
Exemplo n.º 42
0
def get_process_info(pid):
    # https://docs.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-modules-for-a-process
    hProcess = ctypes.windll.kernel32.OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
        False, pid
    )
    if not hProcess:
        return

    count = 1                       # 仅获取进程执行的文件
    hMods = (ctypes.c_ulong * count)()
    cbNeeded = ctypes.c_ulong()

    ctypes.windll.psapi.EnumProcessModules(
        hProcess,
        ctypes.byref(hMods),
        ctypes.sizeof(hMods),
        ctypes.byref(cbNeeded)
    )
    num = min(cbNeeded.value / ctypes.sizeof(ctypes.c_ulong), count)
    i = 0

    exe_name = ''
    while i < num:
        szModName = ctypes.c_buffer(100)
        # ret = ctypes.windll.psapi.GetModuleFileNameExA(
            # hProcess,
            # hMods[i],
            # szModName,
            # ctypes.sizeof(szModName)
        # )
        ret = ctypes.windll.psapi.GetModuleBaseNameA(
            hProcess,
            hMods[i],
            szModName,
            ctypes.sizeof(szModName)
        )
        if ret:
            print "%8d\t%s" % (pid, szModName.value)
            if i == 0:
                exe_name = szModName.value
        i += 1

    ctypes.windll.kernel32.CloseHandle(hProcess)
    return (pid, exe_name)
Exemplo n.º 43
0
    def run(self):
        global dll
        # 启动socket通信
        while True:
            size = self.queue.get()
            if size.get("size"):
                size = size.get("size")
                break
            else:
                self.queue.put(size)

        print("ImageThread启动")
        w, h = size
        print(f"拿到了w={w}h={h}")
        scrw, scrh = autosize(self.scrSize[0], self.scrSize[1], w, h)
        print(f"自适应分辨率{scrw}x{scrh}")
        # scrw,scrh=w,h
        global drawNum
        global threadImg
        dll.init(0, w, h, scrw, scrh)
        lastTime = time.time()
        print(screenX, screenY)
        # cv2.namedWindow("1", flags=cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
        # cv2.resizeWindow("1", scrw, scrh)

        tick = 0
        bufflen = scrw * scrh * 3
        global FPS
        buff = ctypes.c_buffer(bufflen)

        while True:
            try:
                drawNum += 1
                tick += 1
                buffLen = dll.getBuff(buff)
                frame = np.frombuffer(buff.raw, 'uint8', count=bufflen)
                lenx = len(frame)
                solveQps()
                img = frame.reshape((scrh, scrw, 3)).astype('uint8')
                qv.imageT = img
                self.breakSignal.emit(1)

            except Exception as e:
                print(e)
                pass
Exemplo n.º 44
0
    def getSelftestLog(self):
        buf = ctypes.c_buffer(512)
        buf = self.readSmartLog(6)
        log = []
        revision = int.from_bytes(buf[0] + buf[1], byteorder='little')
        for i in range(2, 485, 24):
            if buf[i] == b'\x00':
                continue
            test = {
                b'\x01': "Short offline",
                b'\x02': "Extended offline",
                b'\x03': "Conveyance offline",
                b'\x04': "Selective offline",
                b'\x81': "Short captive",
                b'\x82': "Extended captive",
                b'\x83': "Conveyance captive",
                b'\x84': "Selective captive"
            }.get(buf[i])

            st = int.from_bytes(buf[i + 1], byteorder='little') >> 4
            status = {
                0: "completed",
                1: "aborted by host",
                2: "unknoun failure",
                3: "fatal error",
                4: "interrupted by reset",
                5: "electrical failure",
                6: "servo failure",
                7: "read failure",
                8: "handling damage",
                0x0F: "in progress"
            }.get(st)

            remaining = int(
                (int.from_bytes(buf[i + 1], byteorder='little') & 0x0F) * 10)
            if remaining == 100:
                remaining = 0

            lifetime = int.from_bytes(buf[i + 2] + buf[i + 3],
                                      byteorder='little')
            lba = int.from_bytes(buf[i + 5] + buf[i + 6] + buf[i + 7] +
                                 buf[i + 8],
                                 byteorder='little')
            log.append((test, status, remaining, lifetime, lba))
        return ((revision, log))
Exemplo n.º 45
0
def get_macaddress(host='localhost'):
    """ Returns the MAC address of a network host, requires >= WIN2K. """
    # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812
    import ctypes
    import socket
    import struct

    # Check for api availability
    try:
        SendARP = ctypes.windll.Iphlpapi.SendARP
    except:
        raise NotImplementedError('Usage only on Windows 2000 and above')

    # Doesn't work with loopbacks, but let's try and help.
    if host == '127.0.0.1' or host.lower() == 'localhost':
        host = socket.gethostname()

    # gethostbyname blocks, so use it wisely.
    try:
        inetaddr = ctypes.windll.wsock32.inet_addr(host)
        if inetaddr in (0, -1):
            raise Exception
    except:
        hostip = socket.gethostbyname(host)
        inetaddr = ctypes.windll.wsock32.inet_addr(hostip)

    buffer = ctypes.c_buffer(6)
    addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
    if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
        raise WindowsError('Retreival of mac address(%s) - failed' % host)

    # Convert binary data into a string.
    macaddr = ''
    for intval in struct.unpack('BBBBBB', buffer):
        if intval > 15:
            replacestr = '0x'
        else:
            replacestr = 'x'
        if macaddr != '':
            #macaddr = ':'.join([macaddr, hex(intval).replace(replacestr, '')])
            macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
        else:
            macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])

    return macaddr.upper()
Exemplo n.º 46
0
    def get_name(self,
                 nametype=gdef.CERT_NAME_SIMPLE_DISPLAY_TYPE,
                 param_type=0,
                 flags=0):
        """Retrieve the subject or issuer name of the certificate.
        See `CertGetNameStringA <https://msdn.microsoft.com/en-us/library/windows/desktop/aa376086(v=vs.85).aspx>`_

        :returns: :class:`str`
        """
        if nametype == gdef.CERT_NAME_RDN_TYPE:
            param_type = gdef.DWORD(param_type)
            param_type = gdef.LPDWORD(param_type)
        size = winproxy.CertGetNameStringA(self, nametype, flags, param_type,
                                           None, 0)
        namebuff = ctypes.c_buffer(size)
        size = winproxy.CertGetNameStringA(self, nametype, flags, param_type,
                                           namebuff, size)
        return namebuff[:-1]
Exemplo n.º 47
0
def listDevices(flags=0):
    """Return a list of serial numbers(default), descriptions or
    locations (Windows only) of the connected FTDI devices depending on value
    of flags"""
    n = _ft.DWORD()
    call_ft(_ft.FT_ListDevices, c.byref(n), None, _ft.DWORD(LIST_NUMBER_ONLY))
    devcount = n.value
    if devcount:
        # since ctypes has no pointer arithmetic.
        bd = [c.c_buffer(MAX_DESCRIPTION_SIZE) for _ in range(devcount)] + [None]
        # array of pointers to those strings, initially all NULL
        ba = (c.c_char_p * (devcount + 1))()
        for i in range(devcount):
            ba[i] = c.cast(bd[i], c.c_char_p)
        call_ft(_ft.FT_ListDevices, ba, c.byref(n), _ft.DWORD(LIST_ALL | flags))
        return [res for res in ba[:devcount]]
    else:
        return None
Exemplo n.º 48
0
 def load_image_pyglet(flo,hint=None):
     pic = pyglet.image.load(hint,file=flo)
     if "A" in pic.format:
         format = "RGBA"
     else:
         format = "RGBX"
     owidth = pic.width
     oheight = pic.height
     data = pic.get_data(format,owidth*len(format))
     width = _next_power_of_2(owidth)
     height = _next_power_of_2(oheight)
     if (width,height) != (owidth,oheight):
         ndata = ctypes.c_buffer(width*height*4)
         pyglet.gl.gluScaleImage(
             pyglet.gl.GL_RGBA,owidth,oheight,pyglet.gl.GL_UNSIGNED_BYTE,
             data,width,height,pyglet.gl.GL_UNSIGNED_BYTE,ndata)
         data = ndata.raw
     return ImageData(data,format,width,height)        
Exemplo n.º 49
0
 def securityUnlock(self, master, password):
     buf = ctypes.c_buffer(512)
     if master:
         buf[0] = 1
     else:
         buf[0] = 0
     pwd = str.encode(password)
     i = 2
     for b in pwd:
         buf[i] = b
         i = i + 1
     self.prepareSgio(SECURITY_UNLOCK, 0, 0, 0, SG_DXFER_TO_DEV, buf)
     self.clearSense()
     self.doSgio()
     try:
         self.checkSense()
     except senseError:
         raise securityError()
Exemplo n.º 50
0
def query_file_information(file_or_handle, file_info_class):
    if not isinstance(file_or_handle, windows.pycompat.int_types):
        file_or_handle = windows.utils.get_handle_from_file(file_or_handle)
    handle = file_or_handle
    io_status = gdef.IO_STATUS_BLOCK()
    info = ntqueryinformationfile_info_structs[file_info_class]()
    # Do helper for 'is_pointer' / get pointed_size & co ? (useful for winproxy)
    pinfo = ctypes.pointer(info)
    try:
        windows.winproxy.NtQueryInformationFile(
            handle,
            io_status,
            pinfo,
            ctypes.sizeof(info),
            FileInformationClass=file_info_class)
    except Exception as e:
        if not (e.winerror & 0xffffffff) == gdef.STATUS_BUFFER_OVERFLOW:
            raise
        # STATUS_BUFFER_OVERFLOW -> Guess we have a FILE_NAME_INFORMATION somewhere that need a bigger buffer
        if file_info_class == gdef.FileNameInformation:
            file_name_length = pinfo[0].FileNameLength
        elif file_info_class == gdef.FileAllInformation:
            file_name_length = pinfo[0].NameInformation.FileNameLength
        elif file_info_class == gdef.FileStreamInformation:
            file_name_length = 0x10000
        else:
            raise
        full_size = ctypes.sizeof(
            info
        ) + file_name_length  # We add a little too much size for the sake of simplicity
        buffer = ctypes.c_buffer(full_size)
        windows.winproxy.NtQueryInformationFile(
            handle,
            io_status,
            buffer,
            full_size,
            FileInformationClass=file_info_class)
        pinfo = ctypes.cast(
            buffer,
            ctypes.POINTER(
                ntqueryinformationfile_info_structs[file_info_class]))
        info = pinfo[0]
    # return list of ADS if FileStreamInformation ?
    return info
Exemplo n.º 51
0
def query_volume_information(file_or_handle, volume_info_class):
    if not isinstance(file_or_handle, windows.pycompat.int_types):
        file_or_handle = get_handle_from_file(file_or_handle)
    handle = file_or_handle
    io_status = gdef.IO_STATUS_BLOCK()
    info = ntqueryvolumeinformationfile_info_structs[volume_info_class]()
    # Do helper for 'is_pointer' / get pointed_size & co ? (useful for winproxy)
    pinfo = ctypes.pointer(info)
    try:
        windows.winproxy.NtQueryVolumeInformationFile(
            handle,
            io_status,
            pinfo,
            ctypes.sizeof(info),
            FsInformationClass=volume_info_class)
    except WindowsError as e:
        # import pdb;pdb.set_trace()
        if not (e.winerror & 0xffffffff) == gdef.STATUS_BUFFER_OVERFLOW:
            raise
        if volume_info_class == gdef.FileFsAttributeInformation:
            file_name_length = pinfo[0].FileSystemNameLength
        elif volume_info_class == gdef.FileFsVolumeInformation:
            # Well VolumeLabelLength is clearly broken (after testing..) so we are adding some bytes to it..
            file_name_length = pinfo[
                0].VolumeLabelLength + 0x100  # I have seen cases where the VolumeLabelLength is not even enough..
        else:
            raise
        full_size = ctypes.sizeof(
            info
        ) + file_name_length  # We add a little too much size for the sake of simplicity
        buffer = ctypes.c_buffer(full_size)
        windows.winproxy.NtQueryVolumeInformationFile(
            handle,
            io_status,
            buffer,
            full_size,
            FsInformationClass=volume_info_class)
        pinfo = ctypes.cast(
            buffer,
            ctypes.POINTER(
                ntqueryvolumeinformationfile_info_structs[volume_info_class]))
        info = pinfo[0]
    return info
    return info
Exemplo n.º 52
0
def write_process(hProcess, base_addr, value, byte_num=2):
    """往特定内存地址写入数据"""
    if byte_num == 1:
        buf = ctypes.c_byte(value)
    elif byte_num == 2:
        buf = ctypes.c_short(value)
    elif byte_num == 4:
        buf = ctypes.c_int32(value)
    elif byte_num == 8:
        buf = ctypes.c_int64(value)
    else:
        buf = ctypes.c_buffer(value, byte_num)
    nwrite = SIZE_T()
    ret = ctypes.windll.kernel32.WriteProcessMemory(hProcess, base_addr,
                                                    ctypes.byref(buf),
                                                    ctypes.sizeof(buf),
                                                    ctypes.byref(nwrite))

    return not not ret
Exemplo n.º 53
0
    def _create_shader(self, type, source):
        shader = glCreateShader(type)
        c_source = ctypes.create_string_buffer(source)
        c_source_ptr = ctypes.cast(ctypes.pointer(c_source),
                                   ctypes.POINTER(c_char))
        glShaderSource(shader, 1, ctypes.byref(c_source_ptr), None)
        glCompileShader(shader)

        status = ctypes.c_int()
        glGetShaderiv(shader, GL_COMPILE_STATUS, status)
        if not status.value:
            length = ctypes.c_int()
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, length)
            log = ctypes.c_buffer(length.value)
            glGetShaderInfoLog(shader, len(log), None, log)
            print(log.value, file=sys.stderr)
            raise RuntimeError('Shader compile error')

        return shader
Exemplo n.º 54
0
def sane_get_option_value(handle, option_idx):
    global sane_available
    assert (sane_available)

    # we need the descriptor first in order to allocate a buffer of the correct
    # size, then cast it to the correct type
    opt_desc = sane_get_option_descriptor(handle, option_idx)

    buf = ctypes.c_buffer(max(4, opt_desc.size))
    info = ctypes.c_int()

    status = SANE_LIB.sane_control_option(handle, ctypes.c_int(option_idx),
                                          SaneAction.GET_VALUE,
                                          ctypes.pointer(buf),
                                          ctypes.pointer(info))
    if status != SaneStatus.GOOD:
        raise SaneException(SaneStatus(status))

    return SaneValueType(opt_desc.type).buf_to_pyobj(buf)
Exemplo n.º 55
0
    def py_drop_func(hwnd, msg, wp, lp):
        global files, SetWindowLong
        if msg == WM_DROPFILES:
            pwint = WPARAM(wp)
            count = ctypes.windll.shell32.DragQueryFile(pwint, -1, None, None)
            szFile = ctypes.c_buffer(1024)
            files = []
            for i in range(count):
                ctypes.windll.shell32.DragQueryFile(pwint, i, szFile,
                                                    ctypes.sizeof(szFile))
                dropname = szFile.value
                files.append(dropname)
                #print(dropname)
            func(files)
            ctypes.windll.shell32.DragFinish(pwint)
        oldfunc = globals()[old]

        return CallWindowProcW(LPCVOID(oldfunc), hwnd, msg, WPARAM(wp),
                               LPARAM(lp))
Exemplo n.º 56
0
def MakeTypoglycemia(text):
    c_text = ctypes.c_buffer(text)
    i = 0
    bi = 0
    flag = False
    while i < len(c_text):
        if c_text[i].isalpha(
        ):  #97 <= ord(c_text[i]) <= 122 or 65 <= ord(c_text[i]) <= 90:
            if flag:
                if bi <= i - 3:
                    j = random.randint(bi + 1, i - 1)
                    c_text[j], c_text[i - 1] = c_text[i - 1], c_text[j]
            else:
                flag = True
                bi = i
        else:
            flag = False
        i += 1
    return c_text.value
Exemplo n.º 57
0
def enumerate_type():
    "WIP: DO NOT USE"
    size_needed = DWORD()
    fsize = 8
    fbuffer = ctypes.c_buffer(fsize)
    try:
        winproxy.NtQueryObject(None, gdef.ObjectTypesInformation, fbuffer,
                               fsize, ctypes.byref(size_needed))
    except WindowsError as e:
        if e.code != STATUS_INFO_LENGTH_MISMATCH:
            raise
    else:
        # We had enought memory ?
        return

    # Looks like the Wow64 syscall emulation is broken :D
    # It write AFTER the buffer if we are a wow64 process :D
    # So better allocate a standalone buffer (triggering a ACCESS_VIOLATION) that corrupting the heap
    # This is a worst case scenario, as we allocation more space it should not happen !
    size = size_needed.value + 0x200
    size_needed.value = 0

    with windows.current_process.allocated_memory(
            size, gdef.PAGE_READWRITE) as buffer_base:
        winproxy.NtQueryObject(None, gdef.ObjectTypesInformation, buffer_base,
                               size, ctypes.byref(size_needed))
        # Cache some exceptions ?
        # Parse the buffer data in-place as string are addr-dependant
        types_info = gdef.OBJECT_TYPES_INFORMATION.from_address(buffer_base)
        offset = ctypes.sizeof(
            gdef.PVOID
        )  # Looks like the size of the struct is PTR aligned as the struct is follower by other stuff
        for i in range(types_info.NumberOfTypes):
            info = gdef.PUBLIC_OBJECT_TYPE_INFORMATION.from_address(
                buffer_base + offset)
            yield info
            offset += ctypes.sizeof(gdef.PUBLIC_OBJECT_TYPE_INFORMATION
                                    ) + info.TypeName.MaximumLength
            if offset % ctypes.sizeof(gdef.PVOID):
                offset += ctypes.sizeof(
                    gdef.PVOID) - (offset % ctypes.sizeof(gdef.PVOID))
    # End-of ctx-manager
    return
Exemplo n.º 58
0
 def parse(self, text):
     dll = cdll.LoadLibrary("WordSegAPI/ICTCLAS50.dll")
     dll.ICTCLAS_Init(c_char_p("WordSegAPI"))
     sSentence = c_char_p(text)
     nPaLen = len(sSentence.value)
     sRst = c_buffer(nPaLen * 6)
     #userdict = ";分布式计算;机器学习;"
     userdict = 'userdict.txt'
     #dll.ICTCLAS_ImportUserDict(c_char_p(userdict),3)
     wn = dll.ICTCLAS_ImportUserDictFile(c_char_p(userdict), 0)
     print 'imported %d words from user dictionary' % (wn)
     dll.ICTCLAS_SaveTheUsrDic()
     dll.ICTCLAS_ParagraphProcess(sSentence, c_int(nPaLen), sRst, 0, 0)
     reList = [
         word for word in sRst.value.split(' ') if word not in self._stext
     ]
     del sRst
     dll.ICTCLAS_Exit()
     return reList
Exemplo n.º 59
0
    def get(path, attr):
        """Get an extended attribute on a specified file.

        path - path name of file to check
        attr - name of attribute to get

        None is returned if the named attribute does not exist.  OSError
        is raised if path does not exist or is not readable."""

        if not os.access(path, os.F_OK):
            raise OSError(errno.ENOENT, 'No such file or directory', path)

        size = libc.getxattr(path, attr, '', 0)
        if size < 0:
            return

        buf = ctypes.c_buffer(size + 1)
        libc.getxattr(path, attr, ctypes.byref(buf), size)
        return buf.value
Exemplo n.º 60
-1
def get_pixels(monitor):
    ''' Retrieve pixels from a monitor '''
    ret = ""
    hmon = monitor['hdc']
    width = monitor['width']
    height = monitor['height']
    left = monitor['left']
    top = monitor['top']
    user = ctypes.windll.user32
    gdi = ctypes.windll.gdi32
    metrics = ctypes.windll.user32.GetSystemMetrics(0)
    SRCCOPY = 0xCC0020
    DIB_RGB_COLORS = 0
    srcdc = ctypes.windll.user32.GetWindowDC(0)
    memdc = ctypes.windll.gdi32.CreateCompatibleDC(srcdc)
    bmp = ctypes.windll.gdi32.CreateCompatibleBitmap(srcdc, width, height)
    ctypes.windll.gdi32.SelectObject(memdc, bmp)
    ctypes.windll.gdi32.BitBlt(memdc, 0, 0, width, height, srcdc, left, top, SRCCOPY)
    bmp_header = struct.pack('LHHHH', struct.calcsize('LHHHH'), width, height, 1, 24)
    c_bmp_header = ctypes.c_buffer(bmp_header)
    c_bits =       ctypes.c_buffer(' ' * (height * ((width * 3 + 3) & -4)))
    got_bits =     ctypes.windll.gdi32.GetDIBits(memdc, bmp, 0, height,
                                                 c_bits, c_bmp_header, DIB_RGB_COLORS)
    ret="P6\n%d %d\n255\n" % ( monitor['width'] ,monitor['height'] )
    rv = [ret]
    for i in xrange(height-1,-1,-1):
        start_index =int( i * ((width * 3 + 3) & -4) )
        end_index   =int( start_index+ width*3 )
        rv.append(c_bits.__getslice__(start_index, end_index))
    return "".join(rv)