Esempio n. 1
0
def tls_options(hostname, cert_string=None):
    """Get certificate options for TLS connections.

    If we are unable to use TLS because pyOpenSSL is not installed, this will
    raise an exception.

    Args:
        hostname (string): The hostname we are trying to connect to with TLS.
        cert_string (string): A certificate in PEM format. If provided, we
            return CertificateOptions that will trust only the given cert
            (assuming its canonical name attribute matches the given hostname).
            If not provided, we will try to load a suitable certificate for
            this hostname from our store of trusted self-signed certificates,
            and otherwise fall back to just using the trust roots configured
            for the OS to validate the server certificate.

    Returns (twisted.internet.ssl.CertificateOptions):
        Certificate suitable for use by TLS clients to connect to the given

    Raises:
        Exception: could not import pyOpenSSL package needed for TLS.
    """
    if not TLS:
        raise Exception('Unable to connect to labrad with TLS. Please be sure '
                        'to install pyOpenSSL.')
    if cert_string is None:
        cert_string = load_cert(hostname)
    if cert_string is None:
        logging.info('No certificate found for host "{}" in {}. Will use '
                     'system certs to verify tls'.format(hostname, CERTS_PATH))
        return ssl.optionsForClientTLS(hostname.decode('utf-8'))
    else:
        cert = ssl.Certificate.loadPEM(cert_string)
        return ssl.optionsForClientTLS(hostname.decode('utf-8'), cert)
Esempio n. 2
0
def tls_options(hostname, cert_string=None):
    """Get certificate options for TLS connections.

    If we are unable to use TLS because pyOpenSSL is not installed, this will
    raise an exception.

    Args:
        hostname (string): The hostname we are trying to connect to with TLS.
        cert_string (string): A certificate in PEM format. If provided, we
            return CertificateOptions that will trust only the given cert
            (assuming its canonical name attribute matches the given hostname).
            If not provided, we will try to load a suitable certificate for
            this hostname from our store of trusted self-signed certificates,
            and otherwise fall back to just using the trust roots configured
            for the OS to validate the server certificate.

    Returns (twisted.internet.ssl.CertificateOptions):
        Certificate suitable for use by TLS clients to connect to the given

    Raises:
        Exception: could not import pyOpenSSL package needed for TLS.
    """
    if not TLS:
        raise Exception('Unable to connect to labrad with TLS. Please be sure '
                        'to install pyOpenSSL.')
    if cert_string is None:
        cert_string = load_cert(hostname)
    if cert_string is None:
        logging.info('No certificate found for host "{}" in {}. Will use '
                     'system certs to verify tls'.format(hostname, CERTS_PATH))
        return ssl.optionsForClientTLS(hostname.decode('utf-8'))
    else:
        cert = ssl.Certificate.loadPEM(cert_string)
        return ssl.optionsForClientTLS(hostname.decode('utf-8'), cert)
Esempio n. 3
0
 def _get_avatar(self, avatarId, mind):
     endpointstr = self._endpointstr
     basedn = self._basedn
     binddn = self._binddn
     bindpw = self._bindpw
     query = self._query_template % {
         'username': escape_filter_chars(avatarId)
     }
     if self._service_based_attribs:
         if mind:
             service = mind['service']
         else:
             service = ""
         if service == "" or service is None or self.service_manager is None:
             attributes = self._attribs
         else:
             service_entry = yield defer.maybeDeferred(
                 self.service_manager.getMatchingService, service)
             if service_entry and 'attributes' in service_entry:
                 attributes = service_entry['attributes']
             else:
                 attributes = self._attribs
     else:
         attributes = self._attribs
     e = clientFromString(reactor, self._endpointstr)
     client = yield connectProtocol(e, LDAPClient())
     startTls = self._startTls
     startTlsHostName = self._startTlsHostName
     startTlsAuthority = self._startTlsAuthority
     if startTls:
         startTlsArgs = []
         if startTlsHostName is not None:
             if startTlsAuthority is not None:
                 ctx = optionsForClientTLS(unicode(startTlsHostName),
                                           startTlsAuthority)
             else:
                 ctx = optionsForClientTLS(unicode(startTlsHostName),
                                           platformTrust())
             startTlsArgs.append(ctx)
         client = yield client.startTLS(*startTlsArgs)
     yield client.bind(binddn, bindpw)
     o = ldapsyntax.LDAPEntry(client, basedn)
     results = yield o.search(filterText=query,
                              attributes=attributes.keys())
     yield client.unbind()
     if len(results) != 1:
         raise Exception("No unique account found for '%s'." % avatarId)
     entry = results[0]
     _attribs = attributes
     attribs = []
     for key, alias in _attribs.iteritems():
         if key in entry:
             valuelist = entry[key]
             for value in valuelist:
                 attribs.append((alias, value))
     user = User(avatarId, attribs)
     defer.returnValue(user)
Esempio n. 4
0
 def _get_avatar(self, avatarId, mind):
     endpointstr = self._endpointstr
     basedn = self._basedn
     binddn = self._binddn
     bindpw = self._bindpw
     query = self._query_template % {"username": escape_filter_chars(avatarId)}
     if self._service_based_attribs:
         if mind:
             service = mind["service"]
         else:
             service = ""
         if service == "" or service is None or self.service_manager is None:
             attributes = self._attribs
         else:
             service_entry = yield defer.maybeDeferred(self.service_manager.getMatchingService, service)
             if service_entry and "attributes" in service_entry:
                 attributes = service_entry["attributes"]
             else:
                 attributes = self._attribs
     else:
         attributes = self._attribs
     e = clientFromString(reactor, self._endpointstr)
     client = yield connectProtocol(e, LDAPClient())
     startTls = self._startTls
     startTlsHostName = self._startTlsHostName
     startTlsAuthority = self._startTlsAuthority
     if startTls:
         startTlsArgs = []
         if startTlsHostName is not None:
             if startTlsAuthority is not None:
                 ctx = optionsForClientTLS(unicode(startTlsHostName), startTlsAuthority)
             else:
                 ctx = optionsForClientTLS(unicode(startTlsHostName), platformTrust())
             startTlsArgs.append(ctx)
         client = yield client.startTLS(*startTlsArgs)
     yield client.bind(binddn, bindpw)
     o = ldapsyntax.LDAPEntry(client, basedn)
     results = yield o.search(filterText=query, attributes=attributes.keys())
     yield client.unbind()
     if len(results) != 1:
         raise Exception("No unique account found for '%s'." % avatarId)
     entry = results[0]
     _attribs = attributes
     attribs = []
     for key, alias in _attribs.iteritems():
         if key in entry:
             valuelist = entry[key]
             for value in valuelist:
                 attribs.append((alias, value))
     user = User(avatarId, attribs)
     defer.returnValue(user)
