Example #1
0
def createServiceAPI(resource, sname, config):
    myconfig = config['services'][sname]
    site = server.Site(resource)

    listen = myconfig['listen']

    if 'ssl_enable' in myconfig and myconfig['ssl_enable']:
        try:
            from OpenSSL import crypto
            from twisted.internet import ssl
            ssl_data = {}
            for s in ['ssl_cert', 'ssl_chain']:
                try:
                    with open(myconfig[s], 'rt') as FH:
                        sdata = FH.read()
                        ssl_data[s] = crypto.load_certificate(
                            crypto.FILETYPE_PEM, sdata)
                except Exception as err:
                    ssl_data[s] = None
                    pass

            for s in ['ssl_key']:
                try:
                    with open(myconfig[s], 'rt') as FH:
                        sdata = FH.read()
                        ssl_data[s] = crypto.load_privatekey(
                            crypto.FILETYPE_PEM, sdata)
                except Exception as err:
                    ssl_data[s] = None
                    pass

            if ssl_data['ssl_chain']:
                sfact = ssl.CertificateOptions(
                    privateKey=ssl_data['ssl_key'],
                    certificate=ssl_data['ssl_cert'],
                    extraCertChain=[ssl_data['ssl_chain']])
            else:
                sfact = ssl.CertificateOptions(
                    privateKey=ssl_data['ssl_key'],
                    certificate=ssl_data['ssl_cert'])

            #skey = myconfig['ssl_key']
            #scert = myconfig['ssl_cert']
            #sfact = ssl.DefaultOpenSSLContextFactory(skey, scert)
            svc = internet.SSLServer(int(myconfig['port']),
                                     site,
                                     sfact,
                                     interface=listen)
        except Exception as err:
            raise err
    else:
        svc = internet.TCPServer(int(myconfig['port']), site, interface=listen)

    svc.setName(sname)

    return (svc)
Example #2
0
    def _build_api_service(self):
        """
        Once called, the resource is initialized. Any calls to self._add_resource() should be done before calling this fn.
        :return:
        """

        wsgi_app = self.anchore_service.get_api_application()
        wsgi_site = wsgi.WSGIResource(reactor, reactor.getThreadPool(), application=wsgi_app)

        self._add_resource(self.anchore_service.__service_api_version__.encode('utf-8'), wsgi_site)
        self.root_resource = web.resource.Resource()

        # Add nodes
        for name, resource in self.resource_nodes.items():
            self.root_resource.putChild(name, resource)

        # this will rewrite any calls that do not have an explicit version to the base path before being processed by flask
        self._api_version_bytes = self.anchore_service.__service_api_version__.encode('utf-8') # This is optimization

        # Handle the auth vs non-auth child resources to not consume a path element
        root = rewrite.RewriterResource(self.root_resource, self._default_version_rewrite)

        # Build the main site server
        site = server.Site(root)
        listen = self.anchore_service.configuration['listen']


        if str(self.anchore_service.configuration.get('ssl_enable', '')).lower() == 'true':
            try:
                ssl_data = {
                    'ssl_cert': _load_ssl_cert(self.anchore_service.configuration['ssl_cert']) if 'ssl_cert' in self.anchore_service.configuration else None,
                    'ssl_chain': _load_ssl_cert(self.anchore_service.configuration['ssl_chain']) if 'ssl_chain' in self.anchore_service.configuration else None,
                    'ssl_key': _load_ssl_key(self.anchore_service.configuration['ssl_key']) if 'ssl_key' in self.anchore_service.configuration else None
                }

                if ssl_data['ssl_chain']:
                    sfact = ssl.CertificateOptions(privateKey=ssl_data['ssl_key'], certificate=ssl_data['ssl_cert'],
                                                   extraCertChain=[ssl_data['ssl_chain']])
                else:
                    sfact = ssl.CertificateOptions(privateKey=ssl_data['ssl_key'], certificate=ssl_data['ssl_cert'])

                endpoint = SSL4ServerEndpoint(reactor=reactor, port=int(self.anchore_service.configuration['port']), sslContextFactory=sfact, interface=listen)
            except Exception as err:
                raise err
        else:
            endpoint = TCP4ServerEndpoint(reactor=reactor, port=int(self.anchore_service.configuration['port']), interface=listen)

        ret_svc = StreamServerEndpointService(endpoint=endpoint, factory=site)
        ret_svc.setName(self.anchore_service.name)
        
        return ret_svc
