def listen(self, port):
		'''
		Starts listening on the specified port.
		'''
		portal = Portal(credentials.Realm())
		portal.registerChecker(credentials.PasswordChecker(self.__passwd))
		reactor.listenTCP(port, ServerProtocolFactory(portal, self.userlist))
    def setUp(self):
        super(RootTests, self).setUp()

        self.docroot = self.mktemp()
        os.mkdir(self.docroot)

        RootResource.CheckSACL = FakeCheckSACL(sacls={"calendar": ["dreid"]})

        directory = XMLDirectoryService({"xmlFile" : xmlFile})
        augment.AugmentService = augment.AugmentXMLDB(
            xmlFiles=(augmentsFile.path,)
        )

        principals = DirectoryPrincipalProvisioningResource(
            "/principals/",
            directory
        )

        root = RootResource(self.docroot, principalCollections=[principals])

        root.putChild("principals",
                      principals)

        portal = Portal(auth.DavRealm())
        portal.registerChecker(directory)

        self.root = auth.AuthenticationWrapper(
            root,
            portal,
            credentialFactories=(basic.BasicCredentialFactory("Test realm"),),
            loginInterfaces=(auth.IPrincipal,))

        self.site = server.Site(self.root)
Beispiel #3
0
 def createPortal(self, realmFactory=None):
     if realmFactory is None:
         realmFactory = SillyRealm
     r = realmFactory()
     p = Portal(r)
     p.registerChecker(AllowAnonymousAccess(), IAnonymous)
     return p
Beispiel #4
0
 def portal(self):
   portal = Portal(self.realm())
   for checker in self.auth_checkers():
     portal.registerChecker(checker)
   if len(self.auth_checkers()) == 0:
     portal.registerChecker(checkers.AllowAnonymousAccess())
   return portal
Beispiel #5
0
def makeService(config):
    components.registerAdapter(
        GitSession,
        GitAvatar,
        session.ISession)

    with open(config['conf']) as f:
        conf = yaml.load(f.read())

    port = int(conf.get('port', 22))
    host_key = conf.get('host_key')
    driver_key = conf.get('driver', 'example')

    log.msg('Using driver: \'%s\'' % driver_key)

    mgr = driver.DriverManager(
        namespace='gitserver.driver',
        name=driver_key,
        invoke_on_load=False
    )

    portal = Portal(GitRealm(mgr))
    portal.registerChecker(GitPublicKeyChecker(mgr))

    # factory.SSHFactory takes no arguments, so unlike the
    # websocket server, we will assign portal on the class
    # rather than through the constructor.
    # TypeError: this constructor takes no arguments
    # is raised if we pass portal GitFactory(portal)
    GitFactory.portal = portal
    GitSession.driver_key = driver_key

    return internet.TCPServer(port, GitFactory(host_key=host_key))
 def setUp(self):
     self.realm = Realm()
     portal = Portal(self.realm)
     portal.registerChecker(MockChecker())
     self.authServer = userauth.SSHUserAuthServer()
     self.authServer.transport = FakeTransport(portal)
     self.authServer.serviceStarted()
Beispiel #7
0
    def test_unencryptedConnectionWithoutPasswords(self):
        """
        If the L{SSHUserAuthServer} is not advertising passwords, then an
        unencrypted connection should not cause any warnings or exceptions.
        This is a white box test.
        """
        # create a Portal without password authentication
        portal = Portal(self.realm)
        portal.registerChecker(PrivateKeyChecker())

        # no encryption
        clearAuthServer = userauth.SSHUserAuthServer()
        clearAuthServer.transport = FakeTransport(portal)
        clearAuthServer.transport.isEncrypted = lambda x: False
        clearAuthServer.serviceStarted()
        clearAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                          ['publickey'])

        # only encrypt incoming (the direction the password is sent)
        halfAuthServer = userauth.SSHUserAuthServer()
        halfAuthServer.transport = FakeTransport(portal)
        halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
        halfAuthServer.serviceStarted()
        halfAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                          ['publickey'])
Beispiel #8
0
def deploy(iface, port, dbLocation, dbType, dbUsername=None, dbPassword=None,
           ssl=False, sslRedirect=False, sslPrivate=None, sslCert=None,
           sslPort=None):

    if dbUsername and dbPassword:
        searchService = searchServices[dbType](
            dbLocation, dbUsername, dbPassword)
    else:
        searchService = searchServices[dbType](dbLocation)

    portal = Portal(PublicHTMLRealm(searchService), [AllowAnonymousAccess()])
    portal.registerChecker(QuasselChecker(searchService), IUsernameHashedPassword)
    portal.registerChecker(SessionChecker(), ISessionCredentials)

    application = service.Application("Querryl")
    site = server.Site(BasicWrapper(portal, []))
    site.sessionFactory = LongSession

    if ssl:
        ctx = DefaultOpenSSLContextFactory(sslPrivate, sslCert)
        ssl_sv = internet.SSLServer(sslPort, site, ctx, interface=iface)
        ssl_sv.setServiceParent(application)

        if sslRedirect:
            site = server.Site(RedirectFromRequest(port=sslPort))

    sv = internet.TCPServer(port, site, interface=iface)
    sv.setServiceParent(application)
    return sv
 def __init__(self, conf):
     self._init_keys(conf)
     config = cwconfig.instance_configuration(conf.get('cubicweb-instance'))
     repo = Repository(config, TasksManager(), vreg=None)
     portal = Portal(CubicWebSFTPRealm(repo, conf))
     portal.registerChecker(CubicWebCredentialsChecker(repo))
     self.portal = portal
Beispiel #10
0
    def makeService(self, options):
        class LongSession(Session):
            sessionTimeout = 3600

        if options['steamkey'] is None:
            raise ValueError('Must specify steam API key.')
        if options['strport'] is None:
            raise ValueError('Must specify strport description.')
        if options['dbdir'] is None:
            raise ValueError('Must specify database path.')
        steamAPI = API(key=options['steamkey'])

        store = Store(options['dbdir'])
        keyPath = FilePath(options['dbdir']).child('fernet.key')

        database = Database(store)

        loginRedirect = '/'
        portal = Portal(MapListRealm(database, options['bundle-path'],
                                     steamAPI, loginRedirect))
        portal.registerChecker(PreauthenticatedChecker())
        portal.registerChecker(AllowAnonymousAccess())

        root = HTTPOpenIDAuthSessionWrapper(portal, [], loginRedirect, keyPath,
                                            database)

        site = Site(root)
        site.sessionFactory = LongSession
        return strports.service(options['strport'], site)
Beispiel #11
0
def main_ssh2http():
    portal = Portal(ExampleRealm())
    c_port = 5022
    factory = SSH2HTTPConverterFactory(c_port)
    portal.registerChecker(factory)
    SSH2HTTPConverterFactory.portal = portal
    reactor.listenTCP(c_port, factory)
