Python twisted.cred.portal.Portal() Examples

The following are 30 code examples of twisted.cred.portal.Portal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.cred.portal , or try the search function .
Example #1
Source File: test_httpauth.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def setUp(self):
        """
        Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
        """
        self.username = b'foo bar'
        self.password = b'bar baz'
        self.avatarContent = b"contents of the avatar resource itself"
        self.childName = b"foo-child"
        self.childContent = b"contents of the foo child of the avatar"
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser(self.username, self.password)
        self.avatar = Data(self.avatarContent, 'text/plain')
        self.avatar.putChild(
            self.childName, Data(self.childContent, 'text/plain'))
        self.avatars = {self.username: self.avatar}
        self.realm = Realm(self.avatars.get)
        self.portal = portal.Portal(self.realm, [self.checker])
        self.credentialFactories = []
        self.wrapper = HTTPAuthSessionWrapper(
            self.portal, self.credentialFactories) 
Example #2
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = "contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEquals(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #3
Source File: tap.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeService(config):
    credCheckers = config.get('credCheckers', [])
    wordsRealm = service.InMemoryWordsRealm(config['hostname'])
    wordsPortal = portal.Portal(wordsRealm, credCheckers)

    msvc = MultiService()

    # XXX Attribute lookup on config is kind of bad - hrm.
    for plgName in config.interfacePlugins:
        port = config.get(plgName + '-port')
        if port is not None:
            factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
            svc = strports.service(port, factory)
            svc.setServiceParent(msvc)

    # This is bogus.  createGroup is async.  makeService must be
    # allowed to return a Deferred or some crap.
    for g in config['groups']:
        wordsRealm.createGroup(g)

    return msvc 
Example #4
Source File: tap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeService(config):
    credCheckers = config.get('credCheckers', [])
    wordsRealm = service.InMemoryWordsRealm(config['hostname'])
    wordsPortal = portal.Portal(wordsRealm, credCheckers)

    msvc = MultiService()

    # XXX Attribute lookup on config is kind of bad - hrm.
    for plgName in config.interfacePlugins:
        port = config.get(plgName + '-port')
        if port is not None:
            factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
            svc = strports.service(port, factory)
            svc.setServiceParent(msvc)

    # This is bogus.  createGroup is async.  makeService must be
    # allowed to return a Deferred or some crap.
    for g in config['groups']:
        wordsRealm.createGroup(g)

    return msvc 
Example #5
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setupKeyChecker(self, portal, users):
        """
        Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
        to C{portal}.

        @param portal: A L{Portal} to which to add the checker.
        @type portal: L{Portal}

        @param users: The users and their keys the checker will recognize.  Keys
            are byte strings giving user names.  Values are byte strings giving
            OpenSSH-formatted private keys.
        @type users: L{dict}
        """
        mapping = dict([(k,[Key.fromString(v).public()])
                        for k, v in iteritems(users)])
        checker = SSHPublicKeyChecker(InMemorySSHKeyDB(mapping))
        portal.registerChecker(checker) 
Example #6
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        self.hostname = b"ssh.example.com"
        self.port = 42022
        self.user = b"user"
        self.password = b"password"
        self.reactor = MemoryReactorClock()
        self.realm = TrivialRealm()
        self.portal = Portal(self.realm)
        self.passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
        self.passwdDB.addUser(self.user, self.password)
        self.portal.registerChecker(self.passwdDB)
        self.factory = CommandFactory()
        self.factory.reactor = self.reactor
        self.factory.portal = self.portal
        self.factory.doStart()
        self.addCleanup(self.factory.doStop)

        self.clientAddress = IPv4Address("TCP", "10.0.0.1", 12345)
        self.serverAddress = IPv4Address("TCP", "192.168.100.200", 54321) 
