Ejemplo n.º 1
0
def parse_crl_distribution_points(module, crl_distribution_points):
    result = []
    for index, parse_crl_distribution_point in enumerate(
            crl_distribution_points):
        try:
            params = dict(
                full_name=None,
                relative_name=None,
                crl_issuer=None,
                reasons=None,
            )
            if parse_crl_distribution_point['full_name'] is not None:
                params['full_name'] = [
                    cryptography_get_name(name, 'full name')
                    for name in parse_crl_distribution_point['full_name']
                ]
            if parse_crl_distribution_point['relative_name'] is not None:
                try:
                    params[
                        'relative_name'] = cryptography_parse_relative_distinguished_name(
                            parse_crl_distribution_point['relative_name'])
                except Exception:
                    # If cryptography's version is < 1.6, the error is probably caused by that
                    if CRYPTOGRAPHY_VERSION < LooseVersion('1.6'):
                        raise OpenSSLObjectError(
                            'Cannot specify relative_name for cryptography < 1.6'
                        )
                    raise
            if parse_crl_distribution_point['crl_issuer'] is not None:
                params['crl_issuer'] = [
                    cryptography_get_name(name, 'CRL issuer')
                    for name in parse_crl_distribution_point['crl_issuer']
                ]
            if parse_crl_distribution_point['reasons'] is not None:
                reasons = []
                for reason in parse_crl_distribution_point['reasons']:
                    reasons.append(REVOCATION_REASON_MAP[reason])
                params['reasons'] = frozenset(reasons)
            result.append(cryptography.x509.DistributionPoint(**params))
        except OpenSSLObjectError as e:
            raise OpenSSLObjectError(
                'Error while parsing CRL distribution point #{index}: {error}'.
                format(index=index, error=e))
    return result
Ejemplo n.º 2
0
    def run(self):

        result = dict()

        try:
            with open(self.path, "rb") as f:
                _in = f.read()

            private_key = load_privatekey(
                path=self.privatekey_path,
                content=self.privatekey_content,
                passphrase=self.privatekey_passphrase,
                backend=self.backend,
            )

            signature = OpenSSL.crypto.sign(private_key, _in, "sha256")
            result['signature'] = base64.b64encode(signature)
            return result
        except Exception as e:
            raise OpenSSLObjectError(e)
Ejemplo n.º 3
0
    def run(self):

        result = dict()

        try:
            with open(self.path, "rb") as f:
                _in = f.read()

            _signature = base64.b64decode(self.signature)
            certificate = load_certificate(
                path=self.certificate_path,
                content=self.certificate_content,
                backend=self.backend,
            )

            try:
                OpenSSL.crypto.verify(certificate, _signature, _in, 'sha256')
                result['valid'] = True
            except Exception:
                result['valid'] = False
            return result
        except Exception as e:
            raise OpenSSLObjectError(e)
Ejemplo n.º 4
0
    def run(self):
        _padding = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15()
        _hash = cryptography.hazmat.primitives.hashes.SHA256()

        result = dict()

        try:
            with open(self.path, "rb") as f:
                _in = f.read()

            _signature = base64.b64decode(self.signature)
            certificate = load_certificate(
                path=self.certificate_path,
                content=self.certificate_content,
                backend=self.backend,
            )
            public_key = certificate.public_key()
            verified = False
            valid = False

            if CRYPTOGRAPHY_HAS_DSA_SIGN:
                try:
                    if isinstance(
                            public_key, cryptography.hazmat.primitives.
                            asymmetric.dsa.DSAPublicKey):
                        public_key.verify(_signature, _in, _hash)
                        verified = True
                        valid = True
                except cryptography.exceptions.InvalidSignature:
                    verified = True
                    valid = False

            if CRYPTOGRAPHY_HAS_EC_SIGN:
                try:
                    if isinstance(
                            public_key, cryptography.hazmat.primitives.
                            asymmetric.ec.EllipticCurvePublicKey):
                        public_key.verify(
                            _signature, _in,
                            cryptography.hazmat.primitives.asymmetric.ec.ECDSA(
                                _hash))
                        verified = True
                        valid = True
                except cryptography.exceptions.InvalidSignature:
                    verified = True
                    valid = False

            if CRYPTOGRAPHY_HAS_ED25519_SIGN:
                try:
                    if isinstance(
                            public_key, cryptography.hazmat.primitives.
                            asymmetric.ed25519.Ed25519PublicKey):
                        public_key.verify(_signature, _in)
                        verified = True
                        valid = True
                except cryptography.exceptions.InvalidSignature:
                    verified = True
                    valid = False

            if CRYPTOGRAPHY_HAS_ED448_SIGN:
                try:
                    if isinstance(
                            public_key, cryptography.hazmat.primitives.
                            asymmetric.ed448.Ed448PublicKey):
                        public_key.verify(_signature, _in)
                        verified = True
                        valid = True
                except cryptography.exceptions.InvalidSignature:
                    verified = True
                    valid = False

            if CRYPTOGRAPHY_HAS_RSA_SIGN:
                try:
                    if isinstance(
                            public_key, cryptography.hazmat.primitives.
                            asymmetric.rsa.RSAPublicKey):
                        public_key.verify(_signature, _in, _padding, _hash)
                        verified = True
                        valid = True
                except cryptography.exceptions.InvalidSignature:
                    verified = True
                    valid = False

            if not verified:
                self.module.fail_json(
                    msg="Unsupported key type. Your cryptography version is {0}"
                    .format(CRYPTOGRAPHY_VERSION))
            result['valid'] = valid
            return result

        except Exception as e:
            raise OpenSSLObjectError(e)