def create_context_factory(
    hostnames=None,
    privateKey=None,
    certificate=None,
    caCerts=None,
    verifyDepth=9,
    verbose=False,
):
    """ Create an appropriate SSL context factory for the given CA certs
    and hostname.

    @param hostnames: the hostname (or list of hostnames) to match against.
        Pass 'None' to disable hostname validation
    @param privateKey: client private key, if the server requires it
    @param certificate: client certificate, if the server requires it
    @param caCerts: a list of CA root certs (of type
        OpenSSL.SSL.X509) against which servers should be
        validated. Pass 'None' to entirely disable certificate
        validation
    @param verifyDepth: maximum verify depth
    @param verbose: More detailed log messages for invalid certificates
        (Note: no effect if hostname validation is not enabled)
    """
    if fips_manager.status():
        minimum_ssl_version = ssl.TLSVersion.TLSv1_2
    else:
        minimum_ssl_version = None

    kwargs = {
        "certificate": certificate,
        "raiseMinimumTo": minimum_ssl_version,
        "privateKey": privateKey,
        "verify": False,
    }
    if not caCerts:
        return ssl.CertificateOptions(**kwargs)
    else:
        kwargs.update(
            {
                "verify": True,
                "caCerts": caCerts,
                "verifyDepth": verifyDepth,
                "verifyOnce": False,
                "requireCertificate": True,
            }
        )
        if hostnames:
            return HostnameVerifySSLContextFactory(hostnames, verbose=verbose, **kwargs)
        else:
            return ssl.CertificateOptions(**kwargs)
Example #4
0
    def test_tlsConfiguration(self):
        """
        A TLS configuration is passed to the TLS initializer.
        """
        configs = []

        def init(self, xs, required=True, configurationForTLS=None):
            configs.append(configurationForTLS)

        self.client_jid = jid.JID('[email protected]/resource')

        # Get an XmlStream instance. Note that it gets initialized with the
        # XMPPAuthenticator (that has its associateWithXmlStream called) that
        # is in turn initialized with the arguments to the factory.
        configurationForTLS = ssl.CertificateOptions()
        factory = client.XMPPClientFactory(
            self.client_jid, 'secret', configurationForTLS=configurationForTLS)
        self.patch(xmlstream.TLSInitiatingInitializer, "__init__", init)
        xs = factory.buildProtocol(None)

        # test list of initializers
        version, tls, sasl, bind, session = xs.initializers

        self.assertIsInstance(tls, xmlstream.TLSInitiatingInitializer)
        self.assertIs(configurationForTLS, configs[0])
Example #5
0
def connect(factory):
    if config.has_key("ssl") and config["ssl"]:
        if config["ssl"] == "cert":
            log.info("CONNECT: SSL with client cert")

            cli = load_clicert(config["ssl_clicert"])
            ca = load_cacert(config["ssl_cacert"])

            log.info("Using client certificate:\n %s", cli.inspect())

            reactor.connectSSL(config["host"],
                               config["port"],
                               factory,
                               ssl.CertificateOptions(
                                   privateKey=cli.privateKey.original,
                                   certificate=cli.original,
                                   verify=True,
                                   caCerts=(ca.original,)))
        else:
            log.info("CONNECT: SSL default")
            reactor.connectSSL(config["host"],
                               config["port"],
                               factory,
                               ssl.ClientContextFactory())
    else:
        log.info("CONNECT: No SSL")
        reactor.connectTCP("irc.hackint.org",
                           6666,
                           factory)
