Exemplo n.º 1
0
def verify_sans(amazon_cert: crypto.X509) -> bool:
    """Verifies Subject Alternative Names (SANs) for Amazon certificate.

    Args:
        amazon_cert: Pycrypto X509 Amazon certificate.

    Returns:
        result: True if verification was successful, False if not.
    """
    cert_extentions = [amazon_cert.get_extension(i) for i in range(amazon_cert.get_extension_count())]
    subject_alt_names = ''

    for extention in cert_extentions:
        if 'subjectAltName' in str(extention.get_short_name()):
            subject_alt_names = extention.__str__()
            break

    result = 'echo-api.amazon.com' in subject_alt_names

    return result
Exemplo n.º 2
0
    def get_peer_certificate(self):
        """
        Retrieve the other side's certificate (if any)

        :return: The peer's certificate
        """
        cert = _lib.SSL_get_peer_certificate(self._ssl)
        if cert != _ffi.NULL:
            pycert = X509.__new__(X509)
            pycert._x509 = _ffi.gc(cert, _lib.X509_free)
            return pycert
        return None
Exemplo n.º 3
0
        def wrapper(ok, store_ctx):
            cert = X509.__new__(X509)
            cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
            error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
            error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)

            try:
                result = callback(connection, cert, error_number, error_depth, ok)
            except Exception as e:
                self._problems.append(e)
                return 0
            else:
                if result:
                    _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
                    return 1
                else:
                    return 0
Exemplo n.º 4
0
def get_certificates(self):
    from OpenSSL.crypto import X509
    from OpenSSL._util import ffi as _ffi, lib as _lib
    certs = _ffi.NULL
    if self.type_is_signed():
       certs = self._pkcs7.d.sign.cert
    elif self.type_is_signedAndEnveloped():
        certs = self._pkcs7.d.signed_and_enveloped.cert

    pycerts = []
    for i in range(_lib.sk_X509_num(certs)):
        pycert = X509.__new__(X509)
        pycert._x509 = _lib.sk_X509_value(certs, i)
        pycerts.append(pycert)
    if not pycerts:
        return None
    return tuple(pycerts)
Exemplo n.º 5
0
    def get_peer_cert_chain(self):
        """
        Retrieve the other side's certificate (if any)

        :return: A list of X509 instances giving the peer's certificate chain,
                 or None if it does not have one.
        """
        cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
        if cert_stack == _ffi.NULL:
            return None

        result = []
        for i in range(_lib.sk_X509_num(cert_stack)):
            # TODO could incref instead of dup here
            cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
            pycert = X509.__new__(X509)
            pycert._x509 = _ffi.gc(cert, _lib.X509_free)
            result.append(pycert)
        return result
Exemplo n.º 6
0
        def wrapper(ok, store_ctx):
            cert = X509.__new__(X509)
            cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
            error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
            error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)

            index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
            ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
            connection = Connection._reverse_mapping[ssl]

            try:
                result = callback(connection, cert, error_number, error_depth, ok)
            except Exception as e:
                self._problems.append(e)
                return 0
            else:
                if result:
                    _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
                    return 1
                else:
                    return 0
Exemplo n.º 7
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
Exemplo n.º 8
0
    def _generate_ca(self):
        # Generate key
        self.key = PKey()
        self.key.generate_key(TYPE_RSA, 2048)

        # Generate certificate
        self.cert = X509()
        self.cert.set_version(3)
        self.cert.set_serial_number(1)
        self.cert.get_subject().CN = 'Python proxychain server'
        self.cert.gmtime_adj_notBefore(0)
        self.cert.gmtime_adj_notAfter(315360000)
        self.cert.set_issuer(self.cert.get_subject())
        self.cert.set_pubkey(self.key)
        self.cert.add_extensions([
            X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0"),
            X509Extension("keyUsage", True, "keyCertSign, cRLSign"),
            X509Extension("subjectKeyIdentifier", False, "hash", subject=self.cert),
            ])
        self.cert.sign(self.key, "sha1")

        with open(self.ssl_certificate, 'wb+') as f:
            f.write(dump_privatekey(FILETYPE_PEM, self.key))
            f.write(dump_certificate(FILETYPE_PEM, self.cert))
