Пример #1
0
    def __init__(self):
        cfg = config()

        # protocol^Wwhatever instances are kept here for the interact feature
        self.sessions = {}

        # for use by the uptime command
        self.starttime = time.time()

        # load db loggers
        self.dbloggers = []
        for x in cfg.sections():
            if not x.startswith('database_'):
                continue
            engine = x.split('_')[1]
            dbengine = 'database_' + engine
            lcfg = ConfigParser.ConfigParser()
            lcfg.add_section(dbengine)
            for i in cfg.options(x):
                lcfg.set(dbengine, i, cfg.get(x, i))
            lcfg.add_section('honeypot')
            for i in cfg.options('honeypot'):
                lcfg.set('honeypot', i, cfg.get('honeypot', i))
            print 'Starting Database Logging engine: %s' % (engine, )
            dblogger = __import__('sinh.dblog.%s' % (engine, ), globals(),
                                  locals(), ['dblog']).DBLogger(lcfg)
            log.startLoggingWithObserver(dblogger.emit, setStdout=False)
            self.dbloggers.append(dblogger)
Пример #2
0
 def __init__(self):
     self.cfg = config()
     self.commands = {}
     import sinh.commands
     for c in sinh.commands.__all__:
         module = __import__('sinh.commands.%s' % c, globals(), locals(), ['commands'])
         self.commands.update(module.commands)
     self.fs = pickle.load(file(self.cfg.get('honeypot', 'filesystem_file'), 'rb'))
Пример #3
0
    def save(self):
        """ save the user db """

        userdb_file = '%s/userdb.txt' % \
            (config().get('honeypot', 'data_path'),)

        f = open(userdb_file, 'w')
        for (login, uid, passwd) in self.userdb:
            f.write('%s:%d:%s\n' % (login, uid, passwd))
        f.close()
Пример #4
0
    def connectionMade(self):
        transport = self.transport.session.conn.transport

        transport.ttylog_file = '%s/tty/%s-%s.log' % \
            (config().get('honeypot', 'log_path'),
            time.strftime('%Y%m%d-%H%M%S'),
            int(random.random() * 10000))
        print 'Opening TTY log: %s' % transport.ttylog_file
        ttylog.ttylog_open(transport.ttylog_file, time.time())

        transport.ttylog_open = True

        insults.ServerProtocol.connectionMade(self)
Пример #5
0
    def file_contents(self, target, count = 0):
        if count > 10:
            raise TooManyLevels
        path = self.resolve_path(target, os.path.dirname(target))
        print '%s resolved into %s' % (target, path)
        if not path or not self.exists(path):
            raise FileNotFound
        f = self.getfile(path)
        if f[A_TYPE] == T_LINK:
            return self.file_contents(f[A_TARGET], count + 1)

        realfile = self.realfile(f, '%s/%s' % (config().get('honeypot', 'contents_path'), path))
        if realfile:
            return file(realfile, 'rb').read()
Пример #6
0
    def execCommand(self, protocol, cmd):
        cfg = config()
        if not cfg.has_option('honeypot', 'exec_enabled') or \
                cfg.get('honeypot', 'exec_enabled').lower() not in \
                    ('yes', 'true', 'on'):
            print 'Exec disabled. Not executing command: "%s"' % cmd
            raise core.exceptions.NotEnabledException, \
                'exec_enabled not enabled in configuration file!'
            return

        print 'exec command: "%s"' % cmd
        serverProtocol = sinh.core.protocol.LoggingServerProtocol(
            sinh.core.protocol.HoneyPotExecProtocol, self, self.env, cmd)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))
Пример #7
0
 def call(self):
     fn = '%s/lastlog.txt' % (config().get('honeypot', 'data_path'),)
     if not os.path.exists(fn):
         return
     l = list(self.args)
     numlines = 25
     while len(l):
         arg = l.pop(0)
         if not arg.startswith('-'):
             continue
         elif arg[1:].isdigit():
             numlines = int(arg[1:])
         elif arg == '-n' and len(l) and l[0].isdigit():
             numlines = int(l.pop(0))
     data = utils.tail(file(fn), numlines)
     self.writeln(''.join(data))
