Exemplo n.º 1
0
    def connectionMade(self):
        """
        Called when the connection is made from the other side.
        We send our version, but wait with sending KEXINIT
        """
        self.transportId = uuid.uuid4().hex[:12]
        src_ip = self.transport.getPeer().host

        ipv4_search = self.ipv4rex.search(src_ip)
        if ipv4_search is not None:
            src_ip = ipv4_search.group(1)

        log.msg(
            eventid='cowrie.session.connect',
            format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
            src_ip=src_ip,
            src_port=self.transport.getPeer().port,
            dst_ip=self.transport.getHost().host,
            dst_port=self.transport.getHost().port,
            session=self.transportId,
            sessionno='S{0}'.format(self.transport.sessionno),
            protocol='ssh'
        )

        self.transport.write('{0}\r\n'.format(self.ourVersionString).encode('ascii'))
        self.currentEncryptions = transport.SSHCiphers(b'none', b'none', b'none', b'none')
        self.currentEncryptions.setKeys(b'', b'', b'', b'', b'', b'')

        self.startTime = time.time()
        self.setTimeout(CONFIG.getint('honeypot', 'authentication_timeout', fallback=120))
Exemplo n.º 2
0
    def start(self):
        """
        """
        try:
            host = CONFIG.get('output_influx', 'host')
        except:
            host = ''

        try:
            port = CONFIG.getint('output_influx', 'port')
        except:
            port = 8086

        self.client = None
        try:
            self.client = InfluxDBClient(host=host, port=port)
        except InfluxDBClientError as e:
            log.err("output_influx: I/O error({0}): '{1}'".format(
                e.errno, e.strerror))
            return

        if self.client is None:
            log.err("output_influx: cannot instantiate client!")
            return

        if (CONFIG.has_option('output_influx', 'username') and
                CONFIG.has_option('output_influx', 'password')):
            username = CONFIG.get('output_influx', 'username')
            password = CONFIG.get('output_influx', 'password')
            self.client.switch_user(username, password)

        try:
            dbname = CONIFG.get('output_influx', 'database_name')
        else:
Exemplo n.º 3
0
    def connectionMade(self):
        """
        """
        pt = self.getProtoTransport()

        self.realClientIP = pt.transport.getPeer().host
        self.realClientPort = pt.transport.getPeer().port
        self.clientVersion = self.getClientVersion()
        self.logintime = time.time()

        try:
            timeout = CONFIG.getint('honeypot', 'interactive_timeout')
        except:
            timeout = 180
        self.setTimeout(timeout)

        # Source IP of client in user visible reports (can be fake or real)
        try:
            self.clientIP = CONFIG.get('honeypot', 'fake_addr')
        except:
            self.clientIP = self.realClientIP

        if CONFIG.has_option('honeypot', 'internet_facing_ip'):
            self.kippoIP = CONFIG.get('honeypot', 'internet_facing_ip')
        else:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(("8.8.8.8", 80))
                self.kippoIP = s.getsockname()[0]
            except:
                self.kippoIP = '192.168.0.1'
            finally:
                s.close()
Exemplo n.º 4
0
    def __init__(self):
        self.sessions = {}
        self.ttylogs = {}
        # FIXME figure out what needs to be done here regarding
        self.re_sessionlog = re.compile(
            r'.*HoneyPotSSHTransport,([0-9]+),[:a-f0-9.]+$')

        # cowrie.session.connect is special since it kicks off new logging session,
        # and is not handled here
        self.events = {
            'cowrie.login.success': self.handleLoginSucceeded,
            'cowrie.login.failed': self.handleLoginFailed,
            'cowrie.log.open': self.handleTTYLogOpened,
            'cowrie.command.success': self.handleCommand,
            'cowrie.command.failed': self.handleUnknownCommand,
            'cowrie.session.file_download': self.handleFileDownload,
            'cowrie.command.input': self.handleInput,
            'cowrie.client.version': self.handleClientVersion,
            'cowrie.client.size': self.handleTerminalSize,
            'cowrie.session.closed': self._connectionLost,
            'cowrie.log.closed': self.handleTTYLogClosed,
        }

        self.reported_ssh_port = None
        if CONFIG.has_option('honeypot', 'reported_ssh_port'):
            self.reported_ssh_port = CONFIG.getint('honeypot', 'reported_ssh_port')

        self.report_public_ip = False
        if CONFIG.has_option('honeypot', 'report_public_ip'):
            if CONFIG.getboolean('honeypot', 'report_public_ip') == True:
                self.report_public_ip = True
                import urllib
                self.public_ip = urllib.urlopen('http://myip.threatstream.com').readline()

        self.start()
Exemplo n.º 5
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)
        #self.__dict__['*****@*****.**'] = self.request_agent

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        log.msg("knownHosts = " + repr(self.knownHosts))

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except:
            self.password = None

        log.msg("host = " + self.host)
        log.msg("port = " + str(self.port))
        log.msg("user = " + self.user)

        self.client = ProxyClient(self)
Exemplo n.º 6
0
    def __init__(self):
        addr = CONFIG.get('output_socketlog', 'address')
        self.host = addr.split(':')[0]
        self.port = int(addr.split(':')[1])

        self.timeout = CONFIG.getint('output_socketlog', 'timeout')
        cowrie.core.output.Output.__init__(self)
Exemplo n.º 7
0
    def connectionMade(self):
        """
        """
        self.transportId = uuid.uuid4().hex[:12]
        sessionno = self.transport.sessionno

        self.startTime = time.time()
        try:
            self.setTimeout(CONFIG.getint('honeypot',
                                          'authentication_timeout'))
        except NoOptionError:
            self.setTimeout(120)

        log.msg(
            eventid='cowrie.session.connect',
            format=
            'New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]',
            src_ip=self.transport.getPeer().host,
            src_port=self.transport.getPeer().port,
            dst_ip=self.transport.getHost().host,
            dst_port=self.transport.getHost().port,
            session=self.transportId,
            sessionno='T{0}'.format(str(sessionno)),
            protocol='telnet')
        TelnetTransport.connectionMade(self)
Exemplo n.º 8
0
    def __init__(self):
        self.sessions = {}
        self.ttylogs = {}
        # FIXME figure out what needs to be done here regarding
        self.re_sessionlog = re.compile(
            r'.*HoneyPotSSHTransport,([0-9]+),[:a-f0-9.]+$')

        # cowrie.session.connect is special since it kicks off new logging session,
        # and is not handled here
        self.events = {
            'cowrie.login.success': self.handleLoginSucceeded,
            'cowrie.login.failed': self.handleLoginFailed,
            'cowrie.command.success': self.handleCommand,
            'cowrie.command.failed': self.handleUnknownCommand,
            'cowrie.session.file_download': self.handleFileDownload,
            'cowrie.command.input': self.handleInput,
            'cowrie.client.version': self.handleClientVersion,
            'cowrie.client.size': self.handleTerminalSize,
            'cowrie.session.closed': self._connectionLost,
            'cowrie.log.closed': self.handleTTYLogClosed,
        }

        self.reported_ssh_port = None
        if CONFIG.has_option('honeypot', 'reported_ssh_port'):
            self.reported_ssh_port = CONFIG.getint('honeypot', 'reported_ssh_port')

        self.report_public_ip = False
        if CONFIG.has_option('honeypot', 'report_public_ip'):
            if CONFIG.getboolean('honeypot', 'report_public_ip') == True:
                self.report_public_ip = True
                import urllib
                self.public_ip = urllib.urlopen('http://myip.threatstream.com').readline()

        self.start()
