Example #1
0
    def __init__(self, username, server):
        avatar.ConchUser.__init__(self)
        self.username = username.decode('utf-8')
        self.server = server

        self.channelLookup[b'session'] = sshsession.HoneyPotSSHSession

        try:
            pwentry = pwd.Passwd().getpwnam(self.username)
            self.uid = pwentry['pw_uid']
            self.gid = pwentry['pw_gid']
            self.home = pwentry['pw_dir']
        except:
            self.uid = 1001
            self.gid = 1001
            self.home = '/home'

        # SFTP support enabled only when option is explicitly set
        try:
            if CONFIG.getboolean('ssh', 'sftp_enabled') == True:
                self.subsystemLookup[b'sftp'] = conchfiletransfer.FileTransferServer
        except ValueError as e:
            pass

        # SSH forwarding disabled only when option is explicitly set
        self.channelLookup[b'direct-tcpip'] = forwarding.cowrieOpenConnectForwardingClient
        try:
            if CONFIG.getboolean('ssh', 'forwarding') == False:
                del self.channelLookup[b'direct-tcpip']
        except:
            pass
Example #2
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)
Example #3
0
    def checkUserPass(self, theusername, thepassword, ip):
        # UserDB is the default auth_class
        authname = auth.UserDB

        # Is the auth_class defined in the config file?
        if CONFIG.has_option('honeypot', 'auth_class'):
            authclass = CONFIG.get('honeypot', 'auth_class')
            authmodule = "cowrie.core.auth"

            # Check if authclass exists in this module
            if hasattr(modules[authmodule], authclass):
                authname = getattr(modules[authmodule], authclass)
            else:
                log.msg('auth_class: %s not found in %s' % (authclass, authmodule))

        theauth = authname()

        if theauth.checklogin(theusername, thepassword, ip):
            log.msg(eventid='cowrie.login.success',
                    format='login attempt [%(username)s/%(password)s] succeeded',
                    username=theusername,
                    password=thepassword)
            return True
        else:
            log.msg(eventid='cowrie.login.failed',
                    format='login attempt [%(username)s/%(password)s] failed',
                    username=theusername,
                    password=thepassword)
            return False
Example #4
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()
Example #5
0
    def download(self, url, fakeoutfile, outputfile, *args, **kwargs):
        try:
            parsed = compat.urllib_parse.urlparse(url)
            scheme = parsed.scheme
            host = parsed.hostname.decode('utf8')
            port = parsed.port or (443 if scheme == 'https' else 80)
            if scheme != b'http' and scheme != b'https':
                raise NotImplementedError
        except Exception:
            self.errorWrite('curl: (1) Protocol "{}" not supported or disabled in libcurl\n'.format(scheme))
            self.exit()
            return None

        factory = HTTPProgressDownloader(
            self, fakeoutfile, url, outputfile, *args, **kwargs)
        out_addr = None
        if CONFIG.has_option('honeypot', 'out_addr'):
            out_addr = (CONFIG.get('honeypot', 'out_addr'), 0)

        if scheme == 'https':
            contextFactory = ssl.ClientContextFactory()
            contextFactory.method = SSL.SSLv23_METHOD
            reactor.connectSSL(host, port, factory, contextFactory, bindAddress=out_addr)
        else:  # Can only be http
            self.connection = reactor.connectTCP(
                host, port, factory, bindAddress=out_addr)

        return factory.deferred
Example #6
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()
Example #7
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)
Example #8
0
 def __init__(self):
     cowrie.core.output.Output.__init__(self)
     fn = CONFIG.get('output_jsonlog', 'logfile')
     self.epoch_timestamp = CONFIG.getboolean('output_jsonlog', 'epoch_timestamp', fallback=False)
     dirs = os.path.dirname(fn)
     base = os.path.basename(fn)
     self.outfile = cowrie.python.logfile.CowrieDailyLogFile(base, dirs, defaultMode=0o664)
Example #9
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()
Example #10
0
    def __init__(self, username, server):
        avatar.ConchUser.__init__(self)
        self.username = username.decode('utf-8')
        self.server = server

        self.channelLookup[b'session'] = sshsession.HoneyPotSSHSession

        try:
            pwentry = pwd.Passwd().getpwnam(self.username)
            self.temporary = False
        except KeyError:
            pwentry = pwd.Passwd().setpwentry(self.username)
            self.temporary = True

        self.uid = pwentry['pw_uid']
        self.gid = pwentry['pw_gid']
        self.home = pwentry['pw_dir']

        # SFTP support enabled only when option is explicitly set
        if CONFIG.getboolean('ssh', 'sftp_enabled', fallback=False):
            self.subsystemLookup[b'sftp'] = conchfiletransfer.FileTransferServer

        # SSH forwarding disabled only when option is explicitly set
        if CONFIG.getboolean('ssh', 'forwarding', fallback=True):
            self.channelLookup[b'direct-tcpip'] = forwarding.cowrieOpenConnectForwardingClient
