Exemple #1
0
    def test_unix_already_listening_cant_delete(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required. If it can't delete it, it
        will raise an exception.
        """
        parent_fp = os.path.join("/", "tmp", uuid4().hex)
        os.makedirs(parent_fp)
        fp = os.path.join(parent_fp, uuid4().hex)

        # Something is already there
        open(fp, "w").close()
        os.chmod(fp, 0o544)
        os.chmod(parent_fp, 0o544)

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": fp
        }

        with self.assertRaises(OSError) as e:
            create_listening_endpoint_from_config(config, self.cbdir,
                                                  reactor, self.log)
        self.assertEqual(e.exception.errno, 13)  # Permission Denied

        os.chmod(parent_fp, 0o700)
        shutil.rmtree(parent_fp)
Exemple #2
0
    def test_unix_already_listening_cant_delete(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required. If it can't delete it, it
        will raise an exception.
        """
        parent_fp = os.path.join("/", "tmp", uuid4().hex)
        os.makedirs(parent_fp)
        fp = os.path.join(parent_fp, uuid4().hex)

        # Something is already there
        open(fp, "w").close()
        os.chmod(fp, 0o544)
        os.chmod(parent_fp, 0o544)

        reactor = SelectReactor()
        config = {"type": "unix", "path": fp}

        with self.assertRaises(OSError) as e:
            create_listening_endpoint_from_config(config, self.cbdir, reactor,
                                                  self.log)
        self.assertEqual(e.exception.errno, 13)  # Permission Denied

        os.chmod(parent_fp, 0o700)
        shutil.rmtree(parent_fp)
Exemple #3
0
    def test_unix_already_listening(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required.
        """
        path = os.path.join("/", "tmp", uuid4().hex)
        self.addCleanup(os.remove, path)

        # Something is already there
        open(path, "w").close()

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": path
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir,
                                                         reactor, self.log)
        self.assertTrue(isinstance(endpoint, UNIXServerEndpoint))

        factory = Factory.forProtocol(Echo)
        endpoint.listen(factory)

        self.assertIn(
            factory,
            [getattr(x, "factory", None) for x in reactor.getReaders()])
Exemple #4
0
    def test_unix_already_listening(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required.
        """
        path = os.path.join("/", "tmp", uuid4().hex)
        self.addCleanup(os.remove, path)

        # Something is already there
        open(path, "w").close()

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": path
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir,
                                                         reactor, self.log)
        self.assertTrue(isinstance(endpoint, UNIXServerEndpoint))

        factory = Factory.forProtocol(Echo)
        endpoint.listen(factory)

        self.assertIn(
            factory,
            [getattr(x, "factory", None) for x in reactor.getReaders()])
Exemple #5
0
    def test_twisted_server(self):
        reactor = SelectReactor()
        config = {
            "type": "twisted",
            "server_string": "tcp:9876:interface=127.0.0.1",
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir, reactor, self.log)
        self.assertTrue(isinstance(endpoint, TCP4ServerEndpoint))
Exemple #6
0
    def test_twisted_server(self):
        reactor = SelectReactor()
        config = {
            "type": "twisted",
            "server_string": "tcp:9876:interface=127.0.0.1",
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir, reactor, self.log)
        self.assertTrue(isinstance(endpoint, TCP4ServerEndpoint))
Exemple #7
0
    def test_tls_auth_denied(self):
        """
        A MQTT client offering the wrong certificate won't be authenticated.
        """
        reactor, router, server_factory, session_factory = build_mqtt_server()
        real_reactor = selectreactor.SelectReactor()
        logger = make_logger()

        session, pump = connect_application_session(
            server_factory, ObservingSession, component_config=ComponentConfig(realm=u"mqtt"))

        endpoint = create_listening_endpoint_from_config({
            "type": "tcp",
            "port": 1099,
            "interface": "0.0.0.0",
            "tls": {
                "certificate": "server.crt",
                "key": "server.key",
                "dhparam": "dhparam",
                "ca_certificates": [
                    "ca.cert.pem",
                    "intermediate.cert.pem"
                ]},
        }, FilePath(__file__).sibling('certs').path, real_reactor, logger)

        client_endpoint = create_connecting_endpoint_from_config({
            "type": "tcp",
            "host": "127.0.0.1",
            "port": 1099,
            "tls": {
                # BAD key: trusted by the CA, but wrong ID
                "certificate": "client_1.crt",
                "hostname": u"localhost",
                "key": "client_1.key",
                "ca_certificates": [
                    "ca.cert.pem",
                    "intermediate.cert.pem"
                ]},
        }, FilePath(__file__).sibling('certs').path, real_reactor, logger)

        p = []
        l = endpoint.listen(server_factory)

        class TestProtocol(Protocol):
            data = b""
            expected = (
                ConnACK(session_present=False, return_code=1).serialise())

            def dataReceived(self_, data):
                self_.data = self_.data + data

                if len(self_.data) == len(self_.expected):
                    self.assertEqual(self_.data, self_.expected)
                    real_reactor.stop()

        @l.addCallback
        def _listening(factory):
            d = client_endpoint.connect(Factory.forProtocol(TestProtocol))

            @d.addCallback
            def _(proto):
                p.append(proto)

                proto.transport.write(
                    Connect(client_id=u"test123",
                            flags=ConnectFlags(clean_session=False)).serialise())

                proto.transport.write(
                    Publish(duplicate=False, qos_level=1, retain=False, topic_name=u"test", payload=b"{}", packet_identifier=1).serialise())

        lc = LoopingCall(pump.flush)
        lc.clock = real_reactor
        lc.start(0.01)

        def timeout():
            print("Timing out :(")
            real_reactor.stop()
            print(self.logs.log_text.getvalue())

        # Timeout, just in case
        real_reactor.callLater(10, timeout)
        real_reactor.run()

        client_protocol = p[0]

        # We get a CONNECT
        self.assertEqual(client_protocol.data,
                         ConnACK(session_present=False, return_code=1).serialise())
        client_protocol.data = b""

        pump.flush()

        # No events!
        self.assertEqual(len(session.events), 0)
Exemple #8
0
    def _test_tls_auth(self):
        """
        A MQTT client can connect using mutually authenticated TLS
        authentication.
        """
        reactor, router, server_factory, session_factory = build_mqtt_server()
        real_reactor = selectreactor.SelectReactor()
        logger = make_logger()

        session, pump = connect_application_session(
            server_factory,
            ObservingSession,
            component_config=ComponentConfig(realm="mqtt",
                                             controller=MockContainer()))

        endpoint = create_listening_endpoint_from_config(
            {
                "type": "tcp",
                "port": 1099,
                "interface": "0.0.0.0",
                "tls": {
                    "certificate": "server.crt",
                    "key": "server.key",
                    "dhparam": "dhparam",
                    "ca_certificates":
                    ["ca.cert.pem", "intermediate.cert.pem"]
                },
            },
            FilePath(__file__).sibling('certs').path, real_reactor, logger)

        client_endpoint = create_connecting_endpoint_from_config(
            {
                "type": "tcp",
                "host": "127.0.0.1",
                "port": 1099,
                "tls": {
                    "certificate": "client.crt",
                    "hostname": "localhost",
                    "key": "client.key",
                    "ca_certificates":
                    ["ca.cert.pem", "intermediate.cert.pem"]
                },
            },
            FilePath(__file__).sibling('certs').path, real_reactor, logger)

        p = []
        l = endpoint.listen(server_factory)

        class TestProtocol(Protocol):
            data = b""
            expected = (
                ConnACK(session_present=False, return_code=0).serialise() +
                PubACK(packet_identifier=1).serialise())

            def dataReceived(self_, data):
                self_.data = self_.data + data

                if len(self_.data) == len(self_.expected):
                    self.assertEqual(self_.data, self_.expected)
                    real_reactor.stop()

        @l.addCallback
        def _listening(factory):
            d = client_endpoint.connect(Factory.forProtocol(TestProtocol))

            @d.addCallback
            def _(proto):
                p.append(proto)

                proto.transport.write(
                    Connect(
                        client_id="test123",
                        flags=ConnectFlags(clean_session=False)).serialise())

                proto.transport.write(
                    Publish(duplicate=False,
                            qos_level=1,
                            retain=False,
                            topic_name="test",
                            payload=b"{}",
                            packet_identifier=1).serialise())

        lc = LoopingCall(pump.flush)
        lc.clock = real_reactor
        lc.start(0.01)

        def timeout():
            print("Timing out :(")
            real_reactor.stop()
            print(self.logs.log_text.getvalue())

        # Timeout, just in case
        real_reactor.callLater(10, timeout)
        real_reactor.run()

        client_protocol = p[0]

        # We get a CONNECT
        self.assertEqual(
            client_protocol.data,
            ConnACK(session_present=False, return_code=0).serialise() +
            PubACK(packet_identifier=1).serialise())
        client_protocol.data = b""

        pump.flush()

        # This needs to be replaced with the real deal, see https://github.com/crossbario/crossbar/issues/885
        self.assertEqual(len(session.events), 1)
        self.assertEqual(session.events, [{"args": tuple(), "kwargs": {}}])