Exemplo n.º 9
0
    def _parse(self, buff, digestalgo):
        pkcs7 = crypto.load_pkcs7_data(crypto.FILETYPE_ASN1, buff)

        certs_stack = _ffi.NULL
        if pkcs7.type_is_signed():
            certs_stack = pkcs7._pkcs7.d.sign.cert
        elif pkcs7.type_is_signedAndEnveloped():
            certs_stack = pkcs7._pkcs7.d.signed_and_enveloped.cert

        pycerts = []

        for i in range(_lib.sk_X509_num(certs_stack)):
            tmp = _lib.X509_dup(_lib.sk_X509_value(certs_stack, i))
            pycert = X509._from_raw_x509_ptr(tmp)
            pycerts.append(pycert)

        if not pycerts:
            return None

        for cert in pycerts:
            name = str(cert.get_subject())[19:-2].replace('/', ', ')
            checksum = cert.digest(digestalgo).decode().replace(':', '')

            self.content.append((name, checksum))
Exemplo n.º 10
0
def _validate_dependencies_met():
    """
    Verifies that PyOpenSSL's package-level dependencies have been met.
    Throws `ImportError` if they are not met.
    """
    # Method added in `cryptography==1.1`; not available in older versions
    from cryptography.x509.extensions import Extensions

    if getattr(Extensions, "get_extension_for_class", None) is None:
        raise ImportError(
            "'cryptography' module missing required functionality.  "
            "Try upgrading to v1.3.4 or newer."
        )

    # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
    # attribute is only present on those versions.
    from OpenSSL.crypto import X509

    x509 = X509()
    if getattr(x509, "_x509", None) is None:
        raise ImportError(
            "'pyOpenSSL' module missing required functionality. "
            "Try upgrading to v0.14 or newer."
        )
Exemplo n.º 11
0
    def certificate(self,
                    cert: crypto.X509,
                    name: Union[str, bytes],
                    alt_host: Optional[str] = None,
                    port: int = 443) -> bool:
        """Verifies the certificate presented at name is cert"""
        if alt_host is None:
            # In fact, socket.gethostbyname accepts both bytes and str, but types do not know that.
            host = socket.gethostbyname(cast(str, name)).encode()
        elif isinstance(alt_host, bytes):
            host = alt_host
        else:
            host = alt_host.encode()
        name = name if isinstance(name, bytes) else name.encode()

        try:
            presented_cert = crypto_util.probe_sni(name, host, port)
        except acme_errors.Error as error:
            logger.exception(str(error))
            return False

        # Despite documentation saying that bytes are expected for digest(), we must provide a str.
        return presented_cert.digest(cast(bytes, "sha256")) == cert.digest(
            cast(bytes, "sha256"))
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
0
    def test_default_hash(self):
        expected = (b'Ph\xd4\xd7"\xa1\xd4\xee\xd1\xe8\xf9\xe6\x17\xe2\xa6\\' +
                    b'M\x11\xc4\x99\x93\xc6\xf0\xaf\x01Hr\x0f~\x10\x16t')
        actual = get_cert_hash(X509())

        self.assertEqual(expected, actual)
