Python OpenSSL.crypto.X509Extension() Examples

The following are 30 code examples of OpenSSL.crypto.X509Extension(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenSSL.crypto , or try the search function .
Example #1
Source File: test_lib_certdir.py    From synapse with Apache License 2.0 6 votes vote down vote up
def host_assertions(self, cdir, cert, key, cacert=None):
        '''
        test basic certificate assumptions for a host certificate

        Args:
            cdir (s_certdir.CertDir): certdir object
            cert (crypto.X509): Cert to test
            key (crypto.PKey): Key for the certification
            cacert (crypto.X509): Corresponding CA cert (optional)
        '''
        nextensions = cert.get_extension_count()
        exts = {ext.get_short_name(): ext.get_data() for ext in [cert.get_extension(i) for i in range(nextensions)]}

        nscertext = crypto.X509Extension(b'nsCertType', False, b'server')
        keyuseext = crypto.X509Extension(b'keyUsage', False, b'digitalSignature,keyEncipherment')
        extkeyuseext = crypto.X509Extension(b'extendedKeyUsage', False, b'serverAuth')
        basicconext = crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE')

        self.eq(exts[b'nsCertType'], nscertext.get_data())
        self.eq(exts[b'keyUsage'], keyuseext.get_data())
        self.eq(exts[b'extendedKeyUsage'], extkeyuseext.get_data())
        self.eq(exts[b'basicConstraints'], basicconext.get_data())
        self.isin(b'subjectAltName', exts) 
Example #2
Source File: test_lib_certdir.py    From synapse with Apache License 2.0 6 votes vote down vote up
def user_assertions(self, cdir, cert, key, cacert=None):
        '''
        test basic certificate assumptions for a host certificate

        Args:
            cdir (s_certdir.CertDir): certdir object
            cert (crypto.X509): Cert to test
            key (crypto.PKey): Key for the certification
            cacert (crypto.X509): Corresponding CA cert (optional)
        '''
        nextensions = cert.get_extension_count()
        exts = {ext.get_short_name(): ext.get_data() for ext in [cert.get_extension(i) for i in range(nextensions)]}

        nscertext = crypto.X509Extension(b'nsCertType', False, b'client')
        keyuseext = crypto.X509Extension(b'keyUsage', False, b'digitalSignature')
        extkeyuseext = crypto.X509Extension(b'extendedKeyUsage', False, b'clientAuth')
        basicconext = crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE')
        self.eq(exts[b'nsCertType'], nscertext.get_data())
        self.eq(exts[b'keyUsage'], keyuseext.get_data())
        self.eq(exts[b'extendedKeyUsage'], extkeyuseext.get_data())
        self.eq(exts[b'basicConstraints'], basicconext.get_data())
        self.notin(b'subjectAltName', exts) 
Example #3
Source File: certs.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def __init__(self, typename=None, critical=None, value=None,
                 subject=None, issuer=None, _ext=None):
        if _ext is not None:
            ext = _ext
        # The following is necessary due to the nature of the
        # underlying C implementation.
        elif subject is None and issuer is None:
            ext = crypto.X509Extension(typename, critical, value)
        elif subject is not None and issuer is None:
            subject = subject._cert
            ext = crypto.X509Extension(typename, critical, value,
                                       subject=subject)
        elif subject is None and issuer is not None:
            issuer = issuer._cert
            ext = crypto.X509Extension(typename, critical, value,
                                       issuer=issuer)
        elif subject is not None and issuer is not None:
            issuer = issuer._cert
            ext = crypto.X509Extension(typename, critical, value,
                                       subject=subject, issuer=issuer)
        self._ext = ext 
Example #4
Source File: testtools.py    From flocker with Apache License 2.0 6 votes vote down vote up
def assert_has_extension(test, credential, name, value):
    """
    Assert that the ``X509Extension`` with the matching name from the
    certificate has the given value.

    :param TestCase test: The current test.
    :param FlockerCredential certificate: Credential whose certificate we
        should inspect.
    :param bytes name: The name of the extension.
    :param bytes value: The data encoded in the extension.

    :raises AssertionError: If the extension is not found or has the wrong
        value.
    """
    expected = X509Extension(name, False, value)
    x509 = credential.certificate.original
    values = []
    for i in range(x509.get_extension_count()):
        extension = x509.get_extension(i)
        if extension.get_short_name() == name:
            values.append(extension.get_data())
    test.assertIn(expected.get_data(), values) 
Example #5
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #6
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_server_pair(self, o, cn, san=[]):
        """Issue a X.509 server key/certificate pair"""

        # key
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)

        # cert
        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)

        cert_subject = cert.get_subject()
        cert_subject.O = o
        cert_subject.OU = 'kOVHernetes'
        cert_subject.CN = cn
        cert.set_issuer(self.cert.get_issuer())

        cert_ext = []
        cert_ext.append(crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert))
        cert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid,issuer:always', issuer=self.cert))
        cert_ext.append(crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'))
        cert_ext.append(crypto.X509Extension(b'keyUsage', True, b'digitalSignature, keyEncipherment'))
        cert_ext.append(crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth'))
        if san: cert_ext.append(crypto.X509Extension(b'subjectAltName', False, ','.join(san).encode()))
        cert.add_extensions(cert_ext)

        # sign cert with CA key
        cert.sign(self.key, 'sha256')

        type(self).__next_serial += 1

        return key, cert 
Example #7
Source File: openssl_csr.py    From ansible-nginx-load-balancer with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(
                    b"subjectAltName", False,
                    self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(
                crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(
                    crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #8
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #9
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #10
Source File: man_cert_setup.py    From aws-greengrass-mini-fulfillment with Apache License 2.0 5 votes vote down vote up
def create_group_cert(cli):
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)  # generate RSA key-pair

    cert = crypto.X509()
    cert.get_subject().countryName = "US"
    cert.get_subject().stateOrProvinceName = "CA"
    cert.get_subject().organizationName = "mini-fulfillment"
    cert.get_subject().organizationalUnitName = "demo"
    cert.get_subject().commonName = "mini-fulfillment"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60)  # 5 year expiry date
    cert.set_issuer(cert.get_subject())  # self-sign this certificate
    cert.set_pubkey(k)
    san_list = ["IP:{0}".format(cli.ip_address)]
    extension_list = [
        crypto.X509Extension(type_name=b"basicConstraints",
                             critical=False, value=b"CA:false"),
        crypto.X509Extension(type_name=b"subjectAltName",
                             critical=True, value=", ".join(san_list)),
        # crypto.X509Extension(type_name=b"subjectKeyIdentifier",
        #                      critical=True, value=b"hash")
    ]
    cert.add_extensions(extension_list)
    cert.sign(k, 'sha256')

    prefix = str(cli.out_dir) + '/' + cli.group_name

    open("{0}-server.crt".format(prefix), 'wt').write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open("{0}-server-private.key".format(prefix), 'wt').write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey=k))
    open("{0}-server-public.key".format(prefix), 'wt').write(
        crypto.dump_publickey(crypto.FILETYPE_PEM, pkey=k)) 
Example #11
Source File: test_ssl_util.py    From quay with Apache License 2.0 5 votes vote down vote up
def generate_test_cert(hostname="somehostname", san_list=None, expires=1000000):
    """
    Generates a test SSL certificate and returns the certificate data and private key data.
    """

    # Based on: http://blog.richardknop.com/2012/08/create-a-self-signed-x509-certificate-in-python/
    # Create a key pair.
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # Create a self-signed cert.
    cert = crypto.X509()
    cert.get_subject().CN = hostname

    # Add the subjectAltNames (if necessary).
    if san_list is not None:
        cert.add_extensions([crypto.X509Extension(b"subjectAltName", False, b", ".join(san_list))])

    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(expires)
    cert.set_issuer(cert.get_subject())

    cert.set_pubkey(k)
    cert.sign(k, "sha1")

    # Dump the certificate and private key in PEM format.
    cert_data = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    key_data = crypto.dump_privatekey(crypto.FILETYPE_PEM, k)

    return (cert_data, key_data) 
Example #12
Source File: snakeoil_ca.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def create_keypair(self):
        LOG.debug('Generating Snakeoil CA')
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, self.key_size)

        cert = crypto.X509()
        cert.set_version(self.x509_version)
        cert.set_serial_number(self.serial)
        subject = cert.get_subject()
        set_subject_X509Name(subject, self.subject_dn)
        cert.set_subject(subject)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(self.expiry_days)
        cert.set_issuer(set_subject_X509Name(
            cert.get_issuer(), self.signing_dn))
        cert.set_pubkey(key)
        cert.add_extensions([
            crypto.X509Extension(b"basicConstraints", True,
                                 b"CA:TRUE, pathlen:5"),
        ])
        if not self.signing_key:
            self.signing_key = key  # self-signed

        cert.sign(self.signing_key, 'sha256')

        LOG.debug('Snakeoil CA cert/key generated')

        chain = ""
        if self.parent_chain_path:
            with open(self.parent_chain_path) as fh:
                chain = fh.read()
        chain += crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        pkcs7 = self._generate_pkcs7(chain)
        return cert, key, chain, pkcs7 