Example #7
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_unexpectedLoginError(self):
        """
        Any unexpected failure from L{Portal.login} results in a 500 response
        code and causes the failure to be logged.
        """
        class UnexpectedException(Exception):
            pass

        class BrokenChecker(object):
            credentialInterfaces = (IUsernamePassword,)

            def requestAvatarId(self, credentials):
                raise UnexpectedException()

        self.portal.registerChecker(BrokenChecker())
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) 
Example #8
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeService(config):
    """
    Construct a service for operating a SSH server.

    @param config: An L{Options} instance specifying server options, including
        where server keys are stored and what authentication methods to use.

    @return: A L{twisted.application.service.IService} provider which contains
        the requested SSH server.
    """

    t = factory.OpenSSHFactory()

    r = unix.UnixSSHRealm()
    t.portal = portal.Portal(r, config.get('credCheckers', []))
    t.dataRoot = config['data']
    t.moduliRoot = config['moduli'] or config['data']

    port = config['port']
    if config['interface']:
        # Add warning here
        port += ':interface=' + config['interface']
    return strports.service(port, t) 
Example #9
Source File: ftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r, config.get('credCheckers', []))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP

    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #10
Source File: ftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r)
    p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous)

    if config['password-file'] is not None:
        p.registerChecker(checkers.FilePasswordDB(config['password-file'], cache=True))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP
    
    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #11
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """
        Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
        """
        self.username = 'foo bar'
        self.password = 'bar baz'
        self.avatarContent = "contents of the avatar resource itself"
        self.childName = "foo-child"
        self.childContent = "contents of the foo child of the avatar"
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser(self.username, self.password)
        self.avatar = Data(self.avatarContent, 'text/plain')
        self.avatar.putChild(
            self.childName, Data(self.childContent, 'text/plain'))
        self.avatars = {self.username: self.avatar}
        self.realm = Realm(self.avatars.get)
        self.portal = portal.Portal(self.realm, [self.checker])
        self.credentialFactories = []
        self.wrapper = HTTPAuthSessionWrapper(
            self.portal, self.credentialFactories) 
Example #12
Source File: mail.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def addDomain(self, name, domain):
        """
        Add a domain for which the service will accept email.

        @type name: L{bytes}
        @param name: A domain name.

        @type domain: L{IDomain} provider
        @param domain: A domain object.
        """
        portal = Portal(domain)
        map(portal.registerChecker, domain.getCredentialsCheckers())
        self.domains[name] = domain
        self.portals[name] = portal
        if self.aliases and IAliasableDomain.providedBy(domain):
            domain.setAliasGroup(self.aliases) 
Example #13
Source File: test_httpauth.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = b"contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #14
Source File: ftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r, config.get('credCheckers', []))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP

    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #15
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def setupKeyChecker(self, portal, users):
        """
        Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
        to C{portal}.

        @param portal: A L{Portal} to which to add the checker.
        @type portal: L{Portal}

        @param users: The users and their keys the checker will recognize.  Keys
            are byte strings giving user names.  Values are byte strings giving
            OpenSSH-formatted private keys.
        @type users: L{dict}
        """
        mapping = dict([(k,[Key.fromString(v).public()])
                        for k, v in iteritems(users)])
        checker = SSHPublicKeyChecker(InMemorySSHKeyDB(mapping))
        portal.registerChecker(checker) 
Example #16
Source File: test_pb.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def connectedServerAndClient():
    """
    Returns a 3-tuple: (client, server, pump).
    """
    clientBroker = pb.Broker()
    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(guest='guest')
    factory = pb.PBServerFactory(portal.Portal(DummyRealm(), [checker]))
    serverBroker = factory.buildProtocol(('127.0.0.1',))

    clientTransport = StringIO()
    serverTransport = StringIO()
    clientBroker.makeConnection(protocol.FileWrapper(clientTransport))
    serverBroker.makeConnection(protocol.FileWrapper(serverTransport))
    pump = IOPump(clientBroker, serverBroker, clientTransport, serverTransport)
    # Challenge-response authentication:
    pump.flush()
    return clientBroker, serverBroker, pump 
