def runCommand(self): """ """ def runOrPrompt(): if len(self.cmdpending): self.runCommand() elif self.interactive: self.showPrompt() else: ret = failure.Failure(error.ProcessDone(status="")) self.protocol.terminal.transport.processEnded(ret) if not len(self.cmdpending): if self.interactive: self.showPrompt() else: ret = failure.Failure(error.ProcessDone(status="")) self.protocol.terminal.transport.processEnded(ret) return cmdAndArgs = self.cmdpending.pop(0) cmd2 = copy.copy(cmdAndArgs) # Probably no reason to be this comprehensive for just PATH... environ = copy.copy(self.environ) cmd = None while len(cmdAndArgs): piece = cmdAndArgs.pop(0) if piece.count('='): key, value = piece.split('=', 1) environ[key] = value continue cmd = piece break args = cmdAndArgs if not cmd: runOrPrompt() return rargs = [] for arg in args: matches = self.protocol.fs.resolve_path_wc(arg, self.protocol.cwd) if matches: rargs.extend(matches) else: rargs.append(arg) cmdclass = self.protocol.getCommand(cmd, environ['PATH'].split(':')) if cmdclass: log.msg(eventid='cowrie.command.success', input=' '.join(cmd2), format='Command found: %(input)s') self.protocol.call_command(cmdclass, *rargs) else: log.msg(eventid='cowrie.command.failed', input=' '.join(cmd2), format='Command not found: %(input)s') self.protocol.terminal.write('bash: %s: command not found\n' % (cmd, )) runOrPrompt()
def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'login', b'-p']]) pp.makeConnection(transport) self.assertEqual('pass\n', transport.msg) pp.outReceived('Enter password:\nTICKET_ID_GOES_HERE\n') so = error.ProcessDone(None) pp.processEnded(failure.Failure(so))
def exit(self) -> None: """ Sometimes client is disconnected and command exits after. So cmdstack is gone """ if ( self.protocol and self.protocol.terminal and hasattr(self, "safeoutfile") and self.safeoutfile ): if hasattr(self, "outfile") and self.outfile: self.protocol.terminal.redirFiles.add((self.safeoutfile, self.outfile)) else: self.protocol.terminal.redirFiles.add((self.safeoutfile, "")) if len(self.protocol.cmdstack): self.protocol.cmdstack.pop() if len(self.protocol.cmdstack): self.protocol.cmdstack[-1].resume() else: ret = failure.Failure(error.ProcessDone(status="")) # The session could be disconnected already, when his happens .transport is gone try: self.protocol.terminal.transport.processEnded(ret) except AttributeError: pass
def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'login', b'-p']]) pp.makeConnection(transport) self.assertEqual(b'pass\n', transport.msg) pp.outReceived(b'\xff\xff\xff\xff\xff') so = error.ProcessDone(None) pp.processEnded(failure.Failure(so))
def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'login']]) pp.makeConnection(transport) self.assertEqual(b'pass\n', transport.msg) pp.outReceived(b'Enter password:\n') pp.errReceived(b"Password invalid.\n") so = error.ProcessDone(status=1) pp.processEnded(failure.Failure(so))
def spawnProcess(pp, cmd, argv, env): self.assertEqual([cmd, argv], ['p4', [b'p4', b'-u', b'buildbot_user', b'login']]) pp.makeConnection(transport) self.assertEqual(b'pass\n', transport.msg) pp.outReceived(b'Enter password:\nUser buildbot_user logged in.\n') so = error.ProcessDone(None) pp.processEnded(failure.Failure(so))
def simulateProcessExit(self, clean=True): """Pretend the child process we're monitoring has exited.""" self.protocol.transport.exited = True if clean: exc = error.ProcessDone(None) else: exc = error.ProcessTerminated(exitCode=1) self.protocol.processEnded(failure.Failure(exc))
def test_process_success(self): fail = Failure(error.ProcessDone(None)) self.proto.processEnded(fail) self.assertFalse(self.proto.alive) self.assertEqual(len(self.dispatched), 1) self.assertIsInstance(self.dispatched[0], events.ServerStopped)
def connectionLost(self, reason=None): """Shut down resources.""" # Get the exit status and notify the protocol exitCode = win32process.GetExitCodeProcess(self.hProcess) if exitCode == 0: err = error.ProcessDone(exitCode) else: err = error.ProcessTerminated(exitCode) self.protocol.processEnded(failure.Failure(err))
def _getReason(self, status): # Copied from twisted.internet.process._BaseProcess exitCode = sig = None if os.WIFEXITED(status): exitCode = os.WEXITSTATUS(status) else: sig = os.WTERMSIG(status) if exitCode or sig: return error.ProcessTerminated(exitCode, sig, status) return error.ProcessDone(status)
def processEnded(self, status): """ This is called when the child terminates. """ self.pid = None if status == 0: err = error.ProcessDone(status) else: err = error.ProcessTerminated(status) self.protocol.processEnded(failure.Failure(err))
def checkWork(self): if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0: return 0 exitCode = win32process.GetExitCodeProcess(self.proc.hProcess) if exitCode == 0: err = error.ProcessDone(exitCode) else: err = error.ProcessTerminated(exitCode) self.deactivate() self.proc.protocol.processEnded(failure.Failure(err)) return 0
def setup_complete_no_errors(self, proto, config): todel = proto.to_delete self.assertTrue(len(todel) > 0) proto.processEnded(Failure(error.ProcessDone(0))) self.assertEqual(len(proto.to_delete), 0) for f in todel: self.assertTrue(not os.path.exists(f)) self.assertEqual(proto._timeout_delayed_call, None) ## make sure we set up the config to track the created tor ## protocol connection self.assertEquals(config.protocol, proto.tor_protocol)
def spawnProcess(pp, cmd, argv, path, usePTY, env): self.assertEqual([cmd, argv, path, usePTY, env], [exp_cmd, exp_argv, exp_path, exp_usePTY, exp_env]) for output in outputs: if output[0] == 'out': pp.outReceived(output[1]) elif output[0] == 'err': pp.errReceived(output[1]) elif output[0] == 'rc': if output[1] != 0: so = error.ProcessTerminated(exitCode=output[1]) else: so = error.ProcessDone(None) pp.processEnded(failure.Failure(so))
def test_quit_process(self): process = TorProcessProtocol(None) process.transport = Mock() d = process.quit() self.assertFalse(d.called) process.processExited(Failure(error.ProcessTerminated(exitCode=15))) self.assertTrue(d.called) process.processEnded(Failure(error.ProcessDone(None))) self.assertTrue(d.called) errs = self.flushLoggedErrors() self.assertEqual(1, len(errs)) self.assertTrue("Tor exited with error-code" in str(errs[0]))
def testChildDataReceived(self): self.mock.proto.childDataReceived(1, 'stdout bytes') self.mock.proto.childDataReceived(2, 'stderr bytes') self.mock.proto.childDataReceived(1, 'more stdout bytes') def cbProcessFinished((proto, status, output)): self.assertIdentical(proto, self.mock.proto) self.assertEquals(status, 0) self.assertEquals(output, [(1, 'stdout bytes'), (2, 'stderr bytes'), (1, 'more stdout bytes')]) self.spawnDeferred.addCallback(cbProcessFinished) self.mock.proto.processEnded(failure.Failure(error.ProcessDone(0))) return self.spawnDeferred
def test_protocol(self): """ Test that outReceived writes to AMP and that it triggers the finished deferred once the process ended. """ s = sio() sa = sio() ac = self._makeConnector(s, sa) for x in xrange(99): ac.childDataReceived(4, str(x)) ac.processEnded(failure.Failure(error.ProcessDone(0))) return ac.finished.addCallback(lambda _: self.assertEqual( sa.getvalue(), ''.join(str(x) for x in xrange(99))))
def test_quit_process_already(self): process = TorProcessProtocol(None) process.transport = Mock() def boom(sig): self.assertEqual(sig, 'TERM') raise error.ProcessExitedAlready() process.transport.signalProcess = Mock(side_effect=boom) d = process.quit() process.processEnded(Failure(error.ProcessDone(None))) self.assertTrue(d.called) errs = self.flushLoggedErrors() self.assertEqual(1, len(errs)) self.assertTrue("Tor exited with error-code" in str(errs[0]))
def exit(self): """ Sometimes client is disconnected and command exits after. So cmdstack is gone """ if self.protocol and self.protocol.terminal and hasattr(self, 'safeoutfile') and self.safeoutfile: if hasattr(self, 'outfile') and self.outfile: self.protocol.terminal.redirFiles.add((self.safeoutfile, self.outfile)) else: self.protocol.terminal.redirFiles.add((self.safeoutfile, '')) if self.protocol.cmdstack: self.protocol.cmdstack.pop() if len(self.protocol.cmdstack): self.protocol.cmdstack[-1].resume() else: ret = failure.Failure(error.ProcessDone(status="")) self.protocol.terminal.transport.processEnded(ret)