Пример #1
0
    def validate_cert(chain, leaf):
        from datetime import timedelta
        from OpenSSL.crypto import X509, X509Store, X509StoreContext, X509StoreContextError

        store = X509Store()
        store.set_time(leaf.not_valid_before + timedelta(days=1))
        for c in chain:
            store.add_cert(X509.from_cryptography(c))

        x509_leaf = X509.from_cryptography(leaf)
        ctx = X509StoreContext(store, x509_leaf)
        try:
            ctx.verify_certificate()
        except X509StoreContextError as e:
            return False

        return True
Пример #2
0
 def get_deployer(self, rest_app, port):
     return HendrixDeployTLS("start",
                             key=self._privkey,
                             cert=X509.from_cryptography(self.certificate),
                             context_factory=ExistingKeyTLSContextFactory,
                             context_factory_kwargs={"curve_name": self.curve.name,
                                                     "sslmethod": TLSv1_2_METHOD},
                             options={"wsgi": rest_app, "https_port": port})
Пример #3
0
    def test_basic_tls_traffic(self):

        listener_name = data_utils.rand_name("lb_member_listener1-tls")
        listener_kwargs = {
            const.NAME: listener_name,
            const.PROTOCOL: const.TERMINATED_HTTPS,
            const.PROTOCOL_PORT: '443',
            const.LOADBALANCER_ID: self.lb_id,
            const.DEFAULT_POOL_ID: self.pool_id,
            const.DEFAULT_TLS_CONTAINER_REF: self.secret_ref,
        }
        listener = self.mem_listener_client.create_listener(**listener_kwargs)
        self.listener_id = listener[const.ID]
        self.addCleanup(self.mem_listener_client.cleanup_listener,
                        self.listener_id,
                        lb_client=self.mem_lb_client,
                        lb_id=self.lb_id)

        waiters.wait_for_status(self.mem_lb_client.show_loadbalancer,
                                self.lb_id, const.PROVISIONING_STATUS,
                                const.ACTIVE,
                                CONF.load_balancer.build_interval,
                                CONF.load_balancer.build_timeout)

        # Test HTTPS listener load balancing.
        # Note: certificate validation tests will follow this test
        self.check_members_balanced(self.lb_vip_address,
                                    protocol='https',
                                    verify=False)

        def _verify_cb(connection, x509, errno, errdepth, retcode):
            """Callback for certificate validation."""
            # don't validate names of root certificates
            if errdepth != 0:
                return True
            if errno == 0:
                # Make sure the certificate is the one we generated
                self.assertEqual('{}.example.com'.format(self.server_uuid),
                                 x509.get_subject().commonName)
            else:
                LOG.error('Certificate with CN: {0} failed validation with '
                          'OpenSSL verify errno {1}'.format(
                              x509.get_subject().commonName, errno))
                return False
            return True

        context = SSL.Context(SSL.SSLv23_METHOD)
        context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                           _verify_cb)
        ca_store = context.get_cert_store()
        ca_store.add_cert(X509.from_cryptography(self.ca_cert))
        sock = socket.socket()
        sock = SSL.Connection(context, sock)
        sock.connect((self.lb_vip_address, 443))
        # Validate the certificate is signed by the ca_cert we created
        sock.do_handshake()
Пример #4
0
 def get_x509_cert(**kwargs):
     from cryptography.x509 import load_der_x509_certificate
     from OpenSSL.crypto import X509
     with open(os.path.join(interop_dir, "TR2012", "rsa-cert.der"),
               "rb") as fh:
         return [
             X509.from_cryptography(
                 load_der_x509_certificate(fh.read(),
                                           backend=default_backend()))
         ]
Пример #5
0
    def _new_ssl_context(cls, cert, chain, key):
        ctx = PyOpenSSLContext(ssl.PROTOCOL_TLS)

        ctx._ctx.use_certificate(X509.from_cryptography(cert))

        for ca_cert in chain:
            ctx._ctx.add_extra_chain_cert(X509.from_cryptography(ca_cert))

        def remove_underscore(val: str) -> str:
            return val[len('_'):] if val.startswith('_') else val

        try:
            ctx._ctx.use_privatekey(PKey.from_cryptography_key(key))
        except OpenSSLError as error:
            raise X509AdapterError(str(error)) from error
        except TypeError as error:
            raise X509AdapterError(
                f"unsupported key type, expected RSAPrivateKey/DSAPrivateKey got"
                f" {remove_underscore(type(key).__name__)}") from error

        return ctx