Esempio n. 5
0
 def creatorForNetloc(self, hostname: bytes,
                      port: int) -> IOpenSSLClientConnectionCreator:
     return optionsForClientTLS(
         hostname.decode("ascii"),
         trustRoot=self.sydent.sslComponents.trustRoot,
         clientCertificate=self.sydent.sslComponents.myPrivateCertificate,
     )
Esempio n. 6
0
    def connect(self, host=None, port=None, cert=None, key=None):
        '''
        Connect to another portal somewhere. If retry is set, will attempt to reconnect
        with the target continuously. As of the time of this writing, you cannot stop a 
        polling connection without taking down the portal.

        :param retry: continuously attempt to connect on drops or rejections
        :type retry: bool.
        '''

        host = host if host else self.host
        port = port if port else self.port
        cert = cert if cert else self.certCa
        key = key if key else self.keyPrivate  # ???

        # the first term is the name the server is using in the cert (for now)
        ctx = optionsForClientTLS(u"pds.production", Certificate.loadPEM(cert), PrivateCertificate.loadPEM(key))

        factory = RiffleClientFactory()
        SSL4ClientEndpoint(reactor, host, port, ctx,).connect(factory)

        print 'Connecting to ' + host + ':' + str(port)
        avatar = yield factory.login(self)

        defer.returnValue(Levy(avatar))
Esempio n. 7
0
def main(reactor, args):
    kwds = {}
    caCertData = args.ca_cert.read()
    client_cert = args.client_cert
    if client_cert is not None:
        clientData = args.client_cert.read()
        clientCertificate = ssl.PrivateCertificate.loadPEM(clientData)
        kwds['clientCertificate'] = clientCertificate 
    authority = ssl.Certificate.loadPEM(caCertData)

    host = args.host
    port = args.port
    netloc = "%s:%d" % (host, port)
    
    if args.ssl_method is not None:
        if args.ssl_method == 'ssl3':
            extraCertificateOptions = {'method': SSL.SSLv3_METHOD}
        elif args.ssl_method == 'tls1':
            extraCertificateOptions = {'method': SSL.TLSv1_METHOD}
        elif args.ssl_method == 'tls1_1':
            extraCertificateOptions = {'method': SSL.TLSv1_1_METHOD}
        elif args.ssl_method == 'tls1_2':
            extraCertificateOptions = {'method': SSL.TLSv1_2_METHOD}
        kwds['extraCertificateOptions'] = extraCertificateOptions
    
    options = ssl.optionsForClientTLS( unicode(host), authority, **kwds)
    #options = CustomClientConnectionCreator(ssl_opts, options) 
    s = yield getPage("https://%s/login" % netloc, contextFactory=options)
    print s
Esempio n. 8
0
    def endpointForURI(self, uri):
        if uri.scheme in (b"http", b"https", b"ws", b"wss"):
            defaultport = 443 if uri.scheme in (b"https", b"wss") else 80
            host, port = BaseUrl.parsenetloc(uri.netloc, defaultport)
            endpoint = t_endpoints.HostnameEndpoint(self.reactor, host, port)

            if defaultport == 443:
                ssl_supported = hasattr(t_endpoints, "TLSWrapperClientEndpoint")

                try:
                    from twisted.internet.ssl import optionsForClientTLS
                except ImportError:
                    ssl_supported = False

                if not ssl_supported:
                    raise t_error.SchemeNotSupported(
                        "{} not supported (OpenSSL is not available)".format(uri.scheme.decode("utf_8"))
                    )

                options = optionsForClientTLS(host.decode("utf_8"))
                endpoint = t_endpoints.TLSWrapperClientEndpoint(options, endpoint)

            return endpoint

        if uri.scheme == b"unix":
            path = url_parse.unquote(uri.netloc.decode("ascii"))
            uri.netloc = b"localhost"

            return t_endpoints.UNIXClientEndpoint(self.reactor, path)

        raise t_error.SchemeNotSupported("{} not supported (unrecognized)".format(uri.scheme.decode("utf_8")))
Esempio n. 9
0
    def setUp(self):
        # Initialize resource tree
        root = self._init_resource()
        self.site = Site(root, timeout=None)

        # Start server for testing
        self.hostname = 'localhost'
        context_factory = ssl_context_factory(self.key_file, self.certificate_file)

        server_endpoint = SSL4ServerEndpoint(reactor, 0, context_factory, interface=self.hostname)
        self.server = yield server_endpoint.listen(self.site)
        self.port_number = self.server.getHost().port

        # Connect H2 client with server
        self.client_certificate = get_client_certificate(self.key_file, self.certificate_file)
        client_options = optionsForClientTLS(
            hostname=self.hostname,
            trustRoot=self.client_certificate,
            acceptableProtocols=[b'h2']
        )
        uri = URI.fromBytes(bytes(self.get_url('/'), 'utf-8'))

        self.conn_closed_deferred = Deferred()
        from scrapy.core.http2.protocol import H2ClientFactory
        h2_client_factory = H2ClientFactory(uri, Settings(), self.conn_closed_deferred)
        client_endpoint = SSL4ClientEndpoint(reactor, self.hostname, self.port_number, client_options)
        self.client = yield client_endpoint.connect(h2_client_factory)