Beispiel #12
0
def create_portal(a):
    """I'm responsible for creating the authenticated portal"""
    realm = AggregatorRealm(a)
    portal = Portal(realm)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(version.apiversion, a.getPassword())
    portal.registerChecker(checker)
    return portal
Beispiel #13
0
def makeService(options):
    """
    Makes a new swftp-ftp service. The only option is the config file
    location. The config file has the following options:
     - host
     - port
     - auth_url
     - num_persistent_connections
     - connection_timeout
     - welcome_message
    """
    from twisted.protocols.ftp import FTPFactory
    from twisted.web.client import HTTPConnectionPool
    from twisted.cred.portal import Portal

    from swftp.ftp.server import SwiftFTPRealm
    from swftp.auth import SwiftBasedAuthDB
    from swftp.utils import print_runtime_info

    print('Starting SwFTP-ftp %s' % VERSION)

    c = get_config(options['config_file'], options)
    ftp_service = service.MultiService()

    # Add statsd service
    if c.get('ftp', 'log_statsd_host'):
        try:
            from swftp.statsd import makeService as makeStatsdService
            makeStatsdService(
                c.get('ftp', 'log_statsd_host'),
                c.getint('ftp', 'log_statsd_port'),
                sample_rate=c.getfloat('ftp', 'log_statsd_sample_rate'),
                prefix=c.get('ftp', 'log_statsd_metric_prefix')
            ).setServiceParent(ftp_service)
        except ImportError:
            log.err('Missing Statsd Module. Requires "txstatsd"')

    pool = HTTPConnectionPool(reactor, persistent=True)
    pool.maxPersistentPerHost = c.getint('ftp', 'num_persistent_connections')
    pool.cachedConnectionTimeout = c.getint('ftp', 'connection_timeout')

    authdb = SwiftBasedAuthDB(auth_url=c.get('ftp', 'auth_url'),
                              verbose=c.getboolean('ftp', 'verbose'))

    ftpportal = Portal(SwiftFTPRealm())
    ftpportal.registerChecker(authdb)
    ftpfactory = FTPFactory(ftpportal)
    ftpfactory.welcomeMessage = c.get('ftp', 'welcome_message')
    ftpfactory.allowAnonymous = False

    signal.signal(signal.SIGUSR1, print_runtime_info)
    signal.signal(signal.SIGUSR2, print_runtime_info)

    internet.TCPServer(
        c.getint('ftp', 'port'),
        ftpfactory,
        interface=c.get('ftp', 'host')).setServiceParent(ftp_service)
    return ftp_service
Beispiel #14
0
def main():
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("benchmark", "benchmark")
    portal.registerChecker(checker)
    reactor.listenTCP(8787, pb.PBServerFactory(portal))
    reactor.run()
Beispiel #15
0
class OpenRukoSSHServer(SSHFactory):


    def __init__(self, settings):
        self.settings = settings
        self.portal = Portal(OpenRukoRealm(settings))
        self.portal.registerChecker(OpenRukoCredentialChecker(settings))
        self.privateKeys = {'ssh-rsa': Key.fromFile(settings['gitmouth_private_key'])}
        self.publicKeys = {'ssh-rsa': Key.fromFile(settings['gitmouth_public_key'])}
Beispiel #16
0
def adminWrapper(data):
    """Ties it together"""
    p = Portal(AdminRealm(data))
    p.registerChecker(AllowAnonymousAccess(), IAnonymous)
    p.registerChecker(data.players, IUsernamePassword)
    upw = guard.UsernamePasswordWrapper(p, callback=dumbRedirect)
    r = guard.SessionWrapper(upw)
    r.sessionLifetime = 12 * 3600
    return r
def StartServices(username,password):
    from md5 import md5
    password = md5(password).digest()
    
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username,password)
    portal.registerChecker(checker)
    reactor.listenTCP(7001,pb.PBServerFactory(portal))
    def createDocumentRoot(self):
        docroot = self.mktemp()
        os.mkdir(docroot)

        userResource = TestDAVPrincipalResource("/principals/users/user01")
        userResource.writeDeadProperty(TwistedPasswordProperty("user01"))

        principalCollection = TestPrincipalsCollection(
            "/principals/",
            children={"users": TestPrincipalsCollection(
                    "/principals/users/",
                    children={"user01": userResource})})

        rootResource = self.resource_class(
            docroot, principalCollections=(principalCollection,))

        portal = Portal(DavRealm())
        portal.registerChecker(TwistedPropertyChecker())

        credentialFactories = (basic.BasicCredentialFactory(""),)

        loginInterfaces = (IPrincipal,)

        self.site = Site(AuthenticationWrapper(
            rootResource,
            portal,
            credentialFactories,
            credentialFactories,
            loginInterfaces
        ))

        rootResource.setAccessControlList(self.grant(element.All()))

        for name, acl in (
            ("none"       , self.grant()),
            ("read"       , self.grant(element.Read())),
            ("read-write" , self.grant(element.Read(), element.Write())),
            ("unlock"     , self.grant(element.Unlock())),
            ("all"        , self.grant(element.All())),
        ):
            filename = os.path.join(docroot, name)
            if not os.path.isfile(filename):
                file(filename, "w").close()
            resource = self.resource_class(filename)
            resource.setAccessControlList(acl)

        for name, acl in (
            ("nobind" , self.grant()),
            ("bind"   , self.grant(element.Bind())),
            ("unbind" , self.grant(element.Bind(), element.Unbind())),
        ):
            dirname = os.path.join(docroot, name)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            resource = self.resource_class(dirname)
            resource.setAccessControlList(acl)
        return docroot
