#!/usr/bin/env python
#
# Super simple sshd that just logs username/passwd
# 
# This is very much work in progress.
# Works here<tm>
#
# Todo:
#  * spawn external command when someone tries to acces
#     (blacklist ip in real services or something)
#  * sometimes accept logins an see what they try to do
#
# (C) 2005 Anders Gustafsson
# Use at own risk

from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log, context
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import IUsernamePassword
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
import sys
import os

logfile = file("honeysshd.log","w+")
class LogObserver:
    def _emit(self, ev):
    	global logfile
        if ev['system'] != '-':
            logfile.write("%s - %s\n" % (ev['system'],"".join(ev['message'])))
	    logfile.flush()

log.startLoggingWithObserver(LogObserver()._emit, 0)

class SimpleRealm:
    __implements__ = portal.IRealm

    def requestAvatar(self, avatarId, mind, *interfaces):
        return None

class PassChecker:
    credentialInterfaces = IUsernamePassword,
    __implements__ = ICredentialsChecker

    def requestAvatarId(self, credentials):
        log.msg("login attempt with %s:%s" % (credentials.username, credentials.password))
        return defer.fail(UnauthorizedLogin())


class sshdFactory(factory.SSHFactory):
    def __init__(self):
        keybase=os.tempnam()
        os.system('ssh-keygen -t rsa -N "" -f %s' % keybase)
        privateKey = file(keybase).read()
        publicKey = file(keybase+".pub").read()
        os.unlink(keybase)
        os.unlink(keybase+".pub")
        
        self.publicKeys = {
            'ssh-rsa': keys.getPublicKeyString(data=publicKey)
            }
        self.privateKeys = {
            'ssh-rsa': keys.getPrivateKeyObject(data=privateKey)
            }
        self.services = {
            'ssh-userauth': userauth.SSHUserAuthServer,
            }

portal = portal.Portal(SimpleRealm())
portal.registerChecker(PassChecker())
sshdFactory.portal = portal

#FEL FEL FEL
#from twisted.application import service, internet
#factory = protocol.ServerFactory()
#factory.protocol = sshdFactory
#application = service.Application("honeysshd")
#internet.TCPServer(5022, factory).setServiceParent(application)

if __name__ == '__main__':
    reactor.listenTCP(5022, sshdFactory())
    reactor.run()

