~anitanayak/charms/trusty/ibm-mq/devel

« back to all changes in this revision

Viewing changes to .tox/py35/lib/python3.5/site-packages/setuptools/ssl_support.py

  • Committer: Anita Nayak
  • Date: 2016-10-24 07:11:28 UTC
  • Revision ID: anitanayak@in.ibm.com-20161024071128-oufsbvyx8x344p2j
checking in after fixing lint errors

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import socket
 
3
import atexit
 
4
import re
 
5
 
 
6
from setuptools.extern.six.moves import urllib, http_client, map
 
7
 
 
8
import pkg_resources
 
9
from pkg_resources import ResolutionError, ExtractionError
 
10
 
 
11
try:
 
12
    import ssl
 
13
except ImportError:
 
14
    ssl = None
 
15
 
 
16
__all__ = [
 
17
    'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths',
 
18
    'opener_for'
 
19
]
 
20
 
 
21
cert_paths = """
 
22
/etc/pki/tls/certs/ca-bundle.crt
 
23
/etc/ssl/certs/ca-certificates.crt
 
24
/usr/share/ssl/certs/ca-bundle.crt
 
25
/usr/local/share/certs/ca-root.crt
 
26
/etc/ssl/cert.pem
 
27
/System/Library/OpenSSL/certs/cert.pem
 
28
/usr/local/share/certs/ca-root-nss.crt
 
29
/etc/ssl/ca-bundle.pem
 
30
""".strip().split()
 
31
 
 
32
try:
 
33
    HTTPSHandler = urllib.request.HTTPSHandler
 
34
    HTTPSConnection = http_client.HTTPSConnection
 
35
except AttributeError:
 
36
    HTTPSHandler = HTTPSConnection = object
 
37
 
 
38
is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection)
 
39
 
 
40
 
 
41
try:
 
42
    from ssl import CertificateError, match_hostname
 
43
except ImportError:
 
44
    try:
 
45
        from backports.ssl_match_hostname import CertificateError
 
46
        from backports.ssl_match_hostname import match_hostname
 
47
    except ImportError:
 
48
        CertificateError = None
 
49
        match_hostname = None
 
50
 
 
51
if not CertificateError:
 
52
 
 
53
    class CertificateError(ValueError):
 
54
        pass
 
55
 
 
56
 
 
57
if not match_hostname:
 
58
 
 
59
    def _dnsname_match(dn, hostname, max_wildcards=1):
 
60
        """Matching according to RFC 6125, section 6.4.3
 
61
 
 
62
        http://tools.ietf.org/html/rfc6125#section-6.4.3
 
63
        """
 
64
        pats = []
 
65
        if not dn:
 
66
            return False
 
67
 
 
68
        # Ported from python3-syntax:
 
69
        # leftmost, *remainder = dn.split(r'.')
 
70
        parts = dn.split(r'.')
 
71
        leftmost = parts[0]
 
72
        remainder = parts[1:]
 
73
 
 
74
        wildcards = leftmost.count('*')
 
75
        if wildcards > max_wildcards:
 
76
            # Issue #17980: avoid denials of service by refusing more
 
77
            # than one wildcard per fragment.  A survey of established
 
78
            # policy among SSL implementations showed it to be a
 
79
            # reasonable choice.
 
80
            raise CertificateError(
 
81
                "too many wildcards in certificate DNS name: " + repr(dn))
 
82
 
 
83
        # speed up common case w/o wildcards
 
84
        if not wildcards:
 
85
            return dn.lower() == hostname.lower()
 
86
 
 
87
        # RFC 6125, section 6.4.3, subitem 1.
 
88
        # The client SHOULD NOT attempt to match a presented identifier in which
 
89
        # the wildcard character comprises a label other than the left-most label.
 
90
        if leftmost == '*':
 
91
            # When '*' is a fragment by itself, it matches a non-empty dotless
 
92
            # fragment.
 
93
            pats.append('[^.]+')
 
94
        elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
 
95
            # RFC 6125, section 6.4.3, subitem 3.
 
96
            # The client SHOULD NOT attempt to match a presented identifier
 
97
            # where the wildcard character is embedded within an A-label or
 
98
            # U-label of an internationalized domain name.
 
99
            pats.append(re.escape(leftmost))
 
100
        else:
 
101
            # Otherwise, '*' matches any dotless string, e.g. www*
 
102
            pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
 
103
 
 
104
        # add the remaining fragments, ignore any wildcards
 
105
        for frag in remainder:
 
106
            pats.append(re.escape(frag))
 
107
 
 
108
        pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
 
109
        return pat.match(hostname)
 
110
 
 
111
    def match_hostname(cert, hostname):
 
112
        """Verify that *cert* (in decoded format as returned by
 
113
        SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125
 
114
        rules are followed, but IP addresses are not accepted for *hostname*.
 
115
 
 
116
        CertificateError is raised on failure. On success, the function
 
117
        returns nothing.
 
118
        """
 