Exemplo n.º 15
0
def signReqCA(CA_path, CSR_path, password, csr_type='usr'):
    '''
	Signs the CSR.
	Returns bytes of (Chain of trust, Issued Certificate) if csr_type == 'ca'
	Returns bytes of (Issued Certificate) if csr_type == 'usr' or 'svr'

	CA_path : path of the directory of CA which will sign the request.

	* DIRECTORY IN CA PATH MUST BE THE ONE GENERATED USING OpenCA *
	'''
    if not is_serial_consistent(CA_path):
        raise SerialException(
            'Serial sequence mismatched, Serial is corrupted')

    engine = getDB(CA_path)
    Session = sessionmaker(bind=engine)
    session = Session()

    CA_name = path.split(CA_path)[1]

    # load certifiate of the CA
    CAcert_bytes = open(
        path.join(path.abspath(CA_path), 'certs', (CA_name + '.cert.pem')),
        'rb').read()
    CAcert = load_certificate(FILETYPE_PEM, CAcert_bytes)

    password = bytes(password, 'utf-8') if isinstance(password,
                                                      str) else password

    # load privatekey of the CA.
    CAkey_bytes = open(
        path.join(path.abspath(CA_path), 'private',
                  (CA_name + '.private.pem')), 'rb').read()
    CAkey = load_privatekey(FILETYPE_PEM, CAkey_bytes, passphrase=password)

    # determine if the request is for a CA
    if csr_type == 'ca':
        SUBCA_name = path.split(CSR_path)[1]
        SUBCA_dir = CSR_path[:]
        CSR_path = path.join(path.abspath(CSR_path), 'csr',
                             (SUBCA_name + '.csr.pem'))

    # load the CSR.
    CSR_bytes = open(CSR_path, 'rb').read()
    CSR = load_certificate_request(FILETYPE_PEM, CSR_bytes)

    if CAcert.get_subject().CN == CSR.get_subject().CN:
        raise CNException('CN can not be same as parent')

    cert = X509()

    cert.set_subject(CSR.get_subject())

    # Get the last serial number and dump it in serial.old
    # Increment the serial number and save it in serial
    # give the incremented serial number here
    serial = open(path.join(CA_path, 'serial'), 'rb').read()
    cert.set_serial_number(int(serial))
    open(path.join(CA_path, 'serial.old'), 'wb').write(serial)
    open(path.join(CA_path, 'serial'),
         'wb').write(bytes(str(int(serial) + 1), 'utf-8'))

    cert.gmtime_adj_notBefore(0)

    if csr_type == 'ca':
        cert.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60)
        cert.add_extensions([ X509Extension(b"basicConstraints", True,b"CA:TRUE, pathlen:0"),\
            X509Extension(b"keyUsage", True,b"keyCertSign, cRLSign"),\
            X509Extension(b"authorityKeyIdentifier", False, b"keyid:always",issuer= CAcert),\
            X509Extension(b"subjectKeyIdentifier", False, b"hash",subject=cert)])
    elif csr_type == 'usr':
        cert.gmtime_adj_notAfter(1 * 365 * 24 * 60 * 60)
        cert.add_extensions([ X509Extension(b"basicConstraints",True,b"CA:FALSE"),\
            X509Extension(b"nsCertType",False,b"client, email"),\
            X509Extension(b"nsComment",False, b"Certified Using OpenSSL based OpenCA"),\
            X509Extension(b"subjectKeyIdentifier",False,b"hash",subject=cert),\
            X509Extension(b"authorityKeyIdentifier",False, b"keyid", issuer= CAcert),\
            X509Extension(b"keyUsage",True,b"nonRepudiation, digitalSignature, keyEncipherment"),\
            X509Extension(b"extendedKeyUsage", False, b"clientAuth, emailProtection")])

    elif csr_type == 'svr':
        cert.gmtime_adj_notAfter(2 * 365 * 24 * 60 * 30)
        cert.add_extensions([ X509Extension(b"basicConstraints",True,b"CA:FALSE"),\
            X509Extension(b"nsCertType",False,b"server"),\
            X509Extension(b"nsComment",False, b"Certified Using OpenSSL based OpenCA"),\
            X509Extension(b"subjectKeyIdentifier",False,b"hash",subject=cert),\
            X509Extension(b"authorityKeyIdentifier",False, b"keyid", issuer=CAcert),\
            X509Extension(b"keyUsage",True,b"nonRepudiation, digitalSignature, keyEncipherment"),\
            X509Extension(b"extendedKeyUsage", False, b"serverAuth")])

    cert.set_issuer(CAcert.get_subject())
    cert.set_pubkey(CSR.get_pubkey())
    cert.sign(CAkey, "sha256")

    # Save the signed certificate's information in the index.db
    clist = []
    for i in cert.get_subject().get_components():
        clist.append(i[0] + b'=' + i[1])

    cstring = b'/'.join(clist)
    cstring = b'/' + cstring + b'/'

    IndexObj = Index(expiration_date=cert.get_notAfter(),
                     serial_number_in_hex=str(serial),
                     cert_filename=serial.decode('utf-8') + '.cert.pem',
                     cert_subject=cstring)
    session.add(IndexObj)
    session.commit()

    # save the certificates in newcerts directory of the CA
    cert_bytes = dump_certificate(FILETYPE_PEM, cert)
    open(
        path.join(path.abspath(CA_path), 'newcerts',
                  (serial.decode('utf-8') + '.cert.pem')),
        'wb').write(cert_bytes)

    if csr_type == 'ca':
        # If csr_type is 'ca' then save the chain of trust and it's certificate
        if path.exists(
                path.join(path.abspath(CA_path), 'certs',
                          (CA_name + '.chain.pem'))):
            # If CA has a chain then forward that chain further
            CAcert_bytes = open(
                path.join(path.abspath(CA_path), 'certs',
                          (CA_name + '.chain.pem')), 'rb').read()

        open(
            path.join(path.abspath(SUBCA_dir), 'certs',
                      (SUBCA_name + '.cert.pem')), 'wb').write(cert_bytes)
        open(
            path.join(path.abspath(SUBCA_dir), 'certs',
                      (SUBCA_name + '.chain.pem')),
            'wb').write(cert_bytes + CAcert_bytes)
        return (cert_bytes + CAcert_bytes), cert_bytes
    else:
        print(
            'Certificate Produced @ ',
            path.join(path.abspath(path.split(CSR_path)[0]), 'USER.cert.pem'))
        if csr_type == 'usr':
            open(
                path.join(path.abspath(path.split(CSR_path)[0]),
                          'USER.cert.pem'), 'wb').write(cert_bytes)
        elif csr_type == 'svr':
            open(
                path.join(path.abspath(path.split(CSR_path)[0]),
                          'SERVER.cert.pem'), 'wb').write(cert_bytes)
        return cert_bytes