Example #6
0
 def process(self):
     """ the is the request processor / main decision maker """
     try:
         headers = self.getAllHeaders().copy()
         self.content.seek(0, 0)
         data = self.content.read()
         route = router.route(self.uri.decode())
         if route:
             headers[b'host'] = route.host.encode()
             if not ons_env.is_secure and b'authorization' not in headers:
                 jwt_token = {
                     'expires_at': (datetime.now() + timedelta(seconds=60)).timestamp(),
                     'scope': ['ci:read', 'ci:write']
                 }
                 headers[b'authorization'] = ons_env.jwt.encode(jwt_token).encode()
             class_ = self.protocols[route.proto]
             client_factory = class_(self.method, self.uri, self.clientproto, headers, data, self)
             if route.ssl:
                 reactor.connectSSL(route.host, route.port, client_factory, ssl.CertificateOptions())
             else:
                 reactor.connectTCP(route.host, route.port, client_factory)
         else:
             ons_env.logger.error('no such API endpoint "{}"'.format(self.uri.decode()))
             self.setResponseCode(404, b'no such API endpoint')
             self.finish()
     except Exception as e:
         ons_env.logger.error(str(e))
         self.setResponseCode(500, b'unknown system error')
         self.finish()
Example #7
0
 def makeConnection(self, ip, port):
     logger.info("%s %s %s" % (ip, port, self.param_use_ssl))
     if ssl_support and self.param_use_ssl:
         self.ssl = ssl.CertificateOptions(method=SSL.SSLv3_METHOD)
         reactor.connectSSL(ip, port, self.factory, self.ssl)
     else:
         reactor.connectTCP(ip, port, self.factory)
Example #8
0
def trade_server():
    root = File("./htdocs")
    # for _symbol in MARKETS.keys(): root.putChild(str.encode(_symbol), resource)
    factory = EchoServerFactory()
    factory.protocol = EchoServerProtocol
    factory.startFactory(
    )  # when wrapped as a Twisted Web resource, start the underlying factory manually
    resource = WebSocketResource(factory)
    root.putChild(b"wss", resource)

    root.putChild(b"symbols", SymbolPage())  # 用于向页面传递交易对接口
    root.putChild(b"signin", SignInPage())  # 登录页面
    root.putChild(b"logout", SignOutPage())  # 登出页面
    root.putChild(b"logchk", LogCheckPage())  # 登陆状态检测接口
    root.putChild(b"setlost", SetLostPage())  # 设置全局变量是否自动止损
    root.putChild(b"trade", TradePage())  # 交易接口
    root.putChild(b"cancel", CancelPage())  # 取消所有订单
    root.putChild(b"contract", GetCoinsPage())  # 获取最新价格接口
    root.putChild(b"topdown", TopDownPage())  # 获取和设置当前品种的压力和支撑价格
    # use TLS
    privkey = open('cert/server.key', 'rt').read()
    certif = open('cert/fullchain.cer', 'rt').read()
    privkeypyssl = crypto.load_privatekey(crypto.FILETYPE_PEM, privkey)
    certifpyssl = crypto.load_certificate(crypto.FILETYPE_PEM, certif)
    contextFactory = ssl.CertificateOptions(privateKey=privkeypyssl,
                                            certificate=certifpyssl)

    site = Site(root)
    site.sessionFactory = longTimeoutSession
    reactor.listenSSL(SRV_PORT, site, contextFactory)
    # reactor.listenTCP(SRV_PORT, site)
    reactor.run()