Example #13
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #14
Source File: test_ca.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subject_key_identifier(self):
        ca = self._create_ca()
        e = ca.x509.get_extension(2)
        self.assertEqual(e.get_short_name().decode(), 'subjectKeyIdentifier')
        self.assertEqual(e.get_critical(), False)
        e2 = crypto.X509Extension(
            b'subjectKeyIdentifier', False, b'hash', subject=ca.x509
        )
        self.assertEqual(e.get_data(), e2.get_data()) 
Example #15
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #16
Source File: snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_keypair(self):
        LOG.debug('Generating Snakeoil CA')
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, self.key_size)

        cert = crypto.X509()
        cert.set_version(self.x509_version)
        cert.set_serial_number(self.serial)
        subject = cert.get_subject()
        set_subject_X509Name(subject, self.subject_dn)
        cert.set_subject(subject)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(self.expiry_days)
        cert.set_issuer(set_subject_X509Name(
            cert.get_issuer(), self.signing_dn))
        cert.set_pubkey(key)
        cert.add_extensions([
            crypto.X509Extension(b"basicConstraints", True,
                                 b"CA:TRUE, pathlen:5"),
        ])
        if not self.signing_key:
            self.signing_key = key  # self-signed

        cert.sign(self.signing_key, 'sha256')

        LOG.debug('Snakeoil CA cert/key generated')

        chain = b''
        if self.parent_chain_path:
            with open(self.parent_chain_path, 'rb') as fh:
                chain = fh.read()
        chain += crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        pkcs7 = self._generate_pkcs7(chain)
        return cert, key, chain, pkcs7 