Exemplo n.º 16
0
def validate_certificate_chain(
    *,
    x5c: List[bytes],
    pem_root_certs_bytes: Optional[List[bytes]] = None,
) -> bool:
    """Validate that the certificates in x5c chain back to a known root certificate

    Args:
        `x5c`: X5C certificates from a registration response's attestation statement
        (optional) `pem_root_certs_bytes`: Any additional (PEM-formatted)
        root certificates that may complete the certificate chain

    Raises:
        `helpers.exceptions.InvalidCertificateChain` if chain cannot be validated
    """
    if pem_root_certs_bytes is None or len(pem_root_certs_bytes) < 1:
        # We have no root certs to chain back to, so just pass on validation
        return True

    # Make sure we have at least one certificate to try and link back to a root cert
    if len(x5c) < 1:
        raise InvalidCertificateChain("x5c was empty")

    # Prepare leaf cert
    try:
        leaf_cert_bytes = x5c[0]
        leaf_cert_crypto = load_der_x509_certificate(leaf_cert_bytes,
                                                     default_backend())
        leaf_cert = X509().from_cryptography(leaf_cert_crypto)
    except Exception as err:
        raise InvalidCertificateChain(f"Could not prepare leaf cert: {err}")

    # Prepare any intermediate certs
    try:
        # May be an empty array, that's fine
        intermediate_certs_bytes = x5c[1:]
        intermediate_certs_crypto = [
            load_der_x509_certificate(cert, default_backend())
            for cert in intermediate_certs_bytes
        ]
        intermediate_certs = [
            X509().from_cryptography(cert)
            for cert in intermediate_certs_crypto
        ]
    except Exception as err:
        raise InvalidCertificateChain(
            f"Could not prepare intermediate certs: {err}")

    # Prepare a collection of possible root certificates
    root_certs_store = X509Store()
    try:
        for cert in pem_root_certs_bytes:
            root_certs_store.add_cert(pem_cert_bytes_to_open_ssl_x509(cert))
    except Exception as err:
        raise InvalidCertificateChain(f"Could not prepare root certs: {err}")

    # Load certs into a "context" for validation
    context = X509StoreContext(
        store=root_certs_store,
        certificate=leaf_cert,
        chain=intermediate_certs,
    )

    # Validate the chain (will raise if it can't)
    try:
        context.verify_certificate()
    except X509StoreContextError:
        raise InvalidCertificateChain(
            "Certificate chain could not be validated")

    return True
