コード例 #1
0
    def _write_tls_certificate(
            self,
            port: int,  # used to avoid duplicate certs with the same IP
            certificate: Certificate,
            force: bool = True) -> Path:

        # Read
        x509 = OpenSSL.crypto.X509.from_cryptography(certificate)
        subject_components = x509.get_subject().get_components()
        common_name_as_bytes = subject_components[0][1]
        common_name_on_certificate = common_name_as_bytes.decode()
        host = common_name_on_certificate

        certificate_filepath = self.generate_certificate_filepath(host=host,
                                                                  port=port)
        certificate_already_exists = certificate_filepath.is_file()
        if force is False and certificate_already_exists:
            raise FileExistsError(
                'A TLS certificate already exists at {}.'.format(
                    certificate_filepath))

        # Write
        certificate_filepath.parent.mkdir(parents=True, exist_ok=True)
        with open(certificate_filepath, 'wb') as certificate_file:
            public_pem_bytes = certificate.public_bytes(
                self.TLS_CERTIFICATE_ENCODING)
            certificate_file.write(public_pem_bytes)

        self.log.debug(
            f"Saved TLS certificate for {host} to {certificate_filepath}")
        return certificate_filepath
コード例 #2
0
    def _write_tls_certificate(self,
                               certificate: Certificate,
                               host: str = None,
                               force: bool = True) -> str:

        # Read
        x509 = OpenSSL.crypto.X509.from_cryptography(certificate)
        subject_components = x509.get_subject().get_components()
        common_name_as_bytes = subject_components[0][1]
        common_name_on_certificate = common_name_as_bytes.decode()
        if not host:
            host = common_name_on_certificate

        try:
            pseudonym = certificate.subject.get_attributes_for_oid(
                NameOID.PSEUDONYM)[0]
        except IndexError:
            raise self.InvalidNodeCertificate(
                f"Missing checksum address on certificate for host '{host}'. "
                f"Does this certificate belong to an Ursula?")
        else:
            checksum_address = pseudonym.value

        if not is_checksum_address(checksum_address):
            raise self.InvalidNodeCertificate(
                "Invalid certificate wallet address encountered: {}".format(
                    checksum_address))

        # Validate
        # TODO: It's better for us to have checked this a while ago so that this situation is impossible.  #443
        if host and (host != common_name_on_certificate):
            raise ValueError(
                f"You passed a hostname ('{host}') that does not match the certificate's common name."
            )

        certificate_filepath = self.generate_certificate_filepath(
            checksum_address=checksum_address)
        certificate_already_exists = os.path.isfile(certificate_filepath)
        if force is False and certificate_already_exists:
            raise FileExistsError(
                'A TLS certificate already exists at {}.'.format(
                    certificate_filepath))

        # Write
        os.makedirs(os.path.dirname(certificate_filepath), exist_ok=True)
        with open(certificate_filepath, 'wb') as certificate_file:
            public_pem_bytes = certificate.public_bytes(
                self.TLS_CERTIFICATE_ENCODING)
            certificate_file.write(public_pem_bytes)

        nickname, pairs = nickname_from_seed(checksum_address)
        self.log.debug(
            f"Saved TLS certificate for {nickname} {checksum_address}: {certificate_filepath}"
        )

        return certificate_filepath
コード例 #3
0
    def getpeercert(self, binary_form=False):
        x509 = self.connection.get_peer_certificate()

        if not x509:
            return x509

        if binary_form:
            return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)

        return {
            "subject": ((("commonName", x509.get_subject().CN),),),
            "subjectAltName": get_subj_alt_name(x509),
        }
コード例 #4
0
ファイル: pyopenssl.py プロジェクト: sethmlarson/urllib3
    def getpeercert(self, binary_form: bool = False) -> Dict[str, List[Any]]:
        x509 = self.connection.get_peer_certificate()

        if not x509:
            return x509  # type: ignore[no-any-return]

        if binary_form:
            return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)  # type: ignore[no-any-return]

        return {
            "subject": ((("commonName", x509.get_subject().CN),),),  # type: ignore[dict-item]
            "subjectAltName": get_subj_alt_name(x509),
        }
