コード例 #1
0
    def setUp(self, authentication=False):
        "This will launch InterceptorPB and provide a client connected to it."
        # Launch a client in a disconnected state
        # it will be connected on demand through the self.ipb_connect() method
        self.ipb_client = InterceptorPBProxy()

        yield ProvisionWithoutInterceptorPB.setUp(self)

        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        InterceptorPBConfigInstance = InterceptorPBConfig()

        # Launch the interceptor server
        pbInterceptor_factory = InterceptorPB()
        pbInterceptor_factory.setConfig(InterceptorPBConfigInstance)

        # Configure portal
        p = portal.Portal(JasminPBRealm(pbInterceptor_factory))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser("test_user", md5("test_password").digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.pbInterceptor_server = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbInterceptor_port = self.pbInterceptor_server.getHost().port
コード例 #2
0
ファイル: test_router.py プロジェクト: MeherBouhdid/jasmin
 def setUp(self, authentication = False):
     # Initiating config objects without any filename
     # will lead to setting defaults and that's what we
     # need to run the tests
     self.RouterPBConfigInstance = RouterPBConfig()
     
     # Launch the router server
     self.pbRoot_f = RouterPB()
     
     # Mock callbacks
     # will be used for assertions
     self.pbRoot_f.bill_request_submit_sm_resp_callback = mock.Mock(wraps = self.pbRoot_f.bill_request_submit_sm_resp_callback)
     self.pbRoot_f.deliver_sm_callback = mock.Mock(wraps = self.pbRoot_f.deliver_sm_callback)
     
     self.pbRoot_f.setConfig(self.RouterPBConfigInstance)
     p = portal.Portal(JasminPBRealm(self.pbRoot_f))
     if not authentication:
         p.registerChecker(AllowAnonymousAccess())
     else:
         c = InMemoryUsernamePasswordDatabaseDontUse()
         c.addUser('test_user', md5('test_password').digest())
         p.registerChecker(c)
     jPBPortalRoot = JasminPBPortalRoot(p)
     self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
     self.pbPort = self.PBServer.getHost().port
コード例 #3
0
ファイル: jasmind.py プロジェクト: ktosiu/jasmin
    def startRouterPBService(self):
        "Start Router PB server"

        RouterPBConfigInstance = RouterPBConfig(self.options['config'])
        self.components['router-pb-factory'] = RouterPB()
        self.components['router-pb-factory'].setConfig(RouterPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['router-pb-factory']))
        if RouterPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(RouterPBConfigInstance.admin_username,
                      RouterPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['router-pb-server'] = reactor.listenTCP(
            RouterPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=RouterPBConfigInstance.bind)

        # AMQP Broker is used to listen to deliver_sm/dlr queues
        return self.components['router-pb-factory'].addAmqpBroker(self.components['amqp-broker-factory'])
コード例 #4
0
    def setUp(self):
        yield SMPPClientTestCases.setUp(self)

        # Init SMPPServerPB
        SMPPServerPBConfigInstance = SMPPServerPBConfig()
        SMPPServerPBInstance = SMPPServerPB(SMPPServerPBConfigInstance)
        SMPPServerPBInstance.addSmpps(self.smpps_factory)

        p = portal.Portal(JasminPBRealm(SMPPServerPBInstance))
        c = InMemoryUsernamePasswordDatabaseDontUse()
        c.addUser('smppsadmin', md5('smppspwd').digest())
        p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.SMPPServerPBInstanceServer = reactor.listenTCP(SMPPServerPBConfigInstance.port,
                                                            pb.PBServerFactory(jPBPortalRoot))

        # Init SMPPServerPBClient and connect it to SMPPServerPB
        SMPPServerPBClientConfigInstance = SMPPServerPBClientConfig()
        self.SMPPServerPBProxyInstance = SMPPServerPBProxy()
        yield self.SMPPServerPBProxyInstance.connect(
            SMPPServerPBClientConfigInstance.host,
            SMPPServerPBClientConfigInstance.port,
            SMPPServerPBClientConfigInstance.username,
            SMPPServerPBClientConfigInstance.password,
            retry=False)

        # Lower the timeout config to pass the timeout tests quickly
        self.DLRThrower.config.timeout = 2
        self.DLRThrower.config.retry_delay = 1
        self.DLRThrower.config.max_retries = 2

        # Most important thing:
        # Swap default direct smpps access to perspectivebroker smpps access:
        self.DLRThrower.addSmpps(self.SMPPServerPBProxyInstance)
コード例 #5
0
ファイル: manhole.py プロジェクト: xlhtc007/pyfarm-agent
def manhole_factory(namespace, username, password):
    """
    Produces a factory object which can be used to listen for telnet
    connections to the manhole.
    """
    assert isinstance(namespace, dict)
    assert isinstance(username, STRING_TYPES)
    assert isinstance(password, STRING_TYPES)
    assert TelnetRealm.NAMESPACE is None, "namespace already set"

    # TODO: we should try to use the system to authorize users instead
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username, password)

    # Setup the namespace
    namespace = namespace.copy()
    namespace.setdefault("pp", pprint)
    namespace.setdefault("show", show)

    realm = TelnetRealm()
    TelnetRealm.NAMESPACE = namespace
    portal = Portal(realm, [checker])
    factory = ServerFactory()
    factory.protocol = TransportProtocolFactory(portal)
    return factory
コード例 #6
0
ファイル: jasmind.py プロジェクト: Koulio/jasmin
    def startSMPPClientManagerPBService(self):
        "Start SMPP Client Manager PB server"

        SMPPClientPBConfigInstance = SMPPClientPBConfig(self.options["config"])
        self.components["smppcm-pb-factory"] = SMPPClientManagerPB()
        self.components["smppcm-pb-factory"].setConfig(SMPPClientPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components["smppcm-pb-factory"]))
        if SMPPClientPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(SMPPClientPBConfigInstance.admin_username, SMPPClientPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components["smppcm-pb-server"] = reactor.listenTCP(
            SMPPClientPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=SMPPClientPBConfigInstance.bind,
        )

        # AMQP Broker is used to listen to submit_sm queues and publish to deliver_sm/dlr queues
        self.components["smppcm-pb-factory"].addAmqpBroker(self.components["amqp-broker-factory"])
        self.components["smppcm-pb-factory"].addRedisClient(self.components["rc"])
コード例 #7
0
ファイル: aggregator.py プロジェクト: pwarren/AGDeviceControl
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
コード例 #8
0
ファイル: pbbenchserver.py プロジェクト: BillAndersan/twisted
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()
コード例 #9
0
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))
コード例 #10
0
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))
コード例 #11
0
ファイル: pbecho.py プロジェクト: Almad/twisted
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()
コード例 #12
0
ファイル: auth_server.py プロジェクト: pombredanne/epsilon
def main():
    """
    Start the AMP server and the reactor.
    """
    startLogging(stdout)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("testuser", "examplepass")
    realm = AdditionRealm()
    factory = CredAMPServerFactory(Portal(realm, [checker]))
    reactor.listenTCP(7805, factory)
    reactor.run()
コード例 #13
0
ファイル: test_auth.py プロジェクト: rockstar/txjsonrpc
class WrapResourceTestCase(TestCase):

    def setUp(self):
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser("joe", "blow")

    def test_wrapResourceWeb(self):
        from twisted.web.resource import IResource, Resource
        root = Resource()
        wrapped = wrapResource(root, [self.checker])
        self.assertTrue(IResource.providedBy(wrapped))
コード例 #14
0
ファイル: test_checkers.py プロジェクト: pepijndevos/Twemail
 def setUp(self):
     ch1 = InMemoryUsernamePasswordDatabaseDontUse()
     ch2 = InMemoryUsernamePasswordDatabaseDontUse()
     self.cach = CascadingChecker()
     
     ch1.addUser('foo', 'bar')
     ch1.addUser('boo', 'far')
     ch2.addUser('for', 'bao')
     
     self.cach.registerChecker(ch1)
     self.cach.registerChecker(ch2)
コード例 #15
0
ファイル: smtp.py プロジェクト: firemark/EmailCatcher
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))
コード例 #16
0
ファイル: pb.py プロジェクト: isotoma/badgerproxy
    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)