Example #9
0
    def run(self):
        with open('cert.pem', 'r') as f:
            cert_data = f.read()

        with open('privkey.pem', 'r') as f:
            key_data = f.read()

        site = server.Site(PySOADelayedResource(
            requests_queue=self.requests_queue,
            responses_queue=self.responses_queue,
        ))
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_data)

        options = ssl.CertificateOptions(
            privateKey=key,
            certificate=cert,
            acceptableProtocols=[b'h2'],
        )
        endpoint = endpoints.SSL4ServerEndpoint(
            reactor,
            int(self.backend_layer_config['http_port']),
            options,
            interface=self.backend_layer_config['http_host']
        )
        endpoint.listen(site)
        reactor.run(installSignalHandlers=0)
Example #10
0
    def check(self, scan, env):
        creator = protocol.ClientCreator(env.reactor, BannerProtocol, self.bad,
                                         self.send)
        if env.bind_address:
            bindAddress = (env.bind_address, 0)
        else:
            bindAddress = None

        # Disable the timeout here because our calling scanner should
        # cancel us just fine without it
        if self.tls:
            opt = ssl.CertificateOptions(verify=False)
            d = creator.connectSSL(scan.ip,
                                   self.port,
                                   opt,
                                   timeout=None,
                                   bindAddress=bindAddress)
        else:
            d = creator.connectTCP(scan.ip,
                                   self.port,
                                   timeout=None,
                                   bindAddress=bindAddress)

        def connected(proto):
            return proto.deferred

        def connectFailed(fail):
            # If we could not connect for some sane reason it's just
            # not a proxy. Let unknown errors propagate though.
            fail.trap(error.ConnectionRefusedError, error.TCPTimedOutError)

        d.addCallbacks(connected, connectFailed)

        return d
Example #11
0
def _parseSSL(factory,
              port,
              privateKey="server.pem",
              certKey=None,
              sslmethod=None,
              interface='',
              backlog=50):
    """
    Internal parser function for L{_parseServer} to convert the string
    arguments for an SSL (over TCP/IPv4) stream endpoint into the structured
    arguments.

    @param factory: the protocol factory being parsed, or C{None}.  (This was a
        leftover argument from when this code was in C{strports}, and is now
        mostly None and unused.)
    @type factory: L{IProtocolFactory} or C{NoneType}

    @param port: the integer port number to bind
    @type port: C{str}

    @param interface: the interface IP to listen on
    @param backlog: the length of the listen queue
    @type backlog: C{str}

    @param privateKey: The file name of a PEM format private key file.
    @type privateKey: C{str}

    @param certKey: The file name of a PEM format certificate file.
    @type certKey: C{str}

    @param sslmethod: The string name of an SSL method, based on the name of a
        constant in C{OpenSSL.SSL}.  Must be one of: "SSLv23_METHOD",
        "SSLv2_METHOD", "SSLv3_METHOD", "TLSv1_METHOD".
    @type sslmethod: C{str}

    @return: a 2-tuple of (args, kwargs), describing  the parameters to
        L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments
        to L{SSL4ServerEndpoint}.
    """
    from twisted.internet import ssl
    if certKey is None:
        certKey = privateKey
    kw = {}
    if sslmethod is not None:
        kw['method'] = getattr(ssl.SSL, sslmethod)
    else:
        kw['method'] = ssl.SSL.SSLv23_METHOD
    certPEM = FilePath(certKey).getContent()
    keyPEM = FilePath(privateKey).getContent()
    privateCertificate = ssl.PrivateCertificate.loadPEM(certPEM + keyPEM)
    cf = ssl.CertificateOptions(
        privateKey=privateCertificate.privateKey.original,
        certificate=privateCertificate.original,
        **kw)
    return ((int(port), factory, cf), {
        'interface': interface,
        'backlog': int(backlog)
    })