Пример #6
0
def test_ssl_request():

    port = 9252
    pem_path = 'public.pem'

    statics_path = 'path_on_disk/to/files'
    os.makedirs(statics_path, exist_ok=True)

    cert, pk = get_certificate()

    options = {
        'wsgi': application,
        'max_upload_bytes': 200,
        'https_port': port,
        'resources': [MediaResource(statics_path, namespace='statics')],
    }
    deployer = HendrixDeployTLS(key=pk,
                                cert=openssl_X509.from_cryptography(cert),
                                context_factory=ExistingKeyTLSContextFactory,
                                context_factory_kwargs={
                                    "curve_name": ec.SECP384R1.name,
                                    "sslmethod": TLSv1_2_METHOD
                                },
                                options=options)
    deployer.addServices()
    deployer.start()

    def test_ssl_static_files():

        js_file = 'showmethisfile.js'
        filepath = os.path.join(statics_path, js_file)

        with open(pem_path, "w") as pub_file:
            pub_file.write(
                cert.public_bytes(serialization.Encoding.PEM).decode('utf-8'))

        with open(filepath, 'w') as js_write:
            js_write.write('//console.log("Hello World");')

        response = requests.get(f"https://127.0.0.1:{port}/statics/{js_file}",
                                verify=pem_path)

        assert response.status_code == 200
        assert '//console.log("Hello World");' in response.text
        os.remove(filepath)
        os.removedirs(statics_path)
        os.remove(pem_path)

    d = threads.deferToThread(test_ssl_static_files)
    yield d
Пример #7
0
    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
Пример #8
0
 def get_deployer(self, rest_app, port):
     return HendrixDeployTLS("start",
                             key=self._privkey,
                             cert=X509.from_cryptography(self.certificate),
                             context_factory=ExistingKeyTLSContextFactory,
                             context_factory_kwargs={
                                 "curve_name": _TLS_CURVE.name,
                                 "sslmethod": TLSv1_2_METHOD
                             },
                             options={
                                 "wsgi": rest_app,
                                 "https_port": port,
                                 "max_upload_bytes":
                                 MAX_UPLOAD_CONTENT_LENGTH,
                                 'resources': get_static_resources(),
                             })
Пример #9
0
def save_p12(cert, private, file_name, passphrase=None):
    host_folder = os.getenv(HOST_FOLDER_EXPORTS_PATH_ENV_KEY)

    if file_name and host_folder:
        openssl_cert = X509.from_cryptography(cert)
        openssl_priv_key = PKey.from_cryptography_key(private)

        p12 = PKCS12()
        p12.set_privatekey(openssl_priv_key)
        p12.set_certificate(openssl_cert)

        p12bin = p12.export(passphrase)
        file_path = PATH_TO_EXPORTS_FOLDER + '/{}.p12'.format(file_name)

        if os.path.isfile(file_path):
            raise ValueError
        with open(file_path, 'wb') as f:
            f.write(p12bin)
        return host_folder + '/{}.p12'.format(file_name)
Пример #10
0
def create_ssl_context(cert_byes,
                       pk_bytes,
                       password=None,
                       encoding=Encoding.PEM):
    """Create an SSL Context with the supplied cert/password.

    :param cert_bytes array of bytes containing the cert encoded
           using the method supplied in the ``encoding`` parameter
    :param pk_bytes array of bytes containing the private key encoded
           using the method supplied in the ``encoding`` parameter
    :param password array of bytes containing the passphrase to be used
           with the supplied private key. None if unencrypted.
           Defaults to None.
    :param encoding ``cryptography.hazmat.primitives.serialization.Encoding``
            details the encoding method used on the ``cert_bytes``  and
            ``pk_bytes`` parameters. Can be either PEM or DER.
            Defaults to PEM.
    """
    backend = default_backend()

    cert = None
    key = None
    if encoding == Encoding.PEM:
        cert = x509.load_pem_x509_certificate(cert_byes, backend)
        key = load_pem_private_key(pk_bytes, password, backend)
    elif encoding == Encoding.DER:
        cert = x509.load_der_x509_certificate(cert_byes, backend)
        key = load_der_private_key(pk_bytes, password, backend)
    else:
        raise ValueError('Invalid encoding provided: Must be PEM or DER')

    if not (cert and key):
        raise ValueError('Cert and key could not be parsed from '
                         'provided data')
    check_cert_dates(cert)
    ssl_context = PyOpenSSLContext(PROTOCOL)
    ssl_context._ctx.use_certificate(X509.from_cryptography(cert))
    ssl_context._ctx.use_privatekey(PKey.from_cryptography_key(key))
    return ssl_context
