Ejemplo n.º 1
0
 def endpoint(self, scheme, host, port):
     ep = None
     if scheme == 'http':
         ep = endpoints.TCP4ClientEndpoint(reactor, host, port)
     elif scheme == 'https':
         ep = endpoints.SSL4ClientEndpoint(reactor, host, port, context)
     return ep
Ejemplo n.º 2
0
def run(reactor, host, port):
    options = ssl.optionsForClientTLS(host)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, host, port, options)
    factory = IRCFactory()
    deferred = endpoint.connect(factory)
    deferred.addCallback(lambda protocol: protocol.deferred)
    return deferred
Ejemplo n.º 3
0
    def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{SSL4ClientEndpoint} and return the values needed to verify
        its behaviour.

        @param reactor: A fake L{IReactorSSL} that L{SSL4ClientEndpoint} can
            call L{IReactorSSL.connectSSL} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorSSL.connectSSL}
        """
        address = IPv4Address("TCP", "localhost", 80)

        if connectArgs is None:
            connectArgs = {}

        return (endpoints.SSL4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             self.clientSSLContext,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 self.clientSSLContext,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address)
Ejemplo n.º 4
0
    def start(self):
        log.msg(
            "WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release."
        )

        if CowrieConfig.has_option("output_hpfeeds3", "channel"):
            self.channel = CowrieConfig.get("output_hpfeeds3", "channel")

        if CowrieConfig.has_option("output_hpfeeds3", "endpoint"):
            endpoint = CowrieConfig.get("output_hpfeeds3", "endpoint")
        else:
            server = CowrieConfig.get("output_hpfeeds3", "server")
            port = CowrieConfig.getint("output_hpfeeds3", "port")

            if CowrieConfig.has_option("output_hpfeeds3", "tlscert"):
                with open(CowrieConfig.get("output_hpfeeds3",
                                           "tlscert")) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(
                    reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CowrieConfig.get("output_hpfeeds3", "identifier")
        secret = CowrieConfig.get("output_hpfeeds3", "secret")

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 5
0
    def start(self):
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CONFIG.has_option('output_hpfeeds', 'channel'):
            self.channel = CONFIG.get('output_hpfeeds', 'channel')

        if CONFIG.has_option('output_hpfeeds', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeeds', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeeds', 'server')
            port = CONFIG.getint('output_hpfeeds', 'port')

            if CONFIG.has_option('output_hpfeeds', 'tlscert'):
                with open(CONFIG.get('output_hpfeeds', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 6
0
 def endpoint(self, scheme, host, port):
     ep = None
     if scheme == 'http':
         ep = endpoints.TCP4ClientEndpoint(reactor, host, port)
     elif scheme == 'https':
         from twisted.internet import ssl
         ep = endpoints.SSL4ClientEndpoint(reactor, host, port,
                                           ssl.ClientContextFactory())
     return ep
Ejemplo n.º 7
0
    def join(self):
        from twisted.internet._sslverify import OpenSSLCertificateAuthorities
        from OpenSSL import crypto
        if self._proto:
            raise Exception("Already connected")

        # Own callbacks
        callbacks = {'connected': [CalvinCB(self._connected)],
                     'disconnected': [CalvinCB(self._disconnected)],
                     'connection_failed': [CalvinCB(self._connection_failed)],
                     'data': [CalvinCB(self._data)],
                     'set_proto': [CalvinCB(self._set_proto)]}

        self._factory = TCPClientFactory(callbacks) # addr="%s:%s" % (self._host_ip, self._host_port))
        runtime_to_runtime_security = _conf.get("security","runtime_to_runtime_security")
        if runtime_to_runtime_security=="tls":
            _log.debug("TwistedCalvinTransport with TLS chosen")
            trusted_ca_certs = []
            try:
                self._runtime_credentials = runtime_credentials.RuntimeCredentials(self._node_name)
                ca_cert_list_str, ca_cert_list_x509, truststore = certificate.get_truststore(certificate.TRUSTSTORE_TRANSPORT)
                for ca_cert in ca_cert_list_str:
                    trusted_ca_certs.append(crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert))
                ca_certs = OpenSSLCertificateAuthorities(trusted_ca_certs)
                client_credentials_data =self._runtime_credentials.get_runtime_credentials()
                client_credentials = ssl.PrivateCertificate.loadPEM(client_credentials_data)
            except Exception as err:
                _log.error("TwistedCalvinTransport: Failed to load client credentials, err={}".format(err))
                raise
            try:
                options = ssl.optionsForClientTLS(self._server_node_name,
                                                   trustRoot=ca_certs,
                                                   clientCertificate=client_credentials)
            except Exception as err:
                _log.error("TwistedCalvinTransport: Failed to create optionsForClientTLS "
                                "\n\terr={}"
                                "\n\tself._server_node_name={}".format(err,
                                                                      self._server_node_name))
                raise
            try:
                endpoint = endpoints.SSL4ClientEndpoint(reactor,
                                                        self._host_ip,
                                                        int(self._host_port),
                                                        options)
            except:
                _log.error("TwistedCalvinTransport: Client failed connectSSL")
                raise
            try:
                endpoint.connect(self._factory)
            except Exception as e:
                _log.error("TwistedCalvinTransport: Failed endpoint.connect, e={}".format(e))
                raise
        else:
            reactor.connectTCP(self._host_ip, int(self._host_port), self._factory)
Ejemplo n.º 8
0
def main(reactor):
    factory = protocol.Factory.forProtocol(echoclient.EchoClient)
    certData = getModule(__name__).filePath.sibling("public.pem").getContent()
    authority = ssl.Certificate.loadPEM(certData)
    options = ssl.optionsForClientTLS("example.com", authority)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, "localhost", 8000, options)
    echoClient = yield endpoint.connect(factory)

    done = defer.Deferred()
    echoClient.connectionLost = lambda reason: done.callback(None)
    yield done
Ejemplo n.º 9
0
    def getConnection(self, relay):
        '''Return a deferred which will fire (if connection attempt is
        successful) with a Connection Protocol made to *relay*.

        There are three general cases to handle for incoming connection
        requests:

            1. We already have an open TLS connection to the requested relay.
               In this case, immediately callback the deferred with the
               open connection.
            2. We're currently trying to connect to this relay. In this case,
               add the request to a pending request list for this relay.
               When the connection is made successfully, callback all
               pending request deferreds with the Connection, or errback
               all pending request deferreds on failure.
            3. We have no open or pending connections to this relay (i.e.
               this is the first connection request to this relay). In this
               case, create a new list of pending requests for this connection
               and add the current request. Create an SSL endpoint and add an
               appropriate callback and errback. If the request is successful,
               callback all pending requests with the open connection when
               it opens; errback all pending requests on failure.
        
        :param stem.descriptor.server_descriptor.RelayDescriptor relay:
            relay to make a TLS connection to
        :returns: **twisted.internet.defer.Deferred** which, on success, will
            callback with an oppy.connection.connection.Connection Protocol
            object
        '''
        from twisted.internet import reactor
        
        d = defer.Deferred()
        # case 1
        if relay.fingerprint in self._connection_map:
            d.callback(self._connection_map[relay.fingerprint])
        # case 2
        elif relay.fingerprint in self._pending_map:
            self._pending_map[relay.fingerprint].append(d)
        # case 3
        else:
            connection_defer = endpoints.connectProtocol(
                        endpoints.SSL4ClientEndpoint(reactor, relay.address,
                                                     relay.or_port,
                                                     TLSClientContextFactory()),
                        Connection(relay)
            )
            connection_defer.addCallback(self._connectionSucceeded,
                                         relay.fingerprint)
            connection_defer.addErrback(self._connectionFailed,
                                        relay.fingerprint)
            self._pending_map[relay.fingerprint] = []
            self._pending_map[relay.fingerprint].append(d)

        return d
Ejemplo n.º 10
0
def main(reactor):
    certData = FilePath('server-cert.pem').getContent()
    serverCertificate = ssl.Certificate.loadPEM(certData)
    options = ssl.optionsForClientTLS(
        hostname=TARGET_HOST,
        trustRoot=serverCertificate,
        # `acceptableProtocols` is the targetted option for this example.
        acceptableProtocols=ACCEPTABLE_PROTOCOLS,
    )

    class BasicH2Request(protocol.Protocol):
        def connectionMade(self):
            print("Connection made")
            # Add a deferred that fires where we're done with the connection.
            # This deferred is returned to the reactor, and when we call it
            # back the reactor will clean up the protocol.
            self.complete = defer.Deferred()

            # Write some data to trigger the SSL handshake.
            self.transport.write(TLS_TRIGGER_DATA)

        def dataReceived(self, data):
            # We can only safely be sure what the next protocol is when we know
            # the TLS handshake is over. This is generally *not* in the call to
            # connectionMade, but instead only when we've received some data
            # back.
            print('Next protocol is: %s' % self.transport.negotiatedProtocol)
            self.transport.loseConnection()

            # If this is the first data write, we can tell the reactor we're
            # done here by firing the callback we gave it.
            if self.complete is not None:
                self.complete.callback(None)
                self.complete = None

        def connectionLost(self, reason):
            # If we haven't received any data, an error occurred. Otherwise,
            # we lost the connection on purpose.
            if self.complete is not None:
                print("Connection lost due to error %s" % (reason,))
                self.complete.callback(None)
            else:
                print("Connection closed cleanly")

    return endpoints.connectProtocol(
        endpoints.SSL4ClientEndpoint(
            reactor,
            TARGET_HOST,
            TARGET_PORT,
            options
        ),
        BasicH2Request()
    ).addCallback(lambda protocol: protocol.complete)
Ejemplo n.º 11
0
 def do_ssl(self, p_reactor):
     l_factory = Factory.forProtocol(self.EchoClient)
     l_certData = getModule(__name__).filePath.sibling(
         'public.pem').getContent()
     l_authority = ssl.Certificate.loadPEM(l_certData)
     l_options = ssl.optionsForClientTLS(u'example.com', l_authority)
     l_endpoint = endpoints.SSL4ClientEndpoint(p_reactor, 'localhost', 8000,
                                               l_options)
     echoClient = yield l_endpoint.connect(l_factory)
     d_done = Deferred()
     echoClient.connectionLost = lambda reason: d_done.callback(None)
     yield d_done
Ejemplo n.º 12
0
def main(reactor):
    HOST, PORT = 'localhost', 1717
    factory = protocol.Factory.forProtocol(EchoClient)
    certData = getModule(__name__).filePath.sibling('server.pem').getContent()
    authority = ssl.Certificate.loadPEM(certData)
    options = ssl.optionsForClientTLS(u'example.com', authority)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, HOST, PORT, options)
    echoClient = yield endpoint.connect(factory)

    done = defer.Deferred()
    echoClient.connectionLost = lambda reason: done.callback(None)
    yield done
Ejemplo n.º 13
0
def main():
    from twisted.internet import reactor, ssl
    # Simple 'TrackMarket' example displaying all events processed
    tlsctx = optionsForClientTLS(u'ws.bitcoin.de', None)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, 'ws.bitcoin.de', 443,
                                            tlsctx)
    factory = BitcoinDEMarket()

    connService = ClientService(endpoint, factory)
    connService.startService()

    reactor.run()
Ejemplo n.º 14
0
    def getConnection(self, micro_status_entry):
        '''Return a deferred which will fire (if connection attempt is
        successful) with a Connection Protocol made to *relay*.

        There are three general cases to handle for incoming connection
        requests:

            1. We already have an open TLS connection to the requested relay.
               In this case, immediately callback the deferred with the
               open connection.
            2. We're currently trying to connect to this relay. In this case,
               add the request to a pending request list for this relay.
               When the connection is made successfully, callback all
               pending request deferreds with the Connection, or errback
               all pending request deferreds on failure.
            3. We have no open or pending connections to this relay (i.e.
               this is the first connection request to this relay). In this
               case, create a new list of pending requests for this connection
               and add the current request. Create an SSL endpoint and add an
               appropriate callback and errback. If the request is successful,
               callback all pending requests with the open connection when
               it opens; errback all pending requests on failure.

        :param stem.descriptor.server_descriptor.RelayDescriptor relay:
            relay to make a TLS connection to
        :returns: **twisted.internet.defer.Deferred** which, on success, will
            callback with an oppy.connection.connection.Connection Protocol
            object

        XXX raises:
        '''
        from twisted.internet import reactor

        m = micro_status_entry

        d = defer.Deferred()

        if m.fingerprint in self._connection_dict:
            d.callback(self._connection_dict[m.fingerprint])
        elif m.fingerprint in self._pending_request_dict:
            self._pending_request_dict[m.fingerprint].append(d)
        else:
            try:
                f = endpoints.connectProtocol(endpoints.SSL4ClientEndpoint(
                    reactor, m.address, m.or_port, TLSClientContextFactory()),
                                              ConnectionBuildTask(self, m))
                f.addErrback(self._initialConnectionFailed, m.fingerprint)
                self._pending_request_dict[m.fingerprint] = [d]
            except Exception as e:
                self._initialConnectionFailed(e, m.fingerprint)

        return d
Ejemplo n.º 15
0
    def __init__(self, reactor):
        self.reactor = reactor

        print "BitcoinDESubscribeFactory - constructor"

        tlsctx = optionsForClientTLS(u'ws.bitcoin.de')  #,trustRoot=None)
        self.endpoint = endpoints.SSL4ClientEndpoint(self.reactor,
                                                     'ws.bitcoin.de', 443,
                                                     tlsctx)
        self.factory = BitcoinDESubscribeFactory()

        self.connService = ClientService(self.endpoint, self.factory)
        self.connService.startService()
Ejemplo n.º 16
0
def main(reactor, port, host):
    log.startLogging(sys.stderr, setStdout=False)

    def run_loop(proto):
        proc = CommandProcessor(proto)
        reactor.callInThread(proc.cmdloop)

    factory = protocol.Factory.forProtocol(clien_client.Factory)
    certData = getModule(__name__).filePath.sibling('server.pem').getContent()
    authority = ssl.Certificate.loadPEM(certData)
    options = ssl.optionsForClientTLS(u'example.com', authority)
    endpoints.SSL4ClientEndpoint(reactor, 'localhost', 8125,
                                 options).connect(factory)
Ejemplo n.º 17
0
def run(reactor, host, port, passwd):
    FORMAT = '%(asctime)-15s %(message)s'
    bot_log_path = os.path.join('/home', str(getpass.getuser()), 'seagl-bot.d')
    if not os.path.exists(bot_log_path):
        os.mkdir(bot_log_path, 0o755)
    bot_log = os.path.join(bot_log_path, 'bot.log')
    logging.basicConfig(filename=bot_log, level=logging.DEBUG, format=FORMAT)

    options = ssl.optionsForClientTLS(host)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, host, port, options)
    factory = IRCFactory(passwd)
    deferred = endpoint.connect(factory)
    deferred.addCallback(lambda protocol: protocol.deferred)
    return deferred
Ejemplo n.º 18
0
def connect_mqtt_tls(
    client_id,
    host,
    rootpath,
    port,
    client_creds=None,
    protocols=None,
):
    """Connect an MQTT Client over TLS without client auth.

    :param host: The hostname to connect
    :type host: str

    :param rootpath: Path to the root certificate
    :type rootpath: str

    :param port (optional): The port to use, default 8883
    :type port: int

    :param client_creds: Client cert/key pair
    :type client_creds: ssl.PrivateCertificate

    :param protocols: List of protocols for use with ALPN
    :type protocols: List[bytes]

    """
    with open(rootpath, 'rb') as rootf:
        rootblob = rootf.read()

    trust_root = ssl.trustRootFromCertificates(
        [ssl.Certificate.loadPEM(rootblob)])

    tls_options = ssl.optionsForClientTLS(host,
                                          trustRoot=trust_root,
                                          clientCertificate=client_creds,
                                          acceptableProtocols=protocols)

    endpoint = endpoints.SSL4ClientEndpoint(reactor, host, port, tls_options)

    d = endpoints.connectProtocol(endpoint, MQTTClient(client_id))

    def _socket_connected(client):
        return client.connect()

    d.addCallback(_socket_connected)
    return d
Ejemplo n.º 19
0
def _endpoint_from_config(reactor, factory, transport_config, options):
    # XXX might want some Crossbar code here? e.g. if we allow
    # "transport_config" to be a dict etc.

    # ... passing in the Factory is weird, but that's what parses all
    # the options and the URL currently

    if factory.isSecure:
        # create default client SSL context factory when none given
        from twisted.internet import ssl
        context_factory = ssl.optionsForClientTLS(factory.host)

    if factory.proxy is not None:
        factory.contextFactory = context_factory
        endpoint = endpoints.HostnameEndpoint(
            reactor,
            factory.proxy['host'],
            factory.proxy['port'],
            # timeout,  option?
        )
    else:
        if factory.isSecure:
            from twisted.internet import ssl
            endpoint = endpoints.SSL4ClientEndpoint(
                reactor,
                factory.host,
                factory.port,
                context_factory,
                # timeout,  option?
            )
        else:
            endpoint = endpoints.HostnameEndpoint(  # XXX right? not TCP4ClientEndpoint
                reactor,
                factory.host,
                factory.port,
                # timeout,  option?
                # attemptDelay,  option?
            )
    return endpoint
Ejemplo n.º 20
0
    def start(self):
        self.channel = CONFIG.get('output_hpfeed',
                                  'channel',
                                  fallback='elasticpot')

        if CONFIG.has_option('output_hpfeed', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeed', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeed', 'server')
            port = CONFIG.getint('output_hpfeed', 'port')

            if CONFIG.has_option('output_hpfeed', 'tlscert'):
                with open(CONFIG.get('output_hpfeed', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(
                    reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        try:
            self.tags = [
                tag.strip()
                for tag in CONFIG.get('output_hpfeed', 'tags').split(',')
            ]
        except Exception as e:
            self.tags = []

        ident = CONFIG.get('output_hpfeed', 'identifier')
        secret = CONFIG.get('output_hpfeed', 'secret')

        reported_ip = CONFIG.get('output_hpfeed', 'reported_ip')
        if reported_ip and reported_ip != '':
            self.reported_ip = reported_ip
        else:
            self.reported_ip = None

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 21
0
def main(reactor, host, port=443):
    options = ssl.optionsForClientTLS(hostname=host.decode("utf-8"))
    port = int(port)

    class ShowCertificate(protocol.Protocol):
        def connectionMade(self):
            self.transport.write(b"GET / HTTP/1.0\r\n\r\n")
            self.done = defer.Deferred()

        def dataReceived(self, data):
            certificate = ssl.Certificate(self.transport.getPeerCertificate())
            print("OK:", certificate)
            self.transport.abortConnection()

        def connectionLost(self, reason):
            print("Lost.")
            if not reason.check(error.ConnectionClosed):
                print("BAD:", reason.value)
            self.done.callback(None)

    return endpoints.connectProtocol(
        endpoints.SSL4ClientEndpoint(reactor, host, port, options), ShowCertificate()
    ).addCallback(lambda protocol: protocol.done)
Ejemplo n.º 22
0
def main(reactor, host, port=443):
    options = ssl.optionsForClientTLS(host.decode("utf-8"),
                                      trustRoot=certificate)
    port = int(port)
    done = defer.Deferred()

    class ShowCertificate(protocol.Protocol):
        def connectionMade(self):
            self.transport.write(b"GET / HTTP/1.0\r\n\r\n")
        def dataReceived(self, data):
            certificate = ssl.Certificate(self.transport.getPeerCertificate())
            print(certificate)
            self.transport.loseConnection()
        def connectionLost(self, reason):
            if reason.check(ssl.SSL.Error):
                print(reason.value)
            done.callback(None)

    endpoints.connectProtocol(
        endpoints.SSL4ClientEndpoint(reactor, host, port, options),
        ShowCertificate()
    )
    return done
Ejemplo n.º 23
0
    def start(self):
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CowrieConfig().has_option('output_hpfeeds3', 'channel'):
            self.channel = CowrieConfig().get('output_hpfeeds3', 'channel')

        if CowrieConfig().has_option('output_hpfeeds3', 'endpoint'):
            endpoint = CowrieConfig().get('output_hpfeeds3', 'endpoint')
        else:
            server = CowrieConfig().get('output_hpfeeds3', 'server')
            port = CowrieConfig().getint('output_hpfeeds3', 'port')

            if CowrieConfig().has_option('output_hpfeeds3', 'tlscert'):
                with open(CowrieConfig().get('output_hpfeeds3', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        try:
            self.tags = [tag.strip() for tag in CowrieConfig().get('output_hpfeeds3', 'tags').split(',')]
        except Exception as e:
            self.tags = []

        if CowrieConfig().has_option('output_hpfeeds3', 'reported_ip'):
            self.reported_ip = CowrieConfig().get('output_hpfeeds3', 'reported_ip')
            if self.reported_ip == 'UNSET_REPORTED_IP':
                self.reported_ip = None

        ident = CowrieConfig().get('output_hpfeeds3', 'identifier')
        secret = CowrieConfig().get('output_hpfeeds3', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 24
0
def initial_connection(reactor, config):
    #factory = protocol.Factory.forProtocol(EdgeProtocol)
    factory = pb.PBClientFactory()
    with open('server.pem') as cfile:
        certData = cfile.read()
    with open('ca.crt') as cfile:
        authData = cfile.read()
    clientCertificate = ssl.PrivateCertificate.loadPEM(certData)
    authority = ssl.Certificate.loadPEM(authData)
    options = ssl.optionsForClientTLS(config['server']['server_name'],
                                      authority, clientCertificate)
    endpoint = endpoints.SSL4ClientEndpoint(
        reactor, config['server']['server_name'],
        int(config['server']['server_port']), options)
    edgeClient = yield endpoint.connect(factory)

    server_iface = yield factory.getRootObject()
    start_relaying_horus_telemetry(server_iface, reactor, config)

    if config['server'].getboolean('allow_management', fallback=False):
        server_iface.callRemote('register_management_interface',
                                ManagementInterface(config, reactor))
        log.info('Registered management interface')
    else:
        log.info('Not providing management interface')

    def keepalive_task():
        server_iface.callRemote('ping').addTimeout(5, reactor).addErrback(
            lambda _err: edgeClient.transport.loseConnection())

    l = task.LoopingCall(keepalive_task)
    l.start(3 * 60.0)  # ping the server every 3 minutes

    done = defer.Deferred()
    edgeClient.connectionLost = lambda reason: done.callback(None)
    yield done
Ejemplo n.º 25
0
    def join(self):
        if self._proto:
            raise Exception("Already connected")

        # Own callbacks
        callbacks = {
            'connected': [CalvinCB(self._connected)],
            'disconnected': [CalvinCB(self._disconnected)],
            'connection_failed': [CalvinCB(self._connection_failed)],
            'data': [CalvinCB(self._data)],
            'set_proto': [CalvinCB(self._set_proto)]
        }

        self._factory = TCPClientFactory(
            callbacks)  # addr="%s:%s" % (self._host_ip, self._host_port))
        runtime_to_runtime_security = _conf.get("security",
                                                "runtime_to_runtime_security")
        if runtime_to_runtime_security == "tls":
            _log.debug("TwistedCalvinTransport with TLS chosen")
            try:
                self._runtime_credentials = runtime_credentials.RuntimeCredentials(
                    self._node_name)
                ca_cert_list_str, ca_cert_list_x509, truststore = certificate.get_truststore(
                    certificate.TRUSTSTORE_TRANSPORT)
                #TODO: figure out how to set more than one root cert in twisted truststore
                twisted_trusted_ca_cert = ssl.Certificate.loadPEM(
                    ca_cert_list_str[0])
                client_credentials_data = self._runtime_credentials.get_runtime_credentials(
                )
                client_credentials = ssl.PrivateCertificate.loadPEM(
                    client_credentials_data)
            except Exception as err:
                _log.error(
                    "TwistedCalvinTransport: Failed to load client credentials, err={}"
                    .format(err))
                raise
            try:
                options = ssl.optionsForClientTLS(self._server_node_name,
                                                  twisted_trusted_ca_cert,
                                                  client_credentials)
            except Exception as err:
                _log.error(
                    "TwistedCalvinTransport: Failed to create optionsForClientTLS "
                    "\n\terr={}"
                    "\n\tself._server_node_name={}".format(
                        err, self._server_node_name))
                raise
            try:
                endpoint = endpoints.SSL4ClientEndpoint(
                    reactor, self._host_ip, int(self._host_port), options)
            except:
                _log.error("TwistedCalvinTransport: Client failed connectSSL")
                raise
            try:
                endpoint.connect(self._factory)
            except Exception as e:
                _log.error(
                    "TwistedCalvinTransport: Failed endpoint.connect, e={}".
                    format(e))
                raise
        else:
            reactor.connectTCP(self._host_ip, int(self._host_port),
                               self._factory)