Exemplo n.º 9
0
    def start(self):
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CONFIG.has_option('output_hpfeeds', 'channel'):
            self.channel = CONFIG.get('output_hpfeeds', 'channel')

        if CONFIG.has_option('output_hpfeeds', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeeds', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeeds', 'server')
            port = CONFIG.getint('output_hpfeeds', 'port')

            if CONFIG.has_option('output_hpfeeds', 'tlscert'):
                with open(CONFIG.get('output_hpfeeds', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Exemplo n.º 10
0
    def connectionMade(self):
        """
        Called when the connection is made from the other side.
        We send our version, but wait with sending KEXINIT
        """
        self.transportId = uuid.uuid4().hex[:12]
        src_ip = self.transport.getPeer().host
        ipv4rex = re.compile(r'^::ffff:(\d+\.\d+\.\d+\.\d+)$')
        ipv4_search = ipv4rex.search(src_ip)
        if ipv4_search is not None:
            src_ip = ipv4_search.group(1)

        log.msg(
            eventid='cowrie.session.connect',
            format="New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]",
            src_ip=src_ip,
            src_port=self.transport.getPeer().port,
            dst_ip=self.transport.getHost().host,
            dst_port=self.transport.getHost().port,
            session=self.transportId,
            sessionno='S{0}'.format(self.transport.sessionno),
            protocol='ssh'
        )

        self.transport.write('{0}\r\n'.format(self.ourVersionString).encode('ascii'))
        self.currentEncryptions = transport.SSHCiphers(b'none', b'none', b'none', b'none')
        self.currentEncryptions.setKeys(b'', b'', b'', b'', b'', b'')

        self.startTime = time.time()
        try:
            self.setTimeout(CONFIG.getint('honeypot', 'authentication_timeout'))
        except NoOptionError:
            self.setTimeout(120)
Exemplo n.º 11
0
    def __init__(self, sftpserver, filename, flags, attrs):
        self.sftpserver = sftpserver
        self.filename = filename
        self.transfer_completed = 0
        self.bytesReceived = 0
        self.bytesReceivedLimit = CONFIG.getint('honeypot', 'download_limit_size', fallback=0)

        openFlags = 0
        if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
            openFlags = os.O_RDONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
            openFlags = os.O_WRONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
            openFlags = os.O_RDWR
        if flags & FXF_APPEND == FXF_APPEND:
            openFlags |= os.O_APPEND
        if flags & FXF_CREAT == FXF_CREAT:
            openFlags |= os.O_CREAT
        if flags & FXF_TRUNC == FXF_TRUNC:
            openFlags |= os.O_TRUNC
        if flags & FXF_EXCL == FXF_EXCL:
            openFlags |= os.O_EXCL
        if "permissions" in attrs:
            filemode = attrs["permissions"]
            del attrs["permissions"]
        else:
            filemode = 0o777
        fd = sftpserver.fs.open(filename, openFlags, filemode)
        if attrs:
            self.sftpserver.setAttrs(filename, attrs)
        self.fd = fd

        # Cache a copy of file in memory to read from in readChunk
        if flags & FXF_READ == FXF_READ:
            self.contents = self.sftpserver.fs.file_contents(self.filename)
Exemplo n.º 12
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)

        keyPath = CONFIG.get('proxy', 'private_key')
        self.keys.append(keys.Key.fromFile(keyPath))

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except NoOptionError:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except NoOptionError:
            self.password = None

        log.msg("knownHosts = {0}".format(repr(self.knownHosts)))
        log.msg("host = {0}".format(self.host))
        log.msg("port = {0}".format(self.port))
        log.msg("user = {0}".format(self.user))

        self.client = ProxyClient(self)
Exemplo n.º 13
0
    def __init__(self, *args, **kw):
        channel.CowrieSSHChannel.__init__(self, *args, **kw)

        keyPath = CONFIG.get('proxy', 'private_key')
        self.keys.append(keys.Key.fromFile(keyPath))

        try:
            keyPath = CONFIG.get('proxy', 'private_key')
            self.keys.append(keys.Key.fromFile(keyPath))
        except NoOptionError:
            self.keys = None

        knownHostsPath = CONFIG.get('proxy', 'known_hosts')
        self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)

        self.host = CONFIG.get('proxy', 'host')
        self.port = CONFIG.getint('proxy', 'port')
        self.user = CONFIG.get('proxy', 'user')
        try:
            self.password = CONFIG.get('proxy', 'password')
        except NoOptionError:
            self.password = None

        log.msg("knownHosts = {0}".format(repr(self.knownHosts)))
        log.msg("host = {0}".format(self.host))
        log.msg("port = {0}".format(self.port))
        log.msg("user = {0}".format(self.user))

        self.client = ProxyClient(self)
Exemplo n.º 14
0
 def __init__(self):
     self.host = CONFIG.get(self.RETHINK_DB_SEGMENT, 'host')
     self.port = CONFIG.getint(self.RETHINK_DB_SEGMENT, 'port')
     self.db = CONFIG.get(self.RETHINK_DB_SEGMENT, 'db')
     self.table = CONFIG.get(self.RETHINK_DB_SEGMENT, 'table')
     self.password = CONFIG.get(self.RETHINK_DB_SEGMENT, 'password', raw=True)
     cowrie.core.output.Output.__init__(self)
Exemplo n.º 15
0
    def connectionMade(self):
        pt = self.getProtoTransport()

        self.realClientIP = pt.transport.getPeer().host
        self.realClientPort = pt.transport.getPeer().port
        self.logintime = time.time()

        log.msg(eventid='cowrie.session.params', arch=self.user.server.arch)

        try:
            timeout = CONFIG.getint('honeypot', 'interactive_timeout')
        except Exception:
            timeout = 180
        self.setTimeout(timeout)

        # Source IP of client in user visible reports (can be fake or real)
        try:
            self.clientIP = CONFIG.get('honeypot', 'fake_addr')
        except Exception:
            self.clientIP = self.realClientIP

        # Source IP of server in user visible reports (can be fake or real)
        if CONFIG.has_option('honeypot', 'internet_facing_ip'):
            self.kippoIP = CONFIG.get('honeypot', 'internet_facing_ip')
        else:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(("8.8.8.8", 80))
                self.kippoIP = s.getsockname()[0]
            except Exception:
                self.kippoIP = '192.168.0.1'
            finally:
                s.close()