Example #11
0
 def __init__(self):
     """
     """
     facilityString = CONFIG.get('output_localsyslog', 'facility')
     self.format = CONFIG.get('output_localsyslog', 'format')
     self.facility = vars(syslog)['LOG_' + facilityString]
     self.syslog = twisted.python.syslog.SyslogObserver(prefix='cowrie', facility=self.facility)
     cowrie.core.output.Output.__init__(self)
Example #12
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 = {}
Example #13
0
 def __init__(self):
     """
     """
     self.host = CONFIG.get('output_elasticsearch', 'host')
     self.port = CONFIG.get('output_elasticsearch', 'port')
     self.index = CONFIG.get('output_elasticsearch', 'index')
     self.type = CONFIG.get('output_elasticsearch', 'type')
     self.pipeline = CONFIG.get('output_elasticsearch', 'pipeline')
     cowrie.core.output.Output.__init__(self)
Example #14
0
def cowrieOpenConnectForwardingClient(remoteWindow, remoteMaxPacket, data, avatar):
    """
    This function will redirect an SSH forward request to another address
    or will log the request and do nothing
    """
    remoteHP, origHP = forwarding.unpackOpen_direct_tcpip(data)

    log.msg(eventid='cowrie.direct-tcpip.request',
            format='direct-tcp connection request to %(dst_ip)s:%(dst_port)s from %(src_ip)s:%(src_port)s',
            dst_ip=remoteHP[0], dst_port=remoteHP[1],
            src_ip=origHP[0], src_port=origHP[1])

    # Forward redirect
    redirectEnabled = CONFIG.getboolean('ssh', 'forward_redirect', fallback=False)
    if redirectEnabled:
        redirects = {}
        items = CONFIG.items('ssh')
        for i in items:
            if i[0].startswith('forward_redirect_'):
                destPort = i[0].split('_')[-1]
                redirectHP = i[1].split(':')
                redirects[int(destPort)] = (redirectHP[0], int(redirectHP[1]))
        if remoteHP[1] in redirects:
            remoteHPNew = redirects[remoteHP[1]]
            log.msg(eventid='cowrie.direct-tcpip.redirect',
                    format='redirected direct-tcp connection request from %(src_ip)s:%(src_port)' +
                           'd to %(dst_ip)s:%(dst_port)d to %(new_ip)s:%(new_port)d',
                    new_ip=remoteHPNew[0], new_port=remoteHPNew[1],
                    dst_ip=remoteHP[0], dst_port=remoteHP[1],
                    src_ip=origHP[0], src_port=origHP[1])
            return SSHConnectForwardingChannel(remoteHPNew, remoteWindow=remoteWindow, remoteMaxPacket=remoteMaxPacket)

    # TCP tunnel
    tunnelEnabled = CONFIG.getboolean('ssh', 'forward_tunnel', fallback=False)
    if tunnelEnabled:
        tunnels = {}
        items = CONFIG.items('ssh')
        for i in items:
            if i[0].startswith('forward_tunnel_'):
                destPort = i[0].split('_')[-1]
                tunnelHP = i[1].split(':')
                tunnels[int(destPort)] = (tunnelHP[0], int(tunnelHP[1]))
        if remoteHP[1] in tunnels:
            remoteHPNew = tunnels[remoteHP[1]]
            log.msg(eventid='cowrie.direct-tcpip.tunnel',
                    format='tunneled direct-tcp connection request %(src_ip)s:%(src_port)' +
                           'd->%(dst_ip)s:%(dst_port)d to %(new_ip)s:%(new_port)d',
                    new_ip=remoteHPNew[0], new_port=remoteHPNew[1],
                    dst_ip=remoteHP[0], dst_port=remoteHP[1],
                    src_ip=origHP[0], src_port=origHP[1])
            return TCPTunnelForwardingChannel(remoteHPNew,
                                              remoteHP,
                                              remoteWindow=remoteWindow,
                                              remoteMaxPacket=remoteMaxPacket)

    return FakeForwardingChannel(remoteHP, remoteWindow=remoteWindow, remoteMaxPacket=remoteMaxPacket)
Example #15
0
 def start(self):
     server = CONFIG.get('output_xmpp', 'server')
     user = CONFIG.get('output_xmpp', 'user')
     password = CONFIG.get('output_xmpp', 'password')
     muc = CONFIG.get('output_xmpp', 'muc')
     resource = ''.join([choice(string.ascii_letters)
                         for i in range(8)])
     jid = user + '/' + resource
     application = service.Application('honeypot')
     self.run(application, jid, password, JID(None, [muc, server, None]), server)
