def _certificate_matches_hostname(certificate: Certificate, server_hostname: str) -> bool: """Verify that the certificate was issued for the given hostname. """ # Extract the names from the certificate to create the properly-formatted dictionary try: cert_subject = certificate.subject except ValueError: # Cryptography could not parse the certificate https://github.com/nabla-c0d3/sslyze/issues/495 return False certificate_names = { "subject": (tuple([("commonName", name) for name in get_common_names(cert_subject)]), ), "subjectAltName": tuple([("DNS", name) for name in extract_dns_subject_alternative_names(certificate) ]), } # CertificateError is raised on failure try: match_hostname(certificate_names, server_hostname) # type: ignore return True except CertificateError: return False
def _get_name_as_short_text(name_field: x509.Name) -> str: """Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.""" # Name_field is supposed to be a Subject or an Issuer; print the CN if there is one common_names = get_common_names(name_field) if common_names: # We don't support certs with multiple CNs return common_names[0] else: # Otherwise show the whole field return name_field.rfc4514_string()
def _certificate_matches_hostname(certificate: Certificate, server_hostname: str) -> bool: """Verify that the certificate was issued for the given hostname. """ # Extract the names from the certificate to create the properly-formatted dictionary certificate_names = { "subject": (tuple([("commonName", name) for name in get_common_names(certificate.subject)]),), "subjectAltName": tuple([("DNS", name) for name in extract_dns_subject_alternative_names(certificate)]), } # CertificateError is raised on failure try: ssl.match_hostname(certificate_names, server_hostname) # type: ignore return True except CertificateError: return False
def test_get_common_names(self): assert get_common_names(certificate.subject) == ["github.com"]
def get_common_name(name_field: x509.Name) -> str: try: return get_common_names(name_field)[0] except IndexError: return name_field.rfc4514_string()