blob: 8af22c7e4c88778085e2148446088cc4ed6634c7 [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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010055PROTOCOL_TLSv1_1
56PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010057
58The following constants identify various SSL alert message descriptions as per
59http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
60
61ALERT_DESCRIPTION_CLOSE_NOTIFY
62ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
63ALERT_DESCRIPTION_BAD_RECORD_MAC
64ALERT_DESCRIPTION_RECORD_OVERFLOW
65ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
66ALERT_DESCRIPTION_HANDSHAKE_FAILURE
67ALERT_DESCRIPTION_BAD_CERTIFICATE
68ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
69ALERT_DESCRIPTION_CERTIFICATE_REVOKED
70ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
71ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
72ALERT_DESCRIPTION_ILLEGAL_PARAMETER
73ALERT_DESCRIPTION_UNKNOWN_CA
74ALERT_DESCRIPTION_ACCESS_DENIED
75ALERT_DESCRIPTION_DECODE_ERROR
76ALERT_DESCRIPTION_DECRYPT_ERROR
77ALERT_DESCRIPTION_PROTOCOL_VERSION
78ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
79ALERT_DESCRIPTION_INTERNAL_ERROR
80ALERT_DESCRIPTION_USER_CANCELLED
81ALERT_DESCRIPTION_NO_RENEGOTIATION
82ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
83ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
84ALERT_DESCRIPTION_UNRECOGNIZED_NAME
85ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
86ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
87ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000088"""
89
Christian Heimes05e8be12008-02-23 18:30:17 +000090import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000091import re
Thomas Woutersed03b412007-08-28 21:37:11 +000092
93import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094
Antoine Pitrou04f6a322010-04-05 21:40:07 +000095from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou41032a62011-10-27 23:56:55 +020096from _ssl import _SSLContext
97from _ssl import (
98 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
99 SSLSyscallError, SSLEOFError,
100 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000101from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Victor Stinner99c8b162011-05-24 12:05:19 +0200102from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100103
104def _import_symbols(prefix):
105 for n in dir(_ssl):
106 if n.startswith(prefix):
107 globals()[n] = getattr(_ssl, n)
108
109_import_symbols('OP_')
110_import_symbols('ALERT_DESCRIPTION_')
111_import_symbols('SSL_ERROR_')
112
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100113from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100114
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100115from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200116from _ssl import _OPENSSL_API_VERSION
117
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100118
Victor Stinner3de49192011-05-09 00:42:58 +0200119_PROTOCOL_NAMES = {
120 PROTOCOL_TLSv1: "TLSv1",
121 PROTOCOL_SSLv23: "SSLv23",
122 PROTOCOL_SSLv3: "SSLv3",
123}
124try:
125 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100126 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinner3de49192011-05-09 00:42:58 +0200127except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100128 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200129else:
130 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000131
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100132try:
133 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
134except ImportError:
135 pass
136else:
137 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
138 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
139
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000140from socket import getnameinfo as _getnameinfo
Antoine Pitrou15399c32011-04-28 19:23:55 +0200141from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000142import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000143import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000144import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000145
Andrew Svetlov0832af62012-12-18 23:10:48 +0200146
147socket_error = OSError # keep that public name in module namespace
148
Antoine Pitroud6494802011-07-21 01:11:30 +0200149if _ssl.HAS_TLS_UNIQUE:
150 CHANNEL_BINDING_TYPES = ['tls-unique']
151else:
152 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000153
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100154# Disable weak or insecure ciphers by default
155# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
156_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
157
Thomas Woutersed03b412007-08-28 21:37:11 +0000158
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000159class CertificateError(ValueError):
160 pass
161
162
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200163def _dnsname_to_pat(dn, max_wildcards=1):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000164 pats = []
165 for frag in dn.split(r'.'):
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200166 if frag.count('*') > max_wildcards:
167 # Issue #17980: avoid denials of service by refusing more
168 # than one wildcard per fragment. A survery of established
169 # policy among SSL implementations showed it to be a
170 # reasonable choice.
171 raise CertificateError(
172 "too many wildcards in certificate DNS name: " + repr(dn))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000173 if frag == '*':
174 # When '*' is a fragment by itself, it matches a non-empty dotless
175 # fragment.
176 pats.append('[^.]+')
177 else:
178 # Otherwise, '*' matches any dotless fragment.
179 frag = re.escape(frag)
180 pats.append(frag.replace(r'\*', '[^.]*'))
181 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
182
183
184def match_hostname(cert, hostname):
185 """Verify that *cert* (in decoded format as returned by
186 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
187 are mostly followed, but IP addresses are not accepted for *hostname*.
188
189 CertificateError is raised on failure. On success, the function
190 returns nothing.
191 """
192 if not cert:
193 raise ValueError("empty or no certificate")
194 dnsnames = []
195 san = cert.get('subjectAltName', ())
196 for key, value in san:
197 if key == 'DNS':
198 if _dnsname_to_pat(value).match(hostname):
199 return
200 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200201 if not dnsnames:
202 # The subject is only checked when there is no dNSName entry
203 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000204 for sub in cert.get('subject', ()):
205 for key, value in sub:
206 # XXX according to RFC 2818, the most specific Common Name
207 # must be used.
208 if key == 'commonName':
209 if _dnsname_to_pat(value).match(hostname):
210 return
211 dnsnames.append(value)
212 if len(dnsnames) > 1:
213 raise CertificateError("hostname %r "
214 "doesn't match either of %s"
215 % (hostname, ', '.join(map(repr, dnsnames))))
216 elif len(dnsnames) == 1:
217 raise CertificateError("hostname %r "
218 "doesn't match %r"
219 % (hostname, dnsnames[0]))
220 else:
221 raise CertificateError("no appropriate commonName or "
222 "subjectAltName fields were found")
223
224
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225class SSLContext(_SSLContext):
226 """An SSLContext holds various SSL-related configuration options and
227 data, such as certificates and possibly a private key."""
228
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100229 __slots__ = ('protocol', '__weakref__')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000230
231 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100232 self = _SSLContext.__new__(cls, protocol)
233 if protocol != _SSLv2_IF_EXISTS:
234 self.set_ciphers(_DEFAULT_CIPHERS)
235 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000236
237 def __init__(self, protocol):
238 self.protocol = protocol
239
240 def wrap_socket(self, sock, server_side=False,
241 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000242 suppress_ragged_eofs=True,
243 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000244 return SSLSocket(sock=sock, server_side=server_side,
245 do_handshake_on_connect=do_handshake_on_connect,
246 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000247 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000248 _context=self)
249
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100250 def set_npn_protocols(self, npn_protocols):
251 protos = bytearray()
252 for protocol in npn_protocols:
253 b = bytes(protocol, 'ascii')
254 if len(b) == 0 or len(b) > 255:
255 raise SSLError('NPN protocols must be 1 to 255 in length')
256 protos.append(len(b))
257 protos.extend(b)
258
259 self._set_npn_protocols(protos)
260
Antoine Pitrou152efa22010-05-16 18:19:27 +0000261
262class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000263 """This class implements a subtype of socket.socket that wraps
264 the underlying OS socket in an SSL context when necessary, and
265 provides read and write methods over that channel."""
266
Bill Janssen6e027db2007-11-15 22:23:56 +0000267 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000268 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000269 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
270 do_handshake_on_connect=True,
271 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100272 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000273 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000274 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000275
Antoine Pitrou152efa22010-05-16 18:19:27 +0000276 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100277 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000278 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000279 if server_side and not certfile:
280 raise ValueError("certfile must be specified for server-side "
281 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000282 if keyfile and not certfile:
283 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000284 if certfile and not keyfile:
285 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100286 self._context = SSLContext(ssl_version)
287 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100289 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000290 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100291 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100292 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100293 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100295 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296 self.keyfile = keyfile
297 self.certfile = certfile
298 self.cert_reqs = cert_reqs
299 self.ssl_version = ssl_version
300 self.ca_certs = ca_certs
301 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000302 if server_side and server_hostname:
303 raise ValueError("server_hostname can only be specified "
304 "in client mode")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000305 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000306 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000307 self.do_handshake_on_connect = do_handshake_on_connect
308 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000309 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000310 socket.__init__(self,
311 family=sock.family,
312 type=sock.type,
313 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000314 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000315 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000316 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000317 elif fileno is not None:
318 socket.__init__(self, fileno=fileno)
319 else:
320 socket.__init__(self, family=family, type=type, proto=proto)
321
Antoine Pitrou242db722013-05-01 20:52:07 +0200322 # See if we are connected
323 try:
324 self.getpeername()
325 except OSError as e:
326 if e.errno != errno.ENOTCONN:
327 raise
328 connected = False
329 else:
330 connected = True
331
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000332 self._closed = False
333 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000334 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000335 if connected:
336 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100338 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000339 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000340 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000341 timeout = self.gettimeout()
342 if timeout == 0.0:
343 # non-blocking
344 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000346
Andrew Svetlov0832af62012-12-18 23:10:48 +0200347 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000348 self.close()
349 raise x
Antoine Pitrou242db722013-05-01 20:52:07 +0200350
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100351 @property
352 def context(self):
353 return self._context
354
355 @context.setter
356 def context(self, ctx):
357 self._context = ctx
358 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000359
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000360 def dup(self):
361 raise NotImplemented("Can't dup() %s instances" %
362 self.__class__.__name__)
363
Bill Janssen6e027db2007-11-15 22:23:56 +0000364 def _checkClosed(self, msg=None):
365 # raise an exception here if you wish to check for spurious closes
366 pass
367
Antoine Pitrou242db722013-05-01 20:52:07 +0200368 def _check_connected(self):
369 if not self._connected:
370 # getpeername() will raise ENOTCONN if the socket is really
371 # not connected; note that we can be connected even without
372 # _connected being set, e.g. if connect() first returned
373 # EAGAIN.
374 self.getpeername()
375
Bill Janssen54cc54c2007-12-14 22:08:56 +0000376 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000377 """Read up to LEN bytes and return them.
378 Return zero-length string on EOF."""
379
Bill Janssen6e027db2007-11-15 22:23:56 +0000380 self._checkClosed()
381 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000382 if buffer is not None:
383 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000384 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000385 v = self._sslobj.read(len or 1024)
386 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000387 except SSLError as x:
388 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000389 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000390 return 0
391 else:
392 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000393 else:
394 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000395
396 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000397 """Write DATA to the underlying SSL channel. Returns
398 number of bytes of DATA actually transmitted."""
399
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000401 return self._sslobj.write(data)
402
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000403 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000404 """Returns a formatted version of the data in the
405 certificate provided by the other end of the SSL channel.
406 Return None if no certificate was provided, {} if a
407 certificate was provided, but not validated."""
408
Bill Janssen6e027db2007-11-15 22:23:56 +0000409 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200410 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411 return self._sslobj.peer_certificate(binary_form)
412
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100413 def selected_npn_protocol(self):
414 self._checkClosed()
415 if not self._sslobj or not _ssl.HAS_NPN:
416 return None
417 else:
418 return self._sslobj.selected_npn_protocol()
419
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000420 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000421 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000422 if not self._sslobj:
423 return None
424 else:
425 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000426
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100427 def compression(self):
428 self._checkClosed()
429 if not self._sslobj:
430 return None
431 else:
432 return self._sslobj.compression()
433
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000434 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000435 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000436 if self._sslobj:
437 if flags != 0:
438 raise ValueError(
439 "non-zero flags not allowed in calls to send() on %s" %
440 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200441 try:
442 v = self._sslobj.write(data)
443 except SSLError as x:
444 if x.args[0] == SSL_ERROR_WANT_READ:
445 return 0
446 elif x.args[0] == SSL_ERROR_WANT_WRITE:
447 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000448 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200449 raise
450 else:
451 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000452 else:
453 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000454
Antoine Pitroua468adc2010-09-14 14:43:44 +0000455 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000457 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000458 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000459 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000460 elif addr is None:
461 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000462 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000463 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000464
Nick Coghlan513886a2011-08-28 00:00:27 +1000465 def sendmsg(self, *args, **kwargs):
466 # Ensure programs don't send data unencrypted if they try to
467 # use this method.
468 raise NotImplementedError("sendmsg not allowed on instances of %s" %
469 self.__class__)
470
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000471 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000472 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000473 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000474 if flags != 0:
475 raise ValueError(
476 "non-zero flags not allowed in calls to sendall() on %s" %
477 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000478 amount = len(data)
479 count = 0
480 while (count < amount):
481 v = self.send(data[count:])
482 count += v
483 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000484 else:
485 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000486
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000487 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000488 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000489 if self._sslobj:
490 if flags != 0:
491 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000492 "non-zero flags not allowed in calls to recv() on %s" %
493 self.__class__)
494 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000495 else:
496 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000497
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000498 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000499 self._checkClosed()
500 if buffer and (nbytes is None):
501 nbytes = len(buffer)
502 elif nbytes is None:
503 nbytes = 1024
504 if self._sslobj:
505 if flags != 0:
506 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000507 "non-zero flags not allowed in calls to recv_into() on %s" %
508 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000509 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000510 else:
511 return socket.recv_into(self, buffer, nbytes, flags)
512
Antoine Pitroua468adc2010-09-14 14:43:44 +0000513 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000514 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000515 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000516 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000517 self.__class__)
518 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000519 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000520
Bill Janssen58afe4c2008-09-08 16:45:19 +0000521 def recvfrom_into(self, buffer, nbytes=None, flags=0):
522 self._checkClosed()
523 if self._sslobj:
524 raise ValueError("recvfrom_into not allowed on instances of %s" %
525 self.__class__)
526 else:
527 return socket.recvfrom_into(self, buffer, nbytes, flags)
528
Nick Coghlan513886a2011-08-28 00:00:27 +1000529 def recvmsg(self, *args, **kwargs):
530 raise NotImplementedError("recvmsg not allowed on instances of %s" %
531 self.__class__)
532
533 def recvmsg_into(self, *args, **kwargs):
534 raise NotImplementedError("recvmsg_into not allowed on instances of "
535 "%s" % self.__class__)
536
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000537 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000538 self._checkClosed()
539 if self._sslobj:
540 return self._sslobj.pending()
541 else:
542 return 0
543
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000544 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000545 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000547 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000548
Ezio Melottidc55e672010-01-18 09:15:14 +0000549 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000550 if self._sslobj:
551 s = self._sslobj.shutdown()
552 self._sslobj = None
553 return s
554 else:
555 raise ValueError("No SSL wrapper around " + str(self))
556
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000557 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000559 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000560
Bill Janssen48dc27c2007-12-05 03:38:10 +0000561 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000562 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200563 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000564 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000565 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000566 if timeout == 0.0 and block:
567 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000568 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000569 finally:
570 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000571
Antoine Pitroub4410db2011-05-18 18:51:06 +0200572 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000573 if self.server_side:
574 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000575 # Here we assume that the socket is client-side, and not
576 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000577 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000579 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000580 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200581 if connect_ex:
582 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000583 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200584 rc = None
585 socket.connect(self, addr)
586 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200587 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200588 if self.do_handshake_on_connect:
589 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200590 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200591 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200592 self._sslobj = None
593 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000594
595 def connect(self, addr):
596 """Connects to remote ADDR, and then wraps the connection in
597 an SSL channel."""
598 self._real_connect(addr, False)
599
600 def connect_ex(self, addr):
601 """Connects to remote ADDR, and then wraps the connection in
602 an SSL channel."""
603 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
605 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000606 """Accepts a new connection from a remote client, and returns
607 a tuple containing that new connection wrapped with a server-side
608 SSL channel, and the address of the remote client."""
609
610 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100611 newsock = self.context.wrap_socket(newsock,
612 do_handshake_on_connect=self.do_handshake_on_connect,
613 suppress_ragged_eofs=self.suppress_ragged_eofs,
614 server_side=True)
615 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroud6494802011-07-21 01:11:30 +0200617 def get_channel_binding(self, cb_type="tls-unique"):
618 """Get channel binding data for current connection. Raise ValueError
619 if the requested `cb_type` is not supported. Return bytes of the data
620 or None if the data is not available (e.g. before the handshake).
621 """
622 if cb_type not in CHANNEL_BINDING_TYPES:
623 raise ValueError("Unsupported channel binding type")
624 if cb_type != "tls-unique":
625 raise NotImplementedError(
626 "{0} channel binding type not implemented"
627 .format(cb_type))
628 if self._sslobj is None:
629 return None
630 return self._sslobj.tls_unique_cb()
631
Bill Janssen54cc54c2007-12-14 22:08:56 +0000632
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633def wrap_socket(sock, keyfile=None, certfile=None,
634 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000635 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000636 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100637 suppress_ragged_eofs=True,
638 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Bill Janssen6e027db2007-11-15 22:23:56 +0000640 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000642 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000643 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000644 suppress_ragged_eofs=suppress_ragged_eofs,
645 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Thomas Woutersed03b412007-08-28 21:37:11 +0000647# some utility functions
648
649def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000650 """Takes a date-time string in standard ASN1_print form
651 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
652 a Python time value in seconds past the epoch."""
653
Thomas Woutersed03b412007-08-28 21:37:11 +0000654 import time
655 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657PEM_HEADER = "-----BEGIN CERTIFICATE-----"
658PEM_FOOTER = "-----END CERTIFICATE-----"
659
660def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661 """Takes a certificate in binary DER format and returns the
662 PEM version of it as a string."""
663
Bill Janssen6e027db2007-11-15 22:23:56 +0000664 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
665 return (PEM_HEADER + '\n' +
666 textwrap.fill(f, 64) + '\n' +
667 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
669def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670 """Takes a certificate in ASCII PEM format and returns the
671 DER-encoded version of it as a byte sequence"""
672
673 if not pem_cert_string.startswith(PEM_HEADER):
674 raise ValueError("Invalid PEM encoding; must start with %s"
675 % PEM_HEADER)
676 if not pem_cert_string.strip().endswith(PEM_FOOTER):
677 raise ValueError("Invalid PEM encoding; must end with %s"
678 % PEM_FOOTER)
679 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000680 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000682def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683 """Retrieve the certificate from the server at the specified address,
684 and return it as a PEM-encoded string.
685 If 'ca_certs' is specified, validate the server cert against it.
686 If 'ssl_version' is specified, use it in the connection attempt."""
687
688 host, port = addr
689 if (ca_certs is not None):
690 cert_reqs = CERT_REQUIRED
691 else:
692 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200693 s = create_connection(addr)
694 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000696 dercert = s.getpeercert(True)
697 s.close()
698 return DER_cert_to_PEM_cert(dercert)
699
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000700def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200701 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')