Example #17
Source File: openssl_csr.py    From docket with Apache License 2.0 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not self.check(module, perms_required=False) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            altnames = ', '.join(self.subjectAltName)
            extensions = [crypto.X509Extension(b"subjectAltName", False, altnames.encode('ascii'))]

            if self.keyUsage:
                usages = ', '.join(self.keyUsage)
                extensions.append(crypto.X509Extension(b"keyUsage", False, usages.encode('ascii')))

            if self.extendedKeyUsage:
                usages = ', '.join(self.extendedKeyUsage)
                extensions.append(crypto.X509Extension(b"extendedKeyUsage", False, usages.encode('ascii')))

            req.add_extensions(extensions)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)

            self.changed = True

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #18
Source File: generate.py    From openvpn-rapid-config with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_ca(config_ca):
    ca = crypto.X509()
    ca.set_version(2)
    ca.set_serial_number(config_ca['serial'])
    ca_subj = ca.get_subject()
    if 'commonName' in config_ca:
        ca_subj.commonName = config_ca['commonName']
    if 'stateOrProvinceName' in config_ca:
        ca_subj.stateOrProvinceName = config_ca['stateOrProvinceName']
    if 'localityName' in config_ca:
        ca_subj.localityName = config_ca['localityName']
    if 'organizationName' in config_ca:
        ca_subj.organizationName = config_ca['organizationName']
    if 'organizationalUnitName' in config_ca:
        ca_subj.organizationalUnitName = config_ca['organizationalUnitName']
    if 'emailAddress' in config_ca:
        ca_subj.emailAddress = config_ca['emailAddress']
    if 'countryName' in config_ca:
        ca_subj.countryName = config_ca['countryName']
    if 'validfrom' in config_ca:
        ca.set_notBefore(config_ca['validfrom'])
    if 'validto' in config_ca:
        ca.set_notAfter(config_ca['validto'])
    key = openssl_generate_privatekey(config_ca['keyfilesize'])
    ca.add_extensions([
        crypto.X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0"),
        crypto.X509Extension("keyUsage", False, "keyCertSign, cRLSign"),
        crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=ca),
    ])
    ca.add_extensions([
        crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always",issuer=ca)
    ])
    ca.set_issuer(ca.get_subject())
    ca.set_pubkey(key)
    ca.sign(key, config_ca['hashalgorithm'])
    return ca, key 