Beispiel #19
0
    def __init__(self, soledad_sessions, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = LocalSoledadIMAPRealm(soledad_sessions)
        portal = Portal(realm)
        checker = IMAPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
def StartServices():
    #fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5
    password = md5("daemon").digest()
    for x in range(0,100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7000,pb.PBServerFactory(portal))
Beispiel #21
0
 def startService(self):
     Plugin.startService(self)
     if not self._inputs == []:
         portal = Portal(CollectorRealm(self))
         portal.registerChecker(AllowAnonymousAccess())
         factory = PBServerFactory(portal)
         self._listener = reactor.listenTCP(self._port, factory, interface=self._address)
         logger.info("[%s] listening for remote messages on %s:%i" % (self.name,self._address,self._port))
     else:
         logger.info("[%s] no inputs configured" % self.name)
Beispiel #22
0
    def __init__(self, account, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = TestRealm(account)
        portal = Portal(realm)
        checker = TestCredentialsChecker()
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Beispiel #23
0
def main():
    from twisted.internet import reactor
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
    reactor.run()
Beispiel #24
0
def setup():
    from twisted.internet import reactor
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse


    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)

    reactor.listenTCP(7777, ConsoleSMTPFactory(portal))
Beispiel #25
0
    def setServiceParent(self, parent):
        service.MultiService.setServiceParent(self, parent)

        portal = Portal(PbRealm(parent))

        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        portal.registerChecker(checker)

        s = strports.service("unix:%s" % self.socket, pb.PBServerFactory(portal))
        s.setServiceParent(self)
Beispiel #26
0
    def __init__(self, soledad_sessions, keymanager_sessions, sendmail_opts,
                 encrypted_only=False):
        realm = LocalSMTPRealm(
            keymanager_sessions, soledad_sessions, sendmail_opts,
            encrypted_only)
        portal = Portal(realm)

        checker = SMTPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Beispiel #27
0
class CleanerSite(Site, Loggable):
    def __init__(self, firewall):
        self.user = cattivo.config.get("cleaner", "user")
        self.passwd_file = cattivo.config.get("cleaner", "passwd-file")
        checker = FilePasswordDB(self.passwd_file)
        self.realm = CleanerRealm()
        self.portal = Portal(self.realm)
        self.portal.registerChecker(checker)
        self.firewall = firewall
        Site.__init__(self, CleanerResource(self.portal))
        Loggable.__init__(self)
Beispiel #28
0
    def testUpgrade(self):
        p = Portal(IRealm(self.store),
                   [ICredentialsChecker(self.store)])

        def loggedIn((interface, avatarAspect, logout)):
            # if we can login, i guess everything is fine
            self.assertEquals(avatarAspect.garbage, GARBAGE_LEVEL)

        creds = UsernamePassword('@'.join(CREDENTIALS[:-1]), CREDENTIALS[-1])
        d = p.login(creds, None, IGarbage)
        return d.addCallback(loggedIn)
Beispiel #29
0
    def testUpgrade(self):
        p = Portal(IRealm(self.store),
                   [ICredentialsChecker(self.store)])

        def loggedIn((ifc, av, lgo)):
            assert av.garbage == 7
            # Bug in cooperator?  this triggers an exception.
            # return svc.stopService()
        d = p.login(
            UsernamePassword('*****@*****.**', SECRET), None, IGarbage)
        return d.addCallback(loggedIn)
Beispiel #30
0
class SSHFactory(factory.SSHFactory):
    def __init__(self, settings):
        self.settings = settings
        self.portal = Portal(Realm(settings))
        self.portal.registerChecker(Checker(settings))
        self.privateKeys = {
            'ssh-rsa': Key.fromFile(settings['hadoukngit']['private_key']),
        }
        self.publicKeys = {
            'ssh-rsa': Key.fromFile(settings['hadoukngit']['public_key']),
        }
Beispiel #31
0
 def _getChild(self, branch, request):
     if not branch:
         returnValue(self)
     try:
         git_branch = yield maybeDeferred(self.github_client.get_branch,
                                          self.owner, self.repository,
                                          branch)
         resource = Branch(git_branch)
         portal = Portal(BranchRealm(resource),
                         [PasswordDB(git_branch.passwd)])
         credentialFactory = BasicCredentialFactory(branch)
         returnValue(HTTPAuthSessionWrapper(portal, [credentialFactory]))
     except github.BranchNotFound:
         returnValue(NoResource('Cannot find branch {}'.format(branch)))
     except github.GitError, e:
         logger.error(e)
         returnValue(NoResource(''))
Beispiel #32
0
class SSHServer(SSHFactory):
    'Simulate an OpenSSH server.'
    portal = Portal(NoRootUnixSSHRealm())
    #portal.registerChecker(DummyChecker())

    authorizedKeys = {
        "eedgar":
        "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEApabUX5er6J5dDtalEVaBHvZ8hMAZCeJ7gxnN/9uF6b7aVahPDkRjYxkyLxhQAKdsfqfsNxiFF6C0MulIzpE/xO2CKV2nZd/GJKt6xvEbs3qJcsNPUWujVpsrG/fkBa99IJ3kGW5kmSBwkWnUY21XGa8E/V4rs3C9m/KYMQ3hHuCD2HHaYF/s6UA5AfpoVA8UCF4jCCaiqf+moVuE4xjijUEXPU7apkTDXHsMBX/S8hnkoUUM1aJ4ehboC9aK2HSo6wT1RT4o/6H4tvp5fo2hBUUJGuj92QW386Nx49vr8T/hH4vSdqvWmT4rhydsGdT3Q+VyTyG2W1x226GDdvrT3Q=="
    }

    portal.registerChecker(PublicKeyCredentialsChecker(authorizedKeys))

    def __init__(self):
        #pubkey = '.'.join((privkey, 'pub'))

        self.privateKeys = {'ssh-rsa': Key.fromString(data=privkey)}
        self.publicKeys = {'ssh-rsa': Key.fromString(data=pubkey)}
Beispiel #33
0
    def setupProtectedResource(self, resource_obj, checkers):
        class SimpleRealm(object):
            """
            A realm which gives out L{ChangeHookResource} instances for authenticated
            users.
            """
            implements(IRealm)

            def requestAvatar(self, avatarId, mind, *interfaces):
                if resource.IResource in interfaces:
                    return (resource.IResource, resource_obj, lambda: None)
                raise NotImplementedError()

        portal = Portal(SimpleRealm(), checkers)
        credentialFactory = guard.BasicCredentialFactory('Protected area')
        wrapper = guard.HTTPAuthSessionWrapper(portal, [credentialFactory])
        return wrapper
Beispiel #34
0
    def start(self):
        components.registerAdapter(ExampleSession, Avatar, session.ISession)

        portal = Portal(Realm(self.cli, self.model, self.template_root))
        passwdDB = InMemoryUsernamePasswordDatabaseDontUse()

        for credential in self.model.credentials:
            passwdDB.addUser(credential.username.encode('utf-8'),
                             credential.password.encode('utf-8'))

        portal.registerChecker(passwdDB)
        Factory.portal = portal

        print("Starting ssh socket on " + self.hostaddress + ":" +
              str(self.port))
        reactor.listenTCP(self.port, Factory())
        reactor.run()
Beispiel #35
0
    def __init__(self, base_path):
        """
        :param FilePath base_path: The path beneath which all of the temporary
            SSH server-related files will be created.  An ``ssh`` directory
            will be created as a child of this directory to hold the key pair
            that is generated.  An ``sshd`` directory will also be created here
            to hold the generated host key.  A ``home`` directory is also
            created here and used as the home directory for shell logins to the
            server.
        """
        self.home = base_path.child(b"home")
        self.home.makedirs()

        ssh_path = base_path.child(b"ssh")
        ssh_path.makedirs()
        self.key_path = ssh_path.child(b"key")
        check_call(
            [b"ssh-keygen",
             # Specify the path where the generated key is written.
             b"-f", self.key_path.path,
             # Specify an empty passphrase.
             b"-N", b"",
             # Generate as little output as possible.
             b"-q"])
        key = Key.fromFile(self.key_path.path)

        sshd_path = base_path.child(b"sshd")
        sshd_path.makedirs()
        self.host_key_path = sshd_path.child(b"ssh_host_key")
        check_call(
            [b"ssh-keygen",
             # See above for option explanations.
             b"-f", self.host_key_path.path,
             b"-N", b"",
             b"-q"])

        factory = OpenSSHFactory()
        realm = UnixSSHRealm(self.home)
        checker = _InMemoryPublicKeyChecker(public_key=key.public())
        factory.portal = Portal(realm, [checker])
        factory.dataRoot = sshd_path.path
        factory.moduliRoot = b"/etc/ssh"

        self._port = reactor.listenTCP(0, factory, interface=b"127.0.0.1")
        self.ip = IPAddress(self._port.getHost().host)
        self.port = self._port.getHost().port
Beispiel #36
0
    def secure_resource(self, api_resource):
        """
        Wrap the provide API resource with an HTTP Authentication Session Wrapper

        :param api_resource: API resource to wrap

        :return: Resource, wrapped as requested
        """
        checkers = [self._checker]
        realm = Realm(api_resource, self._checker.users)
        portal = Portal(realm, checkers)

        # TODO: support auth realm
        credentials_factory = BasicCredentialFactory(self._auth_realm)
        # credentials_factory = BasicCredentialFactory('auth')
        resource = HTTPAuthSessionWrapper(portal, [credentials_factory])
        return resource
Beispiel #37
0
def getAuthResource(in_resource, sname, config, password_checker=AnchorePasswordChecker()):

    if not password_checker:
        # explicitly passed in null password checker obj
        return(in_resource)

    if sname in config['services']:
        localconfig = config['services'][sname]
    else:
        # no auth required
        return(in_resource)
        
    do_auth = True
    if localconfig and 'require_auth' in localconfig and not localconfig['require_auth']:
        do_auth = False

    if do_auth:
    #if localconfig and 'require_auth' in localconfig and localconfig['require_auth']:
        #if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']):
        #    raise Exception("require_auth is set for service, but require_auth_file is not set/invalid")
            
        realm = HTTPAuthRealm(resource=in_resource)
        portal = Portal(realm, [password_checker])

        #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'])])
        #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'], hash=hellothere)])

        #
        # for route-based auth, need anon and auth
        #
        #from twisted.cred.checkers import AllowAnonymousAccess
        #portal = Portal(
        #    realm, [
        #        FilePasswordDB('./configs/server-auth.db'),
        #        AllowAnonymousAccess(),
        #    ],
        #)
        
        credential_factory = BasicCredentialFactory('Authentication required')
        #credential_factory = DigestCredentialFactory('md5', 'anchore')
        resource = HTTPAuthSessionWrapper(portal, [credential_factory])
    else:
        resource = in_resource

    return (resource)
Beispiel #38
0
def main(keys_path, port):
    with open(keys_path + '/id_rsa') as privateBlobFile:
        privateBlob = privateBlobFile.read()
        privateKey = Key.fromString(data=privateBlob)

    with open(keys_path + '/id_rsa.pub') as publicBlobFile:
        publicBlob = publicBlobFile.read()
        publicKey = Key.fromString(data=publicBlob)

    factory = SSHFactory()
    factory.privateKeys = {'ssh-rsa': privateKey}
    factory.publicKeys = {'ssh-rsa': publicKey}
    factory.portal = Portal(KeyRealm())
    factory.portal.registerChecker(KeyChecker())
    factory.portal.registerChecker(PasswordChecker())

    reactor.listenTCP(port, factory)
    reactor.run()
Beispiel #39
0
def create_wrapped_resource(webcls, config, app):
    username = config.get('username', '')
    password = config.get('password', '')
    if ':' in username:
        sys.exit("The `username` option contains illegal character ':', "
                 "check and update the configuration file of Scrapyd")
    resource = webcls(config, app)
    if username and password:
        log.msg("Basic authentication enabled")
        portal = Portal(PublicHTMLRealm(resource),
                        [StringCredentialsChecker(username, password)])
        credential_factory = BasicCredentialFactory("Auth")
        return HTTPAuthSessionWrapper(portal, [credential_factory])
    else:
        log.msg(
            "Basic authentication disabled as either `username` or `password` is unset"
        )
        return resource
def main():
    # log
    log.startLogging(sys.stdout)

    # checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]

    checkers = [FilePasswordDB('httpd.password')]

    portal = Portal(SimpleRealm(), checkers)

    credFactory = [guard.DigestCredentialFactory('md5', 'example.com')]

    wrapper = guard.HTTPAuthSessionWrapper(portal, credFactory)

    factory = server.Site(resource=wrapper)

    reactor.listenTCP(8889, factory)

    reactor.run()
Beispiel #41
0
    def setup_Q2Q(self, path,
                  q2qPortnum=q2q.port,
                  inboundTCPPortnum=q2q.port+1,
                  publicIP=None
                  ):
        """Set up a Q2Q service.
        """
        store = DirectoryCertificateAndUserStore(path)
        # store.addPrivateCertificate("kazekage")
        # store.addUser("kazekage", "username", "password1234")

        self.attach(q2q.Q2QService(
                protocolFactoryFactory=IdentityAdminFactory(store).examineRequest,
                certificateStorage=store,
                portal=Portal(store, checkers=[store]),
                q2qPortnum=q2qPortnum,
                inboundTCPPortnum=inboundTCPPortnum,
                publicIP=publicIP,
                ))
Beispiel #42
0
def makeFactory(configdict):
    """
    Creates the ssh server factory.
    """

    pubkeyfile = "ssh-public.key"
    privkeyfile = "ssh-private.key"

    def chainProtocolFactory(username=None):
        return insults.ServerProtocol(
            configdict['protocolFactory'],
            *configdict.get('protocolConfigdict', (username, )),
            **configdict.get('protocolKwArgs', {}))

    rlm = PassAvatarIdTerminalRealm()
    rlm.transportFactory = TerminalSessionTransport_getPeer
    rlm.chainedProtocolFactory = chainProtocolFactory
    factory = ConchFactory(Portal(rlm))
    factory.sessionhandler = configdict['sessions']

    try:
        # create/get RSA keypair
        publicKey, privateKey = getKeyPair(pubkeyfile, privkeyfile)
        factory.publicKeys = {'ssh-rsa': publicKey}
        factory.privateKeys = {'ssh-rsa': privateKey}
    except Exception as e:
        print(
            " getKeyPair error: %(e)s\n WARNING: Evennia could not auto-generate SSH keypair. Using conch default keys instead."
            % {'e': e})
        print(
            " If this error persists, create game/%(pub)s and game/%(priv)s yourself using third-party tools."
            % {
                'pub': pubkeyfile,
                'priv': privkeyfile
            })

    factory.services = factory.services.copy()
    factory.services['ssh-userauth'] = ExtraInfoAuthServer

    factory.portal.registerChecker(PlayerDBPasswordChecker(factory))

    return factory
Beispiel #43
0
def setMain(opt):
    """Create a MainServer class based on `opt` options"""
    instanceName = opt['-n']
    if not instanceName:
        instanceName = ''
    print 'setMain', opt
    # Determine logfile path into datadir
    log_filename = params.log_filename if not opt.has_key(
        '-d') else os.path.join(opt['-d'], 'log', 'misura.log')
    params.log_filename = log_filename
    # Start the object sharing process
    share.init(connect=False, log_filename=log_filename)
    # Instantiate mainserver class
    main = MainServer(instanceName=instanceName,
                      port=opt['-p'],
                      confdir=opt['-c'],
                      datadir=opt['-d'],
                      plug=opt['-e'],
                      manager=share.manager)
    xmlrpc.addIntrospection(main)
    mimetypes = {'.h5': 'application/x-hdf;subtype=bag'}
    static.File.contentTypes.update(mimetypes)
    web = static.File(params.webdir)
    web.putChild('RPC', main)
    web.putChild('data', static.File(params.datadir))
    web.putChild('conf', static.File(params.confdir))
    # StreamServer
    mdir = MisuraDirectory(main)
    web.putChild('stream', mdir)

    # Further reading about auth stuff:
    # http://www.tsheffler.com/blog/?p=502
    realm = MisuraRealm()
    realm.resource = web
    # TODO: use also for FTP!
    checker = UsersChecker(main.users)
    portal = Portal(realm, [checker])
    cred_methods = (DigestCredentialFactory("md5", "MISURA"),
                    BasicCredentialFactory('MISURA'))
    wrapper = HTTPAuthSessionWrapper(portal, cred_methods)
    site = server.Site(wrapper)
    return main, web, site
Beispiel #44
0
def makeAgentService(store):
    """
    Returns a service which will process GatewayAMPCommands, using a socket
    file descripter acquired by launchd

    @param store: an already opened store
    @returns: service
    """
    from twisted.internet import reactor

    sockets = launchActivateSocket("AgentSocket")
    fd = sockets[0]

    family = socket.AF_INET
    endpoint = AdoptedStreamServerEndpoint(reactor, fd, family)

    directory = store.directoryService()

    def becameInactive():
        log.warn("Agent inactive; shutting down")
        reactor.stop()

    from twistedcaldav.config import config
    inactivityDetector = InactivityDetector(
        reactor, config.AgentInactivityTimeoutSeconds, becameInactive)
    root = Resource()
    root.putChild("gateway",
                  AgentGatewayResource(store, directory, inactivityDetector))

    # We need this service to be able to return com.apple.calendarserver,
    # so tell it not to suppress system accounts.
    directory = OpenDirectoryDirectoryService("/Local/Default",
                                              suppressSystemRecords=False)

    portal = Portal(AgentRealm(root, [u"com.apple.calendarserver"]),
                    [HTTPDigestCredentialChecker(directory)])
    credentialFactory = NoQOPDigestCredentialFactory("md5", "/Local/Default")
    wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])

    site = Site(wrapper)

    return StreamServerEndpointService(endpoint, site)