Exemplo n.º 16
0
    def start(self):
        host = CONFIG.get('output_stingarfluentd', 'fluent_host')
        port = CONFIG.getint('output_stingarfluentd', 'fluent_port')
        app = CONFIG.get('output_stingarfluentd', 'app')

        self.sender = sender.FluentSender(app, host=host, port=port)
        self.meta = {}
Exemplo n.º 17
0
    def makeTftpRetrieval(self):
        """
        """
        progresshook = Progress(self).progresshook

        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.artifactFile = Artifact(self.file_to_get)

        tclient = None
        url = ''

        try:
            tclient = tftpy.TftpClient(self.hostname, int(self.port))

            # tftpy can't handle unicode string as filename
            # so we have to convert unicode type to str type
            tclient.download(str(self.file_to_get), self.artifactFile,
                             progresshook)

            url = 'tftp://%s/%s' % (self.hostname, self.file_to_get.strip('/'))

            self.file_to_get = self.fs.resolve_path(self.file_to_get,
                                                    self.protocol.cwd)

            if hasattr(tclient.context, 'metrics'):
                self.fs.mkfile(self.file_to_get, 0, 0,
                               tclient.context.metrics.bytes, 33188)
            else:
                self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)

        except tftpy.TftpException:
            if tclient and tclient.context and not tclient.context.fileobj.closed:
                tclient.context.fileobj.close()

        if url:

            # log to cowrie.log
            log.msg(
                format=
                'Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum)

            self.protocol.logDispatch(
                eventid='cowrie.session.file_download',
                format=
                'Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum,
                destfile=self.file_to_get)

            # Update the honeyfs to point to downloaded file
            self.fs.update_realfile(self.fs.getfile(self.file_to_get),
                                    self.artifactFile.shasumFilename)
            self.fs.chown(self.file_to_get, self.protocol.user.uid,
                          self.protocol.user.gid)
Exemplo n.º 18
0
    def __init__(self):
        addr = CONFIG.get('output_socketlog', 'address')
        self.host = addr.split(':')[0]
        self.port = int(addr.split(':')[1])

        self.timeout = CONFIG.getint('output_socketlog', 'timeout')
        cowrie.core.output.Output.__init__(self)
Exemplo n.º 19
0
    def start(self):
        """
        """
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CONFIG.has_option('output_hpfeeds', 'channel'):
            self.channel = CONFIG.get('output_hpfeeds', 'channel')

        if CONFIG.has_option('output_hpfeeds', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeeds', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeeds', 'server')
            port = CONFIG.getint('output_hpfeeds', 'port')

            if CONFIG.has_option('output_hpfeeds', 'tlscert'):
                with open(CONFIG.get('output_hpfeeds', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Exemplo n.º 20
0
    def start(self):

        server = CONFIG.get('output_hpfeeds', 'server')
        port = CONFIG.getint('output_hpfeeds', 'port')
        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')
        debug = CONFIG.getboolean('output_hpfeeds', 'debug')
        self.client = hpclient(server, port, ident, secret, debug)
        self.meta = {}
Exemplo n.º 21
0
    def start(self):

        server = CONFIG.get('output_hpfeeds', 'server')
        port = CONFIG.getint('output_hpfeeds', 'port')
        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')
        debug = CONFIG.getboolean('output_hpfeeds', 'debug')
        self.client = hpclient(server, port, ident, secret, debug)
        self.meta = {}
Exemplo n.º 22
0
    def __init__(self):
        self.auth_key = CONFIG.get('output_dshield', 'auth_key')
        self.userid = CONFIG.get('output_dshield', 'userid')
        self.batch_size = CONFIG.getint('output_dshield', 'batch_size')
        try:
            self.debug = CONFIG.getboolean('output_dshield', 'debug')
        except Exception:
            self.debug = False

        cowrie.core.output.Output.__init__(self)
Exemplo n.º 23
0
 def __init__(self):
     """
     Initializing the class
     """
     self.index = CONFIG.get('output_splunklegacy', 'index')
     self.username = CONFIG.get('output_splunklegacy', 'username')
     self.password = CONFIG.get('output_splunklegacy', 'password', raw=True)
     self.host = CONFIG.get('output_splunklegacy', 'host')
     self.port = CONFIG.getint('output_splunklegacy', 'port')
     cowrie.core.output.Output.__init__(self)
Exemplo n.º 24
0
    def __init__(self, *args, **kw):
        """
        Initialize logging
        """
        self.ttylogPath = CONFIG.get('honeypot', 'log_path')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')
        self.ttylogEnabled = CONFIG.getboolean('honeypot', 'ttylog', fallback=True)
        self.bytesReceivedLimit = CONFIG.getint('honeypot', 'download_limit_size', fallback=0)

        channel.SSHChannel.__init__(self, *args, **kw)
Exemplo n.º 25
0
 def __init__(self):
     """
     Initializing the class
     """
     self.index = CONFIG.get('output_splunklegacy', 'index')
     self.username = CONFIG.get('output_splunklegacy', 'username')
     self.password = CONFIG.get('output_splunklegacy', 'password', raw=True)
     self.host = CONFIG.get('output_splunklegacy', 'host')
     self.port = CONFIG.getint('output_splunklegacy', 'port')
     cowrie.core.output.Output.__init__(self)
Exemplo n.º 26
0
    def __init__(self):
        self.auth_key = CONFIG.get('output_dshield', 'auth_key')
        self.userid = CONFIG.get('output_dshield', 'userid')
        self.batch_size = CONFIG.getint('output_dshield', 'batch_size')
        try:
            self.debug = CONFIG.getboolean('output_dshield', 'debug')
        except:
            self.debug = False

        cowrie.core.output.Output.__init__(self)
Exemplo n.º 27
0
    def makeTftpRetrieval(self):
        """
        """
        progresshook = Progress(self).progresshook

        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.artifactFile = Artifact(self.file_to_get)

        tclient = None
        url = ''

        try:
            tclient = tftpy.TftpClient(self.hostname, int(self.port))

            # tftpy can't handle unicode string as filename
            # so we have to convert unicode type to str type
            tclient.download(str(self.file_to_get), self.artifactFile, progresshook)

            url = 'tftp://%s/%s' % (self.hostname, self.file_to_get.strip('/'))

            self.file_to_get = self.fs.resolve_path(self.file_to_get, self.protocol.cwd)

            if hasattr(tclient.context, 'metrics'):
                self.fs.mkfile(self.file_to_get, 0, 0, tclient.context.metrics.bytes, 33188)
            else:
                self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)

        except tftpy.TftpException:
            if tclient and tclient.context and not tclient.context.fileobj.closed:
                tclient.context.fileobj.close()

        if url:

            # log to cowrie.log
            log.msg(format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                    url=url,
                    outfile=self.artifactFile.shasumFilename,
                    shasum=self.artifactFile.shasum)

            self.protocol.logDispatch(eventid='cowrie.session.file_download',
                                      format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                                      url=url,
                                      outfile=self.artifactFile.shasumFilename,
                                      shasum=self.artifactFile.shasum,
                                      destfile=self.file_to_get)

            # Update the honeyfs to point to downloaded file
            self.fs.update_realfile(self.fs.getfile(self.file_to_get), self.artifactFile.shasumFilename)
            self.fs.chown(self.file_to_get, self.protocol.user.uid, self.protocol.user.gid)
Exemplo n.º 28
0
    def __init__(self, *args, **kw):
        """
        Initialize logging
        """
        self.ttylogPath = CONFIG.get('honeypot', 'log_path')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')
        self.ttylogEnabled = CONFIG.getboolean('honeypot',
                                               'ttylog',
                                               fallback=True)
        self.bytesReceivedLimit = CONFIG.getint('honeypot',
                                                'download_limit_size',
                                                fallback=0)

        channel.SSHChannel.__init__(self, *args, **kw)
Exemplo n.º 29
0
    def setService(self, service):
        """
        Remove login grace timeout, set zlib compression after auth
        """
        # Reset timeout. Not everyone opens shell so need timeout at transport level
        if service.name == b'ssh-connection':
            self.setTimeout(CONFIG.getint('honeypot', 'interactive_timeout', fallback=300))

        # when auth is successful we enable compression
        # this is called right after MSG_USERAUTH_SUCCESS
        if service.name == 'ssh-connection':
            if self.outgoingCompressionType == '*****@*****.**':
                self.outgoingCompression = zlib.compressobj(6)
            if self.incomingCompressionType == '*****@*****.**':
                self.incomingCompression = zlib.decompressobj()

        transport.SSHServerTransport.setService(self, service)
Exemplo n.º 30
0
    def connectionMade(self):
        self.transportId = uuid.uuid4().hex[:12]
        sessionno = self.transport.sessionno

        self.startTime = time.time()
        self.setTimeout(CONFIG.getint('honeypot', 'authentication_timeout', fallback=120))

        log.msg(eventid='cowrie.session.connect',
                format='New connection: %(src_ip)s:%(src_port)s (%(dst_ip)s:%(dst_port)s) [session: %(session)s]',
                src_ip=self.transport.getPeer().host,
                src_port=self.transport.getPeer().port,
                dst_ip=self.transport.getHost().host,
                dst_port=self.transport.getHost().port,
                session=self.transportId,
                sessionno='T{0}'.format(str(sessionno)),
                protocol='telnet')
        TelnetTransport.connectionMade(self)
Exemplo n.º 31
0
    def __init__(self, *args, **kw):
        """
        Initialize logging
        """
        self.ttylogPath = CONFIG.get('honeypot', 'log_path')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')
        try:
            self.ttylogEnabled = CONFIG.getboolean('honeypot', 'ttylog')
        except NoOptionError:
            self.ttylogEnabled = True

        try:
            self.bytesReceivedLimit = CONFIG.getint('honeypot', 'download_limit_size')
        except NoOptionError:
            self.bytesReceivedLimit = 0

        channel.SSHChannel.__init__(self, *args, **kw)
Exemplo n.º 32
0
    def start(self):
        try:
            port = CONFIG.getint('output_mysql', 'port')
        except Exception:
            port = 3306

        try:
            self.db = ReconnectingConnectionPool(
                'MySQLdb',
                host=CONFIG.get('output_mysql', 'host'),
                db=CONFIG.get('output_mysql', 'database'),
                user=CONFIG.get('output_mysql', 'username'),
                passwd=CONFIG.get('output_mysql', 'password', raw=True),
                port=port,
                cp_min=1,
                cp_max=1)
        except MySQLdb.Error as e:
            log.msg("output_mysql: Error %d: %s" % (e.args[0], e.args[1]))
Exemplo n.º 33
0
    def _cbLogin(self, ial):
        """
        Fired on a successful login
        """
        interface, protocol, logout = ial
        protocol.windowSize = self.windowSize
        self.protocol = protocol
        self.logout = logout
        self.state = 'Command'

        self.transport.write(b'\n')

        # Remove the short timeout of the login prompt.
        self.transport.setTimeout(CONFIG.getint('honeypot', 'interactive_timeout', fallback=300))

        # replace myself with avatar protocol
        protocol.makeConnection(self.transport)
        self.transport.protocol = protocol
Exemplo n.º 34
0
    def _cbLogin(self, ial):
        """
        Fired on a successful login
        """
        interface, protocol, logout = ial
        protocol.windowSize = self.windowSize
        self.protocol = protocol
        self.logout = logout
        self.state = 'Command'

        self.transport.write(b'\n')

        # Remove the short timeout of the login prompt.
        self.transport.setTimeout(
            CONFIG.getint('honeypot', 'interactive_timeout', fallback=300))

        # replace myself with avatar protocol
        protocol.makeConnection(self.transport)
        self.transport.protocol = protocol
Exemplo n.º 35
0
    def __init__(self, prot=None, *a, **kw):
        insults.ServerProtocol.__init__(self, prot, *a, **kw)
        self.bytesReceived = 0

        self.ttylogPath = CONFIG.get('honeypot', 'ttylog_path')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')

        try:
            self.ttylogEnabled = CONFIG.getboolean('honeypot', 'ttylog')
        except Exception:
            self.ttylogEnabled = True

        self.redirFiles = set()

        self.bytesReceivedLimit = CONFIG.getint('honeypot', 'download_limit_size', fallback=0)

        if prot is protocol.HoneyPotExecProtocol:
            self.type = 'e'  # Execcmd
        else:
            self.type = 'i'  # Interactive
Exemplo n.º 36
0
    def start(self):
        try:
            port = CONFIG.getint('output_mysql', 'port')
        except Exception:
            port = 3306

        try:
            self.db = ReconnectingConnectionPool(
                'MySQLdb',
                host=CONFIG.get('output_mysql', 'host'),
                db=CONFIG.get('output_mysql', 'database'),
                user=CONFIG.get('output_mysql', 'username'),
                passwd=CONFIG.get('output_mysql', 'password', raw=True),
                port=port,
                cp_min=1,
                cp_max=1,
                charset='utf8mb4',
                use_unicode=True
            )
        except MySQLdb.Error as e:
            log.msg("output_mysql: Error %d: %s" % (e.args[0], e.args[1]))
Exemplo n.º 37
0
    def __init__(self, sftpserver, filename, flags, attrs):
        self.sftpserver = sftpserver
        self.filename = filename
        self.transfer_completed = 0
        self.bytesReceived = 0

        try:
            self.bytesReceivedLimit = CONFIG.getint('honeypot',
                                                    'download_limit_size')
        except:
            self.bytesReceivedLimit = 0

        openFlags = 0
        if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
            openFlags = os.O_RDONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
            openFlags = os.O_WRONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
            openFlags = os.O_RDWR
        if flags & FXF_APPEND == FXF_APPEND:
            openFlags |= os.O_APPEND
        if flags & FXF_CREAT == FXF_CREAT:
            openFlags |= os.O_CREAT
        if flags & FXF_TRUNC == FXF_TRUNC:
            openFlags |= os.O_TRUNC
        if flags & FXF_EXCL == FXF_EXCL:
            openFlags |= os.O_EXCL
        if "permissions" in attrs:
            filemode = attrs["permissions"]
            del attrs["permissions"]
        else:
            filemode = 0o777
        fd = sftpserver.fs.open(filename, openFlags, filemode)
        if attrs:
            self.sftpserver.setAttrs(filename, attrs)
        self.fd = fd

        # Cache a copy of file in memory to read from in readChunk
        if flags & FXF_READ == FXF_READ:
            self.contents = self.sftpserver.fs.file_contents(self.filename)
Exemplo n.º 38
0
    def start(self):
        """
        docstring here
        """

        try:
            port = CONFIG.getint('output_mysql', 'port')
        except:
            port = 3306

        try:
            self.db = ReconnectingConnectionPool(
                'MySQLdb',
                host=CONFIG.get('output_mysql', 'host'),
                db=CONFIG.get('output_mysql', 'database'),
                user=CONFIG.get('output_mysql', 'username'),
                passwd=CONFIG.get('output_mysql', 'password', raw=True),
                port=port,
                cp_min=1,
                cp_max=1
            )
        except MySQLdb.Error as e:
            log.msg("output_mysql: Error %d: %s" % (e.args[0], e.args[1]))
Exemplo n.º 39
0
    def start(self):
        try:
            host = CONFIG.get('output_influx', 'host')
        except Exception:
            host = ''

        try:
            port = CONFIG.getint('output_influx', 'port')
        except Exception:
            port = 8086

        try:
            ssl = CONFIG.getboolean('output_influx', 'ssl')
        except Exception:
            ssl = False

        self.client = None
        try:
            self.client = InfluxDBClient(host=host, port=port, ssl=ssl, verify_ssl=ssl)
        except InfluxDBClientError as e:
            log.err("output_influx: I/O error({0}): '{1}'".format(
                e.errno, e.strerror))
            return

        if self.client is None:
            log.err("output_influx: cannot instantiate client!")
            return

        if (CONFIG.has_option('output_influx', 'username') and
                CONFIG.has_option('output_influx', 'password')):
            username = CONFIG.get('output_influx', 'username')
            password = CONFIG.get('output_influx', 'password', raw=True)
            self.client.switch_user(username, password)

        try:
            dbname = CONFIG.get('output_influx', 'database_name')
        except Exception:
            dbname = 'cowrie'

        retention_policy_duration_default = '12w'
        retention_policy_name = dbname + "_retention_policy"

        if CONFIG.has_option('output_influx', 'retention_policy_duration'):
            retention_policy_duration = CONFIG.get(
                'output_influx', 'retention_policy_duration')

            match = re.search(r'^\d+[dhmw]{1}$', retention_policy_duration)
            if not match:
                log.err(("output_influx: invalid retention policy."
                         "Using default '{}'..").format(
                    retention_policy_duration))
                retention_policy_duration = retention_policy_duration_default
        else:
            retention_policy_duration = retention_policy_duration_default

        database_list = self.client.get_list_database()
        dblist = [str(elem['name']) for elem in database_list]

        if dbname not in dblist:
            self.client.create_database(dbname)
            self.client.create_retention_policy(
                retention_policy_name, retention_policy_duration, 1,
                database=dbname, default=True)
        else:
            retention_policies_list = self.client.get_list_retention_policies(
                database=dbname)
            rplist = [str(elem['name']) for elem in retention_policies_list]
            if retention_policy_name not in rplist:
                self.client.create_retention_policy(
                    retention_policy_name, retention_policy_duration, 1,
                    database=dbname, default=True)
            else:
                self.client.alter_retention_policy(
                    retention_policy_name, database=dbname,
                    duration=retention_policy_duration,
                    replication=1, default=True)

        self.client.switch_database(dbname)
Exemplo n.º 40
0
Arquivo: tftp.py Projeto: Acey9/cowrie
    def makeTftpRetrieval(self):
        """
        """
        progresshook = Progress(self).progresshook

        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.download_path = CONFIG.get('honeypot', 'download_path')

        tmp_fname = '%s_%s_%s_%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.file_to_get))
        self.safeoutfile = os.path.join(self.download_path, tmp_fname)

        tclient = None

        try:
            tclient = tftpy.TftpClient(self.hostname, int(self.port))
            tclient.download(self.file_to_get, self.safeoutfile, progresshook)

            url = 'tftp://%s/%s' % (self.hostname, self.file_to_get.strip('/'))

            self.file_to_get = self.fs.resolve_path(self.file_to_get,
                                                    self.protocol.cwd)

            if hasattr(tclient.context, 'metrics'):
                self.fs.mkfile(self.file_to_get, 0, 0,
                               tclient.context.metrics.bytes, 33188)
            else:
                self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)

        except tftpy.TftpException as err:
            if tclient and tclient.context and not tclient.context.fileobj.closed:
                tclient.context.fileobj.close()

        if os.path.exists(self.safeoutfile):

            if os.path.getsize(self.safeoutfile) == 0:
                os.remove(self.safeoutfile)
                self.safeoutfile = None
                return

            with open(self.safeoutfile, 'rb') as f:
                #shasum = hashlib.sha256(f.read()).hexdigest()
                shasum = hashlib.md5(f.read()).hexdigest()
                hash_path = os.path.join(self.download_path, shasum)

            # If we have content already, delete temp file
            if not os.path.exists(hash_path):
                os.rename(self.safeoutfile, hash_path)
            else:
                os.remove(self.safeoutfile)
                log.msg("Not storing duplicate content " + shasum)

            self.protocol.logDispatch(
                eventid='cowrie.session.file_download',
                format=
                'Downloaded tftpFile (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                url=url,
                outfile=hash_path,
                shasum=shasum)

            # Link friendly name to hash
            # os.symlink(shasum, self.safeoutfile)

            self.safeoutfile = None

            # Update the honeyfs to point to downloaded file
            self.fs.update_realfile(self.fs.getfile(self.file_to_get),
                                    hash_path)
            self.fs.chown(self.file_to_get, self.protocol.user.uid,
                          self.protocol.user.gid)
            self.exit()
Exemplo n.º 41
0
    def start(self):
        try:
            optlist, args = getopt.getopt(self.args, 'sho:O', ['help', 'manual', 'silent'])
        except getopt.GetoptError as err:
            # TODO: should be 'unknown' instead of 'not recognized'
            self.write("curl: {}\n".format(err))
            self.write("curl: try 'curl --help' or 'curl --manual' for more information\n")
            self.exit()
            return

        for opt in optlist:
            if opt[0] == '-h' or opt[0] == '--help':
                self.curl_help()
                return
            elif opt[0] == '-s' or opt[0] == '--silent':
                self.silent = True

        if len(args):
            if args[0] is not None:
                url = str(args[0]).strip()
        else:
            self.write("curl: try 'curl --help' or 'curl --manual' for more information\n")
            self.exit()
            return

        if '://' not in url:
            url = 'http://' + url
        urldata = compat.urllib_parse.urlparse(url)

        outfile = None
        for opt in optlist:
            if opt[0] == '-o':
                outfile = opt[1]
            if opt[0] == '-O':
                outfile = urldata.path.split('/')[-1]
                if outfile is None or not len(outfile.strip()) or not urldata.path.count('/'):
                    self.write('curl: Remote file name has no length!\n')
                    self.exit()
                    return

        if outfile:
            outfile = self.fs.resolve_path(outfile, self.protocol.cwd)
            path = os.path.dirname(outfile)
            if not path or \
                    not self.fs.exists(path) or \
                    not self.fs.isdir(path):
                self.write('curl: %s: Cannot open: No such file or directory\n' % outfile)
                self.exit()
                return

        url = url.encode('ascii')
        self.url = url
        self.limit_size = 0
        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.download_path = CONFIG.get('honeypot', 'download_path')

        if not hasattr(self, 'safeoutfile'):
            tmp_fname = '%s_%s_%s_%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]', '_', url.decode('ascii')))
            self.safeoutfile = os.path.join(self.download_path, tmp_fname)

        self.deferred = self.download(url, outfile, self.safeoutfile)
        if self.deferred:
            self.deferred.addCallback(self.success, outfile)
            self.deferred.addErrback(self.error, url)