Example #12
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
Example #13
0
    def _allowTLSconnections(self, path):
        try:
            privKey = open(path + '/privkey.pem', 'rt').read()
            certif = open(path + '/cert.pem', 'rt').read()
            chain = open(path + '/chain.pem', 'rt').read()

            self.lastEditCertTime = os.path.getmtime(path + '/cert.pem')

            privKeyPySSL = crypto.load_privatekey(crypto.FILETYPE_PEM, privKey)
            certifPySSL = crypto.load_certificate(crypto.FILETYPE_PEM, certif)
            chainPySSL = [crypto.load_certificate(crypto.FILETYPE_PEM, chain)]

            cipherListString = "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:"\
                               "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"\
                               "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384"
            accCiphers = ssl.AcceptableCiphers.fromOpenSSLCipherString(
                cipherListString)

            try:
                contextFactory = ssl.CertificateOptions(
                    privateKey=privKeyPySSL,
                    certificate=certifPySSL,
                    extraCertChain=chainPySSL,
                    acceptableCiphers=accCiphers,
                    raiseMinimumTo=ssl.TLSVersion.TLSv1_2)
            except AttributeError:
                contextFactory = ssl.CertificateOptions(
                    privateKey=privKeyPySSL,
                    certificate=certifPySSL,
                    extraCertChain=chainPySSL,
                    acceptableCiphers=accCiphers,
                    method=TLSv1_2_METHOD)

            self.options = contextFactory
            self.serverAcceptsTLS = True
            self._TLSattempts = 0
            print("TLS support is enabled.")
        except Exception as e:
            self.options = None
            self.serverAcceptsTLS = False
            self.lastEditCertTime = None
            print("Error while loading the TLS certificates.")
            print(e)
            print("TLS support is not enabled.")
Example #14
0
def _ssl_options(args):
    with open(args.sslkey) as keyfile:
        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, keyfile.read())
    with open(args.sslcert) as certfile:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, certfile.read())
    acceptable = ssl.AcceptableCiphers.fromOpenSSLCipherString(
        u'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:!RC4:HIGH:!MD5:!aNULL:!EDH')
    options = ssl.CertificateOptions(privateKey=pkey, certificate=cert, method=SSL.TLSv1_2_METHOD,
                                     acceptableCiphers=acceptable)
    return options
Example #15
0
    def onProceed(self, obj):
        """
        Proceed with TLS negotiation and reset the XML stream.
        """

        self.xmlstream.removeObserver('/failure', self.onFailure)
        ctx = ssl.CertificateOptions()
        self.xmlstream.transport.startTLS(ctx)
        self.xmlstream.reset()
        self.xmlstream.sendHeader()
        self._deferred.callback(Reset)
Example #16
0
    def loadPEM(self, pemfile, passphrase=""):
        if ssl is None:
            raise xmlstream.TLSNotSupported()

        file = open(pemfile, 'rb')
        pem = file.read()
        file.close()

        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pem, passphrase)
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem)
        self.tls_ctx = ssl.CertificateOptions(privateKey=pkey,
                                              certificate=cert)
Example #17
0
    def __invariant__(self):
        certs = list(
            ssl.Certificate.loadPEM(cert.as_bytes())
            for cert in self.chain.certificates)
        key = ssl.KeyPair.load(self.key.as_bytes(), FILETYPE_PEM)

        # Invoke CertificateOptions' key/certificate match checking logic.
        ssl.CertificateOptions(
            privateKey=key.original,
            certificate=certs[0].original,
            extraCertChain=list(cert.original for cert in certs[1:]),
        ).getContext()
        return (True, "")
Example #18
0
def ssl_conn(ssl_host, ssl_cert, ssl_clientuser, ssl_cacerts):
    """ Make an ssl connection, and return it to calling function """
    log.debug('in ssl_conn with %s', ssl_host)
    factory = ConnClientFactory()
    try:
        with open(ssl_cert) as keyFile:
            with open(ssl_cacerts) as certFile:
                clientCert = ssl.PrivateCertificate.loadPEM(
                    keyFile.read() + certFile.read())
    except IOError:
        log.warn("Sorry, there was some error with the certs")
    reactor.connectSSL(ssl_host, 443, factory, ssl.CertificateOptions())
    return reactor
