def checkUserPass(self, theusername, thepassword, ip): # UserDB is the default auth_class authname = auth.UserDB parameters = None # Is the auth_class defined in the config file? if config().has_option('honeypot', 'auth_class'): authclass = config().get('honeypot', 'auth_class') # Check if authclass exists in this module if hasattr(modules[__name__], authclass): authname = getattr(modules[__name__], authclass) # Are there auth_class parameters? if config().has_option('honeypot', 'auth_class_parameters'): parameters = config().get('honeypot', 'auth_class_parameters') else: log.msg('auth_class: %s not found in %s' % (authclass, __name__)) if parameters: theauth = authname(parameters) else: theauth = authname() if theauth.checklogin(theusername, thepassword, ip): log.msg('login attempt [%s]/[%s] succeeded' % (theusername, thepassword)) return True else: log.msg('login attempt [%s]/[%s] failed' % (theusername, thepassword)) return False
def get_report(resource, filename, dl_url='unknown', protocol=None, origin=None): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": resource, "apikey": apikey } data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() j = simplejson.loads(json) if j['response_code'] == 1: # file known cfg = config() args = {'shasum': resource, 'url': dl_url, 'permalink': j['permalink']} # we don't use dispatcher, so this check is needed if cfg.has_section('database_mysql'): mysql_logger = cowrie.dblog.mysql.DBLogger(cfg) mysql_logger.handleVirustotal(args) args_scan = {'shasum': resource, 'json': json} mysql_logger.handleVirustotalScan(args_scan) if origin == 'db': # we don't use dispatcher, so this check is needed if cfg.has_section('database_textlog'): text_logger = cowrie.dblog.textlog.DBLogger(cfg) text_logger.handleVirustotalLog('log_from database', args) else: msg = 'Virustotal report of %s [%s] at %s' % \ (resource, dl_url, j['permalink']) # we need to print msg, because logs from SFTP are dispatched this way print msg if protocol: protocol.logDispatch(msg) elif j['response_code'] == 0: # file not known if origin == 'db': return j['response_code'] msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg host = "www.virustotal.com" url = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", apikey)] filepath = "dl/%s" % resource file_to_send = open(filepath, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, url, fields, files) print json msg = 'insert to Virustotal backlog %s [%s]' % \ (resource, dl_url) print msg virustotal_backlogs.insert(resource, dl_url) else: msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg return j['response_code']
def checkUserPass(self, theusername, thepassword, ip): # UserDB is the default auth_class authname = auth.UserDB parameters = None # Is the auth_class defined in the config file? if config().has_option('honeypot', 'auth_class'): authclass = config().get('honeypot', 'auth_class') # Check if authclass exists in this module if hasattr(modules[__name__], authclass): authname = getattr(modules[__name__], authclass) # Are there auth_class parameters? if config().has_option('honeypot', 'auth_class_parameters'): parameters = config().get('honeypot', 'auth_class_parameters') else: log.msg('auth_class: %s not found in %s' % (authclass, __name__)) if parameters: theauth = authname(parameters) else: theauth = authname() if theauth.checklogin(theusername, thepassword, ip): log.msg( 'login attempt [%s]/[%s] succeeded' % (theusername, thepassword) ) return True else: log.msg( 'login attempt [%s]/[%s] failed' % (theusername, thepassword) ) return False
def connectionMade(self): transport = self.transport.session.conn.transport transport.ttylog_file = '%s/tty/%s-%s.log' % \ (config().get('honeypot', 'log_path'), time.strftime('%Y%m%d-%H%M%S'), int(random.random() * 10000)) print 'Opening TTY log: %s' % transport.ttylog_file ttylog.ttylog_open(transport.ttylog_file, time.time()) transport.ttylog_open = True insults.ServerProtocol.connectionMade(self) transport.stdinlog_file = '%s/tty/%s-%s.log' % \ (config().get('honeypot', 'download_path'), time.strftime('%Y%m%d-%H%M%S'), int(random.random() * 10000)) transport.stdinlog_open = True
def make_comment(resource): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/comments/put" parameters = {"resource": resource, "comment": "captured by ssh honeypot", "apikey": apikey} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() print json
def insert(shasum, url): p = config().get('honeypot', 'log_path') + '/backlogs.sqlite' dbh = sqlite3.connect(p) cursor = dbh.cursor() dt = datetime.datetime.now() timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") cursor.execute(""" INSERT INTO backlogfiles (shasum, url, timestamp) VALUES (?,?,?) """, (shasum, url, timestamp)) dbh.commit() cursor.close()
def insert(shasum, url): p = config().get('honeypot', 'log_path') + '/backlogs.sqlite' dbh = sqlite3.connect(p) cursor = dbh.cursor() dt = datetime.datetime.now() timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") cursor.execute( """ INSERT INTO backlogfiles (shasum, url, timestamp) VALUES (?,?,?) """, (shasum, url, timestamp)) dbh.commit() cursor.close()
def make_comment(resource): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/comments/put" parameters = { "resource": resource, "comment": "captured by ssh honeypot", "apikey": apikey } data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() print json
def __init__(self, parameters): # Default values self.mintry, self.maxtry, self.maxcache = 2, 5, 10 parlist = parameters.split(',') if len(parlist) == 3: self.mintry = int(parlist[0]) self.maxtry = int(parlist[1]) self.maxcache = int(parlist[2]) if self.maxtry < self.mintry: self.maxtry = self.mintry + 1 log.msg('maxtry < mintry, adjusting maxtry to: %d' % self.maxtry) self.uservar = {} self.uservar_file = '%s/uservar.json' % (config().get('honeypot', 'data_path')) self.loadvars()
def file_contents(self, target, count=0): if count > 10: raise TooManyLevels path = self.resolve_path(target, os.path.dirname(target)) print '%s resolved into %s' % (target, path) if not path or not self.exists(path): raise FileNotFound f = self.getfile(path) if f[A_TYPE] == T_LINK: return self.file_contents(f[A_TARGET], count + 1) realfile = self.realfile(f, '%s/%s' % \ (config().get('honeypot', 'contents_path'), path)) if realfile: return file(realfile, 'rb').read()
def file_contents(self, target, count = 0): if count > 10: raise TooManyLevels path = self.resolve_path(target, os.path.dirname(target)) print '%s resolved into %s' % (target, path) if not path or not self.exists(path): raise FileNotFound f = self.getfile(path) if f[A_TYPE] == T_LINK: return self.file_contents(f[A_TARGET], count + 1) realfile = self.realfile(f, '%s/%s' % \ (config().get('honeypot', 'contents_path'), path)) if realfile: return file(realfile, 'rb').read()
def call(self): fn = '%s/lastlog.txt' % (config().get('honeypot', 'data_path'),) if not os.path.exists(fn): return l = list(self.args) numlines = 25 while len(l): arg = l.pop(0) if not arg.startswith('-'): continue elif arg[1:].isdigit(): numlines = int(arg[1:]) elif arg == '-n' and len(l) and l[0].isdigit(): numlines = int(l.pop(0)) data = utils.tail(file(fn), numlines) self.writeln(''.join(data))
def __init__(self, parameters): # Default values self.mintry, self.maxtry, self.maxcache = 2, 5, 10 parlist = parameters.split(',') if len(parlist) == 3: self.mintry = int(parlist[0]) self.maxtry = int(parlist[1]) self.maxcache = int(parlist[2]) if self.maxtry < self.mintry: self.maxtry = self.mintry + 1 log.msg('maxtry < mintry, adjusting maxtry to: %d' % self.maxtry) self.uservar = {} self.uservar_file = '%s/uservar.json' % (config().get( 'honeypot', 'data_path')) self.loadvars()
def call(self): fn = '%s/lastlog.txt' % (config().get('honeypot', 'data_path'), ) if not os.path.exists(fn): return l = list(self.args) numlines = 25 while len(l): arg = l.pop(0) if not arg.startswith('-'): continue elif arg[1:].isdigit(): numlines = int(arg[1:]) elif arg == '-n' and len(l) and l[0].isdigit(): numlines = int(l.pop(0)) data = utils.tail(file(fn), numlines) self.writeln(''.join(data))
def call(self): cfg = config() self.exit_jail = False if cfg.has_option('honeypot', 'exit_jail'): if (cfg.get('honeypot', 'exit_jail') == "true"): self.exit_jail = True if 'PuTTY' in self.honeypot.clientVersion or \ 'libssh' in self.honeypot.clientVersion or \ 'sshlib' in self.honeypot.clientVersion or \ self.exit_jail is False: self.honeypot.terminal.loseConnection() return self.writeln('Connection to server closed.') self.honeypot.hostname = 'localhost' self.honeypot.cwd = '/root' if not self.fs.exists(self.honeypot.cwd): self.honeypot.cwd = '/'
def check(): p = config().get('honeypot', 'log_path') + '/backlogs.sqlite' dbh = sqlite3.connect(p) cursor = dbh.cursor() r = cursor.execute(""" SELECT shasum, url, timestamp FROM backlogfiles""") for record in r: shasum = format(record[0]) url = format(record[1]) result = virustotal.get_report(shasum, None, url, None, 'db') if result == 1: print "Virustotal backlog record " + shasum + " will be deleted" cursor.execute(""" DELETE FROM backlogfiles WHERE shasum = ?""", (shasum,) ) virustotal.make_comment(shasum) dbh.commit() cursor.close()
def check(): p = config().get('honeypot', 'log_path') + '/backlogs.sqlite' dbh = sqlite3.connect(p) cursor = dbh.cursor() r = cursor.execute(""" SELECT shasum, url, timestamp FROM backlogfiles""") for record in r: shasum = format(record[0]) url = format(record[1]) result = virustotal.get_report(shasum, None, url, None, 'db') if result == 1: print "Virustotal backlog record " + shasum + " will be deleted" cursor.execute( """ DELETE FROM backlogfiles WHERE shasum = ?""", (shasum, )) virustotal.make_comment(shasum) dbh.commit() cursor.close()
def open(self, filename, openFlags, mode): print "fs.open %s" % filename if (openFlags & os.O_APPEND == os.O_APPEND): print "fs.open append" if (openFlags & os.O_CREAT == os.O_CREAT): print "fs.open creat" if (openFlags & os.O_TRUNC == os.O_TRUNC): print "fs.open trunc" if (openFlags & os.O_EXCL == os.O_EXCL): print "fs.open excl" # treat O_RDWR same as O_WRONLY if openFlags & os.O_WRONLY == os.O_WRONLY or openFlags & os.O_RDWR == os.O_RDWR: # strip executable bit hostmode = mode & ~(111) safeoutfile = '%s/%s_%s' % \ (config().get('honeypot', 'download_path'), time.strftime('%Y%m%d%H%M%S'), re.sub('[^A-Za-z0-9]', '_', filename)) print "fs.open file for writing, saving to %s" % safeoutfile self.mkfile(filename, 0, 0, 0, stat.S_IFREG | mode) fd = os.open(safeoutfile, openFlags, hostmode) self.update_realfile(self.getfile(filename), safeoutfile) return (fd, safeoutfile) elif openFlags & os.O_RDONLY == os.O_RDONLY: print "fs.open rdonly" return (None, None) return (None, None)
def get_report(resource, filename, dl_url='unknown', protocol=None, origin=None): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": resource, "apikey": apikey} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() j = simplejson.loads(json) if j['response_code'] == 1: # file known cfg = config() args = {'shasum': resource, 'url': dl_url, 'permalink': j['permalink']} # we don't use dispatcher, so this check is needed if cfg.has_section('database_mysql'): mysql_logger = cowrie.dblog.mysql.DBLogger(cfg) mysql_logger.handleVirustotal(args) args_scan = {'shasum': resource, 'json': json} mysql_logger.handleVirustotalScan(args_scan) if origin == 'db': # we don't use dispatcher, so this check is needed if cfg.has_section('database_textlog'): text_logger = cowrie.dblog.textlog.DBLogger(cfg) text_logger.handleVirustotalLog('log_from database', args) else: msg = 'Virustotal report of %s [%s] at %s' % \ (resource, dl_url, j['permalink']) # we need to print msg, because logs from SFTP are dispatched this way print msg if protocol: protocol.logDispatch(msg) elif j['response_code'] == 0: # file not known if origin == 'db': return j['response_code'] msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg host = "www.virustotal.com" url = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", apikey)] filepath = "dl/%s" % resource file_to_send = open(filepath, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, url, fields, files) print json msg = 'insert to Virustotal backlog %s [%s]' % \ (resource, dl_url) print msg virustotal_backlogs.insert(resource, dl_url) else: msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg return j['response_code']
def __init__(self): self.userdb = [] self.userdb_file = '%s/userdb.txt' % (config().get( 'honeypot', 'data_path'), ) self.load()
def __init__(self): self.userdb = [] self.userdb_file = '%s/userdb.txt' % (config().get('honeypot', 'data_path'),) self.load()