def read_bytes(self, address, bytes=4): """ Read bytes from address """ address = int(address) buffer = create_string_buffer(bytes) bytesRead = c_size_t(0) length = bytes data = b"" while length: if ReadProcessMemory(self.h_process, address, byref(buffer), bytes, byref(bytesRead)): if bytesRead.value: data += buffer.raw[:bytesRead.value] length -= bytesRead.value address += bytesRead.value if not data: print("Error in {0} ReadProcessMemory()".format( GetLastError())) exit(0) return data else: # ERROR_PARTIAL_COPY 299 (0x12B) # Only part of a ReadProcessMemory or WriteProcessMemory request was completed. # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx if GetLastError() == winerror.ERROR_PARTIAL_COPY: data += buffer.raw[:bytesRead.value] raise WinError() return data
def ReadProcessMememory(self, address, bytes): buffer = create_string_buffer(bytes) sizeRead = c_size_t(0) bufferSize = len(buffer) retval = 0 if self._need_64(address): if not ReadProcessMemory64: raise NotImplementedError() retval = ReadProcessMemory64(self.h_process, address, buffer, bufferSize, byref(sizeRead)) else: retval = ReadProcessMemory(self.h_process, address, buffer, bufferSize, byref(sizeRead)) if not retval: if GetLastError() == 299: # Incomplete read pass else: raise WindowsError(GetLastError()) return buffer.raw[:sizeRead.value]
def GetDeviceHardwareId(hDevInfo, deviceInfoData): buffersize = DWORD(0) dataType = DWORD() if SetupDiGetDeviceRegistryProperty( hDevInfo, byref(deviceInfoData), SPDRP_HARDWAREID, None, None, 0, byref(buffersize) ): raise WinError() err = GetLastError() if err == ERROR_INSUFFICIENT_BUFFER: hardwareId = create_unicode_buffer(buffersize.value / 2) else: raise WinError(err) if not SetupDiGetDeviceRegistryProperty( hDevInfo, byref(deviceInfoData), SPDRP_HARDWAREID, byref(dataType), cast(hardwareId, PBYTE), buffersize.value, byref(buffersize) ): raise WinError() return StripRevision(hardwareId.value.upper())
def check_error(value): """Some functions return 0 which may be an error or not, depending on the outcome of GetLastError()""" if value == 0: code = GetLastError() if code: raise WinError(code) return value
def ApplyAlpha(win, bitmap, sourceAlpha=255): setLayered(win, True) r = win.Rect pos = CPoint() pos.x, pos.y = r[:2] size = CPoint() size.x, size.y = r[2:] memdc = wx.MemoryDC(bitmap) imgpos = CPoint() imgpos.x = imgpos.y = 0 colorkey = c_int(0) blendPixelFunction = makeBlendFunction(sourceAlpha) res = UpdateLayeredWindow(win.Handle, GetDC(None), byref(pos), byref(size), memdc.GetHDC(), byref(imgpos), colorkey, byref(blendPixelFunction), ULW_ALPHA) if not res: raise WinError(GetLastError()) memdc.SelectObject(wx.NullBitmap)
def pipe_non_blocking_is_error_blocking(ex): if not isinstance(ex, PortableBlockingIOError): return False from ctypes import GetLastError ERROR_NO_DATA = 232 return (GetLastError() == ERROR_NO_DATA)
def LookupAccountSidW(lpSid): # From https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/win32/advapi32.py PSID = PVOID() if not _ConvertStringSidToSid(lpSid, byref(PSID)): return None, None, None ERROR_INSUFFICIENT_BUFFER = 122 cchName = DWORD(0) cchReferencedDomainName = DWORD(0) peUse = DWORD(0) success = _LookupAccountSidW(None, PSID, None, byref(cchName), None, byref(cchReferencedDomainName), byref(peUse)) error = GetLastError() if not success or error == ERROR_INSUFFICIENT_BUFFER: lpName = create_unicode_buffer(u'', cchName.value + 1) lpReferencedDomainName = create_unicode_buffer( u'', cchReferencedDomainName.value + 1) success = _LookupAccountSidW(None, PSID, lpName, byref(cchName), lpReferencedDomainName, byref(cchReferencedDomainName), byref(peUse)) if success: return lpName.value, lpReferencedDomainName.value, peUse.value _LocalFree(PSID) return None, None, None
def from_path(cls, path, mode="r", shared=False): # type: (str, str, bool) -> WindowsFile """ Create a Windows file objects from `path`. If shared is False: allow write access from other processes. """ DesiredAccess = _mode2access[mode] if shared: ShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE else: ShareMode = FILE_SHARE_READ SecurityAttributes = None CreationDisposition = OPEN_EXISTING FlagsAndAttributes = 0 handle = CreateFileW(path, DesiredAccess, ShareMode, SecurityAttributes, CreationDisposition, FlagsAndAttributes, None) if handle == INVALID_HANDLE_VALUE: winerror = GetLastError() if winerror == ERROR_SHARING_VIOLATION: errno = EACCES strerror = FormatError(winerror) raise SharingViolation(errno, strerror, path, winerror) else: raise WinError() return cls(handle)
def read_bytes(self, address, bytes = 4, use_NtWow64ReadVirtualMemory64=False): #print "reading %s bytes from addr %s"%(bytes, address) if use_NtWow64ReadVirtualMemory64: if NtWow64ReadVirtualMemory64 is None: raise WindowsError("NtWow64ReadVirtualMemory64 is not available from a 64bit process") RpM = NtWow64ReadVirtualMemory64 else: RpM = ReadProcessMemory address = int(address) buffer = create_string_buffer(bytes) bytesread = c_size_t(0) data = '' length = bytes while length: if RpM(self.h_process, address, buffer, bytes, byref(bytesread)) or (use_NtWow64ReadVirtualMemory64 and GetLastError() == 0): if bytesread.value: data += buffer.raw[:bytesread.value] length -= bytesread.value address += bytesread.value if not len(data): raise ProcessException('Error %s in ReadProcessMemory(%08x, %d, read=%d)' % (GetLastError(), address, length, bytesread.value)) return data else: if GetLastError()==299: #only part of ReadProcessMemory has been done, let's return it data += buffer.raw[:bytesread.value] return data raise WinError() # data += buffer.raw[:bytesread.value] # length -= bytesread.value # address += bytesread.value return data
def wrapper(*args, **kwargs): result = f(*args, **kwargs) retcode = GetLastError() if retcode and retcode != ERROR_IO_PENDING: err = WinError(code=retcode) windll.kernel32.SetLastError(0) # clear error code so that we don't raise twice. raise err return result
def process_task(queue_map, process_name): if IS_FROZEN: cmd = f'{process_name}.exe' else: cmd = f'python {process_name}.py' startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW state = PROCESS_STATE_STOP process = None while True: command = None try: command = queue_map[f'{process_name}_process'].get_nowait() except QueueEmpty: pass if command == PROCESS_STATE_START and state == PROCESS_STATE_STOP: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, close_fds=False, bufsize=1, universal_newlines=True, startupinfo=startupinfo) pipe_no_wait(process.stdout.fileno()) state = PROCESS_STATE_START if state == PROCESS_STATE_START: while True: try: while True: line = process.stdout.readline() if not line: break queue_map[f'{process_name}_log'].put(line) except OSError: if GetLastError() == ERROR_NO_DATA: break raise if process.poll() is not None: queue_map[f'{process_name}_process'].put( PROCESS_STATE_STOP) break if command == PROCESS_STATE_STOP and state == PROCESS_STATE_START: # process.kill() subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)], startupinfo=startupinfo) process = None state = PROCESS_STATE_STOP queue_map[f'{process_name}_log'].put('Successfully stopped.\n') time.sleep(0.1)
def move(srcfile, destfile, overwrite, warnBetweenDrives=False, traceToStdout=False, allowDirs=False, useDestModifiedTime=False, createParent=False): if not exists(srcfile): raise IOError('source path does not exist') if not allowDirs and not isfile(srcfile): raise IOError('source path does not exist or is not a file') toSetModTime = None if useDestModifiedTime and exists(destfile): assertTrue(isfile(destfile), 'not supported for directories') toSetModTime = getModTimeNs(destfile) if traceToStdout: trace('move()', srcfile, destfile) if createParent and not exists(getparent(destfile)): makedirs(getparent(destfile)) if srcfile == destfile: pass elif sys.platform.startswith('win'): from ctypes import windll, c_wchar_p, c_int, GetLastError ERROR_NOT_SAME_DEVICE = 17 flags = 0 flags |= 1 if overwrite else 0 flags |= 0 if warnBetweenDrives else 2 res = windll.kernel32.MoveFileExW(c_wchar_p(srcfile), c_wchar_p(destfile), c_int(flags)) if not res: err = GetLastError() if err == ERROR_NOT_SAME_DEVICE and warnBetweenDrives: rinput('Note: moving file from one drive to another. ' + '%s %s Press Enter to continue.\r\n' % (srcfile, destfile)) return move(srcfile, destfile, overwrite, warnBetweenDrives=False) raise IOError( 'MoveFileExW failed (maybe dest already exists?) err=%d' % err + getPrintable(srcfile + '->' + destfile)) elif sys.platform.startswith('linux') and overwrite: _os.rename(srcfile, destfile) else: copy(srcfile, destfile, overwrite) _os.unlink(srcfile) assertTrue(exists(destfile)) if toSetModTime: setModTimeNs(destfile, toSetModTime)
def read_bytes(self, address, bytes=4, use_NtWow64ReadVirtualMemory64=False): #print "reading %s bytes from addr %s"%(bytes, address) if use_NtWow64ReadVirtualMemory64: if NtWow64ReadVirtualMemory64 is None: raise WindowsError( "NtWow64ReadVirtualMemory64 is not available from a 64bit process" ) RpM = NtWow64ReadVirtualMemory64 else: RpM = ReadProcessMemory address = int(address) if not self.isProcessOpen: raise ProcessException( "Can't read_bytes(%s, bytes=%s), process %s is not open" % (address, bytes, self.pid)) #print "creating buf: %s"%bytes buffer = create_string_buffer(bytes) bytesread = c_size_t(0) data = '' length = bytes _address = address _length = length while length: if RpM(self.h_process, address, buffer, bytes, byref(bytesread)) or (use_NtWow64ReadVirtualMemory64 and GetLastError() == 0): if bytesread.value: data += buffer.raw[:bytesread.value] length -= bytesread.value address += bytesread.value if not len(data): raise ProcessException( 'Error %s in ReadProcessMemory(%08x, %d, read=%d)' % (GetLastError(), address, length, bytesread.value)) return data else: raise WinError() data += buffer.raw[:bytesread.value] length -= bytesread.value address += bytesread.value return data
def check_zero(result, func, arguments, *args): if result == 0: code = GetLastError() description = FormatError(code).strip() if func_name is None: raise error(code, func.__name__, description) else: raise error(code, func_name, description) return result
def __start__( self, ledRX=True, ledTX=True, legacyRX=False, repeatStopCodes=False, ): self.args = (ledRX, ledTX, legacyRX, repeatStopCodes) self.codeFormat = UUIRTDRV_IRFMT_PRONTO try: dll = WinDLL('uuirtdrv') except: raise self.Exceptions.DriverNotFound puDrvVersion = c_uint(0) if not dll.UUIRTGetDrvInfo(byref(puDrvVersion)): raise self.Exception("Unable to retrieve uuirtdrv version!") if puDrvVersion.value != 0x0100: raise self.Exception("Invalid uuirtdrv version!") if self.info.evalName[-1].isdigit(): self.deviceStr = "USB-UIRT-%s" % self.info.evalName[-1] else: self.deviceStr = "USB-UIRT" hDrvHandle = dll.UUIRTOpenEx(self.deviceStr, 0, 0, 0) if hDrvHandle == INVALID_HANDLE_VALUE: err = GetLastError() if err == UUIRTDRV_ERR_NO_DLL: raise self.Exceptions.DriverNotFound elif err == UUIRTDRV_ERR_NO_DEVICE: raise self.Exceptions.DeviceNotFound elif err == UUIRTDRV_ERR_NO_RESP: raise self.Exceptions.DeviceInitFailed else: raise self.Exceptions.DeviceInitFailed self.hDrvHandle = hDrvHandle puuInfo = UUINFO() if not dll.UUIRTGetUUIRTInfo(hDrvHandle, byref(puuInfo)): raise self.Exceptions.DeviceInitFailed self.firmwareVersion = "%d.%d" % (puuInfo.fwVersion >> 8, puuInfo.fwVersion & 0xFF) self.protocolVersion = "%d.%d" % (puuInfo.protVersion >> 8, puuInfo.protVersion & 0xFF) self.firmwareDate = datetime.date(puuInfo.fwDateYear + 2000, puuInfo.fwDateMonth, puuInfo.fwDateDay) self.dll = dll self.receiveProc = UUCALLBACKPROC(self.ReceiveCallback) res = dll.UUIRTSetRawReceiveCallback(self.hDrvHandle, self.receiveProc, 0) if not res: self.dll = None raise self.Exception("Error calling UUIRTSetRawReceiveCallback") self.SetConfig(ledRX, ledTX, legacyRX, repeatStopCodes) self.enabled = True eg.Bind("System.DeviceRemoved", self.OnDeviceRemoved)
def GetDevicePaths(): classGuid = GUID() CLSIDFromString(DRIVER_CLASS_GUID, byref(classGuid)) hDevInfo = SetupDiGetClassDevs( classGuid, None, None, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE ) if hDevInfo == INVALID_HANDLE_VALUE: raise WinError() deviceInterfaceData = SP_DEVICE_INTERFACE_DATA() deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA) deviceInfoData = SP_DEVINFO_DATA() deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA) memberIndex = 0 result = {} while True: if not SetupDiEnumDeviceInterfaces( hDevInfo, None, classGuid, memberIndex, byref(deviceInterfaceData) ): err = GetLastError() if err == ERROR_NO_MORE_ITEMS: break else: raise WinError(err) requiredSize = DWORD() SetupDiGetDeviceInterfaceDetail( hDevInfo, byref(deviceInterfaceData), None, 0, byref(requiredSize), byref(deviceInfoData) ) buf = create_string_buffer(requiredSize.value) pDiDetailData = cast(buf, PSP_DEVICE_INTERFACE_DETAIL_DATA) pDiDetailData.contents.cbSize = sizeof( SP_DEVICE_INTERFACE_DETAIL_DATA ) SetupDiGetDeviceInterfaceDetail( hDevInfo, byref(deviceInterfaceData), pDiDetailData, requiredSize.value, byref(requiredSize), None ) devicePath = wstring_at(addressof(pDiDetailData.contents) + 4) hardwareId = WinUsb.GetDeviceHardwareId(hDevInfo, deviceInfoData) result[hardwareId] = devicePath memberIndex += 1 return result
def make_error(function, function_name=None): code = GetLastError() description = FormatError(code).strip() if function_name is None: function_name = function.__name__ exception = WindowsError() exception.winerror = code exception.function = function_name exception.strerror = description return exception
def _create_mutex(self): """ Attempt to create a new mutex. Returns True if the mutex was acquired successfully, or False if the mutex is already in use. """ mutex_name = c_wchar_p(self._app_id[:MAX_PATH]) handle = windll.kernel32.CreateMutexW(None, c_bool(False), mutex_name) self._mutex = handle return not (not handle or GetLastError() == ERROR_ALREADY_EXISTS)
def CryptAcquireContext(): hprov = c_void_p() success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, 0) if not success and GetLastError() & 0xffffffff == NTE_BAD_KEYSET: success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, CRYPT_NEWKEYSET) assert_success(success) return hprov
def _connect_raw(self): # This is a similar procedure to the one in # https://github.com/microsoft/go-winio/blob/master/pipe.go (tryDialPipe) while True: try: return open(self._name, 'wb+', buffering=0) except (OSError, IOError): if GetLastError() != self.ERROR_PIPE_BUSY: raise time.sleep(0.001) # 1ms
def _is_wow64_process(): kernel32 = windll.kernel32 GetCurrentProcess = kernel32.GetCurrentProcess GetCurrentProcess.argtypes = [] GetCurrentProcess.restype = c_void_p IsWow64Process2 = None IMAGE_FILE_MACHINE_UNKNOWN = 0 try: #IsWow64Process2() is only available on Win10 TH2 or later IsWow64Process2 = kernel32.IsWow64Process2 except AttributeError: IsWow64Process2 = None if IsWow64Process2 is not None: IsWow64Process2.argtypes = [ c_void_p, POINTER(c_ushort), POINTER(c_ushort) ] IsWow64Process2.restype = c_int ProcessMachine = c_ushort(1) NativeMachine = c_ushort(1) if IsWow64Process2(GetCurrentProcess(), byref(ProcessMachine), byref(NativeMachine)) != 0: if ProcessMachine.value == IMAGE_FILE_MACHINE_UNKNOWN: return False else: return True else: raise WinError(GetLastError()) else: #Graceful fallback for older OSes IsWow64Process = kernel32.IsWow64Process IsWow64Process.argtypes = [c_void_p, POINTER(c_int)] IsWow64Process.restype = c_int is_wow64 = c_int(0) if IsWow64Process(GetCurrentProcess(), byref(is_wow64)) != 0: if is_wow64.value != 0: return True else: return False else: raise WinError(GetLastError())
def get_short_path_name(long_name): prefix, long_path = prefix_and_path(long_name) buf_size = GetShortPathNameW(long_path, None, 0) # FIX: https://github.com/hsoft/send2trash/issues/31 # If buffer size is zero, an error has occurred. if not buf_size: err_no = GetLastError() raise WindowsError(err_no, FormatError(err_no), long_path) output = create_unicode_buffer(buf_size) GetShortPathNameW(long_path, output, buf_size) return get_awaited_path_from_prefix(prefix, output.value)
def get_short_path_name(long_name): if not long_name.startswith('\\\\?\\'): long_name = '\\\\?\\' + long_name buf_size = GetShortPathNameW(long_name, None, 0) # FIX: https://github.com/hsoft/send2trash/issues/31 # If buffer size is zero, an error has occurred. if not buf_size: err_no = GetLastError() raise WindowsError(err_no, FormatError(err_no), long_name[4:]) output = create_unicode_buffer(buf_size) GetShortPathNameW(long_name, output, buf_size) return output
def VirtualQueryEx(self, lpAddress): if self._need_64(lpAddress): raise NotImplementedError() mbi = MEMORY_BASIC_INFORMATION() if not VirtualQueryEx(self.h_process, lpAddress, byref(mbi), sizeof(mbi)): raise ProcessException('Error VirtualQueryEx: 0x%X (%d)' % (lpAddress, GetLastError())) return mbi
def efi_test(): LPCTSTR = ctypes.c_char_p kernel32 = WinDLL('kernel32',use_last_error=False) GetFirmware = kernel32.GetFirmwareEnvironmentVariableA GetFirmware('',LPCTSTR('{00000000-0000-0000-0000-000000000000}'.encode('ascii')),None,0) error = GetLastError() if error == 1: #ERROR_INVALID_FUNCTION return 'legacy' elif error == 998: return 'EFI' else: return 'error_'+str(error)
def GetUserName(): from ctypes import windll, WinError, create_unicode_buffer, byref, c_uint32, GetLastError DWORD = c_uint32 nSize = DWORD(0) windll.secur32.GetUserNameExW(2, None, byref(nSize)) error = GetLastError() ERROR_INSUFFICIENT_BUFFER = 122 ERROR_MORE_DATA_AVAILABLE = 234 if error not in (ERROR_INSUFFICIENT_BUFFER, ERROR_MORE_DATA_AVAILABLE): raise WinError(error) lpBuffer = create_unicode_buffer('', nSize.value + 1) nSize = DWORD(nSize.value + 1) success = windll.secur32.GetUserNameExW(2, lpBuffer, byref(nSize)) if not success: raise WinError(GetLastError()) return lpBuffer.value
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
def unregister_hotkey(self, wid, keys): mods, kc = keys_from_string(keys) key_index = kc << 16 | mods self.__keybinds.pop(key_index) self.__keygrabs.pop(key_index) if not self.UnregisterHotKey(c_int(wid), key_index): err = "Couldn't unregister hot key '{0}'. Error code = {1}."\ .format(keys, GetLastError()) print(err) return False return True
def Module32First(hSnapshot): _Module32First = windll.kernel32.Module32First _Module32First.argtypes = [HANDLE, LPMODULEENTRY32] _Module32First.restype = bool me = MODULEENTRY32() me.dwSize = sizeof(MODULEENTRY32) success = _Module32First(hSnapshot, byref(me)) if not success: if GetLastError() == ERROR_NO_MORE_FILES: return None raise WinError() return me
def ensure_single_acolyte_instance(self): """Ensure that we are the only acolyte instance.""" if self._mutex is not None: return True name = b'acolyte-instance-lock-{4F0BE4F0-52F2-4A7F-BEAB-D02807303CBF}' self._mutex = winapi.CreateMutexA(None, False, name) if self._mutex is None: raise WinError() if GetLastError() == ERROR_ALREADY_EXISTS: self.release_acolyte_instance_lock() return False self._has_acolyte_lock = True return True