Beispiel #45
0
    def setupProtectedResource(self, resource_obj):
        class SimpleRealm(object):
            """
            A realm which gives out L{ChangeHookResource} instances for authenticated
            users.
            """
            implements(IRealm)

            def requestAvatar(self, avatarId, mind, *interfaces):
                if resource.IResource in interfaces:
                    return (resource.IResource, resource_obj, lambda: None)
                raise NotImplementedError()

        login, password = self.change_hook_auth
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser(login, password)
        portal = Portal(SimpleRealm(), [checker])
        credentialFactory = guard.BasicCredentialFactory('Protected area')
        wrapper = guard.HTTPAuthSessionWrapper(portal, [credentialFactory])
        return wrapper
Beispiel #46
0
def init(ftp_port=None):
    global _FTPServer
    lg.out(4, 'ftp_server.init')
    if _FTPServer:
        lg.warn('already started')
        return
    if not ftp_port:
        ftp_port = settings.getFTPServerPort()
    if not os.path.isfile(settings.FTPServerCredentialsFile()):
        bpio.WriteTextFile(settings.FTPServerCredentialsFile(),
                           'bitdust:bitdust')
    # TODO: add protection: accept connections only from local host: 127.0.0.1
    _FTPServer = reactor.listenTCP(
        ftp_port,
        BitDustFTPFactory(
            Portal(FTPRealm('./'), [
                AllowAnonymousAccess(),
                FilePasswordDB(settings.FTPServerCredentialsFile()),
            ]), ))
    lg.out(4, '    started on port %d' % ftp_port)
