blob: a66461afd8dc3da63c48f4e12b5deb5d52a61b0d [file] [log] [blame]
Bryan Duxbury50409112011-03-21 17:59:49 +00001#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
Bryan Duxbury69720412012-01-03 17:32:30 +000019
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090020import logging
Bryan Duxbury50409112011-03-21 17:59:49 +000021import os
22import socket
23import ssl
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090024import sys
25import warnings
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090026from backports.ssl_match_hostname import match_hostname
Bryan Duxbury2b969ad2011-02-22 18:20:53 +000027
28from thrift.transport import TSocket
Bryan Duxbury50409112011-03-21 17:59:49 +000029from thrift.transport.TTransport import TTransportException
Bryan Duxbury2b969ad2011-02-22 18:20:53 +000030
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090031logger = logging.getLogger(__name__)
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090032warnings.filterwarnings(
33 'default', category=DeprecationWarning, module=__name__)
Bryan Duxbury69720412012-01-03 17:32:30 +000034
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090035
36class TSSLBase(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090037 # SSLContext is not available for Python < 2.7.9
38 _has_ssl_context = sys.hexversion >= 0x020709F0
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090039
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090040 # ciphers argument is not available for Python < 2.7.0
41 _has_ciphers = sys.hexversion >= 0x020700F0
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090042
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090043 # For pythoon >= 2.7.9, use latest TLS that both client and server
44 # supports.
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090045 # SSL 2.0 and 3.0 are disabled via ssl.OP_NO_SSLv2 and ssl.OP_NO_SSLv3.
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090046 # For pythoon < 2.7.9, use TLS 1.0 since TLSv1_X nor OP_NO_SSLvX is
47 # unavailable.
48 _default_protocol = ssl.PROTOCOL_SSLv23 if _has_ssl_context else \
49 ssl.PROTOCOL_TLSv1
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090050
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090051 def _init_context(self, ssl_version):
52 if self._has_ssl_context:
53 self._context = ssl.SSLContext(ssl_version)
54 if self._context.protocol == ssl.PROTOCOL_SSLv23:
55 self._context.options |= ssl.OP_NO_SSLv2
56 self._context.options |= ssl.OP_NO_SSLv3
57 else:
58 self._context = None
59 self._ssl_version = ssl_version
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090060
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090061 @property
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090062 def _should_verify(self):
63 if self._has_ssl_context:
64 return self._context.verify_mode != ssl.CERT_NONE
65 else:
66 return self.cert_reqs != ssl.CERT_NONE
67
68 @property
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090069 def ssl_version(self):
70 if self._has_ssl_context:
71 return self.ssl_context.protocol
72 else:
73 return self._ssl_version
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090074
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090075 @property
76 def ssl_context(self):
77 return self._context
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090078
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090079 SSL_VERSION = _default_protocol
80 """
Nobuaki Sukegawaad835862015-12-23 23:32:09 +090081 Default SSL version.
82 For backword compatibility, it can be modified.
83 Use __init__ keywoard argument "ssl_version" instead.
84 """
85
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090086 def _deprecated_arg(self, args, kwargs, pos, key):
87 if len(args) <= pos:
88 return
89 real_pos = pos + 3
90 warnings.warn(
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +090091 '%dth positional argument is deprecated.'
92 'please use keyward argument insteand.'
93 % real_pos, DeprecationWarning, stacklevel=3)
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090094
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090095 if key in kwargs:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +090096 raise TypeError(
97 'Duplicate argument: %dth argument and %s keyward argument.'
98 % (real_pos, key))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090099 kwargs[key] = args[pos]
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900100
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900101 def _unix_socket_arg(self, host, port, args, kwargs):
102 key = 'unix_socket'
103 if host is None and port is None and len(args) == 1 and key not in kwargs:
104 kwargs[key] = args[0]
105 return True
106 return False
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900107
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900108 def __getattr__(self, key):
109 if key == 'SSL_VERSION':
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900110 warnings.warn(
111 'SSL_VERSION is deprecated.'
112 'please use ssl_version attribute instead.',
113 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900114 return self.ssl_version
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900115
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900116 def __init__(self, server_side, host, ssl_opts):
117 self._server_side = server_side
118 if TSSLBase.SSL_VERSION != self._default_protocol:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900119 warnings.warn(
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900120 'SSL_VERSION is deprecated.'
121 'please use ssl_version keyward argument instead.',
122 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900123 self._context = ssl_opts.pop('ssl_context', None)
124 self._server_hostname = None
125 if not self._server_side:
126 self._server_hostname = ssl_opts.pop('server_hostname', host)
127 if self._context:
128 self._custom_context = True
129 if ssl_opts:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900130 raise ValueError(
131 'Incompatible arguments: ssl_context and %s'
132 % ' '.join(ssl_opts.keys()))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900133 if not self._has_ssl_context:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900134 raise ValueError(
135 'ssl_context is not available for this version of Python')
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900136 else:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900137 self._custom_context = False
138 ssl_version = ssl_opts.pop('ssl_version', TSSLBase.SSL_VERSION)
139 self._init_context(ssl_version)
140 self.cert_reqs = ssl_opts.pop('cert_reqs', ssl.CERT_REQUIRED)
141 self.ca_certs = ssl_opts.pop('ca_certs', None)
142 self.keyfile = ssl_opts.pop('keyfile', None)
143 self.certfile = ssl_opts.pop('certfile', None)
144 self.ciphers = ssl_opts.pop('ciphers', None)
145
146 if ssl_opts:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900147 raise ValueError(
148 'Unknown keyword arguments: ', ' '.join(ssl_opts.keys()))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900149
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900150 if self._should_verify:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900151 if not self.ca_certs:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900152 raise ValueError(
153 'ca_certs is needed when cert_reqs is not ssl.CERT_NONE')
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900154 if not os.access(self.ca_certs, os.R_OK):
155 raise IOError('Certificate Authority ca_certs file "%s" '
156 'is not readable, cannot validate SSL '
157 'certificates.' % (self.ca_certs))
158
159 @property
160 def certfile(self):
161 return self._certfile
162
163 @certfile.setter
164 def certfile(self, certfile):
165 if self._server_side and not certfile:
166 raise ValueError('certfile is needed for server-side')
167 if certfile and not os.access(certfile, os.R_OK):
168 raise IOError('No such certfile found: %s' % (certfile))
169 self._certfile = certfile
170
171 def _wrap_socket(self, sock):
172 if self._has_ssl_context:
173 if not self._custom_context:
174 self.ssl_context.verify_mode = self.cert_reqs
175 if self.certfile:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900176 self.ssl_context.load_cert_chain(self.certfile,
177 self.keyfile)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900178 if self.ciphers:
179 self.ssl_context.set_ciphers(self.ciphers)
180 if self.ca_certs:
181 self.ssl_context.load_verify_locations(self.ca_certs)
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900182 return self.ssl_context.wrap_socket(
183 sock, server_side=self._server_side,
184 server_hostname=self._server_hostname)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900185 else:
186 ssl_opts = {
187 'ssl_version': self._ssl_version,
188 'server_side': self._server_side,
189 'ca_certs': self.ca_certs,
190 'keyfile': self.keyfile,
191 'certfile': self.certfile,
192 'cert_reqs': self.cert_reqs,
193 }
194 if self.ciphers:
195 if self._has_ciphers:
196 ssl_opts['ciphers'] = self.ciphers
197 else:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900198 logger.warning(
199 'ciphers is specified but ignored due to old Python version')
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900200 return ssl.wrap_socket(sock, **ssl_opts)
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900201
202
203class TSSLSocket(TSocket.TSocket, TSSLBase):
Bryan Duxbury50409112011-03-21 17:59:49 +0000204 """
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900205 SSL implementation of TSocket
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900206
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900207 This class creates outbound sockets wrapped using the
208 python standard ssl module for encrypted connections.
209 """
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900210
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900211 # New signature
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900212 # def __init__(self, host='localhost', port=9090, unix_socket=None,
213 # **ssl_args):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900214 # Deprecated signature
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900215 # def __init__(self, host='localhost', port=9090, validate=True,
216 # ca_certs=None, keyfile=None, certfile=None,
217 # unix_socket=None, ciphers=None):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900218 def __init__(self, host='localhost', port=9090, *args, **kwargs):
219 """Positional arguments: ``host``, ``port``, ``unix_socket``
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900220
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900221 Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``,
222 ``ssl_version``, ``ca_certs``,
223 ``ciphers`` (Python 2.7.0 or later),
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900224 ``server_hostname`` (Python 2.7.9 or later)
225 Passed to ssl.wrap_socket. See ssl.wrap_socket documentation.
Bryan Duxbury50409112011-03-21 17:59:49 +0000226
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900227 Alternative keyword arguments: (Python 2.7.9 or later)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900228 ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
229 ``server_hostname``: Passed to SSLContext.wrap_socket
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900230
231 Common keyword argument:
232 ``validate_callback`` (cert, hostname) -> None:
233 Called after SSL handshake. Can raise when hostname does not
234 match the cert.
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900235 """
236 self.is_valid = False
237 self.peercert = None
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900238
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900239 if args:
240 if len(args) > 6:
241 raise TypeError('Too many positional argument')
242 if not self._unix_socket_arg(host, port, args, kwargs):
243 self._deprecated_arg(args, kwargs, 0, 'validate')
244 self._deprecated_arg(args, kwargs, 1, 'ca_certs')
245 self._deprecated_arg(args, kwargs, 2, 'keyfile')
246 self._deprecated_arg(args, kwargs, 3, 'certfile')
247 self._deprecated_arg(args, kwargs, 4, 'unix_socket')
248 self._deprecated_arg(args, kwargs, 5, 'ciphers')
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900249
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900250 validate = kwargs.pop('validate', None)
251 if validate is not None:
252 cert_reqs_name = 'CERT_REQUIRED' if validate else 'CERT_NONE'
253 warnings.warn(
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900254 'validate is deprecated. please use cert_reqs=ssl.%s instead'
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900255 % cert_reqs_name,
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900256 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900257 if 'cert_reqs' in kwargs:
258 raise TypeError('Cannot specify both validate and cert_reqs')
259 kwargs['cert_reqs'] = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE
260
261 unix_socket = kwargs.pop('unix_socket', None)
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900262 self._validate_callback = kwargs.pop('validate_callback', match_hostname)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900263 TSSLBase.__init__(self, False, host, kwargs)
264 TSocket.TSocket.__init__(self, host, port, unix_socket)
265
266 @property
267 def validate(self):
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900268 warnings.warn('validate is deprecated. please use cert_reqs instead',
269 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900270 return self.cert_reqs != ssl.CERT_NONE
271
272 @validate.setter
273 def validate(self, value):
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900274 warnings.warn('validate is deprecated. please use cert_reqs instead',
275 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900276 self.cert_reqs = ssl.CERT_REQUIRED if value else ssl.CERT_NONE
277
278 def open(self):
Bryan Duxbury2b969ad2011-02-22 18:20:53 +0000279 try:
Nobuaki Sukegawace1c8ab2016-02-11 18:21:39 +0900280 addrs = self._resolveAddr()
281 for addr in addrs:
282 sock_family, sock_type, _, _, ip_port = addr
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900283 plain_sock = socket.socket(sock_family, sock_type)
284 self.handle = self._wrap_socket(plain_sock)
285 self.handle.settimeout(self._timeout)
286 try:
287 self.handle.connect(ip_port)
Nobuaki Sukegawace1c8ab2016-02-11 18:21:39 +0900288 except socket.error:
289 self.handle.close()
290 if addr is not addrs[-1]:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900291 logger.warning(
292 'Error while connecting with %s. Trying next one.',
293 ip_port, exc_info=True)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900294 continue
295 else:
296 raise
297 break
jfarrelld565e2f2015-03-18 21:02:47 -0400298 except socket.error as e:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900299 if self._unix_socket:
300 message = 'Could not connect to secure socket %s: %s' \
301 % (self._unix_socket, e)
302 else:
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900303 message = 'Could not connect to %s:%d: %s' \
304 % (self.host, self.port, e)
Nobuaki Sukegawace1c8ab2016-02-11 18:21:39 +0900305 logger.exception(
306 'Error while connecting with %s.', ip_port)
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900307 raise TTransportException(TTransportException.NOT_OPEN, message)
Bryan Duxbury50409112011-03-21 17:59:49 +0000308
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900309 if self._should_verify:
310 self.peercert = self.handle.getpeercert()
311 try:
312 self._validate_callback(self.peercert, self._server_hostname)
313 self.is_valid = True
314 except TTransportException:
315 raise
316 except Exception as ex:
317 raise TTransportException(TTransportException.UNKNOWN, str(ex))
318
319 @staticmethod
320 def legacy_validate_callback(self, cert, hostname):
321 """legacy method to validate the peer's SSL certificate, and to check
322 the commonName of the certificate to ensure it matches the hostname we
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900323 used to make this connection. Does not support subjectAltName records
324 in certificates.
Bryan Duxbury69720412012-01-03 17:32:30 +0000325
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900326 raises TTransportException if the certificate fails validation.
327 """
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900328 if 'subject' not in cert:
329 raise TTransportException(
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900330 TTransportException.NOT_OPEN,
331 'No SSL certificate found from %s:%s' % (self.host, self.port))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900332 fields = cert['subject']
333 for field in fields:
334 # ensure structure we get back is what we expect
335 if not isinstance(field, tuple):
336 continue
337 cert_pair = field[0]
338 if len(cert_pair) < 2:
339 continue
340 cert_key, cert_value = cert_pair[0:2]
341 if cert_key != 'commonName':
342 continue
343 certhost = cert_value
344 # this check should be performed by some sort of Access Manager
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900345 if certhost == hostname:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900346 # success, cert commonName matches desired hostname
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900347 return
348 else:
349 raise TTransportException(
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900350 TTransportException.UNKNOWN,
351 'Hostname we connected to "%s" doesn\'t match certificate '
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900352 'provided commonName "%s"' % (self.host, certhost))
Bryan Duxbury69720412012-01-03 17:32:30 +0000353 raise TTransportException(
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900354 TTransportException.UNKNOWN,
355 'Could not validate SSL certificate from host "%s". Cert=%s'
356 % (hostname, cert))
Bryan Duxbury69720412012-01-03 17:32:30 +0000357
Bryan Duxbury2b969ad2011-02-22 18:20:53 +0000358
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900359class TSSLServerSocket(TSocket.TServerSocket, TSSLBase):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900360 """SSL implementation of TServerSocket
Bryan Duxbury50409112011-03-21 17:59:49 +0000361
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900362 This uses the ssl module's wrap_socket() method to provide SSL
363 negotiated encryption.
Bryan Duxbury50409112011-03-21 17:59:49 +0000364 """
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900365
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900366 # New signature
367 # def __init__(self, host='localhost', port=9090, unix_socket=None, **ssl_args):
368 # Deprecated signature
369 # def __init__(self, host=None, port=9090, certfile='cert.pem', unix_socket=None, ciphers=None):
370 def __init__(self, host=None, port=9090, *args, **kwargs):
371 """Positional arguments: ``host``, ``port``, ``unix_socket``
Nobuaki Sukegawaad835862015-12-23 23:32:09 +0900372
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900373 Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
374 ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
375 See ssl.wrap_socket documentation.
Bryan Duxbury50409112011-03-21 17:59:49 +0000376
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900377 Alternative keyword arguments: (Python 2.7.9 or later)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900378 ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
379 ``server_hostname``: Passed to SSLContext.wrap_socket
Nobuaki Sukegawaf39f7db2016-02-04 15:09:41 +0900380
381 Common keyword argument:
382 ``validate_callback`` (cert, hostname) -> None:
383 Called after SSL handshake. Can raise when hostname does not
384 match the cert.
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900385 """
386 if args:
387 if len(args) > 3:
388 raise TypeError('Too many positional argument')
389 if not self._unix_socket_arg(host, port, args, kwargs):
390 self._deprecated_arg(args, kwargs, 0, 'certfile')
391 self._deprecated_arg(args, kwargs, 1, 'unix_socket')
392 self._deprecated_arg(args, kwargs, 2, 'ciphers')
Bryan Duxbury69720412012-01-03 17:32:30 +0000393
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900394 if 'ssl_context' not in kwargs:
395 # Preserve existing behaviors for default values
396 if 'cert_reqs' not in kwargs:
397 kwargs['cert_reqs'] = ssl.CERT_NONE
398 if'certfile' not in kwargs:
399 kwargs['certfile'] = 'cert.pem'
Bryan Duxbury69720412012-01-03 17:32:30 +0000400
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900401 unix_socket = kwargs.pop('unix_socket', None)
Nobuaki Sukegawaf39f7db2016-02-04 15:09:41 +0900402 self._validate_callback = \
403 kwargs.pop('validate_callback', match_hostname)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900404 TSSLBase.__init__(self, True, None, kwargs)
405 TSocket.TServerSocket.__init__(self, host, port, unix_socket)
Bryan Duxbury50409112011-03-21 17:59:49 +0000406
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900407 def setCertfile(self, certfile):
Nobuaki Sukegawa25536ad2016-02-04 15:08:55 +0900408 """Set or change the server certificate file used to wrap new
409 connections.
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900410
411 @param certfile: The filename of the server certificate,
412 i.e. '/etc/certs/server.pem'
413 @type certfile: str
414
415 Raises an IOError exception if the certfile is not present or unreadable.
416 """
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900417 warnings.warn(
418 'setCertfile is deprecated. please use certfile property instead.',
419 DeprecationWarning, stacklevel=2)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900420 self.certfile = certfile
421
422 def accept(self):
423 plain_client, addr = self.handle.accept()
424 try:
425 client = self._wrap_socket(plain_client)
426 except ssl.SSLError:
Nobuaki Sukegawace1c8ab2016-02-11 18:21:39 +0900427 logger.exception('Error while accepting from %s', addr)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900428 # failed handshake/ssl wrap, close socket to client
429 plain_client.close()
430 # raise
431 # We can't raise the exception, because it kills most TServer derived
432 # serve() methods.
433 # Instead, return None, and let the TServer instance deal with it in
434 # other exception handling. (but TSimpleServer dies anyway)
435 return None
Nobuaki Sukegawaf39f7db2016-02-04 15:09:41 +0900436
437 if self._should_verify:
438 client.peercert = client.getpeercert()
439 try:
440 self._validate_callback(client.peercert, addr[0])
441 client.is_valid = True
442 except Exception:
443 logger.warn('Failed to validate client certificate address',
444 exc_info=True)
445 client.close()
446 plain_client.close()
447 return None
448
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900449 result = TSocket.TSocket()
Nobuaki Sukegawa6a0ca7f2016-02-13 03:11:16 +0900450 result.handle = client
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900451 return result