Пример #11
0
def create_ssl_context(cert_byes, pk_bytes, password=None,
                       encoding=Encoding.PEM):
    """Create an SSL Context with the supplied cert/password.

    :param cert_bytes array of bytes containing the cert encoded
           using the method supplied in the ``encoding`` parameter
    :param pk_bytes array of bytes containing the private key encoded
           using the method supplied in the ``encoding`` parameter
    :param password array of bytes containing the passphrase to be used
           with the supplied private key. None if unencrypted.
           Defaults to None.
    :param encoding ``cryptography.hazmat.primitives.serialization.Encoding``
            details the encoding method used on the ``cert_bytes``  and
            ``pk_bytes`` parameters. Can be either PEM or DER.
            Defaults to PEM.
    """
    backend = default_backend()

    cert = None
    key = None
    if encoding == Encoding.PEM:
        cert = x509.load_pem_x509_certificate(cert_byes, backend)
        key = load_pem_private_key(pk_bytes, password, backend)
    elif encoding == Encoding.DER:
        cert = x509.load_der_x509_certificate(cert_byes, backend)
        key = load_der_private_key(pk_bytes, password, backend)
    else:
        raise ValueError('Invalid encoding provided: Must be PEM or DER')

    if not (cert and key):
        raise ValueError('Cert and key could not be parsed from '
                         'provided data')
    check_cert_dates(cert)
    ssl_context = PyOpenSSLContext(PROTOCOL)
    ssl_context._ctx.use_certificate(X509.from_cryptography(cert))
    ssl_context._ctx.use_privatekey(PKey.from_cryptography_key(key))
    return ssl_context
Пример #12
0
def _certificates_for_authority_and_server(service_identity, key_size=1024):
    """
    Create a self-signed CA certificate and server certificate signed
    by the CA.

    :param service_identity: The identity (hostname) of the server.
    :type service_identity: :py:class:`unicode`

    :param key_size: (optional) The size of CA's and server's private
        RSA keys.  Defaults to 1024 bits, which is the minimum allowed
        by OpenSSL Contexts at the default security level as of 1.1.
    :type key_size: :py:class:`int`

    :return: a 3-tuple of ``(certificate_authority_certificate,
             server_private_key, server_certificate)``.
    :rtype: :py:class:`tuple` of (:py:class:`sslverify.Certificate`,
            :py:class:`OpenSSL.crypto.PKey`,
            :py:class:`OpenSSL.crypto.X509`)
    """
    common_name_for_ca = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example CA')])
    common_name_for_server = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example Server')])
    one_day = datetime.timedelta(1, 0, 0)
    private_key_for_ca = rsa.generate_private_key(public_exponent=65537,
                                                  key_size=key_size,
                                                  backend=default_backend())
    public_key_for_ca = private_key_for_ca.public_key()
    ca_certificate = (x509.CertificateBuilder().subject_name(
        common_name_for_ca).issuer_name(common_name_for_ca).not_valid_before(
            datetime.datetime.today() -
            one_day).not_valid_after(datetime.datetime.today() +
                                     one_day).serial_number(
                                         x509.random_serial_number()).
                      public_key(public_key_for_ca).add_extension(
                          x509.BasicConstraints(ca=True, path_length=9),
                          critical=True,
                      ).sign(private_key=private_key_for_ca,
                             algorithm=hashes.SHA256(),
                             backend=default_backend()))
    private_key_for_server = rsa.generate_private_key(
        public_exponent=65537, key_size=key_size, backend=default_backend())
    public_key_for_server = private_key_for_server.public_key()
    server_certificate = (
        x509.CertificateBuilder().subject_name(common_name_for_server).
        issuer_name(common_name_for_ca).not_valid_before(
            datetime.datetime.today() -
            one_day).not_valid_after(datetime.datetime.today() +
                                     one_day).serial_number(
                                         x509.random_serial_number()).
        public_key(public_key_for_server).add_extension(
            x509.BasicConstraints(ca=False, path_length=None),
            critical=True,
        ).add_extension(
            x509.SubjectAlternativeName([x509.DNSName(service_identity)]),
            critical=True,
        ).sign(private_key=private_key_for_ca,
               algorithm=hashes.SHA256(),
               backend=default_backend()))

    ca_self_cert = Certificate.loadPEM(
        ca_certificate.public_bytes(Encoding.PEM))

    pkey = PKey.from_cryptography_key(private_key_for_server)
    x509_server_certificate = X509.from_cryptography(server_certificate)

    return ca_self_cert, pkey, x509_server_certificate