Esempio n. 10
0
        def setupService(self):
            """
            Setup the application component.
            """
            is_secure, host, port, resource, path, params = parse_ws_url(self.url)

            # factory for use ApplicationSession
            def create():
                cfg = ComponentConfig(self.realm, self.extra)
                session = self.make(cfg)
                return session

            # create a WAMP-over-WebSocket transport client factory
            transport_factory = self.factory(create, url=self.url)

            # setup the client from a Twisted endpoint

            if is_secure:
                from twisted.application.internet import SSLClient
                ctx = self.context_factory
                if ctx is None:
                    from twisted.internet.ssl import optionsForClientTLS
                    ctx = optionsForClientTLS(host)
                client = SSLClient(host, port, transport_factory, contextFactory=ctx)
            else:
                if self.context_factory is not None:
                    raise Exception("context_factory specified on non-secure URI")
                from twisted.application.internet import TCPClient
                client = TCPClient(host, port, transport_factory)

            client.setServiceParent(self)
    def getMapUpdaterComponentService(self, url, realm, mapUpdater):
        def create(config):
            try:
                session = MapUpdaterComponent(mapUpdater, config)
            except Exception as e:
                # the app component could not be created .. fatal
                print(e)
            else:
                session.debug_app = True
                return session

        sessionFactory = ApplicationSessionFactory(
            ComponentConfig(realm, None))
        sessionFactory.session = create

        transportFactory = WampWebSocketClientFactory(
            sessionFactory, url=url)
        transportFactory.noisy = False
        transportFactory.autoPingInterval = 30
        transportFactory.autoPingTimeout = 30

        isSecure, host, port, resource, path, params = parseWsUrl(url)

        endpoint = HostnameEndpoint(reactor, host.encode('utf8'), port)
        if isSecure:
            contextFactory = optionsForClientTLS(hostname=host)
            endpoint = wrapClientTLS(contextFactory, endpoint)
        return ClientService(endpoint, transportFactory)
Esempio n. 12
0
    def _get_new(self):
        """
        Get new mails from IMAP server. This will define the `main loop` of
        the IMAP service.
        """
        onConn = defer.Deferred().addCallback(
            self.cb_server_greeting
        ).addErrback(
            self.eb_server_greeting
        )

        # Connect with endpoints. Connect and disconnect from time to time
        # (defined by the service's interval) instead of establishing a
        # persistent connection
        factory = SimpleIMAP4ClientFactory(self.username, onConn)

        from twisted.internet import reactor
        endpoint = endpoints.HostnameEndpoint(reactor, self.host, self.port)

        contextFactory = ssl.optionsForClientTLS(
            hostname=self.host.decode('utf-8')
        )
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

        log.debug("IMAP:: Connecting to Google's IMAP servers.")
        endpoint.connect(factory)
Esempio n. 13
0
    def connect(self):
        """Connect and authenticate with the IMAP server
        """
        if self.connecting:
            defer.returnValue(None)

        self.connecting = True

        endpoint = endpoints.HostnameEndpoint(reactor, self.host, self.port)

        if self.ssl:
            contextFactory = ssl.optionsForClientTLS(
                hostname=self.host.decode('utf-8'))
            endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

        de = defer.Deferred()
        factory = IMAP4ClientFactory(self.user, de)
        factory.debug = self.debug

        yield endpoint.connect(factory)
        self.proto = yield de

        yield self.proto.authenticate(self.password)

        self.connected = True
        self.connecting = False
Esempio n. 14
0
def func_connect(bot):
    if reactor._started:
        bot.say('[RatTracker] Reactor already running!')
        return
    bot.say('[RatTracker] Gotcha, connecting to RatTracker!')
    MyClientProtocol.bot = bot
    MyClientProtocol.debug_channel = bot.config.ratbot.debug_channel
    MyClientProtocol.board = bot.memory['ratbot']['board']
    factory = MyClientFactory(str(bot.config.socket.websocketurl) + ':' + bot.config.socket.websocketport + '?bearer=' + str(MyClientProtocol.bot.config.ratbot.apitoken))

    factory.protocol = MyClientProtocol
    # print('in connect')
    hostname = str(bot.config.socket.websocketurl).replace("ws://", '').replace("wss://", '')
    print('[Websocket] Hostname: ' + hostname)
    if (bot.config.socket.websocketurl.startswith('wss://')):

        reactor.connectSSL(hostname,
                           int(bot.config.socket.websocketport),
                           factory, contextFactory=optionsForClientTLS(hostname=hostname))
    else:

        reactor.connectTCP(hostname,
                           int(bot.config.socket.websocketport),
                           factory)

    # print('pls')
    thread = Thread(target=reactor.run, kwargs={'installSignalHandlers': 0})

    thread.start()
Esempio n. 15
0
def main():
    hostname = raw_input('IMAP4 Server Hostname: ')
    port = raw_input('IMAP4 Server Port (the default is 143, 993 uses SSL): ')
    username = raw_input('IMAP4 Username: '******'IMAP4 Password: '******'utf-8'))
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

    endpoint.connect(factory)
    reactor.run()
Esempio n. 16
0
    def creatorForNetloc(self, hostname, port):
        """
        Pick from amongst client certs and ca certs to create a proper TLS context
        factory.

        :see: ``twisted.web.iweb.IPolicyForHTTPS``
        """
        hostname = hostname.decode("ascii")

        netloc = NetLocation(host=hostname, port=port)
        client_cert, extra_cert_chain = pick_cert_for_twisted(
            netloc,
            self.credentials,
        )
        trust_root = pick_trust_for_twisted(netloc, self.trust_roots)

        return ssl.optionsForClientTLS(
            # It is not necessarily the case that the certificate presented
            # will use this name but it is common to encounter self-signed
            # certificates which do use this name.  There doesn't seem to be
            # anything in the configuration file which would tell us what the
            # proper name is.  We'll probably need to make this configurable
            # at some point, I guess.
            u"kubernetes",
            clientCertificate=client_cert,
            trustRoot=trust_root,
            extraCertificateOptions=dict(
                # optionsForClientTLS gets mad if extraCertChain is () and
                # client_cert is None even though `()` clearly represents no
                # extra certificate chain.  It wants them to both be None.
                # Make it so.
                extraCertChain=tuple(cert.original
                                     for cert in extra_cert_chain) or None, ),
        )
Esempio n. 17
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
Esempio n. 18
0
    def callRemote(self, method, *args):
        """
        Call remote XML-RPC C{method} with given arguments.

        @return: a L{defer.Deferred} that will fire with the method response,
            or a failure if the method failed. Generally, the failure type will
            be L{Fault}, but you can also have an C{IndexError} on some buggy
            servers giving empty responses.

            If the deferred is cancelled before the request completes, the
            connection is closed and the deferred will fire with a
            L{defer.CancelledError}.
        """
        def cancel(d):
            factory.deferred = None
            connector.disconnect()
        factory = self.queryFactory(
            self.path, self.host, method, self.user,
            self.password, self.allowNone, args, cancel, self.useDateTime)

        if self.secure:
            from twisted.internet import ssl
            contextFactory = ssl.optionsForClientTLS(
                hostname=nativeString(self.host))
            connector = self._reactor.connectSSL(
                nativeString(self.host), self.port or 443,
                factory, contextFactory,
                timeout=self.connectTimeout)
        else:
            connector = self._reactor.connectTCP(
                nativeString(self.host), self.port or 80, factory,
                timeout=self.connectTimeout)
        return factory.deferred