Beispiel #47
0
    def makeService(cls, config):
        """
		Create the txsftp service.
		"""
        if (conf.get('suppress-deprecation-warnings')):
            warnings.filterwarnings('ignore', r'.*', DeprecationWarning)

        get_key = lambda path: Key.fromString(data=open(path).read())
        ssh_public_key = get_key(conf.get('ssh-public-key'))
        ssh_private_key = get_key(conf.get('ssh-private-key'))

        factory = SSHFactory()
        factory.privateKeys = {'ssh-rsa': ssh_private_key}
        factory.publicKeys = {'ssh-rsa': ssh_public_key}

        db = dbapi.connect(conf.get('db-url'))
        factory.portal = Portal(auth.VirtualizedSSHRealm(db))
        factory.portal.registerChecker(auth.UsernamePasswordChecker(db))
        factory.portal.registerChecker(auth.SSHKeyChecker(db))

        return internet.TCPServer(conf.get('sftp-port'), factory)
Beispiel #48
0
    def test_portalRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by an
        L{smtp.SMTP} instance's portal is responded to with the correct error
        code.
        """
        class DisallowAnonymousAccess(object):
            """
            Checker for L{IAnonymous} which rejects authentication attempts.
            """
            implements(ICredentialsChecker)

            credentialInterfaces = (IAnonymous,)

            def requestAvatarId(self, credentials):
                return defer.fail(UnauthorizedLogin())

        realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
        portal = Portal(realm, [DisallowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<*****@*****.**>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<*****@*****.**>: Sender not acceptable\r\n')
Beispiel #49
0
    def __init__(self):
        portal = Portal(authentication.XCAPAuthRealm())
        if AuthenticationConfig.cleartext_passwords:
            http_checker = ServerConfig.backend.PlainPasswordChecker()
        else:
            http_checker = ServerConfig.backend.HashPasswordChecker()
        portal.registerChecker(http_checker)
        trusted_peers = AuthenticationConfig.trusted_peers
        portal.registerChecker(authentication.TrustedPeerChecker(trusted_peers))
        portal.registerChecker(authentication.PublicGetApplicationChecker())

        auth_type = AuthenticationConfig.type
        if auth_type == 'basic':
            credential_factory = basic.BasicCredentialFactory(auth_type)
        elif auth_type == 'digest':
            credential_factory = tweak_DigestCredentialFactory('MD5', auth_type)
        else:
            raise ValueError("Invalid authentication type: '%s'. Please check the configuration." % auth_type)

        root = authentication.XCAPAuthResource(XCAPRoot(),
                                               (credential_factory,),
                                               portal, (authentication.IAuthUser,))
        self.site = XCAPSite(root)
Beispiel #50
0
    def setUp(self):
        self.avatar_content = b"avatar content"
        self.child_content = b"child content"
        self.grandchild_content = b"grandchild content"

        grandchild = Data(self.grandchild_content, b"text/plain")

        child = Data(self.child_content, b"text/plain")
        child.putChild(b"grandchild", grandchild)

        self.avatar = Data(self.avatar_content, b"text/plain")
        self.avatar.putChild(b"child", child)

        self.realm = OneIResourceAvatarRealm(self.avatar)
        self.portal = Portal(
            self.realm,
            [AllowAnonymousAccess()],
        )
        self.guard = HTTPAuthSessionWrapper(
            self.portal,
            [BasicCredentialFactory("example.com")],
        )
Beispiel #51
0
def start_ssh_server(port, username, password, namespace):
    """
    Start an SSH server on the given port, exposing a Python prompt with the
    given namespace.
    """
    # This is a lot of boilerplate, see http://tm.tl/6429 for a ticket to
    # provide a utility function that simplifies this.
    from twisted.internet import reactor
    from twisted.conch.insults import insults
    from twisted.conch import manhole, manhole_ssh
    from twisted.cred.checkers import (
        InMemoryUsernamePasswordDatabaseDontUse as MemoryDB)
    from twisted.cred.portal import Portal

    sshRealm = manhole_ssh.TerminalRealm()
    def chainedProtocolFactory():
        return insults.ServerProtocol(manhole.Manhole, namespace)
    sshRealm.chainedProtocolFactory = chainedProtocolFactory

    sshPortal = Portal(sshRealm, [MemoryDB(**{username: password})])
    reactor.listenTCP(port, manhole_ssh.ConchFactory(sshPortal),
                      interface="127.0.0.1")
Beispiel #52
0
def makeFactory(configdict):
    """
    Creates the ssh server factory.
    """

    pubkeyfile = os.path.join(_GAME_DIR, "server", "ssh-public.key")
    privkeyfile = os.path.join(_GAME_DIR, "server", "ssh-private.key")

    def chainProtocolFactory(username=None):
        return insults.ServerProtocol(
            configdict['protocolFactory'],
            *configdict.get('protocolConfigdict', (username, )),
            **configdict.get('protocolKwArgs', {}))

    rlm = PassAvatarIdTerminalRealm()
    rlm.transportFactory = TerminalSessionTransport_getPeer
    rlm.chainedProtocolFactory = chainProtocolFactory
    factory = ConchFactory(Portal(rlm))
    factory.sessionhandler = configdict['sessions']

    try:
        # create/get RSA keypair
        publicKey, privateKey = getKeyPair(pubkeyfile, privkeyfile)
        factory.publicKeys = {'ssh-rsa': publicKey}
        factory.privateKeys = {'ssh-rsa': privateKey}
    except Exception as err:
        print ( "getKeyPair error: {err}\n WARNING: Evennia could not " \
                "auto-generate SSH keypair. Using conch default keys instead.\n" \
                "If this error persists, create {pub} and " \
                "{priv} yourself using third-party tools.".format(
                    err=err, pub=pubkeyfile, priv=privkeyfile))

    factory.services = factory.services.copy()
    factory.services['ssh-userauth'] = ExtraInfoAuthServer

    factory.portal.registerChecker(PlayerDBPasswordChecker(factory))

    return factory
Beispiel #53
0
def main():
    """
    Create a PB server using MyRealm and run it on port 8800.
    """
    startLogging(stdout)

    p = Portal(MyRealm())

    # Here the username/password checker is registered.
    c1 = InMemoryUsernamePasswordDatabaseDontUse(user1="pass1", user2="pass2")
    p.registerChecker(c1)

    # Here the anonymous checker is registered.
    c2 = AllowAnonymousAccess()
    p.registerChecker(c2)

    reactor.listenTCP(8800, PBServerFactory(p))
    reactor.run()
Beispiel #54
0
    def test_deliveryRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by a
        L{smtp.IMessageDelivery} instance is responded to with the correct
        error code.
        """
        class RejectionDelivery(NotImplementedDelivery):
            """
            Delivery object which rejects all senders as invalid.
            """
            def validateFrom(self, helo, origin):
                raise smtp.SMTPBadSender(origin)

        realm = SingletonRealm(smtp.IMessageDelivery, RejectionDelivery())
        portal = Portal(realm, [AllowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<*****@*****.**>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<*****@*****.**>: Sender not acceptable\r\n')
Beispiel #55
0
def create_factory(authnz, git_configuration, git_viewer=None):
    if git_viewer is None:
        git_viewer = NoResource()
    elif not IResource.providedBy(git_viewer):
        raise ValueError("git_viewer should implement IResource")

    credentialFactories = [BasicCredentialFactory('Git Repositories')]
    gitportal = Portal(
        GitHTTPRealm(authnz, git_configuration, credentialFactories,
                     git_viewer))

    if hasattr(authnz, 'check_password'):
        log.msg("Registering PasswordChecker")
        gitportal.registerChecker(PasswordChecker(authnz.check_password))
    gitportal.registerChecker(AllowAnonymousAccess())

    resource = HTTPAuthSessionWrapper(gitportal, credentialFactories)
    site = Site(resource)

    return site
Beispiel #56
0
    def createDocumentRoot(self):
        docroot = self.mktemp()
        os.mkdir(docroot)

        userResource = TestDAVPrincipalResource("/principals/users/user01")
        userResource.writeDeadProperty(TwistedPasswordProperty("user01"))

        principalCollection = TestPrincipalsCollection(
            "/principals/",
            children={
                "users": TestPrincipalsCollection(
                    "/principals/users/",
                    children={"user01": userResource}
                )
            }
        )

        rootResource = self.resource_class(
            docroot, principalCollections=(principalCollection,))

        portal = Portal(DavRealm())
        portal.registerChecker(TwistedPropertyChecker())

        credentialFactories = (basic.BasicCredentialFactory(""),)

        loginInterfaces = (IPrincipal,)

        self.site = Site(AuthenticationWrapper(
            rootResource,
            portal,
            credentialFactories,
            credentialFactories,
            loginInterfaces
        ))

        rootResource.setAccessControlList(self.grant(element.All()))

        for name, acl in (
            ("none"       , self.grant()),
            ("read"       , self.grant(element.Read())),
            ("read-write" , self.grant(element.Read(), element.Write())),
            ("unlock"     , self.grant(element.Unlock())),
            ("all"        , self.grant(element.All())),
        ):
            filename = os.path.join(docroot, name)
            if not os.path.isfile(filename):
                file(filename, "w").close()
            resource = self.resource_class(filename)
            resource.setAccessControlList(acl)

        for name, acl in (
            ("nobind" , self.grant()),
            ("bind"   , self.grant(element.Bind())),
            ("unbind" , self.grant(element.Bind(), element.Unbind())),
        ):
            dirname = os.path.join(docroot, name)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            resource = self.resource_class(dirname)
            resource.setAccessControlList(acl)
        return docroot
Beispiel #57
0
class SSHUserAuthServerTests(unittest.TestCase):
    """
    Tests for SSHUserAuthServer.
    """

    if keys is None:
        skip = "cannot run without cryptography"

    def setUp(self):
        self.realm = Realm()
        self.portal = Portal(self.realm)
        self.portal.registerChecker(PasswordChecker())
        self.portal.registerChecker(PrivateKeyChecker())
        self.authServer = userauth.SSHUserAuthServer()
        self.authServer.transport = FakeTransport(self.portal)
        self.authServer.serviceStarted()
        self.authServer.supportedAuthentications.sort()  # give a consistent
        # order

    def tearDown(self):
        self.authServer.serviceStopped()
        self.authServer = None

    def _checkFailed(self, ignored):
        """
        Check that the authentication has failed.
        """
        self.assertEqual(self.authServer.transport.packets[-1],
                         (userauth.MSG_USERAUTH_FAILURE,
                          NS(b'password,publickey') + b'\x00'))

    def test_noneAuthentication(self):
        """
        A client may request a list of authentication 'method name' values
        that may continue by using the "none" authentication 'method name'.

        See RFC 4252 Section 5.2.
        """
        d = self.authServer.ssh_USERAUTH_REQUEST(
            NS(b'foo') + NS(b'service') + NS(b'none'))
        return d.addCallback(self._checkFailed)

    def test_successfulPasswordAuthentication(self):
        """
        When provided with correct password authentication information, the
        server should respond by sending a MSG_USERAUTH_SUCCESS message with
        no other data.

        See RFC 4252, Section 5.1.
        """
        packet = b''.join(
            [NS(b'foo'),
             NS(b'none'),
             NS(b'password'),
             chr(0),
             NS(b'foo')])
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)

        def check(ignored):
            self.assertEqual(self.authServer.transport.packets,
                             [(userauth.MSG_USERAUTH_SUCCESS, b'')])

        return d.addCallback(check)

    def test_failedPasswordAuthentication(self):
        """
        When provided with invalid authentication details, the server should
        respond by sending a MSG_USERAUTH_FAILURE message which states whether
        the authentication was partially successful, and provides other, open
        options for authentication.

        See RFC 4252, Section 5.1.
        """
        # packet = username, next_service, authentication type, FALSE, password
        packet = b''.join(
            [NS(b'foo'),
             NS(b'none'),
             NS(b'password'),
             chr(0),
             NS(b'bar')])
        self.authServer.clock = task.Clock()
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        self.assertEqual(self.authServer.transport.packets, [])
        self.authServer.clock.advance(2)
        return d.addCallback(self._checkFailed)

    def test_successfulPrivateKeyAuthentication(self):
        """
        Test that private key authentication completes successfully,
        """
        blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
        obj = keys.Key.fromString(keydata.privateRSA_openssh)
        packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff' +
                  NS(obj.sshType()) + NS(blob))
        self.authServer.transport.sessionID = b'test'
        signature = obj.sign(
            NS(b'test') + chr(userauth.MSG_USERAUTH_REQUEST) + packet)
        packet += NS(signature)
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)

        def check(ignored):
            self.assertEqual(self.authServer.transport.packets,
                             [(userauth.MSG_USERAUTH_SUCCESS, b'')])

        return d.addCallback(check)

    def test_requestRaisesConchError(self):
        """
        ssh_USERAUTH_REQUEST should raise a ConchError if tryAuth returns
        None. Added to catch a bug noticed by pyflakes.
        """
        d = defer.Deferred()

        def mockCbFinishedAuth(self, ignored):
            self.fail('request should have raised ConochError')

        def mockTryAuth(kind, user, data):
            return None

        def mockEbBadAuth(reason):
            d.errback(reason.value)

        self.patch(self.authServer, 'tryAuth', mockTryAuth)
        self.patch(self.authServer, '_cbFinishedAuth', mockCbFinishedAuth)
        self.patch(self.authServer, '_ebBadAuth', mockEbBadAuth)

        packet = NS(b'user') + NS(b'none') + NS(b'public-key') + NS(b'data')
        # If an error other than ConchError is raised, this will trigger an
        # exception.
        self.authServer.ssh_USERAUTH_REQUEST(packet)
        return self.assertFailure(d, ConchError)

    def test_verifyValidPrivateKey(self):
        """
        Test that verifying a valid private key works.
        """
        blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
        packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\x00' +
                  NS(b'ssh-rsa') + NS(blob))
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)

        def check(ignored):
            self.assertEqual(
                self.authServer.transport.packets,
                [(userauth.MSG_USERAUTH_PK_OK, NS(b'ssh-rsa') + NS(blob))])

        return d.addCallback(check)

    def test_failedPrivateKeyAuthenticationWithoutSignature(self):
        """
        Test that private key authentication fails when the public key
        is invalid.
        """
        blob = keys.Key.fromString(keydata.publicDSA_openssh).blob()
        packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\x00' +
                  NS(b'ssh-dsa') + NS(blob))
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        return d.addCallback(self._checkFailed)

    def test_failedPrivateKeyAuthenticationWithSignature(self):
        """
        Test that private key authentication fails when the public key
        is invalid.
        """
        blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
        obj = keys.Key.fromString(keydata.privateRSA_openssh)
        packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff' +
                  NS(b'ssh-rsa') + NS(blob) + NS(obj.sign(blob)))
        self.authServer.transport.sessionID = b'test'
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        return d.addCallback(self._checkFailed)

    def test_ignoreUnknownCredInterfaces(self):
        """
        L{SSHUserAuthServer} sets up
        C{SSHUserAuthServer.supportedAuthentications} by checking the portal's
        credentials interfaces and mapping them to SSH authentication method
        strings.  If the Portal advertises an interface that
        L{SSHUserAuthServer} can't map, it should be ignored.  This is a white
        box test.
        """
        server = userauth.SSHUserAuthServer()
        server.transport = FakeTransport(self.portal)
        self.portal.registerChecker(AnonymousChecker())
        server.serviceStarted()
        server.serviceStopped()
        server.supportedAuthentications.sort()  # give a consistent order
        self.assertEqual(server.supportedAuthentications,
                         [b'password', b'publickey'])

    def test_removePasswordIfUnencrypted(self):
        """
        Test that the userauth service does not advertise password
        authentication if the password would be send in cleartext.
        """
        self.assertIn(b'password', self.authServer.supportedAuthentications)
        # no encryption
        clearAuthServer = userauth.SSHUserAuthServer()
        clearAuthServer.transport = FakeTransport(self.portal)
        clearAuthServer.transport.isEncrypted = lambda x: False
        clearAuthServer.serviceStarted()
        clearAuthServer.serviceStopped()
        self.assertNotIn(b'password', clearAuthServer.supportedAuthentications)
        # only encrypt incoming (the direction the password is sent)
        halfAuthServer = userauth.SSHUserAuthServer()
        halfAuthServer.transport = FakeTransport(self.portal)
        halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
        halfAuthServer.serviceStarted()
        halfAuthServer.serviceStopped()
        self.assertIn(b'password', halfAuthServer.supportedAuthentications)

    def test_unencryptedConnectionWithoutPasswords(self):
        """
        If the L{SSHUserAuthServer} is not advertising passwords, then an
        unencrypted connection should not cause any warnings or exceptions.
        This is a white box test.
        """
        # create a Portal without password authentication
        portal = Portal(self.realm)
        portal.registerChecker(PrivateKeyChecker())

        # no encryption
        clearAuthServer = userauth.SSHUserAuthServer()
        clearAuthServer.transport = FakeTransport(portal)
        clearAuthServer.transport.isEncrypted = lambda x: False
        clearAuthServer.serviceStarted()
        clearAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                         [b'publickey'])

        # only encrypt incoming (the direction the password is sent)
        halfAuthServer = userauth.SSHUserAuthServer()
        halfAuthServer.transport = FakeTransport(portal)
        halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
        halfAuthServer.serviceStarted()
        halfAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                         [b'publickey'])

    def test_loginTimeout(self):
        """
        Test that the login times out.
        """
        timeoutAuthServer = userauth.SSHUserAuthServer()
        timeoutAuthServer.clock = task.Clock()
        timeoutAuthServer.transport = FakeTransport(self.portal)
        timeoutAuthServer.serviceStarted()
        timeoutAuthServer.clock.advance(11 * 60 * 60)
        timeoutAuthServer.serviceStopped()
        self.assertEqual(
            timeoutAuthServer.transport.packets,
            [(transport.MSG_DISCONNECT, b'\x00' * 3 +
              chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
              NS(b"you took too long") + NS(b''))])
        self.assertTrue(timeoutAuthServer.transport.lostConnection)

    def test_cancelLoginTimeout(self):
        """
        Test that stopping the service also stops the login timeout.
        """
        timeoutAuthServer = userauth.SSHUserAuthServer()
        timeoutAuthServer.clock = task.Clock()
        timeoutAuthServer.transport = FakeTransport(self.portal)
        timeoutAuthServer.serviceStarted()
        timeoutAuthServer.serviceStopped()
        timeoutAuthServer.clock.advance(11 * 60 * 60)
        self.assertEqual(timeoutAuthServer.transport.packets, [])
        self.assertFalse(timeoutAuthServer.transport.lostConnection)

    def test_tooManyAttempts(self):
        """
        Test that the server disconnects if the client fails authentication
        too many times.
        """
        packet = b''.join(
            [NS(b'foo'),
             NS(b'none'),
             NS(b'password'),
             chr(0),
             NS(b'bar')])
        self.authServer.clock = task.Clock()
        for i in range(21):
            d = self.authServer.ssh_USERAUTH_REQUEST(packet)
            self.authServer.clock.advance(2)

        def check(ignored):
            self.assertEqual(
                self.authServer.transport.packets[-1],
                (transport.MSG_DISCONNECT, b'\x00' * 3 +
                 chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
                 NS(b"too many bad auths") + NS(b'')))

        return d.addCallback(check)

    def test_failIfUnknownService(self):
        """
        If the user requests a service that we don't support, the
        authentication should fail.
        """
        packet = NS(b'foo') + NS(b'') + NS(b'password') + chr(0) + NS(b'foo')
        self.authServer.clock = task.Clock()
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        return d.addCallback(self._checkFailed)

    def test_tryAuthEdgeCases(self):
        """
        tryAuth() has two edge cases that are difficult to reach.

        1) an authentication method auth_* returns None instead of a Deferred.
        2) an authentication type that is defined does not have a matching
           auth_* method.

        Both these cases should return a Deferred which fails with a
        ConchError.
        """
        def mockAuth(packet):
            return None

        self.patch(self.authServer, 'auth_publickey', mockAuth)  # first case
        self.patch(self.authServer, 'auth_password', None)  # second case

        def secondTest(ignored):
            d2 = self.authServer.tryAuth(b'password', None, None)
            return self.assertFailure(d2, ConchError)

        d1 = self.authServer.tryAuth(b'publickey', None, None)
        return self.assertFailure(d1, ConchError).addCallback(secondTest)
