def inject(self, packet_num, payload): direction = 'INTERACT -> SERVER' packet = self.packetLayout[packet_num] log.msg(log.LBLUE, '[SSH]', direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload)) self.client.sendPacket(packet_num, payload)
def get_credentials(username): cfg = Config.getInstance() user_cfg_path = cfg.get(['spoof', 'users_conf']) if os.path.exists(user_cfg_path): users_cfg = ConfigParser.ConfigParser() users_cfg.read(user_cfg_path) users = users_cfg.sections() retval = [] for user in users: if user == username: if users_cfg.has_option(user, 'fake_passwords'): retval.append([ user, users_cfg.get(user, 'real_password'), 'fixed', users_cfg.get(user, 'fake_passwords') ]) if users_cfg.has_option(user, 'random_chance'): retval.append([ user, users_cfg.get(user, 'real_password'), 'random', users_cfg.get(user, 'random_chance') ]) return retval if len(retval) > 0 else None else: log.msg(log.LRED, '[SPOOF]', 'ERROR: users_conf does not exist') return None
def connectionMade(self): log.msg(log.LGREEN, '[CLIENT]', 'New client connection') self.factory.server.client = self self.factory.server.sshParse.setClient(self) transport.SSHClientTransport.connectionMade(self) self.cfg = self.factory.server.cfg self.out = self.factory.server.out
def launch_container(self): if self.reuse_container: try: # Check for existing container container_data = self.connection.inspect_container(self.peer_ip) # Get container id self.container_id = container_data['Id'] log.msg(log.LGREEN, '[PLUGIN][DOCKER]', 'Reusing container %s ' % self.container_id) # Restart container self.connection.restart(self.container_id) except: self.container_id = None pass if self.container_id is None: host_config = self.connection.create_host_config(pids_limit=self.pids_limit, mem_limit=self.mem_limit, memswap_limit=self.memswap_limit, shm_size=self.shm_size, cpu_period=self.cpu_period, cpu_shares=self.cpu_shares, cpuset_cpus=self.cpuset_cpus) self.container_id = \ self.connection.create_container(image=self.image, tty=True, hostname=self.hostname, name=self.peer_ip, host_config=host_config)['Id'] self.connection.start(self.container_id) exec_id = self.connection.exec_create(self.container_id, self.launch_cmd)['Id'] self.connection.exec_start(exec_id, tty=True) container_data = self.connection.inspect_container(self.container_id) self.container_ip = container_data['NetworkSettings']['Networks']['bridge']['IPAddress'] log.msg(log.LCYAN, '[PLUGIN][DOCKER]', 'Launched container (%s, %s)' % (self.container_ip, self.container_id)) return {"id": self.container_id, "ip": self.container_ip}
def connectionLost(self, reason): transport.SSHClientTransport.connectionLost(self, reason) if self.factory.server.wasConnected: log.msg( log.LBLUE, '[CLIENT]', 'Lost connection with the Honeypot: ' + self.factory.server.sensor_name + ' (' + self.factory.server.honey_ip + ':' + str(self.factory.server.honey_port) + ')') #spi tg.tgMessage( "[3][CLIENT] Lost connection with the Honeypot: {} ({}:{}) )". format(self.factory.server.sensor_name, self.factory.server.honey_ip, self.factory.server.honey_port), 3) else: log.msg( log.LBLUE, '[CLIENT]', 'Lost connection with the Honeypot (Server<->Honeypot not connected)' ) if self.factory.server.post_auth_started or self.factory.server.post_auth.auth_plugin is None: self.factory.server.pre_auth.connection_lost() else: self.factory.server.post_auth.connection_lost()
def connectionLost(self, reason): transport.SSHClientTransport.connectionLost(self, reason) log.msg(log.LBLUE, '[CLIENT]', 'Lost connection with the Honeypot: ' + self.factory.server.sensor_name + ' (' + self.factory.server.honey_ip + ':' + str(self.factory.server.honey_port) + ')') if self.factory.server.post_auth_started or self.factory.server.post_auth.auth_plugin == None: self.factory.server.pre_auth.connection_lost() else: self.factory.server.post_auth.connection_lost()
def connectionLost(self): log.msg(log.LRED, '[OUTPUT]', 'Lost Connection with the attacker: %s' % self.end_ip) dt = self.getDateTime() session = self.connections.set_session_close(self.session_id, dt) plugins.run_plugins_function(self.loaded_plugins, 'connection_lost', True, session) self.connections.del_session(self.session_id)
def file_downloaded(self, download): finished = False file_meta = '' if len(download) == 3: finished = download[1] file_meta = download[2] download = download[0] else: error = download[4] if finished: if file_meta != '': dt = self.get_date_time() channel_id, success, link, file, error = download download = self.connections.set_download_close(channel_id, dt, link, file, success, file_meta[0], file_meta[1]) plugins.run_plugins_function(self.loaded_plugins, 'download_finished', True, download) else: if error: log.msg(log.LRED, '[OUTPUT]', download) else: d = threads.deferToThread(self.get_file_meta, download) d.addCallback(self.file_downloaded)
def setupNetworking(self, peer_ip, honey_ip, honey_port): if self.cfg.get('advNet', 'enabled') == 'true': self.peer_ip = peer_ip self.honey_port = str(honey_port) self.honey_ip = honey_ip self.fake_ip = self.getFakeIP(self.peer_ip) sp = self.runCommand('ip link add name honssh type dummy') result = sp.communicate() if sp.returncode != 0: if 'File exists' in result[0]: log.msg(log.LPURPLE, '[ADV-NET]', 'HonSSH Interface already exists, not re-adding') return self.addFakeIP() else: log.msg(log.LRED, '[ADV-NET]', 'Error creating HonSSH Interface - Using client_addr: ' + result[0]) return self.cfg.get('honeypot', 'client_addr') else: sp = self.runCommand('ip link set honssh up') result = sp.communicate() if sp.returncode != 0: log.msg(log.LRED, '[ADV-NET]', 'Error setting HonSSH Interface UP - Using client_addr: ' + result[0]) return self.cfg.get('honeypot', 'client_addr') else: log.msg(log.LGREEN, '[ADV-NET]', 'HonSSH Interface created') return self.addFakeIP() else: log.msg(log.LPURPLE, '[ADV-NET]', 'Advanced Networking disabled - Using client_addr') return self.cfg.get('honeypot', 'client_addr')
def addFakeIP(self): sp = self.runCommand('ip addr add ' + self.fake_ip + '/32 dev honssh') result = sp.communicate() if sp.returncode != 0: if 'File exists' in result[0]: log.msg(log.LPURPLE, '[ADV-NET]', 'Fake IP Address already exists, not re-adding') return self.fake_ip else: log.msg(log.LRED, '[ADV-NET]', 'Error adding IP address to HonSSH Interface - Using client_addr: ' + result[0]) return self.cfg.get('honeypot', 'client_addr') else: sp = self.runCommand('iptables -t nat -A POSTROUTING -s ' + self.fake_ip + '/32 -d ' + self.honey_ip + '/32 -p tcp --dport ' + self.honey_port + ' -j SNAT --to ' + self.peer_ip) result = sp.communicate() if sp.returncode != 0: log.msg(log.LRED, '[ADV-NET]', 'Error creating POSTROUTING Rule - Using client_addr: ' + result[0]) return self.cfg.get('honeypot', 'client_addr') else: sp = self.runCommand('iptables -t nat -A PREROUTING -s ' + self.honey_ip + '/32 -d ' + self.peer_ip +'/32 -p tcp --sport ' + self.honey_port + ' -j DNAT --to ' + self.fake_ip) result = sp.communicate() if sp.returncode != 0: log.msg(log.LRED, '[ADV-NET]', 'Error creating PREROUTING Rule - Using client_addr: ' + result[0]) return self.cfg.get('honeypot', 'client_addr') else: log.msg(log.LGREEN, '[ADV-NET]', 'HonSSH FakeIP and iptables rules added') return self.fake_ip
def get_conn_details(self): plugin_list = plugins.get_plugin_list(type='honeypot') self.auth_plugin = plugins.import_auth_plugins(self.name, plugin_list, self.cfg) if self.auth_plugin == None: log.msg(log.LRED, '[' + self.name + ']', 'NO PLUGIN ENABLED FOR ' + self.name) return {'success':False} else: return plugins.run_plugins_function(self.auth_plugin, 'get_' + self.name.lower() + '_details', False, self.conn_details)
def start_server(self): log.msg(log.LCYAN, "[PLUGIN][HPFEEDS]", "hpfeeds HPLogger start") server = self.cfg.get("output-hpfeeds", "server") port = self.cfg.get("output-hpfeeds", "port") ident = self.cfg.get("output-hpfeeds", "identifier") secret = self.cfg.get("output-hpfeeds", "secret") return hpfeeds_server.hpclient(server, port, ident, secret)
def connectionMade(self): log.msg(log.LGREEN, '[CLIENT]', 'New client connection') #spi tg.tgMessage("[3][CLIENT] - New client connection", 3) self.out = self.factory.server.out self.factory.server.client = self self.factory.server.sshParse.set_client(self) transport.SSHClientTransport.connectionMade(self)
def start_server(self): log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpfeeds HPLogger start') server = self.cfg.get('output-hpfeeds', 'server') port = self.cfg.get('output-hpfeeds', 'port') ident = self.cfg.get('output-hpfeeds', 'identifier') secret = self.cfg.get('output-hpfeeds', 'secret') return hpfeeds_server.hpclient(server, port, ident, secret)
def pot_connected(self, success): if success: if not self.server.disconnected: self.send_next() else: self.server.client.loseConnection() else: log.msg(log.LRED, '[POST_AUTH][ERROR]', 'COULD NOT CONNECT TO HONEYPOT AFTER 10 SECONDS - DISCONNECTING CLIENT') self.server.loseConnection()
def handle_established(self): log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpclient established') while self.state != 'GOTINFO': self.read() #quickly try to see if there was an error message self.s.settimeout(0.5) self.read() self.s.settimeout(None)
def handle_established(self): log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpclient established') while self.state != 'GOTINFO': self.read() # quickly try to see if there was an error message self.s.settimeout(0.5) self.read() self.s.settimeout(None)
def packet_buffer(self, stage, message_num, payload): if not self.clientConnected: log.msg(log.LPURPLE, '[SERVER]', 'CONNECTION TO HONEYPOT NOT READY, BUFFERING PACKET') stage.delayedPackets.append([message_num, payload]) else: if not stage.finishedSending: stage.delayedPackets.append([message_num, payload]) else: self.sshParse.parse_packet("[SERVER]", message_num, payload)
def dataReceived(self, data): datagrams = data.split('_') for i in range(0, len(datagrams)/3): datagram = datagrams[3*i:(3*i)+3] if datagram[0] == 'honssh' and datagram[1] == 'c': self.parsePacket(datagram[2]) else: log.msg('[INTERACT] - Bad packet received') self.loseConnection()
def dataReceived(self, data): datagrams = data.split("_") for i in range(0, len(datagrams) / 3): datagram = datagrams[3 * i : (3 * i) + 3] if datagram[0] == "honssh" and datagram[1] == "c": self.parsePacket(datagram[2]) else: log.msg("[INTERACT] - Bad packet received") self.loseConnection()
def packet_buffer(self, stage, messageNum, payload): if not self.clientConnected: log.msg(log.LPURPLE, '[SERVER]', 'CONNECTION TO HONEYPOT NOT READY, BUFFERING PACKET') stage.delayedPackets.append([messageNum, payload]) else: if not stage.finishedSending: stage.delayedPackets.append([messageNum, payload]) else: self.sshParse.parsePacket("[SERVER]", messageNum, payload)
def get_conn_details(self): if self.auth_plugin is None: log.msg(log.LRED, '[' + self.name + ']', 'NO AUTH PLUGIN SET FOR ' + self.name) return {'success': False} else: return plugins.run_plugins_function([self.auth_plugin], 'get_' + self.name.lower() + '_details', False, self.conn_details)
def __init__(self): self.otherVersionString = '' self.plugin_servers = [] self.ourVersionString = 'SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3' self.plugin_servers.append({'name': 'honeypot-static', 'server': False}) if self.ourVersionString != '': log.msg(log.LGREEN, '[HONSSH]', 'HonSSH Boot Sequence Complete - Ready for attacks!')
def connect(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.settimeout(3) try: self.s.connect((self.server, self.port)) except: log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpfeeds client could not connect to broker.') self.s = None else: self.s.settimeout(None) self.handle_established()
def inject(self, packet_num, payload): direction = 'INTERACT -> SERVER' packet = self.packetLayout[packet_num] self.out.packet_logged(direction, packet, payload) if self.cfg.has_option('devmode', 'enabled') and self.cfg.getboolean(['devmode', 'enabled']): log.msg(log.LBLUE, '[SSH]', direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload)) self.client.sendPacket(packet_num, payload)
def __init__(self, server, port, ident, secret): log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpfeeds client init broker {0}:{1}, identifier {2}'.format(server, port, ident)) self.server, self.port = server, int(port) self.ident, self.secret = ident.encode('latin1'), secret.encode('latin1') self.unpacker = FeedUnpack() self.state = 'INIT' self.connect() self.sendfiles = [] self.filehandle = None
def pot_connected(self, success): if success: if not self.server.disconnected: self.send_next() else: self.server.client.loseConnection() else: log.msg(log.LRED, '[POST_AUTH][ERROR]', 'COULD NOT CONNECT TO HONEYPOT AFTER %s SECONDS - DISCONNECTING CLIENT' % (self.connection_timeout)) self.server.loseConnection()
def get_conn_details(self): if self.auth_plugin is None: log.msg(log.LRED, '[' + self.name + ']', 'NO AUTH PLUGIN SET FOR ' + self.name) return {'success': False} else: return plugins.run_plugins_function( [self.auth_plugin], 'get_' + self.name.lower() + '_details', False, self.conn_details, self.server ) # NOTE PAUL: Added server to detect if we're disconnected
def send_auth_meta(self, sensor): auth = sensor['session']['auth'] authMeta = { 'sensor_name': sensor['sensor_name'], 'datetime': auth['date_time'], 'username': auth['username'], 'password': auth['password'], 'success': auth['success'] } log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'authMeta: ' + str(authMeta)) self.server.publish(hpfeeds_server.HONSSHAUTHCHAN, **authMeta)
def send_auth_meta(self, sensor): auth = sensor["session"]["auth"] authMeta = { "sensor_name": sensor["sensor_name"], "datetime": auth["date_time"], "username": auth["username"], "password": auth["password"], "success": auth["success"], } log.msg(log.LCYAN, "[PLUGIN][HPFEEDS]", "authMeta: " + str(authMeta)) self.server.publish(hpfeeds_server.HONSSHAUTHCHAN, **authMeta)
def connectionLost(self, reason): transport.SSHClientTransport.connectionLost(self, reason) log.msg( log.LBLUE, '[CLIENT]', 'Lost connection with the Honeypot: ' + self.factory.server.sensor_name + ' (' + self.factory.server.honey_ip + ':' + str(self.factory.server.honey_port) + ')') if self.factory.server.post_auth_started or self.factory.server.post_auth.auth_plugin == None: self.factory.server.pre_auth.connection_lost() else: self.factory.server.post_auth.connection_lost()
def inject(self, packetNum, payload): direction = 'INTERACT -> SERVER' packet = self.packetLayout[packetNum] self.out.packet_logged(direction, packet, payload) if self.cfg.has_option('devmode', 'enabled'): if self.cfg.get('devmode', 'enabled') == 'true': log.msg(log.LBLUE, '[SSH]', direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload)) self.client.sendPacket(packetNum, payload)
def get_conn_details(self): plugin_list = plugins.get_plugin_list(type='honeypot') self.auth_plugin = plugins.import_auth_plugins(self.name, plugin_list, self.cfg) if self.auth_plugin == None: log.msg(log.LRED, '[' + self.name + ']', 'NO PLUGIN ENABLED FOR ' + self.name) return {'success': False} else: return plugins.run_plugins_function( self.auth_plugin, 'get_' + self.name.lower() + '_details', False, self.conn_details)
def __init__(self, server, port, ident, secret): log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpfeeds client init broker {0}:{1}, identifier {2}'.format(server, port, ident)) self.server, self.port = server, int(port) self.ident, self.secret = ident.encode('latin1'), secret.encode('latin1') self.unpacker = FeedUnpack() self.state = 'INIT' self.connect() self.sendfiles = [] self.filehandle = None self.s = None
def connectionLost(self, reason): self.disconnected = True # Added to signal docker pre_auth to teardown container (fixed race condition) try: self.client.loseConnection() except: pass # log.msg(log.LPURPLE, '[SERVER]', 'HONSSHSERVER CONNECTION LOST!!') honsshServer.HonsshServer.connectionLost(self, reason) if self.wasConnected: log.msg(log.LPURPLE, '[SERVER]', 'WAS CONNECTED TRUE!!') self.out.connection_lost() else: log.msg(log.LPURPLE, '[SERVER]', 'WAS CONNECTED FALSE!!')
def get_first_user_credentials(): cfg = Config.getInstance() user_cfg_path = cfg.get(['spoof', 'users_conf']) retval = {} if os.path.exists(user_cfg_path): users_cfg = ConfigParser.ConfigParser() users_cfg.read(user_cfg_path) users = users_cfg.sections() return users[0], users_cfg.get(users[0], 'real_password') else: log.msg(log.LRED, '[SPOOF]', 'ERROR: users_conf does not exist') exit(1)
def dataReceived(self, data): self.buf = self.buf + data if not self.gotVersion: if self.buf.find('\n', self.buf.find('SSH-')) == -1: return lines = self.buf.split('\n') for p in lines: if p.startswith('SSH-'): self.gotVersion = True self.ourVersionString = p.strip() self.factory.server.ourVersionString = self.ourVersionString log.msg(log.LBLUE, '[CLIENT]', 'Got SSH Version String: ' + self.factory.server.ourVersionString) self.loseConnection()
def _runInteraction(self, interaction, *args, **kw): try: return adbapi.ConnectionPool._runInteraction( self, interaction, *args, **kw) except MySQLdb.OperationalError, e: if e[0] not in (2006, 2013): raise log.msg(log.LRED, '[MYSQL]', 'RCP: got error %s, retrying operation' %(e)) conn = self.connections.get(self.threadID()) self.disconnect(conn) # try the interaction again return adbapi.ConnectionPool._runInteraction( self, interaction, *args, **kw)
def launch_container(self): old_container_id = None container_name = self.peer_ip if not self.reuse_container: container_name = container_name + "-" + str(uuid.uuid4()) if self.reuse_container: try: # Get container id container_data = self.connection.inspect_container( self.peer_ip) old_container_id = container_data['Id'] # Will fail if container isn't alive: self.container_id, self.container_ip = self.try_reuse_alive_container( old_container_id) return {"id": self.container_id, "ip": self.container_ip} except Exception: pass if old_container_id: self.container_id = old_container_id log.msg(log.LGREEN, '[PLUGIN][DOCKER]', 'Reusing container %s ' % self.container_id) self.connection.restart(self.container_id) if not self.container_id: host_config = self.connection.create_host_config( pids_limit=self.pids_limit, mem_limit=self.mem_limit, memswap_limit=self.memswap_limit, shm_size=self.shm_size, cpu_period=self.cpu_period, cpu_shares=self.cpu_shares, cpuset_cpus=self.cpuset_cpus) self.container_id = \ self.connection.create_container(image=self.image, hostname=self.hostname, name=container_name, host_config=host_config)['Id'] self.connection.start(self.container_id) exec_id = self.connection.exec_create(self.container_id, self.launch_cmd)['Id'] self.connection.exec_start(exec_id) container_data = self.connection.inspect_container(self.container_id) self.container_ip = container_data['NetworkSettings']['Networks'][ 'bridge']['IPAddress'] log.msg( log.LCYAN, '[PLUGIN][DOCKER]', 'Launched container (%s, %s)' % (self.container_ip, self.container_id)) return {"id": self.container_id, "ip": self.container_ip}
def __init__(self): self.cfg = Config.getInstance() self.otherVersionString = '' self.connections = connections.Connections() self.plugin_servers = [] self.ourVersionString = self.cfg.get(['honeypot', 'ssh_banner']) if len(self.ourVersionString) > 0: log.msg(log.LPURPLE, '[SERVER]', 'Using ssh_banner for SSH Version String: ' + self.ourVersionString) else: if self.cfg.getboolean(['honeypot-static', 'enabled']): log.msg(log.LPURPLE, '[SERVER]', 'Acquiring SSH Version String from honey_ip:honey_port') client_factory = client.HonsshSlimClientFactory() client_factory.server = self reactor.connectTCP(self.cfg.get(['honeypot-static', 'honey_ip']), int(self.cfg.get(['honeypot-static', 'honey_port'])), client_factory) elif self.cfg.getboolean(['honeypot-docker', 'enabled']): log.msg(log.LRED, '[SERVER][ERR]', 'You need to configure the ssh_banner for docker manually!') plugin_list = plugins.get_plugin_list() loaded_plugins = plugins.import_plugins(plugin_list) for plugin in loaded_plugins: plugin_server = plugins.run_plugins_function([plugin], 'start_server', False) plugin_name = plugins.get_plugin_name(plugin) self.plugin_servers.append({'name': plugin_name, 'server': plugin_server}) if self.ourVersionString != '': log.msg(log.LGREEN, '[HONSSH]', 'HonSSH Boot Sequence Complete - Ready for attacks!')
def get_users(cfg, username): usersCfg = ConfigParser.ConfigParser() if os.path.exists(cfg.get('spoof','users_conf')): usersCfg.read(cfg.get('spoof','users_conf')) users = usersCfg.sections() for user in users: if user == username: if usersCfg.has_option(user, 'fake_passwords'): return [user, usersCfg.get(user, 'real_password'), 'fixed', usersCfg.get(user, 'fake_passwords')] if usersCfg.has_option(user, 'random_chance'): return [user, usersCfg.get(user, 'real_password'), 'random', usersCfg.get(user, 'random_chance')] else: log.msg(log.LRED, '[SPOOF]', 'ERROR: users_conf does not exist') return None
def send_back(self, parent, message_num, payload): packet = self.packetLayout[message_num] if parent == '[SERVER]': direction = 'HONSSH -> CLIENT' else: direction = 'HONSSH -> SERVER' log.msg(log.LBLUE, '[SSH]', direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload)) if parent == '[SERVER]': self.server.sendPacket(message_num, payload) elif parent == '[CLIENT]': self.client.sendPacket(message_num, payload)
def try_reuse_alive_container(self, old_container_id): # Check for existing, active container containers_alive = self.connection.containers() old_container = [ c for c in containers_alive if c['Id'] == old_container_id ] if old_container: old_container = old_container[0] container_id = old_container_id container_ip = old_container['NetworkSettings']['Networks'][ 'bridge']['IPAddress'] log.msg(log.LGREEN, '[PLUGIN][DOCKER]', 'Reusing ACTIVE container %s ' % old_container_id) return container_id, container_ip
def pot_connected(self, success): if success: if not self.server.disconnected: self.server.connection_init(self.sensor_name, self.honey_ip, self.honey_port) self.server.connection_setup() log.msg(log.LGREEN, '[PRE_AUTH]', 'CLIENT CONNECTED, REPLAYING BUFFERED PACKETS') for packet in self.delayedPackets: self.server.sshParse.parsePacket("[SERVER]", packet[0], packet[1]) self.finishedSending = True else: self.server.client.loseConnection() else: log.msg(log.LRED, '[PRE_AUTH][ERROR]', 'COULD NOT CONNECT TO HONEYPOT AFTER 10 SECONDS - DISCONNECTING CLIENT') self.server.loseConnection()
def _runInteraction(self, interaction, *args, **kw): try: return adbapi.ConnectionPool._runInteraction( self, interaction, *args, **kw) except MySQLdb.OperationalError, e: if e[0] not in (2006, 2013): raise log.msg(log.LRED, '[MYSQL]', 'RCP: got error %s, retrying operation' % (e)) conn = self.connections.get(self.threadID()) self.disconnect(conn) # try the interaction again return adbapi.ConnectionPool._runInteraction( self, interaction, *args, **kw)
def connection_lost(self): log.msg(log.LRED, '[OUTPUT]', 'Lost Connection with the attacker: %s' % self.end_ip) dt = self.get_date_time() channels = self.connections.get_channels(self.session_id) if channels is not None: for channel in channels: if 'end_time' not in channel: self._channel_closed(channel['uuid']) session = self.connections.set_session_close(self.session_id, dt) plugins.run_plugins_function(self.loaded_plugins, 'connection_lost', True, session) self.connections.del_session(self.session_id)
def connect_to_pot(self, returned_conn_details): if returned_conn_details: if returned_conn_details['success']: self.sensor_name = returned_conn_details['sensor_name'] self.honey_ip = returned_conn_details['honey_ip'] self.honey_port = returned_conn_details['honey_port'] self.username = returned_conn_details['username'] self.password = returned_conn_details['password'] self.auth_packets = [[5, self.to_string('ssh-userauth')], [50, self.to_string(self.username) + self.to_string('ssh-connection') + self.to_string('none')]] if self.sensor_name == self.server.sensor_name and self.honey_ip == self.server.honey_ip and self.honey_port == self.server.honey_port: log.msg(log.LGREEN, '[POST_AUTH]', 'Details the same as pre-auth, not re-directing') self.dont_post_auth() else: self.server.client.loseConnection() self.server.clientConnected = False if not self.server.disconnected: log.msg(log.LGREEN, '[POST_AUTH]', 'Connecting to Honeypot: %s (%s:%s)' % (self.sensor_name, self.honey_ip, self.honey_port)) client_factory = client.HonsshClientFactory() client_factory.server = self.server self.bind_ip = self.server.net.setupNetworking(self.server.peer_ip, self.honey_ip, self.honey_port) self.networkingSetup = True reactor.connectTCP(self.honey_ip, self.honey_port, client_factory, bindAddress=(self.bind_ip, self.server.peer_port+1), timeout=10) pot_connect_defer = threads.deferToThread(self.is_pot_connected) pot_connect_defer.addCallback(self.pot_connected) else: log.msg(log.LBLUE, '[POST_AUTH]', 'SUCCESS = FALSE, NOT POST-AUTHING') self.dont_post_auth() else: log.msg(log.LRED, '[POST_AUTH][ERROR]', 'PLUGIN ERROR - DISCONNECTING ATTACKER') self.server.loseConnection()
def get_connection_details(self): socket = self.cfg.get('honeypot-docker', 'uri') image = self.cfg.get('honeypot-docker', 'image') launch_cmd = self.cfg.get('honeypot-docker', 'launch_cmd') hostname = self.cfg.get('honeypot-docker', 'hostname') honey_port = int(self.cfg.get('honeypot-docker', 'honey_port')) self.docker_drive = docker_driver(socket, image, launch_cmd, hostname) self.container = self.docker_drive.launch_container() log.msg(log.LCYAN, '[PLUGIN][DOCKER]', 'Launched container (%s, %s)' % (self.container['ip'], self.container['id'])) sensor_name = self.container['id'] honey_ip = self.container['ip'] return {'success':True, 'sensor_name':sensor_name, 'honey_ip':honey_ip, 'honey_port':honey_port}
def connection_lost(self, sensor): log.msg(log.LCYAN, "[PLUGIN][HPFEEDS]", "publishing metadata to hpfeeds") sensor["session"].pop("log_location") for channel in sensor["session"]["channels"]: if "class" in channel: channel.pop("class") if "ttylog_file" in channel: fp = open(channel["ttylog_file"], "rb") ttydata = fp.read() fp.close() channel["ttylog"] = ttydata.encode("hex") channel.pop("ttylog_file") log.msg(log.LCYAN, "[PLUGIN][HPFEEDS]", "sessionMeta: " + str(sensor)) self.server.publish(hpfeeds_server.HONSSHSESHCHAN, **sensor)
def extractAttrs(self): cmd = '' flags = '{0:08b}'.format(self.extractInt(4)) if flags[5] == '1': perms = '{0:09b}'.format(self.extractInt(4)) log.msg(log.LPURPLE, self.parent + '[SFTP]', 'PERMS:' + perms) chmod = str(int(perms[:3], 2)) + str(int(perms[3:6], 2)) + str(int(perms[6:], 2)) cmd = 'chmod ' + chmod elif flags[6] == '1': user = str(self.extractInt(4)) group = str(self.extractInt(4)) cmd = 'chown ' + user + ':' + group else: #Unknown attribute log.msg(log.LRED, self.parent + '[SFTP]', 'New SFTP Attribute detected - Please raise a HonSSH issue on github with the details: %s %s' % (flags, self.data)) return cmd
def portForwardLog(self, channelName, connDetails): theDNS = '' try: theDNS = ' (' + socket.gethostbyaddr(connDetails['srcIP'])[0] + ')' except: pass #TODO: LOG SOMEWHERE log.msg(log.LPURPLE, '[OUTPUT]', channelName + ' Source: ' + connDetails['srcIP'] + ':' + str(connDetails['srcPort']) + theDNS) theDNS = '' try: theDNS = ' (' + socket.gethostbyaddr(connDetails['dstIP'])[0] + ')' except: pass #TODO: LOG SOMEWHERE log.msg(log.LPURPLE, '[OUTPUT]', channelName + ' Destination: ' + connDetails['dstIP'] + ':' + str(connDetails['dstPort']) + theDNS)
def removeNetworking(self, connections): if self.cfg.get('advNet', 'enabled') == 'true': if len(connections) == 0: self.removeFakeIP() sp = self.runCommand('ip link del dev honssh') result = sp.communicate() if sp.returncode != 0: log.msg(log.LRED, '[ADV-NET]', 'Error removing HonSSH Interface: ' + result[0]) else: found = False for sensor in connections: for session in sensor['sessions']: if session['peer_ip'] == self.peer_ip: found = True break if not found: self.removeFakeIP()
def sendBack(self, parent, messageNum, payload): packet = self.packetLayout[messageNum] if parent == '[SERVER]': direction = 'HONSSH -> CLIENT' else: direction = 'HONSSH -> SERVER' self.out.packet_logged(direction, packet, payload) if self.cfg.has_option('devmode', 'enabled'): if self.cfg.get('devmode', 'enabled') == 'true': log.msg(log.LBLUE, '[SSH]', direction + ' - ' + packet.ljust(37) + ' - ' + repr(payload)) if parent == '[SERVER]': self.server.sendPacket(messageNum, payload) elif parent == '[CLIENT]': self.client.sendPacket(messageNum, payload)
def sendDisconnect(self, reason, desc): """ http://kbyte.snowpenguin.org/portal/2013/04/30/kippo-protocol-mismatch-workaround/ Workaround for the "bad packet length" error message. @param reason: the reason for the disconnect. Should be one of the DISCONNECT_* values. @type reason: C{int} @param desc: a description of the reason for the disconnection. @type desc: C{str} """ if not 'bad packet length' in desc: # With python >= 3 we can use super? transport.SSHServerTransport.sendDisconnect(self, reason, desc) else: self.transport.write('Protocol mismatch.\n') log.msg(log.LRED, '[SERVER]', 'Disconnecting with error, code %s\nreason: %s' % (reason, desc)) self.transport.loseConnection()
def run_plugins_function(plugins, function, thread, *args, **kwargs): for plugin in plugins: return_value = False class_name = get_plugin_name(plugin).upper() try: func = getattr(plugin, function) if function != 'packet_logged': log.msg(log.LCYAN, '[PLUGIN][' + class_name + ']', function.upper()) if thread: threads.deferToThread(func, *copy.deepcopy(args), **copy.deepcopy(kwargs)) else: return_value = func(*args, **kwargs) if not return_value: return return_value except AttributeError: pass except Exception, ex: log.msg(log.LRED, '[PLUGIN][' + class_name + '][ERR]', str(ex))
def email(self, subject, body): try: #Start send mail code - provided by flofrihandy, modified by peg msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = self.cfg.get('output-email', 'from') msg['To'] = self.cfg.get('output-email', 'to') file_found = False timeout = 0 while not file_found: if not os.path.isfile(body): timeout = timeout + 1 time.sleep(1) else: file_found = True if timeout == 30: break if file_found: time.sleep(2) fp = open(body, 'rb') msg_text = MIMEText(fp.read()) fp.close() msg.attach(msg_text) for tty in self.ttyFiles: fp = open(tty, 'rb') logdata = MIMEBase('application', "octet-stream") logdata.set_payload(fp.read()) fp.close() Encoders.encode_base64(logdata) logdata.add_header('Content-Disposition', 'attachment', filename=os.path.basename(tty)) msg.attach(logdata) s = smtplib.SMTP(self.cfg.get('output-email', 'host'), int(self.cfg.get('output-email', 'port'))) if self.cfg.get('output-email', 'username') != '' and self.cfg.get('output-email', 'password') != '': s.ehlo() if self.cfg.get('output-email', 'use_tls') == 'true': s.starttls() if self.cfg.get('output-email', 'use_smtpauth') == 'true': s.login(self.cfg.get('output-email', 'username'), self.cfg.get('output-email', 'password')) s.sendmail(msg['From'], msg['To'].split(','), msg.as_string()) s.quit() #End send mail code except Exception, ex: log.msg(log.LRED, '[PLUGIN][EMAIL][ERR]', str(ex))
def read(self): if not self.s: return try: d = self.s.recv(BUFSIZ) except socket.timeout: return if not d: self.close() return self.unpacker.feed(d) try: for opcode, data in self.unpacker: log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpclient msg opcode {0} data {1}'.format(opcode, data)) if opcode == OP_INFO: name, rand = strunpack8(data) log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'hpclient server name {0} rand {1}'.format(name, rand)) self.send(msgauth(rand, self.ident, self.secret)) self.state = 'GOTINFO' elif opcode == OP_PUBLISH: ident, data = strunpack8(data) chan, data = strunpack8(data) log.msg(log.LCYAN, '[PLUGIN][HPFEEDS]', 'publish to {0} by {1}: {2}'.format(chan, ident, data)) elif opcode == OP_ERROR: log.err('[PLUGIN][HPFEEDS] - errormessage from server: {0}'.format(data)) else: log.err('[PLUGIN][HPFEEDS] - unknown opcode message: {0}'.format(opcode)) except BadClient: log.err('[PLUGIN][HPFEEDS] - unpacker error, disconnecting.') self.close()