Exemplo n.º 42
0
 def __init__(self):
     self.timeout = [
         CONFIG.getint('output_reversedns', 'timeout', fallback=3)
     ]
     cowrie.core.output.Output.__init__(self)
Exemplo n.º 43
0
 def __init__(self):
     self.timeout = [CONFIG.getint(
         'output_reversedns', 'timeout', fallback=3)]
     cowrie.core.output.Output.__init__(self)
Exemplo n.º 44
0
    def start(self):
        """
        """
        try:
            host = CONFIG.get('output_influx', 'host')
        except:
            host = ''

        try:
            port = CONFIG.getint('output_influx', 'port')
        except:
            port = 8086

        self.client = None
        try:
            self.client = InfluxDBClient(host=host, port=port)
        except InfluxDBClientError as e:
            log.err("output_influx: I/O error({0}): '{1}'".format(
                e.errno, e.strerror))
            return

        if self.client is None:
            log.err("output_influx: cannot instantiate client!")
            return

        if (CONFIG.has_option('output_influx', 'username')
                and CONFIG.has_option('output_influx', 'password')):
            username = CONFIG.get('output_influx', 'username')
            password = CONFIG.get('output_influx', 'password', raw=True)
            self.client.switch_user(username, password)

        try:
            dbname = CONFIG.get('output_influx', 'database_name')
        except:
            dbname = 'cowrie'

        retention_policy_duration_default = '12w'
        retention_policy_name = dbname + "_retention_policy"

        if CONFIG.has_option('output_influx', 'retention_policy_duration'):
            retention_policy_duration = CONFIG.get(
                'output_influx', 'retention_policy_duration')

            match = re.search('^\d+[dhmw]{1}$', retention_policy_duration)
            if not match:
                log.err(
                    ("output_influx: invalid retention policy."
                     "Using default '{}'..").format(retention_policy_duration))
                retention_policy_duration = retention_policy_duration_default
        else:
            retention_policy_duration = retention_policy_duration_default

        database_list = self.client.get_list_database()
        dblist = [str(elem['name']) for elem in database_list]

        if dbname not in dblist:
            self.client.create_database(dbname)
            self.client.create_retention_policy(retention_policy_name,
                                                retention_policy_duration,
                                                1,
                                                database=dbname,
                                                default=True)
        else:
            retention_policies_list = self.client.get_list_retention_policies(
                database=dbname)
            rplist = [str(elem['name']) for elem in retention_policies_list]
            if retention_policy_name not in rplist:
                self.client.create_retention_policy(retention_policy_name,
                                                    retention_policy_duration,
                                                    1,
                                                    database=dbname,
                                                    default=True)
            else:
                self.client.alter_retention_policy(
                    retention_policy_name,
                    database=dbname,
                    duration=retention_policy_duration,
                    replication=1,
                    default=True)

        self.client.switch_database(dbname)
