def StatusCheckLoop(self): hComm = self.hFile waitingOnStatusHandle = False dwCommEvent = DWORD() dwOvRes = DWORD() commMask = ( EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING | EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY ) if not SetCommMask(self.hFile, commMask): raise SerialError("error setting communications mask") osStatus = OVERLAPPED(0) osStatus.hEvent = CreateEvent(None, 1, 0, None) if not osStatus.hEvent: raise SerialError("error creating event") while True: # Issue a status event check if one hasn't been issued already. if not waitingOnStatusHandle: if WaitCommEvent(hComm, byref(dwCommEvent), byref(osStatus)): # WaitCommEvent returned immediately. # Deal with status event as appropriate. self.ReportStatusEvent(dwCommEvent.value) else: if GetLastError() == ERROR_IO_PENDING: waitingOnStatusHandle = True else: raise SerialError("error in WaitCommEvent") # Check on overlapped operation if waitingOnStatusHandle: # Wait a little while for an event to occur. res = WaitForSingleObject(osStatus.hEvent, 1000) if res == WAIT_OBJECT_0: if GetOverlappedResult( hComm, byref(osStatus), byref(dwOvRes), 0 ): # Status event is stored in the event flag # specified in the original WaitCommEvent call. # Deal with the status event as appropriate. self.ReportStatusEvent(dwCommEvent.value) else: # An error occurred in the overlapped operation; # call GetLastError to find out what it was # and abort if it is fatal. raise SerialError() # Set waitingOnStatusHandle flag to indicate that a new # WaitCommEvent is to be issued. waitingOnStatusHandle = True elif res == WAIT_TIMEOUT: print "timeout" else: # This indicates a problem with the OVERLAPPED structure's # event handle. CloseHandle(osStatus.hEvent) raise SerialError("error in the WaitForSingleObject") CloseHandle(osStatus.hEvent)
def run(self): WaitForSingleObject(self.processInformation.hProcess, INFINITE) exitCode = DWORD() if not GetExitCodeProcess( self.processInformation.hProcess, byref(exitCode) ): raise self.Exception(FormatError()) CloseHandle(self.processInformation.hProcess) if hasattr(self.processInformation, "hThread"): CloseHandle(self.processInformation.hThread) if self.pld: try: data = code_open(self.filename, 'r', self.cp) lines = data.readlines() returnValue = "".join(lines) data.close() remove(self.filename) except: returnValue = "" eg.TriggerEvent( self.suffix, prefix = self.prefix, payload = returnValue.rstrip() ) else: eg.TriggerEvent(self.suffix, prefix = self.prefix)
def run(self): WaitForSingleObject(self.processInformation.hProcess, INFINITE) exitCode = DWORD() if not GetExitCodeProcess(self.processInformation.hProcess, byref(exitCode)): raise self.Exception(FormatError()) CloseHandle(self.processInformation.hProcess) CloseHandle(self.processInformation.hThread) eg.TriggerEvent(self.suffix, prefix=self.prefix)
def ThreadLoop(self, startupEvent): try: hDir = CreateFile( self.path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, 0) if hDir == INVALID_HANDLE_VALUE: self.startException = FormatError() startupEvent.set() return overlapped = OVERLAPPED() overlapped.hEvent = CreateEvent(None, 1, 0, None) buffer = (c_byte * BUFSIZE)() events = (HANDLE * 2)(overlapped.hEvent, self.stopEvent) flags = (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SECURITY) includeSubdirs = self.includeSubdirs renamePath = None bytesReturned = DWORD() noneCallback = cast(None, LPOVERLAPPED_COMPLETION_ROUTINE) startupEvent.set() while 1: ReadDirectoryChangesW(hDir, buffer, BUFSIZE, includeSubdirs, flags, byref(bytesReturned), byref(overlapped), noneCallback) rc = MsgWaitForMultipleObjects(2, events, 0, INFINITE, QS_ALLINPUT) if rc == WAIT_OBJECT_0: res = GetOverlappedResult(hDir, byref(overlapped), byref(bytesReturned), 1) address = addressof(buffer) while True: fni = FILE_NOTIFY_INFORMATION.from_address(address) length = fni.FileNameLength / WCHAR_SIZE fileName = wstring_at(address + 12, length) action = fni.Action fullFilename = os.path.join(self.path, fileName) if action == FILE_ACTION_ADDED: self.TriggerEvent("Created", (fullFilename, )) elif action == FILE_ACTION_REMOVED: self.TriggerEvent("Deleted", (fullFilename, )) elif action == FILE_ACTION_MODIFIED: self.TriggerEvent("Updated", (fullFilename, )) elif action == FILE_ACTION_RENAMED_OLD_NAME: renamePath = fullFilename elif action == FILE_ACTION_RENAMED_NEW_NAME: self.TriggerEvent("Renamed", (renamePath, fullFilename)) renamePath = None if fni.NextEntryOffset == 0: break address += fni.NextEntryOffset elif rc == WAIT_OBJECT_0 + 1: break CloseHandle(hDir) except: self.thread = None raise
def __call__(self, hwnd, keystrokeString, useAlternateMethod=False, mode=2): keyData = ParseText(keystrokeString) if keyData: needGetFocus = False sendToFront = False if hwnd is None: sendToFront = True hwnd = GetForegroundWindow() needGetFocus = True dwProcessId = DWORD() threadID = GetWindowThreadProcessId(hwnd, byref(dwProcessId)) processID = dwProcessId.value ourThreadID = GetCurrentThreadId() # If not, attach our thread's 'input' to the foreground thread's if threadID != ourThreadID: AttachThreadInput(threadID, ourThreadID, True) if needGetFocus: hwnd = GetFocus() if not sendToFront: if GetGUIThreadInfo(0, byref(self.guiTreadInfo)): sendToFront = (self.guiTreadInfo.hwndFocus == hwnd) else: sendToFront = False if not hwnd: hwnd = None self.procHandle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, processID) #self.WaitForInputProcessed() oldKeyboardState = PBYTE256() GetKeyboardState(byref(oldKeyboardState)) keyData = ParseText(keystrokeString) if sendToFront and not useAlternateMethod: self.SendRawCodes1(keyData, mode) else: self.SendRawCodes2(keyData, hwnd, mode) SetKeyboardState(byref(oldKeyboardState)) self.WaitForInputProcessed() if threadID != ourThreadID: AttachThreadInput(threadID, ourThreadID, False) if self.procHandle: CloseHandle(self.procHandle)
def __call__( self, pathname='', arguments='', winState=0, waitForCompletion=False, priority=2, workingDir="", triggerEvent=False, disableWOW64=False, ): returnValue = None pathname = eg.ParseString(pathname) if not workingDir: workingDir = dirname(abspath(pathname)) arguments = eg.ParseString(arguments) commandLine = create_unicode_buffer('"%s" %s' % (pathname, arguments)) startupInfo = STARTUPINFO() startupInfo.cb = sizeof(STARTUPINFO) startupInfo.dwFlags = STARTF_USESHOWWINDOW startupInfo.wShowWindow = WINSTATE_FLAGS[winState] priorityFlag = PRIORITY_FLAGS[priority] processInformation = self.processInformation = PROCESS_INFORMATION() disableWOW64 = disableWOW64 and IsWin64() if disableWOW64: prevVal = Wow64DisableWow64FsRedirection() res = CreateProcess( None, # lpApplicationName commandLine, # lpCommandLine None, # lpProcessAttributes None, # lpThreadAttributes False, # bInheritHandles priorityFlag | CREATE_NEW_CONSOLE, # dwCreationFlags None, # lpEnvironment workingDir, # lpCurrentDirectory startupInfo, # lpStartupInfo processInformation # lpProcessInformation ) if disableWOW64: Wow64RevertWow64FsRedirection(prevVal) suffix = "%s.%s" % (self.text.eventSuffix, splitext( split(pathname)[1])[0]) prefix = self.plugin.name.replace(' ', '') if res == 0: raise self.Exception(FormatError()) if winState != 3 and PluginIsEnabled("Task"): def callback(dummyHwnd, dummyMesg, wParam, lParam): pids = GetPids(hwnd=lParam) pid = pids[0] if pids else False if pid == processInformation.dwProcessId: try: eg.messageReceiver.RemoveHandler( WM_SHELLHOOKMESSAGE, refCallback) except: pass sleep(0.3) # Wait for windows to appear hwnds = GetHwnds(pid=processInformation.dwProcessId) if hwnds: #print "Focused via GetHwnds" for hwnd in hwnds: if IsWindowVisible(hwnd): BringHwndToFront(hwnd) break elif IsWindowVisible(lParam): #print "Focused via ShellHook" BringHwndToFront(lParam) elif not ProcessExists(processInformation.dwProcessId): try: eg.messageReceiver.RemoveHandler( WM_SHELLHOOKMESSAGE, refCallback) except: pass try: eg.plugins.Window.FindWindow(basename(pathname)) if len(eg.lastFoundWindows): #print "Focused via FindWindow" BringHwndToFront(eg.lastFoundWindows[0]) except: pass refCallback = callback WM_SHELLHOOKMESSAGE = RegisterWindowMessage("SHELLHOOK") eg.messageReceiver.AddHandler(WM_SHELLHOOKMESSAGE, callback) if waitForCompletion: WaitForSingleObject(processInformation.hProcess, INFINITE) exitCode = DWORD() if not GetExitCodeProcess(processInformation.hProcess, byref(exitCode)): raise self.Exception(FormatError()) returnValue = exitCode.value if triggerEvent: eg.TriggerEvent(suffix, prefix=prefix) CloseHandle(processInformation.hProcess) CloseHandle(processInformation.hThread) return returnValue elif triggerEvent: te = self.TriggerEvent(processInformation, suffix, prefix) te.start() else: CloseHandle(processInformation.hProcess) CloseHandle(processInformation.hThread)
def __call__( self, command='', waitForCompletion=True, triggerEvent=False, additionalSuffix="", disableParsingCommand=True, disableParsingAdditionalSuffix=True, payload=False, disableWOW64=False, runAsAdmin=False, ): if eg.config.refreshEnv: eg.Environment.Refresh() prefix = self.plugin.info.eventPrefix suffix = self.text.eventSuffix if additionalSuffix != "": suffix = "%s.%s" % (suffix, additionalSuffix) if not disableParsingCommand: command = eg.ParseString(command) if not disableParsingAdditionalSuffix: additionalSuffix = eg.ParseString(additionalSuffix) processInformation = self.processInformation = SHELLEXECUTEINFO() processInformation.cbSize = sizeof(processInformation) processInformation.hwnd = 0 processInformation.lpFile = 'cmd.exe' if waitForCompletion or triggerEvent: si = STARTUPINFO() si.dwFlags |= STARTF_USESHOWWINDOW proc = popen("chcp", si) # DOS console codepage data = proc.communicate()[0] if not proc.returncode: cp = "cp" + data.split()[-1].replace(".", "") proc.stdout.close() filename = join(eg.folderPath.TemporaryFiles, "EventGhost-output-%s.txt" % ttime()) processInformation.lpParameters = '/S/C "%s" > %s' % (command, filename) processInformation.fMask = SEE_MASK_NOCLOSEPROCESS else: processInformation.lpParameters = '/S/C "%s"' % command if runAsAdmin: processInformation.lpVerb = "runas" processInformation.nShow = 0 processInformation.hInstApp = 0 disableWOW64 = disableWOW64 and IsWin64() if disableWOW64: prevVal = Wow64DisableWow64FsRedirection() if not windll.shell32.ShellExecuteExW(byref(processInformation)): raise self.Exception(FormatError()) if disableWOW64: Wow64RevertWow64FsRedirection(prevVal) if waitForCompletion: WaitForSingleObject(processInformation.hProcess, INFINITE) exitCode = DWORD() if not GetExitCodeProcess(processInformation.hProcess, byref(exitCode)): raise self.Exception(FormatError()) try: data = code_open(filename, 'r', cp) lines = data.readlines() returnValue = "".join(lines) data.close() remove(filename) except: returnValue = "" if triggerEvent: if payload: eg.TriggerEvent(suffix, prefix=prefix, payload=returnValue.rstrip()) else: eg.TriggerEvent(suffix, prefix=prefix) CloseHandle(processInformation.hProcess) return returnValue.rstrip() elif triggerEvent: te = self.TriggerEvent(processInformation, suffix, prefix, filename, cp, payload) te.start() else: CloseHandle(processInformation.hProcess)
def __call__( self, pathname='', arguments='', winState=0, waitForCompletion=False, priority=2, workingDir="", triggerEvent=False, disableWOW64=False, additionalSuffix="", disableParsingPathname=False, disableParsingArguments=False, disableParsingAdditionalSuffix=False, runAsAdmin=False, ): if eg.config.refreshEnv: eg.Environment.Refresh() returnValue = None pathname = expandvars(pathname) arguments = expandvars(arguments) workingDir = expandvars(workingDir) if not disableParsingPathname: pathname = eg.ParseString(pathname) if not disableParsingArguments: arguments = eg.ParseString(arguments) if not disableParsingAdditionalSuffix: additionalSuffix = eg.ParseString(additionalSuffix) if not workingDir: workingDir = dirname(abspath(pathname)) processInformation = self.processInformation = SHELLEXECUTEINFO() processInformation.cbSize = sizeof(processInformation) processInformation.hwnd = 0 processInformation.lpFile = pathname processInformation.lpParameters = arguments processInformation.lpDirectory = workingDir processInformation.nShow = WINSTATE_FLAGS[winState] processInformation.hInstApp = 0 processInformation.fMask = SEE_MASK_NOCLOSEPROCESS if runAsAdmin: processInformation.lpVerb = "runas" disableWOW64 = disableWOW64 and IsWin64() if disableWOW64: prevVal = Wow64DisableWow64FsRedirection() activeThread = GetWindowThreadProcessId(GetForegroundWindow(), None) currentThread = GetCurrentThreadId() attached = AttachThreadInput(currentThread, activeThread, True) if not windll.shell32.ShellExecuteExW(byref(processInformation)): raise self.Exception(FormatError()) if attached: AttachThreadInput(currentThread, activeThread, False) if disableWOW64: Wow64RevertWow64FsRedirection(prevVal) if priority != 2: try: SetPriorityClass(processInformation.hProcess, PRIORITY_FLAGS[priority]) priorityClass = GetPriorityClass(processInformation.hProcess) if priorityClass != PRIORITY_FLAGS[priority]: raise except: pid = windll.kernel32.GetProcessId(processInformation.hProcess) pi = SHELLEXECUTEINFO() pi.cbSize = sizeof(pi) pi.lpFile = r"C:\Windows\System32\wbem\wmic.exe" pi.lpParameters = ( "process where processid=%d CALL setpriority %d" % (pid, PRIORITY_FLAGS[priority])) pi.lpVerb = "runas" if not windll.shell32.ShellExecuteExW(byref(pi)): eg.PrintError(self.text.priorityIssue) suffix = "%s.%s" % (self.text.eventSuffix, splitext( split(pathname)[1])[0]) if additionalSuffix != "": suffix = suffix + "." + additionalSuffix prefix = self.plugin.name.replace(' ', '') if waitForCompletion: WaitForSingleObject(processInformation.hProcess, INFINITE) exitCode = DWORD() if not GetExitCodeProcess(processInformation.hProcess, byref(exitCode)): raise self.Exception(FormatError()) returnValue = exitCode.value if triggerEvent: eg.TriggerEvent(suffix, prefix=prefix) CloseHandle(processInformation.hProcess) return returnValue elif triggerEvent: te = self.TriggerEvent(processInformation, suffix, prefix) te.start() else: CloseHandle(processInformation.hProcess)