Esempio n. 19
0
    def startConnecting(
            self):  # calling this startFactory yields recursion problems
        self.started = True

        if settings['DESTINATION_TRANSPORT'] == "ssl":
            if not SSL or not ssl:
                print(
                    "SSL destination transport request, but no Python OpenSSL available."
                )
                raise SystemExit(1)
            authority = None
            if settings['DESTINATION_SSL_CA']:
                try:
                    with open(settings['DESTINATION_SSL_CA']) as f:
                        authority = ssl.Certificate.loadPEM(f.read())
                except IOError:
                    print("Failed to read CA chain: %s" %
                          settings['DESTINATION_SSL_CA'])
                    raise SystemExit(1)
            # Twisted 14 introduced this function, it might not be around on older installs.
            if hasattr(ssl, "optionsForClientTLS"):
                from six import u
                client = ssl.optionsForClientTLS(u(self.host), authority)
            else:
                client = CAReplaceClientContextFactory(
                    settings['DESTINATION_SSL_CA'])
            self.connector = reactor.connectSSL(self.host, self.port, self,
                                                client)
        else:
            self.connector = reactor.connectTCP(self.host, self.port, self)
Esempio n. 20
0
def main():
    hostname = raw_input("IMAP4 Server Hostname: ")
    port = raw_input("IMAP4 Server Port (the default is 143, 993 uses SSL): ")

    # Usernames are bytes.
    username = raw_input("IMAP4 Username: "******"ascii")

    # Passwords are bytes.
    password = util.getPassword("IMAP4 Password: "******"ascii")

    onConn = (defer.Deferred().addCallback(
        cbServerGreeting, username,
        password).addErrback(ebConnection).addBoth(cbClose))

    factory = SimpleIMAP4ClientFactory(username, onConn)

    if not port:
        port = 143
    else:
        port = int(port)

    from twisted.internet import reactor

    endpoint = endpoints.HostnameEndpoint(reactor, hostname, port)

    if port == 993:
        if isinstance(hostname, bytes):
            # This is python 2
            hostname = hostname.decode("utf-8")

        contextFactory = ssl.optionsForClientTLS(hostname=hostname, )
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

    endpoint.connect(factory)
    reactor.run()
Esempio n. 21
0
def main(reactor, args):
    kwds = {}
    caCertData = args.ca_cert.read()
    client_cert = args.client_cert
    if client_cert is not None:
        clientData = args.client_cert.read()
        clientCertificate = ssl.PrivateCertificate.loadPEM(clientData)
        kwds['clientCertificate'] = clientCertificate
    authority = ssl.Certificate.loadPEM(caCertData)

    host = args.host
    port = args.port
    netloc = "%s:%d" % (host, port)

    if args.ssl_method is not None:
        if args.ssl_method == 'ssl3':
            extraCertificateOptions = {'method': SSL.SSLv3_METHOD}
        elif args.ssl_method == 'tls1':
            extraCertificateOptions = {'method': SSL.TLSv1_METHOD}
        elif args.ssl_method == 'tls1_1':
            extraCertificateOptions = {'method': SSL.TLSv1_1_METHOD}
        elif args.ssl_method == 'tls1_2':
            extraCertificateOptions = {'method': SSL.TLSv1_2_METHOD}
        kwds['extraCertificateOptions'] = extraCertificateOptions

    options = ssl.optionsForClientTLS(unicode(host), authority, **kwds)
    #options = CustomClientConnectionCreator(ssl_opts, options)
    s = yield getPage("https://%s/login" % netloc, contextFactory=options)
    print s
Esempio n. 22
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()
Esempio n. 23
0
    def download(self, url, fakeoutfile, outputfile, *args, **kwargs):
        try:
            parsed = compat.urllib_parse.urlparse(url)
            scheme = parsed.scheme
            host = parsed.hostname.decode('utf8')
            port = parsed.port or (443 if scheme == 'https' else 80)
            if scheme != b'http' and scheme != b'https':
                raise NotImplementedError
        except Exception:
            self.errorWrite(
                'curl: (1) Protocol "{}" not supported or disabled in libcurl\n'
                .format(scheme))
            self.exit()
            return None

        factory = HTTPProgressDownloader(self, fakeoutfile, url, outputfile,
                                         *args, **kwargs)
        out_addr = None
        if CowrieConfig().has_option('honeypot', 'out_addr'):
            out_addr = (CowrieConfig().get('honeypot', 'out_addr'), 0)

        if scheme == 'https':
            context_factory = ssl.optionsForClientTLS(hostname=host)
            self.connection = reactor.connectSSL(host,
                                                 port,
                                                 factory,
                                                 context_factory,
                                                 bindAddress=out_addr)
        else:  # Can only be http
            self.connection = reactor.connectTCP(host,
                                                 port,
                                                 factory,
                                                 bindAddress=out_addr)

        return factory.deferred
Esempio n. 24
0
def func_connect(bot):
    if reactor._started:
        bot.say('[RatTracker] Reactor already running!')
        return
    bot.say('[RatTracker] Gotcha, connecting to RatTracker!')
    MyClientProtocol.bot = bot
    MyClientProtocol.debug_channel = bot.config.ratbot.debug_channel
    MyClientProtocol.board = bot.memory['ratbot']['board']
    factory = MyClientFactory(str(bot.config.socket.websocketurl) + ':' + bot.config.socket.websocketport)

    factory.protocol = MyClientProtocol
    # print('in connect')
    hostname = str(bot.config.socket.websocketurl).replace("ws://", '').replace("wss://", '')
    print('[Websocket] Hostname: ' + hostname)
    if (bot.config.socket.websocketurl.startswith('wss://')):

        reactor.connectSSL(hostname,
                           int(bot.config.socket.websocketport),
                           factory, contextFactory=optionsForClientTLS(hostname=hostname))
    else:

        reactor.connectTCP(hostname,
                           int(bot.config.socket.websocketport),
                           factory)

    # print('pls')
    thread = Thread(target=reactor.run, kwargs={'installSignalHandlers': 0})

    thread.start()