Example #19
Source File: generate.py    From openvpn-rapid-config with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_certificate(config_cert, ca, cakey, name):
    # Generate the private key
    key = openssl_generate_privatekey(config_cert['keyfilesize'])

    # Generate the certificate request
    req = crypto.X509Req()
    req_subj = req.get_subject()
    if 'commonName' in config_cert:
        req_subj.commonName = config_cert['commonName']
    if 'stateOrProvinceName' in config_cert:
        req_subj.stateOrProvinceName = config_cert['stateOrProvinceName']
    if 'localityName' in config_cert:
        req_subj.localityName = config_cert['localityName']
    if 'organizationName' in config_cert:
        req_subj.organizationName = config_cert['organizationName']
    if 'organizationalUnitName' in config_cert:
        req_subj.organizationalUnitName = config_cert['organizationalUnitName']
    if 'emailAddress' in config_cert:
        req_subj.emailAddress = config_cert['emailAddress']
    if 'countryName' in config_cert:
        req_subj.countryName = config_cert['countryName']

    req.set_pubkey(key)
    req.sign(key, config_cert['hashalgorithm'])

    # Now generate the certificate itself
    cert = crypto.X509()
    cert.set_version(2)
    cert.set_serial_number(config_cert['serial'])
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.set_issuer(ca.get_subject())

    if 'validfrom' in config_cert:
        cert.set_notBefore(config_cert['validfrom'])
    if 'validto' in config_cert:
        cert.set_notAfter(config_cert['validto'])

    if name == 'client':
        usage = 'clientAuth'
        nscerttype = 'client'
    elif name == 'server':
        usage = 'serverAuth'
        nscerttype = 'server'
    else:
        sys.stdout.write("ERROR: Bad certificate type\n")
        sys.exit(1)

    cert.add_extensions([
        crypto.X509Extension("basicConstraints", True, "CA:FALSE"),
        crypto.X509Extension("keyUsage", False, "digitalSignature,keyAgreement"),
        crypto.X509Extension("extendedKeyUsage", False, usage),
        crypto.X509Extension("nsCertType", False, nscerttype),
        crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=cert),
        crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca)
    ])

    cert.sign(cakey, config_cert['hashalgorithm'])
    return req, cert, key 
