# Buggy code
def __init__(self, protocol, *args):
    self.protocol = protocol
    self.args = list(args)
    self.environ = self.protocol.cmdstack[0].environ
    self.fs = self.protocol.fs
    self.data = None  # output data
    self.input_data = None  # used to store STDIN data passed via PIPE
    self.writefn = self.protocol.pp.outReceived
    self.errorWritefn = self.protocol.pp.errReceived
    # MS-DOS style redirect handling, inside the command
    # TODO: handle >>, 2>, etc
    if ">" in self.args or ">>" in self.args:
        self.writtenBytes = 0
        self.writefn = self.write_to_file
        if ">>" in self.args:
            index = self.args.index(">>")
            b_append = True
        else:
            index = self.args.index(">")
            b_append = False
        self.outfile = self.fs.resolve_path(
            str(self.args[(index + 1)]), self.protocol.cwd
        )
        del self.args[index:]
        p = self.fs.getfile(self.outfile)
        if (
            not p
            or not p[fs.A_REALFILE]
            or p[fs.A_REALFILE].startswith("honeyfs")
            or not b_append
        ):
            tmp_fname = "%s-%s-%s-redir_%s" % (
                time.strftime("%Y%m%d-%H%M%S"),
                self.protocol.getProtoTransport().transportId,
                self.protocol.terminal.transport.session.id,
                re.sub("[^A-Za-z0-9]", "_", self.outfile),
            )
            self.safeoutfile = os.path.join(
                CowrieConfig().get("honeypot", "download_path"), tmp_fname
            )
            perm = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            try:
                self.fs.mkfile(self.outfile, 0, 0, 0, stat.S_IFREG | perm)
            except fs.FileNotFound:
                # The outfile locates at a non-existing directory.
                self.errorWrite("-bash: %s: No such file or directory\n" % self.outfile)
                self.writefn = self.write_to_failed
                self.outfile = None
                self.safeoutfile = None
            except fs.PermissionDenied:
                # The outfile locates in a file-system that doesn't allow file creation
                self.errorWrite("-bash: %s: Permission denied\n" % self.outfile)
                self.writefn = self.write_to_failed
                self.outfile = None
                self.safeoutfile = None

            else:
                with open(self.safeoutfile, "ab"):
                    self.fs.update_realfile(
                        self.fs.getfile(self.outfile), self.safeoutfile
                    )
        else:
            self.safeoutfile = p[fs.A_REALFILE]


# Traceback (exceptions.IndexError)
2018-08-13T09:46:46.286838+0300 [CowrieTelnetTransport,68,[redacted]] login attempt [root/] succeeded
2018-08-13T09:46:46.289616+0300 [CowrieTelnetTransport,68,[redacted]] Initialized emulated server as architecture: linux-x64-lsb
2018-08-13T09:46:46.981872+0300 [CowrieTelnetTransport,68,[redacted]] Warning: state changed and new state returned
2018-08-13T09:46:59.394970+0300 [CowrieTelnetTransport,68,[redacted]] CMD: >/dev/netslink/.t &amp;&amp; cd /dev/netslink/ &amp;&amp; for a in `ls -a /dev/netslink/`; do >$a; done; >retrieve
2018-08-13T09:46:59.397926+0300 [CowrieTelnetTransport,68,[redacted]] Command found: > /dev/netslink/.t
2018-08-13T09:46:59.398837+0300 [CowrieTelnetTransport,68,[redacted]] Command found: cd /dev/netslink/
2018-08-13T09:46:59.400542+0300 [CowrieTelnetTransport,68,[redacted]] Can't find command None
2018-08-13T09:46:59.400790+0300 [CowrieTelnetTransport,68,[redacted]] Command not found: for a in ` ls -a /dev/netslink/ `
2018-08-13T09:46:59.404197+0300 [CowrieTelnetTransport,68,[redacted]] Command found: do >
2018-08-13T09:46:59.404647+0300 [CowrieTelnetTransport,68,[redacted]] Unhandled Error
Traceback (most recent call last):
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/python/log.py", line 103, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/python/log.py", line 86, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/python/context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/python/context.py", line 85, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
why = selectable.doRead()
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/internet/tcp.py", line 243, in doRead
return self._dataReceived(data)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/internet/tcp.py", line 249, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/telnet.py", line 636, in dataReceived
self.applicationDataReceived(b''.join(appDataBuffer))
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/telnet.py", line 988, in applicationDataReceived
self.protocol.dataReceived(data)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/telnet.py", line 1035, in dataReceived
self.protocol.dataReceived(data)
File "/home/cowrie/cowrie/src/cowrie/insults/insults.py", line 107, in dataReceived
insults.ServerProtocol.dataReceived(self, data)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/insults/insults.py", line 537, in dataReceived
self.terminalProtocol.keystrokeReceived(ch, None)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/recvline.py", line 225, in keystrokeReceived
m()
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 324, in handle_RETURN
return recvline.RecvLine.handle_RETURN(self)
File "/home/cowrie/cowrie/cowrie-env/lib/python2.7/site-packages/twisted/conch/recvline.py", line 292, in handle_RETURN
self.lineReceived(line)
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 183, in lineReceived
self.cmdstack[-1].lineReceived(line)
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 104, in lineReceived
self.runCommand()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 213, in runCommand
self.protocol.call_command(pp, cmdclass, *cmd_array[0]['rargs'])
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 305, in call_command
HoneyPotBaseProtocol.call_command(self, pp, cmd, *args)
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 192, in call_command
obj.start()
File "/home/cowrie/cowrie/src/cowrie/shell/command.py", line 122, in start
self.exit()
File "/home/cowrie/cowrie/src/cowrie/shell/command.py", line 140, in exit
self.protocol.cmdstack[-1].resume()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 218, in resume
self.runCommand()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 213, in runCommand
self.protocol.call_command(pp, cmdclass, *cmd_array[0]['rargs'])
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 305, in call_command
HoneyPotBaseProtocol.call_command(self, pp, cmd, *args)
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 192, in call_command
obj.start()
File "/home/cowrie/cowrie/src/cowrie/shell/command.py", line 122, in start
self.exit()
File "/home/cowrie/cowrie/src/cowrie/shell/command.py", line 140, in exit
self.protocol.cmdstack[-1].resume()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 218, in resume
self.runCommand()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 211, in runCommand
runOrPrompt()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 113, in runOrPrompt
self.runCommand()
File "/home/cowrie/cowrie/src/cowrie/shell/honeypot.py", line 213, in runCommand
self.protocol.call_command(pp, cmdclass, *cmd_array[0]['rargs'])
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 305, in call_command
HoneyPotBaseProtocol.call_command(self, pp, cmd, *args)
File "/home/cowrie/cowrie/src/cowrie/shell/protocol.py", line 189, in call_command
obj = cmd(self, *args)
File "/home/cowrie/cowrie/src/cowrie/shell/command.py", line 53, in __init__
self.outfile = self.fs.resolve_path(str(self.args[(index + 1)]), self.protocol.cwd)
exceptions.IndexError: list index out of range
2018-08-13T09:46:59.408466+0300 [CowrieTelnetTransport,[redacted]] Duplicate TTY log with hash 0c58d3d66a63aeca0c3e68d928a26ff686d1e08f0d1c70fca45d0ed955cf833f
2018-08-13T09:46:59.408836+0300 [CowrieTelnetTransport,68,[redacted]] Closing TTY Log: log/tty/0c58d3d66a63aeca0c3e68d928a26ff686d1e08f0d1c70fca45d0ed955cf833f after 12 seconds
2018-08-13T09:46:59.411186+0300 [CowrieTelnetTransport,68,[redacted]] Connection lost after 47 seconds

