Python cryptography.x509.ExtensionNotFound() Examples
The following are 30
code examples of cryptography.x509.ExtensionNotFound().
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
cryptography.x509
, or try the search function
.
Example #1
Source File: _certificate_utils.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
def extract_dns_subject_alternative_names(certificate: x509.Certificate) -> List[str]: """Retrieve all the DNS entries of the Subject Alternative Name extension. """ subj_alt_names: List[str] = [] try: san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME) san_ext_value = cast(x509.SubjectAlternativeName, san_ext.value) subj_alt_names = san_ext_value.get_values_for_type(DNSName) except ExtensionNotFound: pass except DuplicateExtension: # Fix for https://github.com/nabla-c0d3/sslyze/issues/420 # Not sure how browsers behave in this case but having a duplicate extension makes the certificate invalid # so we just return no SANs (likely to make hostname validation fail, which is fine) pass return subj_alt_names
Example #2
Source File: defaults.py From lemur with Apache License 2.0 | 6 votes |
def domains(cert): """ Attempts to get an domains listed in a certificate. If 'subjectAltName' extension is not available we simply return the common name. :param cert: :return: List of domains """ domains = [] try: ext = cert.extensions.get_extension_for_oid(x509.OID_SUBJECT_ALTERNATIVE_NAME) entries = ext.value.get_values_for_type(x509.DNSName) for entry in entries: domains.append(entry) except x509.ExtensionNotFound: if current_app.config.get("LOG_SSL_SUBJ_ALT_NAME_ERRORS", True): sentry.captureException() except Exception as e: sentry.captureException() return domains
Example #3
Source File: test_certificates.py From lemur with Apache License 2.0 | 6 votes |
def test_csr_empty_san(client): """Test that an empty "names" list does not produce a CSR with empty SubjectAltNames extension. The Lemur UI always submits this extension even when no alt names are defined. """ csr_text, pkey = create_csr( common_name="daniel-san.example.com", owner="daniel-san@example.com", key_type="RSA2048", extensions={"sub_alt_names": {"names": x509.SubjectAlternativeName([])}}, ) csr = x509.load_pem_x509_csr(csr_text.encode("utf-8"), default_backend()) with pytest.raises(x509.ExtensionNotFound): csr.extensions.get_extension_for_class(x509.SubjectAlternativeName)
Example #4
Source File: utils.py From lemur with Apache License 2.0 | 6 votes |
def get_sans_from_csr(data): """ Fetches SubjectAlternativeNames from CSR. Works with any kind of SubjectAlternativeName :param data: PEM-encoded string with CSR :return: List of LemurAPI-compatible subAltNames """ sub_alt_names = [] try: request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend()) except Exception: raise ValidationError("CSR presented is not valid.") try: alt_names = request.extensions.get_extension_for_class( x509.SubjectAlternativeName ) for alt_name in alt_names.value: sub_alt_names.append( {"nameType": type(alt_name).__name__, "value": alt_name.value} ) except x509.ExtensionNotFound: pass return sub_alt_names
Example #5
Source File: models.py From django-ca with GNU General Public License v3.0 | 6 votes |
def precertificate_signed_certificate_timestamps(self): try: ext = self.x509.extensions.get_extension_for_oid( ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS) except x509.ExtensionNotFound: return None if isinstance(ext.value, x509.UnrecognizedExtension): # Older versions of OpenSSL (and LibreSSL) cannot parse this extension # see https://github.com/pyca/cryptography/blob/master/tests/x509/test_x509_ext.py#L4455-L4459 return UnrecognizedExtension( ext, name=get_extension_name(ext), error='Requires OpenSSL 1.1.0f or later') else: # pragma: only SCT return PrecertificateSignedCertificateTimestamps(ext)
Example #6
Source File: tests_extensions.py From django-ca with GNU General Public License v3.0 | 6 votes |
def test_certs(self): self.load_all_cas() self.load_all_certs() for name, cert in list(self.cas.items()) + list(self.certs.items()): try: val = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value except x509.ExtensionNotFound: continue for policy in val: pi = PolicyInformation(policy) self.assertEqual(pi.for_extension_type, policy) # pass the serialized value to the constructor and see if it's still the same pi2 = PolicyInformation(pi.serialize()) self.assertEqual(pi, pi2) self.assertEqual(pi.serialize(), pi2.serialize()) self.assertEqual(pi2.for_extension_type, policy)
Example #7
Source File: recreate-fixtures.py From django-ca with GNU General Public License v3.0 | 5 votes |
def update_contrib(data, cert, name, filename): cert_data = { 'name': name, 'cn': cert.cn, 'cat': 'sphinx-contrib', 'pub_filename': filename, 'key_filename': False, 'csr_filename': False, 'valid_from': parsed.not_valid_before.strftime(_timeformat), 'valid_until': parsed.not_valid_after.strftime(_timeformat), 'serial': cert.serial, 'subject': cert.distinguishedName(), 'hpkp': cert.hpkp_pin, 'md5': cert.get_digest('md5'), 'sha1': cert.get_digest('sha1'), 'sha256': cert.get_digest('sha256'), 'sha512': cert.get_digest('sha512'), } for ext in cert.extensions: if isinstance(ext, Extension): key = OID_TO_EXTENSION[ext.oid].key cert_data[key] = ext.serialize() elif isinstance(ext, tuple): print('### get extension tuple!!!') key, value = ext if isinstance(value[1], x509.ObjectIdentifier): # Currently just some old StartSSL extensions for Netscape (!) continue else: cert_data[key] = value try: ext = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value cert_data['policy_texts'] = [PolicyInformation(p).as_text() for p in ext] except x509.ExtensionNotFound: pass data[name] = cert_data
Example #8
Source File: utils.py From zentral with Apache License 2.0 | 5 votes |
def is_ca(certificate): # TODO: test self signed if no extensions found extensions = certificate.extensions try: return extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS).value.ca except x509.ExtensionNotFound: try: return extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE).value.key_cert_sign except x509.ExtensionNotFound: pass return False
Example #9
Source File: utils.py From PyKMIP with Apache License 2.0 | 5 votes |
def get_extended_key_usage_from_certificate(certificate): """ Given an X.509 certificate, extract and return the extendedKeyUsage extension. """ try: return certificate.extensions.get_extension_for_oid( x509.oid.ExtensionOID.EXTENDED_KEY_USAGE ).value except x509.ExtensionNotFound: return None
Example #10
Source File: validators.py From lemur with Apache License 2.0 | 5 votes |
def csr(data): """ Determines if the CSR is valid and allowed. :param data: :return: """ try: request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend()) except Exception: raise ValidationError("CSR presented is not valid.") # Validate common name and SubjectAltNames try: for name in request.subject.get_attributes_for_oid(NameOID.COMMON_NAME): common_name(name.value) except ValueError as err: current_app.logger.info("Error parsing Subject from CSR: %s", err) raise ValidationError("Invalid Subject value in supplied CSR") try: alt_names = request.extensions.get_extension_for_class( x509.SubjectAlternativeName ) for name in alt_names.value.get_values_for_type(x509.DNSName): sensitive_domain(name) except x509.ExtensionNotFound: pass
Example #11
Source File: models.py From django-ca with GNU General Public License v3.0 | 5 votes |
def get_authority_key_identifier(self): """Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.""" try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.public_key()) else: return x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski.value)
Example #12
Source File: models.py From django-ca with GNU General Public License v3.0 | 5 votes |
def pathlen(self): """The ``pathlen`` attribute of the ``BasicConstraints`` extension (either an ``int`` or ``None``).""" try: ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS) except x509.ExtensionNotFound: # pragma: no cover - extension should always be present return None return ext.value.path_length
Example #13
Source File: tests_extensions.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_as_text(self): self.assertEqual(self.pi1.as_text(), 'Policy Identifier: 2.5.29.32.0\n' 'Policy Qualifiers:\n* text1') self.assertEqual(self.pi2.as_text(), 'Policy Identifier: 2.5.29.32.0\n' 'Policy Qualifiers:\n' '* UserNotice:\n' ' * Explicit text: text2') self.assertEqual(self.pi3.as_text(), 'Policy Identifier: 2.5.29.32.0\n' 'Policy Qualifiers:\n' '* UserNotice:\n' ' * Reference:\n' ' * Organiziation: text3\n' ' * Notice Numbers: [1]') self.assertEqual(self.pi4.as_text(), 'Policy Identifier: 2.5.29.32.0\n' 'Policy Qualifiers:\n' '* text4\n' '* UserNotice:\n' ' * Explicit text: text5\n' ' * Reference:\n' ' * Organiziation: text6\n' ' * Notice Numbers: [1, 2, 3]') self.assertEqual(self.pi_empty.as_text(), 'Policy Identifier: None\nNo Policy Qualifiers') self.load_all_cas() self.load_all_certs() for name, cert in list(self.cas.items()) + list(self.certs.items()): try: ext = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value except x509.ExtensionNotFound: continue for index, policy in enumerate(ext): pi = PolicyInformation(policy) self.assertEqual(pi.as_text(), certs[name]['policy_texts'][index])
Example #14
Source File: cert_parser.py From octavia with Apache License 2.0 | 5 votes |
def get_host_names(certificate): """Extract the host names from the Pem encoded X509 certificate :param certificate: A PEM encoded certificate :returns: A dictionary containing the following keys: ['cn', 'dns_names'] where 'cn' is the CN from the SubjectName of the certificate, and 'dns_names' is a list of dNSNames (possibly empty) from the SubjectAltNames of the certificate. """ if isinstance(certificate, str): certificate = certificate.encode('utf-8') try: cert = x509.load_pem_x509_certificate(certificate, backends.default_backend()) cn = cert.subject.get_attributes_for_oid(x509.OID_COMMON_NAME)[0] host_names = { 'cn': cn.value.lower(), 'dns_names': [] } try: ext = cert.extensions.get_extension_for_oid( x509.OID_SUBJECT_ALTERNATIVE_NAME ) host_names['dns_names'] = ext.value.get_values_for_type( x509.DNSName) except x509.ExtensionNotFound: LOG.debug("%s extension not found", x509.OID_SUBJECT_ALTERNATIVE_NAME) return host_names except Exception: LOG.exception('Unreadable Certificate.') raise exceptions.UnreadableCert
Example #15
Source File: tests_models.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_get_authority_key_identifier(self): for name, ca in self.cas.items(): self.assertEqual(ca.get_authority_key_identifier().key_identifier, certs[name]['subject_key_identifier'].value) # All CAs have a subject key identifier, so we mock that this exception is not present def side_effect(cls): raise x509.ExtensionNotFound('mocked', x509.SubjectKeyIdentifier.oid) ca = self.cas['child'] with mock.patch('cryptography.x509.extensions.Extensions.get_extension_for_class', side_effect=side_effect): self.assertEqual(ca.get_authority_key_identifier().key_identifier, certs['child']['subject_key_identifier'].value)
Example #16
Source File: pyopenssl.py From luci-py with Apache License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #17
Source File: pyopenssl.py From CudaText with Mozilla Public License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #18
Source File: pyopenssl.py From CudaText with Mozilla Public License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #19
Source File: pyopenssl.py From googletranslate.popclipext with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, x509.UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #20
Source File: pyopenssl.py From scalyr-agent-2 with Apache License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. # This is technically using private APIs, but should work across all # relevant versions until PyOpenSSL gets something proper for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, x509.UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #21
Source File: verify.py From lemur with Apache License 2.0 | 4 votes |
def crl_verify(cert, cert_path): """ Attempts to verify a certificate using CRL. :param cert: :param cert_path: :return: True if certificate is valid, False otherwise :raise Exception: If certificate does not have CRL """ try: distribution_points = cert.extensions.get_extension_for_oid( x509.OID_CRL_DISTRIBUTION_POINTS ).value except x509.ExtensionNotFound: current_app.logger.debug( "No CRLDP extension in certificate {}".format(cert.serial_number) ) return None for p in distribution_points: point = p.full_name[0].value if point not in crl_cache: current_app.logger.debug("Retrieving CRL: {}".format(point)) try: response = requests.get(point) if response.status_code != 200: raise Exception("Unable to retrieve CRL: {0}".format(point)) except InvalidSchema: # Unhandled URI scheme (like ldap://); skip this distribution point. continue except ConnectionError: raise Exception("Unable to retrieve CRL: {0}".format(point)) crl_cache[point] = x509.load_der_x509_crl( response.content, backend=default_backend() ) else: current_app.logger.debug("CRL point is cached {}".format(point)) for r in crl_cache[point]: if cert.serial_number == r.serial_number: try: reason = r.extensions.get_extension_for_class(x509.CRLReason).value # Handle "removeFromCRL" revoke reason as unrevoked; # continue with the next distribution point. # Per RFC 5280 section 6.3.3 (k): # https://tools.ietf.org/html/rfc5280#section-6.3.3 if reason == x509.ReasonFlags.remove_from_crl: break except x509.ExtensionNotFound: pass current_app.logger.debug( "CRL reports certificate " "revoked: {}".format(cert.serial_number) ) return False return True
Example #22
Source File: pyopenssl.py From Hands-On-Application-Development-with-PyCharm with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #23
Source File: pyopenssl.py From script.elementum.burst with Do What The F*ck You Want To Public License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #24
Source File: pyopenssl.py From stopstalk-deployment with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #25
Source File: pyopenssl.py From bash-lambda-layer with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #26
Source File: pyopenssl.py From learn_python3_spider with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #27
Source File: pyopenssl.py From scylla with Apache License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #28
Source File: pyopenssl.py From Ansible with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, x509.UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #29
Source File: pyopenssl.py From telegram-robot-rss with Mozilla Public License 2.0 | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. # This is technically using private APIs, but should work across all # relevant versions until PyOpenSSL gets something proper for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, x509.UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
Example #30
Source File: pyopenssl.py From cronyo with MIT License | 4 votes |
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names