Exemplo n.º 45
0
    def start(self):
        """
        """
        try:
            optlist, args = getopt.getopt(self.args, 'cqO:P:', 'header=')
        except getopt.GetoptError as err:
            self.errorWrite('Unrecognized option\n')
            self.exit()
            return

        if len(args):
            url = args[0].strip()
        else:
            self.errorWrite('wget: missing URL\n')
            self.errorWrite('Usage: wget [OPTION]... [URL]...\n\n')
            self.errorWrite('Try `wget --help\' for more options.\n')
            self.exit()
            return

        outfile = None
        self.quiet = False
        for opt in optlist:
            if opt[0] == '-O':
                outfile = opt[1]
            if opt[0] == '-q':
                self.quiet = True

        # for some reason getopt doesn't recognize "-O -"
        # use try..except for the case if passed command is malformed
        try:
            if not outfile:
                if '-O' in args:
                    outfile = args[args.index('-O') + 1]
        except:
            pass

        if '://' not in url:
            url = 'http://%s' % url

        urldata = compat.urllib_parse.urlparse(url)

        url = url.encode('utf8')

        if outfile is None:
            outfile = urldata.path.split('/')[-1]
            if not len(outfile.strip()) or not urldata.path.count('/'):
                outfile = 'index.html'

        if outfile != '-':
            outfile = self.fs.resolve_path(outfile, self.protocol.cwd)
            path = os.path.dirname(outfile)
            if not path or not self.fs.exists(path) or not self.fs.isdir(path):
                self.errorWrite('wget: %s: Cannot open: No such file or directory\n' % outfile)
                self.exit()
                return

        self.url = url

        self.limit_size = 0
        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')

        self.artifactFile = Artifact(outfile)
        # HTTPDownloader will close() the file object so need to preserve the name

        d = self.download(url, outfile, self.artifactFile)
        if d:
            d.addCallback(self.success, outfile)
            d.addErrback(self.error, url)
        else:
            self.exit()