Example #16
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)
Example #17
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)
Example #18
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)
Example #19
0
    def __init__(self, realm):
        self.hostname = CONFIG.get('honeypot', 'hostname')

        try:
            self.arch = random.choice(CONFIG.get('shell', 'arch').split(','))
            # TODO trim whitespace
        except NoOptionError:
            self.arch = 'linux-x64-lsb'

        log.msg("Initialized emulated server as architecture: {}".format(self.arch))
Example #20
0
    def __init__(self, realm):
        self.hostname = CONFIG.get('honeypot', 'hostname')

        try:
            arches = [arch.strip() for arch in CONFIG.get('shell', 'arch').split(',')]
            self.arch = random.choice(arches)
        except NoOptionError:
            self.arch = 'linux-x64-lsb'

        log.msg("Initialized emulated server as architecture: {}".format(self.arch))
Example #21
0
 def __init__(self):
     self.user = CONFIG.get('output_csirtg', 'username') or USERNAME
     self.feed = CONFIG.get('output_csirtg', 'feed') or FEED
     self.token = CONFIG.get('output_csirtg', 'token') or TOKEN
     try:
         self.description = CONFIG.get('output_csirtg', 'description')
     except Exception:
         self.description = DESCRIPTION
     self.context = {}
     self.client = Client(token=self.token)
     cowrie.core.output.Output.__init__(self)
Example #22
0
 def run(self, application, jidstr, password, muc, server):
     self.xmppclient = XMPPClient(JID(jidstr), password)
     if CONFIG.has_option('output_xmpp', 'debug') and \
             CONFIG.getboolean('output_xmpp', 'debug') is True:
         self.xmppclient.logTraffic = True  # DEBUG HERE
     (user, host, resource) = jid.parse(jidstr)
     self.muc = XMPPLoggerProtocol(
         muc, server, user + '-' + resource)
     self.muc.setHandlerParent(self.xmppclient)
     self.xmppclient.setServiceParent(application)
     self.anonymous = True
     self.xmppclient.startService()
Example #23
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)
Example #24
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)
Example #25
0
    def getCommand(self, cmd, paths):
        if not len(cmd.strip()):
            return None
        path = None
        if cmd in self.commands:
            return self.commands[cmd]
        if cmd[0] in ('.', '/'):
            path = self.fs.resolve_path(cmd, self.cwd)
            if not self.fs.exists(path):
                return None
        else:
            for i in [
                '%s/%s' % (self.fs.resolve_path(x, self.cwd), cmd)
                for x in paths
            ]:
                if self.fs.exists(i):
                    path = i
                    break

        txt = os.path.normpath('{}/txtcmds/{}'.format(CONFIG.get('honeypot', 'share_path'), path))
        if os.path.exists(txt) and os.path.isfile(txt):
            return self.txtcmd(txt)

        if path in self.commands:
            return self.commands[path]

        log.msg("Can't find command {}".format(path))
        return None
Example #26
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))
Example #27
0
def operating_system():
    """
    """
    try:
        return CONFIG.get('shell', 'operating_system')
    except NoOptionError:
        return 'GNU/Linux'
Example #28
0
def kernel_build_string():
    """
    """
    try:
        return CONFIG.get('shell', 'kernel_build_string')
    except NoOptionError:
        return '#1 SMP Debian 3.2.68-1+deb7u1'
Example #29
0
def kernel_name():
    """
    """
    try:
        return CONFIG.get('shell', 'kernel_name')
    except NoOptionError:
        return 'Linux'
Example #30
0
def kernel_version():
    """
    """
    try:
        return CONFIG.get('shell', 'kernel_version')
    except NoOptionError:
        return '3.2.0-4-amd64'
Example #31
0
 def __init__(self):
     self.slack_channel = CONFIG.get('output_slack', 'channel')
     self.slack_token = CONFIG.get('output_slack', 'token')
     cowrie.core.output.Output.__init__(self)
Example #32
0
 def __init__(self):
     self.url_base = CONFIG.get('output_cuckoo', 'url_base').encode('utf-8')
     self.api_user = CONFIG.get('output_cuckoo', 'user')
     self.api_passwd = CONFIG.get('output_cuckoo', 'passwd', raw=True)
     self.cuckoo_force = int(CONFIG.getboolean('output_cuckoo', 'force'))
     cowrie.core.output.Output.__init__(self)
Example #33
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)
Example #34
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()
Example #35
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 = 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)
Example #36
0
except:
    import pickle

