Python ctypes.c_buffer() Examples
The following are 30
code examples of ctypes.c_buffer().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ctypes
, or try the search function
.
Example #1
Source File: cryptmsg.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_param(self, param_type, index=0, raw=False): data_size = gdef.DWORD() # https://msdn.microsoft.com/en-us/library/windows/desktop/aa380227(v=vs.85).aspx winproxy.CryptMsgGetParam(self, param_type, index, None, data_size) buffer = ctypes.c_buffer(data_size.value) winproxy.CryptMsgGetParam(self, param_type, index, buffer, data_size) if raw: return (buffer, data_size) if param_type in self.MSG_PARAM_KNOW_TYPES: buffer = self.MSG_PARAM_KNOW_TYPES[param_type].from_buffer(buffer) if isinstance(buffer, gdef.DWORD): # DWORD -> return the Python int return buffer.value return buffer # Certificate accessors
Example #2
Source File: event_log.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render(self, ctx, rtype): size = 0x10000 buffer = ctypes.c_buffer(size) rsize = gdef.DWORD() elementnb = gdef.DWORD() try: windows.winproxy.EvtRender(ctx, self, rtype, size, buffer, rsize, elementnb) except WindowsError as e: if e.winerror != gdef.ERROR_INSUFFICIENT_BUFFER: raise size = rsize.value buffer = ctypes.c_buffer(size) windows.winproxy.EvtRender(ctx, self, rtype, size, buffer, rsize, elementnb) # Adapting return value type if rtype != gdef.EvtRenderEventValues: # import pdb;pdb.set_trace() # assert elementnb.value == 1 return buffer[:rsize.value] # print("Got <{0}> elt".format(elementnb.value)) return list((ImprovedEVT_VARIANT * elementnb.value).from_buffer(buffer))
Example #3
Source File: dpapi.py From code with MIT License | 6 votes |
def dpapi_decrypt_data(self, encrypted_bytes, entropy = extra_entropy): ''' Decrypts data and returns byte string :param encrypted_bytes: The encrypted data :type encrypted_bytes: Bytes :param entropy: Extra entropy to add to the encryption process (optional) :type entropy: String or Bytes ''' if not isinstance(encrypted_bytes, bytes) or not isinstance(entropy, bytes): self.fatal('The inputs to dpapi must be bytes') buffer_in = c_buffer(encrypted_bytes, len(encrypted_bytes)) buffer_entropy = c_buffer(entropy, len(entropy)) blob_in = DATA_BLOB(len(encrypted_bytes), 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 get_data(blob_out) else: self.fatal('Failed to decrypt data')
Example #4
Source File: atapt.py From atapt with MIT License | 6 votes |
def readSmart(self): buf = ctypes.c_buffer(512) buf = self.readSmartValues() self.selftestStatus = int.from_bytes(buf[363], byteorder='little') self.smart = {} for i in range(30): if buf[2 + i * 12] == b'\x00': continue aid = int.from_bytes(buf[2 + i * 12], byteorder='little') pre_fail = int.from_bytes(buf[2 + i * 12 + 1], byteorder='little') & 1 online = (int.from_bytes(buf[2 + i * 12 + 1], byteorder='little') & 2) >> 1 current = int.from_bytes(buf[2 + i * 12 + 3], byteorder='little') if current == 0 or current == 0xfe or current == 0xff: continue worst = int.from_bytes(buf[2 + i * 12 + 4], byteorder='little') raw = int.from_bytes(buf[2 + i * 12 + 5] + buf[2 + i * 12 + 6] + buf[2 + i * 12 + 7] + buf[2 + i * 12 + 8] + buf[2 + i * 12 + 9] + buf[2 + i * 12 + 10], byteorder='little') self.smart[aid] = [pre_fail, online, current, worst, raw] buf = self.readSmartThresholds() for i in range(30): if buf[2 + i * 12] == b'\x00': continue aid = int.from_bytes(buf[2 + i * 12], byteorder='little') if aid in self.smart: self.smart[aid].append(int.from_bytes(buf[2 + i * 12 + 1], byteorder='little'))
Example #5
Source File: dpapi.py From code with MIT License | 6 votes |
def dpapi_encrypt_data(self, input_bytes, entropy = extra_entropy): ''' Encrypts data and returns byte string :param input_bytes: The data to be encrypted :type input_bytes: String or Bytes :param entropy: Extra entropy to add to the encryption process (optional) :type entropy: String or Bytes ''' if not isinstance(input_bytes, bytes) or not isinstance(entropy, bytes): self.fatal('The inputs to dpapi must be bytes') buffer_in = c_buffer(input_bytes, len(input_bytes)) buffer_entropy = c_buffer(entropy, len(entropy)) blob_in = DATA_BLOB(len(input_bytes), buffer_in) blob_entropy = DATA_BLOB(len(entropy), buffer_entropy) blob_out = DATA_BLOB() if CryptProtectData(byref(blob_in), 'python_data', byref(blob_entropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blob_out)): return get_data(blob_out) else: self.fatal('Failed to decrypt data')
Example #6
Source File: atapt.py From atapt with MIT License | 6 votes |
def securityDisable(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_DISABLE_PASSWORD, 0, 0, 0, SG_DXFER_TO_DEV, buf) self.clearSense() self.doSgio() try: self.checkSense() except senseError: raise securityError()
Example #7
Source File: atapt.py From atapt with MIT License | 6 votes |
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()
Example #8
Source File: core.py From thorlabs_apt with GNU General Public License v2.0 | 6 votes |
def hardware_info(serial_number): """ Retrieves hardware information about the devices identified by its serial number. Parameters ---------- serial_number : int Serial number identifying the device Returns ------- out : tuple hardware information: (model, software version, hardware notes) """ model = ctypes.c_buffer(255) swver = ctypes.c_buffer(255) hwnotes = ctypes.c_buffer(255) err_code = _lib.GetHWInfo(serial_number, model, len(model), swver, len(swver), hwnotes, len(hwnotes)) if (err_code != 0): raise Exception("Getting hardware info failed: %s" % _get_error_text(err_code)) return (model.value, swver.value, hwnotes.value)
Example #9
Source File: atapt.py From atapt with MIT License | 6 votes |
def securitySetPassword(self, master, capability, password): buf = ctypes.c_buffer(512) if master: buf[0] = 1 else: buf[0] = 0 if capability: buf[1] = 1 pwd = str.encode(password) i = 2 for b in pwd: buf[i] = b i = i + 1 self.prepareSgio(SECURITY_SET_PASSWORD, 0, 0, 0, SG_DXFER_TO_DEV, buf) self.clearSense() self.doSgio() try: self.checkSense() except senseError: raise securityError()
Example #10
Source File: alpc.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, msg_or_size=0x1000, attributes=None): # Init the PORT_MESSAGE if isinstance(msg_or_size, windows.pycompat.int_types): self.port_message_buffer_size = msg_or_size self.port_message_raw_buffer = ctypes.c_buffer(msg_or_size) self.port_message = AlpcMessagePort.from_buffer(self.port_message_raw_buffer) self.port_message.set_datalen(0) elif isinstance(msg_or_size, AlpcMessagePort): self.port_message = msg_or_size self.port_message_raw_buffer = self.port_message.raw_buffer self.port_message_buffer_size = len(self.port_message_raw_buffer) else: raise NotImplementedError("Uneexpected type for <msg_or_size>: {0}".format(msg_or_size)) # Init the MessageAttributes if attributes is None: # self.attributes = MessageAttribute.with_all_attributes() self.attributes = MessageAttribute.with_all_attributes() ## Testing else: self.attributes = attributes # PORT_MESSAGE wrappers
Example #11
Source File: renderfield.py From pyglet with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, vertex_source, fragment_source=None): vertex_shader = self._create_shader(GL_VERTEX_SHADER, vertex_source) if fragment_source: fragment_shader = self._create_shader(GL_FRAGMENT_SHADER, fragment_source) program = glCreateProgram() glAttachShader(program, vertex_shader) if fragment_source: glAttachShader(program, fragment_shader) glLinkProgram(program) status = ctypes.c_int() glGetProgramiv(program, GL_LINK_STATUS, status) if not status.value: length = ctypes.c_int() glGetProgramiv(program, GL_INFO_LOG_LENGTH, length) log = ctypes.c_buffer(length.value) glGetProgramInfoLog(program, len(log), None, log) print(log.value, file=sys.stderr) raise RuntimeError('Program link error') self.program = program self._uniforms = {}
Example #12
Source File: renderfield.py From pyglet with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #13
Source File: object_manager.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _directory_query_generator(self): handle = self._open_directory() size = 0x1000 buf = ctypes.c_buffer(size) rres = gdef.ULONG() ctx = gdef.ULONG() while True: try: # Restart == True has we don't save the buffer when resizing it for next call winproxy.NtQueryDirectoryObject(handle, buf, size, False, True, ctypes.byref(ctx), rres) break except gdef.NtStatusException as e: if e.code == gdef.STATUS_NO_MORE_ENTRIES: return if e.code == gdef.STATUS_MORE_ENTRIES: # If the call did not extrack all data: retry with bigger buffer size *= 2 buf = ctypes.c_buffer(size) continue raise # Function -> _extract_objects ? t = gdef.OBJECT_DIRECTORY_INFORMATION.from_buffer(buf) t = gdef.POBJECT_DIRECTORY_INFORMATION(t) res = {} for v in t: if v.Name.Buffer is None: break yield v.Name.str, v.TypeName.str
Example #14
Source File: alpc.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def from_buffer_size(cls, buffer_size): buffer = ctypes.c_buffer(buffer_size) return cls.from_buffer(buffer)
Example #15
Source File: process.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def name(self): """Name of the process :type: :class:`str` """ buffer = ctypes.c_buffer(0x1024) rsize = winproxy.GetProcessImageFileNameA(self.limited_handle, buffer) # GetProcessImageFileNameA returns the fullpath return buffer[:rsize].decode().split("\\")[-1]
Example #16
Source File: process.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def read_memory(self, addr, size): """Read ``size`` from ``addr`` :return: The data read :rtype: :class:`str` """ dbgprint('Read CurrentProcess Memory', 'READMEM') buffer = ctypes.c_buffer(size) ctypes.memmove(buffer, addr, size) return buffer[:]
Example #17
Source File: process.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_mapped_filename(self, addr): """The filename mapped at address ``addr`` or ``None`` :rtype: :class:`unicode` 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): raise return None remote_winstring = rctypes.transform_type_to_remote64bits(gdef.LSA_UNICODE_STRING) mapped_filename = remote_winstring(ctypes.addressof(buffer), windows.current_process) return mapped_filename.str try: size = winproxy.GetMappedFileNameW(self.handle, addr, buffer, buffer_size) except winproxy.WinproxyError as e: if e.winerror not in (gdef.ERROR_UNEXP_NET_ERR, gdef.ERROR_FILE_INVALID): raise # Raise if error type is not expected: detect mapped aborted transaction return None return buffer[: size * 2].decode("utf16")
Example #18
Source File: handle.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #19
Source File: handle.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_object_name(self): lh = self.local_handle size_needed = gdef.DWORD() yyy = ctypes.c_buffer(0x1000) winproxy.NtQueryObject(lh, gdef.ObjectNameInformation, ctypes.byref(yyy), ctypes.sizeof(yyy), ctypes.byref(size_needed)) return gdef.LSA_UNICODE_STRING.from_buffer_copy(yyy[:size_needed.value]).str
Example #20
Source File: event_trace.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def infos(self): size = gdef.DWORD() info_buffer = ctypes.c_buffer(0x1000) try: windows.winproxy.EnumerateTraceGuidsEx(gdef.TraceGuidQueryInfo, self.guid, ctypes.sizeof(self.guid), info_buffer, ctypes.sizeof(info_buffer), size) except WindowsError as e: if not e.winerror == gdef.ERROR_INSUFFICIENT_BUFFER: raise # Buffer to small info_buffer = ctypes.c_buffer(size.value) windows.winproxy.EnumerateTraceGuidsEx(gdef.TraceGuidQueryInfo, self.guid, ctypes.sizeof(self.guid), info_buffer, ctypes.sizeof(info_buffer), size) return TraceGuidInfo.from_raw_buffer(info_buffer) # We dont really care about the C struct layout # Our trace providers should be able to directly returns its instances
Example #21
Source File: token.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _lookup_name(self, luid): size = gdef.DWORD(0x100) buff = ctypes.c_buffer(size.value) winproxy.LookupPrivilegeNameA(None, luid, buff, size) return buff[:size.value]
Example #22
Source File: certificate.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_hash(self): size = gdef.DWORD(100) buffer = ctypes.c_buffer(size.value) winproxy.CryptHashCertificate(None, 0, 0, self.pbCertEncoded, self.cbCertEncoded, ctypes.cast(buffer, gdef.LPBYTE), size) return buffer[:size.value]
Example #23
Source File: security.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def from_binary(cls, data): """Retrieve the security descriptor described by the binary ``data``. Binary security descriptor can be found in the registry for example """ if isinstance(data, basestring): data = ctypes.c_buffer(data) return ctypes.cast(data, cls)
Example #24
Source File: system.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_file_version(self, name): size = winproxy.GetFileVersionInfoSizeA(name) buf = ctypes.c_buffer(size) winproxy.GetFileVersionInfoA(name, 0, size, buf) bufptr = gdef.PVOID() bufsize = gdef.UINT() winproxy.VerQueryValueA(buf, "\\VarFileInfo\\Translation", ctypes.byref(bufptr), ctypes.byref(bufsize)) bufstr = ctypes.cast(bufptr, gdef.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, gdef.LPCSTR) return bufstr.value
Example #25
Source File: test_system_modules.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_system_module_gc(): # Test for issue 12 (Py3) # https://github.com/hakril/PythonForWindows/issues/12 mods = windows.system.modules first_name = mods[0].ImageName import gc; gc.collect() # need to do stuff to trigger the bug # YOLO LA HEAP for i in range(0x1000): ctypes.c_buffer(i) import gc; gc.collect() assert mods[0].ImageName == first_name
Example #26
Source File: dpapi.py From code with MIT License | 5 votes |
def get_data(blob_out): cbData = int(blob_out.cbData) pbData = blob_out.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw
Example #27
Source File: windows.py From ComicStreamer with Apache License 2.0 | 5 votes |
def __init__(self, ArcName=None, ArcNameW=u'', OpenMode=RAR_OM_LIST): self.CmtBuf = ctypes.c_buffer(64*1024) ctypes.Structure.__init__(self, ArcName=ArcName, ArcNameW=ArcNameW, OpenMode=OpenMode, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf))
Example #28
Source File: windows.py From ComicStreamer with Apache License 2.0 | 5 votes |
def __init__(self): self.CmtBuf = ctypes.c_buffer(64*1024) ctypes.Structure.__init__(self, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf))
Example #29
Source File: __init__.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def GetItemList(menu, hWnd): SendMessage(hWnd, WM_INITMENUPOPUP, menu, 0) #REFRESH MENU STATE !!! itemList = [] itemName = c_buffer("\000" * 128) count = GetMenuItemCount(menu) for i in range(count): windll.user32.GetMenuStringA(c_int(menu), c_int(i), itemName, c_int(len(itemName)), MF_BYPOSITION) menuState = windll.user32.GetMenuState(c_int(menu), c_int(i), MF_BYPOSITION) id = windll.user32.GetMenuItemID(c_int(menu), c_int(i)) if menuState & (MF_GRAYED|MF_DISABLED): continue item = itemName.value.replace("&","").split("\t")[0] if item == "" and id == 0: continue checked = bool(menuState & MF_CHECKED) if isabs(item): if not isfile(item): continue else: item = split(item)[1] itemList.append((item, i, checked, id)) return itemList #===============================================================================
Example #30
Source File: playsound.py From playsound with MIT License | 5 votes |
def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3play: https://github.com/michaelgundlach/mp3play I never would have tried using windll.winmm without seeing his code. ''' from ctypes import c_buffer, windll from random import random from time import sleep from sys import getfilesystemencoding 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 alias = 'playsound_' + str(random()) winCommand('open "' + sound + '" alias', alias) winCommand('set', alias, 'time format milliseconds') durationInMS = winCommand('status', alias, 'length') winCommand('play', alias, 'from 0 to', durationInMS.decode()) if block: sleep(float(durationInMS) / 1000.0)