def CreatePipe(inherit_read=False, inherit_write=False): read, write = wintypes.HANDLE(), wintypes.HANDLE() kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0) if inherit_read: kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT, win32con.HANDLE_FLAG_INHERIT) if inherit_write: kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT, win32con.HANDLE_FLAG_INHERIT) return read.value, write.value
def run_safe_process(self, filename, arguments=None, wait=False, new_console=False): safer_level_handle = wintypes.HANDLE() ret_val = advapi32.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN, ctypes.byref(safer_level_handle), None) if not ret_val: raise Exception("SaferCreateLevel failed") token = wintypes.HANDLE() try: ret_val = advapi32.SaferComputeTokenFromLevel( safer_level_handle, None, ctypes.byref(token), 0, None) if not ret_val: raise Exception("SaferComputeTokenFromLevel failed") proc_info = Win32_PROCESS_INFORMATION() startup_info = Win32_STARTUPINFO_W() startup_info.cb = ctypes.sizeof(Win32_STARTUPINFO_W) startup_info.lpDesktop = "" flags = 0 if new_console: flags = CREATE_NEW_CONSOLE cmdline = ctypes.create_unicode_buffer('"%s" ' % filename + arguments) ret_val = advapi32.CreateProcessAsUserW(token, None, cmdline, None, None, False, flags, None, None, ctypes.byref(startup_info), ctypes.byref(proc_info)) if not ret_val: raise Exception("CreateProcessAsUserW failed") if wait and proc_info.hProcess: kernel32.WaitForSingleObject(proc_info.hProcess, INFINITE) if proc_info.hProcess: kernel32.CloseHandle(proc_info.hProcess) if proc_info.hThread: kernel32.CloseHandle(proc_info.hThread) finally: if token: kernel32.CloseHandle(token) advapi32.SaferCloseLevel(safer_level_handle)
def init(storage): import ctypes import ctypes.wintypes as wintypes class __PROCESS_INFORMATION(ctypes.Structure): """see: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684873(v=vs.85).aspx """ _fields_ = [ ("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE), ("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD), ] wintypes.PROCESS_INFORMATION = __PROCESS_INFORMATION pid = wintypes.PROCESS_INFORMATION().dwProcessId PROCESS_ALL_ACCESS = (0x000F0000L | 0x00100000L | 0xFFF) handle = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid) storage['process_pid'] = pid storage['process_handle'] = handle ModuleHandle = ctypes.windll.kernel32.GetModuleHandleA("kernel32.dll") LoadLibraryA = ctypes.windll.kernel32.GetProcAddress( wintypes.HANDLE(ModuleHandle), "LoadLibraryA", ) storage['LoadLibraryA'] = LoadLibraryA return True
def _validate_handle(self): if self._fhandle is None: raise Exception('No file handle') if self._fhandle.value == wintypes.HANDLE(INVALID_HANDLE_VALUE).value: error = windll.kernel32.GetLastError() raise Exception('Failed to open %s. GetLastError(): %d - %s' % (self.path, error, FormatError(error)))
def _validate_handle(self): if self._fhandle is None: raise Exception('No file handle') if self._fhandle.value == wintypes.HANDLE(INVALID_HANDLE_VALUE).value: self._fhandle = None raise Exception('Failed to open device %d. GetLastError(): %d' % (self.index, windll.kernel32.GetLastError()))
def get_modified_date(filename): # # File Open in Windows # # https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea CreateFileA = ctypes.windll.kernel32.CreateFileA file_handle = wt.HANDLE( CreateFileA(filename.encode(), 0x80000000, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0, None)) # print("FILE HANDLE",file_handle) # print("GET LAST ERROR",ctypes.GetLastError()) # # GET TIME # # https://msdn.microsoft.com/en-us/9baf8a0e-59e3-4fbd-9616-2ec9161520d1 #this is how to make a pointer. This is then <ctypes.wintypes.LP_FILETIME> object #I wish I knew what (ctypes.c_int*30)(100) meant. See if that can be figured out #it makes a pointer to be filled up by a windows API call (GetFileTime) file_time_struct_pointer = ctypes.cast((ctypes.c_int * 1)(1), ctypes.POINTER(wt.FILETIME)) GetFileTime = ctypes.windll.kernel32.GetFileTime #restype is the value that's returned # GetFileTime.restype = wt.BOOL #argtypes removes need to encapsulate arguments with Windows data types # GetFileTime.argtypes = [wt.HANDLE,wt.LPFILETIME] #restype & argtypes are both generally called to shorten the syntax #file_time_struct_pointer just gets filled up with correct values GetFileTime(file_handle, 0, 0, file_time_struct_pointer) # print("FILE STRUCT POINTER", file_time_struct_pointer.contents.dwLowDateTime) # print("GET LAST ERROR",ctypes.GetLastError()) # # CONVERT FILE STRUCT TO NORMAL TIME # # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724280(v=vs.85).aspx system_time_struct_pointer = ctypes.cast((ctypes.c_int * 1)(1), ctypes.POINTER(SYSTEMTIME)) FileTimeToSystemTime = ctypes.windll.kernel32.FileTimeToSystemTime #No argstype or restype needed FileTimeToSystemTime(file_time_struct_pointer, system_time_struct_pointer) # print(system_time_strugct_pointer.contents.wYear) # print("GET LAST ERROR",ctypes.GetLastError()) #Get Date_Time_Contents system_time_contents = system_time_struct_pointer.contents year = str(system_time_contents.wYear) month = str(system_time_contents.wMonth) day_of_week = str(system_time_contents.wDayOfWeek) day = str(system_time_contents.wDay) hour = str(system_time_contents.wHour) minute = str(system_time_contents.wMinute) second = str(system_time_contents.wSecond) milliseconds = str(system_time_contents.wMilliseconds) modified_date_string = lz(year) + lz(month) + lz(day) + '_' + lz( hour) + lz(minute) + lz(second) #CLOSE HANDLE # #Necessary for renaming and for preventing "Used By Another Program Errors" CloseHandle = ctypes.windll.kernel32.CloseHandle CloseHandle(file_handle) return modified_date_string
def wait_ipaddr_change(): if g_dll_handle is None: return hlib = g_dll_handle hand = wintypes.HANDLE() hand.value = 0 return hlib.NotifyAddrChange(byref(hand), 0)
def shutdown(msg, timeout, force=False, reboot=True): advapi32 = ctypes.windll.advapi32 kernel32 = ctypes.windll.kernel32 luid = LUID() if not advapi32.LookupPrivilegeValueA(None, SE_SHUTDOWN_NAME, byref(luid)): print 'LookupPrivilegeValueA failed.' attr = LUID_AND_ATTRIBUTES(luid, SE_PRIVILEGE_ENABLED) privilegeCount = 1 tokenPrivileges = TOKEN_PRIVILEGES(privilegeCount, attr) p = kernel32.GetCurrentProcess() hToken = wintypes.HANDLE() if not advapi32.OpenProcessToken(p, TOKEN_ADJUST_PRIVILEGES, byref(hToken)): print 'OpenProcessToken failed.' return False if not advapi32.AdjustTokenPrivileges( hToken, False, byref(tokenPrivileges), None, None, None): print 'AdjustTokenPrivileges failed.' return False if not advapi32.InitiateSystemShutdownA(host, msg, timeout, force, reboot): print 'InitiateSystemShutdownA failed.' return False return True
def wait_for_print_job_info(fields=DEFAULT_FIELDS, timeout=INFINITE, printer_name=None): if timeout != INFINITE: timeout = int(timeout * 1000) hPrinter = wintypes.HANDLE() fields = (wintypes.WORD * len(fields))(*fields) opt = PRINTER_NOTIFY_OPTIONS(pTypes=PRINTER_NOTIFY_OPTIONS_TYPE( Type=JOB_NOTIFY_TYPE, pFields=fields)) pinfo = PPRINTER_NOTIFY_INFO_GC() # note: GC subclass result = [] winspool.OpenPrinterW(printer_name, ctypes.byref(hPrinter), None) try: hChange = winspool.FindFirstPrinterChangeNotification( hPrinter, 0, 0, ctypes.byref(opt)) try: if (kernel32.WaitForSingleObject(hChange, timeout) != WAIT_OBJECT_0): return result winspool.FindNextPrinterChangeNotification(hChange, None, None, ctypes.byref(pinfo)) for data in pinfo[0].aData: if data.Type != JOB_NOTIFY_TYPE: continue nd = (data.Id, ) + data.NotifyData result.append(nd) return result finally: winspool.FindClosePrinterChangeNotification(hChange) finally: winspool.ClosePrinter(hPrinter)
def create_user_logon_session(self, username, password, domain='.', load_profile=True, logon_type=LOGON32_LOGON_INTERACTIVE): LOG.debug("Creating logon session for user: %(domain)s\\%(username)s", { "username": username, "domain": domain }) token = wintypes.HANDLE() ret_val = advapi32.LogonUserW(six.text_type(username), six.text_type(domain), six.text_type(password), logon_type, self.LOGON32_PROVIDER_DEFAULT, ctypes.byref(token)) if not ret_val: raise exception.WindowsCloudbaseInitException( "User logon failed: %r") if load_profile: pi = Win32_PROFILEINFO() pi.dwSize = ctypes.sizeof(Win32_PROFILEINFO) pi.lpUserName = six.text_type(username) ret_val = userenv.LoadUserProfileW(token, ctypes.byref(pi)) if not ret_val: kernel32.CloseHandle(token) raise exception.WindowsCloudbaseInitException( "Cannot load user profile: %r") return token
def convert_vhd(self, src, dest): src_device_id = self._get_device_id_by_path(src) dest_device_id = self._get_device_id_by_path(dest) vst = Win32_VIRTUAL_STORAGE_TYPE() vst.DeviceId = dest_device_id vst.VendorId = self._msft_vendor_id params = Win32_CREATE_VIRTUAL_DISK_PARAMETERS() params.Version = self.CREATE_VIRTUAL_DISK_VERSION_2 params.UniqueId = Win32_GUID() params.MaximumSize = 0 params.BlockSizeInBytes = self.CREATE_VHD_PARAMS_DEFAULT_BLOCK_SIZE params.SectorSizeInBytes = 0x200 params.PhysicalSectorSizeInBytes = 0x200 params.ParentPath = None params.SourcePath = src params.OpenFlags = self.OPEN_VIRTUAL_DISK_FLAG_NONE params.ParentVirtualStorageType = Win32_VIRTUAL_STORAGE_TYPE() params.SourceVirtualStorageType = Win32_VIRTUAL_STORAGE_TYPE() params.SourceVirtualStorageType.DeviceId = src_device_id params.SourceVirtualStorageType.VendorId = self._msft_vendor_id params.ResiliencyGuid = Win32_GUID() handle = wintypes.HANDLE() ret_val = virtdisk.CreateVirtualDisk( ctypes.byref(vst), ctypes.c_wchar_p(dest), self.VIRTUAL_DISK_ACCESS_NONE, None, self.CREATE_VIRTUAL_DISK_FLAG_NONE, 0, ctypes.byref(params), None, ctypes.byref(handle)) if ret_val: raise Exception("Virtual disk conversion failed with error: %s" % ret_val) self._close(handle)
def create_vhd(self, new_vhd_path, new_vhd_type, src_path=None, max_internal_size=0, parent_path=None): new_device_id = self._get_vhd_device_id(new_vhd_path) vst = vdisk_struct.Win32_VIRTUAL_STORAGE_TYPE(DeviceId=new_device_id) params = vdisk_struct.Win32_CREATE_VIRTUAL_DISK_PARAMETERS( MaximumSize=max_internal_size, ParentPath=parent_path, SourcePath=src_path) handle = wintypes.HANDLE() create_virtual_disk_flag = ( vdisk_const.CREATE_VIRTUAL_DISK_FLAGS.get(new_vhd_type)) self._run_and_check_output(virtdisk.CreateVirtualDisk, ctypes.byref(vst), ctypes.c_wchar_p(new_vhd_path), None, None, create_virtual_disk_flag, None, ctypes.byref(params), None, ctypes.byref(handle), cleanup_handle=handle)
def create_user_logon_session(self, username, password, domain='.', load_profile=True): token = wintypes.HANDLE() ret_val = advapi32.LogonUserW(six.text_type(username), six.text_type(domain), six.text_type(password), 2, 0, ctypes.byref(token)) if not ret_val: raise exception.WindowsCloudbaseInitException( "User logon failed: %r") if load_profile: pi = Win32_PROFILEINFO() pi.dwSize = ctypes.sizeof(Win32_PROFILEINFO) pi.lpUserName = six.text_type(username) ret_val = userenv.LoadUserProfileW(token, ctypes.byref(pi)) if not ret_val: kernel32.CloseHandle(token) raise exception.WindowsCloudbaseInitException( "Cannot load user profile: %r") return token
def control_privilege(privilege, status=None): """ Enable or disable certain security privilege Parameters ---------- privilege : str Privilege to get or remove. status : hexadecimal, optional Status of the privilege. It can either be 'SE_PRIVILEGE_ENABLED' to enable it or None (default) to disable it """ status = 0 if status is None else status hToken = wintypes.HANDLE() luid = Luid() tp = TokenPrivileges() advapi32.LookupPrivilegeValueW(None, privilege, ctypes.byref(luid)) tp.Privileges[0].Luid = luid tp.Privileges[0].Attributes = status advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), TOKEN_ALL_ACCESS, ctypes.byref(hToken)) try: advapi32.AdjustTokenPrivileges(hToken, False, ctypes.byref(tp), ctypes.sizeof(tp), None, None) if ctypes.get_last_error() == ERROR_NOT_ALL_ASSIGNED: raise ctypes.WinError(ERROR_NOT_ALL_ASSIGNED) finally: kernel32.CloseHandle(hToken)
def grant_debug_privilege(self, pid=0): """ grant SeDebugPrivilege to own process @param pid: Process id to set permissions of (or 0 if current) @type pid: int @return: True if operation was successful, False otherwise """ ADVAPI_32.OpenProcessToken.argtypes = (wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)) ADVAPI_32.LookupPrivilegeValueW.argtypes = (wintypes.LPWSTR, wintypes.LPWSTR, ctypes.POINTER( injector_defines.LUID)) ADVAPI_32.AdjustTokenPrivileges.argtypes = ( wintypes.HANDLE, wintypes.BOOL, ctypes.POINTER(injector_defines.TOKEN_PRIVILEGES), wintypes.DWORD, ctypes.POINTER(injector_defines.TOKEN_PRIVILEGES), ctypes.POINTER(wintypes.DWORD)) # local or remote process? if pid == 0: h_process = KERNEL_32.GetCurrentProcess() else: h_process = KERNEL_32.OpenProcess( injector_defines.PROCESS_ALL_ACCESS, False, pid) if not h_process: print("Failed to open process for setting debug privileges" % str(pid)) return False # obtain token to process h_current_token = wintypes.HANDLE() if not ADVAPI_32.OpenProcessToken( h_process, injector_defines.TOKEN_ALL_ACCESS, h_current_token): print("Did not obtain process token.") return False # look up current privilege value se_original_luid = injector_defines.LUID() if not ADVAPI_32.LookupPrivilegeValueW(None, "SeDebugPrivilege", se_original_luid): print("Failed to lookup privilege value.") return False luid_attributes = injector_defines.LUID_AND_ATTRIBUTES() luid_attributes.Luid = se_original_luid luid_attributes.Attributes = injector_defines.SE_PRIVILEGE_ENABLED token_privs = injector_defines.TOKEN_PRIVILEGES() token_privs.PrivilegeCount = 1 token_privs.Privileges = luid_attributes if not ADVAPI_32.AdjustTokenPrivileges(h_current_token, False, token_privs, 0, None, None): print("Failed to grant SE_DEBUG_PRIVILEGE to self.") return False KERNEL_32.CloseHandle(h_current_token) KERNEL_32.CloseHandle(h_process) return True
def main(): szCommand = "ping localhost" hPC = HPCON() hPipeIn = wintypes.HANDLE(INVALID_HANDLE_VALUE) hPipeOut = wintypes.HANDLE(INVALID_HANDLE_VALUE) CreatePseudoConsoleAndPipes(hPC, hPipeIn, hPipeOut) t3 = threading.Thread(target=lambda: pipeListener(hPipeIn)) t3.start() startupInfoEx = STARTUPINFOEX() startupInfoEx.StartupInfo.cb = sizeof(STARTUPINFOEX) mem = InitializeStartupInfoAttachedToPseudoConsole(startupInfoEx, hPC) lpProcessInformation = PROCESS_INFORMATION() CreateProcessW(None, # _In_opt_ LPCTSTR szCommand, # _Inout_opt_ LPTSTR None, # _In_opt_ LPSECURITY_ATTRIBUTES None, # _In_opt_ LPSECURITY_ATTRIBUTES False, # _In_ BOOL EXTENDED_STARTUPINFO_PRESENT, # _In_ DWORD None, # _In_opt_ LPVOID None, # _In_opt_ LPCTSTR byref(startupInfoEx.StartupInfo), # _In_ LPSTARTUPINFO byref(lpProcessInformation)) # _Out_ LPPROCESS_INFORMATION WaitForSingleObject(lpProcessInformation.hThread, 10 * 1000) sleep(0.5) CloseHandle(lpProcessInformation.hThread) CloseHandle(lpProcessInformation.hProcess) DeleteProcThreadAttributeList(startupInfoEx.lpAttributeList) HeapFree(GetProcessHeap(), 0, mem) ClosePseudoConsole(hPC) CancelIoEx(hPipeIn, null_ptr) CloseHandle(hPipeOut) CloseHandle(hPipeIn)
def create_user_logon_session(self, username, password, domain='.'): token = wintypes.HANDLE() ret_val = advapi32.LogonUserW(unicode(username), unicode(domain), unicode(password), 2, 0, ctypes.byref(token)) if not ret_val: raise LogonFailedException() return token
def get_process_token(): """ Get the current process token """ token = wintypes.HANDLE() res = process.OpenProcessToken(process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
def mem_is_allocated(addr): mbi_ctor = D.MEMORY_BASIC_INFORMATION if int(py_olly.get_backend_info()['bitness']) == 32 else D.MEMORY_BASIC_INFORMATION64 mbi = mbi_ctor() VirtualQueryEx = C.windll.kernel32.VirtualQueryEx h_process = wintypes.HANDLE(py_olly.get_hprocess()) queried = VirtualQueryEx(h_process, C.c_void_p(addr), C.byref(mbi), C.sizeof(mbi)) return queried > 0
def get_process_token(): "Get the current process token" token = wintypes.HANDLE() TOKEN_ALL_ACCESS = 0xf01ff res = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
def _touch_handler(self, msg, wParam, lParam): touches = (TOUCHINPUT * wParam)() windll.user32.GetTouchInputInfo(wintypes.HANDLE(lParam), wParam, pointer(touches), sizeof(TOUCHINPUT)) for i in xrange(wParam): self.touch_events.appendleft(touches[i]) return True
def StartThread(function): func = LPTHREAD_START_ROUTINE(function) threadID = wintypes.DWORD() handle = wintypes.HANDLE(windll.kernel32.CreateThread(None, 0, func, wintypes.LPVOID(0), 0, ctypes.byref(threadID))) if handle: windll.kernel32.WaitForSingleObject(handle, 1) return handle, threadID
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(), srchandle=kernel32.GetCurrentProcess(), htgt=kernel32.GetCurrentProcess(), access=0, inherit=False, options=win32con.DUPLICATE_SAME_ACCESS): tgthandle = wintypes.HANDLE() kernel32.DuplicateHandle(hsrc, srchandle, htgt, ctypes.byref(tgthandle), access, inherit, options) return tgthandle.value
def DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, desiredAccess, inheritHandle, options ): targetHandle = wintypes.HANDLE() ret = kernel32.DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, ctypes.byref(targetHandle), desiredAccess, inheritHandle, options) CheckError(ret, 'failed to duplicate handle') return Handle(targetHandle.value)
def CreatePseudoConsoleAndPipes(hPC, hPipeIn, hPipeOut): # // Create the pipes to which the ConPTY will connect hPipePTYIn = wintypes.HANDLE(INVALID_HANDLE_VALUE) hPipePTYOut = wintypes.HANDLE(INVALID_HANDLE_VALUE) CreatePipe(byref(hPipePTYIn), byref(hPipeOut), None, 0) CreatePipe(byref(hPipeIn), byref(hPipePTYOut), None, 0) # FIXME: this doesn't work if launched from PyCharm # hConsole = GetStdHandle(STD_OUTPUT_HANDLE) # None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None) # but this works hConsole = CreateFileW("CONOUT$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE, None, OPEN_EXISTING,0, None) consoleMode = DWORD() # print("consoleMode", consoleMode) GetConsoleMode(hConsole, byref(consoleMode)) # print("consoleMode", consoleMode) SetConsoleMode(hConsole, consoleMode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING) consoleSize = COORD() csbi = CONSOLE_SCREEN_BUFFER_INFO() GetConsoleScreenBufferInfo(hConsole, byref(csbi)) consoleSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1 consoleSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1 # consoleSize = COORD() # consoleSize.X = 80 # consoleSize.Y = 24 CreatePseudoConsole(consoleSize, hPipePTYIn, hPipePTYOut, DWORD(0), byref(hPC)) # dummy invocation, just to see, that function works # ResizePseudoConsole(hPC, consoleSize) CloseHandle(hPipePTYOut) CloseHandle(hPipePTYIn)
def largeBufferFill(self, xres, yres, numImages, events=None): numSegments = int(round(numImages / 15.0)) dwSize = wintypes.DWORD(2 * xres * yres) status = DWORD() buf = (c_ushort * xres * yres * 15 * numSegments)() if events is None: event1 = wintypes.HANDLE(5001) event2 = wintypes.HANDLE(5002) events = [event1, event2] ##Add first two segments: self.reAddBuffer(xres, yres, buf[0], 15, events[0]) self.reAddBuffer(xres, yres, buf[1], 15, events[1]) for i in range(2, numSegments): win32event.WaitForSingleObject(events[i % 2].value, 1000) self.reAddBuffer(xres, yres, buf[i], 15, events[i % 2]) return buf
def allocateBuffer(self, xres, yres, buffer_number, num_images=1): sBufNum = wintypes.SHORT(buffer_number) dwSize = wintypes.DWORD(2 * xres * yres * num_images) wBuffer = np.zeros((xres * yres * num_images), dtype=np.uint16) hEvent1 = wintypes.HANDLE() hEvent2 = pywintypes.HANDLE() # err = self.f_allocate(self.hcam, byref(sBufNum), dwSize, addressof(c_void_p(wBuffer.ctypes.data)), byref(hEvent1)) return (err, hEvent1, wBuffer)
def __init__(self): super().__init__() self._negotiated_version = wintypes.DWORD() self._client_handle = wintypes.HANDLE() wlanapi.WlanOpenHandle(wlanapi.CLIENT_VERSION_WINDOWS_VISTA_OR_LATER, None, byref(self._negotiated_version), byref(self._client_handle)) wlanapi.WlanRegisterNotification(self._client_handle, wlanapi.WLAN_NOTIFICATION_SOURCE_ACM, True, notifyHandler, None, None, None)
def safe_read_chunked_memory_region_as_one(base, size): mbi_ctor = D.MEMORY_BASIC_INFORMATION if int(py_olly.get_backend_info( )['bitness']) == 32 else D.MEMORY_BASIC_INFORMATION64 mbi = mbi_ctor() VirtualQueryEx = C.windll.kernel32.VirtualQueryEx VirtualProtectEx = C.windll.kernel32.VirtualProtectEx GetLastError = C.windll.kernel32.GetLastError GRANULARITY = 0x1000 h_process = wintypes.HANDLE( py_olly.get_hprocess()) # oa.Plugingetvalue(oa.VAL_HPROCESS)) try: rv = bytearray(size) except MemoryError: return guarded = list() gpoints = dict() protect = 0 queried = VirtualQueryEx(h_process, C.c_void_p(base), C.byref(mbi), C.sizeof(mbi)) if queried: protect = mbi.Protect else: print >> sys.stderr, 'safe_read_chunked_memory_region_as_one: VirtualQueryEx(ptr 0x%08X, size 0x%08X) failed, error: %u' %\ (base, C.sizeof(mbi), GetLastError()) if queried and mbi.Protect & D.PAGE_GUARD: g = {'ea': base, 'size': GRANULARITY, 'p': mbi.Protect} gpoints[base] = 0 ea = base while True: ea -= GRANULARITY if VirtualQueryEx(h_process, C.c_void_p(ea), C.byref(mbi), C.sizeof(mbi)) and\ (mbi.Protect & D.PAGE_GUARD) != 0 and g['p'] == mbi.Protect: g['ea'] -= GRANULARITY g['size'] += GRANULARITY else: break guarded.append(g) for i in long_xrange(base + GRANULARITY, base + size, GRANULARITY): p_addr = C.c_void_p(i) if VirtualQueryEx(h_process, p_addr, C.byref(mbi), C.sizeof(mbi)) and\ mbi.Protect & D.PAGE_GUARD: prevaddr = i - GRANULARITY if prevaddr in gpoints and guarded[ gpoints[prevaddr]]['p'] == mbi.Protect: idx = gpoints[prevaddr] else: guarded.append({'ea': i, 'size': 0L, 'p': mbi.Protect}) idx = len(guarded) - 1 guarded[idx]['size'] += GRANULARITY gpoints[i] = idx
def lsa_register_logon_process(logon_process_name): if not isinstance(logon_process_name, bytes): logon_process_name = logon_process_name.encode('mbcs') logon_process_name = logon_process_name[:127] buf = ctypes.create_string_buffer(logon_process_name, 128) name = STRING(len(logon_process_name), len(buf), buf) handle = wintypes.HANDLE() mode = LSA_OPERATIONAL_MODE() secur32.LsaRegisterLogonProcess(ctypes.byref(name), ctypes.byref(handle), ctypes.byref(mode)) return handle.value