1 """This is a temporary hack to fix an SSL bug in Python versions before 3.2.
2 It is used automatically when you download an HTTPS URL using a Fetcher.
4 Copyright: Python Software Foundation
6 Downloaded from: http://pypi.python.org/pypi/backports.ssl_match_hostname/"""
10 class CertificateError(ValueError):
13 def _dnsname_to_pat(dn
):
15 for frag
in dn
.split(r
'.'):
17 # When '*' is a fragment by itself, it matches a non-empty dotless
21 # Otherwise, '*' matches any dotless fragment.
22 frag
= re
.escape(frag
)
23 pats
.append(frag
.replace(r
'\*', '[^.]*'))
24 return re
.compile(r
'\A' + r
'\.'.join(pats
) + r
'\Z', re
.IGNORECASE
)
26 def match_hostname(cert
, hostname
):
27 """Verify that *cert* (in decoded format as returned by
28 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
29 are mostly followed, but IP addresses are not accepted for *hostname*.
31 CertificateError is raised on failure. On success, the function
35 raise ValueError("empty or no certificate")
37 san
= cert
.get('subjectAltName', ())
38 for key
, value
in san
:
40 if _dnsname_to_pat(value
).match(hostname
):
42 dnsnames
.append(value
)
44 # The subject is only checked when subjectAltName is empty
45 for sub
in cert
.get('subject', ()):
46 for key
, value
in sub
:
47 # XXX according to RFC 2818, the most specific Common Name
49 if key
== 'commonName':
50 if _dnsname_to_pat(value
).match(hostname
):
52 dnsnames
.append(value
)
54 raise CertificateError("hostname %r "
55 "doesn't match either of %s"
56 % (hostname
, ', '.join(map(repr, dnsnames
))))
57 elif len(dnsnames
) == 1:
58 raise CertificateError("hostname %r "
60 % (hostname
, dnsnames
[0]))
62 raise CertificateError("no appropriate commonName or "
63 "subjectAltName fields were found")