Esempio n. 25
0
    def connect(self, factory):
        # further wrap the protocol if we're doing TLS.
        # "pray i do not wrap the protocol further".
        if self._tls:
            # XXX requires Twisted 14+
            from twisted.internet.ssl import optionsForClientTLS
            if self._tls is True:
                context = optionsForClientTLS(self._host)
            else:
                context = self._tls
            tls_factory = tls.TLSMemoryBIOFactory(context, True, factory)
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', tls_factory,
            )
        else:
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', factory,
            )

        self._socks_factory = socks_factory
        # forward our address (when we get it) to any listeners
        self._socks_factory._get_address().addBoth(self._when_address.fire)
        # XXX isn't this just maybeDeferred()
        if isinstance(self._proxy_ep, Deferred):
            proxy_ep = yield self._proxy_ep
        else:
            proxy_ep = self._proxy_ep

        # socks_proto = yield proxy_ep.connect(socks_factory)
        proto = yield proxy_ep.connect(socks_factory)
        wrapped_proto = yield proto.when_done()
        if self._tls:
            returnValue(wrapped_proto.wrappedProtocol)
        else:
            returnValue(wrapped_proto)
Esempio n. 26
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()
Esempio n. 27
0
        def setupService(self):
            """
            Setup the application component.
            """
            is_secure, host, port, resource, path, params = parse_ws_url(self.url)

            # factory for use ApplicationSession
            def create():
                cfg = ComponentConfig(self.realm, self.extra)
                session = self.make(cfg)
                return session

            # create a WAMP-over-WebSocket transport client factory
            transport_factory = self.factory(create, url=self.url)

            # setup the client from a Twisted endpoint

            if is_secure:
                from twisted.application.internet import SSLClient
                ctx = self.context_factory
                if ctx is None:
                    from twisted.internet.ssl import optionsForClientTLS
                    ctx = optionsForClientTLS(host)
                client = SSLClient(host, port, transport_factory, contextFactory=ctx)
            else:
                if self.context_factory is not None:
                    raise Exception("context_factory specified on non-secure URI")
                from twisted.application.internet import TCPClient
                client = TCPClient(host, port, transport_factory)

            client.setServiceParent(self)
Esempio n. 28
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()
Esempio n. 29
0
    def download(self, url, fakeoutfile, outputfile, *args, **kwargs):
        scheme: bytes
        try:
            parsed = compat.urllib_parse.urlparse(url)
            scheme = parsed.scheme
            host: str = parsed.hostname.decode("utf8")
            port: int = parsed.port or (443 if scheme == "https" else 80)
            if scheme != b"http" and scheme != b"https":
                raise NotImplementedError
        except Exception:
            self.errorWrite(
                f'curl: (1) Protocol "{scheme.encode("utf8")}" not supported or disabled in libcurl\n'
            )
            self.exit()
            return None

        factory = HTTPProgressDownloader(
            self, fakeoutfile, url, outputfile, *args, **kwargs
        )
        out_addr = None
        if CowrieConfig.has_option("honeypot", "out_addr"):
            out_addr = (CowrieConfig.get("honeypot", "out_addr"), 0)

        if scheme == "https":
            context_factory = ssl.optionsForClientTLS(hostname=host)
            self.connection = reactor.connectSSL(
                host, port, factory, context_factory, bindAddress=out_addr
            )
        else:  # Can only be http
            self.connection = reactor.connectTCP(
                host, port, factory, bindAddress=out_addr
            )

        return factory.deferred
Esempio n. 30
0
    def connect(self, factory):
        # further wrap the protocol if we're doing TLS.
        # "pray i do not wrap the protocol further".
        if self._tls:
            # XXX requires Twisted 14+
            from twisted.internet.ssl import optionsForClientTLS
            context = optionsForClientTLS(self._host)
            tls_factory = tls.TLSMemoryBIOFactory(context, True, factory)
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', tls_factory,
            )
        else:
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', factory,
            )

        self._socks_factory = socks_factory
        # forward our address (when we get it) to any listeners
        self._socks_factory._get_address().addBoth(self._when_address.fire)
        # XXX isn't this just maybeDeferred()
        if isinstance(self._proxy_ep, Deferred):
            proxy_ep = yield self._proxy_ep
        else:
            proxy_ep = self._proxy_ep

        # socks_proto = yield proxy_ep.connect(socks_factory)
        proto = yield proxy_ep.connect(socks_factory)
        wrapped_proto = yield proto.when_done()
        if self._tls:
            returnValue(wrapped_proto.wrappedProtocol)
        else:
            returnValue(wrapped_proto)
Esempio n. 31
0
 def load_starttls_trust_anchor(self, pem_path):
     """
     Load the startTLS trust anchor from a file in PEM format.
     """
     log = self.log
     if not self.use_starttls:
         return
     if pem_path is None:
         return
     starttls_hostname = six.u(self.starttls_hostname)
     log.debug("type: {type}, value: {value}",
               type=type(starttls_hostname),
               value=starttls_hostname)
     assert starttls_hostname is not None, "Must set option `starttls_hostname` when using `starttls_trust_anchor`."
     log.debug("Reading PEM file {pem_path}.", pem_path=pem_path)
     #with open(pem_path, "r") as f:
     #    data = f.read()
     #authority = ssl.Certificate.loadPEM(data)
     certs = pem.parse_file(pem_path)
     log.debug("Length `certs`: {len}", len=len(certs))
     for c in certs:
         log.debug("Cert: {cert}", cert=str(c))
     authority = ssl.Certificate.loadPEM('\n'.join(
         str(cert) for cert in certs))
     log.debug("StartTLS authority: {authority}",
               authority=authority.inspect())
     log.debug("StartTLS hostname: '{hostname}'",
               hostname=starttls_hostname)
     self.starttls_trust_anchor = ssl.optionsForClientTLS(
         starttls_hostname, authority)