コード例 #17
0
    def test_setupSiteWithProtectedHook(self):
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "password")

        self.svc.setupSite(self.makeConfig(change_hook_dialects={"base": True}, change_hook_auth=[checker]))
        site = self.svc.site

        # check that it has the right kind of resources attached to its
        # root
        root = site.resource
        req = mock.Mock()
        self.assertIsInstance(root.getChildWithDefault("change_hook", req), HTTPAuthSessionWrapper)
コード例 #18
0
ファイル: pb.py プロジェクト: isotoma/boiler
    def __init__(self, port=8787):
        BaseService.__init__(self)

        boiler = None
        portal = Portal(PbRealm(boiler))

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

        service = strports.service("tcp:%d" % port, pb.PBServerFactory(portal))
        service.setServiceParent(self)
コード例 #19
0
def StartServices(callback):
    global IMPCONNECTED_CALLBACK
    IMPCONNECTED_CALLBACK = callback
    # fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5

    password = md5("imp").digest()
    for x in range(0, 100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7005, pb.PBServerFactory(portal))
コード例 #20
0
 def test_requestAvatarId(self):
     """
     L{SSHProtocolChecker.requestAvatarId} should defer to one if its
     registered checkers to authenticate a user.
     """
     checker = SSHProtocolChecker()
     passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
     passwordDatabase.addUser('test', 'test')
     checker.registerChecker(passwordDatabase)
     d = checker.requestAvatarId(UsernamePassword('test', 'test'))
     def _callback(avatarId):
         self.assertEquals(avatarId, 'test')
     return d.addCallback(_callback)
コード例 #21
0
ファイル: authhmac.py プロジェクト: wgnet/twoost
def protectResource(resource, accessKey, secretKey, realm=None):

    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    from twisted.web.guard import HTTPAuthSessionWrapper
    from twisted.cred.portal import Portal

    portal_realm = _SingleResourceRealm(resource)

    cred_checker = InMemoryUsernamePasswordDatabaseDontUse()
    cred_checker.addUser(accessKey, secretKey)
    portal = Portal(portal_realm, [cred_checker])

    cred_factory = AuthHMACCredentialFactory(realm or 'twoost-app')
    return HTTPAuthSessionWrapper(portal, [cred_factory])
コード例 #22
0
def main():
    from twisted.application import internet
    from twisted.application import service    
    
    portal = Portal(SimpleRealm())
    # initiate a simple checker
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)
    
    a = service.Application("Console SMTP Server")
    internet.TCPServer(2500, ConsoleSMTPFactory(portal)).setServiceParent(a)
    
    return a
コード例 #23
0
 def setUp(self):
     self.service_calls = []
     self.encoder = pdu_encoding.PDUEncoder()
     self.smpp_config = SMPPServerConfig(msgHandler=self._serviceHandler,
                                         systems={'userA': {"max_bindings": 2}}
                                         )
     portal = Portal(self.SmppRealm())
     credential_checker = InMemoryUsernamePasswordDatabaseDontUse()
     credential_checker.addUser('userA', 'valid')
     portal.registerChecker(credential_checker)
     self.factory = SMPPServerFactory(self.smpp_config, auth_portal=portal)
     self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
     self.tr = proto_helpers.StringTransport()
     self.proto.makeConnection(self.tr)
コード例 #24
0
    def test_requestAvatarIdWithNotEnoughAuthentication(self):
        """
        If the client indicates that it is never satisfied, by always returning
        False from _areDone, then L{SSHProtocolChecker} should raise
        L{NotEnoughAuthentication}.
        """
        checker = SSHProtocolChecker()
        def _areDone(avatarId):
            return False
        self.patch(checker, 'areDone', _areDone)

        passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
        passwordDatabase.addUser('test', 'test')
        checker.registerChecker(passwordDatabase)
        d = checker.requestAvatarId(UsernamePassword('test', 'test'))
        return self.assertFailure(d, NotEnoughAuthentication)
コード例 #25
0
ファイル: server.py プロジェクト: Eyepea/xivo-skaro
def new_restricted_server_resource(app, dhcp_request_processing_service,
                                   credentials, realm_name=REALM_NAME):
    """Create and return a new server resource that will be accessible only
    if the given credentials are present in the HTTP requests.
    
    credentials is a (username, password) tuple.
    
    """
    server_resource = ServerResource(app, dhcp_request_processing_service)
    pwd_checker = InMemoryUsernamePasswordDatabaseDontUse()
    pwd_checker.addUser(*credentials)
    realm = _SimpleRealm(server_resource)
    portal = Portal(realm, [pwd_checker])
    credentialFactory = DigestCredentialFactory('MD5', realm_name)
    wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])
    return wrapper
コード例 #26
0
ファイル: test_managers.py プロジェクト: AVert/jasmin
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.SMPPClientPBConfigInstance = SMPPClientPBConfig()
        self.SMPPClientPBConfigInstance.authentication = authentication
        AMQPServiceConfigInstance = AmqpConfig()
        AMQPServiceConfigInstance.reconnectOnConnectionLoss = False

        # Launch AMQP Broker
        self.amqpBroker = AmqpFactory(AMQPServiceConfigInstance)
        self.amqpBroker.preConnect()
        self.amqpClient = reactor.connectTCP(AMQPServiceConfigInstance.host, AMQPServiceConfigInstance.port, self.amqpBroker)

        # Wait for AMQP Broker connection to get ready
        yield self.amqpBroker.getChannelReadyDeferred()

        # Launch the client manager server
        pbRoot = SMPPClientManagerPB()
        pbRoot.setConfig(self.SMPPClientPBConfigInstance)

        yield pbRoot.addAmqpBroker(self.amqpBroker)
        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port

        # Launch the router server
        self.RouterPBInstance = RouterPB()
        self.RouterPBInstance.setConfig(RouterPBConfig())
        pbRoot.addRouterPB(self.RouterPBInstance)

        # Default SMPPClientConfig
        defaultSMPPClientId = '001-testconnector'

        self.defaultConfig = SMPPClientConfig(id=defaultSMPPClientId,
                                              username='******',
                                              reconnectOnConnectionFailure=True,
                                              port=9002,
                                              )
コード例 #27
0
ファイル: node.py プロジェクト: jlg/pydra-map-reduce
    def get_service(self):
        """
        Creates a service object that can be used by twistd init code to start the server
        """
        realm = ClusterRealm()
        realm.server = self

        # create security - Twisted does not support ssh in the pb so were doing our
        # own authentication until it is implmented, leaving in the memory
        # checker just so we dont have to rip out the authentication code
        from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
        checker =   InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser('master','1234')
        p = portal.Portal(realm, [checker])

        factory = pb.PBServerFactory(p)
        return internet.TCPServer(self.port, factory)
コード例 #28
0
	def runConcurrentThread(self):
		
		port = int(self.pluginPrefs.get('smtpPort', '2525'))
		user = self.pluginPrefs.get('smtpUser', 'guest')
		password = self.pluginPrefs.get('smtpPassword', 'password')
							
		portal = Portal(SimpleRealm())
		checker = InMemoryUsernamePasswordDatabaseDontUse()
		checker.addUser(user, password)
		portal.registerChecker(checker)

		try:
			self.smtpFactory = MySMTPFactory(portal)
			self.listeningPort = reactor.listenTCP(port, self.smtpFactory)
			reactor.run()
		except self.StopThread:
			pass	# Optionally catch the StopThread exception and do any needed cleanup.
コード例 #29
0
ファイル: server.py プロジェクト: hawkowl/hawkmail
    def __init__(self, config):
        self._config = config
        self._emails = deque([])
        self._authorisedHelo = config.get("AuthorisedHosts", ["127.0.0.1"])
        self.noisy = config.get("LogNoisy", True)

        self.portal = Portal(SimpleRealm(self))

        if self._config.get("Authentication", False):
            checker = InMemoryUsernamePasswordDatabaseDontUse()
            checker.addUser("guest", "password")
            print "Checking Authentication"
        else:
            checker = AllowAnonymousAccess()
            print "Allowing anonymous access"

        self.portal.registerChecker(checker)
