Example #1
0
    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!')
Example #2
0
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
Example #3
0
    def __init__(self):
        self.cfg = Config.getInstance()
        self.timeoutCount = 0
        self.interactors = []

        self.out = None
        self.net = None
        self.sshParse = None

        self.wasConnected = False
        self.disconnected = False
        self.clientConnected = False
        self.post_auth_started = False
        self.spoofed = False

        self.peer_ip = None
        self.peer_port = 0
        self.local_ip = None
        self.local_port = 0

        self.pre_auth = None
        self.post_auth = None

        self.sensor_name = None
        self.honey_ip = None
        self.honey_port = 0
Example #4
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.connection_timeout = self.cfg.getint(
         ['honeypot', 'connection_timeout'])
     self.docker_drive = None
     self.container = None
     self.sensor_name = None
     self.peer_ip = None
     self.channel_open = False
Example #5
0
    def __init__(self, server, name):
        self.server = server
        self.name = name
        self.auth_plugin = None
        self.cfg = Config.getInstance()

        self.connection_timeout = 10
        self.conn_details = None

        self.finishedSending = False
        self.delayedPackets = []
        self.networkingSetup = False
Example #6
0
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)
Example #7
0
 def __init__(self, factory):
     self.cfg = Config.getInstance()
     self.connections = factory.connections
     self.plugin_servers = factory.plugin_servers
     self.loaded_plugins = None
     self.sensor_name = None
     self.honey_ip = None
     self.honey_port = None
     self.end_ip = None
     self.end_port = None
     self.session_id = None
     self.logLocation = None
     self.downloadFolder = None
Example #8
0
def import_plugins(plugins, search=None):
    from honssh.config import Config
    cfg = Config.getInstance()

    plugin_list = []
    for plugin in plugins:
        cfg_section = plugin.split('/')[-1]
        if cfg.getboolean([cfg_section, 'enabled']):
            if search:
                if cfg.getboolean([cfg_section, search]):
                    plugin_list.append(import_plugin(plugin))
            else:
                plugin_list.append(import_plugin(plugin))
    return plugin_list
Example #9
0
    def __init__(self, server, out):
        super(SSH, self).__init__()

        self.channels = []
        self.username = ''
        self.password = ''

        self.cfg = Config.getInstance()

        self.sendOn = False
        self.out = out
        self.server = server
        self.channels = []
        self.client = None
Example #10
0
    def __init__(self, server, out):
        super(SSH, self).__init__()

        self.channels = []
        self.real_username = '******'
        self.password = ''
        self.auth_type = ''

        self.cfg = Config.getInstance()

        self.sendOn = False
        self.expect_password = 0
        self.out = out
        self.server = server
        self.channels = []
        self.client = None
Example #11
0
def write_spoof_log(conn_details):
    cfg = Config.getInstance()

    logfile = cfg.get(['folders', 'log_path']) + '/spoof.log'
    username = conn_details['username']
    password = conn_details['password']
    ip = conn_details['peer_ip']
    #spi
    tg.tgMessage(
        "[1] New Attacker from {} ({}/{})".format(ip, username, password), 1)
    set_permissions = False
    found = False

    if os.path.isfile(logfile):
        f = file(logfile, 'r')
        lines = f.readlines()
        f.close()

        for i in range(len(lines)):
            lines[i] = lines[i].strip().split(' - ')
            if lines[i][0] == username and lines[i][1] == password:
                found = True
                if ip not in lines[i][2:]:
                    lines[i].append(ip)

        f = file(logfile, 'w')

        for line in lines:
            f.write(' - '.join(line) + '\n')

        if not found:
            f.write("%s - %s - %s\n" % (username, password, ip))

        f.close()
    else:
        f = file(logfile, 'a')
        f.write("%s - %s - %s\n" % (username, password, ip))
        f.close()
        set_permissions = True

    if set_permissions:
        os.chmod(logfile, 0644)
Example #12
0
    def __init__(self, out, uuid, chan_name, command, ssh, blocked):
        super(ExecTerm, self).__init__(uuid, chan_name, ssh)

        self.cfg = Config.getInstance()
        self.out = out
        self.out.register_self(self)

        if command.startswith('scp'):
            self.scp = True
            self.fileName = ''
            self.file = ''
            self.size = -1
        else:
            self.scp = False
            self.ttylog_file = self.out.logLocation + datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") \
                               + '_' + self.name[1:-1] + '.tty'
            self.out.open_tty(self.uuid, self.ttylog_file)
            self.out.input_tty(self.ttylog_file, 'INPUT: ' + command + '\n\n')

        self.out.command_entered(self.uuid, command, blocked=blocked)