Пример #8
0
    def connectionMade(self):
        self.displayMOTD()

        transport = self.terminal.transport.session.conn.transport

        self.realClientIP = transport.transport.getPeer().host
        self.clientVersion = transport.otherVersionString
        self.logintime = transport.logintime
        self.ttylog_file = transport.ttylog_file

        # source IP of client in user visible reports (can be fake or real)
        cfg = config()
        if cfg.has_option('honeypot', 'fake_addr'):
            self.clientIP = cfg.get('honeypot', 'fake_addr')
        else:
            self.clientIP = self.realClientIP
Пример #9
0
 def sendBanner(self):
     """Implemented to show pop up banner when attacker logged in."""
     if self.bannerSent:
         return
     cfg = config()
     if not cfg.has_option('honeypot', 'banner_file'):
         return
     try:
         data = file(cfg.get('honeypot', 'banner_file')).read()
     except IOError:
         print 'Banner file %s does not exist!' % \
             cfg.get('honeypot', 'banner_file')
         return
     if not data or not len(data.strip()):
         return
     data = '\r\n'.join(data.splitlines() + [''])
     self.transport.sendPacket(userauth.MSG_USERAUTH_BANNER,
                               NS(data) + NS('en'))
     self.bannerSent = True
Пример #10
0
    def buildProtocol(self, addr):
        """
        Create an instance of the server side of the SSH protocol.

        @type addr: L{twisted.internet.interfaces.IAddress} provider
        @param addr: The address at which the server will listen.

        @rtype: L{twisted.conch.ssh.SSHServerTransport}
        @return: The built transport.
        """

        _modulis = '/etc/ssh/moduli', '/private/etc/moduli'

        cfg = config()

        # FIXME: try to mimic something real 100%
        t = HoneyPotTransport()

        if cfg.has_option('honeypot', 'ssh_version_string'):
            t.ourVersionString = cfg.get('honeypot', 'ssh_version_string')
        else:
            t.ourVersionString = "SSH-2.0-OpenSSH_5.1p1 Debian-5"

        t.supportedPublicKeys = self.privateKeys.keys()

        for _moduli in _modulis:
            try:
                self.primes = primes.parseModuliFile(_moduli)
                break
            except IOError as err:
                pass

        if not self.primes:
            ske = t.supportedKeyExchanges[:]
            ske.remove('diffie-hellman-group-exchange-sha1')
            t.supportedKeyExchanges = ske

        t.factory = self
        return t
Пример #11
0
    def load(self):
        """ load the user db file which is custom credentials
            created and stored in data/userdb.txt """

        userdb_file = '%s/userdb.txt' % (config().get('honeypot', 'data_path'),)

        f = open(userdb_file, 'r')
        while True:
            line = f.readline()
            if not line:
                break
            line = string.strip(line)
            if not line:
                continue
            (login, uid_str, passwd) = line.split(':', 2)
            uid = 0
            try:
                uid = int(uid_str)
            except ValueError:
                uid = 1001

            self.userdb.append((login, uid, passwd))

        f.close()
Пример #12
0
def getDSAKeys():
    """Get or generate DSA key pair"""
    cfg = config()
    public_key = cfg.get('honeypot', 'dsa_public_key')
    private_key = cfg.get('honeypot', 'dsa_private_key')
    if not (os.path.exists(public_key) and os.path.exists(private_key)):
        print "Generating new DSA keypair..."
        from Crypto.PublicKey import DSA
        from twisted.python import randbytes
        KEY_LENGTH = 1024
        dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom)
        publicKeyString = keys.Key(dsaKey).public().toString('openssh')
        privateKeyString = keys.Key(dsaKey).toString('openssh')
        with file(public_key, 'w+b') as f:
            f.write(publicKeyString)
        with file(private_key, 'w+b') as f:
            f.write(privateKeyString)
        print "Done."
    else:
        with file(public_key) as f:
            publicKeyString = f.read()
        with file(private_key) as f:
            privateKeyString = f.read()
    return publicKeyString, privateKeyString
Пример #13
0
def addToLastlog(message):
    """add entry in last log"""
    f = file('%s/lastlog.txt' % config().get('honeypot', 'data_path'), 'a')
    f.write('%s\n' % (message, ))
    f.close()