119
        if not cert:
 
120
            raise ValueError("empty or no certificate")
 
121
        dnsnames = []
 
122
        san = cert.get('subjectAltName', ())
 
123
        for key, value in san:
 
124
            if key == 'DNS':
 
125
                if _dnsname_match(value, hostname):
 
126
                    return
 
127
                dnsnames.append(value)
 
128
        if not dnsnames:
 
129
            # The subject is only checked when there is no dNSName entry
 
130
            # in subjectAltName
 
131
            for sub in cert.get('subject', ()):
 
132
                for key, value in sub:
 
133
                    # XXX according to RFC 2818, the most specific Common Name
 
134
                    # must be used.
 
135
                    if key == 'commonName':
 
136
                        if _dnsname_match(value, hostname):
 
137
                            return
 
138
                        dnsnames.append(value)
 
139
        if len(dnsnames) > 1:
 
140
            raise CertificateError("hostname %r "
 
141
                "doesn't match either of %s"
 
142
                % (hostname, ', '.join(map(repr, dnsnames))))
 
143
        elif len(dnsnames) == 1:
 
144
            raise CertificateError("hostname %r "
 
145
                "doesn't match %r"
 
146
                % (hostname, dnsnames[0]))
 
147
        else:
 
148
            raise CertificateError("no appropriate commonName or "
 
149
                "subjectAltName fields were found")
 
150
 
 
151
 
 
152
class VerifyingHTTPSHandler(HTTPSHandler):
 
153
    """Simple verifying handler: no auth, subclasses, timeouts, etc."""
 
154
 
 
155
    def __init__(self, ca_bundle):
 
156
        self.ca_bundle = ca_bundle
 
157
        HTTPSHandler.__init__(self)
 
158
 
 
159
    def https_open(self, req):
 
160
        return self.do_open(
 
161
            lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw), req
 
162
        )
 
163
 
 
164
 
 
165
class VerifyingHTTPSConn(HTTPSConnection):
 
166
    """Simple verifying connection: no auth, subclasses, timeouts, etc."""
 
167
 
 
168
    def __init__(self, host, ca_bundle, **kw):
 
169
        HTTPSConnection.__init__(self, host, **kw)
 
170
        self.ca_bundle = ca_bundle
 
171
 
 
172
    def connect(self):
 
173
        sock = socket.create_connection(
 
174
            (self.host, self.port), getattr(self, 'source_address', None)
 
175
        )
 
176
 
 
177
        # Handle the socket if a (proxy) tunnel is present
 
178
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
 
179
            self.sock = sock
 
180
            self._tunnel()
 
181
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
 
182
            # change self.host to mean the proxy server host when tunneling is
 
183
            # being used. Adapt, since we are interested in the destination
 
184
            # host for the match_hostname() comparison.
 
185
            actual_host = self._tunnel_host
 
186
        else:
 
187
            actual_host = self.host
 
188
 
 
189
        self.sock = ssl.wrap_socket(
 
190
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
 
191
        )
 
192
        try:
 
193
            match_hostname(self.sock.getpeercert(), actual_host)
 
194
        except CertificateError:
 
195
            self.sock.shutdown(socket.SHUT_RDWR)
 
196
            self.sock.close()
 
197
            raise
 
198
 
 
199
 
 
200
def opener_for(ca_bundle=None):
 
201
    """Get a urlopen() replacement that uses ca_bundle for verification"""
 
202
    return urllib.request.build_opener(
 
203
        VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())
 
204
    ).open
 
205
 
 
206
 
 
207
_wincerts = None
 
208
 
 
209
 
 
210
def get_win_certfile():
 
211
    global _wincerts
 
212
    if _wincerts is not None:
 
213
        return _wincerts.name
 
214
 
 
215
    try:
 
216
        from wincertstore import CertFile
 
217
    except ImportError:
 
218
        return None
 
219
 
 
220
    class MyCertFile(CertFile):
 
221
        def __init__(self, stores=(), certs=()):
 
222
            CertFile.__init__(self)
 
223
            for store in stores:
 
224
                self.addstore(store)
 
225
            self.addcerts(certs)
 
226
            atexit.register(self.close)
 
227
 
 
228
        def close(self):
 
229
            try:
 
230
                super(MyCertFile, self).close()
 
231
            except OSError:
 
232
                pass
 
233
 
 
234
    _wincerts = MyCertFile(stores=['CA', 'ROOT'])
 
235
    return _wincerts.name
 
236
 
 
237
 
 
238
def find_ca_bundle():
 
239
    """Return an existing CA bundle path, or None"""
 
240
    if os.name == 'nt':
 
241
        return get_win_certfile()
 
242
    else:
 
243
        for cert_path in cert_paths:
 
244
            if os.path.isfile(cert_path):
 
245
                return cert_path
 
246
    try:
 
247
        import certifi
 
248
        return certifi.where()
 
249
    except (ImportError, ResolutionError, ExtractionError):
 
250
        return None