From 03597fd5f2c2c84922249eeeb64169f1d9451e25 Mon Sep 17 00:00:00 2001 From: Michel Oosterhof Date: Wed, 4 Nov 2015 18:53:05 +0400 Subject: [PATCH] rename variable 'honeypot' to 'protocol'. it is the protocol. --- cowrie/commands/adduser.py | 4 +- cowrie/commands/apt.py | 2 +- cowrie/commands/base.py | 80 +++++++++++++------------- cowrie/commands/curl.py | 18 +++--- cowrie/commands/ethtool.py | 8 +-- cowrie/commands/fs.py | 26 ++++----- cowrie/commands/gcc.py | 10 ++-- cowrie/commands/ifconfig.py | 6 +- cowrie/commands/iptables.py | 8 +-- cowrie/commands/last.py | 2 +- cowrie/commands/ls.py | 18 +++--- cowrie/commands/netstat.py | 36 ++++++------ cowrie/commands/nohup.py | 2 +- cowrie/commands/scp.py | 22 +++---- cowrie/commands/ssh.py | 14 ++--- cowrie/commands/tar.py | 8 +-- cowrie/commands/uname.py | 2 +- cowrie/commands/wget.py | 16 +++--- cowrie/core/honeypot.py | 111 +++++++++++++++++------------------- cowrie/core/protocol.py | 4 +- cowrie/core/realm.py | 13 +++-- cowrie/core/server.py | 10 +++- cowrie/core/ssh.py | 8 +-- 23 files changed, 216 insertions(+), 212 deletions(-) diff --git a/cowrie/commands/adduser.py b/cowrie/commands/adduser.py index bd980e6..18ee68e 100644 --- a/cowrie/commands/adduser.py +++ b/cowrie/commands/adduser.py @@ -64,7 +64,7 @@ class command_adduser(HoneyPotCommand): l = self.output[self.item] self.write(l[1] % {'username': self.username}) if l[0] == O_P: - self.honeypot.password_input = True + self.protocol.password_input = True return if l[0] == O_Q: return @@ -88,7 +88,7 @@ class command_adduser(HoneyPotCommand): else: self.item += 1 self.schedule_next() - self.honeypot.password_input = False + self.protocol.password_input = False commands['/usr/sbin/adduser'] = command_adduser commands['/usr/sbin/useradd'] = command_adduser diff --git a/cowrie/commands/apt.py b/cowrie/commands/apt.py index ab0adff..1120271 100644 --- a/cowrie/commands/apt.py +++ b/cowrie/commands/apt.py @@ -156,7 +156,7 @@ pages for more information and options. (p, packages[p]['version'])) self.fs.mkfile('/usr/bin/%s' % p, 0, 0, random.randint(10000, 90000), 33188) - self.honeypot.commands['/usr/bin/%s' % p] = \ + self.protocol.commands['/usr/bin/%s' % p] = \ command_faked_package_class_factory.getCommand(p) yield self.sleep(2) self.exit() diff --git a/cowrie/commands/base.py b/cowrie/commands/base.py index bb2f34e..e138f52 100644 --- a/cowrie/commands/base.py +++ b/cowrie/commands/base.py @@ -17,7 +17,7 @@ commands = {} class command_whoami(HoneyPotCommand): def call(self): - self.writeln(self.honeypot.user.username) + self.writeln(self.protocol.user.username) commands['/usr/bin/whoami'] = command_whoami commands['/usr/bin/users'] = command_whoami @@ -25,9 +25,9 @@ class command_uptime(HoneyPotCommand): def call(self): if len(self.args): secs = int(self.args[0]) - self.honeypot.uptime(time.time() - secs) + self.protocol.uptime(time.time() - secs) self.writeln(' %s up %s, 1 user, load average: 0.00, 0.00, 0.00' % \ - (time.strftime('%H:%M:%S'), utils.uptime(self.honeypot.uptime()))) + (time.strftime('%H:%M:%S'), utils.uptime(self.protocol.uptime()))) commands['/usr/bin/uptime'] = command_uptime class command_help(HoneyPotCommand): @@ -83,21 +83,21 @@ commands['help'] = command_help class command_w(HoneyPotCommand): def call(self): self.writeln(' %s up %s, 1 user, load average: 0.00, 0.00, 0.00' % \ - (time.strftime('%H:%M:%S'), utils.uptime(self.honeypot.uptime()))) + (time.strftime('%H:%M:%S'), utils.uptime(self.protocol.uptime()))) self.writeln('USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT') self.writeln('%-8s pts/0 %s %s 0.00s 0.00s 0.00s w' % \ - (self.honeypot.user.username, - self.honeypot.clientIP[:17].ljust(17), - time.strftime('%H:%M', time.localtime(self.honeypot.logintime)))) + (self.protocol.user.username, + self.protocol.clientIP[:17].ljust(17), + time.strftime('%H:%M', time.localtime(self.protocol.logintime)))) commands['/usr/bin/w'] = command_w class command_who(HoneyPotCommand): def call(self): self.writeln('%-8s pts/0 %s %s (%s)' % \ - (self.honeypot.user.username, - time.strftime('%Y-%m-%d', time.localtime(self.honeypot.logintime)), - time.strftime('%H:%M', time.localtime(self.honeypot.logintime)), - self.honeypot.clientIP)) + (self.protocol.user.username, + time.strftime('%Y-%m-%d', time.localtime(self.protocol.logintime)), + time.strftime('%H:%M', time.localtime(self.protocol.logintime)), + self.protocol.clientIP)) commands['/usr/bin/who'] = command_who class command_echo(HoneyPotCommand): @@ -121,33 +121,33 @@ commands['/bin/echo'] = command_echo # for testing purposes class command_exxxit(HoneyPotCommand): def call(self): - if self.honeypot.clientIP.startswith('127.0.0.'): - self.honeypot.terminal.loseConnection() + if self.protocol.clientIP.startswith('127.0.0.'): + self.protocol.terminal.loseConnection() else: self.writeln('bash: exxxit: command not found') commands['exxxit'] = command_exxxit class command_exit(HoneyPotCommand): def call(self): - self.honeypot.terminal.loseConnection() + self.protocol.terminal.loseConnection() return commands['exit'] = command_exit commands['logout'] = command_exit class command_clear(HoneyPotCommand): def call(self): - self.honeypot.terminal.reset() + self.protocol.terminal.reset() commands['/usr/bin/clear'] = command_clear commands['/usr/bin/reset'] = command_clear class command_hostname(HoneyPotCommand): def call(self): - self.writeln(self.honeypot.hostname) + self.writeln(self.protocol.hostname) commands['/bin/hostname'] = command_hostname class command_ps(HoneyPotCommand): def call(self): - user = self.honeypot.user.username + user = self.protocol.user.username args = '' if len(self.args): args = self.args[0].strip() @@ -209,7 +209,7 @@ commands['/bin/ps'] = command_ps class command_id(HoneyPotCommand): def call(self): - u = self.honeypot.user + u = self.protocol.user self.writeln('uid=%d(%s) gid=%d(%s) groups=%d(%s)' % \ (u.uid, u.username, u.gid, u.username, u.gid, u.username)) commands['/usr/bin/id'] = command_id @@ -217,7 +217,7 @@ commands['/usr/bin/id'] = command_id class command_passwd(HoneyPotCommand): def start(self): self.write('Enter new UNIX password: ') - self.honeypot.password_input = True + self.protocol.password_input = True self.callbacks = [self.ask_again, self.finish] self.passwd = None @@ -226,16 +226,16 @@ class command_passwd(HoneyPotCommand): self.write('Retype new UNIX password: ') def finish(self, line): - self.honeypot.password_input = False + self.protocol.password_input = False if line != self.passwd or self.passwd == '*': self.writeln('Sorry, passwords do not match') self.exit() return - userdb = UserDB(self.honeypot.env.cfg) - userdb.adduser(self.honeypot.user.username, - self.honeypot.user.uid, self.passwd) + userdb = UserDB(self.protocol.env.cfg) + userdb.adduser(self.protocol.user.username, + self.protocol.user.uid, self.passwd) self.writeln('passwd: password updated successfully') self.exit() @@ -274,7 +274,7 @@ class command_shutdown(HoneyPotCommand): self.nextLine() self.writeln( 'Broadcast message from root@%s (pts/0) (%s):' % \ - (self.honeypot.hostname, time.ctime())) + (self.protocol.hostname, time.ctime())) self.nextLine() self.writeln('The system is going down for maintenance NOW!') reactor.callLater(3, self.finish) @@ -283,7 +283,7 @@ class command_shutdown(HoneyPotCommand): self.nextLine() self.writeln( 'Broadcast message from root@%s (pts/0) (%s):' % \ - (self.honeypot.hostname, time.ctime())) + (self.protocol.hostname, time.ctime())) self.nextLine() self.writeln('The system is going down for reboot NOW!') reactor.callLater(3, self.finish) @@ -294,10 +294,10 @@ class command_shutdown(HoneyPotCommand): def finish(self): 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 = '/' + self.protocol.hostname = 'localhost' + self.protocol.cwd = '/root' + if not self.fs.exists(self.protocol.cwd): + self.protocol.cwd = '/' self.exit() commands['/sbin/shutdown'] = command_shutdown commands['/sbin/poweroff'] = command_shutdown @@ -309,29 +309,29 @@ class command_reboot(HoneyPotCommand): self.nextLine() self.writeln( 'Broadcast message from root@%s (pts/0) (%s):' % \ - (self.honeypot.hostname, time.ctime())) + (self.protocol.hostname, time.ctime())) self.nextLine() self.writeln('The system is going down for reboot NOW!') reactor.callLater(3, self.finish) def finish(self): 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 = '/' - self.honeypot.uptime(time.time()) + self.protocol.hostname = 'localhost' + self.protocol.cwd = '/root' + if not self.fs.exists(self.protocol.cwd): + self.protocol.cwd = '/' + self.protocol.uptime(time.time()) self.exit() commands['/sbin/reboot'] = command_reboot class command_history(HoneyPotCommand): def call(self): if len(self.args) and self.args[0] == '-c': - self.honeypot.historyLines = [] - self.honeypot.historyPosition = 0 + self.protocol.historyLines = [] + self.protocol.historyPosition = 0 return count = 1 - for l in self.honeypot.historyLines: + for l in self.protocol.historyLines: self.writeln(' %s %s' % (str(count).rjust(4), l)) count += 1 commands['history'] = command_history @@ -358,7 +358,7 @@ commands['/usr/bin/yes'] = command_yes class command_sh(HoneyPotCommand): def call(self): if len(self.args) and self.args[0].strip() == '-c': - self.honeypot.cmdstack[0].cmdpending.append( + self.protocol.cmdstack[0].cmdpending.append( ' '.join(self.args[1:])) commands['/bin/bash'] = command_sh commands['/bin/sh'] = command_sh @@ -371,7 +371,7 @@ class command_chmod(HoneyPotCommand): self.writeln('Try chmod --help for more information.') return for arg in self.args[1:]: - path = self.fs.resolve_path(arg, self.honeypot.cwd) + path = self.fs.resolve_path(arg, self.protocol.cwd) if not self.fs.exists(path): self.writeln( 'chmod: cannot access %s: No such file or directory' % \ diff --git a/cowrie/commands/curl.py b/cowrie/commands/curl.py index b20fd0c..61f7a93 100644 --- a/cowrie/commands/curl.py +++ b/cowrie/commands/curl.py @@ -80,7 +80,7 @@ class command_curl(HoneyPotCommand): return if outfile: - outfile = self.fs.resolve_path(outfile, self.honeypot.cwd) + outfile = self.fs.resolve_path(outfile, self.protocol.cwd) path = os.path.dirname(outfile) if not path or \ not self.fs.exists(path) or \ @@ -92,7 +92,7 @@ class command_curl(HoneyPotCommand): self.url = url self.limit_size = 0 - cfg = self.honeypot.env.cfg + cfg = self.protocol.env.cfg if cfg.has_option('honeypot', 'download_limit_size'): self.limit_size = int(cfg.get('honeypot', 'download_limit_size')) @@ -128,8 +128,8 @@ class command_curl(HoneyPotCommand): factory = HTTPProgressDownloader( self, fakeoutfile, url, outputfile, *args, **kwargs) out_addr = None - if self.honeypot.env.cfg.has_option('honeypot', 'out_addr'): - out_addr = (self.honeypot.env.cfg.get('honeypot', 'out_addr'), 0) + if self.protocol.env.cfg.has_option('honeypot', 'out_addr'): + out_addr = (self.protocol.env.cfg.get('honeypot', 'out_addr'), 0) if scheme == 'https': contextFactory = ssl.ClientContextFactory() @@ -160,7 +160,7 @@ class command_curl(HoneyPotCommand): os.remove(self.safeoutfile) log.msg("Not storing duplicate content " + shasum) - self.honeypot.logDispatch(format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', + self.protocol.logDispatch(format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', eventid='KIPP0007', url=self.url, outfile=hash_path, shasum=shasum) log.msg(format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', @@ -235,7 +235,7 @@ class HTTPProgressDownloader(client.HTTPDownloader): self.fileName = os.path.devnull self.nomore = True #self.curl.writeln('Saving to: `%s' % self.fakeoutfile) - #self.curl.honeypot.terminal.nextLine() + #self.curl.protocol.terminal.nextLine() if self.fakeoutfile: self.curl.writeln(' % Total % Received % Xferd Average Speed Time Time Time Current') @@ -284,8 +284,8 @@ class HTTPProgressDownloader(client.HTTPDownloader): # ('%s>' % (38 * '='), # splitthousands(str(int(self.totallength))).ljust(12), # self.speed / 1000)) - #self.curl.honeypot.terminal.nextLine() - #self.curl.honeypot.terminal.nextLine() + #self.curl.protocol.terminal.nextLine() + #self.curl.protocol.terminal.nextLine() #self.curl.writeln( # '%s (%d KB/s) - `%s\' saved [%d/%d]' % \ # (time.strftime('%Y-%m-%d %H:%M:%S'), @@ -296,7 +296,7 @@ class HTTPProgressDownloader(client.HTTPDownloader): self.curl.write("\r100 %d 100 %d 0 0 %d 0 --:--:-- --:--:-- --:--:-- %d" % \ (self.currentlength, self.currentlength , 63673, 65181) ) - self.curl.honeypot.terminal.nextLine() + self.curl.protocol.terminal.nextLine() self.curl.fs.mkfile(self.fakeoutfile, 0, 0, self.totallength, 33188) self.curl.fs.update_realfile( diff --git a/cowrie/commands/ethtool.py b/cowrie/commands/ethtool.py index d43ce5d..6d621c5 100644 --- a/cowrie/commands/ethtool.py +++ b/cowrie/commands/ethtool.py @@ -20,15 +20,15 @@ class command_ethtool(HoneyPotCommand): def do_ethtool_help(self): """No real help output.""" - self.honeypot.writeln("""ethtool: bad command line argument(s) + self.protocol.writeln("""ethtool: bad command line argument(s) For more information run ethtool -h """) def do_ethtool_lo(self): - self.honeypot.writeln("""Settings for lo: + self.protocol.writeln("""Settings for lo: Link detected: yes""") def do_ethtool_eth0(self): - self.honeypot.writeln("""Settings for eth0: + self.protocol.writeln("""Settings for eth0: Supported ports: [ TP MII ] Supported link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full @@ -58,7 +58,7 @@ Current message level: 0x00000033 (51) Link detected: yes""") def do_ethtool_eth1(self): - self.honeypot.writeln("""Settings for eth1: + self.protocol.writeln("""Settings for eth1: Cannot get device settings: No such device Cannot get wake-on-lan settings: No such device Cannot get message level: No such device diff --git a/cowrie/commands/fs.py b/cowrie/commands/fs.py index c26d12c..ec6b537 100644 --- a/cowrie/commands/fs.py +++ b/cowrie/commands/fs.py @@ -16,7 +16,7 @@ class command_cat(HoneyPotCommand): pass else: for arg in self.args: - path = self.fs.resolve_path(arg, self.honeypot.cwd) + path = self.fs.resolve_path(arg, self.protocol.cwd) if self.fs.isdir(path): self.writeln('cat: %s: Is a directory' % (arg,)) continue @@ -52,7 +52,7 @@ class command_tail(HoneyPotCommand): self.n = int(opt[1]) for arg in args: - path = self.fs.resolve_path(arg, self.honeypot.cwd) + path = self.fs.resolve_path(arg, self.protocol.cwd) if self.fs.isdir(path): self.writeln("tail: error reading `%s': Is a directory" % (arg,)) continue @@ -97,7 +97,7 @@ class command_head(HoneyPotCommand): self.n = int(opt[1]) for arg in args: - path = self.fs.resolve_path(arg, self.honeypot.cwd) + path = self.fs.resolve_path(arg, self.protocol.cwd) if self.fs.isdir(path): self.writeln("head: error reading `%s': Is a directory" % (arg,)) continue @@ -124,11 +124,11 @@ commands['/bin/head'] = command_head class command_cd(HoneyPotCommand): def call(self): if not self.args or self.args[0] == "~": - path = self.honeypot.user.home + path = self.protocol.user.home else: path = self.args[0] try: - newpath = self.fs.resolve_path(path, self.honeypot.cwd) + newpath = self.fs.resolve_path(path, self.protocol.cwd) inode = self.fs.getfile(newpath) except: newdir = None @@ -141,7 +141,7 @@ class command_cd(HoneyPotCommand): if inode[A_TYPE] != T_DIR: self.writeln('bash: cd: %s: Not a directory' % path) return - self.honeypot.cwd = newpath + self.protocol.cwd = newpath commands['cd'] = command_cd class command_rm(HoneyPotCommand): @@ -151,7 +151,7 @@ class command_rm(HoneyPotCommand): if f.startswith('-') and 'r' in f: recursive = True for f in self.args: - path = self.fs.resolve_path(f, self.honeypot.cwd) + path = self.fs.resolve_path(f, self.protocol.cwd) try: dir = self.fs.get_path('/'.join(path.split('/')[:-1])) except (IndexError, FileNotFound): @@ -188,7 +188,7 @@ class command_cp(HoneyPotCommand): recursive = True def resolv(path): - return self.fs.resolve_path(path, self.honeypot.cwd) + return self.fs.resolve_path(path, self.protocol.cwd) if len(args) < 2: self.writeln("cp: missing destination file operand after `%s'" % \ @@ -252,7 +252,7 @@ class command_mv(HoneyPotCommand): self.exit() def resolv(path): - return self.fs.resolve_path(path, self.honeypot.cwd) + return self.fs.resolve_path(path, self.protocol.cwd) if len(args) < 2: self.writeln("mv: missing destination file operand after `%s'" % \ @@ -307,7 +307,7 @@ commands['/bin/mv'] = command_mv class command_mkdir(HoneyPotCommand): def call(self): for f in self.args: - path = self.fs.resolve_path(f, self.honeypot.cwd) + path = self.fs.resolve_path(f, self.protocol.cwd) if self.fs.exists(path): self.writeln( 'mkdir: cannot create directory `%s\': File exists' % f) @@ -324,7 +324,7 @@ commands['/bin/mkdir'] = command_mkdir class command_rmdir(HoneyPotCommand): def call(self): for f in self.args: - path = self.fs.resolve_path(f, self.honeypot.cwd) + path = self.fs.resolve_path(f, self.protocol.cwd) try: if len(self.fs.get_path(path)): self.writeln( @@ -350,7 +350,7 @@ commands['/bin/rmdir'] = command_rmdir class command_pwd(HoneyPotCommand): def call(self): - self.writeln(self.honeypot.cwd) + self.writeln(self.protocol.cwd) commands['/bin/pwd'] = command_pwd class command_touch(HoneyPotCommand): @@ -360,7 +360,7 @@ class command_touch(HoneyPotCommand): self.writeln('Try `touch --help\' for more information.') return for f in self.args: - path = self.fs.resolve_path(f, self.honeypot.cwd) + path = self.fs.resolve_path(f, self.protocol.cwd) if not self.fs.exists(os.path.dirname(path)): self.writeln( 'touch: cannot touch `%s`: no such file or directory' % \ diff --git a/cowrie/commands/gcc.py b/cowrie/commands/gcc.py index 6a902ea..d90c428 100644 --- a/cowrie/commands/gcc.py +++ b/cowrie/commands/gcc.py @@ -105,7 +105,7 @@ class command_gcc(HoneyPotCommand): # Check for *.c or *.cpp files for value in args: if '.c' in value.lower(): - sourcefile = self.fs.resolve_path(value, self.honeypot.cwd) + sourcefile = self.fs.resolve_path(value, self.protocol.cwd) if self.fs.exists(sourcefile): input_files = input_files + 1 @@ -165,7 +165,7 @@ gcc version %s (Debian %s-5)""" % (version, version_short, version_short, versio data = "" # TODO: make sure it is written to temp file, not downloads safeoutfile = '%s/%s_%s' % \ - (self.honeypot.env.cfg.get('honeypot', 'download_path'), + (self.protocol.env.cfg.get('honeypot', 'download_path'), time.strftime('%Y%m%d%H%M%S'), re.sub('[^A-Za-z0-9]', '_', outfile)) @@ -181,9 +181,9 @@ gcc version %s (Debian %s-5)""" % (version, version_short, version_short, versio with open(safeoutfile, 'wb') as f: f.write(data) # Output file - outfile = self.fs.resolve_path(outfile, self.honeypot.cwd) + outfile = self.fs.resolve_path(outfile, self.protocol.cwd) - # Create file for the honeypot + # Create file for the protocol self.fs.mkfile(outfile, 0, 0, len(data), 33188) self.fs.update_realfile(self.fs.getfile(outfile), safeoutfile) @@ -193,7 +193,7 @@ gcc version %s (Debian %s-5)""" % (version, version_short, version_short, versio self.write("Segmentation fault\n") # Trick the 'new compiled file' as an segfault - self.honeypot.commands[outfile] = segfault_command + self.protocol.commands[outfile] = segfault_command # Done self.exit() diff --git a/cowrie/commands/ifconfig.py b/cowrie/commands/ifconfig.py index bfce332..3c2c4b8 100644 --- a/cowrie/commands/ifconfig.py +++ b/cowrie/commands/ifconfig.py @@ -27,9 +27,9 @@ lo Link encap:Local Loopback TX packets:110 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:19932 (19.9 KB) TX bytes:19932 (19.9 KB)""" % \ - (self.honeypot.kippoIP, - self.honeypot.kippoIP.rsplit('.', 1)[0]) - self.honeypot.writeln(l) + (self.protocol.kippoIP, + self.protocol.kippoIP.rsplit('.', 1)[0]) + self.protocol.writeln(l) commands['/sbin/ifconfig'] = command_ifconfig diff --git a/cowrie/commands/iptables.py b/cowrie/commands/iptables.py index 55e87de..ad106e7 100644 --- a/cowrie/commands/iptables.py +++ b/cowrie/commands/iptables.py @@ -37,7 +37,7 @@ class command_iptables(HoneyPotCommand): DEFAULT_TABLE = "filter" def user_is_root(self): - return self.honeypot.user.username == 'root' + return self.protocol.user.username == 'root' def start(self): """ @@ -155,8 +155,8 @@ class command_iptables(HoneyPotCommand): """ # Create fresh tables on start - if not hasattr(self.honeypot.env, 'iptables'): - setattr(self.honeypot.env, 'iptables', { + if not hasattr(self.protocol.env, 'iptables'): + setattr(self.protocol.env, 'iptables', { "raw": { "PREROUTING": [], "OUTPUT": [] @@ -183,7 +183,7 @@ class command_iptables(HoneyPotCommand): }) # Get the tables - self.tables = getattr(self.honeypot.env, 'iptables') + self.tables = getattr(self.protocol.env, 'iptables') # Verify selected table if not self.is_valid_table(table): diff --git a/cowrie/commands/last.py b/cowrie/commands/last.py index 8a935ce..893c2b8 100644 --- a/cowrie/commands/last.py +++ b/cowrie/commands/last.py @@ -9,7 +9,7 @@ commands = {} class command_last(HoneyPotCommand): def call(self): - fn = '%s/lastlog.txt' % self.honeypot.env.cfg.get('honeypot', 'data_path') + fn = '%s/lastlog.txt' % self.protocol.env.cfg.get('honeypot', 'data_path') if not os.path.exists(fn): return l = list(self.args) diff --git a/cowrie/commands/ls.py b/cowrie/commands/ls.py index 2ae1176..2c2d76e 100644 --- a/cowrie/commands/ls.py +++ b/cowrie/commands/ls.py @@ -22,13 +22,13 @@ class command_ls(HoneyPotCommand): return gid def call(self): - path = self.honeypot.cwd + path = self.protocol.cwd paths = [] if len(self.args): for arg in self.args: if not arg.startswith('-'): - paths.append(self.honeypot.fs.resolve_path(arg, - self.honeypot.cwd)) + paths.append(self.protocol.fs.resolve_path(arg, + self.protocol.cwd)) self.show_hidden = False func = self.do_ls_normal @@ -46,10 +46,10 @@ class command_ls(HoneyPotCommand): def do_ls_normal(self, path): try: - files = self.honeypot.fs.get_path(path) + files = self.protocol.fs.get_path(path) files.sort() except: - self.honeypot.writeln( + self.protocol.writeln( 'ls: cannot access %s: No such file or directory' % path) return l = [x[A_NAME] for x in files \ @@ -63,7 +63,7 @@ class command_ls(HoneyPotCommand): maxlen = max([len(x) for x in l]) try: - wincols = self.honeypot.user.windowSize[1] + wincols = self.protocol.user.windowSize[1] except AttributeError: wincols = 80 @@ -78,10 +78,10 @@ class command_ls(HoneyPotCommand): def do_ls_l(self, path): try: - files = self.honeypot.fs.get_path(path)[:] + files = self.protocol.fs.get_path(path)[:] files.sort() except: - self.honeypot.writeln( + self.protocol.writeln( 'ls: cannot access %s: No such file or directory' % path) return @@ -129,7 +129,7 @@ class command_ls(HoneyPotCommand): file[A_NAME], linktarget) - self.honeypot.writeln(l) + self.protocol.writeln(l) commands['/bin/ls'] = command_ls commands['/bin/dir'] = command_ls diff --git a/cowrie/commands/netstat.py b/cowrie/commands/netstat.py index a386a2b..f0dca42 100644 --- a/cowrie/commands/netstat.py +++ b/cowrie/commands/netstat.py @@ -53,7 +53,7 @@ usage: netstat [-vWeenNcCF] [] -r netstat {-V|--version|-h|--help} x25 (CCITT X.25)""") def do_netstat_route(self): - self.honeypot.writeln("""Kernel IP routing table + self.protocol.writeln("""Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface""") if self.show_numeric: default = "default" @@ -61,48 +61,48 @@ Destination Gateway Genmask Flags MSS Window irtt Iface"" else: default = "0.0.0.0" lgateway = "*" - destination = self.honeypot.kippoIP.rsplit('.', 1)[0] + ".0" - gateway = self.honeypot.kippoIP.rsplit('.', 1)[0] + ".1" + destination = self.protocol.kippoIP.rsplit('.', 1)[0] + ".0" + gateway = self.protocol.kippoIP.rsplit('.', 1)[0] + ".1" l1 = "%s%s0.0.0.0 UG 0 0 0 eth0" % \ ('{:<16}'.format(default), '{:<16}'.format(gateway)) l2 = "%s%s255.255.255.0 U 0 0 0 eth0" % \ ('{:<16}'.format(destination), '{:<16}'.format(lgateway)) - self.honeypot.writeln(l1) - self.honeypot.writeln(l2) + self.protocol.writeln(l1) + self.protocol.writeln(l2) def do_netstat_normal(self): - self.honeypot.writeln("""Active Internet connections (w/o servers) + self.protocol.writeln("""Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State""") - s_name = self.honeypot.hostname - c_port = str(self.honeypot.realClientPort) + s_name = self.protocol.hostname + c_port = str(self.protocol.realClientPort) if self.show_numeric: s_port = "22" - c_name = str(self.honeypot.clientIP) - s_name = str(self.honeypot.kippoIP) + c_name = str(self.protocol.clientIP) + s_name = str(self.protocol.kippoIP) else: s_port = "ssh" - c_name = socket.gethostbyaddr(self.honeypot.clientIP)[0][:17] + c_name = socket.gethostbyaddr(self.protocol.clientIP)[0][:17] if self.show_listen or self.show_all: - self.honeypot.writeln("tcp 0 0 *:ssh *:* LISTEN") + self.protocol.writeln("tcp 0 0 *:ssh *:* LISTEN") if not self.show_listen or self.show_all: l = 'tcp 0 308 %s:%s%s%s:%s%s%s' % \ (s_name, s_port, " "*(24-len(s_name+s_port)-1), c_name, c_port, " "*(24-len(c_name+c_port)-1), "ESTABLISHED") - self.honeypot.writeln(l) + self.protocol.writeln(l) if self.show_listen or self.show_all: - self.honeypot.writeln("tcp6 0 0 [::]:ssh [::]:* LISTEN") - self.honeypot.writeln("""Active UNIX domain sockets (only servers) + self.protocol.writeln("tcp6 0 0 [::]:ssh [::]:* LISTEN") + self.protocol.writeln("""Active UNIX domain sockets (only servers) Proto RefCnt Flags Type State I-Node Path""") if self.show_listen: - self.honeypot.writeln("""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket + self.protocol.writeln("""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket unix 2 [ ACC ] STREAM LISTENING 6807 @/com/ubuntu/upstart unix 2 [ ACC ] STREAM LISTENING 7299 /var/run/dbus/system_bus_socket unix 2 [ ACC ] SEQPACKET LISTENING 7159 /run/udev/control""") elif self.show_all: - self.honeypot.writeln("""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket + self.protocol.writeln("""unix 2 [ ACC ] STREAM LISTENING 8969 /var/run/acpid.socket unix 4 [ ] DGRAM 7445 /dev/log unix 2 [ ACC ] STREAM LISTENING 6807 @/com/ubuntu/upstart unix 2 [ ACC ] STREAM LISTENING 7299 /var/run/dbus/system_bus_socket @@ -124,7 +124,7 @@ unix 3 [ ] DGRAM 7198 unix 2 [ ] DGRAM 9570 unix 3 [ ] STREAM CONNECTED 8619 @/com/ubuntu/upstart""") else: - self.honeypot.writeln("""unix 4 [ ] DGRAM 7445 /dev/log + self.protocol.writeln("""unix 4 [ ] DGRAM 7445 /dev/log unix 3 [ ] STREAM CONNECTED 7323 unix 3 [ ] STREAM CONNECTED 7348 /var/run/dbus/system_bus_socket unix 3 [ ] STREAM CONNECTED 7330 diff --git a/cowrie/commands/nohup.py b/cowrie/commands/nohup.py index 06f000a..d2ef311 100644 --- a/cowrie/commands/nohup.py +++ b/cowrie/commands/nohup.py @@ -16,7 +16,7 @@ class command_nohup(HoneyPotCommand): self.writeln('nohup: missing operand') self.writeln('Try `nohup --help\' for more information.') return - path = self.fs.resolve_path("nohup.out", self.honeypot.cwd) + path = self.fs.resolve_path("nohup.out", self.protocol.cwd) if self.fs.exists(path): return self.fs.mkfile(path, 0, 0, 0, 33188) diff --git a/cowrie/commands/scp.py b/cowrie/commands/scp.py index 3cd041d..ea9c99b 100644 --- a/cowrie/commands/scp.py +++ b/cowrie/commands/scp.py @@ -46,21 +46,21 @@ class command_scp(HoneyPotCommand): self.help() self.exit() return - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) - self.honeypot.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) def lineReceived(self, line): log.msg( eventid='KIPP0008', realm='scp', input=line, format='INPUT (%(realm)s): %(input)s' ) - self.honeypot.terminal.write( '\x00' ) + self.protocol.terminal.write( '\x00' ) commands['/usr/bin/scp'] = command_scp diff --git a/cowrie/commands/ssh.py b/cowrie/commands/ssh.py index f3e04ff..5492d55 100644 --- a/cowrie/commands/ssh.py +++ b/cowrie/commands/ssh.py @@ -79,7 +79,7 @@ class command_ssh(HoneyPotCommand): 'Warning: Permanently added \'%s\' (RSA) to the list of known hosts.' % \ self.host) self.write('%s@%s\'s password: ' % (self.user, self.host)) - self.honeypot.password_input = True + self.protocol.password_input = True def wait(self, line): reactor.callLater(2, self.finish, line) @@ -90,14 +90,14 @@ class command_ssh(HoneyPotCommand): rest = self.host.strip().split('.') if len(rest) and rest[0].isalpha(): host = rest[0] - self.honeypot.hostname = host - self.honeypot.cwd = '/root' - if not self.fs.exists(self.honeypot.cwd): - self.honeypot.cwd = '/' - self.honeypot.password_input = False + self.protocol.hostname = host + self.protocol.cwd = '/root' + if not self.fs.exists(self.protocol.cwd): + self.protocol.cwd = '/' + self.protocol.password_input = False self.writeln( 'Linux %s 2.6.26-2-686 #1 SMP Wed Nov 4 20:45:37 UTC 2009 i686' % \ - self.honeypot.hostname) + self.protocol.hostname) self.writeln('Last login: %s from 192.168.9.4' % \ time.ctime(time.time() - 123123)) self.exit() diff --git a/cowrie/commands/tar.py b/cowrie/commands/tar.py index e88cb45..c6d806b 100644 --- a/cowrie/commands/tar.py +++ b/cowrie/commands/tar.py @@ -45,8 +45,8 @@ class command_tar(HoneyPotCommand): if 'v' in self.args[0]: verbose = True - path = self.fs.resolve_path(filename, self.honeypot.cwd) - if not path or not self.honeypot.fs.exists(path): + path = self.fs.resolve_path(filename, self.protocol.cwd) + if not path or not self.protocol.fs.exists(path): self.writeln('tar: %s: Cannot open: No such file or directory' % \ filename) self.writeln('tar: Error is not recoverable: exiting now') @@ -70,7 +70,7 @@ class command_tar(HoneyPotCommand): return for f in t: - dest = self.fs.resolve_path(f.name.strip('/'), self.honeypot.cwd) + dest = self.fs.resolve_path(f.name.strip('/'), self.protocol.cwd) if verbose: self.writeln(f.name) if not extract or not len(dest): @@ -80,7 +80,7 @@ class command_tar(HoneyPotCommand): elif f.isfile(): self.mkfullpath(os.path.dirname(dest), f) self.fs.mkfile(dest, 0, 0, f.size, f.mode, f.mtime) - self.honeypot.commands[dest] = \ + self.protocol.commands[dest] = \ pick_handler(os.path.basename(dest), f.size) else: log.msg( 'tar: skipping [%s]' % f.name ) diff --git a/cowrie/commands/uname.py b/cowrie/commands/uname.py index 7db8737..078d799 100644 --- a/cowrie/commands/uname.py +++ b/cowrie/commands/uname.py @@ -9,7 +9,7 @@ class command_uname(HoneyPotCommand): if len(self.args) and self.args[0].strip() in ('-a', '--all'): self.writeln( 'Linux %s 3.2.0-4-amd64 #1 SMP Debian 3.2.68-1+deb7u1 x86_64 GNU/Linux' % \ - self.honeypot.hostname) + self.protocol.hostname) elif len(self.args) and self.args[0].strip() in ('-r', '--kernel-release'): self.writeln( '3.2.0-4-amd64' ) elif len(self.args) and self.args[0].strip() in ('-m', '--machine'): diff --git a/cowrie/commands/wget.py b/cowrie/commands/wget.py index 6736297..72958c8 100644 --- a/cowrie/commands/wget.py +++ b/cowrie/commands/wget.py @@ -83,7 +83,7 @@ class command_wget(HoneyPotCommand): if not len(outfile.strip()) or not urldata.path.count('/'): outfile = 'index.html' - outfile = self.fs.resolve_path(outfile, self.honeypot.cwd) + outfile = self.fs.resolve_path(outfile, self.protocol.cwd) path = os.path.dirname(outfile) if not path or \ not self.fs.exists(path) or \ @@ -95,7 +95,7 @@ class command_wget(HoneyPotCommand): self.url = url self.limit_size = 0 - cfg = self.honeypot.env.cfg + cfg = self.protocol.env.cfg if cfg.has_option('honeypot', 'download_limit_size'): self.limit_size = int(cfg.get('honeypot', 'download_limit_size')) @@ -132,8 +132,8 @@ class command_wget(HoneyPotCommand): factory = HTTPProgressDownloader( self, fakeoutfile, url, outputfile, *args, **kwargs) out_addr = None - if self.honeypot.env.cfg.has_option('honeypot', 'out_addr'): - out_addr = (self.honeypot.env.cfg.get('honeypot', 'out_addr'), 0) + if self.protocol.env.cfg.has_option('honeypot', 'out_addr'): + out_addr = (self.protocol.env.cfg.get('honeypot', 'out_addr'), 0) if scheme == 'https': contextFactory = ssl.ClientContextFactory() @@ -164,7 +164,7 @@ class command_wget(HoneyPotCommand): os.remove(self.safeoutfile) log.msg("Not storing duplicate content " + shasum) - self.honeypot.logDispatch( format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', + self.protocol.logDispatch( format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', eventid='KIPP0007', url=self.url, outfile=hash_path, shasum=shasum ) log.msg( format='Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s', @@ -243,7 +243,7 @@ class HTTPProgressDownloader(client.HTTPDownloader): self.nomore = True if self.quiet == False: self.wget.writeln('Saving to: `%s' % self.fakeoutfile) - self.wget.honeypot.terminal.nextLine() + self.wget.protocol.terminal.nextLine() return client.HTTPDownloader.gotHeaders(self, headers) @@ -290,8 +290,8 @@ class HTTPProgressDownloader(client.HTTPDownloader): ('%s>' % (38 * '='), splitthousands(str(int(self.totallength))).ljust(12), self.speed / 1000)) - self.wget.honeypot.terminal.nextLine() - self.wget.honeypot.terminal.nextLine() + self.wget.protocol.terminal.nextLine() + self.wget.protocol.terminal.nextLine() self.wget.writeln( '%s (%d KB/s) - `%s\' saved [%d/%d]' % \ (time.strftime('%Y-%m-%d %H:%M:%S'), diff --git a/cowrie/core/honeypot.py b/cowrie/core/honeypot.py index 2884183..a84014f 100644 --- a/cowrie/core/honeypot.py +++ b/cowrie/core/honeypot.py @@ -5,7 +5,6 @@ import os import shlex import re import copy -import pickle from twisted.python import log @@ -13,24 +12,24 @@ from . import fs class HoneyPotCommand(object): def __init__(self, protocol, *args): - self.honeypot = protocol + self.protocol = protocol self.args = args - self.env = self.honeypot.cmdstack[0].envvars - self.writeln = self.honeypot.writeln - self.write = self.honeypot.terminal.write - self.nextLine = self.honeypot.terminal.nextLine - self.fs = self.honeypot.fs + self.env = self.protocol.cmdstack[0].envvars + self.writeln = self.protocol.writeln + self.write = self.protocol.terminal.write + self.nextLine = self.protocol.terminal.nextLine + self.fs = self.protocol.fs def start(self): self.call() self.exit() def call(self): - self.honeypot.writeln('Hello World! [%s]' % (repr(self.args),)) + self.protocol.writeln('Hello World! [%s]' % (repr(self.args),)) def exit(self): - self.honeypot.cmdstack.pop() - self.honeypot.cmdstack[-1].resume() + self.protocol.cmdstack.pop() + self.protocol.cmdstack[-1].resume() def handle_CTRL_C(self): log.msg('Received CTRL-C, exiting..') @@ -51,7 +50,7 @@ class HoneyPotCommand(object): class HoneyPotShell(object): def __init__(self, protocol, interactive=True): - self.honeypot = protocol + self.protocol = protocol self.interactive = interactive self.showPrompt() self.cmdpending = [] @@ -81,15 +80,15 @@ class HoneyPotShell(object): elif self.interactive: self.showPrompt() else: - self.honeypot.terminal.transport.session.sendEOF() - self.honeypot.terminal.transport.session.sendClose() + self.protocol.terminal.transport.session.sendEOF() + self.protocol.terminal.transport.session.sendClose() if not len(self.cmdpending): if self.interactive: self.showPrompt() else: - self.honeypot.terminal.transport.session.sendEOF() - self.honeypot.terminal.transport.session.sendClose() + self.protocol.terminal.transport.session.sendEOF() + self.protocol.terminal.transport.session.sendClose() return line = self.cmdpending.pop(0) @@ -97,7 +96,7 @@ class HoneyPotShell(object): line = line.replace('>', ' > ').replace('|', ' | ').replace('<',' < ') cmdAndArgs = shlex.split(line) except: - self.honeypot.writeln( + self.protocol.writeln( 'bash: syntax error: unexpected end of file') # could run runCommand here, but i'll just clear the list instead self.cmdpending = [] @@ -123,49 +122,49 @@ class HoneyPotShell(object): rargs = [] for arg in args: - matches = self.honeypot.fs.resolve_path_wc(arg, self.honeypot.cwd) + matches = self.protocol.fs.resolve_path_wc(arg, self.protocol.cwd) if matches: rargs.extend(matches) else: rargs.append(arg) - cmdclass = self.honeypot.getCommand(cmd, envvars['PATH'].split(':')) + cmdclass = self.protocol.getCommand(cmd, envvars['PATH'].split(':')) if cmdclass: log.msg(eventid='KIPP0005', input=line, format='Command found: %(input)s') - #self.honeypot.logDispatch('Command found: %s' % (line,)) - self.honeypot.call_command(cmdclass, *rargs) + #self.protocol.logDispatch('Command found: %s' % (line,)) + self.protocol.call_command(cmdclass, *rargs) else: log.msg(eventid='KIPP0006', input=line, format='Command not found: %(input)s') - #self.honeypot.logDispatch('Command not found: %s' % (line,)) + #self.protocol.logDispatch('Command not found: %s' % (line,)) if len(line): - self.honeypot.writeln('bash: %s: command not found' % (cmd,)) + self.protocol.writeln('bash: %s: command not found' % (cmd,)) runOrPrompt() def resume(self): if self.interactive: - self.honeypot.setInsertMode() + self.protocol.setInsertMode() self.runCommand() def showPrompt(self): if not self.interactive: return # Example: srv03:~# - #prompt = '%s:%%(path)s' % self.honeypot.hostname + #prompt = '%s:%%(path)s' % self.protocol.hostname # Example: root@svr03:~# (More of a "Debianu" feel) - prompt = '%s@%s:%%(path)s' % (self.honeypot.user.username, self.honeypot.hostname,) + prompt = '%s@%s:%%(path)s' % (self.protocol.user.username, self.protocol.hostname,) # Example: [root@svr03 ~]# (More of a "CentOS" feel) - #prompt = '[%s@%s %%(path)s]' % (self.honeypot.user.username, self.honeypot.hostname,) - if not self.honeypot.user.uid: + #prompt = '[%s@%s %%(path)s]' % (self.protocol.user.username, self.protocol.hostname,) + if not self.protocol.user.uid: prompt += '# ' # "Root" user else: prompt += '$ ' # "Non-Root" user - path = self.honeypot.cwd - homelen = len(self.honeypot.user.home) - if path == self.honeypot.user.home: + path = self.protocol.cwd + homelen = len(self.protocol.user.home) + if path == self.protocol.user.home: path = '~' elif len(path) > (homelen+1) and \ - path[:(homelen+1)] == self.honeypot.user.home + '/': + path[:(homelen+1)] == self.protocol.user.home + '/': path = '~' + path[homelen:] # Uncomment the three lines below for a 'better' CentOS look. # Rather than '[root@svr03 /var/log]#' is shows '[root@svr03 log]#'. @@ -174,27 +173,27 @@ class HoneyPotShell(object): # path = '/' attrs = {'path': path} - self.honeypot.terminal.write(prompt % attrs) + self.protocol.terminal.write(prompt % attrs) def handle_CTRL_C(self): - self.honeypot.lineBuffer = [] - self.honeypot.lineBufferIndex = 0 - self.honeypot.terminal.nextLine() + self.protocol.lineBuffer = [] + self.protocol.lineBufferIndex = 0 + self.protocol.terminal.nextLine() self.showPrompt() def handle_CTRL_D(self): log.msg('Received CTRL-D, exiting..') - self.honeypot.call_command(self.honeypot.commands['exit']) + self.protocol.call_command(self.protocol.commands['exit']) # Tab completion def handle_TAB(self): - if not len(self.honeypot.lineBuffer): + if not len(self.protocol.lineBuffer): return - l = ''.join(self.honeypot.lineBuffer) + l = ''.join(self.protocol.lineBuffer) if l[-1] == ' ': clue = '' else: - clue = ''.join(self.honeypot.lineBuffer).split()[-1] + clue = ''.join(self.protocol.lineBuffer).split()[-1] try: basedir = os.path.dirname(clue) except: @@ -205,12 +204,12 @@ class HoneyPotShell(object): files = [] tmppath = basedir if not len(basedir): - tmppath = self.honeypot.cwd + tmppath = self.protocol.cwd try: - r = self.honeypot.fs.resolve_path(tmppath, self.honeypot.cwd) + r = self.protocol.fs.resolve_path(tmppath, self.protocol.cwd) except: return - for x in self.honeypot.fs.get_path(r): + for x in self.protocol.fs.get_path(r): if clue == '': files.append(x) continue @@ -222,9 +221,9 @@ class HoneyPotShell(object): return # Clear early so we can call showPrompt if needed - for i in range(self.honeypot.lineBufferIndex): - self.honeypot.terminal.cursorBackward() - self.honeypot.terminal.deleteCharacter() + for i in range(self.protocol.lineBufferIndex): + self.protocol.terminal.cursorBackward() + self.protocol.terminal.deleteCharacter() newbuf = '' if len(files) == 1: @@ -241,32 +240,30 @@ class HoneyPotShell(object): prefix = '' first = l.split(' ')[:-1] newbuf = ' '.join(first + ['%s%s' % (basedir, prefix)]) - if newbuf == ''.join(self.honeypot.lineBuffer): - self.honeypot.terminal.nextLine() + if newbuf == ''.join(self.protocol.lineBuffer): + self.protocol.terminal.nextLine() maxlen = max([len(x[fs.A_NAME]) for x in files]) + 1 - perline = int(self.honeypot.user.windowSize[1] / (maxlen + 1)) + perline = int(self.protocol.user.windowSize[1] / (maxlen + 1)) count = 0 for file in files: if count == perline: count = 0 - self.honeypot.terminal.nextLine() - self.honeypot.terminal.write(file[fs.A_NAME].ljust(maxlen)) + self.protocol.terminal.nextLine() + self.protocol.terminal.write(file[fs.A_NAME].ljust(maxlen)) count += 1 - self.honeypot.terminal.nextLine() + self.protocol.terminal.nextLine() self.showPrompt() - self.honeypot.lineBuffer = list(newbuf) - self.honeypot.lineBufferIndex = len(self.honeypot.lineBuffer) - self.honeypot.terminal.write(newbuf) + self.protocol.lineBuffer = list(newbuf) + self.protocol.lineBufferIndex = len(self.protocol.lineBuffer) + self.protocol.terminal.write(newbuf) class HoneyPotEnvironment(object): """ """ def __init__(self, cfg): self.cfg = cfg - self.commands = {} - self.hostname = self.cfg.get('honeypot', 'hostname') import cowrie.commands for c in cowrie.commands.__all__: @@ -274,6 +271,4 @@ class HoneyPotEnvironment(object): globals(), locals(), ['commands']) self.commands.update(module.commands) - self.fs = pickle.load(file(cfg.get('honeypot', 'filesystem_file'), 'rb')) - # vim: set sw=4 et: diff --git a/cowrie/core/protocol.py b/cowrie/core/protocol.py index 6dde2b6..1487be3 100644 --- a/cowrie/core/protocol.py +++ b/cowrie/core/protocol.py @@ -20,8 +20,8 @@ class HoneyPotBaseProtocol(insults.TerminalProtocol, TimeoutMixin): self.user = avatar self.env = avatar.env self.cfg = self.env.cfg - self.hostname = avatar.hostname - self.fs = avatar.fs + self.hostname = avatar.server.hostname + self.fs = avatar.server.fs if self.fs.exists(avatar.home): self.cwd = avatar.home else: diff --git a/cowrie/core/realm.py b/cowrie/core/realm.py index b730501..784fde4 100644 --- a/cowrie/core/realm.py +++ b/cowrie/core/realm.py @@ -36,6 +36,9 @@ from . import protocol from . import server from . import ssh +import sys +import gc + class HoneyPotRealm: implements(twisted.cred.portal.IRealm) @@ -47,15 +50,17 @@ class HoneyPotRealm: if mind in self.servers: log.msg( "Using existing server for mind %s" % mind ) - _server = self.servers[mind] else: log.msg( "Starting new server for mind %s" % mind ) - _server = server.CowrieServer(self.cfg) - self.servers[mind] = _server + self.servers[mind] = _server = server.CowrieServer(self.cfg) + + for i in self.servers.keys(): + log.msg( "REFCOUNT: key: %s, refcount %d" % ( i, sys.getrefcount(self.servers[i]))) + log.msg( "Refer: %s" % repr( gc.get_referrers(self.servers[i]))) if conchinterfaces.IConchUser in interfaces: return interfaces[0], \ - ssh.HoneyPotAvatar(avatarId, _server), lambda: None + ssh.HoneyPotAvatar(avatarId, self.servers[mind]), lambda: None else: raise Exception("No supported interfaces found.") diff --git a/cowrie/core/server.py b/cowrie/core/server.py index 556e63d..070ae42 100644 --- a/cowrie/core/server.py +++ b/cowrie/core/server.py @@ -27,13 +27,16 @@ # SUCH DAMAGE. import copy +import pickle + +import twisted.python.log as log from . import fs from . import honeypot class CowrieServer: """ - In traditional Kippo each connect gets its own simulated machine. + In traditional Kippo each connection gets its own simulated machine. This is not always ideal, sometimes two connections come from the same source IP address. we want to give them the same environment as well. So files uploaded through SFTP are visible in the SSH session. @@ -43,5 +46,8 @@ class CowrieServer: def __init__(self, cfg): self.cfg = cfg self.env = honeypot.HoneyPotEnvironment(cfg) - self.fs = fs.HoneyPotFilesystem(copy.deepcopy(self.env.fs),self.env.cfg) + self.hostname = self.cfg.get('honeypot', 'hostname') + log.msg ("Loading pickle file...") + self.pickle = pickle.load(file(cfg.get('honeypot', 'filesystem_file'), 'rb')) + self.fs = fs.HoneyPotFilesystem(self.pickle,self.cfg) diff --git a/cowrie/core/ssh.py b/cowrie/core/ssh.py index 9eb683a..4221962 100644 --- a/cowrie/core/ssh.py +++ b/cowrie/core/ssh.py @@ -417,10 +417,8 @@ class HoneyPotAvatar(avatar.ConchUser): avatar.ConchUser.__init__(self) self.username = username self.server = server - self.cfg = server.cfg - self.env = server.env - self.fs = server.fs - self.hostname = self.env.hostname + self.cfg = self.server.cfg + self.env = self.server.env self.protocol = None self.channelLookup.update({'session': HoneyPotSSHSession}) @@ -604,7 +602,7 @@ class CowrieSFTPServer: def __init__(self, avatar): self.avatar = avatar - self.fs = self.avatar.fs + self.fs = self.avatar.server.fs def _absPath(self, path): home = self.avatar.home