Ejemplo n.º 5
0
    def generate_csr(self):
        """(Re-)Generate CSR."""
        self._ensure_private_key_loaded()

        csr = cryptography.x509.CertificateSigningRequestBuilder()
        try:
            csr = csr.subject_name(
                cryptography.x509.Name([
                    cryptography.x509.NameAttribute(
                        cryptography_name_to_oid(entry[0]), to_text(entry[1]))
                    for entry in self.subject
                ]))
        except ValueError as e:
            raise CertificateSigningRequestError(e)

        if self.subjectAltName:
            csr = csr.add_extension(cryptography.x509.SubjectAlternativeName(
                [cryptography_get_name(name) for name in self.subjectAltName]),
                                    critical=self.subjectAltName_critical)

        if self.keyUsage:
            params = cryptography_parse_key_usage_params(self.keyUsage)
            csr = csr.add_extension(cryptography.x509.KeyUsage(**params),
                                    critical=self.keyUsage_critical)

        if self.extendedKeyUsage:
            usages = [
                cryptography_name_to_oid(usage)
                for usage in self.extendedKeyUsage
            ]
            csr = csr.add_extension(cryptography.x509.ExtendedKeyUsage(usages),
                                    critical=self.extendedKeyUsage_critical)

        if self.basicConstraints:
            params = {}
            ca, path_length = cryptography_get_basic_constraints(
                self.basicConstraints)
            csr = csr.add_extension(cryptography.x509.BasicConstraints(
                ca, path_length),
                                    critical=self.basicConstraints_critical)

        if self.ocspMustStaple:
            try:
                # This only works with cryptography >= 2.1
                csr = csr.add_extension(cryptography.x509.TLSFeature(
                    [cryptography.x509.TLSFeatureType.status_request]),
                                        critical=self.ocspMustStaple_critical)
            except AttributeError as dummy:
                csr = csr.add_extension(
                    cryptography.x509.UnrecognizedExtension(
                        CRYPTOGRAPHY_MUST_STAPLE_NAME,
                        CRYPTOGRAPHY_MUST_STAPLE_VALUE),
                    critical=self.ocspMustStaple_critical)

        if self.name_constraints_permitted or self.name_constraints_excluded:
            try:
                csr = csr.add_extension(
                    cryptography.x509.NameConstraints(
                        [
                            cryptography_get_name(
                                name, 'name constraints permitted')
                            for name in self.name_constraints_permitted
                        ],
                        [
                            cryptography_get_name(name,
                                                  'name constraints excluded')
                            for name in self.name_constraints_excluded
                        ],
                    ),
                    critical=self.name_constraints_critical)
            except TypeError as e:
                raise OpenSSLObjectError(
                    'Error while parsing name constraint: {0}'.format(e))

        if self.create_subject_key_identifier:
            csr = csr.add_extension(
                cryptography.x509.SubjectKeyIdentifier.from_public_key(
                    self.privatekey.public_key()),
                critical=False)
        elif self.subject_key_identifier is not None:
            csr = csr.add_extension(cryptography.x509.SubjectKeyIdentifier(
                self.subject_key_identifier),
                                    critical=False)

        if self.authority_key_identifier is not None or self.authority_cert_issuer is not None or self.authority_cert_serial_number is not None:
            issuers = None
            if self.authority_cert_issuer is not None:
                issuers = [
                    cryptography_get_name(n, 'authority cert issuer')
                    for n in self.authority_cert_issuer
                ]
            csr = csr.add_extension(cryptography.x509.AuthorityKeyIdentifier(
                self.authority_key_identifier, issuers,
                self.authority_cert_serial_number),
                                    critical=False)

        if self.crl_distribution_points:
            csr = csr.add_extension(cryptography.x509.CRLDistributionPoints(
                self.crl_distribution_points),
                                    critical=False)

        digest = None
        if cryptography_key_needs_digest_for_signing(self.privatekey):
            digest = select_message_digest(self.digest)
            if digest is None:
                raise CertificateSigningRequestError(
                    'Unsupported digest "{0}"'.format(self.digest))
        try:
            self.csr = csr.sign(self.privatekey, digest,
                                self.cryptography_backend)
        except TypeError as e:
            if str(
                    e
            ) == 'Algorithm must be a registered hash algorithm.' and digest is None:
                self.module.fail_json(
                    msg=
                    'Signing with Ed25519 and Ed448 keys requires cryptography 2.8 or newer.'
                )
            raise
        except UnicodeError as e:
            # This catches IDNAErrors, which happens when a bad name is passed as a SAN
            # (https://github.com/ansible-collections/community.crypto/issues/105).
            # For older cryptography versions, this is handled by idna, which raises
            # an idna.core.IDNAError. Later versions of cryptography deprecated and stopped
            # requiring idna, whence we cannot easily handle this error. Fortunately, in
            # most versions of idna, IDNAError extends UnicodeError. There is only version
            # 2.3 where it extends Exception instead (see
            # https://github.com/kjd/idna/commit/ebefacd3134d0f5da4745878620a6a1cba86d130
            # and then
            # https://github.com/kjd/idna/commit/ea03c7b5db7d2a99af082e0239da2b68aeea702a).
            msg = 'Error while creating CSR: {0}\n'.format(e)
            if self.using_common_name_for_san:
                self.module.fail_json(
                    msg=msg +
                    'This is probably caused because the Common Name is used as a SAN.'
                    ' Specifying use_common_name_for_san=false might fix this.'
                )
            self.module.fail_json(
                msg=msg +
                'This is probably caused by an invalid Subject Alternative DNS Name.'
            )