from OpenSSL.crypto import X509
from OpenSSL.SSL import TLSv1_2_METHOD

from nkms.crypto.api import generate_self_signed_certificate

DB_NAME = "non-mining-proxy-node"

_URSULA = Ursula(dht_port=3501, dht_interface="localhost", db_name=DB_NAME)
_URSULA.listen()

CURVE = ec.SECP256R1
cert, private_key = generate_self_signed_certificate(
    _URSULA.stamp.fingerprint().decode(), CURVE)

deployer = HendrixDeployTLS("start", {
    "wsgi": _URSULA.rest_app,
    "https_port": 3550
},
                            key=private_key,
                            cert=X509.from_cryptography(cert),
                            context_factory=ExistingKeyTLSContextFactory,
                            context_factory_kwargs={
                                "curve_name": "prime256v1",
                                "sslmethod": TLSv1_2_METHOD
                            })

try:
    deployer.run()
finally:
    os.remove(DB_NAME)
Пример #14
0
 def getPeerCertificate(self) -> X509:
     certificate = generate_certificate(self.peer.private_key, settings.CA_FILEPATH, settings.CA_KEY_FILEPATH)
     openssl_certificate = X509.from_cryptography(certificate)
     return openssl_certificate
Пример #15
0
def _certificates_for_authority_and_server(service_identity, key_size=1024):
    """
    Create a self-signed CA certificate and server certificate signed
    by the CA.

    :param service_identity: The identity (hostname) of the server.
    :type service_identity: :py:class:`unicode`

    :param key_size: (optional) The size of CA's and server's private
        RSA keys.  Defaults to 1024 bits, which is the minimum allowed
        by OpenSSL Contexts at the default security level as of 1.1.
    :type key_size: :py:class:`int`

    :return: a 3-tuple of ``(certificate_authority_certificate,
             server_private_key, server_certificate)``.
    :rtype: :py:class:`tuple` of (:py:class:`sslverify.Certificate`,
            :py:class:`OpenSSL.crypto.PKey`,
            :py:class:`OpenSSL.crypto.X509`)
    """
    common_name_for_ca = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example CA')]
    )
    common_name_for_server = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example Server')]
    )
    one_day = datetime.timedelta(1, 0, 0)
    private_key_for_ca = rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
        backend=default_backend()
    )
    public_key_for_ca = private_key_for_ca.public_key()
    ca_certificate = (
        x509.CertificateBuilder()
        .subject_name(common_name_for_ca)
        .issuer_name(common_name_for_ca)
        .not_valid_before(datetime.datetime.today() - one_day)
        .not_valid_after(datetime.datetime.today() + one_day)
        .serial_number(x509.random_serial_number())
        .public_key(public_key_for_ca)
        .add_extension(
            x509.BasicConstraints(ca=True, path_length=9), critical=True,
        )
        .sign(
            private_key=private_key_for_ca, algorithm=hashes.SHA256(),
            backend=default_backend()
        )
    )
    private_key_for_server = rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
        backend=default_backend()
    )
    public_key_for_server = private_key_for_server.public_key()
    server_certificate = (
        x509.CertificateBuilder()
        .subject_name(common_name_for_server)
        .issuer_name(common_name_for_ca)
        .not_valid_before(datetime.datetime.today() - one_day)
        .not_valid_after(datetime.datetime.today() + one_day)
        .serial_number(x509.random_serial_number())
        .public_key(public_key_for_server)
        .add_extension(
            x509.BasicConstraints(ca=False, path_length=None), critical=True,
        )
        .add_extension(
            x509.SubjectAlternativeName(
                [x509.DNSName(service_identity)]
            ),
            critical=True,
        )
        .sign(
            private_key=private_key_for_ca, algorithm=hashes.SHA256(),
            backend=default_backend()
        )
    )

    ca_self_cert = Certificate.loadPEM(
        ca_certificate.public_bytes(Encoding.PEM)
    )

    pkey = PKey.from_cryptography_key(private_key_for_server)
    x509_server_certificate = X509.from_cryptography(server_certificate)

    return ca_self_cert, pkey, x509_server_certificate