1dd950c489607d06ecc5218292a1b55558b47be8
[SubU] /
1 """The match_hostname() function from Python 3.3.3, essential when using SSL."""
2
3 # Note: This file is under the PSF license as the code comes from the python
4 # stdlib.   http://docs.python.org/3/license.html
5
6 import re
7 import sys
8
9 # ipaddress has been backported to 2.6+ in pypi.  If it is installed on the
10 # system, use it to handle IPAddress ServerAltnames (this was added in
11 # python-3.5) otherwise only do DNS matching.  This allows
12 # util.ssl_match_hostname to continue to be used in Python 2.7.
13 try:
14     import ipaddress
15 except ImportError:
16     ipaddress = None
17
18 __version__ = "3.5.0.1"
19
20
21 class CertificateError(ValueError):
22     pass
23
24
25 def _dnsname_match(dn, hostname, max_wildcards=1):
26     """Matching according to RFC 6125, section 6.4.3
27
28     http://tools.ietf.org/html/rfc6125#section-6.4.3
29     """
30     pats = []
31     if not dn:
32         return False
33
34     # Ported from python3-syntax:
35     # leftmost, *remainder = dn.split(r'.')
36     parts = dn.split(r".")
37     leftmost = parts[0]
38     remainder = parts[1:]
39
40     wildcards = leftmost.count("*")
41     if wildcards > max_wildcards:
42         # Issue #17980: avoid denials of service by refusing more
43         # than one wildcard per fragment.  A survey of established
44         # policy among SSL implementations showed it to be a
45         # reasonable choice.
46         raise CertificateError(
47             "too many wildcards in certificate DNS name: " + repr(dn)
48         )
49
50     # speed up common case w/o wildcards
51     if not wildcards:
52         return dn.lower() == hostname.lower()
53
54     # RFC 6125, section 6.4.3, subitem 1.
55     # The client SHOULD NOT attempt to match a presented identifier in which
56     # the wildcard character comprises a label other than the left-most label.
57     if leftmost == "*":
58         # When '*' is a fragment by itself, it matches a non-empty dotless
59         # fragment.
60         pats.append("[^.]+")
61     elif leftmost.startswith("xn--") or hostname.startswith("xn--"):
62         # RFC 6125, section 6.4.3, subitem 3.
63         # The client SHOULD NOT attempt to match a presented identifier
64         # where the wildcard character is embedded within an A-label or
65         # U-label of an internationalized domain name.
66         pats.append(re.escape(leftmost))
67     else:
68         # Otherwise, '*' matches any dotless string, e.g. www*
69         pats.append(re.escape(leftmost).replace(r"\*", "[^.]*"))
70
71     # add the remaining fragments, ignore any wildcards
72     for frag in remainder:
73         pats.append(re.escape(frag))
74
75     pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE)
76     return pat.match(hostname)
77
78
79 def _to_unicode(obj):
80     if isinstance(obj, str) and sys.version_info < (3,):
81         # ignored flake8 # F821 to support python 2.7 function
82         obj = unicode(obj, encoding="ascii", errors="strict")  # noqa: F821
83     return obj
84
85
86 def _ipaddress_match(ipname, host_ip):
87     """Exact matching of IP addresses.
88
89     RFC 6125 explicitly doesn't define an algorithm for this
90     (section 1.7.2 - "Out of Scope").
91     """
92     # OpenSSL may add a trailing newline to a subjectAltName's IP address
93     # Divergence from upstream: ipaddress can't handle byte str
94     ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
95     return ip == host_ip
96
97
98 def match_hostname(cert, hostname):
99     """Verify that *cert* (in decoded format as returned by
100     SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125
101     rules are followed, but IP addresses are not accepted for *hostname*.
102
103     CertificateError is raised on failure. On success, the function
104     returns nothing.
105     """
106     if not cert:
107         raise ValueError(
108             "empty or no certificate, match_hostname needs a "
109             "SSL socket or SSL context with either "
110             "CERT_OPTIONAL or CERT_REQUIRED"
111         )
112     try:
113         # Divergence from upstream: ipaddress can't handle byte str
114         host_ip = ipaddress.ip_address(_to_unicode(hostname))
115     except (UnicodeError, ValueError):
116         # ValueError: Not an IP address (common case)
117         # UnicodeError: Divergence from upstream: Have to deal with ipaddress not taking
118         # byte strings.  addresses should be all ascii, so we consider it not
119         # an ipaddress in this case
120         host_ip = None
121     except AttributeError:
122         # Divergence from upstream: Make ipaddress library optional
123         if ipaddress is None:
124             host_ip = None
125         else:  # Defensive
126             raise
127     dnsnames = []
128     san = cert.get("subjectAltName", ())
129     for key, value in san:
130         if key == "DNS":
131             if host_ip is None and _dnsname_match(value, hostname):
132                 return
133             dnsnames.append(value)
134         elif key == "IP Address":
135             if host_ip is not None and _ipaddress_match(value, host_ip):
136                 return
137             dnsnames.append(value)
138     if not dnsnames:
139         # The subject is only checked when there is no dNSName entry
140         # in subjectAltName
141         for sub in cert.get("subject", ()):
142             for key, value in sub:
143                 # XXX according to RFC 2818, the most specific Common Name
144                 # must be used.
145                 if key == "commonName":
146                     if _dnsname_match(value, hostname):
147                         return
148                     dnsnames.append(value)
149     if len(dnsnames) > 1:
150         raise CertificateError(
151             "hostname %r "
152             "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames)))
153         )
154     elif len(dnsnames) == 1:
155         raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0]))
156     else:
157         raise CertificateError(
158             "no appropriate commonName or subjectAltName fields were found"
159         )