Esempio n. 32
0
def _ssl_context_factory(parameters):
    """
    Produce a Twisted SSL context object from a pika connection parameter object.
    This is necessary as Twisted manages the connection, not Pika.

    Args:
        parameters (pika.ConnectionParameters): The connection parameters built
            from the fedora_messaging configuration.
    """
    client_cert = None
    key = config.conf["tls"]["keyfile"]
    cert = config.conf["tls"]["certfile"]
    with open(config.conf["tls"]["ca_cert"]) as fd:
        ca_cert = ssl.Certificate.loadPEM(fd.read())
    if key and cert:
        # Note that _configure_tls_parameters sets the auth mode to EXTERNAL
        # if both key and cert are defined, so we don't need to do that here.
        with open(key) as fd:
            client_keypair = fd.read()
        with open(cert) as fd:
            client_keypair += fd.read()
        client_cert = ssl.PrivateCertificate.loadPEM(client_keypair)

    context_factory = ssl.optionsForClientTLS(
        parameters.host,
        trustRoot=ca_cert,
        clientCertificate=client_cert,
        extraCertificateOptions={"raiseMinimumTo": ssl.TLSVersion.TLSv1_2},
    )

    return context_factory
 def create_ssl_context(self, host, ssl_certificate):
   #ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
   #ssl_context.load_verify_locations(cafile = ssl_certificate)
   #ssl_context.verify_mode = ssl.CERT_REQUIRED
   
   certData = FilePath(ssl_certificate).getContent()
   authority = ssl.Certificate.loadPEM(certData)
   options = ssl.optionsForClientTLS(host, authority)
   return options
Esempio n. 34
0
def createConnection(streamName, port, exchange):  # Create a Twisted factory
    log.startLogging(sys.stdout)
    hostName = urlparse(streamName).hostname
    factory = Connect(streamName)
    factory.setProtocolOptions(autoPingInterval=60)
    factory.setProtocolOptions(openHandshakeTimeout=60)
    factory.protocol = exchange
    reactor.connectSSL(hostName, port, factory,
                       ssl.optionsForClientTLS(hostName))
Esempio n. 35
0
 def _connect_tls(self, websocket_location, shared_seed):
     ws_url = str(websocket_location)
     factory = WebSocketClientFactory(ws_url)
     factory.protocol = OutgoingSocket
     factory.ms_protocol_layer = self
     factory.ms_shared_seed = shared_seed
     options = ssl.optionsForClientTLS(hostname=websocket_location.host)
     c = connectWS(factory, options)
     return WebsocketConnectionAttempt(c)
Esempio n. 36
0
def _ssl_context_factory(parameters):
    """
    Produce a Twisted SSL context object from a pika connection parameter object.
    This is necessary as Twisted manages the connection, not Pika.

    Args:
        parameters (pika.ConnectionParameters): The connection parameters built
            from the fedora_messaging configuration.
    """
    client_cert = None
    ca_cert = None
    key = config.conf["tls"]["keyfile"]
    cert = config.conf["tls"]["certfile"]
    ca_file = config.conf["tls"]["ca_cert"]
    if ca_file:
        with open(ca_file, "rb") as fd:
            # Open it in binary mode since otherwise Twisted will immediately
            # re-encode it as ASCII, which won't work if the cert bundle has
            # comments that can't be encoded with ASCII.
            ca_cert = twisted_ssl.Certificate.loadPEM(fd.read())
    if key and cert:
        # Note that _configure_tls_parameters sets the auth mode to EXTERNAL
        # if both key and cert are defined, so we don't need to do that here.
        with open(key) as fd:
            client_keypair = fd.read()
        with open(cert) as fd:
            client_keypair += fd.read()
        client_cert = twisted_ssl.PrivateCertificate.loadPEM(client_keypair)

    hostname = parameters.host
    if not isinstance(hostname, six.text_type):
        # Twisted requires the hostname as decoded text, which it isn't in Python 2
        # Decode with the system encoding since this came from the config file. Die,
        # Python 2, die.
        hostname = hostname.decode(locale.getdefaultlocale()[1])
    try:
        context_factory = twisted_ssl.optionsForClientTLS(
            hostname,
            trustRoot=ca_cert or twisted_ssl.platformTrust(),
            clientCertificate=client_cert,
            extraCertificateOptions={
                "raiseMinimumTo": twisted_ssl.TLSVersion.TLSv1_2
            },
        )
    except AttributeError:
        # Twisted 12.2 path for EL7 :(
        context_factory = twisted_ssl.CertificateOptions(
            certificate=client_cert.original,
            privateKey=client_cert.privateKey.original,
            caCerts=[ca_cert.original] or twisted_ssl.platformTrust(),
            verify=True,
            requireCertificate=True,
            verifyOnce=False,
            enableSessions=False,
        )

    return context_factory
Esempio n. 37
0
 def getClientTLSOptions(self, hostname):
     if (not self.verify):
         log.msg(
             'httpClient ignores verify=false, WILL verify certificate chain for %s against certdir'
             % (hostname),
             system=LOG_SYSTEM)
     return ssl.optionsForClientTLS(
         hostname,
         trustRoot=self._trustRoot,
         extraCertificateOptions=self._extraCertificateOptions)
Esempio n. 38
0
def main(reactor):
    pem = generate_certs.and_generate()
    caPem = FilePath(b"ca-private-cert.pem").getContent()
    clientEndpoint = SSL4ClientEndpoint(
        reactor,
        u"localhost",
        4321,
        optionsForClientTLS(u"the-authority", Certificate.loadPEM(caPem),
                            PrivateCertificate.loadPEM(pem)),
    )
    clientEndpoint = SSL4ClientEndpoint(
        reactor,
        u"localhost",
        4321,
        optionsForClientTLS(u"the-authority", Certificate.loadPEM(caPem),
                            PrivateCertificate.loadPEM(pem)),
    )
    proto = yield clientEndpoint.connect(Factory.forProtocol(SendAnyData))
    yield proto.deferred
Esempio n. 39
0
 def creatorForNetloc(self, hostname, port):
     # trustRoot set to platformTrust() will use the platform's root CAs.
     #
     # This means that a website like https://www.cacert.org will be rejected
     # by default, since CAcert.org CA certificate is seldom shipped.
     return optionsForClientTLS(
         hostname=hostname.decode("ascii"),
         trustRoot=platformTrust(),
         extraCertificateOptions={'method': self._ssl_method},
     )
Esempio n. 40
0
        def creatorForNetloc(self, hostname, port):

            # trustRoot set to platformTrust() will use the platform's root CAs.
            #
            # This means that a website like https://www.cacert.org will be rejected
            # by default, since CAcert.org CA certificate is seldom shipped.
            return optionsForClientTLS(hostname.decode("ascii"),
                                       trustRoot=platformTrust(),
                                       extraCertificateOptions={
                                            'method': self._ssl_method,
                                       })