Ejemplo n.º 6
0
    def run(self):
        _padding = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15()
        _hash = cryptography.hazmat.primitives.hashes.SHA256()

        result = dict()

        try:
            with open(self.path, "rb") as f:
                _in = f.read()

            private_key = load_privatekey(
                path=self.privatekey_path,
                content=self.privatekey_content,
                passphrase=self.privatekey_passphrase,
                backend=self.backend,
            )

            signature = None

            if CRYPTOGRAPHY_HAS_DSA_SIGN:
                if isinstance(
                        private_key, cryptography.hazmat.primitives.asymmetric.
                        dsa.DSAPrivateKey):
                    signature = private_key.sign(_in, _hash)

            if CRYPTOGRAPHY_HAS_EC_SIGN:
                if isinstance(
                        private_key, cryptography.hazmat.primitives.asymmetric.
                        ec.EllipticCurvePrivateKey):
                    signature = private_key.sign(
                        _in,
                        cryptography.hazmat.primitives.asymmetric.ec.ECDSA(
                            _hash))

            if CRYPTOGRAPHY_HAS_ED25519_SIGN:
                if isinstance(
                        private_key, cryptography.hazmat.primitives.asymmetric.
                        ed25519.Ed25519PrivateKey):
                    signature = private_key.sign(_in)

            if CRYPTOGRAPHY_HAS_ED448_SIGN:
                if isinstance(
                        private_key, cryptography.hazmat.primitives.asymmetric.
                        ed448.Ed448PrivateKey):
                    signature = private_key.sign(_in)

            if CRYPTOGRAPHY_HAS_RSA_SIGN:
                if isinstance(
                        private_key, cryptography.hazmat.primitives.asymmetric.
                        rsa.RSAPrivateKey):
                    signature = private_key.sign(_in, _padding, _hash)

            if signature is None:
                self.module.fail_json(
                    msg="Unsupported key type. Your cryptography version is {0}"
                    .format(CRYPTOGRAPHY_VERSION))

            result['signature'] = base64.b64encode(signature)
            return result

        except Exception as e:
            raise OpenSSLObjectError(e)