Exemplo n.º 17
0
def get_public_key(cert: X509) -> str:
    return crypto.dump_publickey(crypto.FILETYPE_PEM,
                                 cert.get_pubkey()).decode('utf-8')
Exemplo n.º 18
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
Exemplo n.º 19
0
        raise ImportError(
            "'cryptography' module missing required functionality.  "
            "Try upgrading to v1.3.4 or newer."
        )
=======
    if getattr(Extensions, "get_extension_for_class", None) is None:
        raise ImportError("'cryptography' module missing required functionality.  "
                          "Try upgrading to v1.3.4 or newer.")
>>>>>>> 71358189c5e72ee2ac9883b408a2f540a7f5745e

    # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
    # attribute is only present on those versions.
    from OpenSSL.crypto import X509
<<<<<<< HEAD

    x509 = X509()
    if getattr(x509, "_x509", None) is None:
        raise ImportError(
            "'pyOpenSSL' module missing required functionality. "
            "Try upgrading to v0.14 or newer."
        )
=======
    x509 = X509()
    if getattr(x509, "_x509", None) is None:
        raise ImportError("'pyOpenSSL' module missing required functionality. "
                          "Try upgrading to v0.14 or newer.")
>>>>>>> 71358189c5e72ee2ac9883b408a2f540a7f5745e