コード例 #5
0
    def _write_tls_certificate(self,
                               certificate: Certificate,
                               host: str = None,
                               force: bool = True) -> str:

        # Read
        x509 = OpenSSL.crypto.X509.from_cryptography(certificate)
        subject_components = x509.get_subject().get_components()
        common_name_as_bytes = subject_components[0][1]
        common_name_on_certificate = common_name_as_bytes.decode()
        if not host:
            host = common_name_on_certificate

        pseudonym = certificate.subject.get_attributes_for_oid(
            NameOID.PSEUDONYM)[0]
        checksum_address = pseudonym.value

        if not is_checksum_address(checksum_address):  # TODO: more?
            raise RuntimeError(
                "Invalid certificate checksum address encountered: {}".format(
                    checksum_address))

        # Validate
        # TODO: It's better for us to have checked this a while ago so that this situation is impossible.  #443
        if host and (host != common_name_on_certificate):
            raise ValueError(
                'You passed a hostname ("{}") that does not match the certificat\'s common name.'
                .format(host))

        certificate_filepath = self.generate_certificate_filepath(
            checksum_address=checksum_address)
        certificate_already_exists = os.path.isfile(certificate_filepath)
        if force is False and certificate_already_exists:
            raise FileExistsError(
                'A TLS certificate already exists at {}.'.format(
                    certificate_filepath))

        # Write
        with open(certificate_filepath, 'wb') as certificate_file:
            public_pem_bytes = certificate.public_bytes(
                self.TLS_CERTIFICATE_ENCODING)
            certificate_file.write(public_pem_bytes)

        self.certificate_filepath = certificate_filepath
        self.log.info("Saved TLS certificate for {}: {}".format(
            self, certificate_filepath))

        return certificate_filepath
コード例 #6
0
ファイル: pyopenssl.py プロジェクト: BenkiKuu/pythonip3
    def getpeercert(self, binary_form=False):
        x509 = self.connection.get_peer_certificate()

        if not x509:
            return x509

        if binary_form:
            return OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_ASN1,
                x509)

        return {
            'subject': (
                (('commonName', x509.get_subject().CN),),
            ),
            'subjectAltName': get_subj_alt_name(x509)
        }