Example #13
0
def cleanup(ttl):
    # Get config
    from honssh.config import Config
    cfg = Config.getInstance()

    # Create client
    socket = cfg.get(['honeypot-docker', 'uri'])
    client = Client(socket)

    # Get all stopped containers
    containers = client.containers(quiet=False,
                                   all=True,
                                   filters={'status': ['exited']})

    # Get now
    now = int(time.time())

    # Convert to seconds
    ttl_secs = (ttl * 60)

    for c in containers:
        c_id = c['Id']

        # Get container info
        ins = client.inspect_container(c_id)
        # Extract date
        finished_at = convert_json_datetime(ins['State']['FinishedAt'])

        # Create time diff in minutes
        diff = now - finished_at

        # Check exceeds ttl and remove container if needed
        if diff > ttl_secs:
            log.msg(log.LYELLOW, '[PLUGIN][DOCKER][CLEANUP]',
                    'Removing container %s' % c_id)
            client.remove_container(c_id, force=True)
    def __init__(self):
        self.cfg = Config.getInstance()
        self.server = None
        host = self.cfg.get(['output-elasticsearch', 'host']),
        port = self.cfg.get(['output-elasticsearch', 'port']),
        user = self.cfg.get(['output-elasticsearch', 'username']),
        passwd = self.cfg.get(['output-elasticsearch', 'password']),
        tup1 = {'username': user, 'password': passwd}
        es = ES(server=host[0] + ":" + port[0], basic_auth=tup1)
        try:
            es.indices.create_index("attacks")
        except:
            print "already there"
        mapping = {
            'ip': {
                'store': 'yes',
                'type': 'keyword',
            },
            'username': {
                'store': 'yes',
                'type': 'keyword',
            },
            'password': {
                'store': 'yes',
                'type': 'keyword',
            },
            'entered_time': {
                'store': 'yes',
                'type': 'date',
                'format': 'dd MMM yyyy HH:mm:ss'
            }
        }
        es.indices.put_mapping("ssh_auth_details", {'properties': mapping},
                               ["attacks"])

        mapping = {
            'ip': {
                'store': 'yes',
                'type': 'keyword',
            },
            'country': {
                'store': 'yes',
                'type': 'keyword',
            },
            'location': {
                'store': 'yes',
                'type': 'geo_point',
            },
            'attack_start_time': {
                'store': 'yes',
                'type': 'date',
                'format': 'dd MMM yyyy HH:mm:ss'
            },
            'attack_end_time': {
                'store': 'yes',
                'type': 'date',
                'format': 'dd MMM yyyy HH:mm:ss'
            }
        }
        es.indices.put_mapping("ssh_connections", {'properties': mapping},
                               ["attacks"])

        mapping = {
            'ip': {
                'store': 'yes',
                'type': 'keyword',
            },
            'country': {
                'store': 'yes',
                'type': 'keyword',
            },
            'location': {
                'store': 'yes',
                'type': 'geo_point',
            },
            'attack_time': {
                'store': 'yes',
                'type': 'date',
                'format': 'dd MMM yyyy HH:mm:ss'
            },
            'protocol': {
                'store': 'yes',
                'type': 'keyword',
            }
        }
        es.indices.put_mapping("connections", {'properties': mapping},
                               ["attacks"])
Example #15
0
from docker import Client
from time import sleep
from honssh.config import Config

client = Client()
conf = Config.getInstance()
honssh_guest_image = conf.get(['honeypot-docker', 'image'])
print("[cleanupd.py][+ ] HONSSH_GUEST_IMAGE = " + honssh_guest_image)

while True:
    print("[cleanupd.py][+ ] Polling!")
    containers = client.containers()
    for container in containers:
        if not honssh_guest_image in container['Image']:
            continue
        time = 0
        time_unit = ''
        try:
            # expect status to be in format of 'up <time> <time_unit>'; time=int, time_unit=seconds/minutes/hours
            status = container['Status']
            _, time, time_unit = status.split(' ')
            time = int(time)
        except:
            continue
        if time > 5 and time_unit == 'minutes':
            print("[cleanupd.py][+ ] Killing container " +
                  container['Names'][0])
            client.kill(container['Id'])
    sleep(30)