Beispiel #58
0
def makePortal(pool):
    realm = ChatRealm(pool)
    portal = Portal(realm)
    checker = TokenChecker(pool)
    portal.registerChecker(checker)
    return portal
Beispiel #59
0
 def getLoginResource(self):
     return HTTPAuthSessionWrapper(
         Portal(AuthRealm(self.master, self), self.checkers),
         self.credentialFactories)
Beispiel #60
0
    def ftp_MKD(self, path):
        FTP.sendLine(self, '257 Folder created')

    def ftp_RMD(self, path):
        FTP.sendLine(self, '250 Requested File Action Completed OK')

    # END HACKS

    def logIt(self, command, successful):
        f = open('/root/ftp.log', 'a')
        data = {
            'timestamp': int(time.time()),
            'sourceIPv4Address': str(self.transport.getPeer().host),
            'command': command,
            'success': successful,
            'session': self.session
        }
        f.write(json.dumps(data) + ',\n')
        f.close()


try:
    factory = FTPFactory(Portal('pub/'), [FilePasswordDB('/passwd')])
    factory.protocol = SimpleFtpProtocol
    reactor.listenTCP(21, factory)
    print('Server listening on Port %s (Plain) and on %s (SSL).' % (21, 990))
    reactor.run()
except Exception as e:
    print(e)