# Fixed code
def __init__(self, protocol, *args):
    self.protocol = protocol
    self.args = list(args)
    self.environ = self.protocol.cmdstack[0].environ
    self.fs = self.protocol.fs
    self.data = None  # output data
    self.input_data = None  # used to store STDIN data passed via PIPE
    self.writefn = self.protocol.pp.outReceived
    self.errorWritefn = self.protocol.pp.errReceived
    # MS-DOS style redirect handling, inside the command
    # TODO: handle >>, 2>, etc
    if ">" in self.args or ">>" in self.args:
        if self.args[-1] in [">", ">>"]:
            self.errorWrite("-bash: parse error near '\\n' \n")
            return
        self.writtenBytes = 0
        self.writefn = self.write_to_file
        if ">>" in self.args:
            index = self.args.index(">>")
            b_append = True
        else:
            index = self.args.index(">")
            b_append = False
        self.outfile = self.fs.resolve_path(
            str(self.args[(index + 1)]), self.protocol.cwd
        )
        del self.args[index:]
        p = self.fs.getfile(self.outfile)
        if (
            not p
            or not p[fs.A_REALFILE]
            or p[fs.A_REALFILE].startswith("honeyfs")
            or not b_append
        ):
            tmp_fname = "%s-%s-%s-redir_%s" % (
                time.strftime("%Y%m%d-%H%M%S"),
                self.protocol.getProtoTransport().transportId,
                self.protocol.terminal.transport.session.id,
                re.sub("[^A-Za-z0-9]", "_", self.outfile),
            )
            self.safeoutfile = os.path.join(
                CowrieConfig().get("honeypot", "download_path"), tmp_fname
            )
            perm = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            try:
                self.fs.mkfile(self.outfile, 0, 0, 0, stat.S_IFREG | perm)
            except fs.FileNotFound:
                # The outfile locates at a non-existing directory.
                self.errorWrite("-bash: %s: No such file or directory\n" % self.outfile)
                self.writefn = self.write_to_failed
                self.outfile = None
                self.safeoutfile = None
            except fs.PermissionDenied:
                # The outfile locates in a file-system that doesn't allow file creation
                self.errorWrite("-bash: %s: Permission denied\n" % self.outfile)
                self.writefn = self.write_to_failed
                self.outfile = None
                self.safeoutfile = None

            else:
                with open(self.safeoutfile, "ab"):
                    self.fs.update_realfile(
                        self.fs.getfile(self.outfile), self.safeoutfile
                    )
        else:
            self.safeoutfile = p[fs.A_REALFILE]