Exemplo n.º 46
0
class CowrieSSHChannel(channel.SSHChannel):
    """
    This is an SSH channel with built-in logging
    """
    ttylogEnabled = True
    ttylogFile = ""
    bytesReceived = 0
    bytesReceivedLimit = 0
    bytesWritten = 0
    name = b'cowrie-ssh-channel'
    startTime = None
    ttylogPath = CONFIG.get('honeypot', 'log_path')
    downloadPath = CONFIG.get('honeypot', 'download_path')
    ttylogEnabled = CONFIG.getboolean('honeypot', 'ttylog', fallback=True)
    bytesReceivedLimit = CONFIG.getint('honeypot',
                                       'download_limit_size',
                                       fallback=0)

    def __repr__(self):
        """
        Return a pretty representation of this object.

        @return Pretty representation of this object as a string
        @rtype: L{str}
        """
        return "Cowrie SSH Channel {}".format(self.name)

    def __init__(self, *args, **kw):
        """
        Initialize logging
        """
        channel.SSHChannel.__init__(self, *args, **kw)

    def channelOpen(self, specificData):
        self.startTime = time.time()
        self.ttylogFile = '%s/tty/%s-%s-%s.log' % (
            self.ttylogPath, time.strftime('%Y%m%d-%H%M%S'),
            self.conn.transport.transportId, self.id)
        log.msg(eventid='cowrie.log.open',
                ttylog=self.ttylogFile,
                format="Opening TTY Log: %(ttylog)s")
        ttylog.ttylog_open(self.ttylogFile, time.time())
        channel.SSHChannel.channelOpen(self, specificData)

    def closed(self):
        log.msg(
            eventid='cowrie.log.closed',
            format="Closing TTY Log: %(ttylog)s after %(duration)d seconds",
            ttylog=self.ttylogFile,
            size=self.bytesReceived + self.bytesWritten,
            duration=time.time() - self.startTime)
        ttylog.ttylog_close(self.ttylogFile, time.time())
        channel.SSHChannel.closed(self)

    def dataReceived(self, data):
        """
        Called when we receive data from the user

        @type data: L{bytes}
        @param data: Data sent to the server from the client
        """
        self.bytesReceived += len(data)
        if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit:
            log.msg("Data upload limit reached for channel {}".format(self.id))
            self.eofReceived()
            return

        if self.ttylogEnabled:
            ttylog.ttylog_write(self.ttylogFile, len(data), ttylog.TYPE_INPUT,
                                time.time(), data)

        channel.SSHChannel.dataReceived(self, data)

    def write(self, data):
        """
        Called when we send data to the user

        @type data: L{bytes}
        @param data: Data sent to the client from the server
        """
        if self.ttylogEnabled:
            ttylog.ttylog_write(self.ttylogFile, len(data), ttylog.TYPE_OUTPUT,
                                time.time(), data)
            self.bytesWritten += len(data)

        channel.SSHChannel.write(self, data)
