def getcert(self, csr): host = self.get_host() trustRoot = ssl.trustRootFromCertificates(self.ca_bundle) opts = ssl.optionsForClientTLS(host, trustRoot, self.cert_key, **TLS_OPTIONS) req = {'request': csr, 'profile': self.profile} url = self.base_url + '/api/v1/cfssl/newcert' res = yield getPage(url, contextFactory=opts, method='POST', postdata=json.dumps(req)) defer.returnValue(res)
def get_test_https_policy(): """Get a test IPolicyForHTTPS which trusts the test CA cert Returns: IPolicyForHTTPS """ ca_file = get_test_ca_cert_file() with open(ca_file) as stream: content = stream.read() cert = Certificate.loadPEM(content) trust_root = trustRootFromCertificates([cert]) return BrowserLikePolicyForHTTPS(trustRoot=trust_root)
def getCertifiTrustRoot(): try: import certifi bundle = certifi.where() except ImportError: log.warn("certifi was not found. Using leap.common bundle") bundle = ca_bundle.where() if bundle is None: log.error("Cannot find an usable cacert bundle. " "Certificate verification will fail") return None cacerts = certsFromBundle(bundle) return trustRootFromCertificates(cacerts)
def setUp(self): description = yield self._httpbin_process.server_description( reactor) self.baseurl = URL(scheme=u"https", host=description.host, port=description.port).asText() root = trustRootFromCertificates( [Certificate.loadPEM(description.cacert)], ) self.agent = Agent( reactor, contextFactory=BrowserLikePolicyForHTTPS(root), ) self.pool = HTTPConnectionPool(reactor, False)
def connect_mqtt_tls( client_id, host, rootpath, port, client_creds=None, protocols=None, ): """Connect an MQTT Client over TLS without client auth. :param host: The hostname to connect :type host: str :param rootpath: Path to the root certificate :type rootpath: str :param port (optional): The port to use, default 8883 :type port: int :param client_creds: Client cert/key pair :type client_creds: ssl.PrivateCertificate :param protocols: List of protocols for use with ALPN :type protocols: List[bytes] """ with open(rootpath, 'rb') as rootf: rootblob = rootf.read() trust_root = ssl.trustRootFromCertificates( [ssl.Certificate.loadPEM(rootblob)]) tls_options = ssl.optionsForClientTLS(host, trustRoot=trust_root, clientCertificate=client_creds, acceptableProtocols=protocols) endpoint = endpoints.SSL4ClientEndpoint(reactor, host, port, tls_options) d = endpoints.connectProtocol(endpoint, MQTTClient(client_id)) def _socket_connected(client): return client.connect() d.addCallback(_socket_connected) return d
def _createTrustRootFromCADirectory(self, certificate_dir): CACertificates = [] for CAFilename in listdir(certificate_dir): if not CAFilename.endswith('.0'): continue CAFileContent = FilePath(certificate_dir).child(CAFilename).getContent() try: CACertificates.append(ssl.Certificate.loadPEM(CAFileContent)) except crypto.Error as error: log.msg(f'Cannot load CA certificate from {CAFilename}: {error}', system=LOG_SYSTEM) else: try: log.msg(f'Loaded CA certificate {CACertificates[-1].getSubject()}', system=LOG_SYSTEM) except: log.msg("Failed to serialize Certificate Subject") if len(CACertificates) == 0: print('No certificates loaded for CTX verification. CA verification will not work.') return ssl.trustRootFromCertificates(CACertificates)
def check_tls_config(self, ca_key, ca_cert, get_kubernetes): """ Verify that a TLS server configured with the given key and certificate and the Kubernetes client returned by ``get_kubernetes`` can negotiate a TLS connection. """ # Set up an HTTPS server that requires the certificate chain from the # configuration file. This, because there's no way to pry inside a # Context and inspect its state nor any easy way to make Agent talk # over an in-memory transport. from twisted.internet import reactor endpoint = SSL4ServerEndpoint( reactor, 0, CertificateOptions( privateKey=ca_key.original, certificate=ca_cert.original, trustRoot=trustRootFromCertificates([ca_cert]), ), ) root = Resource() root.putChild(b"", Data(b"success", "text/plain")) # Construct the Kubernetes client objects with a Redirectable reactor. # This is necessary because the URL we pass to the Agent we get needs # to agree with the configuration file that was already written (or it # won't select the right client certificate). Just one of the many # reasons it would be better if we didn't have to do real networking # here. redirectable = Redirectable(reactor) client = get_kubernetes(redirectable).client() agent = client.agent d = endpoint.listen(Site(root)) def listening(port): self.addCleanup(port.stopListening) redirectable.set_redirect(port.getHost().host, port.getHost().port) url = b"https://127.0.0.1:8443/" return agent.request(b"GET", url) d.addCallback(listening) return d
def _createTrustRootFromCADirectory(self, certificate_dir): CACertificates = [] for CAFilename in listdir(certificate_dir): if not CAFilename.endswith('.0'): continue CAFileContent = FilePath(certificate_dir).child( CAFilename).getContent() try: CACertificates.append(ssl.Certificate.loadPEM(CAFileContent)) except crypto.Error as error: log.msg('Cannot load CA certificate from %s: %s' % (CAFilename, error), system=LOG_SYSTEM) else: log.msg('Loaded CA certificate commonName %s' % (str(CACertificates[-1].getSubject().commonName)), system=LOG_SYSTEM) if len(CACertificates) == 0: print( 'No certificiates loaded for CTX verificiation. CA verification will not work.' ) return ssl.trustRootFromCertificates(CACertificates)
def pick_trust_for_twisted(netloc, possible): """ Pick the right "trust roots" (certificate authority certificates) for the given server and return it in the form Twisted wants. Kubernetes certificates are often self-signed or otherwise exist outside of the typical certificate authority cartel system common for normal websites. This function tries to find the right authority to use. :param NetLocation netloc: The location of the server to consider. :param dict[pem.Certificate] possible: The available certificate authority certificates from which to choose. :return: A provider of ``twisted.internet.interfaces.IOpenSSLTrustRoot`` if there is a known certificate authority certificate for the given server. Otherwise, ``None``. """ try: trust_cert = possible[netloc] except KeyError: return None cert = ssl.Certificate.load(trust_cert.as_bytes(), FILETYPE_PEM) return ssl.trustRootFromCertificates([cert])
def get_certificate_options(self) -> CertificateOptions: """ Return certificate options With certificate generated and signed with peer private key """ certificate = self.get_certificate() openssl_certificate = X509.from_cryptography(certificate) openssl_pkey = PKey.from_cryptography_key(self.private_key) with open(settings.CA_FILEPATH, 'rb') as f: ca = x509.load_pem_x509_certificate(data=f.read(), backend=default_backend()) openssl_ca = X509.from_cryptography(ca) ca_cert = Certificate(openssl_ca) trust_root = trustRootFromCertificates([ca_cert]) # We should not use a ContextFactory # https://twistedmatrix.com/documents/19.7.0/api/twisted.protocols.tls.TLSMemoryBIOFactory.html certificate_options = CertificateOptions( privateKey=openssl_pkey, certificate=openssl_certificate, trustRoot=trust_root, raiseMinimumTo=TLSVersion.TLSv1_3) return certificate_options
'..', '..', '..', '..', 'router', '.crossbar', 'intermediate.cert.pem', ) tls_transport = { "type": "websocket", "url": "wss://127.0.0.1:8083/ws", "endpoint": SSL4ClientEndpoint( reactor, '127.0.0.1', 8083, optionsForClientTLS( 'localhost', # XXX why do I need BOTH the intermediate and actual # cert? Did I create the CA/intermediate certificates # incorrectly? trustRoot=trustRootFromCertificates( [ Certificate.loadPEM(open(cert_fname).read()), Certificate.loadPEM(open(inter_cert_fname).read()), ] ), ), ) } unix_transport = { "type": "websocket", "url": "ws://localhost/ws", "endpoint": UNIXClientEndpoint( reactor, os.path.join( os.path.split(__file__)[0], '..', '..', '..', '..', 'router', '.crossbar', 'intermediate.cert.pem', )
'..', '..', '..', '..', 'router', '.crossbar', 'intermediate.cert.pem', ) tls_transport = { "type": "websocket", "url": "wss://127.0.0.1:8083/ws", "endpoint": SSL4ClientEndpoint( reactor, '127.0.0.1', 8083, optionsForClientTLS( u'localhost', # XXX why do I need BOTH the intermediate and actual # cert? Did I create the CA/intermediate certificates # incorrectly? trustRoot=trustRootFromCertificates( [ Certificate.loadPEM(open(cert_fname).read()), Certificate.loadPEM(open(inter_cert_fname).read()), ] ), ), ) } unix_transport = { "type": "websocket", "url": "ws://localhost/ws", "endpoint": UNIXClientEndpoint( reactor, os.path.join( os.path.split(__file__)[0], '..', '..', '..', '..', 'router', '.crossbar', 'intermediate.cert.pem', )