Example #20
Source File: certgen.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def createSelfSignedCertificate(issuerName, issuerKey, serial, notBefore, notAfter, altNames, digest="sha256"):
    """
    Generate a certificate given a certificate request.
    Arguments: issuerName - The name of the issuer
               issuerKey  - The private key of the issuer
               serial     - Serial number for the certificate
               notBefore  - Timestamp (relative to now) when the certificate
                            starts being valid
               notAfter   - Timestamp (relative to now) when the certificate
                            stops being valid
               altNames   - The alternative names
               digest     - Digest method to use for signing, default is sha256
    Returns:   The signed certificate in an X509 object
    """
    cert = crypto.X509()
    cert.set_version(2)
    cert.set_serial_number(serial)
    cert.get_subject().CN = issuerName
    cert.gmtime_adj_notBefore(notBefore)
    cert.gmtime_adj_notAfter(notAfter)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(issuerKey)

    if altNames:
        cert.add_extensions([crypto.X509Extension(b"subjectAltName", False, altNames)])

    cert.sign(issuerKey, digest)
    return cert 
Example #21
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_server_cert(self, key, o, cn, san=[]):
        """Issue a X.509 server certificate"""

        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)

        cert_subject = cert.get_subject()
        cert_subject.O = o
        cert_subject.OU = 'kOVHernetes'
        cert_subject.CN = cn
        cert.set_issuer(self.cert.get_issuer())

        cert_ext = []
        cert_ext.append(crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert))
        cert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid,issuer:always', issuer=self.cert))
        cert_ext.append(crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'))
        cert_ext.append(crypto.X509Extension(b'keyUsage', True, b'digitalSignature, keyEncipherment'))
        cert_ext.append(crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth'))
        if san:
            cert_ext.append(crypto.X509Extension(b'subjectAltName', False, ','.join(san).encode()))
        cert.add_extensions(cert_ext)

        # sign cert with CA key
        cert.sign(self.key, 'sha256')

        type(self).__next_serial += 1

        return cert 
Example #22
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_client_cert(self, key, o, cn):
        """Issue a X.509 client certificate"""

        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)

        cert_subject = cert.get_subject()
        cert_subject.O = o
        cert_subject.OU = 'kOVHernetes'
        cert_subject.CN = cn
        cert.set_issuer(self.cert.get_issuer())

        cert_ext = []
        cert_ext.append(crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert))
        cert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid,issuer', issuer=self.cert))
        cert_ext.append(crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'))
        cert_ext.append(crypto.X509Extension(b'keyUsage', True, b'nonRepudiation, digitalSignature, keyEncipherment'))
        cert_ext.append(crypto.X509Extension(b'extendedKeyUsage', True, b'clientAuth'))
        cert.add_extensions(cert_ext)

        # sign cert with CA key
        cert.sign(self.key, 'sha256')

        type(self).__next_serial += 1

        return cert 
Example #23
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_client_pair(self, o, cn):
        """Issue a X.509 client key/certificate pair"""

        # key
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)

        # cert
        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)

        cert_subject = cert.get_subject()
        cert_subject.O = o
        cert_subject.OU = 'kOVHernetes'
        cert_subject.CN = cn
        cert.set_issuer(self.cert.get_issuer())

        cert_ext = []
        cert_ext.append(crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert))
        cert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid,issuer', issuer=self.cert))
        cert_ext.append(crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'))
        cert_ext.append(crypto.X509Extension(b'keyUsage', True, b'nonRepudiation, digitalSignature, keyEncipherment'))
        cert_ext.append(crypto.X509Extension(b'extendedKeyUsage', True, b'clientAuth'))
        cert.add_extensions(cert_ext)

        # sign cert with CA key
        cert.sign(self.key, 'sha256')

        type(self).__next_serial += 1

        return key, cert 
Example #24
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # CA key
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)

        # CA cert
        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(10*365*24*60*60)

        cacert_subject = cert.get_subject()
        cacert_subject.O = 'kOVHernetes'
        cacert_subject.OU = 'kOVHernetes Certificate Authority'
        cacert_subject.CN = 'kOVHernetes Root CA'
        cert.set_issuer(cacert_subject)

        cert.add_extensions((crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert),))
        cacert_ext = []
        cacert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', True, b'keyid:always,issuer', issuer=cert))
        cacert_ext.append(crypto.X509Extension(b'basicConstraints', True, b'CA:TRUE'))
        cacert_ext.append(crypto.X509Extension(b'keyUsage', True, b'digitalSignature, cRLSign, keyCertSign'))
        cert.add_extensions(cacert_ext)

        # sign CA cert with CA key
        cert.sign(key, 'sha256')

        type(self).__next_serial += 1

        self.cert = cert
        self.key = key 
