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
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
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
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
def __init__(self): self.apiKey = CONFIG.get('output_virustotal', 'api_key') self.debug = CONFIG.getboolean('output_virustotal', 'debug', fallback=False) self.upload = CONFIG.getboolean('output_virustotal', 'upload', fallback=True) self.comment = CONFIG.getboolean('output_virustotal', 'comment', fallback=True) self.commenttext = CONFIG.get('output_virustotal', 'commenttext', fallback=COMMENT) cowrie.core.output.Output.__init__(self)
def __init__(self): self.apiKey = CONFIG.get('output_virustotal', 'api_key') self.debug = CONFIG.getboolean('output_virustotal', 'debug', fallback=False) self.upload = CONFIG.getboolean('output_virustotal', 'upload', fallback=True) self.comment = CONFIG.getboolean('output_virustotal', 'comment', fallback=True) self.scan_file = CONFIG.getboolean('output_virustotal', 'scan_file', fallback=True) self.scan_url = CONFIG.getboolean('output_virustotal', 'scan_url', fallback=False) self.commenttext = CONFIG.get('output_virustotal', 'commenttext', fallback=COMMENT) cowrie.core.output.Output.__init__(self)
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)
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()
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)
def __init__(self): try: self.debug = CONFIG.getboolean('output_mysql', 'debug') except Exception: self.debug = False cowrie.core.output.Output.__init__(self)
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()
def __init__(self): self.apiKey = CONFIG.get('output_greynoise', 'api_key', fallback=None) self.tags = CONFIG.get('output_greynoise', 'tags', fallback="all").split(",") self.debug = CONFIG.getboolean('output_greynoise', 'debug', fallback=False) cowrie.core.output.Output.__init__(self)
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 = {}
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)
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)
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)
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)
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()
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()
def serviceStarted(self): self.interfaceToMethod[credentials.IUsername] = b'none' self.interfaceToMethod[credentials.IUsernamePasswordIP] = b'password' keyboard = CONFIG.getboolean('ssh', 'auth_keyboard_interactive_enabled', fallback=False) if keyboard is True: self.interfaceToMethod[credentials. IPluggableAuthenticationModulesIP] = ( b'keyboard-interactive') self.bannerSent = False self._pamDeferred = None userauth.SSHUserAuthServer.serviceStarted(self)
def serviceStarted(self): self.interfaceToMethod[credentials.IUsername] = b'none' self.interfaceToMethod[credentials.IUsernamePasswordIP] = b'password' keyboard = CONFIG.getboolean('ssh', 'auth_keyboard_interactive_enabled', fallback=False) if keyboard is True: self.interfaceToMethod[ credentials.IPluggableAuthenticationModulesIP] = ( b'keyboard-interactive') self.bannerSent = False self._pamDeferred = None userauth.SSHUserAuthServer.serviceStarted(self)
def __init__(self, username, server): avatar.ConchUser.__init__(self) self.username = username self.server = server self.channelLookup[b'session'] = proxysession.ProxySSHSession # TODO: Is SFTP still supported? Check git commit 30949e0 for cleaned up code # SSH forwarding disabled only when option is explicitly set self.channelLookup[b'direct-tcpip'] = forwarding.cowrieOpenConnectForwardingClient try: if CONFIG.getboolean('ssh', 'forwarding') is False: del self.channelLookup[b'direct-tcpip'] except NoOptionError: pass
def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(JID(jidstr), password) if CONFIG.has_option('database_xmpp', 'debug') and CONFIG.getboolean( 'database_xmpp', 'debug'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, list(channels.keys()), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService()
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)
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
def __init__(self, username, server): avatar.ConchUser.__init__(self) self.username = username self.server = server self.channelLookup[b'session'] = proxysession.ProxySSHSession # 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
def __init__(self): self.enabled = CONFIG.getboolean('output_malshare', 'enabled') cowrie.core.output.Output.__init__(self)
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)
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)
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) tz = CONFIG.get('honeypot', 'timezone', fallback='UTC') # `system` means use the system time zone if tz != 'system': os.environ['TZ'] = tz 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 enableSSH = CONFIG.getboolean('ssh', 'enabled', fallback=True) # telnet is disabled by default enableTelnet = CONFIG.getboolean('telnet', 'enabled', fallback=False) if enableTelnet is False and enableSSH is False: print('ERROR: You must at least enable SSH or Telnet') sys.exit(1) # 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.getboolean('honeypot', 'auth_none_enabled', fallback=False) 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
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 Exception: 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
def __init__(self): self.enabled = CONFIG.getboolean('output_malshare', 'enabled') self.host = CONFIG.get('output_remotesyslog', 'host') self.port = CONFIG.get('output_remotesyslog', 'port') self.server = CONFIG.get('output_remotesyslog', 'server') cowrie.core.output.Output.__init__(self)
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)
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)