コード例 #7
0
def main():
    module = AnsibleModule(argument_spec=dict(
        ca_cert=dict(type='path'),
        host=dict(type='str', required=True),
        port=dict(type='int', required=True),
        proxy_host=dict(type='str'),
        proxy_port=dict(type='int', default=8080),
        timeout=dict(type='int', default=10),
        select_crypto_backend=dict(
            type='str',
            choices=['auto', 'pyopenssl', 'cryptography'],
            default='auto'),
    ), )

    ca_cert = module.params.get('ca_cert')
    host = module.params.get('host')
    port = module.params.get('port')
    proxy_host = module.params.get('proxy_host')
    proxy_port = module.params.get('proxy_port')
    timeout = module.params.get('timeout')

    backend = module.params.get('select_crypto_backend')
    if backend == 'auto':
        # Detection what is possible
        can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(
            MINIMAL_CRYPTOGRAPHY_VERSION)
        can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(
            MINIMAL_PYOPENSSL_VERSION)

        # First try cryptography, then pyOpenSSL
        if can_use_cryptography:
            backend = 'cryptography'
        elif can_use_pyopenssl:
            backend = 'pyopenssl'

        # Success?
        if backend == 'auto':
            module.fail_json(msg=(
                "Can't detect any of the required Python libraries "
                "cryptography (>= {0}) or PyOpenSSL (>= {1})"
            ).format(MINIMAL_CRYPTOGRAPHY_VERSION, MINIMAL_PYOPENSSL_VERSION))

    if backend == 'pyopenssl':
        if not PYOPENSSL_FOUND:
            module.fail_json(msg=missing_required_lib(
                'pyOpenSSL >= {0}'.format(MINIMAL_PYOPENSSL_VERSION)),
                             exception=PYOPENSSL_IMP_ERR)
        module.deprecate(
            'The module is using the PyOpenSSL backend. This backend has been deprecated',
            version='2.13')
    elif backend == 'cryptography':
        if not CRYPTOGRAPHY_FOUND:
            module.fail_json(msg=missing_required_lib(
                'cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION)),
                             exception=CRYPTOGRAPHY_IMP_ERR)

    result = dict(changed=False, )

    if not PYOPENSSL_FOUND:
        module.fail_json(msg=missing_required_lib('pyOpenSSL >= 0.15'),
                         exception=PYOPENSSL_IMP_ERR)

    if timeout:
        setdefaulttimeout(timeout)

    if ca_cert:
        if not isfile(ca_cert):
            module.fail_json(msg="ca_cert file does not exist")

    if proxy_host:
        if not HAS_CREATE_DEFAULT_CONTEXT:
            module.fail_json(
                msg=
                'To use proxy_host, you must run the get_certificate module with Python 2.7 or newer.',
                exception=CREATE_DEFAULT_CONTEXT_IMP_ERR)

        try:
            connect = "CONNECT %s:%s HTTP/1.0\r\n\r\n" % (host, port)
            sock = socket()
            atexit.register(sock.close)
            sock.connect((proxy_host, proxy_port))
            sock.send(connect.encode())
            sock.recv(8192)

            ctx = create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = CERT_NONE

            if ca_cert:
                ctx.verify_mode = CERT_OPTIONAL
                ctx.load_verify_locations(cafile=ca_cert)

            cert = ctx.wrap_socket(sock,
                                   server_hostname=host).getpeercert(True)
            cert = DER_cert_to_PEM_cert(cert)
        except Exception as e:
            module.fail_json(
                msg="Failed to get cert from port with error: {0}".format(e))

    else:
        try:
            cert = get_server_certificate((host, port), ca_certs=ca_cert)
        except Exception as e:
            module.fail_json(
                msg="Failed to get cert from port with error: {0}".format(e))

    result['cert'] = cert

    if backend == 'pyopenssl':
        x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
        result['subject'] = {}
        for component in x509.get_subject().get_components():
            result['subject'][component[0]] = component[1]

        result['expired'] = x509.has_expired()

        result['extensions'] = []
        extension_count = x509.get_extension_count()
        for index in range(0, extension_count):
            extension = x509.get_extension(index)
            result['extensions'].append({
                'critical': extension.get_critical(),
                'asn1_data': extension.get_data(),
                'name': extension.get_short_name(),
            })

        result['issuer'] = {}
        for component in x509.get_issuer().get_components():
            result['issuer'][component[0]] = component[1]

        result['not_after'] = x509.get_notAfter()
        result['not_before'] = x509.get_notBefore()

        result['serial_number'] = x509.get_serial_number()
        result['signature_algorithm'] = x509.get_signature_algorithm()

        result['version'] = x509.get_version()

    elif backend == 'cryptography':
        x509 = cryptography.x509.load_pem_x509_certificate(
            to_bytes(cert), cryptography_backend())
        result['subject'] = {}
        for attribute in x509.subject:
            result['subject'][crypto_utils.cryptography_oid_to_name(
                attribute.oid, short=True)] = attribute.value

        result['expired'] = x509.not_valid_after < datetime.datetime.utcnow()

        result['extensions'] = []
        for dotted_number, entry in crypto_utils.cryptography_get_extensions_from_cert(
                x509).items():
            oid = cryptography.x509.oid.ObjectIdentifier(dotted_number)
            result['extensions'].append({
                'critical':
                entry['critical'],
                'asn1_data':
                base64.b64decode(entry['value']),
                'name':
                crypto_utils.cryptography_oid_to_name(oid, short=True),
            })

        result['issuer'] = {}
        for attribute in x509.issuer:
            result['issuer'][crypto_utils.cryptography_oid_to_name(
                attribute.oid, short=True)] = attribute.value

        result['not_after'] = x509.not_valid_after.strftime('%Y%m%d%H%M%SZ')
        result['not_before'] = x509.not_valid_before.strftime('%Y%m%d%H%M%SZ')

        result['serial_number'] = x509.serial_number
        result['signature_algorithm'] = crypto_utils.cryptography_oid_to_name(
            x509.signature_algorithm_oid)

        # We need the -1 offset to get the same values as pyOpenSSL
        if x509.version == cryptography.x509.Version.v1:
            result['version'] = 1 - 1
        elif x509.version == cryptography.x509.Version.v3:
            result['version'] = 3 - 1
        else:
            result['version'] = "unknown"

    module.exit_json(**result)
コード例 #8
0
ファイル: storages.py プロジェクト: arifkalayci/nucypher
 def _read_common_name(self, certificate: Certificate):
     x509 = OpenSSL.crypto.X509.from_cryptography(certificate)
     subject_components = x509.get_subject().get_components()
     common_name_as_bytes = subject_components[0][1]
     common_name_from_cert = common_name_as_bytes.decode()
     return common_name_from_cert
コード例 #9
0
                return
        else:
            self._makefile_refs -= 1

    def getpeercert(self, binary_form=False):
        x509 = self.connection.get_peer_certificate()

        if not x509:
            return x509

        if binary_form:
<<<<<<< HEAD
            return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)

        return {
            "subject": ((("commonName", x509.get_subject().CN),),),
            "subjectAltName": get_subj_alt_name(x509),
        }

    def version(self):
        return self.connection.get_protocol_version_name()

=======
            return OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_ASN1,
                x509)

        return {
            'subject': (
                (('commonName', x509.get_subject().CN),),
            ),