import os
import time
import fnmatch
import hashlib
import re
import stat
import errno

from twisted.python import log

from cowrie.core.config import CONFIG

PICKLE = pickle.load(open(CONFIG.get('shell', 'filesystem'), 'rb'))

A_NAME, \
    A_TYPE, \
    A_UID, \
    A_GID, \
    A_SIZE, \
    A_MODE, \
    A_CTIME, \
    A_CONTENTS, \
    A_TARGET, \
    A_REALFILE = list(range(0, 10))
T_LINK, \
    T_DIR, \
    T_FILE, \
    T_BLK, \
Example #37
0
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in Cowrie.
        """

        if options["help"] is True:
            print("""Usage: twistd [options] cowrie [-h]
Options:
  -h, --help             print this help message.

Makes a Cowrie SSH/Telnet honeypot.
""")
            sys.exit(1)

        if os.name == 'posix' and os.getuid() == 0:
            print('ERROR: You must not run cowrie as root!')
            sys.exit(1)

        log.msg("Python Version {}".format(str(sys.version).replace('\n', '')))
        log.msg("Twisted Version {}.{}.{}".format(__version__.major, __version__.minor, __version__.micro))

        # ssh is enabled by default
        try:
            enableSSH = CONFIG.getboolean('ssh', 'enabled')
        except (configparser.NoSectionError, configparser.NoOptionError):
            enableSSH = True

        # telnet is disabled by default
        try:
            enableTelnet = CONFIG.getboolean('telnet', 'enabled')
        except (configparser.NoSectionError, configparser.NoOptionError):
            enableTelnet = False

        if enableTelnet is False and enableSSH is False:
            print('ERROR: You must at least enable SSH or Telnet')
            sys.exit(1)

        # Load db loggers
        self.dbloggers = []
        for x in CONFIG.sections():
            if not x.startswith('database_'):
                continue
            engine = x.split('_')[1]
            try:
                dblogger = __import__('cowrie.dblog.{}'.format(engine),
                                      globals(), locals(), ['dblog']).DBLogger()
                log.addObserver(dblogger.emit)
                self.dbloggers.append(dblogger)
                log.msg("Loaded dblog engine: {}".format(engine))
            except:
                log.err()
                log.msg("Failed to load dblog engine: {}".format(engine))

        # Load output modules
        self.output_plugins = []
        for x in CONFIG.sections():
            if not x.startswith('output_'):
                continue
            if CONFIG.getboolean(x, 'enabled') is False:
                continue
            engine = x.split('_')[1]
            try:
                output = __import__('cowrie.output.{}'.format(engine),
                                    globals(), locals(), ['output']).Output()
                log.addObserver(output.emit)
                self.output_plugins.append(output)
                log.msg("Loaded output engine: {}".format(engine))
            except ImportError as e:
                log.err("Failed to load output engine: {} due to ImportError: {}".format(engine, e))
                log.msg("Please install the dependencies for {} listed in requirements-output.txt".format(engine))
            except Exception:
                log.err()
                log.msg("Failed to load output engine: {}".format(engine))

        topService = service.MultiService()
        application = service.Application('cowrie')
        topService.setServiceParent(application)

        if enableSSH:
            factory = cowrie.ssh.factory.CowrieSSHFactory()
            factory.tac = self
            factory.portal = portal.Portal(core.realm.HoneyPotRealm())
            factory.portal.registerChecker(
                core.checkers.HoneypotPublicKeyChecker())
            factory.portal.registerChecker(
                core.checkers.HoneypotPasswordChecker())

            if CONFIG.has_option('honeypot', 'auth_none_enabled') and \
                    CONFIG.getboolean('honeypot', 'auth_none_enabled') is True:
                factory.portal.registerChecker(
                    core.checkers.HoneypotNoneChecker())

            if CONFIG.has_section('ssh'):
                listen_endpoints = get_endpoints_from_section(CONFIG, 'ssh', 2222)
            else:
                listen_endpoints = get_endpoints_from_section(CONFIG, 'honeypot', 2222)

            create_endpoint_services(reactor, topService, listen_endpoints, factory)

        if enableTelnet:
            f = cowrie.telnet.transport.HoneyPotTelnetFactory()
            f.tac = self
            f.portal = portal.Portal(core.realm.HoneyPotRealm())
            f.portal.registerChecker(core.checkers.HoneypotPasswordChecker())

            listen_endpoints = get_endpoints_from_section(CONFIG, 'telnet', 2223)
            create_endpoint_services(reactor, topService, listen_endpoints, f)

        return topService
Example #38
0
 def __init__(self):
     self.userdb = []
     self.userdb_file = '%s/userdb.txt' % CONFIG.get('honeypot', 'data_path')
     self.load()