Example #17
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def setUp(self):
        self.hostname = b"ssh.example.com"
        self.port = 42022
        self.user = b"user"
        self.password = b"password"
        self.reactor = MemoryReactorClock()
        self.realm = TrivialRealm()
        self.portal = Portal(self.realm)
        self.passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
        self.passwdDB.addUser(self.user, self.password)
        self.portal.registerChecker(self.passwdDB)
        self.factory = CommandFactory()
        self.factory.reactor = self.reactor
        self.factory.portal = self.portal
        self.factory.doStart()
        self.addCleanup(self.factory.doStop)

        self.clientAddress = IPv4Address("TCP", "10.0.0.1", 12345)
        self.serverAddress = IPv4Address("TCP", "192.168.100.200", 54321) 
Example #18
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
        """
        self.username = b'foo bar'
        self.password = b'bar baz'
        self.avatarContent = b"contents of the avatar resource itself"
        self.childName = b"foo-child"
        self.childContent = b"contents of the foo child of the avatar"
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser(self.username, self.password)
        self.avatar = Data(self.avatarContent, 'text/plain')
        self.avatar.putChild(
            self.childName, Data(self.childContent, 'text/plain'))
        self.avatars = {self.username: self.avatar}
        self.realm = Realm(self.avatars.get)
        self.portal = portal.Portal(self.realm, [self.checker])
        self.credentialFactories = []
        self.wrapper = HTTPAuthSessionWrapper(
            self.portal, self.credentialFactories) 
Example #19
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_unexpectedLoginError(self):
        """
        Any unexpected failure from L{Portal.login} results in a 500 response
        code and causes the failure to be logged.
        """
        class UnexpectedException(Exception):
            pass

        class BrokenChecker(object):
            credentialInterfaces = (IUsernamePassword,)

            def requestAvatarId(self, credentials):
                raise UnexpectedException()

        self.portal.registerChecker(BrokenChecker())
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) 
Example #20
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = b"contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #21
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeService(config):
    credCheckers = config.get('credCheckers', [])
    wordsRealm = service.InMemoryWordsRealm(config['hostname'])
    wordsPortal = portal.Portal(wordsRealm, credCheckers)

    msvc = MultiService()

    # XXX Attribute lookup on config is kind of bad - hrm.
    for plgName in config.interfacePlugins:
        port = config.get(plgName + '-port')
        if port is not None:
            factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
            svc = strports.service(port, factory)
            svc.setServiceParent(msvc)

    # This is bogus.  createGroup is async.  makeService must be
    # allowed to return a Deferred or some crap.
    for g in config['groups']:
        wordsRealm.createGroup(g)

    return msvc 
Example #22
Source File: test_userauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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.assertEquals(server.supportedAuthentications,
                          ['keyboard-interactive', 'password', 'publickey']) 
Example #23
Source File: tap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeService(config):
    """
    Construct a service for operating a SSH server.

    @param config: An L{Options} instance specifying server options, including
        where server keys are stored and what authentication methods to use.

    @return: A L{twisted.application.service.IService} provider which contains
        the requested SSH server.
    """

    t = factory.OpenSSHFactory()

    r = unix.UnixSSHRealm()
    t.portal = portal.Portal(r, config.get('credCheckers', []))
    t.dataRoot = config['data']
    t.moduliRoot = config['moduli'] or config['data']

    port = config['port']
    if config['interface']:
        # Add warning here
        port += ':interface=' + config['interface']
    return strports.service(port, t) 
Example #24
Source File: test_httpauth.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """
        Create a portal and add an in memory checker to it.

        Then set up a protectedResource that will be wrapped in each test.
        """
        self.portal = portal.Portal(TestAuthRealm())
        c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
        c.addUser('username', 'password')

        self.portal.registerChecker(c)

        self.credFactory = basic.BasicCredentialFactory('test realm')

        self.protectedResource = ProtectedResource()
        self.protectedResource.responseText = "You shouldn't see me." 
Example #25
Source File: ssh.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getService(self):
        factory = HoneyPotSSHFactory(version=self.version, logger=self.logger)
        factory.canaryservice = self
        factory.portal = portal.Portal(HoneyPotRealm())

        rsa_pubKeyString, rsa_privKeyString = getRSAKeys()
        dsa_pubKeyString, dsa_privKeyString = getDSAKeys()
        factory.portal.registerChecker(HoneypotPasswordChecker(logger=factory.logger))
        factory.portal.registerChecker(CanaryPublicKeyChecker(logger=factory.logger))
        factory.publicKeys = {b'ssh-rsa': keys.Key.fromString(data=rsa_pubKeyString),
                              b'ssh-dss': keys.Key.fromString(data=dsa_pubKeyString)}
        factory.privateKeys = {b'ssh-rsa': keys.Key.fromString(data=rsa_privKeyString),
                               b'ssh-dss': keys.Key.fromString(data=dsa_privKeyString)}
        return internet.TCPServer(self.port, factory, interface=self.listen_addr) 
Example #26
Source File: test_pb.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def connectedServerAndClient(test, realm=None):
    """
    Connect a client and server L{Broker} together with an L{IOPump}

    @param realm: realm to use, defaulting to a L{DummyRealm}

    @returns: a 3-tuple (client, server, pump).
    """
    realm = realm or DummyRealm()
    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(guest=b'guest')
    serverFactory = pb.PBServerFactory(portal.Portal(realm, [checker]))
    clientFactory = pb.PBClientFactory()
    return connectServerAndClient(test, clientFactory, serverFactory) 
Example #27
Source File: test_cftp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def startServer(self):
        realm = FileTransferTestRealm(self.testDir)
        p = portal.Portal(realm)
        p.registerChecker(test_ssh.conchTestPublicKeyChecker())
        fac = test_ssh.ConchTestServerFactory()
        fac.portal = p
        self.server = reactor.listenTCP(0, fac, interface="127.0.0.1") 
Example #28
Source File: test_userauth.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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']) 
Example #29
Source File: test_userauth.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_loopback(self):
        """
        Test that the userauth server and client play nicely with each other.
        """
        server = userauth.SSHUserAuthServer()
        client = ClientUserAuth(b'foo', self.Factory.Service())

        # set up transports
        server.transport = transport.SSHTransportBase()
        server.transport.service = server
        server.transport.isEncrypted = lambda x: True
        client.transport = transport.SSHTransportBase()
        client.transport.service = client
        server.transport.sessionID = client.transport.sessionID = b''
        # don't send key exchange packet
        server.transport.sendKexInit = client.transport.sendKexInit = \
                lambda: None

        # set up server authentication
        server.transport.factory = self.Factory()
        server.passwordDelay = 0 # remove bad password delay
        realm = Realm()
        portal = Portal(realm)
        checker = SSHProtocolChecker()
        checker.registerChecker(PasswordChecker())
        checker.registerChecker(PrivateKeyChecker())
        checker.areDone = lambda aId: (
            len(checker.successfulCredentials[aId]) == 2)
        portal.registerChecker(checker)
        server.transport.factory.portal = portal

        d = loopback.loopbackAsync(server.transport, client.transport)
        server.transport.transport.logPrefix = lambda: '_ServerLoopback'
        client.transport.transport.logPrefix = lambda: '_ClientLoopback'

        server.serviceStarted()
        client.serviceStarted()

        def check(ignored):
            self.assertEqual(server.transport.service.name, b'TestService')
        return d.addCallback(check) 
Example #30
Source File: test_pb.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def setUp(self):
        self.realm = TestRealm()
        self.realm.perspectiveFactory = NonSubclassingPerspective
        self.portal = portal.Portal(self.realm)
        self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser(b"user", b"pass")
        self.portal.registerChecker(self.checker)
        self.factory = WrappingFactory(pb.PBServerFactory(self.portal))
        self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        self.portno = self.port.getHost().port