Example #16
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.login_success = False
     self.ttyFiles = []
     self.log_file = None
Example #17
0
from honssh.config import Config
from twisted.python import log

PLAIN = '\033[0m'
RED = '\033[0;31m'
LRED = '\033[1;31m'
GREEN = '\033[0;32m'
LGREEN = '\033[1;32m'
YELLOW = '\033[0;33m'
LYELLOW = '\033[1;33m'
BLUE = '\033[0;34m'
LBLUE = '\033[1;34m'
PURPLE = '\033[0;35m'
LPURPLE = '\033[1;35m'
CYAN = '\033[0;36m'
LCYAN = '\033[1;36m'

cfg = Config.getInstance()


def msg(color, identifier, message):
    if not isinstance(message, basestring):
        message = repr(message)

    if cfg.has_option('devmode', 'enabled') and cfg.getboolean(
        ['devmode', 'enabled']):
        log.msg(color + identifier + ' - ' + message + '\033[0m')
    else:
        log.msg(identifier + ' - ' + message)
Example #18
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.auth_attempts = []
     self.login_success = False
     self.auth_log_file = None
     self.log_file = None
Example #19
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.peer_ip = None
     self.fake_ip = None
     self.honey_port = None
     self.honey_ip = None
Example #20
0
 def __init__(self):
     self.cfg = Config.getInstance()
Example #21
0
def get_connection_details(conn_details):
    cfg = Config.getInstance()

    if cfg.getboolean(['spoof', 'totalspoof_enabled']):
        username, password = get_first_user_credentials()
        write_spoof_log(conn_details)
        return True, username, password

    elif cfg.getboolean(['spoof', 'enabled']):
        # Get credentials for username
        credentials = get_credentials(conn_details['username'])
        password = None

        if credentials is not None:
            for cred in credentials:
                # Check for real password match
                if cred[1] == conn_details['password']:
                    log.msg(
                        log.LYELLOW, '[SPOOF]', 'Real password match %s/%s' %
                        (cred[0], conn_details['password']))
                    password = cred[1]
                    break
                else:
                    # Check fixed password allowed
                    if cred[2] == 'fixed':
                        passwords = re.sub(r'\s', '', cred[3]).split(',')

                        # Check for fixed password match
                        if conn_details['password'] in passwords:
                            log.msg(
                                log.LYELLOW, '[SPOOF]',
                                'Fixed password match %s/%s' %
                                (cred[0], conn_details['password']))
                            password = cred[1]
                            break
                    # Check random password chance allowed
                    elif cred[2] == 'random':
                        # Try already used credentials from spoof log
                        logfile = cfg.get(['folders', 'log_path'
                                           ]) + "/spoof.log"

                        if os.path.isfile(logfile):
                            f = file(logfile, 'r')
                            used_credentials = f.read().splitlines()
                            f.close()

                            for used_credential in used_credentials:
                                used_credential = used_credential.strip(
                                ).split(' - ')
                                if used_credential[0] == conn_details[
                                        'username'] and used_credential[
                                            1] == conn_details['password']:
                                    # Match - set password
                                    log.msg(
                                        log.LYELLOW, '[SPOOF]',
                                        'Spoof.log password match %s/%s' %
                                        (cred[0], conn_details['password']))
                                    password = cred[1]
                                    break

                            # Break out from loop on match
                            if password is not None:
                                break

                        # Check for random password chance
                        if int(cred[3]) > 0:
                            random_factor = (100 / int(cred[3])) + 1
                            rand = random.randrange(1, random_factor)

                            if rand == 1:
                                # Match - set password
                                log.msg(
                                    log.LYELLOW, '[SPOOF]',
                                    'Random password match %s/%s' %
                                    (cred[0], conn_details['password']))
                                password = cred[1]
                                break

        # Do we have a match?
        if password is not None:
            write_spoof_log(conn_details)
            return True, conn_details['username'], password

    # No match!
    return False, '', ''
Example #22
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.log_file = None
Example #23
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.connection_timeout = self.cfg.getint(
         ['honeypot', 'connection_timeout'])
Example #24
0
 def __init__(self):
     self.cfg = Config.getInstance()
     self.server = None