Esempio n. 41
0
def main(reactor):
    factory = protocol.Factory.forProtocol(StartTLSClient)
    certData = getModule(__name__).filePath.sibling("server.pem").getContent()
    factory.options = ssl.optionsForClientTLS(
        "example.com", ssl.PrivateCertificate.loadPEM(certData))
    endpoint = endpoints.HostnameEndpoint(reactor, "localhost", 8000)
    startTLSClient = yield endpoint.connect(factory)

    done = defer.Deferred()
    startTLSClient.connectionLost = lambda reason: done.callback(None)
    yield done
    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 = certificate.get_truststore_as_list_of_strings(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_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)
Esempio n. 43
0
 def _make_connect(self, credentials):
     basedn = self._basedn
     e = clientFromString(reactor, self._endpointstr)
     client = yield connectProtocol(e, LDAPClient())
     startTls = self._startTls
     startTlsHostName = self._startTlsHostName
     startTlsAuthority = self._startTlsAuthority
     if startTls:
         startTlsArgs = []
         if startTlsHostName is not None:
             if startTlsAuthority is not None:
                 ctx = optionsForClientTLS(unicode(startTlsHostName), startTlsAuthority)
             else:
                 ctx = optionsForClientTLS(unicode(startTlsHostName), platformTrust())
             startTlsArgs.append(ctx)
         client = yield client.startTLS(*startTlsArgs)
     dn = yield self._get_dn(client, credentials.username)
     yield client.bind(dn, credentials.password)
     yield client.unbind()
     defer.returnValue(credentials.username)
Esempio n. 44
0
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    ircEndpoint = SOCKS5ClientEndpoint('CHANGE_THIS', 6697, torEndpoint)
    host = 'CHANGE_THIS'
    options_ = optionsForClientTLS(hostname=host.decode('\
utf-8'), trustRoot=ssl.Certificate.loadPEM(FilePath('\
CHANGE_THIS').getContent()), clientCertificate=None)
    tlsEndpoint = TLSWrapClientEndpoint(options_, ircEndpoint)
    d = tlsEndpoint.connect(SpewingFactory(TorIRCFactory()))
    d.addCallback(lambda proto: proto.wrappedProtocol.deferred)
    return d
Esempio n. 45
0
    def creatorForNetloc(self, hostname, port):
        """
        Create a client connection creator for a given network location.

        @param hostname: The hostname part of the URI.
        @type  hostname: L{bytes}
        @param port:     The port part of the URI.
        @type  port:     L{int}
        """
        return optionsForClientTLS(hostname.decode("ascii"),
                                   trustRoot = self._trustRoot,
                                   extraCertificateOptions = self._opts)
def main(reactor):
    factory = protocol.Factory.forProtocol(EchoClient)
    certData = getModule(__name__).filePath.sibling('public.pem').getContent()
    authority = ssl.Certificate.loadPEM(certData)
    options = ssl.optionsForClientTLS(u'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
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)
def main(reactor):
    factory = protocol.Factory.forProtocol(StartTLSClient)
    certData = getModule(__name__).filePath.sibling('server.pem').getContent()
    factory.options = ssl.optionsForClientTLS(
        u"example.com", ssl.PrivateCertificate.loadPEM(certData)
    )
    endpoint = endpoints.HostnameEndpoint(reactor, 'localhost', 8000)
    startTLSClient = yield endpoint.connect(factory)

    done = defer.Deferred()
    startTLSClient.connectionLost = lambda reason: done.callback(None)
    yield done
Esempio n. 49
0
    def dataReceived(self, data):
        print("@@S dataReceived ", data)
        self.data = data
        ConsoleWriter().write(self.data, "request")
        client = protocol.ClientCreator(reactor, DebugHttpClientProtocol, self.transport)

        # 証明書とか自分で取ってこないとダメ?
        certData = getModule(__name__).filePath.sibling('public.pem').getContent()
        authority = ssl.Certificate.loadPEM(certData)
        print(authority)
        options = ssl.optionsForClientTLS(u'google.com', authority)
        d = client.connectSSL(self.factory.targetHost, self.factory.targetPort, options)
        d.addCallback(self.forwardToClient, client)
def run(messagehandler): 

    options = optionsForClientTLS(
        hostname=AUTHORITY,
        acceptableProtocols=[b'h2', b'http/1.1'],
    )

    connectProtocol(
        SSL4ClientEndpoint(reactor, AUTHORITY, 443, options),
        H2Protocol(messagehandler)
    )

    reactor.run(installSignalHandlers=0)
def main(reactor):
    factory = protocol.Factory.forProtocol(other_proto.DecisionProtocol)
    ca_data = FilePath(b'ca_cert.pem').getContent()
    client_data = FilePath(b'a.client.pem').getContent()
    ca_cert = ssl.Certificate.loadPEM(ca_data)
    client_key = ssl.PrivateCertificate.loadPEM(client_data)
    options = ssl.optionsForClientTLS(u'the-authority', ca_cert, client_key)
    exampleEndpoint = txtorcon.TorClientEndpoint(ip, 8966, socks_hostname="127.0.0.1")
    tlsEndpoint = TLSWrapClientEndpoint(options, exampleEndpoint)
    deferred = yield tlsEndpoint.connect(factory)
    done = defer.Deferred()
    deferred.connectionLost = lambda reason: done.callback(None)
    yield done
Esempio n. 52
0
def _create_tls_client_context(config, cbdir, log):
    """
    Create a CertificateOptions object for use with TLS listening endpoints.
    """
    # server hostname: The expected name of the remote host.
    hostname = config['hostname']

    # explicit trust (certificate) root
    ca_certs = None
    if 'ca_certificates' in config:
        log.info("TLS client using explicit trust ({cnt_certs} certificates)", cnt_certs=len(config['ca_certificates']))
        ca_certs = []
        for cert_fname in [os.path.abspath(os.path.join(cbdir, x)) for x in (config['ca_certificates'])]:
            cert = crypto.load_certificate(
                crypto.FILETYPE_PEM,
                six.u(open(cert_fname, 'r').read())
            )
            log.info("TLS client trust root CA certificate loaded from '{fname}'", fname=cert_fname)
            ca_certs.append(cert)
        ca_certs = OpenSSLCertificateAuthorities(ca_certs)
    else:
        log.info("TLS client using platform trust")

    # client key/cert to use
    client_cert = None
    if 'key' in config:
        if 'certificate' not in config:
            raise Exception('TLS client key present, but certificate missing')

        key_fname = os.path.abspath(os.path.join(cbdir, config['key']))
        with open(key_fname, 'r') as f:
            private_key = KeyPair.load(f.read(), format=crypto.FILETYPE_PEM)
            log.info("Loaded client TLS key from '{key_fname}'", key_fname=key_fname)

        cert_fname = os.path.abspath(os.path.join(cbdir, config['certificate']))
        with open(cert_fname, 'r') as f:
            cert = Certificate.loadPEM(f.read(),)
            log.info("Loaded client TLS certificate from '{cert_fname}' (cn='{cert_cn}', sha256={cert_sha256}..)",
                     cert_fname=cert_fname,
                     cert_cn=cert.getSubject().CN,
                     cert_sha256=cert.digest('sha256')[:12])

        client_cert = PrivateCertificate.fromCertificateAndKeyPair(cert, private_key)
    else:
        if 'certificate' in config:
            log.warn('TLS client certificate present, but key is missing')

    # create TLS client context
    ctx = optionsForClientTLS(hostname, trustRoot=ca_certs, clientCertificate=client_cert)

    return ctx