Example #25
Source File: test_ca.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_authority_key_identifier(self):
        ca = self._create_ca()
        e = ca.x509.get_extension(3)
        self.assertEqual(e.get_short_name().decode(), 'authorityKeyIdentifier')
        self.assertEqual(e.get_critical(), False)
        e2 = crypto.X509Extension(
            b'authorityKeyIdentifier',
            False,
            b'keyid:always,issuer:always',
            issuer=ca.x509,
        )
        self.assertEqual(e.get_data(), e2.get_data()) 
Example #26
Source File: test_cert.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_subject_key_identifier(self):
        cert = self._create_cert()
        e = cert.x509.get_extension(2)
        self.assertEqual(e.get_short_name().decode(), 'subjectKeyIdentifier')
        self.assertEqual(e.get_critical(), False)
        e2 = crypto.X509Extension(
            b'subjectKeyIdentifier', False, b'hash', subject=cert.x509
        )
        self.assertEqual(e.get_data(), e2.get_data()) 
Example #27
Source File: test_cert.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_authority_key_identifier(self):
        cert = self._create_cert()
        e = cert.x509.get_extension(3)
        self.assertEqual(e.get_short_name().decode(), 'authorityKeyIdentifier')
        self.assertEqual(e.get_critical(), False)
        e2 = crypto.X509Extension(
            b'authorityKeyIdentifier',
            False,
            b'keyid:always,issuer:always',
            issuer=cert.ca.x509,
        )
        self.assertEqual(e.get_data(), e2.get_data()) 
Example #28
Source File: _ca.py    From flocker with Apache License 2.0 5 votes vote down vote up
def initialize(cls, output_path, authority, username, begin=None):
        """
        Generate a certificate signed by the supplied root certificate.

        :param FilePath output_path: Directory where the certificate will be
            written.
        :param CertificateAuthority authority: The certificate authority with
            which this certificate will be signed.
        :param unicode username: A UTF-8 encoded username to be included in
            the certificate.
        :param datetime begin: The datetime from which the generated
            certificate should be valid.
        """
        key_filename = username + u".key"
        cert_filename = username + u".crt"
        # The common name for the node certificate.
        name = u"user-" + username
        # The organizational unit is set to the common name of the
        # authority, which in our case is a byte string identifying
        # the cluster.
        organizational_unit = authority.organizational_unit
        dn = DistinguishedName(
            commonName=name, organizationalUnitName=organizational_unit
        )
        keypair = flocker_keypair()
        request = keypair.keypair.requestObject(dn)
        serial = os.urandom(16).encode(b"hex")
        serial = int(serial, 16)
        cert = sign_certificate_request(
            authority.credential.keypair.keypair,
            authority.credential.certificate.original.get_subject(), request,
            serial, EXPIRY_20_YEARS, b'sha256', start=begin,
            additional_extensions=[crypto.X509Extension(
                b"extendedKeyUsage", False, b"clientAuth")])
        credential = FlockerCredential(
            path=output_path, keypair=keypair, certificate=cert
        )
        credential.write_credential_files(key_filename, cert_filename)
        instance = cls(credential=credential, username=username)
        return instance 