コード例 #30
0
ファイル: test_interceptor.py プロジェクト: AVert/jasmin
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.InterceptorPBConfigInstance = InterceptorPBConfig()
        self.InterceptorPBConfigInstance.authentication = authentication

        # Launch the interceptor pb server
        pbRoot = InterceptorPB()
        pbRoot.setConfig(self.InterceptorPBConfigInstance)

        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.IPBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.ipbPort = self.IPBServer.getHost().port

        # Test fixtures
        self.SubmitSMPDU = SubmitSM(
            source_addr='20203060',
            destination_addr='20203060',
            short_message='MT hello world',
        )
        self.DeliverSMPDU = DeliverSM(
            source_addr='20203060',
            destination_addr='20203060',
            short_message='MO hello world',
        )
        self.connector = Connector('abc')
        self.user = User(1, Group(100), 'username', 'password')

        # Routables fixtures
        self.routable_simple = SimpleRoutablePDU(self.connector, self.SubmitSMPDU, self.user, datetime.now())

        # Scripts fixtures
        self.script_generic = InterceptorScript('somevar = "something in MOIS"')
        self.script_3_second = InterceptorScript('import time;time.sleep(3)')
        self.script_syntax_error = InterceptorScript('somevar = sssss')
        self.script_http_status = InterceptorScript('http_status = 404')
        self.script_smpp_status = InterceptorScript('smpp_status = 64')
コード例 #31
0
 def setUp(self):
     self.service_calls = []
     self.clock = task.Clock()
     self.encoder = pdu_encoding.PDUEncoder()
     self.smpp_config = SMPPServerConfig(msgHandler=self._serviceHandler,
                                         systems={'userA': {"max_bindings": 2}},
                                         enquireLinkTimerSecs=0.1,
                                         responseTimerSecs=0.1
                                         )
     portal = Portal(self.SmppRealm())
     credential_checker = InMemoryUsernamePasswordDatabaseDontUse()
     credential_checker.addUser('userA', 'valid')
     portal.registerChecker(credential_checker)
     self.factory = SMPPServerFactory(self.smpp_config, auth_portal=portal)
     self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
     self.proto.callLater = self.clock.callLater
     self.tr = proto_helpers.StringTransport()
     self.proto.makeConnection(self.tr)
コード例 #32
0
def main():
    from twisted.application import internet
    from twisted.application import service

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

    a = service.Application("Console SMTP Server")
    internet.TCPServer(2500, ConsoleSMTPFactory(portal)).setServiceParent(a)

    # Tell the reactor to just totally stop in a few seconds.
    WAIT_TIME = 10
    reactor.callLater(WAIT_TIME, reactor.stop)

    # OK, configure is complete.
    return a
コード例 #33
0
ファイル: cred_memory.py プロジェクト: ling-1/GETAiqiyiDanmu
    def generateChecker(self, argstring):
        """
        This checker factory expects to get a list of
        username:password pairs, with each pair also separated by a
        colon. For example, the string 'alice:f:bob:g' would generate
        two users, one named 'alice' and one named 'bob'.
        """
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        if argstring:
            pieces = argstring.split(":")
            if len(pieces) % 2:
                from twisted.cred.strcred import InvalidAuthArgumentString

                raise InvalidAuthArgumentString("argstring must be in format U:P:...")
            for i in range(0, len(pieces), 2):
                username, password = pieces[i], pieces[i + 1]
                checker.addUser(username, password)
        return checker
コード例 #34
0
    def test_requestAvatarIdWithNotEnoughAuthentication(self):
        """
        If the client indicates that it is never satisfied, by always returning
        False from _areDone, then L{SSHProtocolChecker} should raise
        L{NotEnoughAuthentication}.
        """
        checker = checkers.SSHProtocolChecker()

        def _areDone(avatarId):
            return False

        self.patch(checker, 'areDone', _areDone)

        passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
        passwordDatabase.addUser('test', 'test')
        checker.registerChecker(passwordDatabase)
        d = checker.requestAvatarId(UsernamePassword('test', 'test'))
        return self.assertFailure(d, NotEnoughAuthentication)