Example #19
0
    def connectionMade(self):
        """
        Called by twisted when a client connects to the
        proxy.  Makes an TLS connection from the proxy to
        the server to complete the chain.
        """
        print("Connection made from CLIENT => PROXY")
        proxy_to_server_factory = protocol.ClientFactory()
        proxy_to_server_factory.protocol = ProxyToServerProtocol
        proxy_to_server_factory.server = self

        reactor.connectSSL(DST_IP, DST_PORT, proxy_to_server_factory,
                           twisted_ssl.CertificateOptions())
Example #20
0
def __connect(host, port, factory, connectTimeout, ssl,
              ssl_CertificateOptions):
    if not ssl:
        reactor.connectTCP(host, port, factory, timeout=connectTimeout)
    else:
        if not ssl_CertificateOptions:
            from twisted.internet import ssl
            ssl_CertificateOptions = ssl.CertificateOptions()
        reactor.connectSSL(host,
                           port,
                           factory,
                           ssl_CertificateOptions,
                           timeout=connectTimeout)
Example #21
0
def _parseClientSSL(*args, **kwargs):
    """
    Perform any argument value coercion necessary for SSL client parameters.

    Valid keyword arguments to this function are all L{IReactorSSL.connectSSL}
    arguments except for C{contextFactory}.  Instead, C{certKey} (the path name
    of the certificate file) C{privateKey} (the path name of the private key
    associated with the certificate) are accepted and used to construct a
    context factory.

    Valid positional arguments to this function are host and port.

    @param caCertsDir: The one parameter which is not part of
        L{IReactorSSL.connectSSL}'s signature, this is a path name used to
        construct a list of certificate authority certificates.  The directory
        will be scanned for files ending in C{.pem}, all of which will be
        considered valid certificate authorities for this connection.

    @type caCertsDir: C{str}

    @return: The coerced values as a C{dict}.
    """
    from twisted.internet import ssl
    kwargs = _parseClientTCP(*args, **kwargs)
    certKey = kwargs.pop('certKey', None)
    privateKey = kwargs.pop('privateKey', None)
    caCertsDir = kwargs.pop('caCertsDir', None)
    if certKey is not None:
        certx509 = ssl.Certificate.loadPEM(
            FilePath(certKey).getContent()).original
    else:
        certx509 = None
    if privateKey is not None:
        privateKey = ssl.PrivateCertificate.loadPEM(
            FilePath(privateKey).getContent()).privateKey.original
    else:
        privateKey = None
    if caCertsDir is not None:
        verify = True
        caCerts = _loadCAsFromDir(FilePath(caCertsDir))
    else:
        verify = False
        caCerts = None
    kwargs['sslContextFactory'] = ssl.CertificateOptions(
        method=ssl.SSL.SSLv23_METHOD,
        certificate=certx509,
        privateKey=privateKey,
        verify=verify,
        caCerts=caCerts
    )
    return kwargs
Example #22
0
 def __init__(self, audience,
              verifierURL=VERIFIER_URL,
              certsDir=CERTS_DIR,
              persistentConnections=True):
     assertMsg = "'audience' must be a domain like 'https://example.com'"
     assert re.search("^https?://", audience), assertMsg
     self.audience = audience
     self.verifier_url = verifierURL
     caCerts = _loadCAsFromDir(FilePath(certsDir))
     sslFactory = ssl.CertificateOptions(method=ssl.SSL.SSLv23_METHOD,
                                         verify=True, caCerts=caCerts)
     cf = _NormalToWebContextFactory(sslFactory)
     pool = HTTPConnectionPool(reactor, persistent=persistentConnections)
     self.agent = Agent(reactor, contextFactory=cf, pool=pool)
