Debian Codegraph @

glanceclient/common/https.py

raw symbols SCIP
1 # Copyright 2014 Red Hat, Inc
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import socket
17 import ssl
18 import struct
19
20 import OpenSSL
21
22
23 try:
24 from eventlet import patcher
25 # Handle case where we are running in a monkey patched environment
26 if patcher.is_monkey_patched('socket'):
27 from eventlet.green.httplib import HTTPSConnection
28 from eventlet.green.OpenSSL.SSL import GreenConnection as Connection
29 else:
30 raise ImportError
31 except ImportError:
32 import http.client
33 from OpenSSL import SSL
34 HTTPSConnection = http.client.HTTPSConnection
35 Connection = SSL.Connection
36
37
38 from glanceclient import exc
39
40
41 def verify_callback(host=None):
42 """Provide wrapper for do_verify_callback.
43
44 We use a partial around the 'real' verify_callback function
45 so that we can stash the host value without holding a
46 reference on the VerifiedHTTPSConnection.
47 """
48 def wrapper(connection, x509, errnum,
49 depth, preverify_ok, host=host):
50 return do_verify_callback(connection, x509, errnum,
51 depth, preverify_ok, host=host)
52 return wrapper
53
54
55 def do_verify_callback(connection, x509, errnum,
56 depth, preverify_ok, host=None):
57 """Verify the server's SSL certificate.
58
59 This is a standalone function rather than a method to avoid
60 issues around closing sockets if a reference is held on
61 a VerifiedHTTPSConnection by the callback function.
62 """
63 if x509.has_expired():
64 msg = "SSL Certificate expired on '%s'" % x509.get_notAfter()
65 raise exc.SSLCertificateError(msg)
66
67 if depth == 0 and preverify_ok:
68 # We verify that the host matches against the last
69 # certificate in the chain
70 return host_matches_cert(host, x509)
71 else:
72 # Pass through OpenSSL's default result
73 return preverify_ok
74
75
76 def host_matches_cert(host, x509):
77 """Verify the certificate identifies the host.
78
79 Verify that the x509 certificate we have received
80 from 'host' correctly identifies the server we are
81 connecting to, ie that the certificate's Common Name
82 or a Subject Alternative Name matches 'host'.
83 """
84 def check_match(name):
85 # Directly match the name
86 if name == host:
87 return True
88
89 # Support single wildcard matching
90 if name.startswith('*.') and host.find('.') > 0:
91 if name[2:] == host.split('.', 1)[1]:
92 return True
93
94 common_name = x509.get_subject().commonName
95
96 # First see if we can match the CN
97 if check_match(common_name):
98 return True
99 # Also try Subject Alternative Names for a match
100 san_list = None
101 for i in range(x509.get_extension_count()):
102 ext = x509.get_extension(i)
103 if ext.get_short_name() == b'subjectAltName':
104 san_list = str(ext)
105 for san in ''.join(san_list.split()).split(','):
106 if san.startswith('DNS:'):
107 if check_match(san.split(':', 1)[1]):
108 return True
109
110 # Server certificate does not match host
111 msg = ('Host "%s" does not match x509 certificate contents: '
112 'CommonName "%s"' % (host, common_name))
113 if san_list is not None:
114 msg = msg + ', subjectAltName "%s"' % san_list
115 raise exc.SSLCertificateError(msg)
116
117
118 def to_bytes(s):
119 if isinstance(s, str):
120 return bytes(s, 'latin-1')
121 else:
122 return s
123
124
125 class OpenSSLConnectionDelegator(object):
126 """An OpenSSL.SSL.Connection delegator.
127
128 Supplies an additional 'makefile' method which httplib requires
129 and is not present in OpenSSL.SSL.Connection.
130
131 Note: Since it is not possible to inherit from OpenSSL.SSL.Connection
132 a delegator must be used.
133 """
134 def __init__(self, *args, **kwargs):
135 self.connection = Connection(*args, **kwargs)
136
137 def __getattr__(self, name):
138 return getattr(self.connection, name)
139
140 def makefile(self, *args, **kwargs):
141 return socket._fileobject(self.connection, *args, **kwargs)
142
143
144 class VerifiedHTTPSConnection(HTTPSConnection):
145 """Extended OpenSSL HTTPSConnection for enhanced SSL support.
146
147 Note: Much of this functionality can eventually be replaced
148 with native Python 3.3 code.
149 """
150 # Restrict the set of client supported cipher suites
151 CIPHERS = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:'\
152 'eCDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:'\
153 'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'
154
155 def __init__(self, host, port=None, key_file=None, cert_file=None,
156 cacert=None, timeout=None, insecure=False,
157 ssl_compression=True):
158 # List of exceptions reported by Python3 instead of
159 # SSLConfigurationError
160 excp_lst = (TypeError, FileNotFoundError, ssl.SSLError)
161 try:
162 HTTPSConnection.__init__(self, host, port,
163 key_file=key_file,
164 cert_file=cert_file)
165 self.key_file = key_file
166 self.cert_file = cert_file
167 self.timeout = timeout
168 self.insecure = insecure
169 # NOTE(flaper87): `is_verified` is needed for
170 # requests' urllib3. If insecure is True then
171 # the request is not `verified`, hence `not insecure`
172 self.is_verified = not insecure
173 self.ssl_compression = ssl_compression
174 self.cacert = None if cacert is None else str(cacert)
175 self.set_context()
176 # ssl exceptions are reported in various form in Python 3
177 # so to be compatible, we report the same kind as under
178 # Python2
179 except excp_lst as e:
180 raise exc.SSLConfigurationError(str(e))
181
182 def set_context(self):
183 """Set up the OpenSSL context."""
184 self.context = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
185 self.context.set_cipher_list(self.CIPHERS)
186
187 if self.ssl_compression is False:
188 self.context.set_options(0x20000) # SSL_OP_NO_COMPRESSION
189
190 if self.insecure is not True:
191 self.context.set_verify(OpenSSL.SSL.VERIFY_PEER,
192 verify_callback(host=self.host))
193 else:
194 self.context.set_verify(OpenSSL.SSL.VERIFY_NONE,
195 lambda *args: True)
196
197 if self.cert_file:
198 try:
199 self.context.use_certificate_file(self.cert_file)
200 except Exception as e:
201 msg = 'Unable to load cert from "%s" %s' % (self.cert_file, e)
202 raise exc.SSLConfigurationError(msg)
203 if self.key_file is None:
204 # We support having key and cert in same file
205 try:
206 self.context.use_privatekey_file(self.cert_file)
207 except Exception as e:
208 msg = ('No key file specified and unable to load key '
209 'from "%s" %s' % (self.cert_file, e))
210 raise exc.SSLConfigurationError(msg)
211
212 if self.key_file:
213 try:
214 self.context.use_privatekey_file(self.key_file)
215 except Exception as e:
216 msg = 'Unable to load key from "%s" %s' % (self.key_file, e)
217 raise exc.SSLConfigurationError(msg)
218
219 if self.cacert:
220 try:
221 self.context.load_verify_locations(to_bytes(self.cacert))
222 except Exception as e:
223 msg = 'Unable to load CA from "%s" %s' % (self.cacert, e)
224 raise exc.SSLConfigurationError(msg)
225 else:
226 self.context.set_default_verify_paths()
227
228 def connect(self):
229 """Connect to an SSL port using the OpenSSL library.
230
231 This method also applies per-connection parameters to the connection.
232 """
233 result = socket.getaddrinfo(self.host, self.port, 0,
234 socket.SOCK_STREAM)
235 if result:
236 socket_family = result[0][0]
237 if socket_family == socket.AF_INET6:
238 sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
239 else:
240 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
241 else:
242 # If due to some reason the address lookup fails - we still connect
243 # to IPv4 socket. This retains the older behavior.
244 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
245 if self.timeout is not None:
246 # '0' microseconds
247 sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO,
248 struct.pack('LL', self.timeout, 0))
249 self.sock = OpenSSLConnectionDelegator(self.context, sock)
250 self.sock.connect((self.host, self.port))