Exemplo n.º 47
0
    def start(self):
        try:
            optlist, args = getopt.getopt(self.args, 'cqO:P:', 'header=')
        except getopt.GetoptError:
            self.errorWrite('Unrecognized option\n')
            self.exit()
            return

        if len(args):
            url = args[0].strip()
        else:
            self.errorWrite('wget: missing URL\n')
            self.errorWrite('Usage: wget [OPTION]... [URL]...\n\n')
            self.errorWrite('Try `wget --help\' for more options.\n')
            self.exit()
            return

        outfile = None
        self.quiet = False
        for opt in optlist:
            if opt[0] == '-O':
                outfile = opt[1]
            if opt[0] == '-q':
                self.quiet = True

        # for some reason getopt doesn't recognize "-O -"
        # use try..except for the case if passed command is malformed
        try:
            if not outfile:
                if '-O' in args:
                    outfile = args[args.index('-O') + 1]
        except Exception:
            pass

        if '://' not in url:
            url = 'http://%s' % url

        urldata = compat.urllib_parse.urlparse(url)

        url = url.encode('utf8')

        if outfile is None:
            outfile = urldata.path.split('/')[-1]
            if not len(outfile.strip()) or not urldata.path.count('/'):
                outfile = 'index.html'

        if outfile != '-':
            outfile = self.fs.resolve_path(outfile, self.protocol.cwd)
            path = os.path.dirname(outfile)
            if not path or not self.fs.exists(path) or not self.fs.isdir(path):
                self.errorWrite(
                    'wget: %s: Cannot open: No such file or directory\n' %
                    outfile)
                self.exit()
                return

        self.url = url

        self.limit_size = 0
        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')
        self.downloadPath = CONFIG.get('honeypot', 'download_path')

        self.artifactFile = Artifact(outfile)
        # HTTPDownloader will close() the file object so need to preserve the name

        d = self.download(url, outfile, self.artifactFile)
        if d:
            d.addCallback(self.success, outfile)
            d.addErrback(self.error, url)
        else:
            self.exit()