Example #23
0
    def onProceed(self, obj):
        """
        Proceed with TLS negotiation and reset the XML stream.
        """

        self.xmlstream.removeObserver('/failure', self.onFailure)
        cert = self.xmlstream.authenticator.certificate
        key = self.xmlstream.authenticator.privkey
        print "using certificate data: %s" % (cert.get_subject(), )
        ctx = ssl.CertificateOptions(privateKey=key, certificate=cert)
        self.xmlstream.transport.startTLS(ctx)
        self.xmlstream.reset()
        self.xmlstream.sendHeader()
        self._deferred.callback(xmlstream.Reset)
    def tlsAuth(self, auth):
        with open(CA_KEY, 'rb') as f:
            pem_key = f.read()
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pem_key, "")

        with open(CA_CERT, 'rb') as f:
            pem_cert = f.read()
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_cert)

        tls_ctx = ssl.CertificateOptions(privateKey=pkey, certificate=cert)

        self.xmlstream.send(domish.Element((ns.NS_XMPP_TLS, 'proceed')))
        self.xmlstream.transport.startTLS(tls_ctx)
        self.xmlstream.reset()
        self.tls_encrypted = True
Example #25
0
def startWebsocket():
    load_places()
    host_name = '10.35.33.55'
    cert_path = False
    
    url = u'wss://{}/api/fleet/wamp/'.format(host_name)
    if cert_path:
        with open(cert_path) as cert_file:
            cert = ssl.Certificate.loadPEM(cert_file.read())
        cert_options = ssl.optionsForClientTLS(host_name, cert)
    else:
        # Warning: This disables SSL verifiation
        cert_options = ssl.CertificateOptions(verify=False)

    runner = ApplicationRunner(url, realm=u'default', ssl=cert_options)
    runner.run(Component)
Example #26
0
def certificateOptionsFromPEMs(pemObjects, **kw):
    """
    Load a CertificateOptions from the given collection of PEM objects
    (already-loaded private keys and certificates).
    """
    from OpenSSL.SSL import FILETYPE_PEM
    from twisted.internet import ssl

    keys = [key for key in pemObjects if isinstance(key, Key)]
    if not len(keys):
        raise ValueError('Supplied PEM file(s) does *not* contain a key.')
    if len(keys) > 1:
        raise ValueError('Supplied PEM file(s) contains *more* than one key.')

    privateKey = ssl.KeyPair.load(keys[0].pem_str, FILETYPE_PEM)

    certs = [cert for cert in pemObjects if isinstance(cert, Certificate)]
    if not len(certs):
        raise ValueError('*At least one* certificate is required.')
    certificates = [ssl.Certificate.loadPEM(str(certPEM)) for certPEM in certs]

    certificatesByFingerprint = dict([(certificate.getPublicKey().keyHash(),
                                       certificate)
                                      for certificate in certificates])

    if privateKey.keyHash() not in certificatesByFingerprint:
        raise ValueError("No certificate matching {fingerprint} found.".format(
            fingerprint=privateKey.keyHash()))

    primaryCertificate = certificatesByFingerprint.pop(privateKey.keyHash())

    fakeEDHSupport = "dhParameters" in kw and not _DH_PARAMETERS_SUPPORTED
    if fakeEDHSupport:
        dhParameters = kw.pop("dhParameters")

    ctxFactory = ssl.CertificateOptions(
        privateKey=privateKey.original,
        certificate=primaryCertificate.original,
        extraCertChain=[
            chain.original for chain in certificatesByFingerprint.values()
        ],
        **kw)

    if fakeEDHSupport:
        return _DHParamContextFactory(ctxFactory, dhParameters)
    else:
        return ctxFactory
Example #27
0
    def __init__(self, accessList, ircAddress):
        self.accessList = accessList

        ircAddress, ircPort = ircAddress

        if "+" in ircPort:
            ircPort = int(ircPort[1:])

            sslOptions = ssl.CertificateOptions()
            reactor.connectSSL(ircAddress, ircPort, self, sslOptions)

        else:
            ircPort = int(ircPort)

            reactor.connectTCP(ircAddress, ircPort, self)

        reactor.run()