Example #29
Source File: certificate.py    From lecm with Apache License 2.0 4 votes vote down vote up
def _create_csr(self):
        LOG.info('[%s] Generating CSR' % self.name)
        req = crypto.X509Req()
        LOG.debug('[%s] Attaching Certificate Version to CSR: %s' %
                  (self.name, self.version))
        req.set_version(self.version)
        subject = req.get_subject()

        for (key, value) in self.subject.items():
            if value is not None:
                LOG.debug('[%s] Attaching %s to CSR: %s' %
                          (self.name, key, value))
                setattr(subject, key, value)

        LOG.info('[%s] Attaching SAN extention: %s' %
                 (self.name, self.subjectAltName))

        try:
            req.add_extensions([crypto.X509Extension(
                bytes('subjectAltName', 'utf-8'), False,
                bytes(self.subjectAltName, 'utf-8')
            )])
        except TypeError:
            req.add_extensions([crypto.X509Extension('subjectAltName', False,
                                                     self.subjectAltName)])

        LOG.debug('[%s] Loading private key: %s/private/%s.key' %
                  (self.name, self.path, self.name))
        privatekey_content = open('%s/private/%s.key' %
                                  (self.path, self.name)).read()

        privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                            privatekey_content)

        LOG.info('[%s] Signing CSR' % self.name)
        req.set_pubkey(privatekey)
        req.sign(privatekey, self.digest)

        LOG.debug('[%s] Writting CSR: %s/csr/%s.csr' %
                  (self.name, self.path, self.name))
        csr_file = open('%s/csr/%s.csr' % (self.path, self.name), 'w')
        csr_file.write((crypto.dump_certificate_request(crypto.FILETYPE_PEM,
                                                        req)).decode('utf-8'))
        csr_file.close() 
Example #30
Source File: test_ssl.py    From oss-ftp with MIT License 4 votes vote down vote up
def _create_certificate_chain():
    """
    Construct and return a chain of certificates.

        1. A new self-signed certificate authority certificate (cacert)
        2. A new intermediate certificate signed by cacert (icert)
        3. A new server certificate signed by icert (scert)
    """
    caext = X509Extension(b('basicConstraints'), False, b('CA:true'))

    # Step 1
    cakey = PKey()
    cakey.generate_key(TYPE_RSA, 512)
    cacert = X509()
    cacert.get_subject().commonName = "Authority Certificate"
    cacert.set_issuer(cacert.get_subject())
    cacert.set_pubkey(cakey)
    cacert.set_notBefore(b("20000101000000Z"))
    cacert.set_notAfter(b("20200101000000Z"))
    cacert.add_extensions([caext])
    cacert.set_serial_number(0)
    cacert.sign(cakey, "sha1")

    # Step 2
    ikey = PKey()
    ikey.generate_key(TYPE_RSA, 512)
    icert = X509()
    icert.get_subject().commonName = "Intermediate Certificate"
    icert.set_issuer(cacert.get_subject())
    icert.set_pubkey(ikey)
    icert.set_notBefore(b("20000101000000Z"))
    icert.set_notAfter(b("20200101000000Z"))
    icert.add_extensions([caext])
    icert.set_serial_number(0)
    icert.sign(cakey, "sha1")

    # Step 3
    skey = PKey()
    skey.generate_key(TYPE_RSA, 512)
    scert = X509()
    scert.get_subject().commonName = "Server Certificate"
    scert.set_issuer(icert.get_subject())
    scert.set_pubkey(skey)
    scert.set_notBefore(b("20000101000000Z"))
    scert.set_notAfter(b("20200101000000Z"))
    scert.add_extensions([
            X509Extension(b('basicConstraints'), True, b('CA:false'))])
    scert.set_serial_number(0)
    scert.sign(ikey, "sha1")

    return [(cakey, cacert), (ikey, icert), (skey, scert)]