blob: cd8d6b4c9eec0239a46b5ccf49fec9fb75ac8f0e [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
15
16 cert_time_to_seconds -- convert time string used for certificate
17 notBefore and notAfter functions to integer
18 seconds past the Epoch (the time values
19 returned from time.time())
20
21 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22 by the server running on HOST at port PORT. No
23 validation of the certificate is performed.
24
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
54PROTOCOL_TLSv1
55"""
56
Christian Heimes05e8be12008-02-23 18:30:17 +000057import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000058import re
Thomas Woutersed03b412007-08-28 21:37:11 +000059
60import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061
Antoine Pitrou04f6a322010-04-05 21:40:07 +000062from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou41032a62011-10-27 23:56:55 +020063from _ssl import _SSLContext
64from _ssl import (
65 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
66 SSLSyscallError, SSLEOFError,
67 )
Thomas Woutersed03b412007-08-28 21:37:11 +000068from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Antoine Pitrou6db49442011-12-19 13:27:11 +010069from _ssl import (
70 OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1,
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +010071 OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE
Antoine Pitrou6db49442011-12-19 13:27:11 +010072 )
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +010073try:
74 from _ssl import OP_NO_COMPRESSION
75except ImportError:
76 pass
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +010077try:
78 from _ssl import OP_SINGLE_ECDH_USE
79except ImportError:
80 pass
Victor Stinner99c8b162011-05-24 12:05:19 +020081from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Guido van Rossum5b8b1552007-11-16 00:06:11 +000082from _ssl import (
83 SSL_ERROR_ZERO_RETURN,
84 SSL_ERROR_WANT_READ,
85 SSL_ERROR_WANT_WRITE,
86 SSL_ERROR_WANT_X509_LOOKUP,
87 SSL_ERROR_SYSCALL,
88 SSL_ERROR_SSL,
89 SSL_ERROR_WANT_CONNECT,
90 SSL_ERROR_EOF,
91 SSL_ERROR_INVALID_ERROR_CODE,
92 )
Antoine Pitroud5d17eb2012-03-22 00:23:03 +010093from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Victor Stinner3de49192011-05-09 00:42:58 +020094from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
95 PROTOCOL_TLSv1)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020096from _ssl import _OPENSSL_API_VERSION
97
Victor Stinner3de49192011-05-09 00:42:58 +020098_PROTOCOL_NAMES = {
99 PROTOCOL_TLSv1: "TLSv1",
100 PROTOCOL_SSLv23: "SSLv23",
101 PROTOCOL_SSLv3: "SSLv3",
102}
103try:
104 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100105 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinner3de49192011-05-09 00:42:58 +0200106except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100107 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200108else:
109 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000110
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000111from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +0000112from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +0200113from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100114from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000115import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000116import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000117import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000118
Antoine Pitroud6494802011-07-21 01:11:30 +0200119if _ssl.HAS_TLS_UNIQUE:
120 CHANNEL_BINDING_TYPES = ['tls-unique']
121else:
122 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000123
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100124# Disable weak or insecure ciphers by default
125# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
126_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
127
Thomas Woutersed03b412007-08-28 21:37:11 +0000128
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000129class CertificateError(ValueError):
130 pass
131
132
Georg Brandl72c98d32013-10-27 07:16:53 +0100133def _dnsname_match(dn, hostname, max_wildcards=1):
134 """Matching according to RFC 6125, section 6.4.3
135
136 http://tools.ietf.org/html/rfc6125#section-6.4.3
137 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000138 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100139 if not dn:
140 return False
141
142 leftmost, *remainder = dn.split(r'.')
143
144 wildcards = leftmost.count('*')
145 if wildcards > max_wildcards:
146 # Issue #17980: avoid denials of service by refusing more
147 # than one wildcard per fragment. A survery of established
148 # policy among SSL implementations showed it to be a
149 # reasonable choice.
150 raise CertificateError(
151 "too many wildcards in certificate DNS name: " + repr(dn))
152
153 # speed up common case w/o wildcards
154 if not wildcards:
155 return dn.lower() == hostname.lower()
156
157 # RFC 6125, section 6.4.3, subitem 1.
158 # The client SHOULD NOT attempt to match a presented identifier in which
159 # the wildcard character comprises a label other than the left-most label.
160 if leftmost == '*':
161 # When '*' is a fragment by itself, it matches a non-empty dotless
162 # fragment.
163 pats.append('[^.]+')
164 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
165 # RFC 6125, section 6.4.3, subitem 3.
166 # The client SHOULD NOT attempt to match a presented identifier
167 # where the wildcard character is embedded within an A-label or
168 # U-label of an internationalized domain name.
169 pats.append(re.escape(leftmost))
170 else:
171 # Otherwise, '*' matches any dotless string, e.g. www*
172 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
173
174 # add the remaining fragments, ignore any wildcards
175 for frag in remainder:
176 pats.append(re.escape(frag))
177
178 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
179 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000180
181
182def match_hostname(cert, hostname):
183 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100184 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
185 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000186
187 CertificateError is raised on failure. On success, the function
188 returns nothing.
189 """
190 if not cert:
191 raise ValueError("empty or no certificate")
192 dnsnames = []
193 san = cert.get('subjectAltName', ())
194 for key, value in san:
195 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100196 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000197 return
198 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200199 if not dnsnames:
200 # The subject is only checked when there is no dNSName entry
201 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000202 for sub in cert.get('subject', ()):
203 for key, value in sub:
204 # XXX according to RFC 2818, the most specific Common Name
205 # must be used.
206 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100207 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000208 return
209 dnsnames.append(value)
210 if len(dnsnames) > 1:
211 raise CertificateError("hostname %r "
212 "doesn't match either of %s"
213 % (hostname, ', '.join(map(repr, dnsnames))))
214 elif len(dnsnames) == 1:
215 raise CertificateError("hostname %r "
216 "doesn't match %r"
217 % (hostname, dnsnames[0]))
218 else:
219 raise CertificateError("no appropriate commonName or "
220 "subjectAltName fields were found")
221
222
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223class SSLContext(_SSLContext):
224 """An SSLContext holds various SSL-related configuration options and
225 data, such as certificates and possibly a private key."""
226
227 __slots__ = ('protocol',)
228
229 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100230 self = _SSLContext.__new__(cls, protocol)
231 if protocol != _SSLv2_IF_EXISTS:
232 self.set_ciphers(_DEFAULT_CIPHERS)
233 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000234
235 def __init__(self, protocol):
236 self.protocol = protocol
237
238 def wrap_socket(self, sock, server_side=False,
239 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000240 suppress_ragged_eofs=True,
241 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000242 return SSLSocket(sock=sock, server_side=server_side,
243 do_handshake_on_connect=do_handshake_on_connect,
244 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000245 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000246 _context=self)
247
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100248 def set_npn_protocols(self, npn_protocols):
249 protos = bytearray()
250 for protocol in npn_protocols:
251 b = bytes(protocol, 'ascii')
252 if len(b) == 0 or len(b) > 255:
253 raise SSLError('NPN protocols must be 1 to 255 in length')
254 protos.append(len(b))
255 protos.extend(b)
256
257 self._set_npn_protocols(protos)
258
Antoine Pitrou152efa22010-05-16 18:19:27 +0000259
260class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000261 """This class implements a subtype of socket.socket that wraps
262 the underlying OS socket in an SSL context when necessary, and
263 provides read and write methods over that channel."""
264
Bill Janssen6e027db2007-11-15 22:23:56 +0000265 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000266 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000267 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
268 do_handshake_on_connect=True,
269 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100270 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000271 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000272 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000273
Antoine Pitrou152efa22010-05-16 18:19:27 +0000274 if _context:
275 self.context = _context
276 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000277 if server_side and not certfile:
278 raise ValueError("certfile must be specified for server-side "
279 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000280 if keyfile and not certfile:
281 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282 if certfile and not keyfile:
283 keyfile = certfile
284 self.context = SSLContext(ssl_version)
285 self.context.verify_mode = cert_reqs
286 if ca_certs:
287 self.context.load_verify_locations(ca_certs)
288 if certfile:
289 self.context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100290 if npn_protocols:
291 self.context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000292 if ciphers:
293 self.context.set_ciphers(ciphers)
294 self.keyfile = keyfile
295 self.certfile = certfile
296 self.cert_reqs = cert_reqs
297 self.ssl_version = ssl_version
298 self.ca_certs = ca_certs
299 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100300 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
301 # mixed in.
302 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
303 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000304 if server_side and server_hostname:
305 raise ValueError("server_hostname can only be specified "
306 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000307 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000308 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000309 self.do_handshake_on_connect = do_handshake_on_connect
310 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000311 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000312 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000313 socket.__init__(self,
314 family=sock.family,
315 type=sock.type,
316 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000317 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000318 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000319 # see if it's connected
320 try:
321 sock.getpeername()
322 except socket_error as e:
323 if e.errno != errno.ENOTCONN:
324 raise
325 else:
326 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000327 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000328 elif fileno is not None:
329 socket.__init__(self, fileno=fileno)
330 else:
331 socket.__init__(self, family=family, type=type, proto=proto)
332
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000333 self._closed = False
334 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000335 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000336 if connected:
337 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000338 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000339 self._sslobj = self.context._wrap_socket(self, server_side,
340 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000341 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000342 timeout = self.gettimeout()
343 if timeout == 0.0:
344 # non-blocking
345 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000346 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000347
Bill Janssen6e027db2007-11-15 22:23:56 +0000348 except socket_error as x:
349 self.close()
350 raise x
351
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000352 def dup(self):
353 raise NotImplemented("Can't dup() %s instances" %
354 self.__class__.__name__)
355
Bill Janssen6e027db2007-11-15 22:23:56 +0000356 def _checkClosed(self, msg=None):
357 # raise an exception here if you wish to check for spurious closes
358 pass
359
Bill Janssen54cc54c2007-12-14 22:08:56 +0000360 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000361 """Read up to LEN bytes and return them.
362 Return zero-length string on EOF."""
363
Bill Janssen6e027db2007-11-15 22:23:56 +0000364 self._checkClosed()
365 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000366 if buffer is not None:
367 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000368 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000369 v = self._sslobj.read(len or 1024)
370 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000371 except SSLError as x:
372 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000373 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000374 return 0
375 else:
376 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000377 else:
378 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
380 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000381 """Write DATA to the underlying SSL channel. Returns
382 number of bytes of DATA actually transmitted."""
383
Bill Janssen6e027db2007-11-15 22:23:56 +0000384 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000385 return self._sslobj.write(data)
386
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000388 """Returns a formatted version of the data in the
389 certificate provided by the other end of the SSL channel.
390 Return None if no certificate was provided, {} if a
391 certificate was provided, but not validated."""
392
Bill Janssen6e027db2007-11-15 22:23:56 +0000393 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394 return self._sslobj.peer_certificate(binary_form)
395
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100396 def selected_npn_protocol(self):
397 self._checkClosed()
398 if not self._sslobj or not _ssl.HAS_NPN:
399 return None
400 else:
401 return self._sslobj.selected_npn_protocol()
402
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000403 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000404 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405 if not self._sslobj:
406 return None
407 else:
408 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000409
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100410 def compression(self):
411 self._checkClosed()
412 if not self._sslobj:
413 return None
414 else:
415 return self._sslobj.compression()
416
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000417 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000418 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000419 if self._sslobj:
420 if flags != 0:
421 raise ValueError(
422 "non-zero flags not allowed in calls to send() on %s" %
423 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000424 while True:
425 try:
426 v = self._sslobj.write(data)
427 except SSLError as x:
428 if x.args[0] == SSL_ERROR_WANT_READ:
429 return 0
430 elif x.args[0] == SSL_ERROR_WANT_WRITE:
431 return 0
432 else:
433 raise
434 else:
435 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000436 else:
437 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000438
Antoine Pitroua468adc2010-09-14 14:43:44 +0000439 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000440 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000441 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000442 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000443 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000444 elif addr is None:
445 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000446 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000447 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000448
Nick Coghlan513886a2011-08-28 00:00:27 +1000449 def sendmsg(self, *args, **kwargs):
450 # Ensure programs don't send data unencrypted if they try to
451 # use this method.
452 raise NotImplementedError("sendmsg not allowed on instances of %s" %
453 self.__class__)
454
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000455 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000457 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000458 if flags != 0:
459 raise ValueError(
460 "non-zero flags not allowed in calls to sendall() on %s" %
461 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000462 amount = len(data)
463 count = 0
464 while (count < amount):
465 v = self.send(data[count:])
466 count += v
467 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000468 else:
469 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000470
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000471 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000472 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000473 if self._sslobj:
474 if flags != 0:
475 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000476 "non-zero flags not allowed in calls to recv() on %s" %
477 self.__class__)
478 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000479 else:
480 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000481
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000482 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000483 self._checkClosed()
484 if buffer and (nbytes is None):
485 nbytes = len(buffer)
486 elif nbytes is None:
487 nbytes = 1024
488 if self._sslobj:
489 if flags != 0:
490 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000491 "non-zero flags not allowed in calls to recv_into() on %s" %
492 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000493 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000494 else:
495 return socket.recv_into(self, buffer, nbytes, flags)
496
Antoine Pitroua468adc2010-09-14 14:43:44 +0000497 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000498 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000499 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000500 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000501 self.__class__)
502 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000503 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000504
Bill Janssen58afe4c2008-09-08 16:45:19 +0000505 def recvfrom_into(self, buffer, nbytes=None, flags=0):
506 self._checkClosed()
507 if self._sslobj:
508 raise ValueError("recvfrom_into not allowed on instances of %s" %
509 self.__class__)
510 else:
511 return socket.recvfrom_into(self, buffer, nbytes, flags)
512
Nick Coghlan513886a2011-08-28 00:00:27 +1000513 def recvmsg(self, *args, **kwargs):
514 raise NotImplementedError("recvmsg not allowed on instances of %s" %
515 self.__class__)
516
517 def recvmsg_into(self, *args, **kwargs):
518 raise NotImplementedError("recvmsg_into not allowed on instances of "
519 "%s" % self.__class__)
520
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000521 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000522 self._checkClosed()
523 if self._sslobj:
524 return self._sslobj.pending()
525 else:
526 return 0
527
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000528 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000529 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000531 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000532
Ezio Melottidc55e672010-01-18 09:15:14 +0000533 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000534 if self._sslobj:
535 s = self._sslobj.shutdown()
536 self._sslobj = None
537 return s
538 else:
539 raise ValueError("No SSL wrapper around " + str(self))
540
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000541 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000543 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000544 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000545
Bill Janssen48dc27c2007-12-05 03:38:10 +0000546 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000547 """Perform a TLS/SSL handshake."""
548
Bill Janssen48dc27c2007-12-05 03:38:10 +0000549 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000550 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000551 if timeout == 0.0 and block:
552 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000553 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000554 finally:
555 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000556
Antoine Pitroub4410db2011-05-18 18:51:06 +0200557 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000558 if self.server_side:
559 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000560 # Here we assume that the socket is client-side, and not
561 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000562 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000564 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000565 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200566 if connect_ex:
567 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000568 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200569 rc = None
570 socket.connect(self, addr)
571 if not rc:
572 if self.do_handshake_on_connect:
573 self.do_handshake()
574 self._connected = True
575 return rc
576 except socket_error:
577 self._sslobj = None
578 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000579
580 def connect(self, addr):
581 """Connects to remote ADDR, and then wraps the connection in
582 an SSL channel."""
583 self._real_connect(addr, False)
584
585 def connect_ex(self, addr):
586 """Connects to remote ADDR, and then wraps the connection in
587 an SSL channel."""
588 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000589
590 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000591 """Accepts a new connection from a remote client, and returns
592 a tuple containing that new connection wrapped with a server-side
593 SSL channel, and the address of the remote client."""
594
595 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100596 newsock = self.context.wrap_socket(newsock,
597 do_handshake_on_connect=self.do_handshake_on_connect,
598 suppress_ragged_eofs=self.suppress_ragged_eofs,
599 server_side=True)
600 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Antoine Pitroud6494802011-07-21 01:11:30 +0200602 def get_channel_binding(self, cb_type="tls-unique"):
603 """Get channel binding data for current connection. Raise ValueError
604 if the requested `cb_type` is not supported. Return bytes of the data
605 or None if the data is not available (e.g. before the handshake).
606 """
607 if cb_type not in CHANNEL_BINDING_TYPES:
608 raise ValueError("Unsupported channel binding type")
609 if cb_type != "tls-unique":
610 raise NotImplementedError(
611 "{0} channel binding type not implemented"
612 .format(cb_type))
613 if self._sslobj is None:
614 return None
615 return self._sslobj.tls_unique_cb()
616
Bill Janssen54cc54c2007-12-14 22:08:56 +0000617
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618def wrap_socket(sock, keyfile=None, certfile=None,
619 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000620 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000621 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100622 suppress_ragged_eofs=True,
623 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Bill Janssen6e027db2007-11-15 22:23:56 +0000625 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000627 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000628 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000629 suppress_ragged_eofs=suppress_ragged_eofs,
630 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Thomas Woutersed03b412007-08-28 21:37:11 +0000632# some utility functions
633
634def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000635 """Takes a date-time string in standard ASN1_print form
636 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
637 a Python time value in seconds past the epoch."""
638
Thomas Woutersed03b412007-08-28 21:37:11 +0000639 import time
640 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
641
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642PEM_HEADER = "-----BEGIN CERTIFICATE-----"
643PEM_FOOTER = "-----END CERTIFICATE-----"
644
645def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646 """Takes a certificate in binary DER format and returns the
647 PEM version of it as a string."""
648
Bill Janssen6e027db2007-11-15 22:23:56 +0000649 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
650 return (PEM_HEADER + '\n' +
651 textwrap.fill(f, 64) + '\n' +
652 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
654def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655 """Takes a certificate in ASCII PEM format and returns the
656 DER-encoded version of it as a byte sequence"""
657
658 if not pem_cert_string.startswith(PEM_HEADER):
659 raise ValueError("Invalid PEM encoding; must start with %s"
660 % PEM_HEADER)
661 if not pem_cert_string.strip().endswith(PEM_FOOTER):
662 raise ValueError("Invalid PEM encoding; must end with %s"
663 % PEM_FOOTER)
664 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000665 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000667def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 """Retrieve the certificate from the server at the specified address,
669 and return it as a PEM-encoded string.
670 If 'ca_certs' is specified, validate the server cert against it.
671 If 'ssl_version' is specified, use it in the connection attempt."""
672
673 host, port = addr
674 if (ca_certs is not None):
675 cert_reqs = CERT_REQUIRED
676 else:
677 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200678 s = create_connection(addr)
679 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681 dercert = s.getpeercert(True)
682 s.close()
683 return DER_cert_to_PEM_cert(dercert)
684
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000685def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200686 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')