def _dnsname_to_stdlib(name):
    """
Exemplo n.º 20
0
def _createCertificateKey(serial,
                          CN,
                          starttime,
                          endtime,
                          dump_cert_path,
                          dump_key_path,
                          issuerCert=None,
                          issuerKey=None,
                          key_type=TYPE_RSA,
                          key_bits=1024,
                          digest="sha256"):
    """Generate a certificate given a certificate request.

        'serial' is the serial number for the certificate

        'CN' is the subject common name of the certificate.

        'starttime' is the timestamp when the certificate starts
                          being valid. 0 means now.

        'endtime' is the timestamp when the certificate stops being
                        valid

        'dump_cert_path' is the file the generated certificate gets dumped.

        'dump_key_path' is the file the generated key gets dumped.

        'issuerCert' is the certificate object of the issuer.

        'issuerKey' is the key object of the issuer.

        'key_type' is the key type. allowed value: TYPE_RSA and TYPE_DSA.

        'key_bits' is number of bits to use in the key.

        'digest' is the digestion method to use for signing.
        """

    key = PKey()
    key.generate_key(key_type, key_bits)

    cert = X509()
    cert.set_serial_number(serial)
    cert.gmtime_adj_notBefore(starttime)
    cert.gmtime_adj_notAfter(endtime)

    cert.get_subject().C = "US"
    cert.get_subject().ST = "California"
    cert.get_subject().L = "Santa Clara"
    cert.get_subject().O = "pkg5"

    cert.set_pubkey(key)
    # If a issuer is specified, set the issuer. otherwise set cert
    # itself as a issuer.
    if issuerCert:
        cert.get_subject().CN = CN
        cert.set_issuer(issuerCert.get_subject())
    else:
        cert.get_subject().CN = "Depot Test CA"
        cert.set_issuer(cert.get_subject())

    # If there is a issuer key, sign with that key. Otherwise,
    # create a self-signed cert.
    # Cert requires bytes.
    if issuerKey:
        cert.add_extensions(
            [X509Extension(b"basicConstraints", True, b"CA:FALSE")])
        cert.sign(issuerKey, digest)
    else:
        cert.add_extensions(
            [X509Extension(b"basicConstraints", True, b"CA:TRUE")])
        cert.sign(key, digest)
    with open(dump_cert_path, "wb") as f:
        f.write(dump_certificate(FILETYPE_PEM, cert))
    with open(dump_key_path, "wb") as f:
        f.write(dump_privatekey(FILETYPE_PEM, key))
    return (cert, key)
Exemplo n.º 21
0
    def test_empty_x509_hash(self):
        cert = X509()
        expected = 'ajwehjgcua5ak6ykeqe8zhrysqo'

        self.assertEqual(expected, get_certificate_hash_encoding_a(cert))
Exemplo n.º 22
0
def check_authorized(signature, public_key, payload):
    """Reformat PEM-encoded public key for pyOpenSSL, verify signature."""
    pkey_public_key = load_publickey(FILETYPE_PEM, public_key)
    certificate = X509()
    certificate.set_pubkey(pkey_public_key)
    verify(certificate, signature, payload, str('sha1'))
Exemplo n.º 23
0
from OpenSSL.crypto import X509, PKey, X509Name, X509Req, X509Extension
from OpenSSL.crypto import dump_privatekey, dump_certificate
from OpenSSL.crypto import dump_certificate_request, sign, verify
from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM

ca_key = PKey()
ca_key.generate_key(TYPE_RSA, 2048)

f = open("CA.key", "w")
f.write(dump_privatekey(FILETYPE_PEM, ca_key))
f.close()

ca = X509()

ca.get_subject().commonName = "Bunchy McX"
ca.get_subject().emailAddress = "*****@*****.**"

ca.set_serial_number(1)
ca.gmtime_adj_notBefore(0)
ca.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)

ca.set_issuer(ca.get_subject())

ca.set_pubkey(ca_key)

ca.add_extensions([
    X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0"),
    X509Extension("keyUsage", True, "keyCertSign, cRLSign"),
    X509Extension("subjectKeyIdentifier", False, "hash", subject=ca)
])
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)
Exemplo n.º 25
0
def check_authorized(signature, public_key, payload):
    pkey_public_key = load_publickey(FILETYPE_PEM, public_key)
    certificate = X509()
    certificate.set_pubkey(pkey_public_key)
    verify(certificate, signature, payload, 'sha1')
Exemplo n.º 26
0
    def generate_new_certificate(ca_cert_path, username, is_ca_generation_request=False, ip=None):
        try:
            if not is_ca_generation_request:
                ca = get_certificate(ca_cert_path)
                if not ca:
                    log.warn("CA with key {} not found in redis".format(ca_cert_path))
                    return None

                ca_key = load_privatekey(FILETYPE_PEM, base64.b64decode(ca.get('k').encode('ascii')))
                cert_authority = load_certificate(FILETYPE_PEM, base64.b64decode(ca.get('c').encode('ascii')))

                client_key = PKey()
                client_key.generate_key(TYPE_RSA, 4096)

                x509 = X509()
                x509.set_version(2)
                x509.set_serial_number(random.randint(0,100000000))

                client_subj = x509.get_subject()
                client_subj.commonName = username

                ca_extension = X509Extension("basicConstraints", False, "CA:FALSE")
                key_usage = X509Extension("keyUsage", True, "digitalSignature")

                if username == 'kubernetes-apiserver':
                    san_list = ['IP:{}'.format(ip), 'DNS:kubernetes', 'DNS:kubernetes.default', 'DNS:kubernetes.default.svc', 'DNS:kubernetes.default.svc.cluster', 'DNS:kubernetes.svc.cluster.local']
                    x509.add_extensions([
                        ca_extension,
                        X509Extension("subjectKeyIdentifier", False, "hash", subject=x509),
                        X509Extension("extendedKeyUsage", True, "clientAuth"),
                        X509Extension("subjectAltName", False, ', '.join(san_list).encode()),
                        key_usage
                    ])
                else:
                    x509.add_extensions([
                        ca_extension,
                        X509Extension("subjectKeyIdentifier", False, "hash", subject=x509),
                        X509Extension("extendedKeyUsage", True, "clientAuth"),
                        key_usage
                    ])

                x509.set_issuer(cert_authority.get_subject())
                x509.set_pubkey(client_key)
                x509.gmtime_adj_notBefore(0)
                # default certificate validity is 1 year
                x509.gmtime_adj_notAfter(1*365*24*60*60 - 1)
                x509.sign(ca_key, 'sha256')
            else:
                client_key = PKey()
                client_key.generate_key(TYPE_RSA, 4096)

                x509 = X509()
                x509.set_version(2)
                x509.set_serial_number(random.randint(0,100000000))

                client_subj = x509.get_subject()
                client_subj.commonName = username

                ca_extension = X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0")
                key_usage = X509Extension("keyUsage", False, "cRLSign,digitalSignature,keyCertSign")

                x509.add_extensions([
                    ca_extension,
                    X509Extension("subjectKeyIdentifier", False, "hash", subject=x509),
                    X509Extension("extendedKeyUsage", True, "clientAuth"),
                    key_usage
                ])

                x509.set_issuer(client_subj)
                x509.set_pubkey(client_key)
                x509.gmtime_adj_notBefore(0)
                # default certificate validity is 1 year
                x509.gmtime_adj_notAfter(1*365*24*60*60 - 1)
                x509.sign(client_key, 'sha256')

            b64_cert = base64.b64encode(dump_certificate(FILETYPE_PEM, x509).encode('ascii')).decode('ascii')
            b64_key = base64.b64encode(dump_privatekey(FILETYPE_PEM, client_key).encode('ascii')).decode('ascii')

            return {"f": mTLS._get_digest(dump_certificate(FILETYPE_PEM, x509)), "c": b64_cert, "k": b64_key}

        except Exception as e:
            print "Exception: {}".format(e)
            return None
Exemplo n.º 27
0
#    f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, pkey))
#with open("private.pem", 'ab+') as f:
#    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
# 공개키, 개인키 읽어오기
with open("private.pem", 'rb+') as f:
    priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
with open("public.pem", 'rb+') as f:
    pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, f.read())
# 데이터 해시화
content = '_message'  # 가져와야 하는것
_hash = SHA.new(content.encode('utf-8')).digest()  # 데이터 해시화

#개인키로 전자서명
_sig = sign(priv_key, _hash, 'sha256')  # 개인키로 해시화 되어 있는 데이터의 전자서명 생성
print(_sig)
x509 = X509()  # 인증서를 사용할 수 있도록 하는 메서드 제공
x509.set_pubkey(pub_key)
# 비교 대상
cc2 = '_message'
t_hash = SHA.new(cc2.encode('utf-8')).digest()
# 사용법: verify(x509, 전자서명, 비교할 해시, 'sha256')
try:
    verify(x509, _sig, t_hash, 'sha256')
    app = QtWidgets.QApplication(sys.argv)
    QMessageBox.information(None, 'Success!', u"변조되지않았습니다.", QMessageBox.Ok)
    sys.exit(1)
except:
    app = QtWidgets.QApplication(sys.argv)
    QMessageBox.critical(None, 'Error!', u"변조되었습니다.", QMessageBox.Ok)
    sys.exit(1)
Exemplo n.º 28
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()))]
Exemplo n.º 29
0
def logHeader():
    popen_list = [sys.executable, lazylibrarian.FULL_PATH]
    popen_list += lazylibrarian.ARGS
    header = "Startup cmd: %s\n" % str(popen_list)
    header += 'Interface: %s\n' % lazylibrarian.CONFIG['HTTP_LOOK']
    header += 'Loglevel: %s\n' % lazylibrarian.LOGLEVEL
    header += 'Sys_Encoding: %s\n' % lazylibrarian.SYS_ENCODING
    for item in lazylibrarian.CONFIG_GIT:
        header += '%s: %s\n' % (item.lower(), lazylibrarian.CONFIG[item])
    header += "Python version: %s\n" % sys.version.split('\n')
    # noinspection PyDeprecation
    header += "Distribution: %s\n" % str(platform.dist())
    header += "System: %s\n" % str(platform.system())
    header += "Machine: %s\n" % str(platform.machine())
    header += "Platform: %s\n" % str(platform.platform())
    header += "uname: %s\n" % str(platform.uname())
    header += "version: %s\n" % str(platform.version())
    header += "mac_ver: %s\n" % str(platform.mac_ver())
    header += "requests: %s\n" % getattr(requests, '__version__', None)
    if not lazylibrarian.GROUP_CONCAT:
        # 3.5.4 is the earliest version with GROUP_CONCAT which we use, but is not essential
        header += 'sqlite3: missing required functionality. Try upgrading to v3.5.4 or newer. You have '
    header += "sqlite3: %s\n" % getattr(sqlite3, 'sqlite_version', None)
    try:
        from lib.unrar import rarfile
        version = rarfile.unrarlib.RARGetDllVersion()
        header += "unrar: DLL version %s\n" % version
    except Exception as e:
        header += "unrar: missing: %s\n" % str(e)

    header += "openssl: %s\n" % getattr(ssl, 'OPENSSL_VERSION', None)
    try:
        # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
        # attribute is only present on those versions.
        # noinspection PyUnresolvedReferences
        import OpenSSL
        # noinspection PyUnresolvedReferences
        from OpenSSL.crypto import X509
        x509 = X509()
        if getattr(x509, "_x509", None) is None:
            header += "pyOpenSSL: module missing required functionality. Try upgrading to v0.14 or newer. You have "
        header += "pyOpenSSL: %s\n" % getattr(OpenSSL, '__version__', None)
        from OpenSSL import SSL
    except ImportError:
        header += "pyOpenSSL: module missing\n"

    try:
        import OpenSSL.SSL
    except (ImportError, AttributeError) as e:
        header += 'OpenSSL missing module/attribute: %s\n' % e

    try:
        # get_extension_for_class method added in `cryptography==1.1`; not available in older versions
        # but need cryptography >= 1.3.4 for access from pyopenssl >= 0.14
        # noinspection PyUnresolvedReferences
        import cryptography
        # noinspection PyUnresolvedReferences
        from cryptography.x509.extensions import Extensions
        if getattr(Extensions, "get_extension_for_class", None) is None:
            header += "cryptography: module missing required functionality."
            header += " Try upgrading to v1.3.4 or newer. You have "
        header += "cryptography: %s\n" % getattr(cryptography, '__version__', None)
    except ImportError:
        header += "cryptography: module missing\n"

    try:
        import magic
    except ImportError:
        try:
            import lib.magic as magic
        except ImportError:
            magic = None

    if magic:
        try:
            # noinspection PyProtectedMember
            ver = magic.libmagic._name
        except AttributeError:
            ver = 'missing'
        header += "magic: %s\n" % ver
    else:
        header += "magic: missing\n"

    return header
def check_authorized(signature, public_key, payload):
    """Convert PEM encoded public key to a format palatable for pyOpenSSL."""
    pkey_public_key = load_publickey(FILETYPE_PEM, public_key)
    certificate = X509()
    certificate.set_pubkey(pkey_public_key)
    verify(certificate, signature, payload, str('sha1'))
Exemplo n.º 31
0
import datetime

#Note public private key pairs for both client, server and KDC are computed beforehand.

#Reading the public key of KDC.
with open("kdcpublickey.pem") as f:
    KDC_public_key = f.read()

#Reading the private key of client in sign format.
with open("clientprivate.pem") as f:
    private_key_data = f.read()
private_key_sign = load_privatekey(FILETYPE_PEM, private_key_data)

#Creating a temporary certificate of KDC from public key.
public_key_KDC = load_publickey(FILETYPE_PEM, KDC_public_key)
x509_KDC = X509()
x509_KDC.set_pubkey(public_key_KDC)

#Getting the public key of server from KDC.
target_url = "http://shantanu.pro/keydistributor.php"

#Generating data to be sent
files = {}
files['file'] = "serverpublic.pem"
mydata = urllib.urlencode(files)
print("Values sent to Key Distribution Centre:")
print("Data: " + mydata)

#Signing the data
my_sign = sign(private_key_sign, mydata, "SHA1")
print("My signature: ")