Exemplo n.º 48
0
class LoggingServerProtocol(insults.ServerProtocol):
    """
    Wrapper for ServerProtocol that implements TTY logging
    """
    redirlogOpen = False  # it will be set at core/protocol.py
    stdinlogOpen = False
    ttylogOpen = False
    ttylogPath = CONFIG.get('honeypot', 'ttylog_path')
    downloadPath = CONFIG.get('honeypot', 'download_path')
    ttylogEnabled = CONFIG.getboolean('honeypot', 'ttylog', fallback=True)
    bytesReceivedLimit = CONFIG.getint('honeypot',
                                       'download_limit_size',
                                       fallback=0)
    bytesReceived = 0
    redirFiles = set()

    def __init__(self, prot=None, *a, **kw):
        insults.ServerProtocol.__init__(self, prot, *a, **kw)

        if prot is protocol.HoneyPotExecProtocol:
            self.type = 'e'  # Execcmd
        else:
            self.type = 'i'  # Interactive

    def getSessionId(self):
        transportId = self.transport.session.conn.transport.transportId
        channelId = self.transport.session.id
        return (transportId, channelId)

    def connectionMade(self):
        transportId, channelId = self.getSessionId()
        self.startTime = time.time()

        if self.ttylogEnabled:
            self.ttylogFile = '%s/%s-%s-%s%s.log' % \
                              (self.ttylogPath, time.strftime('%Y%m%d-%H%M%S'),
                               transportId, channelId, self.type)
            ttylog.ttylog_open(self.ttylogFile, self.startTime)
            self.ttylogOpen = True
            self.ttylogSize = 0

        self.stdinlogFile = '%s/%s-%s-%s-stdin.log' % \
                            (self.downloadPath, time.strftime('%Y%m%d-%H%M%S'), transportId, channelId)

        if self.type == 'e':
            self.stdinlogOpen = True
        else:
            self.stdinlogOpen = False

        insults.ServerProtocol.connectionMade(self)

        if self.type == 'e':
            cmd = self.terminalProtocol.execcmd.encode('utf8')
            ttylog.ttylog_write(self.ttylogFile, len(cmd),
                                ttylog.TYPE_INTERACT, time.time(), cmd)

    def write(self, data):
        if self.ttylogEnabled and self.ttylogOpen:
            ttylog.ttylog_write(self.ttylogFile, len(data), ttylog.TYPE_OUTPUT,
                                time.time(), data)
            self.ttylogSize += len(data)

        insults.ServerProtocol.write(self, data)

    def dataReceived(self, data):
        """
        Input received from user
        """
        self.bytesReceived += len(data)
        if self.bytesReceivedLimit and self.bytesReceived > self.bytesReceivedLimit:
            log.msg(format='Data upload limit reached')
            self.eofReceived()
            return

        if self.stdinlogOpen:
            with open(self.stdinlogFile, 'ab') as f:
                f.write(data)
        elif self.ttylogEnabled and self.ttylogOpen:
            ttylog.ttylog_write(self.ttylogFile, len(data), ttylog.TYPE_INPUT,
                                time.time(), data)

        # prevent crash if something like this was passed:
        # echo cmd ; exit; \n\n
        if self.terminalProtocol:
            insults.ServerProtocol.dataReceived(self, data)

    def eofReceived(self):
        """
        Receive channel close and pass on to terminal
        """
        if self.terminalProtocol:
            self.terminalProtocol.eofReceived()

    def loseConnection(self):
        """
        Override super to remove the terminal reset on logout
        """
        self.transport.loseConnection()

    def connectionLost(self, reason):
        """
        FIXME: this method is called 4 times on logout....
        it's called once from Avatar.closed() if disconnected
        """
        if self.stdinlogOpen:
            try:
                with open(self.stdinlogFile, 'rb') as f:
                    shasum = hashlib.sha256(f.read()).hexdigest()
                    shasumfile = os.path.join(self.downloadPath, shasum)
                    if os.path.exists(shasumfile):
                        os.remove(self.stdinlogFile)
                        duplicate = True
                    else:
                        os.rename(self.stdinlogFile, shasumfile)
                        duplicate = False

                log.msg(
                    eventid='cowrie.session.file_download',
                    format=
                    'Saved stdin contents with SHA-256 %(shasum)s to %(outfile)s',
                    url='stdin',
                    duplicate=duplicate,
                    outfile=shasumfile,
                    shasum=shasum,
                    destfile='')
            except IOError:
                pass
            finally:
                self.stdinlogOpen = False

        if self.redirFiles:
            for rp in self.redirFiles:

                rf = rp[0]

                if rp[1]:
                    url = rp[1]
                else:
                    url = rf[rf.find('redir_') + len('redir_'):]

                try:
                    if not os.path.exists(rf):
                        continue

                    if os.path.getsize(rf) == 0:
                        os.remove(rf)
                        continue

                    with open(rf, 'rb') as f:
                        shasum = hashlib.sha256(f.read()).hexdigest()
                        shasumfile = os.path.join(self.downloadPath, shasum)
                        if os.path.exists(shasumfile):
                            os.remove(rf)
                            duplicate = True
                        else:
                            os.rename(rf, shasumfile)
                            duplicate = False
                    log.msg(
                        eventid='cowrie.session.file_download',
                        format=
                        'Saved redir contents with SHA-256 %(shasum)s to %(outfile)s',
                        url=url,
                        duplicate=duplicate,
                        outfile=shasumfile,
                        shasum=shasum,
                        destfile=url)
                except IOError:
                    pass
            self.redirFiles.clear()

        if self.ttylogEnabled and self.ttylogOpen:
            ttylog.ttylog_close(self.ttylogFile, time.time())
            self.ttylogOpen = False
            shasum = ttylog.ttylog_inputhash(self.ttylogFile)
            shasumfile = os.path.join(self.ttylogPath, shasum)

            if os.path.exists(shasumfile):
                duplicate = True
                os.remove(self.ttylogFile)
            else:
                duplicate = False
                os.rename(self.ttylogFile, shasumfile)
                umask = os.umask(0)
                os.umask(umask)
                os.chmod(shasumfile, 0o666 & ~umask)

            log.msg(
                eventid='cowrie.log.closed',
                format='Closing TTY Log: %(ttylog)s after %(duration)d seconds',
                ttylog=shasumfile,
                size=self.ttylogSize,
                shasum=shasum,
                duplicate=duplicate,
                duration=time.time() - self.startTime)

        insults.ServerProtocol.connectionLost(self, reason)
Exemplo n.º 49
0
Arquivo: curl.py Projeto: Acey9/cowrie
    def start(self):
        """
        """
        try:
            optlist, args = getopt.getopt(self.args, 'sho:O',
                                          ['help', 'manual', 'silent'])
        except getopt.GetoptError as err:
            # TODO: should be 'unknown' instead of 'not recognized'
            self.write("curl: {}\n".format(err))
            self.write(
                "curl: try 'curl --help' or 'curl --manual' for more information\n"
            )
            self.exit()
            return

        for opt in optlist:
            if opt[0] == '-h' or opt[0] == '--help':
                self.curl_help()
                return
            elif opt[0] == '-s' or opt[0] == '--silent':
                self.silent = True

        if len(args):
            if args[0] is not None:
                url = str(args[0]).strip()
        else:
            self.write(
                "curl: try 'curl --help' or 'curl --manual' for more information\n"
            )
            self.exit()
            return

        if '://' not in url:
            url = 'http://' + url
        urldata = compat.urllib_parse.urlparse(url)

        outfile = None
        for opt in optlist:
            if opt[0] == '-o':
                outfile = opt[1]
            if opt[0] == '-O':
                outfile = urldata.path.split('/')[-1]
                if outfile is None or not len(
                        outfile.strip()) or not urldata.path.count('/'):
                    self.write('curl: Remote file name has no length!\n')
                    self.exit()
                    return

        if outfile:
            outfile = self.fs.resolve_path(outfile, self.protocol.cwd)
            path = os.path.dirname(outfile)
            if not path or \
                    not self.fs.exists(path) or \
                    not self.fs.isdir(path):
                self.write('curl: %s: Cannot open: No such file or directory\n' % \
                    (outfile,))
                self.exit()
                return

        url = url.encode('ascii')
        self.url = url
        self.limit_size = 0
        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.download_path = CONFIG.get('honeypot', 'download_path')

        if not hasattr(self, 'safeoutfile'):
            tmp_fname = '%s_%s_%s_%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]', '_', url.decode('ascii')))
            self.safeoutfile = os.path.join(self.download_path, tmp_fname)

        self.deferred = self.download(url, outfile, self.safeoutfile)
        if self.deferred:
            self.deferred.addCallback(self.success, outfile)
            self.deferred.addErrback(self.error, url)