コード例 #35
0
ファイル: test_managers.py プロジェクト: techniclite/jasmin
    def setUp(self, authentication=False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.SMPPClientPBConfigInstance = SMPPClientPBConfig()
        self.SMPPClientPBConfigInstance.authentication = authentication
        AMQPServiceConfigInstance = AmqpConfig()
        AMQPServiceConfigInstance.reconnectOnConnectionLoss = False

        # Launch AMQP Broker
        self.amqpBroker = AmqpFactory(AMQPServiceConfigInstance)
        self.amqpBroker.preConnect()
        self.amqpClient = reactor.connectTCP(AMQPServiceConfigInstance.host,
                                             AMQPServiceConfigInstance.port,
                                             self.amqpBroker)

        # Wait for AMQP Broker connection to get ready
        yield self.amqpBroker.getChannelReadyDeferred()

        # Launch the client manager server
        pbRoot = SMPPClientManagerPB()
        pbRoot.setConfig(self.SMPPClientPBConfigInstance)
        yield pbRoot.addAmqpBroker(self.amqpBroker)
        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port

        # Default SMPPClientConfig
        defaultSMPPClientId = '001-testconnector'

        self.defaultConfig = SMPPClientConfig(
            id=defaultSMPPClientId,
            username='******',
            reconnectOnConnectionFailure=True,
            port=9002,
        )
コード例 #36
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
コード例 #37
0
    def setUp(self, authentication=False):
        SMPPServerTestCases.setUp(self)

        # Initiating config objects without any filename
        self.SMPPServerPBConfigInstance = SMPPServerPBConfig()
        self.SMPPServerPBConfigInstance.authentication = authentication

        # Launch the SMPPServerPB
        pbRoot = SMPPServerPB(self.SMPPServerPBConfigInstance)
        pbRoot.addSmpps(self.smpps_factory)

        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port
コード例 #38
0
    def startInterceptorPBService(self):
        """Start Interceptor PB server"""

        InterceptorPBConfigInstance = InterceptorPBConfig(self.options['config'])
        self.components['interceptor-pb-factory'] = InterceptorPB(InterceptorPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['interceptor-pb-factory']))
        if InterceptorPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(InterceptorPBConfigInstance.admin_username,
                      InterceptorPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['interceptor-pb-server'] = reactor.listenTCP(
            InterceptorPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=InterceptorPBConfigInstance.bind)
コード例 #39
0
    def startSMPPClientManagerPBService(self):
        "Start SMPP Client Manager PB server"

        SMPPClientPBConfigInstance = SMPPClientPBConfig(self.options['config'])
        self.components['smppcm-pb-factory'] = SMPPClientManagerPB()
        self.components['smppcm-pb-factory'].setConfig(
            SMPPClientPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['smppcm-pb-factory']))
        if SMPPClientPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(SMPPClientPBConfigInstance.admin_username,
                      SMPPClientPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['smppcm-pb-server'] = reactor.listenTCP(
            SMPPClientPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=SMPPClientPBConfigInstance.bind)

        # AMQP Broker is used to listen to submit_sm queues and publish to deliver_sm/dlr queues
        self.components['smppcm-pb-factory'].addAmqpBroker(
            self.components['amqp-broker-factory'])
        self.components['smppcm-pb-factory'].addRedisClient(
            self.components['rc'])
        self.components['smppcm-pb-factory'].addRouterPB(
            self.components['router-pb-factory'])

        # Add interceptor if enabled:
        if 'interceptor-pb-client' in self.components:
            self.components['smppcm-pb-factory'].addInterceptorPBClient(
                self.components['interceptor-pb-client'])
コード例 #40
0
    def __init__(self, map, total_players):
        import player

        players = [player.PlayerCacheable(i) for i in range(total_players)]
        import game

        self.game = game.Game(players=players, server=self)
        map.setup()
        self.game.set_map(map)
        self.ai_players = []

        from twisted.cred.portal import Portal
        from twisted.cred.checkers import (
            AllowAnonymousAccess,
            InMemoryUsernamePasswordDatabaseDontUse,
        )

        portal = Portal(RequestClientRealm(self))
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        # 	checker = AllowAnonymousAccess()
        portal.registerChecker(checker)
        self.listening_port = reactor.listenTCP(pb.portno,
                                                pb.PBServerFactory(portal))
コード例 #41
0
def main():
    realm = TradeRealm()
    realm.server = TradeEngine(realm)
    
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    checker.addUser("admin","123")
    checker.addUser("0017aca","1")
    checker.addUser('0017cac','1')
    portal = Portal(realm, [checker])  
    
    factory = pb.PBServerFactory(portal)
    reactor.listenTCP(pb.portno, factory)
    reactor.run()
コード例 #42
0
ファイル: fnemon.py プロジェクト: gatekeep/dvmfne
    # Start update loop
    update_stats = task.LoopingCall(websock_update)
    update_stats.start(FREQUENCY)

    # Connect to fne_core
    report_client = reportClientFactory()
    reactor.connectTCP(FNEMON_IP, FNEMON_PORT, report_client)

    # Create websocket server to push content to clients
    dashboard_server = dashboardFactory('ws://*:9000')
    dashboard_server.protocol = dashboard
    reactor.listenTCP(9000, dashboard_server)

    # Start activity update loop
    update_act = task.LoopingCall(gen_activity)
    update_act.start(ACT_FREQUENCY)

    siteResource = File('./webroot')

    passwd_db = InMemoryUsernamePasswordDatabaseDontUse()
    passwd_db.addUser(HTACCESS_USER, HTACCESS_PASS)

    portal = Portal(publicHTMLRealm(), [passwd_db])
    resource = HTTPAuthSessionWrapper(portal, [BasicCredentialFactory('auth')])

    # Create static web server to push initial index.html
    website = Site(resource)
    reactor.listenTCP(WEB_SERVER_PORT, website)

    reactor.run()
コード例 #43
0
def init():
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("foobar", "2c03333fd2e55480e4685cb7d9dd3ee2ef1357bb")
    portal.registerChecker(checker)
    reactor.listenTCP(25, SMTPFactory(portal))
コード例 #44
0
class SoledadSessionTestCase(unittest.TestCase):
    """
    Tests adapted from for
    L{twisted.web.test.test_httpauth.HTTPAuthSessionWrapper}.
    """
    def makeRequest(self, *args, **kwargs):
        request = DummyRequest(*args, **kwargs)
        request.path = '/'
        return request

    def setUp(self):
        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.wrapper = SoledadSession(self.portal)

    def _authorizedTokenLogin(self, request):
        authorization = b64encode(self.username + b':' + self.password)
        request.requestHeaders.addRawHeader(b'authorization',
                                            b'Token ' + authorization)
        return getChildForRequest(self.wrapper, request)

    def test_getChildWithDefault(self):
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def _invalidAuthorizationTest(self, response):
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization', response)
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_getChildWithDefaultUnauthorizedUser(self):
        return self._invalidAuthorizationTest(b'Basic ' +
                                              b64encode(b'foo:bar'))

    def test_getChildWithDefaultUnauthorizedPassword(self):
        return self._invalidAuthorizationTest(b'Basic ' +
                                              b64encode(self.username +
                                                        b':bar'))

    def test_getChildWithDefaultUnrecognizedScheme(self):
        return self._invalidAuthorizationTest(b'Quux foo bar baz')

    def test_getChildWithDefaultAuthorized(self):
        request = self.makeRequest([self.childName])
        child = self._authorizedTokenLogin(request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(request.written, [self.childContent])

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_renderAuthorized(self):
        # Request it exactly, not any of its children.
        request = self.makeRequest([])
        child = self._authorizedTokenLogin(request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(request.written, [self.avatarContent])

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_decodeRaises(self):
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization',
                                            b'Token decode should fail')
        child = getChildForRequest(self.wrapper, request)
        self.assertIsInstance(child, UnauthorizedResource)

    def test_parseResponse(self):
        basicAuthorization = b'Basic abcdef123456'
        self.assertEqual(self.wrapper._parseHeader(basicAuthorization), None)
        tokenAuthorization = b'Token abcdef123456'
        self.assertEqual(self.wrapper._parseHeader(tokenAuthorization),
                         b'abcdef123456')

    def test_unexpectedDecodeError(self):
        class UnexpectedException(Exception):
            pass

        class BadFactory(object):
            scheme = b'bad'

            def getChallenge(self, client):
                return {}

            def decode(self, response, request):
                print("decode raised")
                raise UnexpectedException()

        self.wrapper._credentialFactory = BadFactory()
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization', b'Bad abc')
        child = getChildForRequest(self.wrapper, request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        errors = self.flushLoggedErrors(UnexpectedException)
        self.assertEqual(len(errors), 1)

    def test_unexpectedLoginError(self):
        class UnexpectedException(Exception):
            pass

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

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

        self.portal.registerChecker(BrokenChecker())
        request = self.makeRequest([self.childName])
        child = self._authorizedTokenLogin(request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
コード例 #45
0
ファイル: objshssh.py プロジェクト: iapyeh/objsh
def getObjshPortal(protocol_class, acl_options):

    realm = ObjshRealm(protocol_class)
    portal = cred_portal.Portal(realm)

    # ssh client's public key
    sshclient_pubkey_folders = acl_options.get('client_publickeys')
    if sshclient_pubkey_folders:
        del acl_options['client_publickeys']
        client_keydb = {}
        loaded_folders = []
        for sshclient_pubkey_folder in sshclient_pubkey_folders:
            if sshclient_pubkey_folder in loaded_folders: continue
            if not os.path.exists(sshclient_pubkey_folder): continue
            loaded_folders.append(sshclient_pubkey_folder)
            for file in os.listdir(sshclient_pubkey_folder):
                username, ext = os.path.splitext(file)
                if username.startswith('.') or ext != '.pub': continue
                try:
                    client_keydb[username].append(
                        ssh_keys.Key.fromFile(
                            os.path.join(sshclient_pubkey_folder, file)))
                    log.msg('load key-based ssh user ' + username)
                except KeyError:
                    try:
                        client_keydb[username] = [
                            ssh_keys.Key.fromFile(
                                os.path.join(sshclient_pubkey_folder, file))
                        ]
                        log.msg('load key-based ssh user ' + username)
                    except ssh_keys.BadKeyError:
                        log.msg('Warning! failed to load sshkey of ' +
                                username)
        sshDB = SSHPublicKeyChecker(InMemorySSHKeyDB(client_keydb))

        # this should register to portal to make it work
        portal.registerChecker(sshDB)

    # username, password based authentication
    cascading_checker = CascadingChecker()
    for acl_name, acl_settings in acl_options.items():
        if acl_settings['kind'] == 'LDAP':
            if LDAPBindingChecker is None:
                log.msg(
                    'Warning: package ldaptor is not installed, LDAP authentication ignored'
                )
                continue
            #basedn = 'dc=example,dc=com'
            basedn = acl_settings['basedn']
            query = '(%s=%%(name)s)' % acl_settings['uid_attrname']
            cfg = ldaptor_config.LDAPConfig(basedn, {
                basedn: (acl_settings['host'], acl_settings.get('port', 389))
            }, None, query)
            checker = LDAPBindingChecker(acl_settings['uid_attrname'], cfg)
            cascading_checker.registerChecker(checker)
        elif acl_settings['kind'] == 'PAM':
            # system accounts
            cascading_checker.registerChecker(
                PamPasswordDatabase(acl_settings['usernames'],
                                    acl_settings['username_prefix']))
        elif acl_settings['kind'] == 'IN_MEMORY_ACCOUNTS':
            # in memory accounts
            passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
            for username, password in acl_settings.get('accounts', {}).items():
                username = username.strip()  # do not allow empty username
                password = password.strip()  # do not allow empty password
                if password and username:
                    passwdDB.addUser(username, password)
                    log.msg('Warning! in memory account: %s' % (username))
            cascading_checker.registerChecker(passwdDB)
        else:
            raise ValueError('Acl kind of %s is unknown' % acl_name)

    portal.registerChecker(cascading_checker)
    return portal
コード例 #46
0
            return defer.fail(failure.Failure(ewords.NoSuchUser(name)))
        else:
            return defer.succeed(user)

    def lookupGroup(self, name):
        assert isinstance(name, unicode)
        name = name.lower()
        try:
            group = self.groups[name]
        except KeyError:
            return defer.fail(failure.Failure(ewords.NoSuchGroup(name)))
        else:
            return defer.succeed(group)


if __name__ == '__main__':
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    realm = InMemoryWordsRealm('localhost')
    realm.addGroup(Group('testing123'))

    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser('testuser1', 'testpassword')
    checker.addUser('testuser2', 'testpassword')

    p = portal.Portal(realm, [checker])

    factory = IRCFactory(realm, p)
    factory.protocol = IRCUser

    reactor.listenTCP(6667, factory)
    reactor.run()
コード例 #47
0
        return text

    def perspective_error(self):
        raise DefinedError("exception!")

    def logout(self):
        print self, "logged out"


class SimpleRealm:
    implements(IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if pb.IPerspective in interfaces:
            avatar = SimplePerspective()
            return pb.IPerspective, avatar, avatar.logout
        else:
            raise NotImplementedError("no interface")


if __name__ == '__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()
コード例 #48
0
ファイル: test_httpauth.py プロジェクト: ryanc-me/twisted
class HTTPAuthHeaderTests(unittest.TestCase):
    """
    Tests for L{HTTPAuthSessionWrapper}.
    """
    makeRequest = DummyRequest

    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)

    def _authorizedBasicLogin(self, request):
        """
        Add an I{basic authorization} header to the given request and then
        dispatch it, starting from C{self.wrapper} and returning the resulting
        L{IResource}.
        """
        authorization = b64encode(self.username + b':' + self.password)
        request.requestHeaders.addRawHeader(b'authorization',
                                            b'Basic ' + authorization)
        return getChildForRequest(self.wrapper, request)

    def test_getChildWithDefault(self):
        """
        Resource traversal which encounters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} instance when the request does
        not have the required I{Authorization} headers.
        """
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def _invalidAuthorizationTest(self, response):
        """
        Create a request with the given value as the value of an
        I{Authorization} header and perform resource traversal with it,
        starting at C{self.wrapper}.  Assert that the result is a 401 response
        code.  Return a L{Deferred} which fires when this is all done.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization', response)
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_getChildWithDefaultUnauthorizedUser(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with a user which does not exist.
        """
        return self._invalidAuthorizationTest(b'Basic ' +
                                              b64encode(b'foo:bar'))

    def test_getChildWithDefaultUnauthorizedPassword(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with a user which exists and the wrong
        password.
        """
        return self._invalidAuthorizationTest(b'Basic ' +
                                              b64encode(self.username +
                                                        b':bar'))

    def test_getChildWithDefaultUnrecognizedScheme(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with an unrecognized scheme.
        """
        return self._invalidAuthorizationTest(b'Quux foo bar baz')

    def test_getChildWithDefaultAuthorized(self):
        """
        Resource traversal which encounters an L{HTTPAuthSessionWrapper}
        results in an L{IResource} which renders the L{IResource} avatar
        retrieved from the portal when the request has a valid I{Authorization}
        header.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(request.written, [self.childContent])

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_renderAuthorized(self):
        """
        Resource traversal which terminates at an L{HTTPAuthSessionWrapper}
        and includes correct authentication headers results in the
        L{IResource} avatar (not one of its children) retrieved from the
        portal being rendered.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        # Request it exactly, not any of its children.
        request = self.makeRequest([])
        child = self._authorizedBasicLogin(request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(request.written, [self.avatarContent])

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def test_getChallengeCalledWithRequest(self):
        """
        When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue
        a challenge, it calls the C{getChallenge} method with the request as an
        argument.
        """
        @implementer(ICredentialFactory)
        class DumbCredentialFactory:
            scheme = b'dumb'

            def __init__(self):
                self.requests = []

            def getChallenge(self, request):
                self.requests.append(request)
                return {}

        factory = DumbCredentialFactory()
        self.credentialFactories.append(factory)
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(factory.requests, [request])

        d.addCallback(cbFinished)
        request.render(child)
        return d

    def _logoutTest(self):
        """
        Issue a request for an authentication-protected resource using valid
        credentials and then return the C{DummyRequest} instance which was
        used.

        This is a helper for tests about the behavior of the logout
        callback.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))

        class SlowerResource(Resource):
            def render(self, request):
                return NOT_DONE_YET

        self.avatar.putChild(self.childName, SlowerResource())
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        request.render(child)
        self.assertEqual(self.realm.loggedOut, 0)
        return request

    def test_logout(self):
        """
        The realm's logout callback is invoked after the resource is rendered.
        """
        request = self._logoutTest()
        request.finish()
        self.assertEqual(self.realm.loggedOut, 1)

    def test_logoutOnError(self):
        """
        The realm's logout callback is also invoked if there is an error
        generating the response (for example, if the client disconnects
        early).
        """
        request = self._logoutTest()
        request.processingFailed(
            Failure(ConnectionDone("Simulated disconnect")))
        self.assertEqual(self.realm.loggedOut, 1)

    def test_decodeRaises(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has a I{Basic
        Authorization} header which cannot be decoded using base64.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization',
                                            b'Basic decode should fail')
        child = getChildForRequest(self.wrapper, request)
        self.assertIsInstance(child, UnauthorizedResource)

    def test_selectParseResponse(self):
        """
        L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving
        the L{ICredentialFactory} to use to parse the header and a string
        containing the portion of the header which remains to be parsed.
        """
        basicAuthorization = b'Basic abcdef123456'
        self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization),
                         (None, None))
        factory = BasicCredentialFactory('example.com')
        self.credentialFactories.append(factory)
        self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization),
                         (factory, b'abcdef123456'))

    def test_unexpectedDecodeError(self):
        """
        Any unexpected exception raised by the credential factory's C{decode}
        method results in a 500 response code and causes the exception to be
        logged.
        """
        logObserver = EventLoggingObserver.createWithCleanup(
            self, globalLogPublisher)

        class UnexpectedException(Exception):
            pass

        class BadFactory:
            scheme = b'bad'

            def getChallenge(self, client):
                return {}

            def decode(self, response, request):
                raise UnexpectedException()

        self.credentialFactories.append(BadFactory())
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization', b'Bad abc')
        child = getChildForRequest(self.wrapper, request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEquals(1, len(logObserver))
        self.assertIsInstance(logObserver[0]["log_failure"].value,
                              UnexpectedException)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)

    def test_unexpectedLoginError(self):
        """
        Any unexpected failure from L{Portal.login} results in a 500 response
        code and causes the failure to be logged.
        """
        logObserver = EventLoggingObserver.createWithCleanup(
            self, globalLogPublisher)

        class UnexpectedException(Exception):
            pass

        class BrokenChecker:
            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.assertEquals(1, len(logObserver))
        self.assertIsInstance(logObserver[0]["log_failure"].value,
                              UnexpectedException)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)

    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
コード例 #49
0
    publicKeys = {
        b'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PUBLIC)
    }
    privateKeys = {
        b'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PRIVATE)
    }
    # Service handlers.
    services = {
        b'ssh-userauth': userauth.SSHUserAuthServer,
        b'ssh-connection': connection.SSHConnection
    }

    def getPrimes(self):
        """
        See: L{factory.SSHFactory}
        """
        return PRIMES


portal = portal.Portal(ExampleRealm())
passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser(b'admin', b'123')
sshDB = SSHPublicKeyChecker(InMemorySSHKeyDB(
    {b'user': [keys.Key.fromFile(CLIENT_RSA_PUBLIC)]}))
portal.registerChecker(passwdDB)
portal.registerChecker(sshDB)
ExampleFactory.portal = portal

if __name__ == '__main__':
    reactor.listenTCP(5022, ExampleFactory())
    reactor.run()
コード例 #50
0
ファイル: test_httpauth.py プロジェクト: yingjun2/codenode
class HTTPAuthHeaderTests(unittest.TestCase):
    """
    Tests for L{HTTPAuthSessionWrapper}.
    """
    makeRequest = DummyRequest

    def setUp(self):
        """
        Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
        """
        self.username = '******'
        self.password = '******'
        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 = Resource()
        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)

    def _authorizedBasicLogin(self, request):
        """
        Add an I{basic authorization} header to the given request and then
        dispatch it, starting from C{self.wrapper} and returning the resulting
        L{IResource}.
        """
        authorization = b64encode(self.username + ':' + self.password)
        request.headers['authorization'] = 'Basic ' + authorization
        return getChildForRequest(self.wrapper, request)

    def test_getChildWithDefault(self):
        """
        Resource traversal which encounters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} instance when the request does
        not have the required I{Authorization} headers.
        """
        request = self.makeRequest([self.childName])
        child = self.wrapper.getChildWithDefault(self.childName, request)
        self.assertIsInstance(child, UnauthorizedResource)

    def _invalidAuthorizationTest(self, response):
        """
        Create a request with the given value as the value of an
        I{Authorization} header and perform resource traversal with it,
        starting at C{self.wrapper}.  Assert that the result is a 401 response
        code.  Return a L{Deferred} which fires when this is all done.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        request.headers['authorization'] = response
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)

        d.addCallback(cbFinished)
        render(child, request)
        return d

    def test_getChildWithDefaultUnauthorizedUser(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with a user which does not exist.
        """
        return self._invalidAuthorizationTest('Basic ' + b64encode('foo:bar'))

    def test_getChildWithDefaultUnauthorizedPassword(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with a user which exists and the wrong
        password.
        """
        return self._invalidAuthorizationTest('Basic ' +
                                              b64encode(self.username +
                                                        ':bar'))

    def test_getChildWithDefaultUnrecognizedScheme(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has an
        I{Authorization} header with an unrecognized scheme.
        """
        return self._invalidAuthorizationTest('Quux foo bar baz')

    def test_getChildWithDefaultAuthorized(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{IResource} which renders the L{IResource} avatar
        retrieved from the portal when the request has a valid I{Authorization}
        header.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEquals(request.written, [self.childContent])

        d.addCallback(cbFinished)
        render(child, request)
        return d

    def test_getChallengeCalledWithRequest(self):
        """
        When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue
        a challenge, it calls the C{getChallenge} method with the request as an
        argument.
        """
        class DumbCredentialFactory(object):
            implements(ICredentialFactory)
            scheme = 'dumb'

            def __init__(self):
                self.requests = []

            def getChallenge(self, request):
                self.requests.append(request)
                return {}

        factory = DumbCredentialFactory()
        self.credentialFactories.append(factory)
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()

        def cbFinished(ignored):
            self.assertEqual(factory.requests, [request])

        d.addCallback(cbFinished)
        render(child, request)
        return d

    def test_logout(self):
        """
        The realm's logout callback is invoked after the resource is rendered.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))

        class SlowerResource(Resource):
            def render(self, request):
                return NOT_DONE_YET

        self.avatar.putChild(self.childName, SlowerResource())
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        render(child, request)
        self.assertEqual(self.realm.loggedOut, 0)
        request.finish()
        self.assertEqual(self.realm.loggedOut, 1)

    def test_decodeRaises(self):
        """
        Resource traversal which enouncters an L{HTTPAuthSessionWrapper}
        results in an L{UnauthorizedResource} when the request has a I{Basic
        Authorization} header which cannot be decoded using base64.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        request.headers['authorization'] = 'Basic decode should fail'
        child = getChildForRequest(self.wrapper, request)
        self.assertIsInstance(child, UnauthorizedResource)

    def test_selectParseResponse(self):
        """
        L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving
        the L{ICredentialFactory} to use to parse the header and a string
        containing the portion of the header which remains to be parsed.
        """
        basicAuthorization = 'Basic abcdef123456'
        self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization),
                         (None, None))
        factory = BasicCredentialFactory('example.com')
        self.credentialFactories.append(factory)
        self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization),
                         (factory, 'abcdef123456'))

    def test_unexpectedDecodeError(self):
        """
        Any unexpected exception raised by the credential factory's C{decode}
        method results in a 500 response code and causes the exception to be
        logged.
        """
        class UnexpectedException(Exception):
            pass

        class BadFactory(object):
            scheme = 'bad'

            def getChallenge(self, client):
                return {}

            def decode(self, response, request):
                raise UnexpectedException()

        self.credentialFactories.append(BadFactory())
        request = self.makeRequest([self.childName])
        request.headers['authorization'] = 'Bad abc'
        child = getChildForRequest(self.wrapper, request)
        render(child, request)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)

    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)
        render(child, request)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
コード例 #51
0
        glob_rules_file = conf.get('nx_extract', 'rules_path')
    except:
        print "No rules path in conf file ! Using default (/etc/nginx/sec-rules/core.rules)"

    try:
        glob_user = conf.get('nx_extract', 'username')
    except:
        print 'No username for web access ! Nx_extract will exit.'
        exit(-1)

    try:
        glob_pass = conf.get('nx_extract', 'password')
    except:
        print 'No password for web access ! Nx_extract will exit.'
        exit(-1)
    fd.close()

    credshandler = InMemoryUsernamePasswordDatabaseDontUse(
    )  # i know there is DontUse in the name
    credshandler.addUser(glob_user, glob_pass)
    portal = Portal(HTTPRealm(), [credshandler])
    credentialFactory = DigestCredentialFactory("md5", "Naxsi-UI")

    webroot = HTTPAuthSessionWrapper(portal, [credentialFactory])

    factory = Site(webroot)
    reactor.listenTCP(port, factory)

    #   daemonize(stdout = '/tmp/nx_extract_output', stderr = '/tmp/nx_extract_error')
    reactor.run()
コード例 #52
0
ファイル: test_ampauth.py プロジェクト: perkinslr/epsilon-py3
class CredReceiverTests(TestCase):
    """
    Tests for L{CredReceiver}, an L{IBoxReceiver} which integrates with
    L{twisted.cred} to provide authentication and authorization of AMP
    connections.
    """
    def setUp(self):
        """
        Create a L{CredReceiver} hooked up to a fake L{IBoxSender} which
        records boxes sent through it.
        """
        self.username = '******'
        self.password = '******'
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser(self.username, self.password)
        self.avatar = StubAvatar()
        self.realm = StubRealm(self.avatar)
        self.portal = Portal(self.realm, [self.checker])
        self.server = CredReceiver()
        self.server.portal = self.portal
        self.client = AMP()
        self.finished = loopbackAsync(self.server, self.client)

    def test_otpLogin(self):
        """
        L{CredReceiver.otpLogin} returns without error if the pad is valid.
        """
        PAD = 'test_otpLogin'
        self.portal.registerChecker(OneTimePadChecker({PAD: 'user'}))
        d = self.server.otpLogin(PAD)

        def cbLoggedIn(result):
            self.assertEqual(result, {})

        d.addCallback(cbLoggedIn)
        return d

    def test_otpLoginUnauthorized(self):
        """
        L{CredReceiver.otpLogin} should fail with L{UnauthorizedLogin} if an
        invalid pad is received.
        """
        self.portal.registerChecker(OneTimePadChecker({}))
        return self.assertFailure(
            self.server.otpLogin('test_otpLoginUnauthorized'),
            UnauthorizedLogin)

    def test_otpLoginNotImplemented(self):
        """
        L{CredReceiver.otpLogin} should fail with L{NotImplementedError} if
        the realm raises L{NotImplementedError} when asked for the avatar.
        """
        def noAvatar(avatarId, mind, *interfaces):
            raise NotImplementedError()

        self.realm.requestAvatar = noAvatar

        PAD = 'test_otpLoginNotImplemented'
        self.portal.registerChecker(OneTimePadChecker({PAD: 'user'}))
        return self.assertFailure(self.server.otpLogin(PAD),
                                  NotImplementedError)

    def test_otpLoginResponder(self):
        """
        L{CredReceiver} responds to the L{OTPLogin} command.
        """
        PAD = 'test_otpLoginResponder'
        self.portal.registerChecker(OneTimePadChecker({PAD: 'user'}))
        d = self.client.callRemote(OTPLogin, pad=PAD)

        def cbLoggedIn(result):
            self.assertEqual(result, {})

        d.addCallback(cbLoggedIn)
        return d

    def test_passwordLoginDifferentChallenges(self):
        """
        L{CredReceiver.passwordLogin} returns a new challenge each time it is
        called.
        """
        first = self.server.passwordLogin(self.username)
        second = self.server.passwordLogin(self.username)
        self.assertNotEqual(first['challenge'], second['challenge'])

    def test_passwordLoginResponder(self):
        """
        L{CredReceiver} responds to the L{PasswordLogin} L{Command} with a
        challenge.
        """
        d = self.client.callRemote(PasswordLogin, username=self.username)

        def cbLogin(result):
            self.assertIn('challenge', result)

        d.addCallback(cbLogin)
        return d

    def test_determineFromDifferentNonces(self):
        """
        Each time L{PasswordChallengeResponse.determineFrom} is used, it
        generates a different C{cnonce} value.
        """
        first = PasswordChallengeResponse.determineFrom('a', 'b')
        second = PasswordChallengeResponse.determineFrom('a', 'b')
        self.assertNotEqual(first['cnonce'], second['cnonce'])

    def test_passwordChallengeResponse(self):
        """
        L{CredReceiver.passwordChallengeResponse} returns without error if the
        response is valid.
        """
        challenge = self.server.passwordLogin(self.username)['challenge']
        cnonce = '123abc'
        cleartext = '%s %s %s' % (challenge, cnonce, self.password)
        response = sha1(cleartext).digest()
        d = self.server.passwordChallengeResponse(cnonce, response)

        def cbLoggedIn(result):
            self.assertEqual(result, {})

        d.addCallback(cbLoggedIn)
        return d

    def test_passwordChallengeResponseResponder(self):
        """
        L{CredReceiver} responds to the L{PasswordChallengeResponse} L{Command}
        with an empty box if the response supplied is valid.
        """
        challenge = self.server.passwordLogin(self.username)['challenge']
        d = self.client.callRemote(
            PasswordChallengeResponse,
            **PasswordChallengeResponse.determineFrom(challenge,
                                                      self.password))

        def cbResponded(result):
            self.assertEqual(result, {})

        d.addCallback(cbResponded)
        return d

    def test_response(self):
        """
        L{PasswordChallengeResponse.determineFrom} generates the correct
        response to a challenge issued by L{CredReceiver.passwordLogin}.
        """
        challenge = self.server.passwordLogin(self.username)['challenge']
        result = PasswordChallengeResponse.determineFrom(
            challenge, self.password)
        d = self.server.passwordChallengeResponse(**result)

        def cbLoggedIn(ignored):
            [(avatarId, mind, interfaces)] = self.realm.requests
            self.assertEqual(avatarId, self.username)
            self.assertEqual(interfaces, (IBoxReceiver, ))

            # The avatar is now the protocol's box receiver.
            self.assertIdentical(self.server.boxReceiver, self.avatar)

            # And the avatar has been started up with the protocol's
            # IBoxSender.
            self.assertIdentical(self.avatar.boxSender, self.server.boxSender)

            # After the connection is lost, the logout function should be
            # called.
            self.assertEqual(self.realm.loggedOut, 0)
            self.server.connectionLost(
                Failure(ConnectionDone("test connection lost")))
            self.assertEqual(self.realm.loggedOut, 1)

        d.addCallback(cbLoggedIn)
        return d

    def test_invalidResponse(self):
        """
        L{CredReceiver.passwordChallengeResponse} returns a L{Deferred} which
        fails with L{UnauthorizedLogin} if it is passed a response which is not
        valid.
        """
        challenge = self.server.passwordLogin(self.username)['challenge']
        return self.assertFailure(
            self.server.passwordChallengeResponse(cnonce='bar',
                                                  response='baz'),
            UnauthorizedLogin)

    def test_connectionLostWithoutAvatar(self):
        """
        L{CredReceiver.connectionLost} does not raise an exception if no login
        has occurred when it is called.
        """
        self.server.connectionLost(
            Failure(ConnectionDone("test connection lost")))

    def test_unrecognizedCredentialsLogin(self):
        """
        L{login} raises L{UnhandledCredentials} if passed a credentials object
        which provides no interface explicitly supported by that function,
        currently L{IUsernamePassword}.
        """
        self.assertRaises(UnhandledCredentials, login, None, None)

    def test_passwordChallengeLogin(self):
        """
        L{login} issues the commands necessary to authenticate against
        L{CredReceiver} when given an L{IUsernamePassword} provider with its
        C{username} and C{password} attributes set to valid credentials.
        """
        loginDeferred = login(self.client,
                              UsernamePassword(self.username, self.password))

        def cbLoggedIn(clientAgain):
            self.assertIdentical(self.client, clientAgain)
            self.assertIdentical(self.server.boxReceiver, self.avatar)

        loginDeferred.addCallback(cbLoggedIn)
        return loginDeferred

    def test_passwordChallengeInvalid(self):
        """
        L{login} returns a L{Deferred} which fires with L{UnauthorizedLogin} if
        the L{UsernamePassword} credentials object given does not contain valid
        authentication information.
        """
        boxReceiver = self.server.boxReceiver
        loginDeferred = login(
            self.client, UsernamePassword(self.username + 'x', self.password))
        self.assertFailure(loginDeferred, UnauthorizedLogin)

        def cbFailed(ignored):
            self.assertIdentical(self.server.boxReceiver, boxReceiver)

        loginDeferred.addCallback(cbFailed)
        return loginDeferred

    def test_noAvatar(self):
        """
        L{login} returns a L{Deferred} which fires with L{NotImplementedError}
        if the realm raises L{NotImplementedError} when asked for the avatar.
        """
        def noAvatar(avatarId, mind, *interfaces):
            raise NotImplementedError()

        self.realm.requestAvatar = noAvatar

        loginDeferred = login(self.client,
                              UsernamePassword(self.username, self.password))
        return self.assertFailure(loginDeferred, NotImplementedError)
コード例 #53
0
    services = {
        b'ssh-userauth': userauth.SSHUserAuthServer,
        #b'ssh-userauth': authserver.SSHUserAuthServer,
        b'ssh-connection': connection.SSHConnection
    }

    def getPrimes(self):
        """
        See: L{factory.SSHFactory}
        """
        return PRIMES


portal = portal.Portal(ExampleRealm())
passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser(b'user', b'password')
#sshDB = SSHPublicKeyChecker(InMemorySSHKeyDB(
#    {b'user': [keys.Key.fromFile(CLIENT_RSA_PUBLIC)]}))
portal.registerChecker(passwdDB)
#portal.registerChecker(sshDB)
ExampleFactory.portal = portal


class Counter(resource.Resource):
    isLeaf = True
    numberRequests = 0

    def render_GET(self, request):
        self.numberRequests += 1
        request.setHeader(b"content-type", b"text/plain")
        content = u"I am request #{}\n".format(self.numberRequests)
コード例 #54
0
class SSHCommandClientEndpointTestsMixin(object):
    """
    Tests for L{SSHCommandClientEndpoint}, an L{IStreamClientEndpoint}
    implementations which connects a protocol with the stdin and stdout of a
    command running in an SSH session.

    These tests apply to L{SSHCommandClientEndpoint} whether it is constructed
    using L{SSHCommandClientEndpoint.existingConnection} or
    L{SSHCommandClientEndpoint.newConnection}.

    Subclasses must override L{create}, L{assertClientTransportState}, and
    L{finishConnection}.
    """
    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)

    def create(self):
        """
        Create and return a new L{SSHCommandClientEndpoint} to be tested.
        Override this to implement creation in an interesting way the endpoint.
        """
        raise NotImplementedError("%r did not implement create" %
                                  (self.__class__.__name__, ))

    def assertClientTransportState(self, client, immediateClose):
        """
        Make an assertion about the connectedness of the given protocol's
        transport.  Override this to implement either a check for the
        connection still being open or having been closed as appropriate.

        @param client: The client whose state is being checked.

        @param immediateClose: Boolean indicating whether the connection was
            closed immediately or not.
        """
        raise NotImplementedError(
            "%r did not implement assertClientTransportState" %
            (self.__class__.__name__, ))

    def finishConnection(self):
        """
        Do any remaining work necessary to complete an in-memory connection
        attempted initiated using C{self.reactor}.
        """
        raise NotImplementedError("%r did not implement finishConnection" %
                                  (self.__class__.__name__, ))

    def connectedServerAndClient(self, serverFactory, clientFactory):
        """
        Set up an in-memory connection between protocols created by
        C{serverFactory} and C{clientFactory}.

        @return: A three-tuple.  The first element is the protocol created by
            C{serverFactory}.  The second element is the protocol created by
            C{clientFactory}.  The third element is the L{IOPump} connecting
            them.
        """
        clientProtocol = clientFactory.buildProtocol(None)
        serverProtocol = serverFactory.buildProtocol(None)

        clientTransport = AbortableFakeTransport(
            clientProtocol,
            isServer=False,
            hostAddress=self.clientAddress,
            peerAddress=self.serverAddress)
        serverTransport = AbortableFakeTransport(
            serverProtocol,
            isServer=True,
            hostAddress=self.serverAddress,
            peerAddress=self.clientAddress)

        pump = connect(serverProtocol, serverTransport, clientProtocol,
                       clientTransport)
        return serverProtocol, clientProtocol, pump

    def test_interface(self):
        """
        L{SSHCommandClientEndpoint} instances provide L{IStreamClientEndpoint}.
        """
        endpoint = SSHCommandClientEndpoint.newConnection(
            self.reactor, b"dummy command", b"dummy user", self.hostname,
            self.port)
        self.assertTrue(verifyObject(IStreamClientEndpoint, endpoint))

    def test_channelOpenFailure(self):
        """
        If a channel cannot be opened on the authenticated SSH connection, the
        L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
        a L{Failure} wrapping the reason given by the server.
        """
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        # The server logs the channel open failure - this is expected.
        errors = self.flushLoggedErrors(ConchError)
        self.assertIn('unknown channel',
                      (errors[0].value.data, errors[0].value.value))
        self.assertEqual(1, len(errors))

        # Now deal with the results on the endpoint side.
        f = self.failureResultOf(connected)
        f.trap(ConchError)
        self.assertEqual('unknown channel', f.value.value)

        self.assertClientTransportState(client, False)

    def test_execFailure(self):
        """
        If execution of the command fails, the L{Deferred} returned by
        L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
        the reason given by the server.
        """
        self.realm.channelLookup[b'session'] = BrokenExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        f = self.failureResultOf(connected)
        f.trap(ConchError)
        self.assertEqual('channel request failed', f.value.value)

        self.assertClientTransportState(client, False)

    def test_execCancelled(self):
        """
        If execution of the command is cancelled via the L{Deferred} returned
        by L{SSHCommandClientEndpoint.connect}, the connection is closed
        immediately.
        """
        self.realm.channelLookup[b'session'] = UnsatisfiedExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)
        server, client, pump = self.finishConnection()

        connected.cancel()

        f = self.failureResultOf(connected)
        f.trap(CancelledError)

        self.assertClientTransportState(client, True)

    def test_buildProtocol(self):
        """
        Once the necessary SSH actions have completed successfully,
        L{SSHCommandClientEndpoint.connect} uses the factory passed to it to
        construct a protocol instance by calling its C{buildProtocol} method
        with an address object representing the SSH connection and command
        executed.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = AddressSpyFactory()
        factory.protocol = Protocol

        endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        self.assertIsInstance(factory.address, SSHCommandAddress)
        self.assertEqual(server.transport.getHost(), factory.address.server)
        self.assertEqual(self.user, factory.address.username)
        self.assertEqual(b"/bin/ls -l", factory.address.command)

    def test_makeConnection(self):
        """
        L{SSHCommandClientEndpoint} establishes an SSH connection, creates a
        channel in it, runs a command in that channel, and uses the protocol's
        C{makeConnection} to associate it with a protocol representing that
        command's stdin and stdout.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        self.assertNotIdentical(None, protocol.transport)

    def test_dataReceived(self):
        """
        After establishing the connection, when the command on the SSH server
        produces output, it is delivered to the protocol's C{dataReceived}
        method.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        dataReceived = []
        protocol.dataReceived = dataReceived.append

        # Figure out which channel on the connection this protocol is
        # associated with so the test can do a write on it.
        channelId = protocol.transport.id

        server.service.channels[channelId].write(b"hello, world")
        pump.pump()
        self.assertEqual(b"hello, world", b"".join(dataReceived))

    def test_connectionLost(self):
        """
        When the command closes the channel, the protocol's C{connectionLost}
        method is called.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        connectionLost = []
        protocol.connectionLost = connectionLost.append

        # Figure out which channel on the connection this protocol is associated
        # with so the test can do a write on it.
        channelId = protocol.transport.id
        server.service.channels[channelId].loseConnection()

        pump.pump()
        connectionLost[0].trap(ConnectionDone)

        self.assertClientTransportState(client, False)

    def _exitStatusTest(self, request, requestArg):
        """
        Test handling of non-zero exit statuses or exit signals.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        connectionLost = []
        protocol.connectionLost = connectionLost.append

        # Figure out which channel on the connection this protocol is associated
        # with so the test can simulate command exit and channel close.
        channelId = protocol.transport.id
        channel = server.service.channels[channelId]

        server.service.sendRequest(channel, request, requestArg)
        channel.loseConnection()
        pump.pump()
        self.assertClientTransportState(client, False)
        return connectionLost[0]

    def test_zeroExitCode(self):
        """
        When the command exits with a non-zero status, the protocol's
        C{connectionLost} method is called with a L{Failure} wrapping an
        exception which encapsulates that status.
        """
        exitCode = 0
        exc = self._exitStatusTest('exit-status', pack('>L', exitCode))
        exc.trap(ConnectionDone)

    def test_nonZeroExitStatus(self):
        """
        When the command exits with a non-zero status, the protocol's
        C{connectionLost} method is called with a L{Failure} wrapping an
        exception which encapsulates that status.
        """
        exitCode = 123
        signal = None
        exc = self._exitStatusTest('exit-status', pack('>L', exitCode))
        exc.trap(ProcessTerminated)
        self.assertEqual(exitCode, exc.value.exitCode)
        self.assertEqual(signal, exc.value.signal)

    def test_nonZeroExitSignal(self):
        """
        When the command exits with a non-zero signal, the protocol's
        C{connectionLost} method is called with a L{Failure} wrapping an
        exception which encapsulates that status.
        """
        exitCode = None
        signal = 123
        exc = self._exitStatusTest('exit-signal', pack('>L', signal))
        exc.trap(ProcessTerminated)
        self.assertEqual(exitCode, exc.value.exitCode)
        self.assertEqual(signal, exc.value.signal)

    def record(self, server, protocol, event, noArgs=False):
        """
        Hook into and record events which happen to C{protocol}.

        @param server: The SSH server protocol over which C{protocol} is
            running.
        @type server: L{IProtocol} provider

        @param protocol:

        @param event:

        @param noArgs:
        """
        # Figure out which channel the test is going to send data over so we can
        # look for it to arrive at the right place on the server.
        channelId = protocol.transport.id

        recorder = []
        if noArgs:
            f = lambda: recorder.append(None)
        else:
            f = recorder.append

        setattr(server.service.channels[channelId], event, f)
        return recorder

    def test_write(self):
        """
        The transport connected to the protocol has a C{write} method which
        sends bytes to the input of the command executing on the SSH server.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)

        dataReceived = self.record(server, protocol, 'dataReceived')
        protocol.transport.write(b"hello, world")
        pump.pump()
        self.assertEqual(b"hello, world", b"".join(dataReceived))

    def test_writeSequence(self):
        """
        The transport connected to the protocol has a C{writeSequence} method which
        sends bytes to the input of the command executing on the SSH server.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)

        dataReceived = self.record(server, protocol, 'dataReceived')
        protocol.transport.writeSequence(list(b"hello, world"))
        pump.pump()
        self.assertEqual(b"hello, world", b"".join(dataReceived))
コード例 #55
0
    # Server's host keys.
    # To simplify the example this server is defined only with a host key of
    # type RSA.
    publicKeys = {'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PUBLIC)}
    privateKeys = {'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PRIVATE)}
    # Service handlers.
    services = {
        'ssh-userauth': userauth.SSHUserAuthServer,
        'ssh-connection': connection.SSHConnection
    }

    def getPrimes(self):
        """
        See: L{factory.SSHFactory}
        """
        return PRIMES


portal = portal.Portal(ExampleRealm())
passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser('user', 'password')
sshDB = SSHPublicKeyChecker(
    InMemorySSHKeyDB({'user': [keys.Key.fromFile(CLIENT_RSA_PUBLIC)]}))
portal.registerChecker(passwdDB)
portal.registerChecker(sshDB)
ExampleFactory.portal = portal

if __name__ == '__main__':
    reactor.listenTCP(5022, ExampleFactory())
    reactor.run()
コード例 #56
0
    def display_message(self, event):
        if len(self.mailbox.messages) == 0:
            return
        message_num = self.message_list.list.nearest(event.y)
        self.messagecontent.text.delete('0.0', T.END)
        self.messagecontent.text.insert(
            '0.0', self.mailbox.messages[message_num].content())


if __name__ == '__main__':
    service = Service()
    mailbox = Mailbox()
    portal = Portal(SimpleRealm(mailbox))
    auth = InMemoryUsernamePasswordDatabaseDontUse()
    auth.addUser(service.username, service.password)
    portal.registerChecker(auth)

    f = ServerFactory()
    f.protocol = POP3Server
    f.protocol.portal = portal

    print "Starting to listen on {}:{}...".format(service.interface,
                                                  service.port)
    service.listeningPort = reactor.listenTCP(port=service.port,
                                              factory=f,
                                              interface=service.interface)
    #root.addCleanup(service.listeningPort.stopListening)

    root = T.Tk()
    tksupport.install(root)