Esempio n. 53
0
    def connect(self, protocolfactory):
        last_error = None
        kwargs = dict()
        if self.socks_username is not None and self.socks_password is not None:
            kwargs['methods'] = dict(
                login=(self.socks_username, self.socks_password),
            )
        if self.socks_endpoint is not None:
            args = (self.host, self.port, self.socks_endpoint)
            socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
            if self.tls:
                context = optionsForClientTLS(unicode(self.host))
                socks_ep = TLSWrapClientEndpoint(context, socks_ep)
            proto = yield socks_ep.connect(protocolfactory)
            defer.returnValue(proto)
        else:
            for socks_port in self._socks_port_iter:
                tor_ep = TCP4ClientEndpoint(
                    reactor,
                    "127.0.0.1",
                    socks_port,
                )
                args = (self.host, self.port, tor_ep)
                socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
                if self.tls:
                    # XXX only twisted 14+
                    context = optionsForClientTLS(unicode(self.host))
                    socks_ep = TLSWrapClientEndpoint(context, socks_ep)

                try:
                    proto = yield socks_ep.connect(protocolfactory)
                    defer.returnValue(proto)

                except error.ConnectError as e0:
                    last_error = e0
            if last_error is not None:
                raise last_error
Esempio n. 54
0
 def connect_to_one_broker_TLS(self, p_pyhouse_obj, p_broker):
     l_host = p_broker.BrokerAddress
     l_port = p_broker.BrokerPort
     l_username = p_broker.UserName
     l_password = p_broker.Password
     l_clientID = 'PyH-' + p_pyhouse_obj.Computer.Name
     LOG.info('Connecting via TLS...')
     #  l_factory = protocol.Factory.forProtocol(echoclient.EchoClient)
     l_factory = PyHouseMqttFactory(p_pyhouse_obj, l_clientID, p_broker, l_username, l_password)
     l_certData = PEM_FILE.getContent()
     l_authority = Certificate.loadPEM(l_certData)
     l_options = optionsForClientTLS(l_host.decode('utf-8'), l_authority)
     l_endpoint = SSL4ClientEndpoint(p_pyhouse_obj.Twisted.Reactor, l_host, l_port, l_options)
     l_client = yield l_endpoint.connect(l_factory)
     l_done = defer.Deferred()
     l_client.connectionLost = lambda reason: l_done.callback(None)
     yield l_done
Esempio n. 55
0
    def execute(self, app, args):
        if app.state != AppState.offline:
            raise CommandException('You must be offline to connect!')

        app.terminal.message('Connecting to server... ')

        app.factory = ClientFactory()
        app.factory.protocol = lambda: ConnectCommand.client_types[args.type](app)

        with open('./certs/public.pem') as file:
            authority = ssl.Certificate.loadPEM(file.read())

        options = ssl.optionsForClientTLS(u'example.com', authority)
        app.port = reactor.connectSSL(args.host, args.port, app.factory, options)
        app.state = AppState.client

        app.terminal.message('Done.', new=False)
Esempio n. 56
0
File: web.py Progetto: Sliim/faraday
    def proxyClientFactoryClass(self, *args, **kwargs):
        """
        Overwrites proxyClientFactoryClass to add a TLS wrapper to all
        connections generated by ReverseProxyResource protocol factory
        if enabled.
        """
        client_factory = HTTPProxyClientFactory(*args, **kwargs)

        if self.__ssl_enabled:
            with open(server.config.ssl.certificate) as cert_file:
                cert = ssl.Certificate.loadPEM(cert_file.read())

            # TLSMemoryBIOFactory is the wrapper that takes TLS options and
            # the wrapped factory to add TLS to connections
            return TLSMemoryBIOFactory(
                ssl.optionsForClientTLS(self.host.decode("ascii"), cert), isClient=True, wrappedFactory=client_factory
            )
        else:
            return client_factory
Esempio n. 57
0
    def connect(self, factory):
        # further wrap the protocol if we're doing TLS.
        # "pray i do not wrap the protocol further".
        if self._tls:
            # XXX requires Twisted 14+
            from twisted.internet.ssl import optionsForClientTLS
            if self._tls is True:
                context = optionsForClientTLS(self._host)
            else:
                context = self._tls
            tls_factory = tls.TLSMemoryBIOFactory(context, True, factory)
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', tls_factory,
            )
        else:
            socks_factory = _TorSocksFactory(
                self._host, self._port, 'CONNECT', factory,
            )

        self._socks_factory = socks_factory
        # forward our address (when we get it) to any listeners
        self._socks_factory._get_address().addBoth(self._when_address.fire)
        # XXX isn't this just maybeDeferred()
        if isinstance(self._proxy_ep, Deferred):
            proxy_ep = yield self._proxy_ep
            if not IStreamClientEndpoint.providedBy(proxy_ep):
                raise ValueError(
                    "The Deferred provided as 'socks_endpoint' must "
                    "resolve to an IStreamClientEndpoint provider (got "
                    "{})".format(type(proxy_ep).__name__)
                )
        else:
            proxy_ep = self._proxy_ep

        # socks_proto = yield proxy_ep.connect(socks_factory)
        proto = yield proxy_ep.connect(socks_factory)
        wrapped_proto = yield proto.when_done()
        if self._tls:
            returnValue(wrapped_proto.wrappedProtocol)
        else:
            returnValue(wrapped_proto)
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)
Esempio n. 59
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[u'host'],
            factory.proxy[u'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