jpayne@7: """The match_hostname() function from Python 3.5, essential when using SSL.""" jpayne@7: jpayne@7: # Note: This file is under the PSF license as the code comes from the python jpayne@7: # stdlib. http://docs.python.org/3/license.html jpayne@7: # It is modified to remove commonName support. jpayne@7: jpayne@7: from __future__ import annotations jpayne@7: jpayne@7: import ipaddress jpayne@7: import re jpayne@7: import typing jpayne@7: from ipaddress import IPv4Address, IPv6Address jpayne@7: jpayne@7: if typing.TYPE_CHECKING: jpayne@7: from .ssl_ import _TYPE_PEER_CERT_RET_DICT jpayne@7: jpayne@7: __version__ = "3.5.0.1" jpayne@7: jpayne@7: jpayne@7: class CertificateError(ValueError): jpayne@7: pass jpayne@7: jpayne@7: jpayne@7: def _dnsname_match( jpayne@7: dn: typing.Any, hostname: str, max_wildcards: int = 1 jpayne@7: ) -> typing.Match[str] | None | bool: jpayne@7: """Matching according to RFC 6125, section 6.4.3 jpayne@7: jpayne@7: http://tools.ietf.org/html/rfc6125#section-6.4.3 jpayne@7: """ jpayne@7: pats = [] jpayne@7: if not dn: jpayne@7: return False jpayne@7: jpayne@7: # Ported from python3-syntax: jpayne@7: # leftmost, *remainder = dn.split(r'.') jpayne@7: parts = dn.split(r".") jpayne@7: leftmost = parts[0] jpayne@7: remainder = parts[1:] jpayne@7: jpayne@7: wildcards = leftmost.count("*") jpayne@7: if wildcards > max_wildcards: jpayne@7: # Issue #17980: avoid denials of service by refusing more jpayne@7: # than one wildcard per fragment. A survey of established jpayne@7: # policy among SSL implementations showed it to be a jpayne@7: # reasonable choice. jpayne@7: raise CertificateError( jpayne@7: "too many wildcards in certificate DNS name: " + repr(dn) jpayne@7: ) jpayne@7: jpayne@7: # speed up common case w/o wildcards jpayne@7: if not wildcards: jpayne@7: return bool(dn.lower() == hostname.lower()) jpayne@7: jpayne@7: # RFC 6125, section 6.4.3, subitem 1. jpayne@7: # The client SHOULD NOT attempt to match a presented identifier in which jpayne@7: # the wildcard character comprises a label other than the left-most label. jpayne@7: if leftmost == "*": jpayne@7: # When '*' is a fragment by itself, it matches a non-empty dotless jpayne@7: # fragment. jpayne@7: pats.append("[^.]+") jpayne@7: elif leftmost.startswith("xn--") or hostname.startswith("xn--"): jpayne@7: # RFC 6125, section 6.4.3, subitem 3. jpayne@7: # The client SHOULD NOT attempt to match a presented identifier jpayne@7: # where the wildcard character is embedded within an A-label or jpayne@7: # U-label of an internationalized domain name. jpayne@7: pats.append(re.escape(leftmost)) jpayne@7: else: jpayne@7: # Otherwise, '*' matches any dotless string, e.g. www* jpayne@7: pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) jpayne@7: jpayne@7: # add the remaining fragments, ignore any wildcards jpayne@7: for frag in remainder: jpayne@7: pats.append(re.escape(frag)) jpayne@7: jpayne@7: pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) jpayne@7: return pat.match(hostname) jpayne@7: jpayne@7: jpayne@7: def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: jpayne@7: """Exact matching of IP addresses. jpayne@7: jpayne@7: RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded jpayne@7: bytes of the IP address. An IP version 4 address is 4 octets, and an IP jpayne@7: version 6 address is 16 octets. [...] A reference identity of type IP-ID jpayne@7: matches if the address is identical to an iPAddress value of the jpayne@7: subjectAltName extension of the certificate." jpayne@7: """ jpayne@7: # OpenSSL may add a trailing newline to a subjectAltName's IP address jpayne@7: # Divergence from upstream: ipaddress can't handle byte str jpayne@7: ip = ipaddress.ip_address(ipname.rstrip()) jpayne@7: return bool(ip.packed == host_ip.packed) jpayne@7: jpayne@7: jpayne@7: def match_hostname( jpayne@7: cert: _TYPE_PEER_CERT_RET_DICT | None, jpayne@7: hostname: str, jpayne@7: hostname_checks_common_name: bool = False, jpayne@7: ) -> None: jpayne@7: """Verify that *cert* (in decoded format as returned by jpayne@7: SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 jpayne@7: rules are followed, but IP addresses are not accepted for *hostname*. jpayne@7: jpayne@7: CertificateError is raised on failure. On success, the function jpayne@7: returns nothing. jpayne@7: """ jpayne@7: if not cert: jpayne@7: raise ValueError( jpayne@7: "empty or no certificate, match_hostname needs a " jpayne@7: "SSL socket or SSL context with either " jpayne@7: "CERT_OPTIONAL or CERT_REQUIRED" jpayne@7: ) jpayne@7: try: jpayne@7: # Divergence from upstream: ipaddress can't handle byte str jpayne@7: # jpayne@7: # The ipaddress module shipped with Python < 3.9 does not support jpayne@7: # scoped IPv6 addresses so we unconditionally strip the Zone IDs for jpayne@7: # now. Once we drop support for Python 3.9 we can remove this branch. jpayne@7: if "%" in hostname: jpayne@7: host_ip = ipaddress.ip_address(hostname[: hostname.rfind("%")]) jpayne@7: else: jpayne@7: host_ip = ipaddress.ip_address(hostname) jpayne@7: jpayne@7: except ValueError: jpayne@7: # Not an IP address (common case) jpayne@7: host_ip = None jpayne@7: dnsnames = [] jpayne@7: san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) jpayne@7: key: str jpayne@7: value: str jpayne@7: for key, value in san: jpayne@7: if key == "DNS": jpayne@7: if host_ip is None and _dnsname_match(value, hostname): jpayne@7: return jpayne@7: dnsnames.append(value) jpayne@7: elif key == "IP Address": jpayne@7: if host_ip is not None and _ipaddress_match(value, host_ip): jpayne@7: return jpayne@7: dnsnames.append(value) jpayne@7: jpayne@7: # We only check 'commonName' if it's enabled and we're not verifying jpayne@7: # an IP address. IP addresses aren't valid within 'commonName'. jpayne@7: if hostname_checks_common_name and host_ip is None and not dnsnames: jpayne@7: for sub in cert.get("subject", ()): jpayne@7: for key, value in sub: jpayne@7: if key == "commonName": jpayne@7: if _dnsname_match(value, hostname): jpayne@7: return jpayne@7: dnsnames.append(value) jpayne@7: jpayne@7: if len(dnsnames) > 1: jpayne@7: raise CertificateError( jpayne@7: "hostname %r " jpayne@7: "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) jpayne@7: ) jpayne@7: elif len(dnsnames) == 1: jpayne@7: raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") jpayne@7: else: jpayne@7: raise CertificateError("no appropriate subjectAltName fields were found")