Example #28
0
 def startNegotiation(self, server, prefix, params):
     self.bot.log.info("[{server}] Server replied: \"{reply}\"",
                       server=server,
                       reply=params[1])
     self.bot.log.info("[{server}] Proceeding with TLS handshake...",
                       server=server)
     self.bot.servers[server].transport.startTLS(ssl.CertificateOptions())
     if ISSLTransport.providedBy(self.bot.servers[server].transport):
         self.bot.servers[server].secureConnection = True
         self.bot.log.info(
             "[{server}] TLS handshake successful. Connection is now secure.",
             server=server)
     else:
         self.bot.log.warn(
             "[{server}] TLS handshake failed. Connection is still not secure!",
             server=server)
     self.bot.moduleHandler.runGenericAction("cap-handler-finished", server,
                                             self.capName)
     return True
def main(reactor):
    log = Logger()

    def fe(inp):
        return formatEventAsClassicLogText(inp) + "\n"

    globalLogPublisher.addObserver(FileLogObserver(sys.stdout, fe))

    ds_certData = getModule(__name__).filePath.sibling('darkserver').child(
        'darkserver.pem').getContent()
    rt_certData = getModule(__name__).filePath.sibling('rootCA.d').child(
        'rootCA.crt').getContent()

    ds_cert = ssl.PrivateCertificate.loadPEM(ds_certData)
    rt_cert = ssl.Certificate.loadPEM(rt_certData)

    #  l.info("ds_cert: {ds_cert.inspect()}", ds_cert=ds_cert)
    #  l.info("ds_cert key: ds_cert.privateKey.inspect()", privateKey=ds_cert.privateKey)
    #  l.info("rt_cert: rt_cert.inspect()", rt_cert=rt_cert)

    options = ssl.CertificateOptions(certificate=ds_cert.original,
                                     privateKey=ds_cert.privateKey.original,
                                     trustRoot=rt_cert,
                                     verifyDepth=2,
                                     raiseMinimumTo=ssl.TLSVersion.TLSv1_1)

    #  l.info('Starting service')
    #  f = MainService()
    #  f.options = options

    log.info('Initiating listening')
    #  tlsFactory = TLSMemoryBIOFactory(options, False, f.getFingerFactory())
    #  reactor.listenTCP(8123, tlsFactory)
    reactor.listenSSL(
        8123, MainFactory(), options
    )  # FingerFactory({b'alice' : b'nice girl'})) #, ds_cert.options(rt_cert))
    #  reactor.listenTCP(8123, f.getFingerFactory())
    return defer.Deferred()
Example #30
0
 def spawn(self):
     # General algorithm
     # Query the central server what the active game is
     # Query the webserver for Hosts in that game and HostStatus of those hosts
     # See if last HostStatus entry is within the threshold
     # If so, queue a check for the host
     # Upon check, update the database with the result and schedule the next query for the host
     # Repeat process for each Service and ServiceStatus for each Host
     # Repeat process for each Content and Content Status for each Service
     # Validate credentials for service and/or content along the way
     #
     # Now the details...
     # Get the active game
     jobs = JobFactory(self.params)
     if self.params.get_scheme() == "https":
         ssl_obj = ssl.CertificateOptions()
         reactor.connectSSL(self.params.get_ip(), self.params.get_port(), jobs, ssl_obj,\
                                         self.params.get_timeout())
     elif self.params.get_scheme() == "http":
         reactor.connectTCP(self.params.get_ip(), self.params.get_port(), jobs, \
                 self.params.get_timeout())
     else:
         raise Exception("Unknown scheme:  %s" % self.params.get_scheme())
     reactor.callLater(self.sleep_time, self.spawn)